Skip to main content

beads_rs/daemon/
query.rs

1//! Query types and filters.
2//!
3//! Provides:
4//! - `Query` - All query operations
5//! - `Filters` - Filtering criteria for list queries
6//! - `QueryResult` - Query results
7
8use std::path::PathBuf;
9
10use serde::{Deserialize, Serialize};
11
12use crate::api::{
13    BlockedIssue as ApiBlockedIssue, CountResult as ApiCountResult, DaemonInfo as ApiDaemonInfo,
14    DeletedLookup as ApiDeletedLookup, DepEdge as ApiDepEdge, EpicStatus as ApiEpicStatus, Issue,
15    IssueSummary, Note as ApiNote, ReadyResult as ApiReadyResult, StatusOutput as ApiStatusOutput,
16    Tombstone as ApiTombstone,
17};
18use crate::core::{ActorId, Bead, BeadId, BeadType, Claim, Priority};
19
20// =============================================================================
21// Filters - Filtering criteria
22// =============================================================================
23
24/// Filters for list queries.
25#[derive(Debug, Clone, Default, Serialize, Deserialize)]
26pub struct Filters {
27    /// Filter by status (open, in_progress, closed).
28    #[serde(default)]
29    pub status: Option<String>,
30
31    /// Filter by priority.
32    #[serde(default)]
33    pub priority: Option<Priority>,
34
35    /// Filter by minimum priority (inclusive).
36    #[serde(default)]
37    pub priority_min: Option<Priority>,
38
39    /// Filter by maximum priority (inclusive).
40    #[serde(default)]
41    pub priority_max: Option<Priority>,
42
43    /// Filter by bead type.
44    #[serde(default, rename = "type")]
45    pub bead_type: Option<BeadType>,
46
47    /// Filter by assignee.
48    #[serde(default)]
49    pub assignee: Option<ActorId>,
50
51    /// Filter by labels (AND: must have ALL).
52    #[serde(default)]
53    pub labels: Option<Vec<String>>,
54
55    /// Filter by labels (OR: must have AT LEAST ONE).
56    #[serde(default)]
57    pub labels_any: Option<Vec<String>>,
58
59    /// Filter by specific issue IDs.
60    #[serde(default)]
61    pub ids: Option<Vec<BeadId>>,
62
63    /// Filter by title text (case-insensitive substring match).
64    #[serde(default)]
65    pub title: Option<String>,
66
67    /// Pattern matching: title contains substring.
68    #[serde(default)]
69    pub title_contains: Option<String>,
70
71    /// Pattern matching: description contains substring.
72    #[serde(default)]
73    pub desc_contains: Option<String>,
74
75    /// Pattern matching: notes contains substring.
76    #[serde(default)]
77    pub notes_contains: Option<String>,
78
79    /// Date ranges: created after/before (ms since epoch).
80    #[serde(default)]
81    pub created_after: Option<u64>,
82    #[serde(default)]
83    pub created_before: Option<u64>,
84    #[serde(default)]
85    pub updated_after: Option<u64>,
86    #[serde(default)]
87    pub updated_before: Option<u64>,
88    #[serde(default)]
89    pub closed_after: Option<u64>,
90    #[serde(default)]
91    pub closed_before: Option<u64>,
92
93    /// Filter issues with empty description.
94    #[serde(default)]
95    pub empty_description: bool,
96
97    /// Filter issues with no assignee.
98    #[serde(default)]
99    pub no_assignee: bool,
100
101    /// Filter issues with no labels.
102    #[serde(default)]
103    pub no_labels: bool,
104
105    /// Filter to only show unclaimed beads.
106    #[serde(default)]
107    pub unclaimed: bool,
108
109    /// Text search in title/description.
110    #[serde(default)]
111    pub search: Option<String>,
112
113    /// Limit number of results.
114    #[serde(default)]
115    pub limit: Option<usize>,
116
117    /// Sort field.
118    #[serde(default)]
119    pub sort_by: Option<SortField>,
120
121    /// Sort direction (default: descending).
122    #[serde(default)]
123    pub ascending: bool,
124
125    /// Filter by parent epic ID (only show children).
126    #[serde(default)]
127    pub parent: Option<BeadId>,
128}
129
130/// Fields to sort by.
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
132#[serde(rename_all = "snake_case")]
133pub enum SortField {
134    Priority,
135    CreatedAt,
136    UpdatedAt,
137    Title,
138}
139
140impl Filters {
141    /// Check if a bead matches these filters.
142    pub fn matches(&self, bead: &Bead) -> bool {
143        // Status filter
144        if let Some(ref status) = self.status {
145            // NOTE: "blocked" is derived and handled by higher-level queries when needed.
146            if status != "all"
147                && status != "blocked"
148                && bead.fields.workflow.value.status() != status
149            {
150                return false;
151            }
152        }
153
154        // Priority filter
155        if let Some(priority) = self.priority
156            && bead.fields.priority.value != priority
157        {
158            return false;
159        }
160
161        if let Some(min) = self.priority_min
162            && bead.fields.priority.value < min
163        {
164            return false;
165        }
166        if let Some(max) = self.priority_max
167            && bead.fields.priority.value > max
168        {
169            return false;
170        }
171
172        // Type filter
173        if let Some(bead_type) = self.bead_type
174            && bead.fields.bead_type.value != bead_type
175        {
176            return false;
177        }
178
179        // Assignee filter
180        if let Some(ref assignee) = self.assignee {
181            match &bead.fields.claim.value {
182                Claim::Claimed { assignee: a, .. } if a == assignee => {}
183                _ => return false,
184            }
185        }
186
187        if self.no_assignee && bead.fields.claim.value.is_claimed() {
188            return false;
189        }
190
191        // Labels filter (AND)
192        if let Some(ref labels) = self.labels {
193            let bead_labels = &bead.fields.labels.value;
194            let has_all = labels.iter().all(|l| bead_labels.contains(l));
195            if !has_all {
196                return false;
197            }
198        }
199
200        // LabelsAny filter (OR)
201        if let Some(ref labels_any) = self.labels_any {
202            let bead_labels = &bead.fields.labels.value;
203            let has_any = labels_any.iter().any(|l| bead_labels.contains(l));
204            if !has_any {
205                return false;
206            }
207        }
208
209        if self.no_labels && !bead.fields.labels.value.is_empty() {
210            return false;
211        }
212
213        // IDs filter
214        if let Some(ref ids) = self.ids
215            && !ids.iter().any(|id| id == bead.id())
216        {
217            return false;
218        }
219
220        // Unclaimed filter
221        if self.unclaimed && bead.fields.claim.value.is_claimed() {
222            return false;
223        }
224
225        // Empty description filter
226        if self.empty_description && !bead.fields.description.value.trim().is_empty() {
227            return false;
228        }
229
230        // Title filter
231        if let Some(ref title) = self.title {
232            let needle = title.to_lowercase();
233            if !bead.fields.title.value.to_lowercase().contains(&needle) {
234                return false;
235            }
236        }
237
238        // Text search
239        if let Some(ref search) = self.search {
240            let search_lower = search.to_lowercase();
241            let title_match = bead
242                .fields
243                .title
244                .value
245                .to_lowercase()
246                .contains(&search_lower);
247            let desc_match = bead
248                .fields
249                .description
250                .value
251                .to_lowercase()
252                .contains(&search_lower);
253            if !title_match && !desc_match {
254                return false;
255            }
256        }
257
258        // Pattern matching
259        if let Some(ref needle) = self.title_contains {
260            let n = needle.to_lowercase();
261            if !bead.fields.title.value.to_lowercase().contains(&n) {
262                return false;
263            }
264        }
265        if let Some(ref needle) = self.desc_contains {
266            let n = needle.to_lowercase();
267            if !bead.fields.description.value.to_lowercase().contains(&n) {
268                return false;
269            }
270        }
271        if let Some(ref needle) = self.notes_contains {
272            let n = needle.to_lowercase();
273            let any = bead
274                .notes
275                .iter()
276                .any(|(_, note)| note.content.to_lowercase().contains(&n));
277            if !any {
278                return false;
279            }
280        }
281
282        // Date ranges
283        let created_ms = bead.core.created().at.wall_ms;
284        if let Some(after) = self.created_after
285            && created_ms < after
286        {
287            return false;
288        }
289        if let Some(before) = self.created_before
290            && created_ms > before
291        {
292            return false;
293        }
294
295        let updated_ms = bead.updated_stamp().at.wall_ms;
296        if let Some(after) = self.updated_after
297            && updated_ms < after
298        {
299            return false;
300        }
301        if let Some(before) = self.updated_before
302            && updated_ms > before
303        {
304            return false;
305        }
306
307        let closed_ms = bead
308            .fields
309            .workflow
310            .value
311            .is_closed()
312            .then_some(bead.fields.workflow.stamp.at.wall_ms);
313        if let Some(after) = self.closed_after
314            && closed_ms.map(|t| t < after).unwrap_or(true)
315        {
316            return false;
317        }
318        if let Some(before) = self.closed_before
319            && closed_ms.map(|t| t > before).unwrap_or(true)
320        {
321            return false;
322        }
323
324        true
325    }
326}
327
328// =============================================================================
329// Query - All query operations
330// =============================================================================
331
332/// Query operations.
333#[derive(Debug, Clone, Serialize, Deserialize)]
334#[serde(tag = "query", rename_all = "snake_case")]
335pub enum Query {
336    /// Get a single bead by ID.
337    Show { repo: PathBuf, id: BeadId },
338
339    /// List beads with filters.
340    List {
341        repo: PathBuf,
342        #[serde(default)]
343        filters: Filters,
344    },
345
346    /// Get beads that are ready to work on (no blockers, unclaimed or claimed by actor).
347    Ready {
348        repo: PathBuf,
349        #[serde(default)]
350        limit: Option<usize>,
351    },
352
353    /// Get the dependency tree for a bead.
354    DepTree { repo: PathBuf, id: BeadId },
355
356    /// Get all deps for a bead (both incoming and outgoing).
357    Deps { repo: PathBuf, id: BeadId },
358
359    /// Get notes for a bead.
360    Notes { repo: PathBuf, id: BeadId },
361
362    /// Get issue database status (overview counts).
363    Status { repo: PathBuf },
364
365    /// Get blocked issues.
366    Blocked { repo: PathBuf },
367
368    /// Get stale issues.
369    Stale {
370        repo: PathBuf,
371        days: u32,
372        #[serde(default)]
373        status: Option<String>,
374        #[serde(default)]
375        limit: Option<usize>,
376    },
377
378    /// Count issues matching filters.
379    Count {
380        repo: PathBuf,
381        #[serde(default)]
382        filter: Filters,
383        #[serde(default)]
384        group_by: Option<String>,
385    },
386
387    /// Show deleted (tombstoned) issues.
388    Deleted {
389        repo: PathBuf,
390        /// If set, only include deletions newer than (now - since_ms).
391        #[serde(default)]
392        since_ms: Option<u64>,
393        /// Optional specific issue id lookup.
394        #[serde(default)]
395        id: Option<BeadId>,
396    },
397
398    /// Epic completion status.
399    EpicStatus {
400        repo: PathBuf,
401        #[serde(default)]
402        eligible_only: bool,
403    },
404
405    /// Validate the state (check for issues).
406    Validate { repo: PathBuf },
407}
408
409impl Query {
410    /// Get the repo path for this query.
411    pub fn repo(&self) -> &PathBuf {
412        match self {
413            Query::Show { repo, .. } => repo,
414            Query::List { repo, .. } => repo,
415            Query::Ready { repo, .. } => repo,
416            Query::DepTree { repo, .. } => repo,
417            Query::Deps { repo, .. } => repo,
418            Query::Notes { repo, .. } => repo,
419            Query::Status { repo } => repo,
420            Query::Blocked { repo } => repo,
421            Query::Stale { repo, .. } => repo,
422            Query::Count { repo, .. } => repo,
423            Query::Deleted { repo, .. } => repo,
424            Query::EpicStatus { repo, .. } => repo,
425            Query::Validate { repo } => repo,
426        }
427    }
428}
429
430// =============================================================================
431// QueryResult - Query results
432// =============================================================================
433
434/// Result of a query.
435#[derive(Debug, Clone, Serialize, Deserialize)]
436#[serde(tag = "result", content = "data", rename_all = "snake_case")]
437#[allow(clippy::large_enum_variant)]
438pub enum QueryResult {
439    /// Single issue result.
440    Issue(Issue),
441
442    /// List of issues (summaries).
443    Issues(Vec<IssueSummary>),
444
445    /// Dependency tree.
446    DepTree {
447        root: BeadId,
448        edges: Vec<ApiDepEdge>,
449    },
450
451    /// Dependencies for a bead.
452    Deps {
453        incoming: Vec<ApiDepEdge>,
454        outgoing: Vec<ApiDepEdge>,
455    },
456
457    /// Notes for a bead.
458    Notes(Vec<ApiNote>),
459
460    /// Issue database status (counts, etc).
461    Status(ApiStatusOutput),
462
463    /// Blocked issues.
464    Blocked(Vec<ApiBlockedIssue>),
465
466    /// Ready issues with summary counts.
467    Ready(ApiReadyResult),
468
469    /// Stale issues.
470    Stale(Vec<IssueSummary>),
471
472    /// Count results.
473    Count(ApiCountResult),
474
475    /// Deleted issues (tombstones) list.
476    Deleted(Vec<ApiTombstone>),
477
478    /// Deleted issue lookup by id.
479    DeletedLookup(ApiDeletedLookup),
480
481    /// Epic completion status.
482    EpicStatus(Vec<ApiEpicStatus>),
483
484    /// Validation result.
485    Validation { warnings: Vec<String> },
486
487    /// Daemon info (handshake).
488    DaemonInfo(ApiDaemonInfo),
489}
490
491// NOTE: daemon IPC uses the canonical `crate::api` schemas for issues/notes/deps.
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496
497    #[test]
498    fn filters_default_matches_all() {
499        // Can't easily test without a bead, but at least verify default construction
500        let filters = Filters::default();
501        assert!(filters.status.is_none());
502        assert!(filters.priority.is_none());
503        assert!(!filters.unclaimed);
504    }
505
506    #[test]
507    fn query_repo() {
508        let query = Query::Show {
509            repo: PathBuf::from("/test"),
510            id: BeadId::parse("bd-abc").unwrap(),
511        };
512        assert_eq!(query.repo(), &PathBuf::from("/test"));
513    }
514}