devist 0.17.2

Project bootstrap CLI for AI-assisted development. Spin up new projects from templates, manage backends, and keep your codebase comprehensible.
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#![allow(dead_code)]
// Supabase L2 push: batches local SQLite events into worker_events table
// via the PostgREST endpoint. Idempotent on (client_id, client_event_id).

use anyhow::{anyhow, Context, Result};
use reqwest::blocking::Client;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::worker::db::Event;

const LOCALE_CACHE_TTL: Duration = Duration::from_secs(300); // 5 min

#[derive(Debug, Clone, Deserialize)]
pub struct RuleRow {
    pub scope: String,
    pub content: String,
    pub updated_at: String,
}

#[derive(Debug, Clone)]
pub struct PendingAdvice {
    pub id: i64,
    pub text: String,
    pub paths: Vec<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct JobRow {
    pub id: i64,
    pub kind: String,
    pub scope: String,
    pub input: Value,
    #[serde(default)]
    pub output: Option<Value>,
    pub status: String,
}

pub struct SupabaseClient {
    http: Client,
    base_url: String,
    key: String,
    client_id: String,
    /// Cached (lang, fetched_at) for the most-recently-active user.
    /// None inside Option means "no preference set".
    locale_cache: Mutex<Option<(Option<String>, Instant)>>,
}

#[derive(Debug, Serialize)]
struct EventRow<'a> {
    client_id: &'a str,
    client_event_id: i64,
    project: &'a str,
    event_type: &'a str,
    path: Option<&'a str>,
    payload: Value,
    severity: &'a str,
    created_at: &'a str,
}

impl SupabaseClient {
    pub fn new(url: &str, key: &str, client_id: &str) -> Result<Self> {
        if url.is_empty() || key.is_empty() {
            return Err(anyhow!("supabase_url and supabase_key required"));
        }
        if client_id.is_empty() {
            return Err(anyhow!("client_id required"));
        }
        let http = Client::builder().timeout(Duration::from_secs(20)).build()?;
        Ok(Self {
            http,
            base_url: url.trim_end_matches('/').to_string(),
            key: key.to_string(),
            client_id: client_id.to_string(),
            locale_cache: Mutex::new(None),
        })
    }

    /// Push events to `worker_events`. Returns the count actually accepted
    /// (best-effort — Supabase returns minimal on success).
    pub fn push_events(&self, events: &[Event]) -> Result<usize> {
        if events.is_empty() {
            return Ok(0);
        }

        let rows: Vec<EventRow<'_>> = events
            .iter()
            .filter_map(|e| {
                let id = e.id?;
                let payload = serde_json::from_str::<Value>(&e.payload)
                    .unwrap_or_else(|_| Value::Object(Default::default()));
                Some(EventRow {
                    client_id: &self.client_id,
                    client_event_id: id,
                    project: &e.project,
                    event_type: &e.event_type,
                    path: e.path.as_deref(),
                    payload,
                    severity: &e.severity,
                    created_at: &e.created_at,
                })
            })
            .collect();

        if rows.is_empty() {
            return Ok(0);
        }

        let endpoint = format!("{}/rest/v1/worker_events", self.base_url);
        let resp = self
            .http
            .post(&endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .header("Content-Type", "application/json")
            .header("Prefer", "resolution=ignore-duplicates,return=minimal")
            .json(&rows)
            .send()
            .context("supabase: request failed")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(anyhow!(
                "supabase HTTP {}: {}",
                status,
                body.chars().take(400).collect::<String>()
            ));
        }
        Ok(rows.len())
    }

    /// Fetch all worker_rules rows.
    pub fn list_rules(&self) -> Result<Vec<RuleRow>> {
        let endpoint = format!(
            "{}/rest/v1/worker_rules?select=scope,content,updated_at",
            self.base_url
        );
        let resp = self
            .http
            .get(&endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .send()
            .context("supabase list_rules: request failed")?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(anyhow!(
                "list_rules HTTP {}: {}",
                status,
                body.chars().take(400).collect::<String>()
            ));
        }
        let rows: Vec<RuleRow> = resp.json().context("list_rules: parse")?;
        Ok(rows)
    }

    /// Fetch un-acked, verifiable advice rows for a project.
    /// Filters by jsonb payload->>'verifiable' = 'true'.
    pub fn list_pending_verifiable_advice(&self, project: &str) -> Result<Vec<PendingAdvice>> {
        let endpoint = format!(
            "{}/rest/v1/worker_events?project=eq.{}&event_type=eq.advice&acked_at=is.null&payload->>verifiable=eq.true&select=id,payload,created_at&order=id.asc",
            self.base_url,
            urlencoding::encode(project)
        );
        let resp = self
            .http
            .get(&endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .send()
            .context("supabase list_pending_verifiable_advice")?;
        if !resp.status().is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(anyhow!("list_pending HTTP error: {}", body));
        }
        let raw: Vec<Value> = resp.json().context("parse")?;
        let mut out = Vec::new();
        for v in raw {
            let id = v.get("id").and_then(|x| x.as_i64()).unwrap_or(0);
            let payload = v.get("payload").cloned().unwrap_or(json!({}));
            let text = payload
                .get("text")
                .and_then(|x| x.as_str())
                .unwrap_or("")
                .to_string();
            let paths: Vec<String> = payload
                .get("paths")
                .and_then(|x| x.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|p| p.as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default();
            out.push(PendingAdvice { id, text, paths });
        }
        Ok(out)
    }

    /// Mark an advice row as acked, attributing the source.
    pub fn ack_event(&self, id: i64, source: &str) -> Result<()> {
        let endpoint = format!("{}/rest/v1/worker_events?id=eq.{}", self.base_url, id);
        let resp = self
            .http
            .patch(&endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .header("Content-Type", "application/json")
            .header("Prefer", "return=minimal")
            .json(&json!({
                "acked_at": chrono::Utc::now().to_rfc3339(),
                "acked_by": source,
            }))
            .send()
            .context("supabase ack_event")?;
        if !resp.status().is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(anyhow!("ack_event HTTP error: {}", body));
        }
        Ok(())
    }

    /// Read the most-recently-active user's preferred locale from the
    /// `public.user_locale_pref` view. Cached for 5 minutes. Returns
    /// None on missing preference, missing view, or any HTTP error —
    /// the caller is expected to fall back to its config default.
    pub fn get_user_locale(&self) -> Option<String> {
        // Cache hit?
        if let Ok(guard) = self.locale_cache.lock() {
            if let Some((cached, fetched_at)) = guard.as_ref() {
                if fetched_at.elapsed() < LOCALE_CACHE_TTL {
                    return cached.clone();
                }
            }
        }

        // Cache miss — fetch.
        let endpoint = format!(
            "{}/rest/v1/user_locale_pref?select=lang&limit=1",
            self.base_url
        );
        let result: Option<String> = (|| -> Result<Option<String>> {
            let resp = self
                .http
                .get(&endpoint)
                .header("apikey", &self.key)
                .header("Authorization", format!("Bearer {}", self.key))
                .send()?;
            if !resp.status().is_success() {
                return Ok(None);
            }
            let rows: Vec<Value> = resp.json()?;
            Ok(rows
                .into_iter()
                .next()
                .and_then(|v| v.get("lang").and_then(|l| l.as_str().map(String::from))))
        })()
        .unwrap_or(None);

        if let Ok(mut guard) = self.locale_cache.lock() {
            *guard = Some((result.clone(), Instant::now()));
        }
        result
    }

    /// Upsert a heartbeat row for (client_id, thread). Idempotent.
    pub fn heartbeat(&self, thread: &str) -> Result<()> {
        let endpoint = format!("{}/rest/v1/worker_heartbeat", self.base_url);
        let body = json!([{
            "client_id": self.client_id,
            "thread": thread,
            "last_beat_at": chrono::Utc::now().to_rfc3339(),
        }]);
        let resp = self
            .http
            .post(&endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .header("Content-Type", "application/json")
            .header("Prefer", "resolution=merge-duplicates,return=minimal")
            .json(&body)
            .send()
            .context("supabase heartbeat: request failed")?;
        if !resp.status().is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(anyhow!("heartbeat HTTP error: {}", body));
        }
        Ok(())
    }

    /// Atomically claim the next pending job for this client.
    /// Returns None if no pending job exists.
    pub fn claim_next_pending_job(&self) -> Result<Option<JobRow>> {
        // 1. Find the oldest pending job
        let pending_endpoint = format!(
            "{}/rest/v1/worker_jobs?status=eq.pending&order=created_at.asc&limit=1&select=*",
            self.base_url
        );
        let pending_resp = self
            .http
            .get(&pending_endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .send()
            .context("supabase claim_next: list request failed")?;
        if !pending_resp.status().is_success() {
            let body = pending_resp.text().unwrap_or_default();
            return Err(anyhow!("claim_next list HTTP error: {}", body));
        }
        let pending_rows: Vec<JobRow> = pending_resp.json().context("claim_next: parse")?;
        let candidate = match pending_rows.into_iter().next() {
            Some(r) => r,
            None => return Ok(None),
        };

        // 2. UPDATE WHERE id=X AND status='pending' to claim it.
        // Returns the updated row(s); if another client already claimed,
        // we get an empty array.
        let claim_endpoint = format!(
            "{}/rest/v1/worker_jobs?id=eq.{}&status=eq.pending",
            self.base_url, candidate.id
        );
        let claim_resp = self
            .http
            .patch(&claim_endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .header("Content-Type", "application/json")
            .header("Prefer", "return=representation")
            .json(&json!({
                "status": "running",
                "client_id": self.client_id,
            }))
            .send()
            .context("supabase claim_next: claim request failed")?;
        if !claim_resp.status().is_success() {
            let body = claim_resp.text().unwrap_or_default();
            return Err(anyhow!("claim_next claim HTTP error: {}", body));
        }
        let claimed: Vec<JobRow> = claim_resp.json().context("claim_next: parse claim")?;
        Ok(claimed.into_iter().next())
    }

    /// Mark a job done with an output payload.
    pub fn complete_job(&self, id: i64, output: Value) -> Result<()> {
        self.update_job(
            id,
            json!({ "status": "done", "output": output, "error": null }),
        )
    }

    /// Mark a job errored.
    pub fn fail_job(&self, id: i64, error: &str) -> Result<()> {
        self.update_job(id, json!({ "status": "error", "error": error }))
    }

    fn update_job(&self, id: i64, body: Value) -> Result<()> {
        let endpoint = format!("{}/rest/v1/worker_jobs?id=eq.{}", self.base_url, id);
        let resp = self
            .http
            .patch(&endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .header("Content-Type", "application/json")
            .header("Prefer", "return=minimal")
            .json(&body)
            .send()
            .context("supabase update_job: request failed")?;
        if !resp.status().is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(anyhow!("update_job HTTP error: {}", body));
        }
        Ok(())
    }

    /// Get a single rule's content by scope (returns None if missing).
    pub fn get_rule(&self, scope: &str) -> Result<Option<String>> {
        let endpoint = format!(
            "{}/rest/v1/worker_rules?scope=eq.{}&select=content",
            self.base_url, scope
        );
        let resp = self
            .http
            .get(&endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .send()
            .context("supabase get_rule: request failed")?;
        if !resp.status().is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(anyhow!("get_rule HTTP error: {}", body));
        }
        let rows: Vec<Value> = resp.json().context("get_rule: parse")?;
        Ok(rows
            .into_iter()
            .next()
            .and_then(|v| v.get("content").and_then(|c| c.as_str().map(String::from))))
    }

    /// Upsert a single worker_rules row by scope.
    pub fn upsert_rule(&self, scope: &str, content: &str) -> Result<()> {
        let endpoint = format!("{}/rest/v1/worker_rules", self.base_url);
        let body = json!([{ "scope": scope, "content": content }]);
        let resp = self
            .http
            .post(&endpoint)
            .header("apikey", &self.key)
            .header("Authorization", format!("Bearer {}", self.key))
            .header("Content-Type", "application/json")
            .header("Prefer", "resolution=merge-duplicates,return=minimal")
            .json(&body)
            .send()
            .context("supabase upsert_rule: request failed")?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().unwrap_or_default();
            return Err(anyhow!(
                "upsert_rule HTTP {}: {}",
                status,
                body.chars().take(400).collect::<String>()
            ));
        }
        Ok(())
    }
}