1use crate::store::{MemoryEntry, Task, TaskStore, TokenUsage};
8use anyhow::anyhow;
9use std::sync::Arc;
10
11pub type StoreResult<T> = anyhow::Result<Option<T>>;
13
14fn token_i64_to_u64_non_negative(tokens: i64) -> u64 {
15 u64::try_from(tokens.max(0)).unwrap_or(0)
16}
17
18async fn resolved_store<'a>(
19 store: Option<&'a Arc<TaskStore>>,
20 repo: &str,
21 task_id: &str,
22) -> Option<(&'a TaskStore, i64)> {
23 let s = store?;
24 match s.resolve_task_id(repo, task_id).await {
25 Ok(Some(id)) => Some((s.as_ref(), id)),
26 Ok(None) => None,
27 Err(e) => {
28 tracing::warn!(task_id, error = %e, "resolve_task_id failed in store write helper");
29 None
30 }
31 }
32}
33
34async fn require_resolved<'a>(
35 store: Option<&'a Arc<TaskStore>>,
36 repo: &str,
37 task_id: &str,
38) -> anyhow::Result<(&'a TaskStore, i64)> {
39 let s = store.ok_or_else(|| anyhow!("task store unavailable"))?;
40 let store_id = s
41 .resolve_task_id(repo, task_id)
42 .await?
43 .ok_or_else(|| anyhow!("task {repo}/{task_id} not found in store"))?;
44 Ok((s.as_ref(), store_id))
45}
46
47pub async fn resolve_store_id(
52 store: &Option<Arc<TaskStore>>,
53 repo: &str,
54 task_id: &str,
55) -> Option<i64> {
56 let s = store.as_ref()?;
57 match s.resolve_task_id(repo, task_id).await {
58 Ok(Some(id)) => Some(id),
59 Ok(None) => None,
60 Err(e) => {
61 tracing::warn!(task_id, error = %e, "failed to resolve task id for store operations");
62 None
63 }
64 }
65}
66
67pub async fn opt_store_get_task_by_id(
72 store: &Option<Arc<TaskStore>>,
73 store_id: i64,
74) -> Option<Task> {
75 let s = store.as_ref()?;
76 match s.get(store_id).await {
77 Ok(task) => Some(task),
78 Err(e) => {
79 tracing::warn!(store_id, error = %e, "failed to fetch task from store");
80 None
81 }
82 }
83}
84
85pub async fn opt_store_get_task(
90 store: &Option<Arc<TaskStore>>,
91 repo: &str,
92 task_id: &str,
93) -> Option<Task> {
94 let s = store.as_ref()?;
95 let store_id = match s.resolve_task_id(repo, task_id).await {
96 Ok(Some(id)) => id,
97 Ok(None) => return None,
98 Err(e) => {
99 tracing::warn!(task_id, error = %e, "failed to resolve task id in store");
100 return None;
101 }
102 };
103 opt_store_get_task_by_id(store, store_id).await
104}
105
106pub async fn store_set_by_id(
110 store: Option<&Arc<TaskStore>>,
111 store_id: i64,
112 store_fields: &[(&str, serde_json::Value)],
113) -> anyhow::Result<()> {
114 if let Some(store) = store {
115 store.set_fields(store_id, store_fields).await?;
116 }
117 Ok(())
118}
119
120pub async fn store_set(
124 store: &Option<Arc<TaskStore>>,
125 repo: &str,
126 task_id: &str,
127 store_fields: &[(&str, serde_json::Value)],
128) {
129 let Some((store, store_id)) = resolved_store(store.as_ref(), repo, task_id).await else {
130 return;
131 };
132 if let Err(e) = store.set_fields(store_id, store_fields).await {
133 tracing::warn!(task_id, error = %e, "store set_fields failed");
134 }
135}
136
137pub async fn store_set_result_by_id(
143 store: &Option<Arc<TaskStore>>,
144 store_id: i64,
145 store_fields: &[(&str, serde_json::Value)],
146) -> anyhow::Result<()> {
147 store_set_by_id(store.as_ref(), store_id, store_fields).await
148}
149
150pub async fn store_set_result(
156 store: &Option<Arc<TaskStore>>,
157 repo: &str,
158 task_id: &str,
159 store_fields: &[(&str, serde_json::Value)],
160) -> anyhow::Result<()> {
161 if let Some(store) = store {
162 let store_id = store
163 .resolve_task_id(repo, task_id)
164 .await?
165 .ok_or_else(|| anyhow::anyhow!("task {task_id} not found in store"))?;
166 store.set_fields(store_id, store_fields).await?;
167 }
168 Ok(())
169}
170
171pub async fn store_touch_updated_at(store: &Option<Arc<TaskStore>>, repo: &str, task_id: &str) {
175 let Some((store, store_id)) = resolved_store(store.as_ref(), repo, task_id).await else {
176 return;
177 };
178 match store.touch_updated_at(store_id).await {
179 Err(e) => {
180 tracing::warn!(task_id, error = %e, "store touch_updated_at failed");
181 }
182 _ => {
183 tracing::debug!(task_id, store_id, "store touch_updated_at succeeded");
187 }
188 }
189}
190
191#[expect(
193 clippy::too_many_arguments,
194 reason = "the arguments are the activity row columns"
195)]
196pub async fn store_log_activity(
197 store: &Option<Arc<TaskStore>>,
198 repo: &str,
199 task_id: &str,
200 event_type: &str,
201 from_status: Option<&str>,
202 to_status: Option<&str>,
203 agent: Option<&str>,
204 model: Option<&str>,
205 details: Option<&serde_json::Value>,
206) {
207 let Some((store, store_id)) = resolved_store(store.as_ref(), repo, task_id).await else {
208 return;
209 };
210 if let Err(e) = store
211 .append_activity(
212 store_id,
213 event_type,
214 from_status,
215 to_status,
216 agent,
217 model,
218 details,
219 )
220 .await
221 {
222 tracing::warn!(task_id, event_type, error = %e, "store append_activity failed");
223 }
224}
225
226pub async fn store_increment_by_id(
234 store: &Option<Arc<TaskStore>>,
235 store_id: i64,
236 field: &str,
237) -> anyhow::Result<u64> {
238 let s = store
239 .as_ref()
240 .ok_or_else(|| anyhow!("task store unavailable"))?;
241 match s.increment(store_id, field).await {
242 Ok(new_val) => Ok(u64::try_from(new_val).unwrap_or(0)),
243 Err(e) => Err(anyhow!("store.increment failed: {e}")),
244 }
245}
246
247pub async fn store_increment(
255 store: &Option<Arc<TaskStore>>,
256 repo: &str,
257 task_id: &str,
258 field: &str,
259) -> anyhow::Result<u64> {
260 let s = store
261 .as_ref()
262 .ok_or_else(|| anyhow!("task store unavailable"))?;
263 match s.resolve_task_id(repo, task_id).await {
264 Ok(Some(store_id)) => store_increment_by_id(store, store_id, field).await,
265 Ok(None) => Err(anyhow!("task not present in store: {repo}/{task_id}")),
266 Err(e) => {
267 tracing::warn!(task_id, error = %e, "resolve_task_id failed in store write helper");
268 Err(anyhow!("resolve_task_id failed: {e}"))
269 }
270 }
271}
272
273pub async fn get_task_field(
275 store: &Option<Arc<TaskStore>>,
276 repo: &str,
277 task_id: &str,
278 field: &str,
279) -> Option<String> {
280 let task = opt_store_get_task(store, repo, task_id).await?;
281 if field == "no_code_last_agent" {
282 Some(task.no_code_last_agent)
283 } else {
284 tracing::warn!(task_id, field, "get_task_field: unknown field");
285 None
286 }
287}
288
289pub async fn get_task_field_direct(
291 store: &Arc<TaskStore>,
292 repo: &str,
293 task_id: &str,
294 field: &str,
295) -> Option<String> {
296 let store_opt: &Option<Arc<TaskStore>> = &Some(Arc::clone(store));
297 get_task_field(store_opt, repo, task_id, field).await
298}
299
300pub async fn store_reset_counters(store: &Option<Arc<TaskStore>>, repo: &str, task_id: &str) {
302 let Some((store, store_id)) = resolved_store(store.as_ref(), repo, task_id).await else {
303 return;
304 };
305 if let Err(e) = store.reset_counters(store_id).await {
306 tracing::warn!(task_id, err = %e, "store reset_counters failed");
307 }
308}
309
310pub async fn store_reset_failure_counters(
315 store: &Option<Arc<TaskStore>>,
316 repo: &str,
317 task_id: &str,
318) {
319 let Some((store, store_id)) = resolved_store(store.as_ref(), repo, task_id).await else {
320 return;
321 };
322 if let Err(e) = store.reset_failure_counters(store_id).await {
323 tracing::warn!(task_id, err = %e, "failed to reset failure counters after review dispatch");
324 }
325}
326
327pub async fn get_token_usage_result(
329 store: &Option<Arc<TaskStore>>,
330 repo: &str,
331 task_id: &str,
332) -> StoreResult<TokenUsage> {
333 let (s, store_id) = require_resolved(store.as_ref(), repo, task_id).await?;
334 let task = s.get(store_id).await?;
335 Ok(Some(TokenUsage {
336 input_tokens: token_i64_to_u64_non_negative(task.input_tokens),
337 output_tokens: token_i64_to_u64_non_negative(task.output_tokens),
338 }))
339}
340
341pub async fn get_token_usage(
346 store: &Option<Arc<TaskStore>>,
347 repo: &str,
348 task_id: &str,
349) -> TokenUsage {
350 match get_token_usage_result(store, repo, task_id).await {
351 Ok(Some(usage)) => usage,
352 Ok(None) => TokenUsage::default(),
353 Err(e) => {
354 tracing::warn!(task_id, error = %e, "get_token_usage failed — returning zero usage");
355 TokenUsage::default()
356 }
357 }
358}
359
360pub async fn get_reported_cost_result(
362 store: &Option<Arc<TaskStore>>,
363 repo: &str,
364 task_id: &str,
365) -> StoreResult<f64> {
366 let (s, store_id) = require_resolved(store.as_ref(), repo, task_id).await?;
367 let task = s.get(store_id).await?;
368 Ok(task.reported_cost_usd())
369}
370
371pub async fn get_reported_cost(
376 store: &Option<Arc<TaskStore>>,
377 repo: &str,
378 task_id: &str,
379) -> Option<f64> {
380 match get_reported_cost_result(store, repo, task_id).await {
381 Ok(cost) => cost,
382 Err(e) => {
383 tracing::warn!(task_id, error = %e, "get_reported_cost failed — returning no cost");
384 None
385 }
386 }
387}
388
389pub async fn get_recent_memory_result(
391 store: &Option<Arc<TaskStore>>,
392 repo: &str,
393 task_id: &str,
394 max: usize,
395) -> StoreResult<Vec<MemoryEntry>> {
396 let (s, store_id) = require_resolved(store.as_ref(), repo, task_id).await?;
397 let entries = s.recent_memory(store_id, max).await?;
398 Ok(Some(entries))
399}
400
401pub async fn get_recent_memory(
406 store: &Option<Arc<TaskStore>>,
407 repo: &str,
408 task_id: &str,
409 max: usize,
410) -> Vec<MemoryEntry> {
411 match get_recent_memory_result(store, repo, task_id, max).await {
412 Ok(Some(entries)) => entries,
413 Ok(None) => Vec::new(),
414 Err(e) => {
415 tracing::warn!(task_id, error = %e, "get_recent_memory failed — returning empty memory");
416 Vec::new()
417 }
418 }
419}