cliban 0.13.0

Self-hosted, agent-first kanban for the terminal: flat CLI, ratatui board, SQLite storage
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
//! `cliban issue lint` — validate the description contract before it bites.
//!
//! The contract (`## Spec` / `## Plan` / `## Activity Log`, `### Task N:`
//! headings, GFM checkbox steps) is what `tick`, `promote`, and every reader
//! of `--section` rely on. An agent that hand-writes a plan finds out it's
//! malformed only when `tick` fails mid-execution; lint moves that discovery
//! to write time. Pure functions over the description text — the store is not
//! consulted.

use crate::descmd::{find_section, find_step, find_task};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
    /// Breaks a tool (`tick` will refuse, a section won't parse).
    Error,
    /// Parses, but not as the contract intends (a skipped task number, an
    /// activity line no reader will surface).
    Warning,
}

impl Severity {
    pub fn as_str(&self) -> &'static str {
        match self {
            Severity::Error => "error",
            Severity::Warning => "warning",
        }
    }
}

#[derive(Debug, Clone)]
pub struct Finding {
    pub severity: Severity,
    pub message: String,
}

fn err(findings: &mut Vec<Finding>, message: String) {
    findings.push(Finding {
        severity: Severity::Error,
        message,
    });
}

fn warn(findings: &mut Vec<Finding>, message: String) {
    findings.push(Finding {
        severity: Severity::Warning,
        message,
    });
}

/// Lint one issue description. Empty result = clean.
pub fn lint_description(desc: &str) -> Vec<Finding> {
    let mut findings = Vec::new();

    if !desc.trim().is_empty() && !find_section(desc, "Spec").2 {
        warn(&mut findings, "no ## Spec section".to_string());
    }

    // A `## Files` entry that does not parse is dropped by every reader, so one
    // typo silently removes the ticket from wave collision detection and two
    // agents land on the same file. That is the failure the section exists to
    // prevent, so a malformed entry is an error rather than a warning.
    for line in cliban_core::sections::file_lines(desc) {
        if let cliban_core::sections::FileLine::Invalid(text) = line {
            err(
                &mut findings,
                format!(
                    "## Files entry \"{text}\" is not \"<A|M|D> <path>\" — \
                     collision detection will not see it"
                ),
            );
        }
    }

    // Duplicate anchors: every section tool resolves the first, so the rest
    // are unaddressable — the residue of an entry that split the description.
    // Exact match, because find_section resolves anchors case-sensitively.
    let mut seen: Vec<String> = Vec::new();
    for anchor in cliban_core::sections::h2_anchors(desc) {
        if seen.contains(&anchor) {
            err(
                &mut findings,
                format!(
                    "duplicate \"## {anchor}\" section — only the first is addressable; \
                     repair by rewriting the whole description with \
                     issue edit --description-file"
                ),
            );
        } else {
            seen.push(anchor);
        }
    }

    // Timestamped activity entries outside ## Activity Log are the residue of
    // an entry that split the section: a phantom H2 landed between them and
    // their section. Nothing else writes `- <ts> — <msg>` items elsewhere.
    let (a_start, a_end, a_ok) = find_section(desc, "Activity Log");
    let mut stranded = 0usize;
    for item in cliban_core::sections::top_level_list_items(desc) {
        if a_ok && item.start >= a_start && item.end <= a_end {
            continue;
        }
        let body = cliban_core::sections::list_item_body(&desc[item]);
        let head = body.split_once('\n').map_or(body.as_str(), |(h, _)| h);
        if crate::descmd::parse_entry_head(head).is_some() {
            stranded += 1;
        }
    }
    if stranded > 0 {
        err(
            &mut findings,
            format!(
                "{stranded} timestamped activity entr{} outside ## Activity Log — the \
                 residue of a split section; repair by rewriting the whole description \
                 with issue edit --description-file",
                if stranded == 1 { "y" } else { "ies" }
            ),
        );
    }

    let (plan_start, plan_end, has_plan) = find_section(desc, "Plan");
    if has_plan {
        lint_plan(&desc[plan_start..plan_end], &mut findings);
    }

    if find_section(desc, "Activity Log").2 {
        lint_activity(desc, &mut findings);
    }

    findings
}

fn lint_plan(plan: &str, findings: &mut Vec<Finding>) {
    // Every H3 in the plan must be a task heading; collect the numbers, and
    // note where the first one starts — a checkbox before it lints clean
    // structurally but `tick` can never address it.
    //
    // Headings and list items come from the markdown grammar (the same source
    // `tick` reads), so a `### Task 2:` or a `- [X]` quoted inside a fenced
    // code block is content, not structure, and no longer reported.
    let mut numbers: Vec<i32> = Vec::new();
    let mut first_task_at: Option<usize> = None;
    let mut unreachable_steps = 0usize;
    for h in cliban_core::sections::h3_headings(plan) {
        match cliban_core::sections::task_number(&h.text) {
            Some(n) => {
                numbers.push(n);
                first_task_at.get_or_insert(h.range.start);
            }
            None => err(
                findings,
                format!(
                    "plan heading {:?} is not \"### Task N: <title>\"",
                    plan[h.range.clone()].trim_end()
                ),
            ),
        }
    }

    for item in cliban_core::sections::list_items(plan) {
        let src = &plan[item.range.clone()];
        let first_line = src.split_once('\n').map_or(src, |(l, _)| l).trim_end();
        if !first_line.starts_with("- [") {
            continue;
        }
        let well_formed = first_line.starts_with("- [ ] ") || first_line.starts_with("- [x] ");
        // Checkboxes tick/find_step will not recognize. At the top level that's
        // a malformed step (error); nested it's a child bullet — legitimate per
        // the contract, but silently untickable, so worth a heads-up.
        if item.depth > 0 {
            warn(
                findings,
                format!(
                    "indented checkbox {first_line:?} is a child bullet — tick cannot reach it"
                ),
            );
        } else if !well_formed {
            err(
                findings,
                format!("malformed checkbox {first_line:?} (want \"- [ ] \" or \"- [x] \")"),
            );
        } else if first_task_at.is_none_or(|at| item.range.start < at) {
            unreachable_steps += 1;
        }
    }

    if unreachable_steps > 0 {
        warn(
            findings,
            format!(
                "{unreachable_steps} step(s) outside any \"### Task N:\" heading — \
                 tick cannot reach them"
            ),
        );
    }

    for (i, n) in numbers.iter().enumerate() {
        let expected = (i + 1) as i32;
        if *n != expected {
            warn(
                findings,
                format!(
                    "plan tasks are numbered {numbers:?}; expected 1..{}",
                    numbers.len()
                ),
            );
            break;
        }
    }

    for n in &numbers {
        let (task_start, task_end, ok) = find_task(plan, *n);
        if !ok {
            continue; // duplicate number: find_task sees the first; the sequence check flagged it
        }
        if find_step(&plan[task_start..task_end], 1).is_none() {
            warn(findings, format!("Task {n} has no steps"));
        }
    }
}

/// `desc` rather than the section slice: the entry parser locates
/// `## Activity Log` itself, and routing lint through the very function the
/// reader uses is what stops the two from disagreeing about what an entry is.
fn lint_activity(desc: &str, findings: &mut Vec<Finding>) {
    for entry in crate::descmd::activity_entries(desc) {
        if entry.parsed.is_none() {
            let head = &entry.head;
            warn(
                findings,
                format!("activity entry \"- {head}\" does not parse as \"- <ts> — <msg>\""),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn errors(desc: &str) -> usize {
        lint_description(desc)
            .iter()
            .filter(|f| f.severity == Severity::Error)
            .count()
    }

    #[test]
    fn duplicate_section_anchors_are_an_error() {
        // The compounded phantom-section state: a re-logged entry recreated
        // sections that already existed. Only the first of each is addressable.
        let d = "## Spec\n\ns\n\n## Plan\n\nplan\n\n## Spec\n\nagain\n";
        let f = lint_description(d);
        assert!(
            f.iter().any(|f| f.severity == Severity::Error
                && f.message.contains("Spec")
                && f.message.contains("--description-file")),
            "duplicate anchor must be an error naming the repair: {f:?}"
        );
    }

    #[test]
    fn a_custom_h2_is_not_an_error() {
        let d = "## Spec\n\ns\n\n## Rollout\n\ncustom section\n";
        assert_eq!(errors(d), 0);
    }

    #[test]
    fn a_stranded_timestamped_entry_is_an_error() {
        // The single-phantom state: a log entry's H2 split ## Activity Log,
        // leaving timestamped entries under a foreign section.
        let d = "## Spec\n\ns\n\n## Activity Log\n\n- 2026-08-08T10:00Z — ok\n\n\
                 ## Phantom\n\n- 2026-08-08T10:01Z — stranded tail\n";
        let f = lint_description(d);
        assert!(
            f.iter().any(|f| f.severity == Severity::Error
                && f.message.contains("--description-file")),
            "stranded entry must be an error naming the repair: {f:?}"
        );
    }

    #[test]
    fn plain_bullets_in_a_custom_section_are_clean() {
        let d = "## Spec\n\ns\n\n## Rollout\n\n- step one\n- step two\n";
        assert_eq!(errors(d), 0);
    }

    #[test]
    fn a_conforming_description_is_clean() {
        let d = "## Spec\n\ns\n\n## Plan\n\n### Task 1: a\n\n- [ ] **Step 1: x**\n\n\
                 ## Activity Log\n\n- 2026-08-02T10:00Z — started\n";
        assert!(lint_description(d).is_empty(), "{:?}", lint_description(d));
    }

    #[test]
    fn empty_description_is_clean() {
        assert!(lint_description("").is_empty());
    }

    #[test]
    fn bad_task_heading_is_an_error() {
        let d = "## Plan\n\n### Step one\n\n- [ ] x\n";
        assert_eq!(errors(d), 1);
    }

    #[test]
    fn malformed_checkbox_is_an_error() {
        // Uppercase X at column zero: looks ticked, tick/find_step disagree.
        let d = "## Plan\n\n### Task 1: a\n\n- [X] step\n";
        assert_eq!(errors(d), 1);
    }

    #[test]
    fn indented_checkbox_is_a_warning_not_an_error() {
        // Child bullets are legitimate, but a checkbox down there is
        // unreachable by tick — flag without failing.
        let d = "## Plan\n\n### Task 1: a\n\n- [ ] real step\n  - [ ] hidden\n";
        assert_eq!(errors(d), 0);
        assert!(lint_description(d)
            .iter()
            .any(|f| f.severity == Severity::Warning && f.message.contains("indented")));
    }

    #[test]
    fn skipped_task_number_is_a_warning() {
        let d = "## Plan\n\n### Task 1: a\n\n- [ ] x\n\n### Task 3: b\n\n- [ ] y\n";
        let f = lint_description(d);
        assert!(f.iter().any(|f| f.severity == Severity::Warning));
        assert_eq!(errors(d), 0);
    }

    #[test]
    fn flat_checklist_without_tasks_is_flagged() {
        // Lints structurally clean, but tick can't address a single step.
        let d = "## Plan\n\n- [ ] first\n- [ ] second\n";
        let f = lint_description(d);
        assert!(
            f.iter().any(|f| f.message.contains("tick cannot reach")),
            "{f:?}"
        );
    }

    #[test]
    fn steps_inside_tasks_are_not_flagged_as_unreachable() {
        let d = "## Plan\n\n### Task 1: a\n\n- [ ] in task\n";
        assert!(!lint_description(d)
            .iter()
            .any(|f| f.message.contains("tick cannot reach")));
    }

    #[test]
    fn stepless_task_is_a_warning() {
        let d = "## Plan\n\n### Task 1: a\n\nprose only\n";
        let f = lint_description(d);
        assert!(f
            .iter()
            .any(|f| f.severity == Severity::Warning && f.message.contains("no steps")));
    }

    #[test]
    fn unparseable_activity_line_is_a_warning() {
        let d = "## Activity Log\n\n- yesterday: did stuff\n";
        let f = lint_description(d);
        assert_eq!(f.len(), 2, "{f:?}"); // missing-spec warning + activity warning
        assert!(f.iter().all(|f| f.severity == Severity::Warning));
    }

    #[test]
    fn a_sublist_under_a_log_entry_is_not_a_malformed_entry() {
        // The reported bug: detail bullets beneath an entry drew one spurious
        // "does not parse" warning each.
        let d = "## Spec\n\ns\n\n## Activity Log\n\n- 2026-08-08T10:00Z — did a thing\n  \
                 - detail one\n  - detail two\n";
        let f = lint_description(d);
        assert!(f.is_empty(), "sublists are entry body, not entries: {f:?}");
    }

    #[test]
    fn a_wrapped_log_entry_is_not_flagged() {
        let d = "## Spec\n\ns\n\n## Activity Log\n\n- 2026-08-08T10:00Z — a long entry that\n  \
                 wraps onto another line\n";
        assert!(lint_description(d).is_empty(), "{:?}", lint_description(d));
    }

    #[test]
    fn a_fenced_plan_is_content_not_structure() {
        // A spec-shaped plan quoting the contract used to draw a malformed
        // checkbox error and a bogus task heading error from inside a fence.
        let d = "## Spec\n\ns\n\n## Plan\n\n### Task 1: a\n\n- [ ] **Step 1: x**\n\n\
                 The format is:\n\n```markdown\n### Step one\n\n- [X] not a real checkbox\n```\n";
        let f = lint_description(d);
        assert!(f.is_empty(), "fenced content must not lint: {f:?}");
    }

    #[test]
    fn steps_after_a_fenced_block_still_count_as_inside_the_task() {
        let d = "## Spec\n\ns\n\n## Plan\n\n### Task 1: a\n\n```\n### Task 9: fake\n```\n\n\
                 - [ ] **Step 1: x**\n";
        let f = lint_description(d);
        assert!(
            !f.iter().any(|f| f.message.contains("tick cannot reach")),
            "{f:?}"
        );
    }

    #[test]
    fn a_malformed_files_entry_is_an_error_not_a_warning() {
        // Silently dropped, it removes the ticket from collision detection.
        let d = "## Spec\n\ns\n\n## Files\n\n- M good/path.rs\n- X bad/status.rs\n";
        let f = lint_description(d);
        let bad: Vec<_> = f.iter().filter(|f| f.message.contains("## Files")).collect();
        assert_eq!(bad.len(), 1, "{f:?}");
        assert_eq!(bad[0].severity, Severity::Error, "{f:?}");
        assert!(bad[0].message.contains("X bad/status.rs"), "{f:?}");
    }

    #[test]
    fn a_well_formed_files_section_with_prose_lints_clean() {
        let d = "## Spec\n\ns\n\n## Files\n\nPredicted, amended when wrong.\n\n\
                 - A new/file.rs\n- M old/file.rs\n- D gone/file.rs\n";
        assert!(lint_description(d).is_empty(), "{:?}", lint_description(d));
    }
}