1#[cfg(test)]
4use super::{ALLOWED_FIELDS, TASK_COLS, Task, sql_value_for_task_field};
5use super::{
6 INCREMENTABLE_FIELDS, StoreRoute, StoreRouteCmd, apply, is_local_column, owned_updates,
7};
8use crate::store::Command;
9use crate::store::TaskStore;
10use crate::store::now_stamp;
11use sqlx::Row;
12use std::collections::HashSet;
13
14impl TaskStore {
15 pub async fn set_fields(
18 &self,
19 id: i64,
20 updates: &[(&str, serde_json::Value)],
21 ) -> anyhow::Result<()> {
22 self.set_fields_split(id, updates, false).await
23 }
24
25 pub async fn set_fields_silent(
30 &self,
31 id: i64,
32 updates: &[(&str, serde_json::Value)],
33 ) -> anyhow::Result<()> {
34 self.set_fields_split(id, updates, true).await
35 }
36
37 async fn set_fields_split(
39 &self,
40 id: i64,
41 updates: &[(&str, serde_json::Value)],
42 silent: bool,
43 ) -> anyhow::Result<()> {
44 let all = owned_updates(updates)?;
45 if !self.replicates() {
47 let mut tx = self.begin_write().await?;
48 apply::set_fields(&mut tx, &now_stamp(), id, &all, silent).await?;
49 tx.commit().await?;
50 return Ok(());
51 }
52
53 let (local, replicated): (Vec<_>, Vec<_>) =
54 all.into_iter().partition(|(col, _)| is_local_column(col));
55 if !local.is_empty() {
56 let mut tx = self.begin_write().await?;
57 apply::set_fields(&mut tx, &now_stamp(), id, &local, silent).await?;
58 tx.commit().await?;
59 }
60
61 if replicated.is_empty() {
62 return Ok(());
63 }
64
65 self.write(Command::TaskSetFields {
66 id,
67 updates: replicated,
68 silent,
69 })
70 .await
71 .map(|_| ())
72 }
73
74 pub async fn increment(&self, id: i64, field: &str) -> anyhow::Result<i32> {
76 anyhow::ensure!(
77 INCREMENTABLE_FIELDS.contains(&field),
78 "field {field} is not incrementable"
79 );
80 let n = self
81 .write_int(Command::TaskIncrement {
82 id,
83 field: field.to_string(),
84 })
85 .await?;
86 Ok(i32::try_from(n)?)
87 }
88
89 pub async fn reset_counters(&self, id: i64) -> anyhow::Result<()> {
91 self.write(Command::TaskResetCounters {
92 id,
93 failure_only: false,
94 })
95 .await
96 .map(|_| ())
97 }
98
99 pub async fn reset_failure_counters(&self, id: i64) -> anyhow::Result<()> {
114 self.write(Command::TaskResetCounters {
115 id,
116 failure_only: true,
117 })
118 .await
119 .map(|_| ())
120 }
121
122 pub async fn store_route(&self, route: &StoreRoute<'_>) -> anyhow::Result<()> {
124 self.write(Command::TaskStoreRoute(StoreRouteCmd {
125 id: route.id,
126 agent: route.agent.to_string(),
127 model: route.model.map(str::to_string),
128 complexity: route.complexity.to_string(),
129 estimate: route.estimate,
130 reason: route.reason.to_string(),
131 profile: route.profile.to_string(),
132 }))
133 .await
134 .map(|_| ())
135 }
136
137 pub async fn list_external_tasks_with_estimates(&self) -> anyhow::Result<Vec<(String, u8)>> {
145 let rows = sqlx::query(
146 "SELECT external_id, estimate FROM tasks \
147 WHERE estimate > 0 AND external_id NOT LIKE 'internal:%' \
148 AND status NOT IN ('done', 'blocked')",
149 )
150 .fetch_all(&self.pool)
151 .await?;
152
153 let mut result = Vec::new();
154 for row in &rows {
155 let external_id: String = row.try_get("external_id")?;
156 let estimate_raw: i64 = row.try_get("estimate")?;
157 if let Ok(estimate @ 1..) = u8::try_from(estimate_raw) {
158 result.push((external_id, estimate));
159 }
160 }
161 Ok(result)
162 }
163
164 pub async fn set_estimate_if_zero(&self, id: i64, estimate: u8) -> anyhow::Result<bool> {
170 self.write_bool(Command::TaskSetEstimateIfZero { id, estimate })
171 .await
172 }
173
174 pub async fn mark_cleaned(&self, id: i64) -> anyhow::Result<()> {
176 self.write(Command::TaskMarkCleaned { id })
177 .await
178 .map(|_| ())
179 }
180
181 #[cfg(test)]
187 pub async fn batch_set_fields(
188 &self,
189 updates: &[(i64, &[(&str, serde_json::Value)])],
190 ) -> anyhow::Result<()> {
191 if updates.is_empty() {
192 return Ok(());
193 }
194
195 for (_, entry_updates) in updates {
196 for (col, _) in *entry_updates {
197 anyhow::ensure!(
198 ALLOWED_FIELDS.contains(col),
199 "column {col} is not in the update allowlist"
200 );
201 }
202 }
203
204 let mut tx = self.begin_write().await?;
205 for (id, entry_updates) in updates {
206 if entry_updates.is_empty() {
207 continue;
208 }
209 let mut set_parts = Vec::new();
210 let mut values: Vec<Option<String>> = Vec::new();
211 for (col, val) in *entry_updates {
212 set_parts.push(format!("{col} = ?"));
213 values.push(sql_value_for_task_field(col, val)?);
214 }
215 set_parts.push("updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')".to_string());
216 let sql = format!("UPDATE tasks SET {} WHERE id = ?", set_parts.join(", "));
217 let mut query = sqlx::query(sqlx::AssertSqlSafe(sql.as_str()));
218 for v in &values {
219 query = query.bind(v.as_deref());
220 }
221 query = query.bind(*id);
222 query.execute(&mut *tx).await?;
223 }
224 tx.commit().await?;
225 Ok(())
226 }
227
228 #[cfg(test)]
233 pub async fn batch_increment(&self, entries: &[(i64, &str)]) -> anyhow::Result<()> {
234 if entries.is_empty() {
235 return Ok(());
236 }
237
238 for (_, field) in entries {
239 anyhow::ensure!(
240 INCREMENTABLE_FIELDS.contains(field),
241 "field {field} is not incrementable"
242 );
243 }
244
245 let mut tx = self.begin_write().await?;
246 for (id, field) in entries {
247 let sql = format!(
248 "UPDATE tasks SET {field} = {field} + 1, updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = ?"
249 );
250 sqlx::query(sqlx::AssertSqlSafe(sql.as_str()))
251 .bind(*id)
252 .execute(&mut *tx)
253 .await?;
254 }
255 tx.commit().await?;
256 Ok(())
257 }
258
259 #[cfg(test)]
266 pub async fn batch_reset_failure_counters(&self, ids: &[i64]) -> anyhow::Result<()> {
267 const CHUNK_SIZE: usize = 500;
270 if ids.is_empty() {
271 return Ok(());
272 }
273
274 let mut tx = self.begin_write().await?;
275
276 for chunk in ids.chunks(CHUNK_SIZE) {
277 let placeholders = chunk.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
279 let sql = format!(
280 "UPDATE tasks SET
281 route_attempts = 0,
282 review_agent_failures = 0,
283 review_resets = 0,
284 review_invocations = 0,
285 pr_create_failures = 0,
286 push_failures = 0,
287 network_retries = 0,
288 timeout_retries = 0,
289 auto_unblock_count = 0,
290 auto_unblock_last_at = '',
291 auto_unblock_last_reason = '',
292 ci_recovery_count = 0,
293 no_code_reroutes = 0,
294 needs_review_refires = 0,
295 updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
296 WHERE id IN ({placeholders})",
297 );
298 let mut query = sqlx::query(sqlx::AssertSqlSafe(sql.as_str()));
299 for id in chunk {
300 query = query.bind(*id);
301 }
302 query.execute(&mut *tx).await?;
303 }
304
305 tx.commit().await?;
306 Ok(())
307 }
308
309 #[cfg(test)]
314 pub async fn batch_mark_cleaned(&self, ids: &[i64]) -> anyhow::Result<()> {
315 const CHUNK_SIZE: usize = 500;
317 if ids.is_empty() {
318 return Ok(());
319 }
320
321 let mut tx = self.begin_write().await?;
322
323 for chunk in ids.chunks(CHUNK_SIZE) {
324 let placeholders = chunk.iter().map(|_| "?").collect::<Vec<_>>().join(", ");
325 let sql = format!(
326 "UPDATE tasks SET worktree_cleaned = 1, updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id IN ({placeholders})",
327 );
328 let mut query = sqlx::query(sqlx::AssertSqlSafe(sql.as_str()));
329 for id in chunk {
330 query = query.bind(*id);
331 }
332 query.execute(&mut *tx).await?;
333 }
334
335 let details = serde_json::json!({ "worktree_cleaned": true });
339 let details_json = serde_json::to_string(&details)?;
340 for id in ids {
341 sqlx::query(
342 "INSERT INTO task_activity (task_id, event_type, from_status, to_status, agent, model, details) VALUES (?, ?, ?, ?, ?, ?, ?)",
343 )
344 .bind(*id)
345 .bind("branch_delete")
346 .bind(None::<&str>)
347 .bind(None::<&str>)
348 .bind(None::<&str>)
349 .bind(None::<&str>)
350 .bind(details_json.as_str())
351 .execute(&mut *tx)
352 .await?;
353 }
354
355 tx.commit().await?;
356 Ok(())
357 }
358
359 #[cfg(test)]
362 pub async fn list_cleanable(&self, repo: &str) -> anyhow::Result<Vec<Task>> {
363 let rows = sqlx::query(sqlx::AssertSqlSafe(format!(
364 "SELECT {TASK_COLS} FROM tasks
365 WHERE repo = ?
366 AND worktree != ''
367 AND worktree_cleaned = 0
368 AND status IN ('done', 'blocked')
369 ORDER BY updated_at ASC"
370 )))
371 .bind(repo)
372 .fetch_all(&self.pool)
373 .await?;
374
375 rows.iter().map(Self::row_to_task).collect()
376 }
377
378 pub async fn cleaned_external_ids(&self, repo: &str) -> anyhow::Result<HashSet<String>> {
383 let rows: Vec<(String,)> =
384 sqlx::query_as("SELECT external_id FROM tasks WHERE repo = ? AND worktree_cleaned = 1 AND external_id IS NOT NULL")
385 .bind(repo)
386 .fetch_all(&self.pool)
387 .await?;
388
389 Ok(rows.into_iter().map(|(id,)| id).collect())
390 }
391}