diff --git a/AGENTS.md b/AGENTS.md index 71710cd..c8f118c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -79,6 +79,19 @@ and this file is for what someone changing worklane's own code needs. - 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 +### Relating Tickets + +- **The Relations section is `relate`'s alone.** `RELATIONS` is in the section table but deliberately out of `section_args`, so `set` and `append` cannot reach it: a relation names a target that has to be resolved to a uuid first, and a prose flag would let an unresolvable line into the one section that is read back by machine. Same rule as Owner and Status, one field one writer +- **`add` does not write the section.** The plan on 4179958 asked for it in the ticket writer; it is out on purpose. A `_No relations._` block in every new ticket is noise in every `show`, and the insertion path has to exist regardless for every ticket written before the section did, so leaving it out means one path that is always exercised rather than two +- **The full uuid is stored, not the seven characters `ls` prints.** It resolves without a scan and cannot turn ambiguous as the board grows. `show` renders the short id and the target's title instead: the file is the machine's copy, the output is the reader's +- **One direction is stored and the inverse is derived.** `blocked by` goes on the gated ticket rather than `blocks` on the blocker, because the gated ticket is the one whose move is refused and whose author knows about the dependency. `relates to` is symmetric and is written once, on whichever end the caller ran it from. `RelationIndex::inbound` finds the far end by scanning, which is what keeps `relate` a single-file write +- **A line in the section that is not a relation is an error naming the ticket**, not a line quietly dropped. Nothing but `relate` writes there, so a bad line means a hand-edited file. The TUI is the deliberate exception: `detail_of` falls back to no block, since one corrupt ticket must not take the whole board down +- **The block is built outside `content_trim` and passed in.** Half of it comes from other tickets and `content_trim` has only the body. It is spliced over the stored lines where the file has the section, and injected ahead of the metadata where it does not, because a ticket that is only pointed at has no section of its own and still has relations to show +- `ensure_section` inserts against `SECTION_ORDER`, before the first following section that is actually in the file, and adds no blank line that was not already there. A handwritten `## Notes` between the plan and the metadata therefore keeps its place, and Metadata is in that list as an anchor rather than as something anything appends to +- **The blocker check runs on every move**, after the already-in-that-status return and behind `force`. An open blocker is a reason not to start and a reason not to finish, and one rule is easier to hold than a table of which transitions care. A move to the status the ticket is already in is not a move, so it is not refused. `-f` now bypasses three rules, which is the right home for it: each one is a deliberate override of something the board would otherwise keep true +- **A blocker that is not on the board warns and allows the move.** Refusing would wedge the ticket with no way out but `-f`, and a uuid nothing carries is a bookkeeping fault rather than a dependency. The refusal names **every** open blocker, since clearing the one that happened to be printed would leave the ticket blocked +- Left out on purpose: removing a relation, which 4179958 assigns to 74904dc, and a blocked marker on the TUI card, which is its own ticket. Nothing on a card is worth a scan of the board per tick until the card is designed for it + ### The Board View - `worklane` with no subcommand and `worklane tui` both open it, the way a bare `frig` does. `Cli::command` is therefore an `Option` - The worklane directory is looked for **before** the terminal, so running outside one gives the usual "No .worklane directory found" rather than a complaint about the tty. Both errors stay reachable and both are testable without a pty diff --git a/Cargo.lock b/Cargo.lock index 43ed466..8b8331a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.10.0" +version = "0.11.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 409940a..95b3d73 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.10.0" +version = "0.11.0" edition = "2024" [dependencies] diff --git a/README.md b/README.md index cdbdcba..0c2a991 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ 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 relate ` | Records an edge to another ticket with `--blocked-by`, `--regression-of` or `--relates-to`, each repeatable. At least one required. Only the ticket named is written; `show` derives the other end by scanning. `mv` refuses to move a ticket blocked by one that is not done, unless `-f` | | `worklane chown ` | Sets the Owner field, the only command that writes it. Free text, checked against nothing. User first and ticket second, after Unix `chown` | | `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 | diff --git a/assets/SKILL.md b/assets/SKILL.md index 211bdff..3edd062 100644 --- a/assets/SKILL.md +++ b/assets/SKILL.md @@ -32,6 +32,9 @@ go straight to `reviewing` and has to be walked through `committed` anyway. Doin front is the same two commands in a more useful order. `-f` allows a backward or skipping move, for correcting a mistake. +A move is also refused while the ticket is blocked by one that is not done yet, see +[Relating tickets](#relating-tickets). + ## Reading the board ``` @@ -105,6 +108,28 @@ resolve as a ticket. `worklane init` creates `.worklane/` with the four status directories, for a repo that has no board yet. +## Relating tickets + +``` +worklane relate 1b78a24 --blocked-by 4179958 # this one waits on that one +worklane relate 1b78a24 --regression-of 6d327df # this one broke that one's fix +worklane relate 1b78a24 --relates-to 7bfb9fc # neighbours, no dependency +``` + +One flag per kind, and each repeats. The ticket comes first and the flag says what it is +to the target, so read the call as a sentence: `relate A --blocked-by B` means A waits +on B. **Only one side is stored**, on the ticket you name, and `show` derives the other +end for the ticket at the far side, so never record both directions. + +`--blocked-by` is enforced: `mv` refuses to move a ticket while a ticket it is blocked by +is not in `done`, whichever move it is, and names every open blocker. `-f` moves it +anyway, beside the backward and skipping moves it already allows. The other two kinds are +reference data and never refuse anything. + +Recording a relation the ticket already holds reports no change. A ticket cannot relate +to itself, and a target that later disappears shows as `_missing_` rather than silently +going away. + ## Search the backlog before filing Run `worklane ls` in the directory the ticket would land in and look for the same issue, @@ -114,9 +139,10 @@ existing ticket will have been written from a different angle. - Already there and still open: add what you learned as a comment, not a second ticket. - Already there and closed, but the issue is back: file a **new** ticket naming the old - id, and say it is a regression. There is no way to reopen one, and moving a done - ticket back would destroy the record of the original fix. -- Related but not the same: file it and reference the neighbour by id. + id, and record it with `relate --regression-of `. There is no way to reopen + one, and moving a done ticket back would destroy the record of the original fix. +- Related but not the same: file it, and record it with `relate --relates-to ` + rather than only mentioning the id in prose. ## Addressing a ticket diff --git a/src/command.rs b/src/command.rs index 5affe98..7a4ba3c 100644 --- a/src/command.rs +++ b/src/command.rs @@ -2,7 +2,7 @@ use clap::Parser; use std::sync::LazyLock; -use crate::util::{PRIORITY_RANGE, priority_legend}; +use crate::util::{PRIORITY_RANGE, RelationKind, priority_legend}; /// clap wants a `&str` with a long enough lifetime, and the legend is built from /// the same ramp the listing uses rather than spelled out a second time. @@ -109,6 +109,9 @@ pub enum Command { /// Add to a section of an existing ticket Append(AppendArgs), + /// Record a relation from one ticket to another + Relate(RelateArgs), + /// Change the owner of a ticket /// /// User first, ticket second, after Unix `chown`. That reverses the ticket-first @@ -280,6 +283,50 @@ pub struct AppendArgs { pub plan: Vec, } +/// `relate` is the only writer of the Relations section, the way `chown` is the only +/// writer of Owner. One flag per kind rather than a `--kind` value: the accepted kinds +/// are then clap's business, an unknown one is a usage error, and a call reads as a +/// sentence about the ticket it names. +/// +/// Each flag repeats, so several relations of one kind land in a single call. The +/// targets are ticket searches, resolved by the same three tiers every other ticket +/// argument is, and stored as the target's uuid. +#[derive(clap::Args)] +#[command(group( + clap::ArgGroup::new("relation_kinds") + .required(true) + .multiple(true) + .args(["blocked_by", "regression_of", "relates_to"]) +))] +pub struct RelateArgs { + /// Ticket UUID or title + pub ticket: String, + + /// Ticket this one waits on. Its own moves are refused until the target is done + #[arg(long, value_parser = non_empty)] + pub blocked_by: Vec, + + /// Ticket whose fix this one broke + #[arg(long, value_parser = non_empty)] + pub regression_of: Vec, + + /// Ticket this one is merely related to. Symmetric, so it is recorded once + #[arg(long, value_parser = non_empty)] + pub relates_to: Vec, +} + +impl RelateArgs { + /// The relations asked for, one entry per kind, so the handler walks a table + /// instead of repeating itself three times. + pub fn requested(&self) -> [(RelationKind, &[String]); 3] { + [ + (RelationKind::BlockedBy, &self.blocked_by), + (RelationKind::RegressionOf, &self.regression_of), + (RelationKind::RelatesTo, &self.relates_to), + ] + } +} + /// `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. diff --git a/src/handlers.rs b/src/handlers.rs index 8af712d..974716c 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -4,7 +4,7 @@ use std::fs; use std::io::{BufRead, IsTerminal, Write}; use std::path::Path; -use crate::command::{AddArgs, AppendArgs, CheckArgs, SetArgs}; +use crate::command::{AddArgs, AppendArgs, CheckArgs, RelateArgs, SetArgs}; use crate::install; use crate::util::*; @@ -302,13 +302,16 @@ fn write_new_comment(comments_dir: &Path, stem: &str, content: &str) -> Result Result<()> { let (_status, title, content) = resolve_ticket(search, worklane_dir)?; let ticket_uuid = parse_ticket_field(&content, "ID"); + // Read before anything is printed, so a board that cannot be read fails instead of + // half printing a ticket. + let relations = relations_block(&content, worklane_dir, should_use_colors())?; // The only title in the output: content_trim_colored used to print it a second // time from the file content. Green per the colour guideline, and the rule is // measured in characters so a non-ASCII title is not over-drawn. println!("{}", color_text(&title, Color::Green)); println!("{}", "─".repeat(title.chars().count())); - println!("\n{}", content_trim_colored(&content)); + println!("\n{}", content_trim_colored(&content, &relations)); if ticket_uuid != "_Not set_" { let comments_dir = worklane_dir.join("comments").join(&ticket_uuid); @@ -434,6 +437,59 @@ fn move_ticket_file( }) } +/// Refuse a move while a ticket it is `blocked by` is not done. +/// +/// Every move, not only the one into committed: an open blocker is a reason not to +/// start and a reason not to finish, and one rule is easier to hold than a table of +/// which transitions care. Called before anything is written, so a refusal leaves no +/// rename, no rewritten field and no half moved ticket. +/// +/// A target the board does not have warns and allows the move. Refusing there would +/// wedge the ticket behind a bookkeeping fault with no way out but `--force`, and a +/// dangling uuid is not a dependency. +fn check_blockers(worklane_dir: &Path, content: &str, title: &str) -> Result<()> { + let blockers: Vec = parse_relations(content, title)? + .into_iter() + .filter(|relation| relation.kind == RelationKind::BlockedBy) + .collect(); + + if blockers.is_empty() { + return Ok(()); + } + + let index = RelationIndex::load(worklane_dir)?; + let mut open: Vec = Vec::new(); + + for blocker in &blockers { + match index.get(&blocker.target) { + Some(target) if target.status == DONE => {} + Some(target) => open.push(format!( + " ({}) {} [{}]", + color_text(short_id(&target.uuid), Color::Red), + target.title, + color_text(&target.status, Color::Orange), + )), + None => eprintln!( + "Warning: ticket '{}' is blocked by {}, which is not on the board.", + title, + short_id(&blocker.target), + ), + } + } + + if open.is_empty() { + return Ok(()); + } + + // Every open blocker, not the first: a ticket waiting on three of them is not + // unblocked by clearing the one the message happened to name. + Err(anyhow!( + "Cannot move '{}' while it is blocked by:\n{}\nUse --force (-f) to move it anyway.", + color_text(title, Color::Green), + open.join("\n"), + )) +} + pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -> Result<()> { let valid_statuses = ["backlog", "committed", "reviewing", "done"]; let forward_order = ["backlog", "committed", "reviewing", "done"]; @@ -480,6 +536,13 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) - return Ok(()); } + // After the no-op above, so a ticket is never refused for a move it is not making, + // and behind `force`, which is where the other two overrides of a rule the board + // keeps true already live. + if !force { + check_blockers(&worklane_dir, &resolved, &title)?; + } + let current_path = worklane_dir.join(¤t_status); let target_path = worklane_dir.join(target_status); @@ -750,6 +813,76 @@ pub fn cmd_append(args: &AppendArgs, start: &Path) -> Result<()> { Ok(()) } +/// Record a relation from one ticket to another. +/// +/// One side is written and the inverse is derived wherever it is shown. `blocked by` +/// goes on the gated ticket rather than `blocks` on the blocker: the gated ticket is the +/// one whose move is refused and whose author knows about the dependency. `relates to` +/// is symmetric, so it is written once, on whichever end the caller ran it from. +/// +/// The kinds are a flag each rather than a `--kind` value, so an unknown kind is a +/// usage error at the door instead of a line written into the file and refused on the +/// way back out. +pub fn cmd_relate(args: &RelateArgs, start: &Path) -> Result<()> { + let worklane_dir = find_worklane_dir(start)?; + let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?; + let uuid = parse_ticket_field(&original, "ID"); + let existing = parse_relations(&original, &title)?; + + // Every target resolved and every refusal raised before a byte is written, so a + // call naming one good ticket and one bad one records neither. + let mut items: Vec = Vec::new(); + let mut changed: Vec<&str> = Vec::new(); + + for (kind, targets) in args.requested() { + for search in targets { + let (_target_status, target_title, target) = resolve_ticket(search, &worklane_dir)?; + let target_uuid = parse_ticket_field(&target, "ID"); + + if target_uuid.trim().is_empty() || is_unknown_value(&target_uuid) { + return Err(anyhow!( + "Ticket '{}' has no ID field, so nothing can point at it", + target_title + )); + } + + if target_uuid == uuid { + return Err(anyhow!( + "A ticket cannot relate to itself, and '{}' is the ticket being edited", + title + )); + } + + let relation = Relation { + kind, + target: target_uuid, + }; + + // Already held, either in the file or earlier in this call. Recording it + // twice would read as two dependencies on one ticket. + if existing.contains(&relation) || items.contains(&relation.item()) { + continue; + } + + items.push(relation.item()); + if !changed.contains(&kind.label()) { + changed.push(kind.label()); + } + } + } + + if items.is_empty() { + report(&[], &title, "Recorded"); + return Ok(()); + } + + let content = append_section_body(&ensure_section(&original, &RELATIONS), &RELATIONS, &items)?; + save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?; + + report(&changed, &title, "Recorded"); + 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 diff --git a/src/main.rs b/src/main.rs index ed1f2bc..c560de7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -59,6 +59,7 @@ fn main() -> Result<()> { }) => cmd_mv(&ticket, &status, force, &start), Some(Command::Set(args)) => cmd_set(&args, &start), Some(Command::Append(args)) => cmd_append(&args, &start), + Some(Command::Relate(args)) => cmd_relate(&args, &start), Some(Command::Chown { user, ticket }) => cmd_chown(&user, &ticket, &start), Some(Command::Check(args)) => cmd_check(&args, true, &start), Some(Command::Uncheck(args)) => cmd_check(&args, false, &start), diff --git a/src/tui.rs b/src/tui.rs index 95ac00e..89350bd 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -501,16 +501,25 @@ impl Board { fn detail_of(card: &Card) -> Detail { let ticket = &card.ticket; let content = std::fs::read_to_string(&ticket.path).unwrap_or_default(); - let mut out = content_trim(&content, false); - let uuid = parse_ticket_field(&content, "ID"); - let comments = match ticket.path.parent().and_then(|status| status.parent()) { + let worklane_dir = ticket.path.parent().and_then(|status| status.parent()); + + // Both of these read the tree beside the ticket, and both fall back to nothing: one + // unreadable file must not take the board down with it. The relations cost a scan of + // the board, paid only while a ticket is open and only on a tick that changed + // something, which is what already reloads every card. + let relations = worklane_dir + .and_then(|dir| relations_block(&content, dir, false).ok()) + .unwrap_or_default(); + let comments = match worklane_dir { Some(worklane_dir) => { read_comments(&worklane_dir.join("comments").join(&uuid)).unwrap_or_default() } None => Vec::new(), }; + let mut out = content_trim(&content, false, &relations); + out.push('\n'); out.push_str(&format_comments_with(&comments, false)); Detail { @@ -2666,4 +2675,73 @@ mod tests { } + + /// The detail view is the second renderer of a ticket body, so it resolves a + /// relation the way `show` does rather than printing the uuid the file stores. + /// + /// The section goes in `extra`, after the metadata, which is not where `relate` + /// writes it. Position is the CLI's test to make; this one is about the lookup. + #[test] + fn the_detail_view_resolves_a_relation_to_a_title() { + let dir = board_dir(); + let target = "22222222-0000-4000-8000-000000000000"; + write_ticket(&dir, "backlog", target, "The target", ""); + write_ticket( + &dir, + "backlog", + "11111111-0000-4000-8000-000000000000", + "A holder", + &format!("\n## Relations\n- blocked by {target}\n"), + ); + + let mut board = one_board(&dir); + board.toggle_detail(); + + let text = &board.detail.as_ref().expect("no detail").text; + assert!(text.contains("blocked by (2222222) The target"), "{text:?}"); + assert!(!text.contains(target), "the bare uuid was drawn: {text:?}"); + } + + /// The far end of a relation stores nothing, so the board derives it too. + #[test] + fn the_detail_view_derives_the_other_end() { + let dir = board_dir(); + let holder = "11111111-0000-4000-8000-000000000000"; + write_ticket( + &dir, + "backlog", + holder, + "A holder", + "\n## Relations\n- blocked by 22222222-0000-4000-8000-000000000000\n", + ); + write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "The target", ""); + + let mut board = one_board(&dir); + // The holder sorts first by title, so the target is the card below it. + board.select_card(1, SCREEN); + board.toggle_detail(); + + let text = &board.detail.as_ref().expect("no detail").text; + assert!(text.contains("blocks (1111111) A holder"), "{text:?}"); + } + + /// The CLI refuses a relations line it cannot read, naming the ticket. The board + /// cannot: one hand-edited file must not take every other card down with it. + #[test] + fn a_relations_line_that_cannot_be_read_still_draws_the_ticket() { + let dir = board_dir(); + write_ticket( + &dir, + "backlog", + "11111111-0000-4000-8000-000000000000", + "A holder", + "\n## Relations\n- depends on 22222222-0000-4000-8000-000000000000\n", + ); + + let mut board = one_board(&dir); + board.toggle_detail(); + + let text = &board.detail.as_ref().expect("no detail").text; + assert!(text.contains("A description."), "the body was lost: {text:?}"); + } } diff --git a/src/util.rs b/src/util.rs index 59b2819..5e63fbd 100644 --- a/src/util.rs +++ b/src/util.rs @@ -236,6 +236,15 @@ fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyh /// `ls` shows [`SHORT_ID_WIDTH`] characters, and pasting that back has to resolve. pub const MIN_ID_SEARCH: usize = 4; +/// The ticket's title, from the first `# ` heading, or empty when it has none. +fn heading_title(content: &str) -> String { + content + .lines() + .find(|line| line.starts_with("# ")) + .map(|line| line[2..].trim().to_string()) + .unwrap_or_default() +} + pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> { let search_lower = search.to_lowercase(); let long_enough_for_an_id = search.chars().count() >= MIN_ID_SEARCH; @@ -263,12 +272,7 @@ pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, Stri Ok(c) => c, Err(_) => continue, }; - let title = content - .lines() - .find(|l| l.starts_with("# ")) - .map(|l| l[2..].trim()) - .unwrap_or("") - .to_string(); + let title = heading_title(&content); let filename = path .file_stem() .map(|s| s.to_string_lossy().to_string()) @@ -343,47 +347,88 @@ pub fn format_comments_with( result } -pub fn content_trim_colored(content: &str) -> String { - content_trim(content, should_use_colors()) +pub fn content_trim_colored(content: &str, relations: &str) -> String { + content_trim(content, should_use_colors(), relations) +} + +/// A section heading, its rule, and the blank line the body opens under. +/// +/// The rule is measured on the name as displayed, in characters. It used to span the +/// raw line, so it ran three past the heading for the `## `, and byte length over-drew +/// anything non-ASCII. +fn push_heading(out: &mut String, heading: &str, colored: bool) { + let name = heading.strip_prefix("## ").unwrap_or(heading); + + out.push_str(&paint(name, Color::Orange, colored)); + out.push('\n'); + out.push_str(&"─".repeat(name.chars().count())); + out.push('\n'); + out.push('\n'); } /// The ticket body rendered for display, with the colour decision passed in. /// /// The TUI needs the plain form: ratatui draws styled spans, and an escape sequence /// embedded in a paragraph would be printed as literal bytes. -pub fn content_trim(content: &str, colored: bool) -> String { +/// +/// `relations` is the block [`relations_block`] built, or empty. It is passed in rather +/// than derived here because half of it comes from other tickets: the section stores +/// one side of each edge and bare uuids for its targets, so the body alone cannot say +/// what a relation points at, nor that anything points back. +pub fn content_trim(content: &str, colored: bool, relations: &str) -> String { let lines: Vec<&str> = content.trim().lines().collect(); let mut result = String::new(); let mut current_section = ""; let mut criterion = 0; let mut i = 0; + // Whether the file keeps the section, which decides whether the block is spliced + // into it or injected ahead of the metadata. + let stores_relations = section_body(&lines, RELATIONS.heading).is_some(); + let mut shown_relations = false; + while i < lines.len() { let line = lines[i]; // Track current section if let Some(section_name) = line.strip_prefix("## ") { current_section = line; - result.push_str(&paint(section_name, Color::Orange, colored)); - result.push('\n'); - // Measured on the name as displayed, in characters. The rule used to span - // the raw line, so it ran three past the heading for the "## ", and byte - // length over-drew for anything non-ASCII. - result.push_str(&"─".repeat(section_name.chars().count())); - result.push('\n'); - result.push('\n'); + + // Only one side of a relation is stored, so a ticket nothing points at has + // no Relations section and still has relations to show. Injected where the + // file would have kept it, ahead of the metadata, rather than tacked on + // after everything. + if is_metadata_heading(line) && !stores_relations && !relations.is_empty() { + push_heading(&mut result, RELATIONS.heading, colored); + result.push_str(relations); + result.push('\n'); + shown_relations = true; + } + + push_heading(&mut result, section_name, colored); i += 1; // Metadata is rendered as a block, so it is consumed here rather than // falling through to the line-at-a-time cases below. if is_metadata_heading(line) { - let end = lines[i..] - .iter() - .position(|l| l.starts_with("## ")) - .map_or(lines.len(), |offset| i + offset); + let end = section_end(&lines, i); result.push_str(&render_metadata_table(&lines[i..end], colored)); i = end; } + + // As is Relations, whose stored lines carry a bare uuid each. The block + // holds the same edges resolved to a title, and the inverses with them. + if line.trim_end() == RELATIONS.heading && !relations.is_empty() { + let end = section_end(&lines, i); + result.push_str(relations); + // The blank line the skipped body ended with, before the next heading. + if end < lines.len() { + result.push('\n'); + } + i = end; + shown_relations = true; + } + continue; } @@ -451,6 +496,16 @@ pub fn content_trim(content: &str, colored: bool) -> String { result.push('\n'); } + // A ticket with neither a Relations section nor a Metadata heading has nothing for + // the block to be injected ahead of, so it goes at the end rather than being lost. + if !relations.is_empty() && !shown_relations { + if !result.ends_with("\n\n") { + result.push('\n'); + } + push_heading(&mut result, RELATIONS.heading, colored); + result.push_str(relations); + } + result } @@ -485,8 +540,9 @@ fn colorize_ordered(line: &str, colored: bool) -> String { line.to_string() } -/// Space between the field column and the value column. -const METADATA_GUTTER: &str = " "; +/// Space between a label column and the value beside it, in the metadata table and in +/// the relations block. +const COLUMN_GUTTER: &str = " "; /// One line of the Metadata section, as the table sees it. enum MetadataRow<'a> { @@ -561,7 +617,7 @@ fn render_metadata_table(lines: &[&str], colored: bool) -> String { MetadataRow::Field { name, value } => { result.push_str(&paint(name, Color::Red, colored)); result.push_str(&" ".repeat(field_width - name.chars().count())); - result.push_str(METADATA_GUTTER); + result.push_str(COLUMN_GUTTER); result.push_str(&metadata_value_cell(name, value, colored)); } // The decision this row is rendered under, not the one the terminal @@ -778,6 +834,8 @@ pub enum SectionKind { Checklist, /// One `N. ` step per line. Numbered, + /// One `- ` item per line, unnumbered, with no blank line between items. + Bullets, } /// A section of a ticket whose body `set` and `append` can rewrite. @@ -816,6 +874,19 @@ pub const PLAN: Section = Section { kind: SectionKind::Numbered, }; +/// The edges to other tickets, one per line. +/// +/// Deliberately absent from `section_args`, so `set` and `append` cannot write it: a +/// relation names a target that has to be resolved to a uuid first, and a prose flag +/// would let an unresolvable line into the one section that is read back by machine. +/// `relate` is its only writer, the way `chown` is the only writer of Owner. +pub const RELATIONS: Section = Section { + heading: "## Relations", + label: "relations", + placeholder: "_No relations._", + kind: SectionKind::Bullets, +}; + impl Section { /// The values a caller supplied, reduced to the lines that belong in the body. /// @@ -824,7 +895,7 @@ impl Section { pub fn normalise(&self, values: &[String]) -> Vec { match self.kind { SectionKind::Prose => trim_blank_ends(values).to_vec(), - SectionKind::Checklist | SectionKind::Numbered => values + SectionKind::Checklist | SectionKind::Numbered | SectionKind::Bullets => values .iter() .filter(|value| !value.trim().is_empty()) .cloned() @@ -837,6 +908,7 @@ impl Section { match self.kind { SectionKind::Prose => items.to_vec(), SectionKind::Checklist => items.iter().map(|i| format!("- [ ] {}", i)).collect(), + SectionKind::Bullets => items.iter().map(|i| format!("- {}", i)).collect(), SectionKind::Numbered => items .iter() .enumerate() @@ -853,17 +925,22 @@ fn is_numbered_item(line: &str) -> bool { digits > 0 && line[digits..].starts_with(". ") } +/// Where the section whose body starts at `from` ends: the next `## ` heading, or the +/// end of the file. +fn section_end(lines: &[&str], from: usize) -> usize { + lines[from..] + .iter() + .position(|line| line.starts_with("## ")) + .map_or(lines.len(), |offset| from + offset) +} + /// The lines of a section's body, excluding the heading, running to the next `## ` /// heading or the end of the file. fn section_body(lines: &[&str], heading: &str) -> Option> { let at = lines.iter().position(|line| line.trim_end() == heading)?; let after = at + 1; - let end = lines[after..] - .iter() - .position(|line| line.starts_with("## ")) - .map_or(lines.len(), |offset| after + offset); - Some(after..end) + Some(after..section_end(lines, after)) } /// Where the body's content ends, ignoring the blank lines that separate it from @@ -936,6 +1013,334 @@ pub fn append_section_body(content: &str, section: &Section, items: &[String]) - Ok(join_lines(&out)) } +/// The order the tool's own sections sit in a ticket file. +/// +/// Relations goes between the plan and the metadata: it is reference data rather than +/// the prose a reader needs first. Metadata is in the list as the anchor a missing +/// section is inserted against, not as a section anything appends to. +const SECTION_ORDER: [&str; 5] = [ + DESCRIPTION.heading, + ACCEPTANCE.heading, + PLAN.heading, + RELATIONS.heading, + METADATA_HEADING, +]; + +/// `content` with `section` present, empty, and in its place when it was absent. +/// +/// Inserted before the first section that follows it in [`SECTION_ORDER`] and is +/// actually in the file, so a ticket written before the section existed gains it +/// without being regenerated: a handwritten `## Notes` in between keeps its place, and +/// so does every blank line already there. +pub fn ensure_section(content: &str, section: &Section) -> String { + let lines: Vec<&str> = content.lines().collect(); + if section_body(&lines, section.heading).is_some() { + return content.to_string(); + } + + let at = SECTION_ORDER + .iter() + .skip_while(|heading| **heading != section.heading) + .skip(1) + .filter_map(|heading| lines.iter().position(|line| line.trim_end() == *heading)) + .min() + .unwrap_or(lines.len()); + + let mut out: Vec = lines[..at].iter().map(|l| l.to_string()).collect(); + // The template separates sections with one blank line. Whatever is already there + // is left as it is, and the line is only added when there is none. + if out.last().is_some_and(|line| !line.trim().is_empty()) { + out.push(String::new()); + } + out.push(section.heading.to_string()); + out.push(section.placeholder.to_string()); + if at < lines.len() { + out.push(String::new()); + } + out.extend(lines[at..].iter().map(|l| l.to_string())); + + join_lines(&out) +} + +// ------------------------------------------------------------------- relations -- + +/// The kinds of edge one ticket can record to another. +/// +/// Three, and none of them carries prose of its own: that is what separates a relation +/// from a campaign, 7bfb9fc, which is a container with a description and a definition +/// of done. No label is a prefix of another, so a stored line parses unambiguously. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RelationKind { + BlockedBy, + RegressionOf, + RelatesTo, +} + +impl RelationKind { + /// How the kind is written into the file and printed back. + pub fn label(self) -> &'static str { + match self { + RelationKind::BlockedBy => "blocked by", + RelationKind::RegressionOf => "regression of", + RelationKind::RelatesTo => "relates to", + } + } + + /// How the kind reads from the other end, where nothing is stored. + /// + /// `relates to` is its own inverse: the relation is symmetric, and the only thing + /// that differs between the two ends is which file happens to hold the line. + pub fn inverse_label(self) -> &'static str { + match self { + RelationKind::BlockedBy => "blocks", + RelationKind::RegressionOf => "regressed by", + RelationKind::RelatesTo => "relates to", + } + } + + /// Every kind, so a caller can walk them without listing them a second time. + pub const ALL: [RelationKind; 3] = [ + RelationKind::BlockedBy, + RelationKind::RegressionOf, + RelationKind::RelatesTo, + ]; +} + +/// One stored edge: a kind, and the full uuid of the ticket it points at. +/// +/// The full uuid, not the seven characters `ls` prints. Longer to read in the file, but +/// it resolves without a scan and cannot turn ambiguous as the board grows. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Relation { + pub kind: RelationKind, + pub target: String, +} + +impl Relation { + /// The body line as the section stores it, without the list marker. + pub fn item(&self) -> String { + format!("{} {}", self.kind.label(), self.target) + } +} + +/// One relation from a body line, or an error naming what could not be read. +fn parse_relation(line: &str) -> Result { + let body = line.trim(); + let body = body.strip_prefix("- ").unwrap_or(body).trim(); + + for kind in RelationKind::ALL { + if let Some(target) = body.strip_prefix(kind.label()) { + let target = target.trim(); + if target.is_empty() { + return Err(anyhow!("relation '{}' names no target", body)); + } + + return Ok(Relation { + kind, + target: target.to_string(), + }); + } + } + + Err(anyhow!( + "'{}' is not a relation. The kinds are {}", + body, + RelationKind::ALL + .iter() + .map(|kind| kind.label()) + .collect::>() + .join(", ") + )) +} + +/// The relations a ticket stores, in the order they are written. +/// +/// A line in the section that is not a relation is an error, not a line quietly +/// dropped. The section is the one part of a ticket that is read back by machine, and +/// an edge nobody can read is worse than a refusal to read the ticket. Nothing but +/// `relate` writes it, so a bad line means the file was edited by hand. +pub fn parse_relations(content: &str, title: &str) -> Result> { + let lines: Vec<&str> = content.lines().collect(); + let Some(body) = section_body(&lines, RELATIONS.heading) else { + return Ok(Vec::new()); + }; + + lines[body] + .iter() + .filter(|line| !line.trim().is_empty() && line.trim() != RELATIONS.placeholder) + .map(|line| parse_relation(line).map_err(|e| anyhow!("Ticket '{}': {}", title, e))) + .collect() +} + +/// A ticket as the other end of a relation sees it. +pub struct RelatedTicket { + pub uuid: String, + pub title: String, + /// The directory it sits in, which is what decides whether a blocker is still open. + pub status: String, + /// The relations it stores, and therefore where an inverse is derived from. + pub relations: Vec, +} + +/// Every ticket on the board with the relations it stores, read in one pass. +/// +/// One side of a relation is stored and the other is derived, so anything that shows or +/// checks one has to look at every ticket. Read once here rather than per edge: a +/// lookup per relation would walk the whole tree once for each line. +pub struct RelationIndex { + tickets: Vec, +} + +impl RelationIndex { + /// The index over a list of tickets already read, so a test can build one without + /// a tree and `load` has one place that decides what the type holds. + pub fn new(tickets: Vec) -> Self { + Self { tickets } + } + + pub fn load(worklane_dir: &Path) -> Result { + let mut tickets = Vec::new(); + + for status in status_dirs() { + let status_path = worklane_dir.join(status); + if !status_path.exists() { + continue; + } + + for entry in fs::read_dir(&status_path)? { + let path = entry?.path(); + if !path.extension().is_some_and(|e| e == "md") { + continue; + } + let Ok(content) = fs::read_to_string(&path) else { + continue; + }; + + let title = heading_title(&content); + tickets.push(RelatedTicket { + uuid: parse_ticket_field(&content, "ID"), + relations: parse_relations(&content, &title)?, + title, + status: status.to_string(), + }); + } + } + + Ok(Self::new(tickets)) + } + + /// The ticket carrying `uuid`, or nothing when the board no longer has it. + pub fn get(&self, uuid: &str) -> Option<&RelatedTicket> { + self.tickets.iter().find(|ticket| ticket.uuid == uuid) + } + + /// The relations other tickets hold pointing at `uuid`, as the kind reads from + /// this end and the ticket that holds it. + /// + /// A uuid the file does not carry matches nothing: without the guard every ticket + /// with no ID field would relate to every other one that has none either. + pub fn inbound(&self, uuid: &str) -> Vec<(RelationKind, &RelatedTicket)> { + if uuid.trim().is_empty() || is_unknown_value(uuid) { + return Vec::new(); + } + + self.tickets + .iter() + .filter(|holder| holder.uuid != uuid) + .flat_map(|holder| { + holder + .relations + .iter() + .filter(|relation| relation.target == uuid) + .map(move |relation| (relation.kind, holder)) + }) + .collect() + } +} + +/// A relation's target as it reads: the short id, then the title. +/// +/// `_missing_` rather than a bare uuid for a target the board no longer has. The id is +/// kept either way, since it is the only thing left to go looking for. +fn target_cell(target: Option<&RelatedTicket>, uuid: &str, colored: bool) -> String { + let id = paint(short_id(uuid), Color::Red, colored); + + match target { + Some(ticket) => format!("({}) {}", id, ticket.title), + None => format!("({}) {}", id, paint("_missing_", Color::Grey, colored)), + } +} + +/// The Relations section as it is shown, or empty when there is nothing to show. +/// +/// Both directions, stored first: the relations the ticket holds, then the ones held +/// against it, named from this end. Rendered from the index rather than from the body +/// alone, because a bare uuid says nothing and half the relations are not in the file. +pub fn render_relations( + stored: &[Relation], + index: &RelationIndex, + uuid: &str, + colored: bool, +) -> String { + let mut rows: Vec<(&'static str, String)> = stored + .iter() + .map(|relation| { + ( + relation.kind.label(), + target_cell(index.get(&relation.target), &relation.target, colored), + ) + }) + .collect(); + + rows.extend(index.inbound(uuid).into_iter().map(|(kind, holder)| { + ( + kind.inverse_label(), + target_cell(Some(holder), &holder.uuid, colored), + ) + })); + + if rows.is_empty() { + return String::new(); + } + + // Measured on the labels, which carry no colour, and padded before the target cell + // is joined on, for the reason the metadata table is: an escape sequence counted + // towards a width tilts the column the moment colour is on. + let width = rows + .iter() + .map(|(label, _)| label.chars().count()) + .max() + .unwrap_or(0); + + let mut out = String::new(); + for (label, cell) in &rows { + out.push_str(label); + out.push_str(&" ".repeat(width - label.chars().count())); + out.push_str(COLUMN_GUTTER); + out.push_str(cell); + out.push('\n'); + } + + out +} + +/// The rendered Relations block for one ticket, reading the board for the rest of it. +/// +/// The colour decision is passed in rather than asked for, like everything else the +/// body renders: the board draws the same text with colour off. +pub fn relations_block(content: &str, worklane_dir: &Path, colored: bool) -> Result { + let title = heading_title(content); + let stored = parse_relations(content, &title)?; + let index = RelationIndex::load(worklane_dir)?; + + Ok(render_relations( + &stored, + &index, + &parse_ticket_field(content, "ID"), + colored, + )) +} + /// 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. @@ -1307,11 +1712,10 @@ pub fn collect_ticket_items(status_path: impl AsRef) -> Result "_No title_".to_string(), + title => title, + }; let owner = parse_ticket_field(&content, "Owner"); let due = parse_ticket_field(&content, "Due"); let filename = e.path().file_stem()?.to_string_lossy().to_string(); @@ -1632,7 +2036,7 @@ mod tests { /// is no place for an escape sequence, and two paths asked the terminal instead. #[test] fn the_body_carries_no_escape_when_the_colour_is_off() { - let rendered = content_trim(BOTH_LEAKS, false); + let rendered = content_trim(BOTH_LEAKS, false, ""); assert!( !rendered.contains('\x1b'), @@ -1648,7 +2052,7 @@ mod tests { /// could be a colouring path that was simply deleted. #[test] fn the_body_colours_the_plan_number_and_a_metadata_note_when_the_colour_is_on() { - let rendered = content_trim(BOTH_LEAKS, true); + let rendered = content_trim(BOTH_LEAKS, true, ""); assert!( rendered.contains(&format!("{}1.", Color::Cyan.ansi())), @@ -1750,7 +2154,7 @@ mod tests { #[test] fn a_section_rule_matches_the_width_of_its_name() { - let rendered = content_trim_colored("# T\n\n## Description\nbody\n"); + let rendered = content_trim_colored("# T\n\n## Description\nbody\n", ""); // Eleven characters, not fourteen: the rule used to span "## Description" assert!( @@ -1761,14 +2165,14 @@ mod tests { #[test] fn a_non_ascii_section_name_is_not_over_drawn() { - let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n"); + let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n", ""); assert!(rendered.starts_with("Résumé\n──────\n"), "{rendered:?}"); } #[test] fn the_body_leaves_the_title_to_cmd_show() { - let rendered = content_trim_colored("# Only Once\n\n## Description\nbody\n"); + let rendered = content_trim_colored("# Only Once\n\n## Description\nbody\n", ""); assert!(!rendered.contains("Only Once"), "{rendered:?}"); // And no gap where it was @@ -1778,7 +2182,7 @@ mod tests { #[test] fn the_metadata_section_renders_as_a_table_inside_the_body() { let content = "# T\n\n## Metadata\n\n- **ID**: abc\n- **Owner**: alice\n"; - let rendered = content_trim_colored(content); + let rendered = content_trim_colored(content, ""); assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n"); } @@ -1786,7 +2190,7 @@ mod tests { #[test] fn a_section_after_metadata_still_renders() { let content = "# T\n\n## Metadata\n\n- **ID**: abc\n\n## Notes\n\nafter\n"; - let rendered = content_trim_colored(content); + let rendered = content_trim_colored(content, ""); assert!(rendered.contains("ID abc"), "{rendered:?}"); assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}"); @@ -2058,4 +2462,221 @@ mod tests { assert_eq!(format_created_at(value), "", "for {value:?}"); } } + // --------------------------------------------------------------- relations -- + + const TARGET: &str = "b1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d"; + const SELF: &str = "641e3d5c-1b0e-4d2f-9a7e-3c8b5f0a2d61"; + + fn related(uuid: &str, title: &str, status: &str, relations: Vec) -> RelatedTicket { + RelatedTicket { + uuid: uuid.to_string(), + title: title.to_string(), + status: status.to_string(), + relations, + } + } + + fn relation(kind: RelationKind, target: &str) -> Relation { + Relation { + kind, + target: target.to_string(), + } + } + + #[test] + fn a_stored_line_parses_back_into_the_relation_that_wrote_it() { + for kind in RelationKind::ALL { + let stored = format!("- {}", relation(kind, TARGET).item()); + assert_eq!(parse_relation(&stored).unwrap(), relation(kind, TARGET)); + } + } + + /// No label is a prefix of another, so the longer kind cannot be read as a shorter + /// one with a target that starts with the rest of its name. + #[test] + fn no_kind_label_is_a_prefix_of_another() { + for kind in RelationKind::ALL { + for other in RelationKind::ALL { + assert!( + kind == other || !other.label().starts_with(kind.label()), + "{} is a prefix of {}", + kind.label(), + other.label() + ); + } + } + } + + /// An unreadable line is an error naming the kinds, not a line quietly dropped: + /// the section is the one part of a ticket that is read back by machine. + #[test] + fn a_line_that_is_not_a_relation_is_refused() { + let error = parse_relation("- depends on abc").unwrap_err().to_string(); + assert!(error.contains("is not a relation"), "{error}"); + assert!(error.contains("blocked by"), "{error}"); + + assert!(parse_relation("- blocked by").unwrap_err().to_string().contains("no target")); + } + + #[test] + fn the_placeholder_is_no_relations_rather_than_a_bad_line() { + let content = format!( + "# T\n\n## Relations\n{}\n\n## Metadata\n\n- **ID**: x\n", + RELATIONS.placeholder + ); + assert_eq!(parse_relations(&content, "T").unwrap(), Vec::new()); + } + + #[test] + fn a_ticket_with_no_relations_section_has_none() { + assert_eq!( + parse_relations("# T\n\n## Metadata\n\n- **ID**: x\n", "T").unwrap(), + Vec::new() + ); + } + + /// Between the plan and the metadata, and only once: a second call is a no-op + /// rather than a second heading. + #[test] + fn the_section_is_inserted_before_the_metadata() { + let content = "# T\n\n## Implementation Plan\n1. Step\n\n## Metadata\n\n- **ID**: x\n"; + let inserted = ensure_section(content, &RELATIONS); + + assert_eq!( + inserted, + "# T\n\n## Implementation Plan\n1. Step\n\n## Relations\n_No relations._\n\n## Metadata\n\n- **ID**: x\n" + ); + assert_eq!(ensure_section(&inserted, &RELATIONS), inserted); + } + + /// The anchor is the metadata, not the plan, so a section the tool knows nothing + /// about keeps its place instead of being pushed down. + #[test] + fn an_unknown_section_between_the_two_keeps_its_place() { + let content = "# T\n\n## Implementation Plan\n1. Step\n\n## Notes\nBy hand.\n\n## Metadata\n\n- **ID**: x\n"; + let inserted = ensure_section(content, &RELATIONS); + + assert!( + inserted.contains("## Notes\nBy hand.\n\n## Relations\n_No relations._\n\n## Metadata"), + "{inserted}" + ); + } + + /// Nothing to insert in front of, so it goes at the end rather than nowhere. + #[test] + fn the_section_lands_at_the_end_when_nothing_follows_it() { + assert_eq!( + ensure_section("# T\n\n## Description\nBody.\n", &RELATIONS), + "# T\n\n## Description\nBody.\n\n## Relations\n_No relations._\n" + ); + } + + /// Both directions in one block, the stored edges first, each padded to the widest + /// label. `relates to` is symmetric, so it reads the same from either end. + #[test] + fn the_block_renders_both_directions() { + let index = RelationIndex::new(vec![ + related(TARGET, "The blocker", "backlog", Vec::new()), + related( + "cccccccc-1111-4222-8333-444444444444", + "The other one", + "reviewing", + vec![ + relation(RelationKind::BlockedBy, SELF), + relation(RelationKind::RelatesTo, SELF), + ], + ), + ]); + let stored = vec![relation(RelationKind::RegressionOf, TARGET)]; + + assert_eq!( + render_relations(&stored, &index, SELF, false), + "regression of (b1b2c3d) The blocker\n\ + blocks (ccccccc) The other one\n\ + relates to (ccccccc) The other one\n" + ); + } + + /// The id is kept, since it is the only thing left to go looking for, and the title + /// is `_missing_` rather than a bare uuid pretending to be one. + #[test] + fn a_target_the_board_does_not_have_renders_as_missing() { + let stored = vec![relation(RelationKind::BlockedBy, TARGET)]; + + assert_eq!( + render_relations(&stored, &RelationIndex::new(Vec::new()), SELF, false), + "blocked by (b1b2c3d) _missing_\n" + ); + } + + #[test] + fn a_ticket_with_no_relations_at_either_end_renders_no_block() { + let index = RelationIndex::new(vec![related(TARGET, "Elsewhere", "backlog", Vec::new())]); + assert_eq!(render_relations(&[], &index, SELF, false), ""); + } + + /// Without the guard every ticket with no ID field relates to every other one that + /// has none either, since `_Not set_` matches `_Not set_`. + #[test] + fn a_ticket_with_no_id_derives_no_inverse() { + let index = RelationIndex::new(vec![related( + TARGET, + "The holder", + "backlog", + vec![relation(RelationKind::BlockedBy, "_Not set_")], + )]); + + assert!(index.inbound("_Not set_").is_empty()); + assert!(index.inbound("").is_empty()); + } + + /// The stored lines carry a bare uuid, so the block replaces the body rather than + /// being printed beside it. + #[test] + fn the_body_shows_the_block_in_place_of_the_stored_lines() { + let content = format!( + "# T\n\n## Relations\n- blocked by {}\n\n## Metadata\n\n- **ID**: {}\n", + TARGET, SELF + ); + let rendered = content_trim(&content, false, "blocked by (b1b2c3d) The blocker\n"); + + assert!( + rendered.contains("Relations\n─────────\n\nblocked by (b1b2c3d) The blocker\n\nMetadata"), + "{rendered:?}" + ); + assert!(!rendered.contains(TARGET), "the bare uuid was printed: {rendered:?}"); + } + + /// Only one side of a relation is stored, so the ticket at the other end has no + /// section at all and still has something to show. It goes where the file would + /// have kept it, ahead of the metadata. + #[test] + fn the_body_injects_the_block_when_the_file_has_no_section() { + let content = format!("# T\n\n## Description\nBody.\n\n## Metadata\n\n- **ID**: {}\n", SELF); + let rendered = content_trim(&content, false, "blocks (641e3d5) The gated one\n"); + + assert!( + rendered.contains("Body.\n\nRelations\n─────────\n\nblocks (641e3d5) The gated one\n\nMetadata"), + "{rendered:?}" + ); + } + + /// A file with no metadata heading has nothing to inject ahead of, and the block is + /// worth more at the end than dropped. + #[test] + fn the_body_appends_the_block_when_there_is_no_metadata() { + let rendered = content_trim("# T\n\n## Description\nBody.\n", false, "blocks (641e3d5) X\n"); + + assert!(rendered.ends_with("Relations\n─────────\n\nblocks (641e3d5) X\n"), "{rendered:?}"); + } + + /// No block and a section holding only its placeholder: the section renders as it + /// is written, the way every other empty section does. + #[test] + fn an_empty_block_leaves_the_section_as_written() { + let content = "# T\n\n## Relations\n_No relations._\n\n## Metadata\n\n- **ID**: x\n"; + let rendered = content_trim(content, false, ""); + + assert!(rendered.contains("Relations\n─────────\n\n_No relations._\n"), "{rendered:?}"); + } } diff --git a/tests/cmd_mv.rs b/tests/cmd_mv.rs index 2e51378..4b57ff1 100644 --- a/tests/cmd_mv.rs +++ b/tests/cmd_mv.rs @@ -645,3 +645,236 @@ fn mv_moves_the_resolved_ticket_when_two_share_a_title() { vec!["11111111-aaaa-bbbb-cccc-dddddddddddd_foo.md".to_string()] ); } + +// --------------------------------------------------------------- blocked by -- + +/// A ticket waiting on another, and a second one for it to wait on. Returns the +/// filename of the gated ticket, whose relations the moves are then checked against. +fn create_gated_pair(worklane: &std::path::Path, temp: &TempDir, status: &str) -> String { + let filename = create_ticket( + worklane, + status, + "Gated Task", + "Waits on the blocker.", + "aaaa1111aaaa1111aaaa1111aaaa1111aaaa", + "alice", + "_Not set_", + "test", + ); + create_ticket( + worklane, + "backlog", + "The Blocker", + "Nothing waits on this.", + "bbbb2222bbbb2222bbbb2222bbbb2222bbbb", + "bob", + "_Not set_", + "test", + ); + + // Through the command, so the fixture cannot store a relation in a shape the tool + // does not actually write. + Command::cargo_bin(BIN_NAME) + .unwrap() + .current_dir(temp.path()) + .args(["relate", "aaaa1111", "--blocked-by", "bbbb2222"]) + .assert() + .success(); + + filename +} + +fn move_ticket(temp: &TempDir, ticket: &str, status: &str, force: bool) -> std::process::Output { + let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); + cmd.current_dir(temp.path()) + .args(["mv", ticket, "--status", status]); + if force { + cmd.arg("-f"); + } + + cmd.assert().get_output().clone() +} + +/// Refused, and nothing written: not the rename, not the Status field, not a stray +/// temp file. The blocker is named with its status, since that is what has to change. +#[test] +fn mv_refuses_a_move_while_a_blocker_is_open() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + let filename = create_gated_pair(&worklane, &temp, "backlog"); + let before = fs::read_to_string(worklane.join("backlog").join(&filename)).unwrap(); + + let out = move_ticket(&temp, "aaaa1111", "committed", false); + assert!(!out.status.success()); + + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("blocked by"), "{stderr}"); + assert!(stderr.contains("The Blocker"), "{stderr}"); + assert!(stderr.contains("backlog"), "{stderr}"); + assert!(stderr.contains("--force"), "{stderr}"); + + assert!(worklane.join("backlog").join(&filename).exists()); + assert_eq!(md_files(&worklane.join("committed")).len(), 0); + assert_eq!( + fs::read_to_string(worklane.join("backlog").join(&filename)).unwrap(), + before, + "a refused move rewrote the ticket" + ); + assert_eq!(stray_files(&worklane), Vec::::new()); +} + +/// Every open blocker, not the first: clearing the one the message happened to name +/// would leave the ticket blocked and the reader surprised. +#[test] +fn mv_names_every_open_blocker() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_gated_pair(&worklane, &temp, "backlog"); + create_ticket( + &worklane, + "reviewing", + "The Second Blocker", + "Also not done.", + "cccc3333cccc3333cccc3333cccc3333cccc", + "bob", + "_Not set_", + "test", + ); + + Command::cargo_bin(BIN_NAME) + .unwrap() + .current_dir(temp.path()) + .args(["relate", "aaaa1111", "--blocked-by", "cccc3333"]) + .assert() + .success(); + + let out = move_ticket(&temp, "aaaa1111", "committed", false); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("The Blocker"), "{stderr}"); + assert!(stderr.contains("The Second Blocker"), "{stderr}"); +} + +/// `-f` is where the deliberate overrides live, beside the backward and skipping moves. +#[test] +fn mv_moves_a_blocked_ticket_with_force() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + let filename = create_gated_pair(&worklane, &temp, "backlog"); + + let out = move_ticket(&temp, "aaaa1111", "committed", true); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(worklane.join("committed").join(&filename).exists()); +} + +#[test] +fn mv_allows_the_move_once_the_blocker_is_done() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + let filename = create_gated_pair(&worklane, &temp, "backlog"); + + for status in ["committed", "reviewing", "done"] { + assert!( + move_ticket(&temp, "bbbb2222", status, false).status.success(), + "the blocker itself could not be moved to {status}" + ); + } + + let out = move_ticket(&temp, "aaaa1111", "committed", false); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(worklane.join("committed").join(&filename).exists()); +} + +/// Every move, not only the one into committed. An open blocker is a reason not to +/// finish as much as a reason not to start. +#[test] +fn mv_checks_the_blockers_on_every_move() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + let filename = create_gated_pair(&worklane, &temp, "reviewing"); + + let out = move_ticket(&temp, "aaaa1111", "done", false); + assert!(!out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(worklane.join("reviewing").join(&filename).exists()); +} + +/// A move to the status the ticket is already in is not a move, so it is reported the +/// way it always was rather than refused. +#[test] +fn mv_does_not_check_the_blockers_on_a_no_op() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_gated_pair(&worklane, &temp, "backlog"); + + let out = move_ticket(&temp, "aaaa1111", "backlog", false); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(String::from_utf8_lossy(&out.stdout).contains("already in")); +} + +/// A dangling target is a bookkeeping fault, not a dependency. Refusing there would +/// wedge the ticket with no way out but `--force`. +#[test] +fn mv_warns_and_allows_when_a_blocker_is_not_on_the_board() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + let filename = create_gated_pair(&worklane, &temp, "backlog"); + fs::remove_file( + worklane + .join("backlog") + .join("bbbb2222bbbb2222bbbb2222bbbb2222bbbb_the-blocker.md"), + ) + .unwrap(); + + let out = move_ticket(&temp, "aaaa1111", "committed", false); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!( + String::from_utf8_lossy(&out.stderr).contains("not on the board"), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(worklane.join("committed").join(&filename).exists()); +} + +/// Only `blocked by` gates a move. The other two kinds are reference data. +#[test] +fn mv_ignores_the_kinds_that_are_not_blockers() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + let filename = create_ticket( + &worklane, + "backlog", + "Related Task", + "Points at an open ticket.", + "aaaa1111aaaa1111aaaa1111aaaa1111aaaa", + "alice", + "_Not set_", + "test", + ); + create_ticket( + &worklane, + "backlog", + "The Other", + "Still open.", + "bbbb2222bbbb2222bbbb2222bbbb2222bbbb", + "bob", + "_Not set_", + "test", + ); + + Command::cargo_bin(BIN_NAME) + .unwrap() + .current_dir(temp.path()) + .args([ + "relate", + "aaaa1111", + "--regression-of", + "bbbb2222", + "--relates-to", + "bbbb2222", + ]) + .assert() + .success(); + + let out = move_ticket(&temp, "aaaa1111", "committed", false); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(worklane.join("committed").join(&filename).exists()); +} diff --git a/tests/cmd_relate.rs b/tests/cmd_relate.rs new file mode 100644 index 0000000..a73d1c7 --- /dev/null +++ b/tests/cmd_relate.rs @@ -0,0 +1,358 @@ +use assert_cmd::Command; +use assert_fs::TempDir; +use assert_fs::fixture::{PathChild, PathCreateDir}; +use std::fs; +use std::path::{Path, PathBuf}; + +const BIN_NAME: &str = env!("CARGO_BIN_EXE_worklane"); + +/// The ticket under edit, the one it points at, and one that is already done. +const GATED: &str = "641e3d5c-1b0e-4d2f-9a7e-3c8b5f0a2d61"; +const BLOCKER: &str = "b1b2c3d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d"; +const FIXED: &str = "f1f2f3f4-5a6b-4c7d-8e9f-0a1b2c3d4e5f"; + +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() +} + +fn slug(title: &str) -> String { + title + .to_lowercase() + .chars() + .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_') + .map(|c| if c == ' ' { '-' } else { c }) + .collect() +} + +/// A ticket with a ticked criterion and a section the tool knows nothing about, so +/// every test can check that recording a relation leaves both exactly as they were. +fn create_ticket(worklane: &Path, status: &str, title: &str, uuid: &str) -> PathBuf { + let path = worklane + .join(status) + .join(format!("{}_{}.md", uuid, slug(title))); + + fs::write( + &path, + format!( + "# {}\n\ + \n\ + ## Description\n\ + Prose.\n\ + \n\ + ## Acceptance Criteria\n\ + - [x] Crit one\n\ + \n\ + ## Implementation Plan\n\ + 1. Step one\n\ + \n\ + ## Notes\n\ + A handwritten note the tool knows nothing about.\n\ + \n\ + ## Metadata\n\ + \n\ + - **ID**: {}\n\ + - **Priority**: 3\n\ + - **Tags**: alpha\n\ + - **Due**: _Not set_\n\ + - **Owner**: alice\n\ + - **Created At**: 2026-08-21 02:10:17\n\ + - **Status**: {}\n", + title, uuid, status + ), + ) + .unwrap(); + + path +} + +/// The three tickets every test starts from: the one being edited, one it can wait on, +/// and one in done. +fn board(temp: &TempDir) -> PathBuf { + let worklane = setup_worklane(temp); + create_ticket(&worklane, "backlog", "The gated one", GATED); + create_ticket(&worklane, "backlog", "The blocker", BLOCKER); + create_ticket(&worklane, "done", "The old fix", FIXED); + worklane +} + +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 stdout(out: &std::process::Output) -> String { + String::from_utf8_lossy(&out.stdout).to_string() +} + +fn find(worklane: &Path, uuid: &str) -> PathBuf { + for status in ["backlog", "committed", "reviewing", "done"] { + let dir = worklane.join(status); + for entry in fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()) { + if entry.file_name().to_string_lossy().starts_with(uuid) { + return entry.path(); + } + } + } + + panic!("no file for ticket {uuid}"); +} + +fn ticket(worklane: &Path, uuid: &str) -> String { + fs::read_to_string(find(worklane, uuid)).unwrap() +} + +/// All three tiers, since the target is a ticket argument like any other: a uuid +/// prefix, a title substring, and a substring reaching the middle of the filename. +#[test] +fn a_target_resolves_by_uuid_prefix_title_or_filename() { + for search in ["b1b2", "blocker", "4a7b"] { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + let out = run(&temp, &["relate", GATED, "--blocked-by", search]); + assert!( + out.status.success(), + "{search}: {}", + String::from_utf8_lossy(&out.stderr) + ); + assert!( + ticket(&worklane, GATED).contains(&format!("- blocked by {}", BLOCKER)), + "{search}: {}", + ticket(&worklane, GATED) + ); + } +} + +#[test] +fn every_kind_is_recorded_under_its_own_label() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + let out = run( + &temp, + &[ + "relate", + GATED, + "--blocked-by", + BLOCKER, + "--regression-of", + FIXED, + "--relates-to", + "old fix", + ], + ); + assert!(out.status.success()); + + let content = ticket(&worklane, GATED); + assert!(content.contains(&format!("- blocked by {}", BLOCKER)), "{content}"); + assert!(content.contains(&format!("- regression of {}", FIXED)), "{content}"); + assert!(content.contains(&format!("- relates to {}", FIXED)), "{content}"); + + // Each kind named once in the report, whatever the order of the flags. + let reported = stdout(&out); + for kind in ["blocked by", "regression of", "relates to"] { + assert!(reported.contains(kind), "{reported}"); + } +} + +/// The kinds are flags, so anything else never reaches the file: clap refuses it with +/// a usage error, exit code 2, and nothing is written. +#[test] +fn an_unknown_kind_is_a_usage_error() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + let before = ticket(&worklane, GATED); + + let out = run(&temp, &["relate", GATED, "--depends-on", BLOCKER]); + assert_eq!(out.status.code(), Some(2), "{}", stdout(&out)); + assert_eq!(ticket(&worklane, GATED), before); +} + +/// A bare `relate ` is a usage error too, not a silent no-op, the same way a +/// bare `set` and a bare `append` are. +#[test] +fn a_relate_with_no_kind_is_a_usage_error() { + let temp = TempDir::new().unwrap(); + board(&temp); + + assert_eq!(run(&temp, &["relate", GATED]).status.code(), Some(2)); +} + +/// Between the plan and the metadata, created for a ticket written before the section +/// existed, and behind a handwritten section rather than in front of it. +#[test] +fn the_section_is_created_in_its_place() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]); + + let content = ticket(&worklane, GATED); + let at = |heading: &str| content.find(heading).unwrap_or_else(|| panic!("{heading}")); + assert!(at("## Implementation Plan") < at("## Relations"), "{content}"); + assert!(at("## Notes") < at("## Relations"), "{content}"); + assert!(at("## Relations") < at("## Metadata"), "{content}"); +} + +/// The full uuid, not the seven characters `ls` prints, which is what makes the link +/// survive a rename of the target and stay unambiguous as the board grows. +#[test] +fn the_stored_target_is_the_full_uuid() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]); + assert!( + ticket(&worklane, GATED).contains(&format!("- blocked by {}\n", BLOCKER)), + "{}", + ticket(&worklane, GATED) + ); + + run(&temp, &["set", BLOCKER, "--title", "Renamed entirely"]); + + let shown = stdout(&run(&temp, &["show", GATED])); + assert!(shown.contains("Renamed entirely"), "{shown}"); +} + +#[test] +fn a_ticket_cannot_relate_to_itself() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + let before = ticket(&worklane, GATED); + + let out = run(&temp, &["relate", GATED, "--relates-to", "gated"]); + assert!(!out.status.success()); + assert!( + String::from_utf8_lossy(&out.stderr).contains("cannot relate to itself"), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert_eq!(ticket(&worklane, GATED), before); +} + +#[test] +fn a_relation_already_held_reports_no_change_and_writes_nothing() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]); + let before = ticket(&worklane, GATED); + + let out = run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]); + assert!(out.status.success()); + assert!(stdout(&out).contains("No changes"), "{}", stdout(&out)); + assert_eq!( + ticket(&worklane, GATED), + before, + "the relation was recorded twice" + ); +} + +/// One direction is stored. The inverse is derived by a scan, so the ticket at the +/// other end is not touched at all. +#[test] +fn only_the_ticket_named_is_written() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + let before = ticket(&worklane, BLOCKER); + + run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]); + + assert_eq!(ticket(&worklane, BLOCKER), before); + assert!(!ticket(&worklane, BLOCKER).contains("Relations")); +} + +/// The tick, the handwritten section and the prose are what a regenerated file would +/// lose, and the section is spliced in rather than rewritten around them. +#[test] +fn relate_leaves_everything_it_was_not_asked_about_alone() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]); + + let content = ticket(&worklane, GATED); + assert!(content.contains("- [x] Crit one"), "the tick was lost: {content}"); + assert!( + content.contains("## Notes\nA handwritten note the tool knows nothing about.\n"), + "the unknown section was lost: {content}" + ); + assert!(content.contains("1. Step one"), "{content}"); + assert!(content.contains("- **Owner**: alice"), "{content}"); +} + +/// The kind, the short id and the title, so the section reads without a second lookup. +#[test] +fn show_renders_the_kind_the_short_id_and_the_title() { + let temp = TempDir::new().unwrap(); + board(&temp); + + run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]); + + let shown = stdout(&run(&temp, &["show", GATED])); + assert!(shown.contains("Relations"), "{shown}"); + assert!(shown.contains("blocked by (b1b2c3d) The blocker"), "{shown}"); + // Never the stored line: a bare uuid says nothing about what it points at. + assert!(!shown.contains(BLOCKER), "{shown}"); +} + +/// Derived by scanning, since the file at this end holds nothing at all. +#[test] +fn show_lists_the_relation_the_other_ticket_holds() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]); + run(&temp, &["relate", GATED, "--relates-to", FIXED]); + + let shown = stdout(&run(&temp, &["show", BLOCKER])); + assert!(shown.contains("blocks (641e3d5) The gated one"), "{shown}"); + assert!(!ticket(&worklane, BLOCKER).contains("Relations")); + + // `relates to` is symmetric, so it reads the same way from either end. + let shown = stdout(&run(&temp, &["show", FIXED])); + assert!(shown.contains("relates to (641e3d5) The gated one"), "{shown}"); +} + +#[test] +fn a_target_that_no_longer_exists_renders_as_missing() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]); + fs::remove_file(find(&worklane, BLOCKER)).unwrap(); + + let shown = stdout(&run(&temp, &["show", GATED])); + assert!(shown.contains("blocked by (b1b2c3d) _missing_"), "{shown}"); +} + +/// The section is the one part of a ticket read back by machine, so a line nobody can +/// parse is an error naming the ticket rather than a line quietly skipped. +#[test] +fn a_line_that_is_not_a_relation_is_an_error() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + let path = find(&worklane, GATED); + let content = fs::read_to_string(&path) + .unwrap() + .replace( + "## Metadata", + &format!("## Relations\n- depends on {}\n\n## Metadata", BLOCKER), + ); + fs::write(&path, content).unwrap(); + + let out = run(&temp, &["show", GATED]); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("is not a relation"), "{stderr}"); + assert!(stderr.contains("The gated one"), "{stderr}"); +}