1use super::{
4 BlockedEvent, MergedEvent, RunEvent, StatsEvents, StatusChange, TASK_COLS, Task, TaskStatus,
5};
6use crate::store::TaskStore;
7use sqlx::Row;
8use std::collections::HashMap;
9use std::collections::HashSet;
10
11impl TaskStore {
12 pub async fn list_by_status(
14 &self,
15 repo: &str,
16 status: TaskStatus,
17 ) -> anyhow::Result<Vec<Task>> {
18 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
19 "SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND status = ? ORDER BY created_at DESC"
20 )))
21 .bind(repo)
22 .bind(status.as_str())
23 .fetch_all(&self.pool)
24 .await?;
25
26 rows.iter().map(Self::row_to_task).collect()
27 }
28
29 pub async fn list_for_board(&self, repo: &str, done_limit: i64) -> anyhow::Result<Vec<Task>> {
31 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
32 "SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND status != 'done'
33 UNION ALL
34 SELECT {TASK_COLS} FROM (SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND status = 'done'
35 ORDER BY updated_at DESC LIMIT ?)
36 ORDER BY updated_at DESC"
37 )))
38 .bind(repo)
39 .bind(repo)
40 .bind(done_limit)
41 .fetch_all(&self.pool)
42 .await?;
43
44 rows.iter().map(Self::row_to_task).collect()
45 }
46
47 pub async fn list_running(&self) -> anyhow::Result<Vec<Task>> {
49 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
50 "SELECT {TASK_COLS} FROM tasks WHERE status IN ('in_progress', 'in_review') ORDER BY updated_at ASC"
51 )))
52 .fetch_all(&self.pool)
53 .await?;
54
55 rows.iter().map(Self::row_to_task).collect()
56 }
57
58 pub async fn recent_status_changes(
61 &self,
62 repo: Option<&str>,
63 limit: i64,
64 ) -> anyhow::Result<Vec<StatusChange>> {
65 let rows: Vec<StatusChange> = sqlx::query_as(
66 "SELECT timestamp, task_id, repo, external_id, title, from_status, to_status, agent FROM (
67 SELECT a.timestamp, a.task_id, t.repo, t.external_id, t.title,
68 a.from_status, a.to_status, a.agent
69 FROM task_activity a JOIN tasks t ON t.id = a.task_id
70 WHERE a.to_status IS NOT NULL AND a.to_status IS NOT a.from_status
71 AND (?1 IS NULL OR t.repo = ?1)
72 ORDER BY a.timestamp DESC, a.id DESC LIMIT ?2
73 ) ORDER BY timestamp ASC",
74 )
75 .bind(repo)
76 .bind(limit)
77 .fetch_all(&self.pool)
78 .await?;
79 Ok(rows)
80 }
81
82 pub async fn list_open(&self, repo: Option<&str>) -> anyhow::Result<Vec<Task>> {
84 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
85 "SELECT {TASK_COLS} FROM tasks WHERE status != 'done' AND (?1 IS NULL OR repo = ?1)
86 ORDER BY updated_at DESC"
87 )))
88 .bind(repo)
89 .fetch_all(&self.pool)
90 .await?;
91
92 rows.iter().map(Self::row_to_task).collect()
93 }
94
95 pub async fn entered_between(
97 &self,
98 status: TaskStatus,
99 from: &str,
100 to: &str,
101 repo: Option<&str>,
102 ) -> anyhow::Result<Vec<(String, Task)>> {
103 let hits: Vec<(i64, String)> = sqlx::query_as(
104 "SELECT a.task_id, MAX(a.timestamp) FROM task_activity a JOIN tasks t ON t.id = a.task_id
105 WHERE a.to_status = ?1 AND a.from_status IS NOT ?1
106 AND a.timestamp >= ?2 AND a.timestamp < ?3 AND (?4 IS NULL OR t.repo = ?4)
107 GROUP BY a.task_id ORDER BY MAX(a.timestamp) DESC",
108 )
109 .bind(status.as_str())
110 .bind(from)
111 .bind(to)
112 .bind(repo)
113 .fetch_all(&self.pool)
114 .await?;
115 let mut out = Vec::with_capacity(hits.len());
116 for (id, at) in hits {
117 if let Ok(task) = self.get(id).await {
118 out.push((at, task));
119 }
120 }
121 Ok(out)
122 }
123
124 pub async fn stats_since(&self, since: &str) -> anyhow::Result<StatsEvents> {
126 let merged: Vec<MergedEvent> = sqlx::query_as(
127 "SELECT MAX(a.timestamp) AS at, t.id AS task_id, t.repo, t.agent, t.created_at,
128 t.attempts, t.review_cycles
129 FROM task_activity a JOIN tasks t ON t.id = a.task_id
130 WHERE a.to_status = 'done' AND a.timestamp >= ?1
131 GROUP BY t.id ORDER BY at",
132 )
133 .bind(since)
134 .fetch_all(&self.pool)
135 .await?;
136 let blocked: Vec<BlockedEvent> = sqlx::query_as(
137 "SELECT a.timestamp AS at, t.id AS task_id, t.repo
138 FROM task_activity a JOIN tasks t ON t.id = a.task_id
139 WHERE a.to_status = 'blocked' AND a.from_status IS NOT 'blocked' AND a.timestamp >= ?1
140 ORDER BY a.timestamp",
141 )
142 .bind(since)
143 .fetch_all(&self.pool)
144 .await?;
145 let runs: Vec<RunEvent> = sqlx::query_as(
146 "SELECT r.started_at AS at, t.repo, r.agent, r.model, r.run_type, r.outcome,
147 COALESCE(r.duration_secs, 0.0) AS duration_secs
148 FROM task_runs r JOIN tasks t ON t.id = r.task_id
149 WHERE r.started_at >= ?1 ORDER BY r.started_at",
150 )
151 .bind(since)
152 .fetch_all(&self.pool)
153 .await?;
154 Ok(StatsEvents {
155 merged,
156 blocked,
157 runs,
158 })
159 }
160
161 pub async fn entered_status(&self, ids: &[i64]) -> anyhow::Result<HashMap<i64, String>> {
163 if ids.is_empty() {
164 return Ok(HashMap::new());
165 }
166
167 let marks = vec!["?"; ids.len()].join(",");
168 let sql = format!(
169 "SELECT a.task_id, MAX(a.timestamp) FROM task_activity a JOIN tasks t ON t.id = a.task_id
170 WHERE a.task_id IN ({marks}) AND a.to_status = t.status
171 AND a.from_status IS NOT a.to_status
172 GROUP BY a.task_id"
173 );
174 let mut query = sqlx::query_as::<_, (i64, String)>(sqlx::AssertSqlSafe(sql));
175 for id in ids {
176 query = query.bind(id);
177 }
178 Ok(query.fetch_all(&self.pool).await?.into_iter().collect())
179 }
180
181 pub async fn count_by_status(&self, repo: &str) -> anyhow::Result<Vec<(String, i64)>> {
183 let rows: Vec<(String, i64)> =
184 sqlx::query_as("SELECT status, COUNT(*) FROM tasks WHERE repo = ? GROUP BY status")
185 .bind(repo)
186 .fetch_all(&self.pool)
187 .await?;
188 Ok(rows)
189 }
190
191 pub async fn list_children(&self, repo: &str, parent_id: i64) -> anyhow::Result<Vec<Task>> {
193 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
194 "SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND parent_id = ? ORDER BY created_at ASC"
195 )))
196 .bind(repo)
197 .bind(parent_id)
198 .fetch_all(&self.pool)
199 .await?;
200
201 rows.iter().map(Self::row_to_task).collect()
202 }
203
204 pub async fn list_external_by_status(
206 &self,
207 repo: &str,
208 status: TaskStatus,
209 ) -> anyhow::Result<Vec<Task>> {
210 let rows = sqlx::query(
211 sqlx::AssertSqlSafe(format!("SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND origin != 'internal' AND status = ? ORDER BY created_at DESC")),
212 )
213 .bind(repo)
214 .bind(status.as_str())
215 .fetch_all(&self.pool)
216 .await?;
217
218 rows.iter().map(Self::row_to_task).collect()
219 }
220
221 pub async fn list_routable(&self, repo: &str) -> anyhow::Result<Vec<Task>> {
223 self.list_by_status(repo, TaskStatus::New).await
224 }
225
226 pub async fn list_internal_by_status(
228 &self,
229 repo: &str,
230 status: TaskStatus,
231 ) -> anyhow::Result<Vec<Task>> {
232 let rows = sqlx::query(
233 sqlx::AssertSqlSafe(format!("SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND origin = 'internal' AND status = ? ORDER BY created_at DESC")),
234 )
235 .bind(repo)
236 .bind(status.as_str())
237 .fetch_all(&self.pool)
238 .await?;
239
240 rows.iter().map(Self::row_to_task).collect()
241 }
242
243 pub async fn list_all_internal(&self, repo: &str) -> anyhow::Result<Vec<Task>> {
245 let rows = sqlx::query(
246 sqlx::AssertSqlSafe(format!("SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND origin = 'internal' ORDER BY created_at DESC")),
247 )
248 .bind(repo)
249 .fetch_all(&self.pool)
250 .await?;
251
252 rows.iter().map(Self::row_to_task).collect()
253 }
254
255 pub async fn list_internal_by_source(
258 &self,
259 repo: &str,
260 source: &str,
261 ) -> anyhow::Result<Vec<Task>> {
262 let rows = sqlx::query(
263 sqlx::AssertSqlSafe(format!("SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND origin = 'internal' AND source = ? ORDER BY created_at DESC")),
264 )
265 .bind(repo)
266 .bind(source)
267 .fetch_all(&self.pool)
268 .await?;
269
270 rows.iter().map(Self::row_to_task).collect()
271 }
272
273 pub async fn list_source_ids_by_source(
278 &self,
279 repo: &str,
280 source: &str,
281 since_days: i64,
282 ) -> anyhow::Result<Vec<String>> {
283 let cutoff = format!("-{since_days} days");
284 let rows = sqlx::query(
285 "SELECT source_id FROM tasks WHERE repo = ? AND origin = 'internal' AND source = ? AND created_at >= datetime('now', ?)",
286 )
287 .bind(repo)
288 .bind(source)
289 .bind(&cutoff)
290 .fetch_all(&self.pool)
291 .await?;
292
293 let mut ids = Vec::with_capacity(rows.len());
294 for row in &rows {
295 ids.push(row.try_get::<String, _>("source_id").map_err(|e| {
296 anyhow::anyhow!(
297 "list_source_ids_by_source: failed to decode source_id for repo={repo}, source={source}: {e}"
298 )
299 })?);
300 }
301 Ok(ids)
302 }
303
304 pub async fn list_active(&self, repo: &str) -> anyhow::Result<Vec<Task>> {
306 let rows = sqlx::query(
307 sqlx::AssertSqlSafe(format!("SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND status != 'done' ORDER BY created_at DESC")),
308 )
309 .bind(repo)
310 .fetch_all(&self.pool)
311 .await?;
312
313 rows.iter().map(Self::row_to_task).collect()
314 }
315
316 pub async fn list_all_external(&self, repo: &str) -> anyhow::Result<Vec<Task>> {
318 let rows = sqlx::query(
319 sqlx::AssertSqlSafe(format!("SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND origin != 'internal' ORDER BY created_at DESC")),
320 )
321 .bind(repo)
322 .fetch_all(&self.pool)
323 .await?;
324
325 rows.iter().map(Self::row_to_task).collect()
326 }
327
328 pub async fn has_external_tasks(&self, repo: &str) -> anyhow::Result<bool> {
330 let has_external = sqlx::query_scalar::<_, i32>(
331 "SELECT 1 FROM tasks WHERE repo = ? AND origin != 'internal' LIMIT 1",
332 )
333 .bind(repo)
334 .fetch_optional(&self.pool)
335 .await?
336 .is_some();
337 Ok(has_external)
338 }
339
340 pub async fn existing_external_ids(&self, repo: &str) -> anyhow::Result<HashSet<String>> {
344 let rows: Vec<(String,)> = sqlx::query_as(
345 "SELECT external_id FROM tasks WHERE repo = ? AND origin != 'internal' AND external_id IS NOT NULL",
346 )
347 .bind(repo)
348 .fetch_all(&self.pool)
349 .await?;
350
351 Ok(rows
352 .into_iter()
353 .filter_map(|(id,)| if id.is_empty() { None } else { Some(id) })
354 .collect())
355 }
356
357 pub async fn list_for_doctor(&self, repo: &str, cutoff_str: &str) -> anyhow::Result<Vec<Task>> {
360 let rows = sqlx::query(
361 sqlx::AssertSqlSafe(format!("SELECT {TASK_COLS} FROM tasks WHERE repo = ? AND (status != 'done' OR updated_at >= ?) ORDER BY created_at DESC")),
362 )
363 .bind(repo)
364 .bind(cutoff_str)
365 .fetch_all(&self.pool)
366 .await?;
367 rows.iter().map(Self::row_to_task).collect()
368 }
369
370 pub async fn list_all(&self, repo: &str) -> anyhow::Result<Vec<Task>> {
372 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
373 "SELECT {TASK_COLS} FROM tasks WHERE repo = ? ORDER BY created_at DESC"
374 )))
375 .bind(repo)
376 .fetch_all(&self.pool)
377 .await?;
378 rows.iter().map(Self::row_to_task).collect()
379 }
380
381 pub async fn distinct_repos(&self) -> anyhow::Result<Vec<String>> {
383 let rows =
384 sqlx::query("SELECT DISTINCT repo FROM tasks WHERE repo IS NOT NULL AND repo != ''")
385 .fetch_all(&self.pool)
386 .await?;
387 let mut repos = Vec::new();
388 for row in &rows {
389 repos.push(row.try_get::<String, _>("repo").map_err(|e| {
390 anyhow::anyhow!("distinct_repos: failed to decode 'repo' column: {e}")
391 })?);
392 }
393 Ok(repos)
394 }
395
396 pub async fn list_all_active_global(&self) -> anyhow::Result<Vec<Task>> {
401 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
402 "SELECT {TASK_COLS} FROM tasks WHERE status != 'done' ORDER BY created_at DESC"
403 )))
404 .fetch_all(&self.pool)
405 .await?;
406 rows.iter().map(Self::row_to_task).collect()
407 }
408
409 pub async fn list_all_global(&self) -> anyhow::Result<Vec<Task>> {
413 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
414 "SELECT {TASK_COLS} FROM tasks ORDER BY created_at DESC"
415 )))
416 .fetch_all(&self.pool)
417 .await?;
418 rows.iter().map(Self::row_to_task).collect()
419 }
420
421 pub async fn list_all_by_status_global(&self, status: TaskStatus) -> anyhow::Result<Vec<Task>> {
425 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
426 "SELECT {TASK_COLS} FROM tasks WHERE status = ? ORDER BY created_at DESC"
427 )))
428 .bind(status.as_str())
429 .fetch_all(&self.pool)
430 .await?;
431 rows.iter().map(Self::row_to_task).collect()
432 }
433
434 pub async fn get_batch(&self, ids: &[i64]) -> anyhow::Result<HashMap<i64, Task>> {
437 const CHUNK_SIZE: usize = 500;
440 if ids.is_empty() {
441 return Ok(HashMap::new());
442 }
443
444 let mut result = HashMap::new();
445
446 for chunk in ids.chunks(CHUNK_SIZE) {
447 let placeholders = chunk.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
448 let sql = format!("SELECT {TASK_COLS} FROM tasks WHERE id IN ({placeholders})");
449 let mut query = sqlx::query(sqlx::AssertSqlSafe(sql.as_str()));
450 for id in chunk {
451 query = query.bind(*id);
452 }
453 let rows = query.fetch_all(&self.pool).await?;
454 for row in &rows {
455 let task = Self::row_to_task(row)?;
456 result.insert(task.id, task);
457 }
458 }
459 Ok(result)
460 }
461
462 pub async fn get_statuses_by_external_ids(
467 &self,
468 repo: &str,
469 ext_ids: &[&str],
470 ) -> anyhow::Result<HashMap<String, TaskStatus>> {
471 const CHUNK_SIZE: usize = 500;
472 let mut result = HashMap::new();
473 if ext_ids.is_empty() {
474 return Ok(result);
475 }
476
477 for chunk in ext_ids.chunks(CHUNK_SIZE) {
478 let placeholders = chunk.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
479 let sql = format!(
480 "SELECT external_id, status FROM tasks WHERE repo = ? AND external_id IN ({placeholders})"
481 );
482 let mut query = sqlx::query(sqlx::AssertSqlSafe(sql.as_str()));
483 query = query.bind(repo);
484 for id in chunk {
485 query = query.bind(id);
486 }
487 let rows = query.fetch_all(&self.pool).await?;
488 for row in &rows {
489 let external_id: Result<String, _> = row.try_get("external_id");
490 let status_str: Result<String, _> = row.try_get("status");
491 match (external_id, status_str) {
492 (Ok(ext_id), Ok(sts)) => {
493 if ext_id.is_empty() {
494 tracing::warn!(status = %sts, "skipping task row with empty external_id");
495 continue;
496 }
497 if let Some(status) = TaskStatus::from_str(&sts) {
498 result.insert(ext_id, status);
499 } else {
500 tracing::warn!(external_id = %ext_id, status = %sts, "unknown status value in tasks table");
501 }
502 }
503 (Err(e), _) => {
504 tracing::warn!(error = %e, "skipping task row with decode error for external_id");
505 }
506 (_, Err(e)) => {
507 tracing::warn!(error = %e, "skipping task row with decode error for status");
508 }
509 }
510 }
511 }
512
513 Ok(result)
514 }
515}