diff --git a/.opencode/skill/worklane-kanban-skill/SKILL.md b/.opencode/skill/worklane-kanban-skill/SKILL.md index d9e0e15..f5b757c 100644 --- a/.opencode/skill/worklane-kanban-skill/SKILL.md +++ b/.opencode/skill/worklane-kanban-skill/SKILL.md @@ -138,6 +138,26 @@ worklane append a1b2c3d4 -a "One more criterium" worklane append a1b2c3d4 -p "A later step" ``` +### `worklane check` and `worklane uncheck` + +Tick or untick a single acceptance criterion. Every other criterion keeps its state, +and handwritten lines in the section are left alone. + +**Positional arguments:** +- ``: Ticket UUID prefix (4+ characters) or title +- `[criterion]`: The number as shown by `worklane show`, or a substring of its text + +Omit the criterion and the numbered criteria are listed and the number asked for. With +no terminal, as when driving the CLI from a tool, the same list comes back as an error +instead, so re-run with the number. A substring matching more than one criterion is an +error listing the matches with their real numbers. + +```bash +worklane check a1b2c3d4 2 +worklane check a1b2c3d4 "renames the file" +worklane uncheck a1b2c3d4 2 +``` + ### `worklane comment` Add a comment to a ticket. @@ -163,4 +183,5 @@ worklane comment a1b2c3d4 "LGTM, approved" 3. Use `worklane show ` to view full ticket details 4. Use `worklane mv --status ` to move tickets through the workflow 5. Use `worklane set ` to correct a field, or `worklane append ` to add to a section -6. Use `worklane comment ` to add notes to tickets +6. Use `worklane check ` to tick a criterion as it is met +7. Use `worklane comment ` to add notes to tickets diff --git a/.opencode/tools/worklane.ts b/.opencode/tools/worklane.ts index 3243978..1c97dfa 100644 --- a/.opencode/tools/worklane.ts +++ b/.opencode/tools/worklane.ts @@ -394,3 +394,49 @@ export const append = tool({ } }, }); + +/** + * check and uncheck differ only in the verb, so the tool is built once. + * + * The criterion is required here even though the CLI makes it optional: without it the + * CLI prompts, and there is no terminal on this side of the pipe. The CLI answers a + * missing criterion with the numbered list on stderr, which run() relays, so the model + * sees the options and can retry with a number. + */ +function checkboxTool(verb: "check" | "uncheck") { + const past = verb === "check" ? "Checked" : "Unchecked"; + + return tool({ + description: + `${past === "Checked" ? "Tick" : "Untick"} one acceptance criterion on a worklane ticket. ` + + "Every other criterion keeps its state. Identify the criterion by its number as shown by show, " + + "or by a substring of its text; a substring matching more than one is an error listing them.", + args: { + ticket: tool.schema + .string() + .describe("Ticket UUID prefix (4+ chars) or title substring (required)"), + criterion: tool.schema + .string() + .describe( + "Criterion number as shown by show, or a substring of its text (required)", + ), + }, + async execute(args: Record, context: ToolContext) { + if (!args.ticket) { + return `Error running ${verb}: ticket is required`; + } + if (!args.criterion) { + return `Error running ${verb}: criterion is required, give the number or a substring`; + } + + try { + return await run([verb, args.ticket, String(args.criterion)], context); + } catch (err: any) { + return `Error running ${verb}: ${err.message}`; + } + }, + }); +} + +export const check = checkboxTool("check"); +export const uncheck = checkboxTool("uncheck"); diff --git a/AGENTS.md b/AGENTS.md index b29106e..3e5cfad 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,6 +52,16 @@ - `find_ticket_file()` matches on the uuid, never the title. Duplicate titles are allowed, so a title scan can land on a different ticket than the one resolved: `mv ` used to move the first ticket sharing its title - `write_then_replace()` is the only way a ticket file is written. Content first, rename second, so a failure leaves a correct ticket under a stale name rather than a half-written one +### Checking Off a Criterion +- `check` and `uncheck` are separate commands, not one verb with a flag. They share `CheckArgs` and `cmd_check(args, checked)` +- `criteria()` is scoped to the Acceptance Criteria section and counts only checkbox lines, so a checkbox written into a description is not a criterion and a handwritten line inside the section takes no number +- `set_criterion()` splices only the character between the brackets. Rebuilding the line would normalise its indentation and whatever spacing followed the checkbox +- The criterion argument is an index first, a substring second, so a criterion whose text is literally `2` is reachable only by substring +- **A number out of range is a bad index, not a failed substring search**, and says so. `is_index()` makes that distinction +- Any listing of a subset must keep the real numbers, via `numbered_criteria()`. Renumbering the matches from one contradicts the advice to use the number and points at the wrong criterion +- With the criterion omitted: prompt when stdin is a terminal, otherwise return the numbered list as an error. Never prompt unconditionally, the opencode wrapper has no tty and would block on a stdin that never closes. This is the same choice `resolve_ticket` makes for an ambiguous match, and for the same reason +- `show` numbers the criteria as `1. [x] text`, so the index is visible where the ticket is read. The number replaces the list marker rather than joining it + ### Color and Output - Use `color_text()` helper for colored output — it respects `should_use_colors()` (terminal detection) - Color codes are defined in `get_color()`: red (31), cyan (36), orange (33), green (32), grey (38;5;8), magenta (1;35), brightred (38;5;9) diff --git a/Cargo.lock b/Cargo.lock index 3f842c1..6752247 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1029,7 +1029,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.5.0" +version = "0.6.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 79a81e1..ef165be 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.5.0" +version = "0.6.0" edition = "2024" [dependencies] diff --git a/README.md b/README.md index 2dd6ae5..7dd3629 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ Worklane is a local Kanban flow for agentic software development. | `worklane mv --status [-f]` | Moves ticket between statuses. Default: forward only, one stage at a time. `-f` bypasses both restrictions | | `worklane set ` | Replaces fields with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--priority`. At least one required. Changing the title renames the file, keeping the UUID | | `worklane append ` | Adds to a section with `--description`, `--acceptance`, `--plan`. At least one required. The description gains a paragraph; list items go on the end, steps numbered on from the last | +| `worklane check [criterion]` | Ticks one acceptance criterion, by number as shown by `show` or by a substring. Prompts with the numbered list if omitted, or errors with it when there is no terminal | +| `worklane uncheck [criterion]` | Unticks one acceptance criterion, addressed the same way | | `worklane comment ` | Adds a comment to a ticket by UUID or title | ## Exit codes diff --git a/src/command.rs b/src/command.rs index fe788e3..7ffeae2 100644 --- a/src/command.rs +++ b/src/command.rs @@ -140,6 +140,12 @@ pub enum Command { /// Add to a section of an existing ticket Append(AppendArgs), + /// Tick an acceptance criterion + Check(CheckArgs), + + /// Untick an acceptance criterion + Uncheck(CheckArgs), + /// Add a comment to a ticket Comment { /// Ticket UUID or title @@ -225,3 +231,19 @@ pub struct AppendArgs { #[arg(short, long, allow_hyphen_values = PROSE)] pub plan: Vec, } + +/// `check` and `uncheck` are separate commands rather than one verb with a flag, +/// because the two read as opposites at the call site and neither needs the other's +/// name to make sense. +/// +/// The criterion is optional: without it the criteria are listed and the index asked +/// for, or, where there is no terminal to ask at, returned as an error carrying the +/// same list. +#[derive(clap::Args)] +pub struct CheckArgs { + /// Ticket UUID or title + pub ticket: String, + + /// Criterion index as shown by `show`, or a substring of its text. Prompts if omitted + pub criterion: Option, +} diff --git a/src/handlers.rs b/src/handlers.rs index 74e9fbd..92375eb 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -1,10 +1,10 @@ use anyhow::{Result, anyhow}; use chrono::Local; use std::fs; -use std::io::Write; +use std::io::{BufRead, IsTerminal, Write}; use std::path::Path; -use crate::command::{AppendArgs, SetArgs}; +use crate::command::{AppendArgs, CheckArgs, SetArgs}; use crate::util::*; pub fn cmd_init(start: &Path) -> Result<()> { @@ -749,3 +749,121 @@ pub fn cmd_append(args: &AppendArgs, start: &Path) -> Result<()> { report(&changed, &title, "Appended to"); Ok(()) } + +/// Which criterion to act on, asked for when the caller did not say. +/// +/// A terminal gets the list and a prompt. Anything else gets the same list as an +/// error, which is what `resolve_ticket` does for an ambiguous match and for the same +/// reason: the opencode wrapper throws on the exit code and keeps stderr, so a list +/// printed to stdout would be discarded and an agent would learn nothing. Prompting +/// regardless would leave it blocked on a stdin that never closes. +fn ask_which_criterion(criteria: &[Criterion], title: &str) -> Result { + let listing = criteria_list(criteria); + + if !std::io::stdin().is_terminal() { + return Err(anyhow!( + "Which criterion of '{}'?\n{}\n\nRe-run with the number, or a substring of the text.", + title, + listing + )); + } + + println!("Acceptance criteria of '{}':", color_text(title, "green")); + println!("{}", listing); + // Either form, since find_criteria takes both. + print!("Number or text: "); + std::io::stdout().flush()?; + + let mut answer = String::new(); + std::io::stdin().lock().read_line(&mut answer)?; + + // An empty needle matches every criterion, so it would otherwise be reported as + // ambiguous rather than as nothing having been chosen. + if answer.trim().is_empty() { + return Err(anyhow!("No criterion chosen")); + } + + let chosen = find_criteria(criteria, &answer); + match chosen.len() { + 1 => Ok(chosen[0]), + 0 => Err(anyhow!( + "'{}' matches none of the {} criteria", + answer.trim(), + criteria.len() + )), + _ => Err(anyhow!( + "'{}' matches more than one criterion, use the number", + answer.trim() + )), + } +} + +pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path) -> Result<()> { + let worklane_dir = find_worklane_dir(start)?; + let (status, title, content) = resolve_ticket(&args.ticket, &worklane_dir)?; + + let criteria = criteria(&content); + if criteria.is_empty() { + return Err(anyhow!("Ticket '{}' has no acceptance criteria", title)); + } + + let chosen = match &args.criterion { + None => ask_which_criterion(&criteria, &title)?, + Some(search) => { + let found = find_criteria(&criteria, search); + match found.len() { + 1 => found[0], + 0 if is_index(search) => { + return Err(anyhow!( + "'{}' is not one of the {} criteria of '{}':\n{}", + search.trim(), + criteria.len(), + title, + criteria_list(&criteria) + )); + } + 0 => { + return Err(anyhow!( + "No criterion of '{}' matches '{}'. Its criteria are:\n{}", + title, + search, + criteria_list(&criteria) + )); + } + _ => { + return Err(anyhow!( + "'{}' matches {} criteria of '{}':\n{}\n\nUse the number instead.", + search, + found.len(), + title, + numbered_criteria(&criteria, &found) + )); + } + } + } + }; + + let criterion = &criteria[chosen]; + let verb = if checked { "checked" } else { "unchecked" }; + + if criterion.checked == checked { + println!( + "Already {}: {}", + verb, + color_text(&criterion.text, "green") + ); + return Ok(()); + } + + let updated = set_criterion(&content, criterion.line, checked); + let uuid = parse_ticket_field(&content, "ID"); + save_ticket(&worklane_dir, &status, &uuid, &title, None, &updated)?; + + println!( + "{} {}: {}", + if checked { "Checked" } else { "Unchecked" }, + chosen + 1, + color_text(&criterion.text, "green") + ); + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index f80adf4..9e79eb0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -72,6 +72,8 @@ fn main() -> Result<()> { } => cmd_mv(&ticket, &status, force, &start), Command::Set(args) => cmd_set(&args, &start), Command::Append(args) => cmd_append(&args, &start), + Command::Check(args) => cmd_check(&args, true, &start), + Command::Uncheck(args) => cmd_check(&args, false, &start), Command::Comment { ticket, body, owner } => cmd_comment(&ticket, &body, &owner, &start), } } diff --git a/src/util.rs b/src/util.rs index 42ee35b..43a6edb 100644 --- a/src/util.rs +++ b/src/util.rs @@ -290,6 +290,7 @@ pub fn content_trim_colored(content: &str) -> String { let colored = should_use_colors(); let mut result = String::new(); let mut current_section = ""; + let mut criterion = 0; let mut i = 0; while i < lines.len() { @@ -342,10 +343,22 @@ pub fn content_trim_colored(content: &str) -> String { continue; } - // Acceptance Criteria checkboxes - if line.starts_with("- [ ]") { - result.push_str(&paint("- [ ]", "grey", colored)); - result.push_str(&line[5..]); + // Acceptance Criteria checkboxes, numbered so the index `check` takes is + // visible where the ticket is read. The number replaces the list marker + // rather than joining it, and is cyan like the numbers in the plan section. + if current_section == ACCEPTANCE.heading + && let Some((checked, text)) = checkbox(line) + { + criterion += 1; + result.push_str(&paint(&format!("{}.", criterion), "cyan", colored)); + result.push(' '); + result.push_str(&paint( + if checked { "[x]" } else { "[ ]" }, + "grey", + colored, + )); + result.push(' '); + result.push_str(&colorize_line(text)); result.push('\n'); continue; } @@ -849,6 +862,150 @@ pub fn append_section_body(content: &str, section: &Section, items: &[String]) - Ok(join_lines(&out)) } +/// One acceptance criterion as it sits in the file. +pub struct Criterion { + /// Index into `content.lines()`, so the one line can be rewritten in place. + pub line: usize, + pub checked: bool, + pub text: String, +} + +/// A checkbox line's state and text, or `None` when the line is not one. +/// +/// Both `[x]` and `[X]` count as ticked. Anything else between the brackets is not a +/// criterion, so a handwritten line in the section is left out of the numbering. +pub fn checkbox(line: &str) -> Option<(bool, &str)> { + let rest = line.trim_start().strip_prefix("- [")?; + let mut chars = rest.char_indices(); + + let (_, mark) = chars.next()?; + let (closes_at, close) = chars.next()?; + if close != ']' { + return None; + } + + let checked = match mark { + ' ' => false, + 'x' | 'X' => true, + _ => return None, + }; + + Some((checked, rest[closes_at + 1..].trim())) +} + +/// The acceptance criteria, numbered in the order they appear. +/// +/// Scoped to the section, so a checkbox written into a description is not a criterion, +/// and non-checkbox lines inside the section are skipped rather than numbered. +pub fn criteria(content: &str) -> Vec { + let lines: Vec<&str> = content.lines().collect(); + let Some(body) = section_body(&lines, ACCEPTANCE.heading) else { + return Vec::new(); + }; + + lines[body.clone()] + .iter() + .enumerate() + .filter_map(|(offset, line)| { + checkbox(line).map(|(checked, text)| Criterion { + line: body.start + offset, + checked, + text: text.to_string(), + }) + }) + .collect() +} + +/// The criteria at `shown`, numbered by their real position in the list. +/// +/// The position matters: a subset renumbered from one would contradict the advice to +/// use the number, pointing at whichever criterion happens to sit there instead. +pub fn numbered_criteria(criteria: &[Criterion], shown: &[usize]) -> String { + let colored = should_use_colors(); + + shown + .iter() + .filter_map(|offset| criteria.get(*offset).map(|criterion| (offset, criterion))) + .map(|(offset, criterion)| { + format!( + " {} {} {}", + paint(&format!("{}.", offset + 1), "cyan", colored), + paint( + if criterion.checked { "[x]" } else { "[ ]" }, + "grey", + colored + ), + criterion.text + ) + }) + .collect::>() + .join("\n") +} + +/// The whole list, numbered as `show` numbers it. +pub fn criteria_list(criteria: &[Criterion]) -> String { + numbered_criteria(criteria, &(0..criteria.len()).collect::>()) +} + +/// Whether `search` is a number rather than a substring, so a value out of range can +/// be reported as a bad index instead of a fruitless text search. +pub fn is_index(search: &str) -> bool { + search.trim().parse::().is_ok() +} + +/// Which criterion `search` names: a one-based index as `show` prints, or a +/// case-insensitive substring of the text. +/// +/// The index is tried first, so a criterion whose text is literally "2" is reachable +/// only by substring. Returns every match, leaving the caller to refuse more than one. +pub fn find_criteria(criteria: &[Criterion], search: &str) -> Vec { + if let Ok(index) = search.trim().parse::() { + if index >= 1 && index <= criteria.len() { + return vec![index - 1]; + } + // A number outside the range is a bad index, not a substring to hunt for. + return Vec::new(); + } + + // Trimmed, like the index path: an answer typed at the prompt arrives with its + // newline attached, and no criterion text contains one. + let needle = search.trim().to_lowercase(); + criteria + .iter() + .enumerate() + .filter(|(_, criterion)| criterion.text.to_lowercase().contains(&needle)) + .map(|(offset, _)| offset) + .collect() +} + +/// Tick or untick the criterion on `line`, leaving every other byte alone. +/// +/// Only the character between the brackets is spliced. Rebuilding the line would +/// normalise its indentation and whatever spacing it carried after the checkbox. +pub fn set_criterion(content: &str, line: usize, checked: bool) -> String { + let mark = if checked { 'x' } else { ' ' }; + let mut out = String::with_capacity(content.len()); + + for (index, current) in content.lines().enumerate() { + match (index == line, current.find("- [")) { + (true, Some(at)) => { + let opens = at + "- [".len(); + out.push_str(¤t[..opens]); + out.push(mark); + // Past the one character the brackets hold. Nothing follows on a line + // that ends mid-checkbox, which is why this is not unconditional. + if let Some((offset, _)) = current[opens..].char_indices().nth(1) { + out.push_str(¤t[opens + offset..]); + } + } + _ => out.push_str(current), + } + out.push('\n'); + } + + out +} + /// The slice with blank values trimmed from both ends, interior ones kept. /// /// Description values are joined with a single newline, so an empty value is how a diff --git a/tests/cmd_check.rs b/tests/cmd_check.rs new file mode 100644 index 0000000..9b0de75 --- /dev/null +++ b/tests/cmd_check.rs @@ -0,0 +1,287 @@ +use assert_cmd::Command; +use assert_fs::TempDir; +use assert_fs::fixture::{PathChild, PathCreateDir}; +use std::fs; +use std::path::PathBuf; + +const BIN_NAME: &str = env!("CARGO_BIN_EXE_worklane"); +const UUID: &str = "475534a3-8a0d-45cb-9a97-39c251dd8e39"; + +fn setup_worklane(temp: &TempDir) -> PathBuf { + let worklane = temp.child(".worklane"); + worklane.create_dir_all().unwrap(); + + for dir in ["backlog", "committed", "reviewing", "done"] { + worklane.child(dir).create_dir_all().unwrap(); + } + + worklane.path().to_path_buf() +} + +/// One criterion already ticked, one handwritten line inside the section, and a +/// checkbox in the description that must not be counted as a criterion. +fn create_ticket(worklane: &PathBuf) { + // Written without line continuations on purpose: a trailing `\` strips the next + // line's leading whitespace, so the indented line would arrive unindented and the + // test would prove nothing about preserving it. + let lines = [ + "# Check me", + "", + "## Description", + "- [ ] A checkbox in the description, which is not a criterion.", + "", + "## Acceptance Criteria", + "- [ ] alpha shared", + "- [x] beta alone", + " A handwritten line inside the section.", + "- [ ] gamma shared", + "", + "## Implementation Plan", + "1. Step one", + "", + "## Metadata", + "", + &format!("- **ID**: {}", UUID), + "- **Status**: backlog", + "", + ]; + + fs::write( + worklane.join("backlog").join(format!("{}_check-me.md", UUID)), + lines.join("\n"), + ) + .unwrap(); +} + +fn run(temp: &TempDir, args: &[&str]) -> std::process::Output { + let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); + cmd.current_dir(&temp.path()).args(args); + cmd.assert().get_output().clone() +} + +fn ticket(worklane: &PathBuf) -> String { + fs::read_to_string(worklane.join("backlog").join(format!("{}_check-me.md", UUID))).unwrap() +} + +/// The whole point: one line changes and every other keeps its state. +#[test] +fn check_ticks_one_criterion_by_index() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + + let out = run(&temp, &["check", UUID, "1"]); + assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr)); + + let content = ticket(&worklane); + assert!(content.contains("- [x] alpha shared\n"), "{content}"); + assert!(content.contains("- [x] beta alone\n"), "beta lost its tick: {content}"); + assert!(content.contains("- [ ] gamma shared\n"), "{content}"); +} + +#[test] +fn check_ticks_one_criterion_by_substring() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + + run(&temp, &["check", UUID, "GAMMA"]); + assert!(ticket(&worklane).contains("- [x] gamma shared\n")); +} + +#[test] +fn uncheck_unticks_one_criterion() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + + run(&temp, &["uncheck", UUID, "2"]); + + let content = ticket(&worklane); + assert!(content.contains("- [ ] beta alone\n"), "{content}"); + assert!(content.contains("- [ ] alpha shared\n"), "{content}"); +} + +/// The handwritten line sits between two criteria, so it is the thing most likely to +/// be lost by a rewrite, and it must not take a number either. +#[test] +fn a_handwritten_line_in_the_section_survives_and_is_not_numbered() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + + // gamma is the third criterion even though it is the fourth line of the section + run(&temp, &["check", UUID, "3"]); + + let content = ticket(&worklane); + assert!(content.contains("- [x] gamma shared\n"), "{content}"); + assert!( + content.contains(" A handwritten line inside the section.\n"), + "the handwritten line was lost or reindented: {content}" + ); +} + +/// A checkbox outside the section is not a criterion, so the numbering starts inside it. +#[test] +fn a_checkbox_in_the_description_is_not_a_criterion() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + + run(&temp, &["check", UUID, "1"]); + + let content = ticket(&worklane); + assert!( + content.contains("- [ ] A checkbox in the description, which is not a criterion.\n"), + "the description checkbox was ticked: {content}" + ); +} + +#[test] +fn checking_an_already_checked_criterion_changes_nothing() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + let before = ticket(&worklane); + + let out = run(&temp, &["check", UUID, "2"]); + assert!(out.status.success()); + assert!( + String::from_utf8_lossy(&out.stdout).contains("Already checked"), + "{:?}", + String::from_utf8_lossy(&out.stdout) + ); + assert_eq!(ticket(&worklane), before, "the file was rewritten anyway"); +} + +/// The listed numbers have to be the real ones, or the advice to use the number points +/// at the wrong criterion. alpha and gamma are 1 and 3, never 1 and 2. +#[test] +fn an_ambiguous_substring_lists_the_matches_with_their_real_numbers() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + let before = ticket(&worklane); + + let out = run(&temp, &["check", UUID, "shared"]); + let stderr = String::from_utf8_lossy(&out.stderr); + + assert_eq!(out.status.code(), Some(1)); + assert!(stderr.contains("matches 2 criteria"), "{stderr:?}"); + assert!(stderr.contains("1. [ ] alpha shared"), "{stderr:?}"); + assert!(stderr.contains("3. [ ] gamma shared"), "{stderr:?}"); + assert!(!stderr.contains("2. [ ] gamma"), "renumbered: {stderr:?}"); + assert_eq!(ticket(&worklane), before); +} + +#[test] +fn a_substring_matching_nothing_is_an_error_listing_the_criteria() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + + let out = run(&temp, &["check", UUID, "nowhere"]); + let stderr = String::from_utf8_lossy(&out.stderr); + + assert_eq!(out.status.code(), Some(1)); + assert!(stderr.contains("No criterion"), "{stderr:?}"); + assert!(stderr.contains("1. [ ] alpha shared"), "{stderr:?}"); +} + +/// A number out of range is a bad index, not a substring that happened to miss. +#[test] +fn an_index_out_of_range_says_so() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + + let out = run(&temp, &["check", UUID, "9"]); + let stderr = String::from_utf8_lossy(&out.stderr); + + assert_eq!(out.status.code(), Some(1)); + assert!(stderr.contains("is not one of the 3 criteria"), "{stderr:?}"); +} + +/// No terminal to prompt at, so the list comes back as an error instead. This is the +/// path the opencode wrapper takes, and it must not block on stdin. +#[test] +fn omitting_the_criterion_without_a_terminal_returns_the_list_as_an_error() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + let before = ticket(&worklane); + + let out = run(&temp, &["check", UUID]); + let stderr = String::from_utf8_lossy(&out.stderr); + + assert_eq!(out.status.code(), Some(1)); + assert!(stderr.contains("Which criterion"), "{stderr:?}"); + assert!(stderr.contains("1. [ ] alpha shared"), "{stderr:?}"); + assert!(stderr.contains("2. [x] beta alone"), "{stderr:?}"); + assert!(stderr.contains("3. [ ] gamma shared"), "{stderr:?}"); + assert_eq!(ticket(&worklane), before); +} + +#[test] +fn a_ticket_with_no_criteria_says_so() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + + fs::write( + worklane.join("backlog").join("aaaaaaaa-0000-4000-8000-000000000000_bare.md"), + "# Bare\n\n## Acceptance Criteria\n_No acceptance criteria provided._\n\n## Metadata\n\n- **ID**: aaaaaaaa-0000-4000-8000-000000000000\n- **Status**: backlog\n", + ) + .unwrap(); + + let out = run(&temp, &["check", "aaaaaaaa", "1"]); + assert_eq!(out.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&out.stderr).contains("no acceptance criteria"), + "{:?}", + String::from_utf8_lossy(&out.stderr) + ); +} + +/// show numbers the criteria, so the index check takes is visible where it is read. +#[test] +fn show_numbers_the_criteria() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + + let out = run(&temp, &["show", UUID]); + let stdout = String::from_utf8_lossy(&out.stdout); + + assert!(stdout.contains("1. [ ] alpha shared"), "{stdout:?}"); + assert!(stdout.contains("2. [x] beta alone"), "{stdout:?}"); + assert!(stdout.contains("3. [ ] gamma shared"), "{stdout:?}"); + + // The handwritten line is shown but takes no number + assert!(stdout.contains(" A handwritten line inside the section."), "{stdout:?}"); + assert!(!stdout.contains("4. ["), "the handwritten line was numbered: {stdout:?}"); + + // And the description checkbox is left as it is, outside the numbering + assert!( + stdout.contains("- [ ] A checkbox in the description"), + "{stdout:?}" + ); +} + +#[test] +fn check_leaves_nothing_behind() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_ticket(&worklane); + + run(&temp, &["check", UUID, "1"]); + + let strays: Vec = fs::read_dir(&worklane) + .unwrap() + .filter_map(|e| e.ok()) + .map(|e| e.file_name().into_string().unwrap()) + .filter(|name| { + !["backlog", "committed", "reviewing", "done", "comments"].contains(&name.as_str()) + }) + .collect(); + assert_eq!(strays, Vec::::new()); +}