Skip to main content

orch/store/
helpers.rs

1//! Store helper functions used by the engine/CLI.
2//!
3//! These helpers operate on the unified SQLite task store (`TaskStore`) but accept
4//! `Option<Arc<TaskStore>>` because parts of the engine can run before the store is
5//! initialized.
6
7use crate::store::{MemoryEntry, Task, TaskStore, TokenUsage};
8use anyhow::anyhow;
9use std::sync::Arc;
10
11/// Result type for helpers that distinguish "not found" from "read error".
12pub 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
47/// Resolve a task's numeric store ID from its external identifier.
48///
49/// Returns `None` if the store is unavailable, the task is not found, or the
50/// lookup fails (with a warning logged in that case).
51pub 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
67/// Load the full `Task` record from the store.
68///
69/// Returns `None` if the store is unavailable, the task cannot be resolved,
70/// or the task row cannot be loaded.
71pub 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
85/// Load the full `Task` record from the store.
86///
87/// Returns `None` if the store is unavailable, the task cannot be resolved,
88/// or the task row cannot be loaded.
89pub 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
106/// Write fields to the task store.
107///
108/// `store` may be None if the store isn't initialized yet.
109pub 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
120/// Write fields to the task store.
121///
122/// `store` may be None if the store isn't initialized yet.
123pub 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
137/// Write fields to the task store, returning an error if the write fails.
138///
139/// Unlike `store_set`, this variant propagates failures so callers can
140/// abort further processing when a critical write (e.g. a watermark) fails.
141/// Returns `Ok(())` when `store` is `None` (store not yet initialized).
142pub 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
150/// Write fields to the task store, returning an error if the write fails.
151///
152/// Unlike `store_set`, this variant propagates failures so callers can
153/// abort further processing when a critical write (e.g. a watermark) fails.
154/// Returns `Ok(())` when `store` is `None` (store not yet initialized).
155pub 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
171/// Touch `updated_at` to now so the stuck-task timer is reset after a session exits.
172///
173/// No-op when the store is unavailable or the task cannot be resolved.
174pub 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            // Logged on success (not just failure) so a stuck-task reclaim race
184            // can be diagnosed from logs by checking whether this touch actually
185            // landed before the reclaim's own age check ran.
186            tracing::debug!(task_id, store_id, "store touch_updated_at succeeded");
187        }
188    }
189}
190
191/// Append a lifecycle activity event to a task timeline.
192#[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
226/// Increment a counter in the task store.
227///
228/// Uses `store.increment()` for an atomic SQL `field + 1`.
229/// Returns `Ok(new_value)` on success or `Err(anyhow::Error)` when the
230/// store is unavailable, the task cannot be resolved, or the underlying
231/// SQL increment failed. Callers must handle errors explicitly — this
232/// helper no longer silently returns 0 on error.
233pub 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
247/// Increment a counter in the task store.
248///
249/// Uses `store.increment()` for an atomic SQL `field + 1`.
250/// Returns `Ok(new_value)` on success or `Err(anyhow::Error)` when the
251/// store is unavailable, the task cannot be resolved, or the underlying
252/// SQL increment failed. Callers must handle errors explicitly — this
253/// helper no longer silently returns 0 on error.
254pub 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
273/// Read a specific string field from a task record.
274pub 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
289/// Read a specific string field from a task record (store always available).
290pub 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
300/// Reset all task counters in the task store.
301pub 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
310/// Reset transient failure/retry counters, preserving `review_cycles`.
311///
312/// Use this after a `RequestChanges` review decision so that per-attempt
313/// noise is cleared without undoing the cycle count set by `handle_review_changes`.
314pub 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
327/// Get token usage from the store, surfacing DB read errors.
328pub 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
341/// Get token usage from the store.
342///
343/// Returns `TokenUsage::default()` when the store is unavailable or the task is not found.
344/// DB read errors are logged as warnings and return the default.
345pub 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
360/// Get the cost the task's agents reported, surfacing DB read errors.
361pub 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
371/// Get the cost the task's agents reported.
372///
373/// Returns `None` when no run reported a cost, the store is unavailable or the task is not
374/// found. DB read errors are logged as warnings and return `None`.
375pub 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
389/// Get recent memory entries for a task, surfacing DB read errors.
390pub 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
401/// Get recent memory entries for a task.
402///
403/// Returns an empty vec when the store is unavailable or the task is not found.
404/// DB read errors are logged as warnings and return an empty vec.
405pub 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}