beads_rust 0.5.3

Agent-first issue tracker (SQLite + JSONL)
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use crate::model::{Comment, Event, Issue, IssueType, Priority, Status};
use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Minimal issue output for stale command (bd parity).
/// Contains only the fields that bd's stale command outputs.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct StaleIssue {
    pub created_at: DateTime<Utc>,
    pub id: String,
    pub issue_type: IssueType,
    pub priority: Priority,
    pub status: Status,
    pub title: String,
    pub updated_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assignee: Option<String>,
}

/// Minimal issue output for ready command (bd parity).
///
/// Contains only the fields that bd's ready command outputs.
/// Does NOT include: `compaction_level`, `original_size`, `dependency_count`, `dependent_count`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ReadyIssue {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub acceptance_criteria: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub assignee: Option<String>,
    pub created_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_by: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub estimated_minutes: Option<i32>,
    pub id: String,
    pub issue_type: IssueType,
    /// Labels attached to the issue.
    ///
    /// Always emitted (as `[]` when empty) so downstream consumers can filter
    /// `br ready --json` output on labels the same way they filter
    /// `br list --json` (#309).
    pub labels: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner: Option<String>,
    pub priority: Priority,
    pub status: Status,
    pub title: String,
    pub updated_at: DateTime<Utc>,
}

impl From<Issue> for ReadyIssue {
    fn from(issue: Issue) -> Self {
        Self {
            acceptance_criteria: issue.acceptance_criteria,
            assignee: issue.assignee,
            created_at: issue.created_at,
            created_by: issue.created_by,
            description: issue.description,
            estimated_minutes: issue.estimated_minutes,
            id: issue.id,
            issue_type: issue.issue_type,
            labels: issue.labels,
            notes: issue.notes,
            owner: issue.owner,
            priority: issue.priority,
            status: issue.status,
            title: issue.title,
            updated_at: issue.updated_at,
        }
    }
}

/// Minimal issue output for blocked command (bd parity).
///
/// Contains only the fields that bd's blocked command outputs, plus `blocked_by` info.
/// Does NOT include: `compaction_level`, `original_size`
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BlockedIssueOutput {
    pub blocked_by: Vec<String>,
    pub blocked_by_count: usize,
    pub created_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_by: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub id: String,
    pub issue_type: IssueType,
    pub priority: Priority,
    pub status: Status,
    pub title: String,
    pub updated_at: DateTime<Utc>,
}

impl From<Issue> for StaleIssue {
    fn from(issue: Issue) -> Self {
        Self {
            created_at: issue.created_at,
            id: issue.id,
            issue_type: issue.issue_type,
            priority: issue.priority,
            status: issue.status,
            title: issue.title,
            updated_at: issue.updated_at,
            assignee: issue.assignee,
        }
    }
}

/// Issue with counts for list/search views.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct IssueWithCounts {
    #[serde(flatten)]
    pub issue: Issue,
    pub dependency_count: usize,
    pub dependent_count: usize,
}

/// Paginated list response envelope for `br list --json`.
///
/// Wraps the issue array with pagination metadata so consumers can detect
/// truncation and iterate through all results using `--limit` / `--offset`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ListPage {
    /// The issues in this page of results.
    pub issues: Vec<IssueWithCounts>,
    /// Total number of issues matching the query (ignoring LIMIT/OFFSET).
    pub total: usize,
    /// Maximum number of results requested (`--limit`; 0 means unlimited).
    pub limit: usize,
    /// Number of results skipped (`--offset`).
    pub offset: usize,
    /// Whether there are more results beyond this page.
    pub has_more: bool,
}

/// Issue details with full relations for show view.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct IssueDetails {
    #[serde(flatten)]
    pub issue: Issue,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub labels: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dependencies: Vec<IssueWithDependencyMetadata>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dependents: Vec<IssueWithDependencyMetadata>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub comments: Vec<Comment>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub events: Vec<Event>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent: Option<String>,
    /// Derived parent-child subtree rollup; present only when the issue has
    /// local parent-child children (GitHub #384 phase 3).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rollup: Option<RollupSummary>,
    /// Inherited governing context from ancestor beads (beads_rust#297).
    /// Present only when the project has opted in to inherited-context
    /// emission and an ancestor supplies `agent_context`; populated for
    /// JSON/TOON output so structured consumers receive the same governing
    /// context that text mode renders (beads_rust#430).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub inherited_context: Vec<crate::inheritance::InheritedBlock>,
}

/// Derived parent-child subtree rollup for a parent issue (GitHub #384
/// phase 3: hierarchy observability).
///
/// The rollup reports what a parent's subtree is effectively doing without
/// mutating the parent's explicit status: an epic can stay `open` while its
/// rollup says `in_progress` because a descendant started.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RollupSummary {
    /// Furthest-along non-terminal descendant status in workflow order, or
    /// `closed` when every descendant is terminal.
    pub status: String,
    /// Count of strict parent-child descendants by stored status.
    pub descendants: std::collections::BTreeMap<String, u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct IssueWithDependencyMetadata {
    pub id: String,
    pub title: String,
    pub status: Status,
    pub priority: Priority,
    #[serde(rename = "dependency_type")]
    pub dep_type: String,
}

/// Blocked issue for blocked view.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BlockedIssue {
    #[serde(flatten)]
    pub issue: Issue,
    pub blocked_by_count: usize,
    pub blocked_by: Vec<String>,
}

/// Tree node for dependency tree view.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TreeNode {
    #[serde(flatten)]
    pub issue: Issue,
    pub depth: usize,
    pub parent_id: Option<String>,
    pub truncated: bool,
}

/// Summary statistics for the project.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct StatsSummary {
    pub total_issues: usize,
    pub open_issues: usize,
    pub in_progress_issues: usize,
    pub closed_issues: usize,
    pub blocked_issues: usize,
    pub deferred_issues: usize,
    pub draft_issues: usize,
    pub ready_issues: usize,
    pub tombstone_issues: usize,
    pub pinned_issues: usize,
    pub epics_eligible_for_closure: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub average_lead_time_hours: Option<f64>,
}

/// Breakdown statistics by a dimension.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Breakdown {
    pub dimension: String,
    pub counts: Vec<BreakdownEntry>,
}

/// A single entry in a breakdown.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct BreakdownEntry {
    pub key: String,
    pub count: usize,
}

/// Recent activity statistics from git history.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecentActivity {
    pub hours_tracked: u32,
    pub commit_count: usize,
    pub issues_created: usize,
    pub issues_closed: usize,
    pub issues_updated: usize,
    pub issues_reopened: usize,
    pub total_changes: usize,
}

/// Observed occupancy of one workflow capacity (GitHub #384 phase 6).
///
/// One row per repository capacity plus one row per occupied partition of
/// each scoped capacity, mirroring the enforcement engine's counting
/// (exemptions and hierarchy modes included).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CapacityStat {
    /// The status or group name.
    pub name: String,
    /// `status` or `group`.
    pub kind: String,
    /// Scope partition dimension (`repository`, `actor`, ...).
    pub scope: String,
    /// Partition key within a non-repository scope.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope_key: Option<String>,
    /// Occupancy excluding exemptions (and hierarchy aggregates).
    pub counted: u32,
    /// Active issues excluded as hierarchy aggregates (`leaf_work`/`roots`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aggregate_parents_excluded: Option<u32>,
    /// Occupancy excluded by active, authorized exemptions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exempt: Option<u32>,
    /// Advisory threshold, if configured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub soft_limit: Option<u32>,
    /// Enforced threshold, if configured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hard_limit: Option<u32>,
    /// `hard_limit - counted`, clamped at zero; absent without a hard limit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub remaining: Option<u32>,
    /// `healthy` | `soft-limit` | `at-hard` | `over-hard`.
    pub state: String,
    /// Counting mode the numbers were computed under.
    pub counting_mode: String,
    /// Policy location of the limit.
    pub policy_path: String,
}

impl CapacityStat {
    /// Derive the display/state fields from a storage snapshot row.
    #[must_use]
    pub fn from_snapshot(row: crate::storage::sqlite::CapacitySnapshotRow) -> Self {
        let counted = row.counted;
        let soft_hit = row.soft.is_some_and(|soft| counted >= soft);
        let state = row.hard.map_or_else(
            || if soft_hit { "soft-limit" } else { "healthy" },
            |hard| {
                if counted > hard {
                    "over-hard"
                } else if counted == hard {
                    "at-hard"
                } else if soft_hit {
                    "soft-limit"
                } else {
                    "healthy"
                }
            },
        );
        Self {
            name: row.name,
            kind: row.kind,
            scope: row.scope,
            scope_key: row.scope_key,
            counted,
            aggregate_parents_excluded: row.aggregate_parents_excluded,
            exempt: row.exempt,
            soft_limit: row.soft,
            hard_limit: row.hard,
            remaining: row.hard.map(|hard| hard.saturating_sub(counted)),
            state: state.to_string(),
            counting_mode: row.counting_mode,
            policy_path: row.policy_path,
        }
    }
}

/// Aggregate statistics output.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Statistics {
    pub summary: StatsSummary,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub breakdowns: Vec<Breakdown>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recent_activity: Option<RecentActivity>,
    /// Workflow capacity occupancy (GitHub #384). Absent when no capacity
    /// is configured, preserving the pre-capacity payload shape.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub capacity: Vec<CapacityStat>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{TimeZone, Utc};

    fn base_issue(id: &str, title: &str) -> Issue {
        Issue {
            id: id.to_string(),
            content_hash: None,
            title: title.to_string(),
            description: None,
            design: None,
            acceptance_criteria: None,
            notes: None,
            status: Status::Open,
            priority: Priority::MEDIUM,
            issue_type: crate::model::IssueType::Task,
            assignee: None,
            owner: None,
            estimated_minutes: None,
            created_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
            created_by: None,
            updated_at: Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap(),
            closed_at: None,
            close_reason: None,
            closed_by_session: None,
            due_at: None,
            defer_until: None,
            external_ref: None,
            source_system: None,
            source_repo: None,
            source_repo_path: None,
            agent_context: None,
            deleted_at: None,
            deleted_by: None,
            delete_reason: None,
            original_type: None,
            compaction_level: None,
            compacted_at: None,
            compacted_at_commit: None,
            original_size: None,
            sender: None,
            ephemeral: false,
            pinned: false,
            is_template: false,
            labels: vec![],
            dependencies: vec![],
            comments: vec![],
        }
    }

    #[test]
    fn issue_with_counts_serializes_counts() {
        let issue = base_issue("bd-1", "Test");
        let iwc = IssueWithCounts {
            issue,
            dependency_count: 2,
            dependent_count: 1,
        };

        let json = serde_json::to_string(&iwc).unwrap();
        assert!(json.contains("\"dependency_count\":2"));
        assert!(json.contains("\"dependent_count\":1"));
        assert!(json.contains("\"id\":\"bd-1\""));
    }

    #[test]
    fn issue_details_serializes_parent_and_relations() {
        let issue = base_issue("bd-2", "Details");
        let details = IssueDetails {
            issue,
            labels: vec!["backend".to_string()],
            dependencies: vec![],
            dependents: vec![],
            comments: vec![],
            events: vec![],
            parent: Some("bd-parent".to_string()),
            rollup: None,
            inherited_context: Vec::new(),
        };

        let json = serde_json::to_string(&details).unwrap();
        assert!(json.contains("\"parent\":\"bd-parent\""));
        assert!(json.contains("\"labels\":[\"backend\"]"));
        assert!(!json.contains("\"rollup\""));
    }

    #[test]
    fn blocked_issue_serializes_blockers() {
        let issue = base_issue("bd-3", "Blocked");
        let blocked = BlockedIssue {
            issue,
            blocked_by_count: 2,
            blocked_by: vec!["bd-a".to_string(), "bd-b".to_string()],
        };

        let json = serde_json::to_string(&blocked).unwrap();
        assert!(json.contains("\"blocked_by_count\":2"));
        assert!(json.contains("\"blocked_by\":[\"bd-a\",\"bd-b\"]"));
    }
}