Skip to main content

agentmux_srv/drone/executor/blocks/
app_query.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! App query block: reads AgentMux's own state, read-only (the Drone real-world jobs spec §4.2).
5//! Deterministic and free: no agent turn, no network.
6//!
7//! Block config (`node.data`):
8//!   * `query`   required, one of:
9//!       - `muxbus`  whether cloud messages are reaching this machine.
10//!       - `agents`  every agent this machine has: how many it wants running, and which of them are not.
11//!       - `agent`   one agent's availability. Needs `agent`, its name, written in the graph.
12//!       - `tasks`   Kanban tasks, filtered by `holder`, `state` and `pr` (each optional).
13//!       - `lan_peers`  the other machines this one sees on the LAN, and whether each answered lately.
14//!       - `jobs`    recent job runs: one job's with `job`, else the newest run of every job.
15//!       - `memory`  one Global Memory entry, by id or name (`entry`), read-only. Needs `entry`, written in
16//!                   the graph. An entry of the system tier is not offered. Nothing here writes Memory.
17//!       - `presence`  which agents on this machine are working on a repository, a path or a branch
18//!                   (`repo`, `path`, `branch`; at least one), from their own work facts. Names, state and how
19//!                   each matched; no goals, no file names, and claims and posts are not read.
20//!   * `agent`, `job`, `entry`   the agent's, the job's or the Memory entry's name (a job's or an entry's id
21//!               works too). Never a `{{reference}}`: a value from outside must not pick whose state the
22//!               graph reads (§6.2).
23//!   * `holder`, `state`, `pr`   task filters. They only find tasks, so each may be built from a
24//!               `{{reference}}` (a PR url from the trigger). `pr` matches a task's PR link exactly.
25//!   * `repo`, `path`, `branch`   the `presence` filters. They only find who is working there, so each may be
26//!               built from a `{{reference}}`.
27//!   * `max_chars`   `memory`, how much of the entry to return (default 4000, at most 20000).
28//!   * `limit`   tasks and jobs, how many to return (tasks: default 50, at most 200; jobs: default 20, at most 100).
29//!
30//! Output, by query:
31//!   * `muxbus`: `{ "state", "connected", "signed_in", "since_ms", "last_ok_ms"?, "last_error"? }`.
32//!   * `agents`: `{ "count": N, "wanted_running": W, "up": U, "all_up": bool, "problem_count": P, "problems": [{ "agent",
33//!               "state", "detail"? }], "problem_names": "<name (state), ...>" }`. An agent is `up` when it is wanted
34//!               running and idle, working or waiting on the person; a wanted-running agent that is stopped, starting,
35//!               limited, signed out or in error is a problem (at most 20 listed). `all_up` is true with no problem.
36//!   * `agent`:  `{ "found": bool, "ambiguous"?: true, "state"?, "would"?, "reason"?, ... }`, the
37//!               availability the Agents tool shows. `found` is false for a name no agent here has.
38//!   * `tasks`:  `{ "count": N, "tasks": [{ "num", "title", "state", "holder", "pr", "branch" }] }`.
39//!   * `lan_peers`: `{ "count": N, "answered": M, "peers": [{ "host", "channel", "version", "os", "agents",
40//!               "last_seen_ms", "last_answered_ms"?, "answered" }] }`. `answered` is true when the peer
41//!               answered this machine's own poll (asked every 30 s) in the last two minutes: it is up and
42//!               reachable from here. It is not a signature check.
43//!   * `jobs`:   (scheduled, Drone and cloud jobs alike, as the run ledger holds them) `{ "found": bool, "count": N, "runs": [{ "id", "job_id", "job", "state", "outcome", "trigger",
44//!               "summary", "started_ms", "ended_ms"?, "cost_usd"? }], "last_ok"? }`; `found` is false for a `job` that
45//!               matches none. With a `job`, `last_ok` is that job's newest run that finished with outcome `ok` or
46//!               `findings` (a run row, or null when there is none), found whatever `limit` cuts `runs` to.
47//!   * `memory`: `{ "found": bool, "id"?, "name"?, "content"?, "chars"?, "truncated"? }`; `found` is false for
48//!               an entry nobody has (or the system tier), with `ambiguous` when two entries share the name.
49//!   * `presence`: `{ "count": N, "agents": [{ "agent", "status", "repo"?, "branch"?, "matched": ["claim", "dirty", ...] }] }`.
50//!
51//! Every answer of this block is outside text to the run (the taint bits): what an entry or an agent's
52//! branch says is not the graph's own.
53
54use serde_json::{json, Value};
55
56use crate::backend::rpc_types::{MuxBusDeliveryState, MuxBusDeliveryStatus};
57use crate::backend::storage::work_board::BoardTask;
58use crate::drone::data_flow::ExecutionScope;
59use crate::drone::types::FlowNode;
60
61/// Tasks returned when the node gives no `limit`.
62const DEFAULT_LIMIT: usize = 50;
63/// The most tasks one query returns.
64const MAX_LIMIT: usize = 200;
65/// How many board tasks are read before filtering: every open task and the recently finished ones.
66const SCAN_LIMIT: usize = 2_000;
67/// Finished tasks changed within this many days are still seen by a query.
68const FINISHED_WINDOW_DAYS: i64 = 30;
69/// Job runs returned when the node gives no `limit`, and the most one query returns.
70const DEFAULT_RUNS: usize = 20;
71const MAX_RUNS: usize = 100;
72/// A peer that answered this machine's poll within this many seconds counts as answering
73/// (the poll is every 30 s, so four missed ones in a row).
74const ANSWERED_WITHIN_SECS: u64 = 120;
75/// A run's summary is cut to this many characters.
76const RUN_SUMMARY_CHARS: usize = 200;
77/// A Memory entry is cut to this many characters when the node gives no `max_chars`, and never to more than the cap.
78const DEFAULT_MEMORY_CHARS: usize = 4_000;
79const MAX_MEMORY_CHARS: usize = 20_000;
80/// The most agents a `presence` query lists.
81const MAX_PRESENCE: usize = 50;
82
83/// What the block asks.
84#[derive(Debug, PartialEq)]
85pub(crate) enum Query {
86    MuxBus,
87    Agents,
88    Agent(String),
89    Tasks(TaskFilter),
90    LanPeers,
91    Jobs(JobsFilter),
92    Memory(MemoryFilter),
93    Presence(PresenceFilter),
94}
95
96/// The filters of a `memory` query: one Global Memory entry, by id or name, and how much of it to return.
97#[derive(Debug, PartialEq, Default)]
98pub(crate) struct MemoryFilter {
99    pub entry: String,
100    pub max_chars: usize,
101}
102
103/// The filters of a `presence` query: what to ask who is working on; at least one is not empty.
104#[derive(Debug, PartialEq, Default)]
105pub(crate) struct PresenceFilter {
106    pub repo: String,
107    pub path: String,
108    pub branch: String,
109}
110
111/// The filters of a `jobs` query: one job by name or id (empty is every job) and how many runs.
112#[derive(Debug, PartialEq, Default)]
113pub(crate) struct JobsFilter {
114    pub job: String,
115    pub limit: usize,
116}
117
118/// The filters of a `tasks` query; an empty one matches anything.
119#[derive(Debug, PartialEq, Default)]
120pub(crate) struct TaskFilter {
121    pub holder: String,
122    pub state: String,
123    pub pr: String,
124    pub limit: usize,
125}
126
127pub async fn run(node: &FlowNode, scope: &ExecutionScope) -> Result<Value, String> {
128    match plan(node, scope)? {
129        Query::MuxBus => Ok(muxbus_answer(&crate::muxbus::delivery_status::status())),
130        Query::Agents => {
131            let state = crate::drone::host::state()?.clone();
132            let now = agentmux_common::time::now_ms_u64();
133            tokio::task::spawn_blocking(move || agents_answer(&crate::server::agent_runtime::list(&state, now)))
134                .await
135                .map_err(|e| format!("app query: {e}"))
136        }
137        Query::Agent(name) => {
138            let state = crate::drone::host::state()?;
139            Ok(agent_answer(crate::server::availability_view::view_of_agent(state, &name).await))
140        }
141        Query::LanPeers => {
142            let state = crate::drone::host::state()?;
143            let own = crate::backend::lan::listeners::cached_local_addresses();
144            Ok(lan_peers_answer(&state.lan_discovery.get_instances(), &own, agentmux_common::time::now_secs() as u64))
145        }
146        Query::Jobs(filter) => {
147            let state = crate::drone::host::state()?;
148            let (Some(jobs), Some(ledger)) = (crate::server::cron::jobs_store(state), state.cron_scheduler.runs().cloned()) else {
149                return Err("app query: the job ledger isn't ready yet".to_string());
150            };
151            tokio::task::spawn_blocking(move || jobs_answer(&jobs, ledger.store(), &filter))
152                .await
153                .map_err(|e| format!("app query: {e}"))?
154        }
155        Query::Memory(filter) => {
156            let state = crate::drone::host::state()?.clone();
157            tokio::task::spawn_blocking(move || {
158                let entries = state.id_store.bundle_list_global().map_err(|e| format!("app query: couldn't read Global Memory: {e}"))?;
159                Ok(memory_answer(&entries, &filter))
160            })
161            .await
162            .map_err(|e| format!("app query: {e}"))?
163        }
164        Query::Presence(filter) => {
165            let state = crate::drone::host::state()?;
166            let facts = crate::server::work_facts_handlers::local_facts(state).await;
167            presence_answer(&facts, &filter)
168        }
169        Query::Tasks(filter) => {
170            let state = crate::drone::host::state()?;
171            let store = crate::server::cron::work_store(state);
172            let now = agentmux_common::time::now_ms() as i64;
173            let since = now - FINISHED_WINDOW_DAYS * 24 * 3_600_000;
174            let all = tokio::task::spawn_blocking(move || store.work_board_list(since, SCAN_LIMIT, now))
175                .await
176                .map_err(|e| format!("app query: {e}"))?
177                .map_err(|e| format!("app query: couldn't read the tasks: {e}"))?;
178            Ok(tasks_answer(&all, &filter))
179        }
180    }
181}
182
183/// The question a `poll` trigger asks (`backend::jobs::poll`): the App query named by the filter's `query`, with
184/// the filter's own keys as its config and no references to resolve.
185pub(crate) fn poll_check() -> crate::backend::jobs::poll::Check {
186    std::sync::Arc::new(|filter| {
187        Box::pin(async move {
188            // A poll of a site outside AgentMux: the API block's own call, which never asks the person (`api_poll`).
189            if filter.get("query").and_then(|q| q.as_str()) == Some("api") {
190                return super::api_poll::ask(filter).await;
191            }
192            let node = FlowNode { id: "poll".to_string(), position: Default::default(), data: Value::Object(filter), node_type: None };
193            run(&node, &ExecutionScope::new()).await
194        })
195    })
196}
197
198/// What the node asks, with the filters' references resolved. Pure, so it is testable without a server.
199pub(crate) fn plan(node: &FlowNode, scope: &ExecutionScope) -> Result<Query, String> {
200    let text = |key: &str| node.data.get(key).and_then(|v| v.as_str()).map(str::trim).unwrap_or("");
201    match text("query") {
202        "muxbus" => Ok(Query::MuxBus),
203        "agents" => Ok(Query::Agents),
204        "agent" => {
205            let name = text("agent");
206            if name.is_empty() {
207                return Err("app query: the `agent` query needs `agent`".to_string());
208            }
209            if name.contains("{{") {
210                return Err("app query: `agent` must name an agent, not a {{reference}}".to_string());
211            }
212            Ok(Query::Agent(name.to_string()))
213        }
214        "tasks" => {
215            let limit = match node.data.get("limit").and_then(|v| v.as_u64()) {
216                Some(n) => (n as usize).clamp(1, MAX_LIMIT),
217                None => DEFAULT_LIMIT,
218            };
219            let resolved = |key: &str| scope.resolve(text(key)).trim().to_string();
220            Ok(Query::Tasks(TaskFilter { holder: resolved("holder"), state: resolved("state"), pr: resolved("pr"), limit }))
221        }
222        "lan_peers" => Ok(Query::LanPeers),
223        "jobs" => {
224            let job = text("job");
225            if job.contains("{{") {
226                return Err("app query: `job` must name a job, not a {{reference}}".to_string());
227            }
228            let limit = match node.data.get("limit").and_then(|v| v.as_u64()) {
229                Some(n) => (n as usize).clamp(1, MAX_RUNS),
230                None => DEFAULT_RUNS,
231            };
232            Ok(Query::Jobs(JobsFilter { job: job.to_string(), limit }))
233        }
234        "memory" => {
235            let entry = text("entry");
236            if entry.is_empty() {
237                return Err("app query: the `memory` query needs `entry`".to_string());
238            }
239            if entry.contains("{{") {
240                return Err("app query: `entry` must name a Global Memory entry, not a {{reference}}".to_string());
241            }
242            let max_chars = match node.data.get("max_chars").and_then(|v| v.as_u64()) {
243                Some(n) => (n as usize).clamp(1, MAX_MEMORY_CHARS),
244                None => DEFAULT_MEMORY_CHARS,
245            };
246            Ok(Query::Memory(MemoryFilter { entry: entry.to_string(), max_chars }))
247        }
248        "presence" => {
249            let resolved = |key: &str| scope.resolve(text(key)).trim().to_string();
250            let filter = PresenceFilter { repo: resolved("repo"), path: resolved("path"), branch: resolved("branch") };
251            if filter.repo.is_empty() && filter.path.is_empty() && filter.branch.is_empty() {
252                return Err("app query: the `presence` query needs `repo`, `path` or `branch`".to_string());
253            }
254            Ok(Query::Presence(filter))
255        }
256        "" => Err("app query block missing `query`".to_string()),
257        other => Err(format!("app query: unknown query {other:?}; this AgentMux has muxbus, agents, agent, tasks, lan_peers, jobs, memory and presence")),
258    }
259}
260
261/// `muxbus`: the delivery state in the words a Condition reads.
262pub(crate) fn muxbus_answer(s: &MuxBusDeliveryStatus) -> Value {
263    let mut out = json!({
264        "state": serde_json::to_value(s.state).unwrap_or(Value::Null),
265        "connected": s.state == MuxBusDeliveryState::Connected,
266        "signed_in": matches!(s.state, MuxBusDeliveryState::Connected | MuxBusDeliveryState::Reconnecting),
267        "since_ms": s.since_ms,
268    });
269    if let Some(ms) = s.last_ok_ms {
270        out["last_ok_ms"] = json!(ms);
271    }
272    if let Some(e) = &s.last_error {
273        out["last_error"] = json!(e);
274    }
275    out
276}
277
278/// `agent`: the availability view, with `found` first.
279fn agent_answer(known: crate::server::availability_view::Known) -> Value {
280    use crate::server::availability_view::Known;
281    match known {
282        Known::Live(mut v) => {
283            if let Some(o) = v.as_object_mut() {
284                o.insert("found".to_string(), json!(true));
285            }
286            v
287        }
288        Known::Ambiguous => json!({ "found": false, "ambiguous": true }),
289        Known::Unknown => json!({ "found": false }),
290    }
291}
292
293/// The most agents `agents` lists as a problem.
294const MAX_PROBLEMS: usize = 20;
295
296/// `agents`: how many agents the machine wants running and which of those are not up. Pure, so a test can hand it rows.
297pub(crate) fn agents_answer(rows: &[crate::backend::agent_runtime_state::AgentRuntime]) -> Value {
298    use crate::backend::agent_runtime_state::{AgentDesiredState, AgentRuntimeState as S};
299    let wanted: Vec<_> = rows.iter().filter(|r| r.desired == AgentDesiredState::Running).collect();
300    let is_up = |r: &crate::backend::agent_runtime_state::AgentRuntime| matches!(r.state, S::Idle | S::Working | S::WaitingOnUser);
301    let up = wanted.iter().filter(|r| is_up(r)).count();
302    let down: Vec<_> = wanted.iter().filter(|r| !is_up(r)).collect();
303    let state_name = |r: &crate::backend::agent_runtime_state::AgentRuntime| serde_json::to_value(r.state).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
304    let problems: Vec<Value> = down
305        .iter()
306        .take(MAX_PROBLEMS)
307        .map(|r| {
308            let mut p = json!({ "agent": r.name, "state": state_name(r) });
309            if let Some(d) = &r.detail {
310                p["detail"] = json!(d);
311            }
312            p
313        })
314        .collect();
315    let names = down.iter().take(MAX_PROBLEMS).map(|r| format!("{} ({})", r.name, state_name(r))).collect::<Vec<_>>().join(", ");
316    json!({ "count": rows.len(), "wanted_running": wanted.len(), "up": up, "all_up": down.is_empty(), "problem_count": down.len(), "problems": problems, "problem_names": names })
317}
318
319/// `tasks`: the tasks that match, newest first as the board lists them, cut to the limit.
320pub(crate) fn tasks_answer(all: &[BoardTask], f: &TaskFilter) -> Value {
321    let hits: Vec<Value> = all
322        .iter()
323        .filter(|t| f.holder.is_empty() || t.item.claimed_by == f.holder)
324        .filter(|t| f.state.is_empty() || t.item.state == f.state)
325        .filter(|t| f.pr.is_empty() || t.card.pr_url == f.pr)
326        .take(f.limit)
327        .map(|t| {
328            json!({
329                "num": t.card.num,
330                "title": t.item.title,
331                "state": t.item.state,
332                "holder": t.item.claimed_by,
333                "pr": t.card.pr_url,
334                "branch": t.card.branch,
335            })
336        })
337        .collect();
338    json!({ "count": hits.len(), "tasks": hits })
339}
340
341/// `lan_peers`: the machines on the LAN other than this one (a peer at one of this machine's own addresses
342/// is another channel here), by host name, each with whether it answered the poll lately.
343pub(crate) fn lan_peers_answer(peers: &[crate::backend::lan::discovery::LanInstance], own_addrs: &std::collections::HashSet<std::net::IpAddr>, now_secs: u64) -> Value {
344    let mut rows: Vec<(String, Value, bool)> = peers
345        .iter()
346        .filter(|p| !p.address.parse::<std::net::IpAddr>().is_ok_and(|a| own_addrs.contains(&a)))
347        .map(|p| {
348            let answered = p.last_polled_ok > 0 && now_secs.saturating_sub(p.last_polled_ok) <= ANSWERED_WITHIN_SECS;
349            let host = if p.hostname.trim().is_empty() { "unnamed host".to_string() } else { p.hostname.trim().to_string() };
350            let mut row = json!({
351                "host": host,
352                "channel": p.channel,
353                "version": p.version,
354                "os": p.os,
355                "agents": p.agents.len(),
356                "last_seen_ms": p.last_seen.saturating_mul(1000),
357                "answered": answered,
358            });
359            if p.last_polled_ok > 0 {
360                row["last_answered_ms"] = json!(p.last_polled_ok.saturating_mul(1000));
361            }
362            (host.to_lowercase(), row, answered)
363        })
364        .collect();
365    rows.sort_by(|a, b| a.0.cmp(&b.0));
366    let answered = rows.iter().filter(|r| r.2).count();
367    json!({ "count": rows.len(), "answered": answered, "peers": rows.into_iter().map(|r| r.1).collect::<Vec<_>>() })
368}
369
370/// One run, for the graph: what happened and when, with the summary cut.
371fn run_row(r: &crate::backend::storage::job_runs::JobRun) -> Value {
372    let mut row = json!({
373        "id": r.id,
374        "job_id": r.job_id,
375        "job": r.job_name,
376        "state": r.state,
377        "outcome": r.outcome,
378        "trigger": r.trigger,
379        "summary": r.summary.chars().take(RUN_SUMMARY_CHARS).collect::<String>(),
380        "started_ms": r.started_at_ms,
381    });
382    if let Some(end) = r.ended_at_ms {
383        row["ended_ms"] = json!(end);
384    }
385    if r.cost_known {
386        row["cost_usd"] = json!(r.cost_usd);
387    }
388    row
389}
390
391/// `jobs`: the named job's newest runs, or the newest run of every job, newest first, cut to the limit. A job is
392/// whatever the run ledger has runs of (scheduled, Drone and cloud jobs alike), and a scheduled job with no run yet.
393pub(crate) fn jobs_answer(jobs: &crate::backend::storage::store::Store, ledger: &crate::backend::storage::store::Store, f: &JobsFilter) -> Result<Value, String> {
394    let read = |e: crate::backend::storage::StoreError| format!("app query: couldn't read the runs: {e}");
395    if f.job.is_empty() {
396        let rows: Vec<Value> = ledger.job_runs_latest_per_job(f.limit as i64).map_err(read)?.iter().map(run_row).collect();
397        return Ok(json!({ "found": true, "count": rows.len(), "runs": rows }));
398    }
399    let mut ids = ledger.job_ids_named(&f.job).map_err(read)?;
400    for job in jobs.cron_list().map_err(|e| format!("app query: couldn't read the jobs: {e}"))? {
401        if (job.id == f.job || job.name == f.job) && !ids.contains(&job.id) {
402            ids.push(job.id);
403        }
404    }
405    match ids.as_slice() {
406        [] => Ok(json!({ "found": false, "count": 0, "runs": [] })),
407        [id] => {
408            let rows: Vec<Value> = ledger.job_runs_for_job(id, f.limit as i64, None).map_err(read)?.iter().map(run_row).collect();
409            let last_ok = ledger.job_run_last_good(id).map_err(read)?.map(|r| run_row(&r)).unwrap_or(Value::Null);
410            Ok(json!({ "found": true, "count": rows.len(), "runs": rows, "last_ok": last_ok }))
411        }
412        _ => Ok(json!({ "found": false, "ambiguous": true, "count": 0, "runs": [] })),
413    }
414}
415
416/// `memory`: the Global Memory entry whose id is `f.entry`, or whose name is (without regard to case), cut to
417/// `f.max_chars`. An entry of the system tier is not offered, and two entries with one name are not guessed between.
418pub(crate) fn memory_answer(entries: &[crate::backend::storage::bundles::Bundle], f: &MemoryFilter) -> Value {
419    let want = f.entry.to_lowercase();
420    let mut hits = entries.iter().filter(|b| b.is_global && !b.is_system && (b.id == f.entry || b.name.to_lowercase() == want));
421    match (hits.next(), hits.next()) {
422        (Some(b), None) => {
423            let chars = b.instructions.chars().count();
424            let content: String = b.instructions.chars().take(f.max_chars).collect();
425            json!({ "found": true, "id": b.id, "name": b.name, "content": content, "chars": chars, "truncated": chars > f.max_chars })
426        }
427        (Some(_), Some(_)) => json!({ "found": false, "ambiguous": true }),
428        _ => json!({ "found": false }),
429    }
430}
431
432/// `presence`: the agents whose own work facts (their clones' uncommitted changes, recent edits, branch and repository)
433/// touch what is asked. Claims and posts are not read. Only what `Presence who` shows of each agent that a graph needs:
434/// its name, its state and how it matched; no goal, no file names. Pure over the facts, so a test can hand it some.
435pub(crate) fn presence_answer(facts: &[crate::backend::work_facts::WorkFacts], f: &PresenceFilter) -> Result<Value, String> {
436    use crate::backend::work_facts::matching;
437    let asked = matching::WhoQuery { path: Some(f.path.clone()), repo: Some(f.repo.clone()), branch: Some(f.branch.clone()), query: None };
438    let target = matching::resolve(&asked, None, facts).map_err(|e| format!("app query: {e}"))?;
439    let found = matching::who_is_working_on(&target, facts);
440    let agents: Vec<Value> = found
441        .iter()
442        .take(MAX_PRESENCE)
443        .map(|r| {
444            let matched: Vec<Value> = r.matches.iter().map(|m| serde_json::to_value(m.kind).unwrap_or(Value::Null)).collect();
445            let mut row = json!({ "agent": r.agent, "status": r.status, "matched": matched });
446            if let Some(repo) = &r.repo {
447                row["repo"] = json!(repo);
448            }
449            if let Some(branch) = &r.branch {
450                row["branch"] = json!(branch);
451            }
452            row
453        })
454        .collect();
455    Ok(json!({ "count": found.len(), "agents": agents }))
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461    use crate::backend::storage::work_board::WorkCard;
462    use crate::backend::storage::work_queue::WorkItem;
463    use crate::drone::types::NodePosition;
464
465    fn node(data: Value) -> FlowNode {
466        FlowNode { id: "q1".to_string(), position: NodePosition::default(), data, node_type: None }
467    }
468
469    fn task(num: i64, state: &str, holder: &str, pr: &str) -> BoardTask {
470        let item: WorkItem = serde_json::from_value(json!({
471            "id": format!("w{num}"), "title": format!("task {num}"), "payload": "", "state": state,
472            "claimed_by": holder, "created_at": 0, "updated_at": 0,
473        }))
474        .unwrap();
475        BoardTask { item, card: WorkCard { num, pr_url: pr.to_string(), ..Default::default() } }
476    }
477
478    #[test]
479    fn the_query_names_what_is_read_and_an_unknown_one_says_what_exists() {
480        let s = ExecutionScope::new();
481        assert_eq!(plan(&node(json!({ "query": "muxbus" })), &s).unwrap(), Query::MuxBus);
482        let err = plan(&node(json!({ "query": "weather" })), &s).unwrap_err();
483        assert!(err.contains("muxbus, agents, agent, tasks, lan_peers, jobs, memory and presence"), "{err}");
484        assert!(plan(&node(json!({})), &s).is_err());
485    }
486
487    #[test]
488    fn the_agent_is_named_in_the_graph_and_never_by_a_reference() {
489        let s = ExecutionScope::new();
490        assert_eq!(plan(&node(json!({ "query": "agent", "agent": " clamk " })), &s).unwrap(), Query::Agent("clamk".to_string()));
491        assert!(plan(&node(json!({ "query": "agent" })), &s).is_err());
492        let err = plan(&node(json!({ "query": "agent", "agent": "{{trigger.who}}" })), &s).unwrap_err();
493        assert!(err.contains("not a {{reference}}"), "{err}");
494    }
495
496    #[test]
497    fn task_filters_may_come_from_a_reference_and_the_limit_is_capped() {
498        let s = ExecutionScope::with_trigger(json!({ "url": "https://github.com/o/r/pull/7" }));
499        let q = plan(&node(json!({ "query": "tasks", "pr": "{{trigger.url}}", "state": "claimed", "limit": 9999 })), &s).unwrap();
500        assert_eq!(
501            q,
502            Query::Tasks(TaskFilter { holder: String::new(), state: "claimed".to_string(), pr: "https://github.com/o/r/pull/7".to_string(), limit: MAX_LIMIT })
503        );
504        let q = plan(&node(json!({ "query": "tasks" })), &s).unwrap();
505        assert_eq!(q, Query::Tasks(TaskFilter { limit: DEFAULT_LIMIT, ..Default::default() }));
506    }
507
508    fn entry(id: &str, name: &str, text: &str, system: bool) -> crate::backend::storage::bundles::Bundle {
509        crate::backend::storage::bundles::Bundle {
510            id: id.to_string(),
511            name: name.to_string(),
512            description: String::new(),
513            is_blank: false,
514            is_global: true,
515            provider: String::new(),
516            model: String::new(),
517            instructions: text.to_string(),
518            instructions_by_provider: "{}".to_string(),
519            context_files: "[]".to_string(),
520            mcp_servers: "[]".to_string(),
521            skills: "[]".to_string(),
522            sort_order: 0,
523            created_at: 0,
524            updated_at: 0,
525            is_system: system,
526        }
527    }
528
529    #[test]
530    fn the_memory_entry_is_named_in_the_graph_and_never_by_a_reference() {
531        let s = ExecutionScope::new();
532        assert_eq!(
533            plan(&node(json!({ "query": "memory", "entry": " Release rules " })), &s).unwrap(),
534            Query::Memory(MemoryFilter { entry: "Release rules".to_string(), max_chars: DEFAULT_MEMORY_CHARS })
535        );
536        assert!(plan(&node(json!({ "query": "memory" })), &s).is_err(), "an entry is required");
537        let err = plan(&node(json!({ "query": "memory", "entry": "{{trigger.name}}" })), &s).unwrap_err();
538        assert!(err.contains("not a {{reference}}"), "{err}");
539        let capped = plan(&node(json!({ "query": "memory", "entry": "x", "max_chars": 999_999 })), &s).unwrap();
540        assert_eq!(capped, Query::Memory(MemoryFilter { entry: "x".to_string(), max_chars: MAX_MEMORY_CHARS }));
541    }
542
543    #[test]
544    fn a_memory_entry_is_read_by_id_or_name_and_cut_to_the_limit() {
545        let all = vec![entry("b1", "Release rules", "one two three four", false), entry("b2", "Other", "x", false)];
546        let f = |e: &str, n: usize| MemoryFilter { entry: e.to_string(), max_chars: n };
547        let by_name = memory_answer(&all, &f("release RULES", 100));
548        assert_eq!((by_name["found"].clone(), by_name["id"].clone(), by_name["content"].clone()), (json!(true), json!("b1"), json!("one two three four")));
549        assert_eq!(by_name["truncated"], json!(false));
550        let cut = memory_answer(&all, &f("b1", 7));
551        assert_eq!((cut["content"].clone(), cut["chars"].clone(), cut["truncated"].clone()), (json!("one two"), json!(18), json!(true)));
552        assert_eq!(memory_answer(&all, &f("nothing", 10)), json!({ "found": false }));
553    }
554
555    #[test]
556    fn the_system_tier_and_an_ambiguous_name_are_not_offered() {
557        let all = vec![entry("s1", "Baseline", "secret rules", true), entry("b1", "Notes", "a", false), entry("b2", "notes", "b", false)];
558        let f = |e: &str| MemoryFilter { entry: e.to_string(), max_chars: 100 };
559        assert_eq!(memory_answer(&all, &f("Baseline")), json!({ "found": false }), "a system entry is not found by name");
560        assert_eq!(memory_answer(&all, &f("s1")), json!({ "found": false }), "nor by id");
561        assert_eq!(memory_answer(&all, &f("Notes")), json!({ "found": false, "ambiguous": true }));
562        assert_eq!(memory_answer(&all, &f("b2"))["found"], json!(true), "an id still picks one of two same-named entries");
563    }
564
565    #[test]
566    fn a_memory_entry_is_cut_on_characters_not_bytes() {
567        let all = vec![entry("b1", "N", "h\u{e9}llo w\u{f6}rld", false)];
568        let out = memory_answer(&all, &MemoryFilter { entry: "N".to_string(), max_chars: 4 });
569        assert_eq!(out["content"], json!("h\u{e9}ll"));
570    }
571
572    #[test]
573    fn presence_needs_something_to_look_for_and_its_filters_may_be_references() {
574        let s = ExecutionScope::with_trigger(json!({ "branch": "loap/fix" }));
575        let err = plan(&node(json!({ "query": "presence" })), &s).unwrap_err();
576        assert!(err.contains("needs `repo`, `path` or `branch`"), "{err}");
577        let blank = ExecutionScope::with_trigger(json!({ "branch": "" }));
578        assert!(plan(&node(json!({ "query": "presence", "branch": "{{trigger.branch}}" })), &blank).is_err(), "a reference that is empty is nothing to look for");
579        assert_eq!(
580            plan(&node(json!({ "query": "presence", "repo": " a/b ", "branch": "{{trigger.branch}}" })), &s).unwrap(),
581            Query::Presence(PresenceFilter { repo: "a/b".to_string(), path: String::new(), branch: "loap/fix".to_string() })
582        );
583    }
584
585    fn facts(agent: &str, repo: &str, branch: &str, status: &str) -> crate::backend::work_facts::WorkFacts {
586        crate::backend::work_facts::WorkFacts {
587            agent: agent.to_string(),
588            repo: Some(repo.to_string()),
589            branch: Some(branch.to_string()),
590            status: status.to_string(),
591            goal: Some("a goal the graph must not see".to_string()),
592            dirty_files: vec!["secret/file.rs".to_string()],
593            dirty_count: 1,
594            ..Default::default()
595        }
596    }
597
598    #[test]
599    fn presence_lists_who_is_on_the_repo_and_branch_without_goals_or_file_names() {
600        let all = vec![facts("loap", "a/b", "loap/fix", "busy"), facts("opaz", "a/b", "main", "idle"), facts("other", "c/d", "main", "idle")];
601        let f = |repo: &str, branch: &str| PresenceFilter { repo: repo.to_string(), path: String::new(), branch: branch.to_string() };
602        let on_repo = presence_answer(&all, &f("a/b", "")).unwrap();
603        assert_eq!(on_repo["count"], json!(2));
604        let names: Vec<_> = on_repo["agents"].as_array().unwrap().iter().map(|a| a["agent"].as_str().unwrap().to_string()).collect();
605        assert!(names.contains(&"loap".to_string()) && names.contains(&"opaz".to_string()) && !names.contains(&"other".to_string()), "{names:?}");
606        let text = on_repo.to_string();
607        assert!(!text.contains("a goal the graph must not see") && !text.contains("secret/file.rs"), "{text}");
608        let on_branch = presence_answer(&all, &f("a/b", "loap/fix")).unwrap();
609        assert!(on_branch["agents"].as_array().unwrap().iter().any(|a| a["agent"] == "loap" && a["matched"].as_array().is_some_and(|m| !m.is_empty())));
610    }
611
612    #[test]
613    fn a_relative_path_with_no_repository_is_an_error_not_an_empty_answer() {
614        let all = vec![facts("loap", "a/b", "main", "idle")];
615        let f = PresenceFilter { repo: String::new(), path: "src/lib.rs".to_string(), branch: String::new() };
616        assert!(presence_answer(&all, &f).unwrap_err().starts_with("app query: "));
617    }
618
619    #[test]
620    fn tasks_are_found_by_holder_state_and_pr_link() {
621        let all = vec![task(1, "claimed", "masty", "https://x/pull/1"), task(2, "done", "masty", "https://x/pull/2"), task(3, "claimed", "maop", "https://x/pull/1")];
622        let f = |holder: &str, state: &str, pr: &str| TaskFilter { holder: holder.into(), state: state.into(), pr: pr.into(), limit: 50 };
623        assert_eq!(tasks_answer(&all, &f("masty", "", ""))["count"], 2);
624        assert_eq!(tasks_answer(&all, &f("", "claimed", "https://x/pull/1"))["count"], 2);
625        let one = tasks_answer(&all, &f("masty", "claimed", "https://x/pull/1"));
626        assert_eq!(one["count"], 1);
627        assert_eq!(one["tasks"][0]["num"], 1);
628        assert_eq!(tasks_answer(&all, &f("nobody", "", ""))["count"], 0);
629        assert_eq!(tasks_answer(&all, &TaskFilter { limit: 1, ..Default::default() })["count"], 1);
630    }
631
632    fn peer(host: &str, address: &str, last_seen: u64, polled: u64) -> crate::backend::lan::discovery::LanInstance {
633        serde_json::from_value(json!({
634            "instance_id": format!("{host}-i"), "hostname": host, "version": "0.60.26", "channel": "stable", "os": "linux", "install": "", "build": "",
635            "address": address, "port": 29700, "agents": ["a", "b"], "agent_status": {}, "agent_lines": {}, "agent_providers": {},
636            "first_seen": 1, "last_seen": last_seen, "last_polled_ok": polled, "other_ttl_secs": 4500,
637        }))
638        .unwrap()
639    }
640
641    #[test]
642    fn lan_peers_say_who_answered_the_poll_lately_and_leave_out_this_machines_own() {
643        let own: std::collections::HashSet<std::net::IpAddr> = ["203.0.113.21".parse().unwrap()].into_iter().collect();
644        let now = 10_000;
645        let peers = vec![peer("narko", "203.0.113.10", now - 5, now - 30), peer("charlie", "203.0.113.11", now - 5, now - 600), peer("area54", "203.0.113.12", now - 5, 0), peer("starpower-2", "203.0.113.21", now, now)];
646        let a = lan_peers_answer(&peers, &own, now);
647        assert_eq!((a["count"].clone(), a["answered"].clone()), (json!(3), json!(1)), "this machine's own address is another channel here");
648        let hosts: Vec<&str> = a["peers"].as_array().unwrap().iter().map(|p| p["host"].as_str().unwrap()).collect();
649        assert_eq!(hosts, vec!["area54", "charlie", "narko"], "by host name");
650        let by = |h: &str| a["peers"].as_array().unwrap().iter().find(|p| p["host"] == h).unwrap().clone();
651        assert_eq!(by("narko")["answered"], json!(true));
652        assert_eq!(by("charlie")["answered"], json!(false), "answered ten minutes ago");
653        assert!(by("area54").get("last_answered_ms").is_none() && by("area54")["answered"] == json!(false), "never answered");
654        assert_eq!(by("narko")["last_answered_ms"], json!((now - 30) * 1000));
655        assert_eq!(by("narko")["agents"], json!(2));
656    }
657
658    /// A test state whose store holds the jobs and, through `job_runs_ensure_schema`, their runs.
659    fn ledger_with(jobs: &[(&str, &str)], runs: &[(&str, &str, i64)]) -> crate::server::AppState {
660        use crate::backend::storage::cron::CronJob;
661        use crate::backend::storage::job_runs::JobRun;
662        let state = crate::server::tests::test_state();
663        state.mstore.job_runs_ensure_schema().unwrap();
664        for (id, name) in jobs {
665            state.mstore.cron_create(&CronJob { id: id.to_string(), name: name.to_string(), ..Default::default() }).unwrap();
666        }
667        for (id, job, at) in runs {
668            let name = jobs.iter().find(|j| j.0 == *job).map(|j| j.1).unwrap_or("");
669            state.mstore.job_run_insert(&JobRun::new(id, job, "cron", name, "schedule", "finished", *at)).unwrap();
670        }
671        state
672    }
673
674    #[tokio::test]
675    async fn jobs_without_a_name_give_the_newest_run_of_each_job_newest_first() {
676        let state = ledger_with(&[("j1", "Nightly"), ("j2", "Backup")], &[("r1", "j1", 100), ("r2", "j1", 300), ("r3", "j2", 200)]);
677        let a = jobs_answer(&state.mstore, &state.mstore, &JobsFilter { job: String::new(), limit: 20 }).unwrap();
678        let ids: Vec<&str> = a["runs"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect();
679        assert_eq!((a["found"].clone(), a["count"].clone(), ids), (json!(true), json!(2), vec!["r2", "r3"]));
680        assert_eq!(jobs_answer(&state.mstore, &state.mstore, &JobsFilter { job: String::new(), limit: 1 }).unwrap()["count"], 1);
681    }
682
683    #[tokio::test]
684    async fn jobs_of_other_sources_count_too_and_a_scheduled_job_with_no_run_is_found() {
685        use crate::backend::storage::job_runs::JobRun;
686        let state = ledger_with(&[("j1", "Nightly"), ("j9", "Idle")], &[("r1", "j1", 100)]);
687        state.mstore.job_run_insert(&JobRun::new("d1", "drone-1", "drone", "Report drone", "manual", "finished", 500)).unwrap();
688        state.mstore.job_run_insert(&JobRun::new("c1", "tpl.cloud", "cloud", "Cloud check", "event", "finished", 400)).unwrap();
689        let all = jobs_answer(&state.mstore, &state.mstore, &JobsFilter { job: String::new(), limit: 20 }).unwrap();
690        let ids: Vec<&str> = all["runs"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect();
691        assert_eq!(ids, vec!["d1", "c1", "r1"], "the Drone and cloud jobs' newest runs are in, newest first");
692        for who in ["Report drone", "drone-1", "Cloud check", "tpl.cloud"] {
693            let a = jobs_answer(&state.mstore, &state.mstore, &JobsFilter { job: who.to_string(), limit: 20 }).unwrap();
694            assert_eq!((a["found"].clone(), a["count"].clone()), (json!(true), json!(1)), "{who}");
695        }
696        let idle = jobs_answer(&state.mstore, &state.mstore, &JobsFilter { job: "Idle".to_string(), limit: 20 }).unwrap();
697        assert_eq!((idle["found"].clone(), idle["count"].clone()), (json!(true), json!(0)), "a scheduled job that hasn't run yet exists");
698    }
699
700    #[tokio::test]
701    async fn a_named_job_says_its_last_good_run_even_when_newer_runs_failed_and_the_limit_hides_it() {
702        use crate::backend::storage::job_runs::JobRun;
703        let state = ledger_with(&[("j1", "Nightly")], &[]);
704        let run = |id: &str, outcome: &str, at: i64| {
705            let mut r = JobRun::new(id, "j1", "cron", "Nightly", "schedule", "finished", at);
706            r.outcome = outcome.to_string();
707            r.ended_at_ms = Some(at + 10);
708            state.mstore.job_run_insert(&r).unwrap();
709        };
710        run("old-ok", "ok", 100);
711        run("fail-1", "failed", 200);
712        run("fail-2", "failed", 300);
713        let a = jobs_answer(&state.mstore, &state.mstore, &JobsFilter { job: "Nightly".to_string(), limit: 2 }).unwrap();
714        let ids: Vec<&str> = a["runs"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect();
715        assert_eq!(ids, vec!["fail-2", "fail-1"], "the listing is cut to the two newest, both failed");
716        assert_eq!(a["last_ok"]["id"], json!("old-ok"), "the last good run is not in it, and is still said");
717        assert_eq!(a["last_ok"]["ended_ms"], json!(110));
718        let none = ledger_with(&[("j2", "Never")], &[]);
719        let n = jobs_answer(&none.mstore, &none.mstore, &JobsFilter { job: "Never".to_string(), limit: 20 }).unwrap();
720        assert!(n["last_ok"].is_null(), "no good run: null");
721    }
722
723    #[tokio::test]
724    async fn a_named_job_gives_its_own_runs_by_name_or_id_and_an_unknown_one_is_not_found() {
725        let state = ledger_with(&[("j1", "Nightly"), ("j2", "Backup")], &[("r1", "j1", 100), ("r2", "j1", 300), ("r3", "j2", 200)]);
726        for who in ["Nightly", "j1"] {
727            let a = jobs_answer(&state.mstore, &state.mstore, &JobsFilter { job: who.to_string(), limit: 20 }).unwrap();
728            let ids: Vec<&str> = a["runs"].as_array().unwrap().iter().map(|r| r["id"].as_str().unwrap()).collect();
729            assert_eq!(ids, vec!["r2", "r1"], "{who}: its own runs, newest first");
730        }
731        let none = jobs_answer(&state.mstore, &state.mstore, &JobsFilter { job: "Nope".to_string(), limit: 20 }).unwrap();
732        assert_eq!((none["found"].clone(), none["count"].clone()), (json!(false), json!(0)));
733    }
734
735    #[test]
736    fn the_job_is_named_in_the_graph_and_never_by_a_reference_and_the_run_limit_is_capped() {
737        let s = ExecutionScope::new();
738        assert_eq!(plan(&node(json!({ "query": "jobs", "job": " Nightly ", "limit": 9999 })), &s).unwrap(), Query::Jobs(JobsFilter { job: "Nightly".to_string(), limit: MAX_RUNS }));
739        assert_eq!(plan(&node(json!({ "query": "jobs" })), &s).unwrap(), Query::Jobs(JobsFilter { job: String::new(), limit: DEFAULT_RUNS }));
740        assert!(plan(&node(json!({ "query": "jobs", "job": "{{trigger.job}}" })), &s).unwrap_err().contains("not a {{reference}}"));
741        assert_eq!(plan(&node(json!({ "query": "lan_peers" })), &s).unwrap(), Query::LanPeers);
742    }
743
744    #[test]
745    fn muxbus_says_connected_and_signed_in_in_words_a_condition_can_test() {
746        let status = |state| MuxBusDeliveryStatus { state, since_ms: 5, last_ok_ms: None, last_error: Some("relay down".to_string()), account_email: None, sign_in_unreachable: false };
747        let up = muxbus_answer(&status(MuxBusDeliveryState::Connected));
748        assert_eq!((up["connected"].clone(), up["signed_in"].clone()), (json!(true), json!(true)));
749        let down = muxbus_answer(&status(MuxBusDeliveryState::Reconnecting));
750        assert_eq!((down["connected"].clone(), down["signed_in"].clone()), (json!(false), json!(true)));
751        let out = muxbus_answer(&status(MuxBusDeliveryState::SignedOut));
752        assert_eq!((out["state"].clone(), out["signed_in"].clone(), out["last_error"].clone()), (json!("signed_out"), json!(false), json!("relay down")));
753    }
754
755    #[test]
756    fn an_agent_nobody_has_is_not_found_rather_than_an_error() {
757        use crate::server::availability_view::Known;
758        assert_eq!(agent_answer(Known::Unknown), json!({ "found": false }));
759        assert_eq!(agent_answer(Known::Ambiguous), json!({ "found": false, "ambiguous": true }));
760        assert_eq!(agent_answer(Known::Live(json!({ "state": "idle", "would": "deliver" }))), json!({ "state": "idle", "would": "deliver", "found": true }));
761    }
762
763    #[test]
764    fn agents_say_how_many_are_up_and_which_wanted_running_ones_are_not() {
765        use crate::backend::agent_runtime_state::{AgentDesiredState as D, AgentRuntime, AgentRuntimeState as S};
766        let row = |name: &str, state: S, desired: D, detail: Option<&str>| AgentRuntime {
767            agent_id: format!("uid-{name}"),
768            state,
769            detail: detail.map(str::to_string),
770            resets_at: None,
771            block_id: None,
772            waiting_in: None,
773            desired,
774            name: name.to_string(),
775            provider: "claude".to_string(),
776            icon: String::new(),
777            color: None,
778            blocked: None,
779            runtime: Default::default(),
780            model_id: None,
781            model_label: None,
782            model_source: None,
783            effort: None,
784            pending_switch: None,
785            definition_model_label: None,
786            quiet_since_ms: None,
787            handover: None,
788        };
789        let healthy = agents_answer(&[row("a", S::Idle, D::Running, None), row("b", S::Working, D::Running, None), row("c", S::WaitingOnUser, D::Running, None), row("off", S::Stopped, D::Stopped, None)]);
790        assert_eq!((healthy["count"].clone(), healthy["wanted_running"].clone(), healthy["up"].clone(), healthy["all_up"].clone()), (json!(4), json!(3), json!(3), json!(true)), "an agent wanted stopped is no problem");
791        assert_eq!(healthy["problems"], json!([]));
792        let sick = agents_answer(&[row("a", S::Idle, D::Running, None), row("lost", S::Stopped, D::Running, None), row("out", S::SignedOut, D::Running, Some("needs_login")), row("slow", S::Starting, D::Running, None)]);
793        assert_eq!((sick["wanted_running"].clone(), sick["up"].clone(), sick["all_up"].clone(), sick["problem_count"].clone()), (json!(4), json!(1), json!(false), json!(3)));
794        assert_eq!(sick["problems"][1], json!({ "agent": "out", "state": "signed_out", "detail": "needs_login" }));
795        assert_eq!(sick["problem_names"], json!("lost (stopped), out (signed_out), slow (starting)"));
796        assert_eq!(agents_answer(&[])["all_up"], json!(true), "no agent wanted running is nothing wrong");
797    }
798
799    #[test]
800    fn the_agents_query_has_no_filter() {
801        assert_eq!(plan(&node(json!({ "query": "agents" })), &ExecutionScope::new()).unwrap(), Query::Agents);
802    }
803}