Skip to main content

orch/store/
metrics.rs

1use std::collections::HashMap;
2
3use super::TaskStore;
4#[cfg(test)]
5use chrono::Datelike;
6use chrono::Utc;
7use serde::{Deserialize, Serialize};
8use sqlx::Row;
9
10/// Parameters for inserting a new task metric record.
11#[derive(Debug, Clone)]
12pub struct InsertTaskMetric<'a> {
13    pub repo: &'a str,
14    pub task_id: &'a str,
15    pub agent: &'a str,
16    pub model: Option<&'a str>,
17    pub complexity: Option<&'a str>,
18    pub outcome: &'a str,
19    pub duration_seconds: f64,
20    pub started_at: &'a chrono::DateTime<Utc>,
21    pub completed_at: &'a chrono::DateTime<Utc>,
22    pub attempts: i32,
23    pub files_changed: i32,
24    pub error_type: Option<&'a str>,
25    pub input_tokens: Option<i64>,
26    pub output_tokens: Option<i64>,
27    pub total_cost_usd: Option<f64>,
28}
29
30/// Metrics summary for the CLI output.
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct MetricsSummary {
33    pub tasks_completed_24h: i64,
34    pub tasks_failed_24h: i64,
35    pub avg_duration_simple: Option<f64>,
36    pub avg_duration_medium: Option<f64>,
37    pub avg_duration_complex: Option<f64>,
38    pub agent_stats: Vec<AgentStat>,
39    pub rate_limits_24h: i64,
40}
41
42/// Agent statistics from metrics.
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct AgentStat {
45    pub agent: String,
46    pub total_runs: i64,
47    pub success_count: i64,
48    pub success_rate: f64,
49}
50
51/// Slow task info for pattern detection.
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct SlowTaskInfo {
54    pub task_id: String,
55    pub agent: String,
56    pub complexity: Option<String>,
57    pub duration_seconds: f64,
58}
59
60/// Error type distribution for pattern detection.
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct ErrorStat {
63    pub error_type: Option<String>,
64    pub count: i64,
65}
66
67/// Task with high review cycle count (persistent review loop).
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct HighReviewCycleTask {
70    pub external_id: Option<String>,
71    pub agent: Option<String>,
72    pub review_cycles: i64,
73    pub title: String,
74}
75
76/// Cost summary across multiple time periods.
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct CostSummary {
79    pub periods: Vec<CostPeriod>,
80}
81
82/// Cost data for a single time period.
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct CostPeriod {
85    pub label: String,
86    pub input_tokens: i64,
87    pub output_tokens: i64,
88    pub total_cost_usd: f64,
89    pub task_count: i64,
90}
91
92/// Cost breakdown by a grouping dimension (agent, model, etc.).
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct CostByGroup {
95    pub name: String,
96    pub input_tokens: i64,
97    pub output_tokens: i64,
98    pub total_cost_usd: f64,
99    pub task_count: i64,
100}
101
102/// Build the week-scoped KV key for the self-improvement counter.
103/// Test-only helper.
104#[cfg(test)]
105fn self_improvement_key() -> String {
106    let now = Utc::now();
107    format!(
108        "self_improvement_issues_{}_w{}",
109        now.iso_week().year(),
110        now.iso_week().week()
111    )
112}
113
114impl TaskStore {
115    pub async fn cost_summary(&self, repo: &str) -> anyhow::Result<(i64, i64, f64)> {
116        let row = sqlx::query(
117            "SELECT
118            COALESCE(SUM(input_tokens), 0) as total_input,
119            COALESCE(SUM(output_tokens), 0) as total_output,
120            COALESCE(SUM(total_cost_usd), 0.0) as total_cost
121         FROM tasks WHERE repo = ?",
122        )
123        .bind(repo)
124        .fetch_one(&self.pool)
125        .await?;
126
127        Ok((
128            row.try_get::<i64, _>("total_input")?,
129            row.try_get::<i64, _>("total_output")?,
130            row.try_get::<f64, _>("total_cost")?,
131        ))
132    }
133
134    /// Count tasks by status for a repo.
135    /// Returns a map of status string → count.
136    /// Only needed by tests.
137    #[cfg(test)]
138    pub async fn status_counts(&self, repo: &str) -> anyhow::Result<HashMap<String, i64>> {
139        let rows =
140            sqlx::query("SELECT status, COUNT(*) as cnt FROM tasks WHERE repo = ? GROUP BY status")
141                .bind(repo)
142                .fetch_all(&self.pool)
143                .await?;
144
145        let mut map = HashMap::new();
146        for row in &rows {
147            let status: String = row.try_get("status")?;
148            let count: i64 = row.try_get("cnt")?;
149            map.insert(status, count);
150        }
151        Ok(map)
152    }
153
154    pub async fn insert_task_metric(&self, metric: &InsertTaskMetric<'_>) -> anyhow::Result<i64> {
155        let mut tx = self.begin_write().await?;
156
157        sqlx::query(
158            "DELETE FROM task_metrics WHERE datetime(completed_at) < datetime('now', '-90 days')",
159        )
160        .execute(&mut *tx)
161        .await?;
162
163        let row = sqlx::query(
164        "INSERT INTO task_metrics (repo, task_id, agent, model, complexity, outcome, duration_seconds,
165         started_at, completed_at, attempts, files_changed, error_type,
166         input_tokens, output_tokens, total_cost_usd)
167         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
168         RETURNING id",
169    )
170    .bind(metric.repo)
171    .bind(metric.task_id)
172    .bind(metric.agent)
173    .bind(metric.model)
174    .bind(metric.complexity)
175    .bind(metric.outcome)
176    .bind(metric.duration_seconds)
177    .bind(metric.started_at.to_rfc3339())
178    .bind(metric.completed_at.to_rfc3339())
179    .bind(metric.attempts)
180    .bind(metric.files_changed)
181    .bind(metric.error_type)
182    .bind(metric.input_tokens)
183    .bind(metric.output_tokens)
184    .bind(metric.total_cost_usd)
185    .fetch_one(&mut *tx)
186    .await?;
187
188        tx.commit().await?;
189        Ok(row.try_get("id")?)
190    }
191
192    /// Get aggregated metrics for a configurable time window.
193    ///
194    /// `hours` controls how far back to look (e.g. 24 for 24 h, 168 for 7 days).
195    /// The interval string is built from a `u32` config value, not user input.
196    pub async fn get_metrics_summary(&self, hours: u32) -> anyhow::Result<MetricsSummary> {
197        let interval = format!("-{hours} hours");
198
199        let row = sqlx::query(
200            "SELECT
201                COALESCE(SUM(CASE WHEN outcome = 'success' THEN 1 ELSE 0 END), 0) AS completed,
202                COALESCE(SUM(CASE WHEN outcome != 'success' THEN 1 ELSE 0 END), 0) AS failed,
203                AVG(CASE WHEN complexity = 'simple' THEN duration_seconds END) AS avg_simple,
204                AVG(CASE WHEN complexity = 'medium' THEN duration_seconds END) AS avg_medium,
205                AVG(CASE WHEN complexity = 'complex' THEN duration_seconds END) AS avg_complex
206             FROM task_metrics
207             WHERE datetime(completed_at) >= datetime('now', ?)",
208        )
209        .bind(&interval)
210        .fetch_one(&self.pool)
211        .await?;
212
213        let completed: i64 = row.try_get("completed")?;
214        let failed: i64 = row.try_get("failed")?;
215        // AVG over a filtered subset is legitimately NULL when no rows match the complexity.
216        let avg_simple: Option<f64> = row.try_get("avg_simple")?;
217        let avg_medium: Option<f64> = row.try_get("avg_medium")?;
218        let avg_complex: Option<f64> = row.try_get("avg_complex")?;
219
220        let agent_rows = sqlx::query(
221            "SELECT agent, COUNT(*) as total,
222                COALESCE(SUM(CASE WHEN outcome = 'success' THEN 1 ELSE 0 END), 0) as success_count
223             FROM task_metrics
224             WHERE datetime(completed_at) >= datetime('now', ?)
225             GROUP BY agent",
226        )
227        .bind(&interval)
228        .fetch_all(&self.pool)
229        .await?;
230
231        #[expect(clippy::cast_precision_loss, reason = "a display percentage")]
232        let agent_stats: Vec<AgentStat> = agent_rows
233            .iter()
234            .map(|row| {
235                let total: i64 = row.try_get("total")?;
236                let success: i64 = row.try_get("success_count")?;
237                Ok::<AgentStat, sqlx::Error>(AgentStat {
238                    agent: row.try_get("agent")?,
239                    total_runs: total,
240                    success_count: success,
241                    success_rate: if total > 0 {
242                        (success as f64 / total as f64) * 100.0
243                    } else {
244                        0.0
245                    },
246                })
247            })
248            .collect::<Result<Vec<_>, _>>()?;
249
250        let rate_limit_count: (i64,) = sqlx::query_as(
251            "SELECT COUNT(*) FROM rate_limits WHERE occurred_at >= datetime('now', ?)",
252        )
253        .bind(&interval)
254        .fetch_one(&self.pool)
255        .await?;
256
257        Ok(MetricsSummary {
258            tasks_completed_24h: completed,
259            tasks_failed_24h: failed,
260            avg_duration_simple: avg_simple,
261            avg_duration_medium: avg_medium,
262            avg_duration_complex: avg_complex,
263            agent_stats,
264            rate_limits_24h: rate_limit_count.0,
265        })
266    }
267
268    /// Get aggregated metrics for the last 24 hours.
269    /// Test-only convenience wrapper — delegates to `get_metrics_summary(24)` so the
270    /// test exercises the same code path as production.
271    #[cfg(test)]
272    pub async fn get_metrics_summary_24h(&self) -> anyhow::Result<MetricsSummary> {
273        self.get_metrics_summary(24).await
274    }
275
276    /// Get metrics summary for a configurable time window, filtered by repo.
277    ///
278    /// `hours` controls how far back to look. Uses `COALESCE(NULLIF(m.repo, ''), t.repo)`
279    /// join pattern so older metric rows without a repo column still match.
280    ///
281    /// Optimized to use a single CTE query with conditional aggregation instead of 7 sequential queries.
282    pub async fn get_metrics_summary_by_repo(
283        &self,
284        repo: &str,
285        hours: u32,
286    ) -> anyhow::Result<MetricsSummary> {
287        let interval = format!("-{hours} hours");
288
289        let rows = sqlx::query(
290            "WITH base AS (
291                SELECT m.outcome, m.complexity, m.duration_seconds, m.agent,
292                    COALESCE(NULLIF(m.repo, ''), (
293                    SELECT t.repo FROM tasks t
294                    WHERE CAST(t.id AS TEXT) = m.task_id OR t.external_id = m.task_id
295                    ORDER BY (CAST(t.id AS TEXT) = m.task_id) DESC LIMIT 1
296                )) AS resolved_repo
297                FROM task_metrics m
298                WHERE datetime(m.completed_at) >= datetime('now', ?)
299            )
300            SELECT
301                COALESCE(SUM(CASE WHEN outcome = 'success' THEN 1 ELSE 0 END), 0) AS completed,
302                COALESCE(SUM(CASE WHEN outcome != 'success' THEN 1 ELSE 0 END), 0) AS failed,
303                AVG(CASE WHEN complexity = 'simple' THEN duration_seconds END) AS avg_simple,
304                AVG(CASE WHEN complexity = 'medium' THEN duration_seconds END) AS avg_medium,
305                AVG(CASE WHEN complexity = 'complex' THEN duration_seconds END) AS avg_complex
306            FROM base
307            WHERE resolved_repo = ?",
308        )
309        .bind(&interval)
310        .bind(repo)
311        .fetch_one(&self.pool)
312        .await?;
313
314        let completed: i64 = rows.try_get("completed")?;
315        let failed: i64 = rows.try_get("failed")?;
316        // AVG over a filtered subset is legitimately NULL when no rows match the complexity.
317        let avg_simple: Option<f64> = rows.try_get("avg_simple")?;
318        let avg_medium: Option<f64> = rows.try_get("avg_medium")?;
319        let avg_complex: Option<f64> = rows.try_get("avg_complex")?;
320
321        let agent_rows = sqlx::query(
322            "SELECT m.agent, COUNT(*) as total,
323                COALESCE(SUM(CASE WHEN m.outcome = 'success' THEN 1 ELSE 0 END), 0) as success_count
324             FROM task_metrics m
325             WHERE datetime(m.completed_at) >= datetime('now', ?)
326             AND COALESCE(NULLIF(m.repo, ''), (
327                    SELECT t.repo FROM tasks t
328                    WHERE CAST(t.id AS TEXT) = m.task_id OR t.external_id = m.task_id
329                    ORDER BY (CAST(t.id AS TEXT) = m.task_id) DESC LIMIT 1
330                )) = ?
331             GROUP BY m.agent",
332        )
333        .bind(&interval)
334        .bind(repo)
335        .fetch_all(&self.pool)
336        .await?;
337
338        #[expect(clippy::cast_precision_loss, reason = "a display percentage")]
339        let agent_stats: Vec<AgentStat> = agent_rows
340            .iter()
341            .map(|row| {
342                let total: i64 = row.try_get("total")?;
343                let success: i64 = row.try_get("success_count")?;
344                Ok::<AgentStat, sqlx::Error>(AgentStat {
345                    agent: row.try_get("agent")?,
346                    total_runs: total,
347                    success_count: success,
348                    success_rate: if total > 0 {
349                        (success as f64 / total as f64) * 100.0
350                    } else {
351                        0.0
352                    },
353                })
354            })
355            .collect::<Result<Vec<_>, _>>()?;
356
357        let rate_limits: (i64,) = sqlx::query_as(
358            "SELECT COUNT(*)
359             FROM rate_limits r
360             WHERE r.occurred_at >= datetime('now', ?)
361             AND (
362                 SELECT t.repo FROM tasks t
363                 WHERE t.external_id = r.task_id OR CAST(t.id AS TEXT) = r.task_id
364                 ORDER BY (t.external_id = r.task_id) DESC, t.id LIMIT 1
365             ) = ?",
366        )
367        .bind(&interval)
368        .bind(repo)
369        .fetch_one(&self.pool)
370        .await?;
371
372        Ok(MetricsSummary {
373            tasks_completed_24h: completed,
374            tasks_failed_24h: failed,
375            avg_duration_simple: avg_simple,
376            avg_duration_medium: avg_medium,
377            avg_duration_complex: avg_complex,
378            agent_stats,
379            rate_limits_24h: rate_limits.0,
380        })
381    }
382
383    /// Get cost summary filtered to a specific repository for a configurable window.
384    ///
385    /// Uses the same `COALESCE(NULLIF(m.repo, ''), t.repo)` join pattern as
386    /// `get_metrics_summary_by_repo` so older metrics rows that lack a `repo`
387    /// column value are still matched via the tasks table.
388    pub async fn get_cost_summary_by_repo(
389        &self,
390        repo: &str,
391        hours: u32,
392    ) -> anyhow::Result<CostSummary> {
393        let interval = format!("-{hours} hours");
394        let row = sqlx::query(
395            "SELECT COALESCE(SUM(m.input_tokens), 0) as input_tokens,
396                COALESCE(SUM(m.output_tokens), 0) as output_tokens,
397                COALESCE(SUM(m.total_cost_usd), 0.0) as total_cost_usd,
398                COUNT(*) as task_count
399         FROM task_metrics m
400         WHERE datetime(m.completed_at) >= datetime('now', ?)
401         AND COALESCE(NULLIF(m.repo, ''), (
402                    SELECT t.repo FROM tasks t
403                    WHERE CAST(t.id AS TEXT) = m.task_id OR t.external_id = m.task_id
404                    ORDER BY (CAST(t.id AS TEXT) = m.task_id) DESC LIMIT 1
405                )) = ?",
406        )
407        .bind(&interval)
408        .bind(repo)
409        .fetch_one(&self.pool)
410        .await?;
411
412        Ok(CostSummary {
413            periods: vec![CostPeriod {
414                label: if hours == 24 {
415                    "24h".to_string()
416                } else if hours.is_multiple_of(24) {
417                    format!("{}d", hours / 24)
418                } else {
419                    format!("{hours}h")
420                },
421                input_tokens: row.try_get("input_tokens")?,
422                output_tokens: row.try_get("output_tokens")?,
423                total_cost_usd: row.try_get("total_cost_usd")?,
424                task_count: row.try_get("task_count")?,
425            }],
426        })
427    }
428
429    /// Record a rate limit event. Prunes records older than 30 days.
430    pub async fn record_rate_limit(
431        &self,
432        agent: &str,
433        limit_type: &str,
434        task_id: Option<&str>,
435    ) -> anyhow::Result<i64> {
436        let mut tx = self.begin_write().await?;
437
438        sqlx::query("DELETE FROM rate_limits WHERE occurred_at < datetime('now', '-30 days')")
439            .execute(&mut *tx)
440            .await?;
441
442        let row = sqlx::query(
443            "INSERT INTO rate_limits (agent, limit_type, occurred_at, task_id)
444         VALUES (?, ?, datetime('now'), ?)
445         RETURNING id",
446        )
447        .bind(agent)
448        .bind(limit_type)
449        .bind(task_id)
450        .fetch_one(&mut *tx)
451        .await?;
452
453        tx.commit().await?;
454        Ok(row.try_get("id")?)
455    }
456
457    /// Record a rate limit event at an explicit SQLite datetime (`YYYY-MM-DD HH:MM:SS`)
458    pub async fn record_rate_limit_at(
459        &self,
460        agent: &str,
461        limit_type: &str,
462        task_id: Option<&str>,
463        occurred_at: &str,
464    ) -> anyhow::Result<i64> {
465        let mut tx = self.begin_write().await?;
466
467        sqlx::query("DELETE FROM rate_limits WHERE occurred_at < datetime('now', '-30 days')")
468            .execute(&mut *tx)
469            .await?;
470
471        let row = sqlx::query(
472            "INSERT INTO rate_limits (agent, limit_type, occurred_at, task_id)
473         VALUES (?, ?, ?, ?)
474         RETURNING id",
475        )
476        .bind(agent)
477        .bind(limit_type)
478        .bind(occurred_at)
479        .bind(task_id)
480        .fetch_one(&mut *tx)
481        .await?;
482
483        tx.commit().await?;
484        Ok(row.try_get("id")?)
485    }
486
487    /// Distinct agents that have at least one `rate_limits` row
488    pub async fn rate_limit_agents(&self) -> anyhow::Result<Vec<String>> {
489        let rows = sqlx::query("SELECT DISTINCT agent FROM rate_limits")
490            .fetch_all(&self.pool)
491            .await?;
492        let mut agents = Vec::with_capacity(rows.len());
493        for row in &rows {
494            agents.push(row.try_get("agent")?);
495        }
496        Ok(agents)
497    }
498
499    /// Count recent rate-limit events per agent within the given window (in hours).
500    ///
501    /// Only `limit_type = 'rate'` rows count. Failures, auth errors and
502    /// timeouts keep their own cooldowns and must not mark an agent degraded.
503    /// Rows at or before `rate_limits_cleared_at:{agent}` are ignored so
504    /// `orch cooldown clear` can un-degrade without deleting metrics
505    pub async fn recent_rate_limit_counts(
506        &self,
507        window_hours: u32,
508    ) -> anyhow::Result<HashMap<String, i64>> {
509        // SQLite datetime modifiers don't support parameterised intervals, so
510        // we build the interval string and embed it directly.  The value comes
511        // from a config integer, not user input, so this is safe.
512        let interval = format!("-{window_hours} hours");
513        let rows = sqlx::query(
514            "SELECT r.agent, COUNT(*) as cnt
515             FROM rate_limits r
516             LEFT JOIN kv ON kv.key = 'rate_limits_cleared_at:' || r.agent
517             WHERE r.occurred_at >= datetime('now', ?)
518               AND r.limit_type = 'rate'
519               AND (
520                 kv.value IS NULL
521                 OR r.occurred_at > datetime(CAST(kv.value AS INTEGER), 'unixepoch')
522               )
523             GROUP BY r.agent",
524        )
525        .bind(&interval)
526        .fetch_all(&self.pool)
527        .await?;
528
529        let mut map = HashMap::new();
530        for row in &rows {
531            let agent: String = row.try_get("agent")?;
532            let cnt: i64 = row.try_get("cnt")?;
533            map.insert(agent, cnt);
534        }
535        Ok(map)
536    }
537
538    /// Get slow tasks (top 10 longest running) for a configurable time window.
539    pub async fn get_slow_tasks(&self, hours: u32) -> anyhow::Result<Vec<SlowTaskInfo>> {
540        let interval = format!("-{hours} hours");
541        let rows = sqlx::query(
542            "SELECT task_id, agent, complexity, duration_seconds
543         FROM task_metrics
544         WHERE datetime(completed_at) >= datetime('now', ?) AND outcome = 'success'
545         ORDER BY duration_seconds DESC
546         LIMIT 10",
547        )
548        .bind(&interval)
549        .fetch_all(&self.pool)
550        .await?;
551
552        rows.iter()
553            .map(|row| {
554                Ok(SlowTaskInfo {
555                    task_id: row.try_get("task_id")?,
556                    agent: row.try_get("agent")?,
557                    // complexity is a nullable column — NULL is a valid value
558                    complexity: row.try_get("complexity")?,
559                    duration_seconds: row.try_get("duration_seconds")?,
560                })
561            })
562            .collect()
563    }
564
565    /// Get slow tasks (top 10 longest running) from the last 7 days.
566    /// Test-only wrapper.
567    #[cfg(test)]
568    pub async fn get_slow_tasks_7d(&self) -> anyhow::Result<Vec<SlowTaskInfo>> {
569        let rows = sqlx::query(
570            "SELECT task_id, agent, complexity, duration_seconds
571         FROM task_metrics
572         WHERE datetime(completed_at) >= datetime('now', '-7 days') AND outcome = 'success'
573         ORDER BY duration_seconds DESC
574         LIMIT 10",
575        )
576        .fetch_all(&self.pool)
577        .await?;
578
579        rows.iter()
580            .map(|row| {
581                Ok(SlowTaskInfo {
582                    task_id: row.try_get("task_id")?,
583                    agent: row.try_get("agent")?,
584                    // complexity is a nullable column — NULL is a valid value
585                    complexity: row.try_get("complexity")?,
586                    duration_seconds: row.try_get("duration_seconds")?,
587                })
588            })
589            .collect()
590    }
591
592    /// Get error type distribution for a configurable time window.
593    pub async fn get_error_distribution(&self, hours: u32) -> anyhow::Result<Vec<ErrorStat>> {
594        let interval = format!("-{hours} hours");
595        let rows = sqlx::query(
596            "SELECT error_type, COUNT(*) as count
597         FROM task_metrics
598         WHERE datetime(completed_at) >= datetime('now', ?)
599           AND outcome != 'success'
600           AND error_type IS NOT NULL
601         GROUP BY error_type
602         ORDER BY count DESC",
603        )
604        .bind(&interval)
605        .fetch_all(&self.pool)
606        .await?;
607
608        rows.iter()
609            .map(|row| {
610                Ok(ErrorStat {
611                    // error_type is a nullable column — NULL is a valid value
612                    error_type: row.try_get("error_type")?,
613                    count: row.try_get("count")?,
614                })
615            })
616            .collect()
617    }
618
619    /// Get cost summary over multiple time windows (24h, 7d, 30d).
620    ///
621    /// Uses separate static queries per window because SQLite's `datetime()`
622    /// modifier argument cannot be parameterised via `?` bind.
623    pub async fn get_cost_summary(&self) -> anyhow::Result<CostSummary> {
624        // Each entry: (static SQL with the interval baked in, label)
625        let windows: &[(&'static str, &str)] = &[
626            (
627                "SELECT COALESCE(SUM(input_tokens), 0) as input_tokens,
628                    COALESCE(SUM(output_tokens), 0) as output_tokens,
629                    COALESCE(SUM(total_cost_usd), 0.0) as total_cost_usd,
630                    COUNT(*) as task_count
631             FROM task_metrics
632             WHERE datetime(completed_at) >= datetime('now', '-24 hours')",
633                "24h",
634            ),
635            (
636                "SELECT COALESCE(SUM(input_tokens), 0) as input_tokens,
637                    COALESCE(SUM(output_tokens), 0) as output_tokens,
638                    COALESCE(SUM(total_cost_usd), 0.0) as total_cost_usd,
639                    COUNT(*) as task_count
640             FROM task_metrics
641             WHERE datetime(completed_at) >= datetime('now', '-7 days')",
642                "7d",
643            ),
644            (
645                "SELECT COALESCE(SUM(input_tokens), 0) as input_tokens,
646                    COALESCE(SUM(output_tokens), 0) as output_tokens,
647                    COALESCE(SUM(total_cost_usd), 0.0) as total_cost_usd,
648                    COUNT(*) as task_count
649             FROM task_metrics
650             WHERE datetime(completed_at) >= datetime('now', '-30 days')",
651                "30d",
652            ),
653        ];
654
655        let mut periods = Vec::new();
656        for (query, label) in windows {
657            let row = sqlx::query(*query).fetch_one(&self.pool).await?;
658            periods.push(CostPeriod {
659                label: label.to_string(),
660                input_tokens: row.try_get("input_tokens")?,
661                output_tokens: row.try_get("output_tokens")?,
662                total_cost_usd: row.try_get("total_cost_usd")?,
663                task_count: row.try_get("task_count")?,
664            });
665        }
666
667        Ok(CostSummary { periods })
668    }
669
670    /// Get cost breakdown by agent.
671    pub async fn get_cost_by_agent(&self) -> anyhow::Result<Vec<CostByGroup>> {
672        let rows = sqlx::query(
673            "SELECT agent as name,
674                COALESCE(SUM(input_tokens), 0) as input_tokens,
675                COALESCE(SUM(output_tokens), 0) as output_tokens,
676                COALESCE(SUM(total_cost_usd), 0.0) as total_cost_usd,
677                COUNT(*) as task_count
678         FROM task_metrics
679         GROUP BY agent
680         ORDER BY SUM(total_cost_usd) DESC",
681        )
682        .fetch_all(&self.pool)
683        .await?;
684
685        rows.iter()
686            .map(|row| {
687                Ok(CostByGroup {
688                    name: row.try_get("name")?,
689                    input_tokens: row.try_get("input_tokens")?,
690                    output_tokens: row.try_get("output_tokens")?,
691                    total_cost_usd: row.try_get("total_cost_usd")?,
692                    task_count: row.try_get("task_count")?,
693                })
694            })
695            .collect()
696    }
697
698    /// Get cost breakdown by model.
699    pub async fn get_cost_by_model(&self) -> anyhow::Result<Vec<CostByGroup>> {
700        let rows = sqlx::query(
701            "SELECT COALESCE(model, 'unknown') as name,
702                COALESCE(SUM(input_tokens), 0) as input_tokens,
703                COALESCE(SUM(output_tokens), 0) as output_tokens,
704                COALESCE(SUM(total_cost_usd), 0.0) as total_cost_usd,
705                COUNT(*) as task_count
706         FROM task_metrics
707         GROUP BY model
708         ORDER BY SUM(total_cost_usd) DESC",
709        )
710        .fetch_all(&self.pool)
711        .await?;
712
713        rows.iter()
714            .map(|row| {
715                Ok(CostByGroup {
716                    name: row.try_get("name")?,
717                    input_tokens: row.try_get("input_tokens")?,
718                    output_tokens: row.try_get("output_tokens")?,
719                    total_cost_usd: row.try_get("total_cost_usd")?,
720                    task_count: row.try_get("task_count")?,
721                })
722            })
723            .collect()
724    }
725
726    /// Get the duration_seconds from the most recent metric row for a task.
727    /// Returns `None` when no metric has been recorded yet.
728    pub async fn latest_task_metric_duration(&self, task_id: &str) -> Option<f64> {
729        sqlx::query_scalar(
730            "SELECT duration_seconds FROM task_metrics WHERE task_id = ? ORDER BY completed_at DESC LIMIT 1",
731        )
732        .bind(task_id)
733        .fetch_optional(&self.pool)
734        .await
735        .ok()
736        .flatten()
737    }
738
739    /// Get count of self-improvement issues created this week.
740    /// Test-only helper that reads the KV counter.
741    #[cfg(test)]
742    pub async fn count_self_improvement_issues_7d(&self) -> anyhow::Result<i64> {
743        let key = self_improvement_key();
744        let count = self.kv_get(&key).await?;
745        Ok(count.and_then(|c| c.parse().ok()).unwrap_or(0))
746    }
747
748    /// Get tasks with high review cycle counts (persistent review loops) for a configurable window.
749    pub async fn get_high_review_cycle_tasks(
750        &self,
751        hours: u32,
752    ) -> anyhow::Result<Vec<HighReviewCycleTask>> {
753        let interval = format!("-{hours} hours");
754        let rows = sqlx::query(
755            "SELECT external_id, agent, review_cycles, title
756         FROM tasks
757         WHERE review_cycles >= 2
758           AND datetime(updated_at) >= datetime('now', ?)
759         ORDER BY review_cycles DESC
760         LIMIT 10",
761        )
762        .bind(&interval)
763        .fetch_all(&self.pool)
764        .await?;
765
766        rows.iter()
767            .map(|row| {
768                Ok(HighReviewCycleTask {
769                    // external_id and agent are nullable columns — NULL is a valid value
770                    external_id: row.try_get("external_id")?,
771                    agent: row.try_get("agent")?,
772                    review_cycles: row.try_get("review_cycles")?,
773                    title: row.try_get("title")?,
774                })
775            })
776            .collect()
777    }
778
779    /// Get tasks with high review cycle counts (persistent review loops) from the last 7 days.
780    /// Test-only wrapper.
781    #[cfg(test)]
782    pub async fn get_high_review_cycle_tasks_7d(&self) -> anyhow::Result<Vec<HighReviewCycleTask>> {
783        let rows = sqlx::query(
784            "SELECT external_id, agent, review_cycles, title
785         FROM tasks
786         WHERE review_cycles >= 2
787           AND datetime(updated_at) >= datetime('now', '-7 days')
788         ORDER BY review_cycles DESC
789         LIMIT 10",
790        )
791        .fetch_all(&self.pool)
792        .await?;
793
794        rows.iter()
795            .map(|row| {
796                Ok(HighReviewCycleTask {
797                    // external_id and agent are nullable columns — NULL is a valid value
798                    external_id: row.try_get("external_id")?,
799                    agent: row.try_get("agent")?,
800                    review_cycles: row.try_get("review_cycles")?,
801                    title: row.try_get("title")?,
802                })
803            })
804            .collect()
805    }
806
807    /// Increment the self-improvement issue counter for the current week.
808    /// Uses a single atomic SQL statement to avoid TOCTOU race conditions.
809    /// Test-only helper.
810    #[cfg(test)]
811    pub async fn increment_self_improvement_counter(&self) -> anyhow::Result<()> {
812        let key = self_improvement_key();
813        sqlx::query(
814        "INSERT INTO kv (key, value, updated_at) VALUES (?, '1', strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
815         ON CONFLICT(key) DO UPDATE SET value = CAST(value AS INTEGER) + 1, updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')",
816    )
817    .bind(&key)
818    .execute(&self.pool)
819    .await?;
820        Ok(())
821    }
822}