1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
use crate::db::Pool;
use crate::db::database::interact_err;
use crate::db::models::CronJobRun;
use anyhow::{Context, Result};
use rusqlite::params;
#[derive(Clone)]
pub struct CronJobRunRepository {
pool: Pool,
}
impl CronJobRunRepository {
pub fn new(pool: Pool) -> Self {
Self { pool }
}
/// Insert a new run record (status = "running").
pub async fn insert(&self, run: &CronJobRun) -> Result<()> {
let r = run.clone();
self.pool
.get()
.await
.context("Failed to get connection")?
.interact(move |conn| {
conn.execute(
"INSERT INTO cron_job_runs (id, job_id, job_name, status, content, error, input_tokens, output_tokens, cost, provider, model, started_at, completed_at, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
params![
r.id.to_string(),
r.job_id.to_string(),
r.job_name,
r.status,
r.content,
r.error,
r.input_tokens,
r.output_tokens,
r.cost,
r.provider,
r.model,
r.started_at.to_rfc3339(),
r.completed_at.map(|d: chrono::DateTime<chrono::Utc>| d.to_rfc3339()),
r.created_at.to_rfc3339(),
],
)
})
.await
.map_err(interact_err)?
.context("Failed to insert cron job run")?;
Ok(())
}
/// Mark a run as completed with success.
pub async fn complete_success(
&self,
run_id: &str,
content: &str,
input_tokens: i64,
output_tokens: i64,
cost: f64,
) -> Result<()> {
let id = run_id.to_string();
let content = content.to_string();
self.pool
.get()
.await
.context("Failed to get connection")?
.interact(move |conn| {
conn.execute(
"UPDATE cron_job_runs SET status = 'success', content = ?1, input_tokens = ?2, output_tokens = ?3, cost = ?4, completed_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = ?5",
params![content, input_tokens, output_tokens, cost, id],
)
})
.await
.map_err(interact_err)?
.context("Failed to update cron job run")?;
Ok(())
}
/// Mark a run as failed with error.
///
/// Every status this table ever holds, and the single writer of each:
/// - `running`: set by [`Self::insert`] when the run starts
/// - `success`: set by [`Self::complete_success`] when execution finished
/// with its report delivered. The agent-turn path only earns it with
/// execution evidence (#1703); direct-trigger runs use it without tools
/// by design.
/// - `no_op`: set by [`Self::complete_no_op`] when the turn completed but
/// executed zero tools; the ledger refuses to vouch for it
/// - `error`: set here, when execution failed
/// - `interrupted`: set by `doctor --fix`, for an aged `running` row whose
/// process is gone, so a watchdog sweep is never mistaken for a failure
///
/// Delivery outcome is deliberately absent: the scheduler discards the
/// result of `deliver_result` at both call sites, so a run whose execution
/// succeeded and whose delivery failed is still stored as `success`. Do not
/// document a `delivery_failed` status until something writes one.
pub async fn complete_error(&self, run_id: &str, error: &str) -> Result<()> {
let id = run_id.to_string();
let error = error.to_string();
self.pool
.get()
.await
.context("Failed to get connection")?
.interact(move |conn| {
conn.execute(
"UPDATE cron_job_runs SET status = 'error', error = ?1, completed_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = ?2",
params![error, id],
)
})
.await
.map_err(interact_err)?
.context("Failed to update cron job run error")?;
Ok(())
}
/// Mark a run as completed without execution evidence (#1703). The agent
/// turn returned normally but started zero tools, so its report cannot be
/// told apart from a stale-context replay: the produced content stays in
/// the row for forensics and the tokens/cost are recorded (they were
/// really spent), yet the status is deliberately not `success`.
pub async fn complete_no_op(
&self,
run_id: &str,
content: &str,
input_tokens: i64,
output_tokens: i64,
cost: f64,
) -> Result<()> {
let id = run_id.to_string();
let content = content.to_string();
self.pool
.get()
.await
.context("Failed to get connection")?
.interact(move |conn| {
conn.execute(
"UPDATE cron_job_runs SET status = 'no_op', content = ?1, input_tokens = ?2, output_tokens = ?3, cost = ?4, completed_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = ?5",
params![content, input_tokens, output_tokens, cost, id],
)
})
.await
.map_err(interact_err)?
.context("Failed to update cron job run no-op")?;
Ok(())
}
/// List recent runs for a specific job (most recent first).
pub async fn list_by_job(&self, job_id: &str, limit: i64) -> Result<Vec<CronJobRun>> {
let job_id = job_id.to_string();
self.pool
.get()
.await
.context("Failed to get connection")?
.interact(move |conn| -> rusqlite::Result<Vec<CronJobRun>> {
let mut stmt = conn.prepare_cached(
"SELECT * FROM cron_job_runs WHERE job_id = ?1 ORDER BY started_at DESC LIMIT ?2",
)?;
let rows = stmt.query_map(params![job_id, limit], CronJobRun::from_row)?;
rows.collect()
})
.await
.map_err(interact_err)?
.context("Failed to list cron job runs")
}
/// List all recent runs across all jobs.
pub async fn list_recent(&self, limit: i64) -> Result<Vec<CronJobRun>> {
self.pool
.get()
.await
.context("Failed to get connection")?
.interact(move |conn| -> rusqlite::Result<Vec<CronJobRun>> {
let mut stmt = conn.prepare_cached(
"SELECT * FROM cron_job_runs ORDER BY started_at DESC LIMIT ?1",
)?;
let rows = stmt.query_map(params![limit], CronJobRun::from_row)?;
rows.collect()
})
.await
.map_err(interact_err)?
.context("Failed to list recent cron job runs")
}
}