Files
worklane/src/util.rs
T
Ansho ReiandClaude Opus 5 90b313952b (6d327df) Stop colour escapes leaking into the board's detail view, and bump to 0.8.4
The detail view renders with colour off, because ratatui draws styled spans and
an escape sequence inside a paragraph is not one. `detail_of` asks for that with
`content_trim(&content, false)`. Two paths ignored the argument and asked the
terminal instead.

`colorize_ordered` took no colour parameter at all and called `color_text`,
which is `paint(.., should_use_colors())`, and `content_trim` routes every
Implementation Plan line through it. In the TUI stdout is a terminal, so each
numbered step arrived as ESC[36m, the number, ESC[0m, then the text: exactly the
gap between the number and the step text where the reported artifact showed.
`colorize_line` did the same for a hand-written line inside a Metadata section,
and `colorize_bold` honoured its `enabled` flag on the early return and then
asked `should_use_colors()` again for the bold run, which made the flag a lie in
half the function.

`colorize_ordered` now takes the decision and is private, `content_trim` being
its only caller. `colorize_line` is deleted rather than given the argument: it
was a `pub` alias for `colorize_bold` with one caller, and asking the terminal
was the only thing it added, so `render_metadata_table` calls `colorize_bold`
with the decision it already holds.

Why this shipped, and the reason for the shape of the tests. The guard was an
assert that the detail view holds no escape byte, and it could not fail: a test
binary has no tty, so `should_use_colors()` was false and the leaking branch was
never taken. An absence is now asserted alongside a presence, `content_trim(..,
false)` carries no escape and `content_trim(.., true)` still colours, which pins
the flag as the only thing that decides. A third test scans this file for
`color_text` callers and fails on a new one; it also corrected the assumption
this commit started from, since the remaining caller is `ambiguous` and not
`display_ticket_items`.

The visible symptom is a terminal artifact that no test here can see, since
TestBackend applies cell updates and parses no escapes. What is proven is that
the escapes are gone, and that the CLI still paints its plan numbers cyan in a
pty, which is the condition the leak needed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 16:48:01 +02:00

1954 lines
70 KiB
Rust

use anyhow::{Result, anyhow};
use chrono::NaiveDateTime;
use std::fs;
use std::io::IsTerminal;
use std::path::Path;
use std::sync::OnceLock;
/// How timestamps are written into tickets and comments, and therefore how they
/// are read back. Shared so the writer and the reader cannot drift apart.
pub const TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
/// How a comment filename is stamped.
///
/// Microseconds, not seconds: at second resolution two comments in the same
/// second produced the same name and the second silently truncated the first.
/// Fixed width, so the lexicographic sort in `read_comments` stays chronological.
pub const COMMENT_FILE_FORMAT: &str = "%Y%m%d_%H%M%S_%6f";
/// Whether colour is wanted, from the three inputs that decide it.
///
/// Split out from the caching wrapper so it can be tested without a pty and
/// without touching the process environment.
///
/// `NO_COLOR` follows the no-color.org convention: set and non-empty disables,
/// whatever the value. An empty value is treated as unset, which is what lets a
/// wrapper script clear an inherited one.
fn colors_wanted(is_terminal: bool, no_color: Option<&str>, term: Option<&str>) -> bool {
if no_color.is_some_and(|value| !value.is_empty()) {
return false;
}
if matches!(term, Some("dumb") | Some("")) {
return false;
}
is_terminal
}
pub fn should_use_colors() -> bool {
// Decided once: it cannot change mid-run, and color_text asks on every call.
static ENABLED: OnceLock<bool> = OnceLock::new();
*ENABLED.get_or_init(|| {
let no_color = std::env::var("NO_COLOR").ok();
let term = std::env::var("TERM").ok();
colors_wanted(
std::io::stdout().is_terminal(),
no_color.as_deref(),
term.as_deref(),
)
})
}
/// The palette, as a type rather than a set of strings.
///
/// One definition for both renderers. The CLI needs an escape sequence and the TUI
/// needs a `ratatui::style::Color`, and an enum makes a colour that exists for one and
/// not the other a compile error instead of something a test has to go looking for.
/// The stringly-typed version needed exactly such a test, and a missing entry silently
/// produced an empty prefix, which is how `magenta` came to be undefined.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Color {
Red,
Cyan,
Orange,
Green,
Grey,
Magenta,
BrightRed,
}
impl Color {
/// The SGR sequence the CLI writes.
pub fn ansi(self) -> &'static str {
match self {
Color::Red => "\x1b[31m",
Color::Cyan => "\x1b[36m",
Color::Orange => "\x1b[33m",
Color::Green => "\x1b[32m",
// Indexed colour 8 in the 256-colour form, which is byte for byte what
// crossterm emits for ratatui's Color::DarkGray, the grey frig and pantop
// use for dimmed rows. Neither SGR 90 nor 37 renders as grey on every
// palette: 90 leans on the bright-black slot and 37 can sit right on top
// of the default foreground.
Color::Grey => "\x1b[38;5;8m",
// Bold, per the guideline in AGENTS.md.
Color::Magenta => "\x1b[1;35m",
// Indexed, for the same reason grey is: this is the spelling that renders.
Color::BrightRed => "\x1b[38;5;9m",
}
}
/// Every colour in the palette, so a test can walk them without listing them.
pub const ALL: [Color; 7] = [
Color::Red,
Color::Cyan,
Color::Orange,
Color::Green,
Color::Grey,
Color::Magenta,
Color::BrightRed,
];
}
/// The same palette as ratatui sees it.
///
/// Chosen to match what crossterm emits for the escape above, so a card in the TUI and
/// a row in the listing are the same colour rather than two guesses at it.
impl From<Color> for ratatui::style::Color {
fn from(color: Color) -> Self {
use ratatui::style::Color as Tui;
match color {
Color::Red => Tui::Red,
Color::Cyan => Tui::Cyan,
Color::Orange => Tui::Yellow,
Color::Green => Tui::Green,
Color::Grey => Tui::DarkGray,
Color::Magenta => Tui::Magenta,
Color::BrightRed => Tui::LightRed,
}
}
}
/// `color_text` with the decision passed in rather than asked for.
///
/// The seam matters for anything that aligns columns: a caller has to be able to
/// render both ways in one process to prove the padding does not depend on it.
pub fn paint(text: &str, color: Color, enabled: bool) -> String {
if enabled {
format!("{}{}{}", color.ansi(), text, "\x1b[0m")
} else {
text.to_string()
}
}
pub fn color_text(text: &str, color: Color) -> String {
paint(text, color, should_use_colors())
}
pub fn find_worklane_dir(start: &Path) -> Result<std::path::PathBuf> {
let mut current = start.canonicalize()?;
loop {
let worklane_dir = current.join(".worklane");
if worklane_dir.exists() {
return Ok(worklane_dir);
}
if !current.pop() {
break;
}
}
Err(anyhow!(
"No .worklane directory found. Run `worklane init` first."
))
}
/// Width of the abbreviated id shown by `ls` and by the disambiguation list.
pub const SHORT_ID_WIDTH: usize = 7;
/// The leading characters of `text`, counted in characters rather than bytes.
///
/// Byte slicing panics twice over here: on text shorter than the width, and on a
/// multibyte character straddling the cut. Both reach this code from a filename,
/// which nothing validates.
pub fn truncate_chars(text: &str, width: usize) -> &str {
match text.char_indices().nth(width) {
Some((byte, _)) => &text[..byte],
None => text,
}
}
/// A ticket id abbreviated for display.
pub fn short_id(id: &str) -> &str {
truncate_chars(id, SHORT_ID_WIDTH)
}
pub fn slug(title: &str) -> String {
title
.to_lowercase()
.chars()
.filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_')
.map(|c| if c == ' ' { '-' } else { c })
.collect()
}
pub fn get_git_user() -> Option<String> {
std::process::Command::new("git")
.args(["config", "user.name"])
.output()
.ok()
.and_then(|out| {
if out.status.success() {
String::from_utf8(out.stdout)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
} else {
None
}
})
}
/// The candidate list for an ambiguous search, as an error rather than a print
/// followed by `exit(1)`.
///
/// An error reaches the user on stderr and leaves the exit code non-zero, which
/// is the only combination the opencode wrapper can relay: it throws on the exit
/// code and keeps stderr, so the list printed to stdout was thrown away and the
/// agent saw nothing but a bare exit code.
fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyhow::Error {
let mut message = format!("Multiple tickets found matching '{}':\n", search);
for (i, (status, title, _, id)) in matches.iter().enumerate() {
message.push_str(&format!(
" {}. ({}) {} [{}]\n",
i + 1,
color_text(short_id(id), Color::Red),
title,
color_text(status, Color::Orange),
));
}
message.push_str("\nUse the displayed ID or a more specific search term to select.");
anyhow!(message)
}
/// Shortest search tried as a UUID prefix. Below it the search is text, so a one or
/// two character term is a title search rather than a prefix matching half the board.
///
/// Four, not eight. The guard this replaces read `short_id.len() >= 8`, and `short_id`
/// there was always the full 36 character uuid, so it was always true and any length
/// already worked. Requiring eight would have broken the id the tool prints itself:
/// `ls` shows [`SHORT_ID_WIDTH`] characters, and pasting that back has to resolve.
pub const MIN_ID_SEARCH: usize = 4;
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;
// Three tiers, filled in one pass and consulted in order. A uuid prefix has to win
// outright rather than join a flat list: ticket titles reference other tickets by
// id, so an exact prefix match was reported as ambiguous against whichever title
// happened to mention it.
let mut by_id: Vec<(String, String, String, String)> = Vec::new();
let mut by_title: Vec<(String, String, String, String)> = Vec::new();
let mut by_filename: Vec<(String, String, String, String)> = Vec::new();
for status in status_dirs() {
let status_path = worklane_dir.join(status);
if !status_path.exists() {
continue;
}
let entries = fs::read_dir(&status_path)?;
for entry in entries.filter_map(|e| e.ok()) {
let path = entry.path();
if !path.extension().is_some_and(|e| e == "md") {
continue;
}
let content = match fs::read_to_string(&path) {
Ok(c) => c,
Err(_) => continue,
};
let title = content
.lines()
.find(|l| l.starts_with("# "))
.map(|l| l[2..].trim())
.unwrap_or("")
.to_string();
let filename = path
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
let uuid = filename.split('_').next().unwrap_or("");
let by_prefix = long_enough_for_an_id && uuid.to_lowercase().starts_with(&search_lower);
let in_title = title.to_lowercase().contains(&search_lower);
// Still reaches the middle of a uuid, which the prefix tier cannot.
let in_filename = filename.to_lowercase().contains(&search_lower);
if !(by_prefix || in_title || in_filename) {
continue;
}
let found = (status.to_string(), title, content, uuid.to_string());
if by_prefix {
by_id.push(found);
} else if in_title {
by_title.push(found);
} else {
by_filename.push(found);
}
}
}
let mut matches = match (by_id.is_empty(), by_title.is_empty()) {
(false, _) => by_id,
(true, false) => by_title,
(true, true) => by_filename,
};
if matches.is_empty() {
return Err(anyhow!("No ticket found matching '{}'", search));
}
if matches.len() > 1 {
return Err(ambiguous(search, &matches));
}
let (status, title, content, _short_id) = matches.remove(0);
Ok((status, title, content))
}
pub fn format_comments(comments: &[(String, String, String, String)]) -> String {
format_comments_with(comments, should_use_colors())
}
/// As above, with the colour decision passed in for the TUI.
pub fn format_comments_with(
comments: &[(String, String, String, String)],
colored: bool,
) -> String {
if comments.is_empty() {
return paint("No comments yet.", Color::Grey, colored);
}
let mut result = String::new();
result.push('\n');
result.push_str(&paint("COMMENTS", Color::Orange, colored));
result.push_str(&format!("\n{}\n", "─".repeat(20)));
for (_filename, author, time, body) in comments {
result.push('\n');
result.push_str(&paint(&format!("From {} ({})", author, time), Color::Cyan, colored));
result.push('\n');
if !body.is_empty() {
result.push_str(" ");
result.push_str(body);
}
result.push('\n');
}
result
}
pub fn content_trim_colored(content: &str) -> String {
content_trim(content, should_use_colors())
}
/// 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 {
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;
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');
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);
result.push_str(&render_metadata_table(&lines[i..end], colored));
i = end;
}
continue;
}
// The title belongs to cmd_show, which prints it with its rule. Printing it
// again from the file content is what repeated it in every show output.
if line.starts_with("# ") && current_section.is_empty() {
i += 1;
// Along with the blank line the template puts under it, so dropping the
// title does not leave a gap where it used to be.
while i < lines.len() && lines[i].trim().is_empty() {
i += 1;
}
continue;
}
i += 1;
// Implementation Plan - color numbers in cyan
if current_section == "## Implementation Plan" {
result.push_str(&colorize_ordered(line, colored));
result.push('\n');
continue;
}
// 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), Color::Cyan, colored));
result.push(' ');
result.push_str(&paint(
if checked { "[x]" } else { "[ ]" },
Color::Grey,
colored,
));
result.push(' ');
result.push_str(&colorize_bold(text, colored));
result.push('\n');
continue;
}
// Standard markdown link colorization in cyan
if line.contains("[")
&& line.contains("(")
&& line.contains("]")
&& let Some(start) = line.find("[")
{
let bracket_text = &line[start..];
if let Some(end_bracket) = bracket_text.find("](") {
let link_start = start + end_bracket + 1;
if let Some(end) = line[link_start..].find(']') {
let absolute_end = link_start + end + 1;
result.push_str(&paint(&line[start..absolute_end], Color::Cyan, colored));
result.push('\n');
continue;
}
}
}
// Regular content - colorize **bold** in magenta
result.push_str(&colorize_bold(line, colored));
result.push('\n');
}
result
}
/// Colour the `1.` at the head of a numbered line, leaving the rest alone.
///
/// Takes the decision rather than asking for it. Asking is what put `\x1b[36m` and
/// `\x1b[0m` around every Implementation Plan number in the board's detail view,
/// which renders with colour off precisely because a paragraph is not a place an
/// escape sequence can go.
fn colorize_ordered(line: &str, colored: bool) -> String {
if line.chars().next().is_none_or(|c| !c.is_ascii_digit()) {
return line.to_string();
}
// Match "1. " pattern and color the number in cyan
let mut result = String::new();
let chars: Vec<char> = line.chars().collect();
for (i, c) in chars.iter().enumerate() {
if c.is_ascii_digit() {
// still scanning digits
} else if *c == '.' && i + 1 < chars.len() && chars[i + 1] == ' ' {
let number = &line[..i + 1];
result.push_str(&paint(number, Color::Cyan, colored));
result.push_str(&line[i + 1..]);
return result;
} else {
break;
}
}
line.to_string()
}
/// Space between the field column and the value column.
const METADATA_GUTTER: &str = " ";
/// One line of the Metadata section, as the table sees it.
enum MetadataRow<'a> {
/// A `- **Name**: value` line, the shape the file stores fields in.
Field { name: &'a str, value: &'a str },
/// Anything else, carried through verbatim so a hand-written note in the
/// section is not dropped on the way to the screen.
Other(&'a str),
}
/// Split a metadata line into a field and its value, sharing the anchoring rules
/// `parse_ticket_field` uses: list marker optional, name matched at the start.
fn metadata_row(line: &str) -> MetadataRow<'_> {
let body = metadata_field_body(line);
let Some(rest) = body.strip_prefix("**") else {
return MetadataRow::Other(line);
};
let Some(close) = rest.find("**:") else {
return MetadataRow::Other(line);
};
MetadataRow::Field {
name: &rest[..close],
value: rest[close + "**:".len()..].trim(),
}
}
/// The value cell for a field, styled per the colour guideline.
fn metadata_value_cell(name: &str, value: &str, colored: bool) -> String {
if name == "Priority" {
// Reads as a glyph, while the file keeps storing the number.
let (glyph, colour) = priority_mark(priority_from_value(value));
return format!("{} {}", paint(glyph, colour, colored), value);
}
if is_unknown_value(value) {
return paint(value, Color::Grey, colored);
}
value.to_string()
}
/// Render the Metadata section as two aligned columns.
///
/// Taken as a block rather than a line at a time because the field column cannot be
/// sized until every name has been seen. The file is untouched by this: it goes on
/// storing the markdown list, and this is only how the list is shown.
fn render_metadata_table(lines: &[&str], colored: bool) -> String {
// The heading already emits its own blank separator, so the one the template
// puts under it would otherwise open the section with a gap.
let start = lines
.iter()
.position(|line| !line.trim().is_empty())
.unwrap_or(lines.len());
let rows: Vec<MetadataRow> = lines[start..].iter().map(|line| metadata_row(line)).collect();
// Measured on the raw names, in characters, and padded before anything is
// styled. Measuring a coloured name counts its escape sequences towards its
// width, which is what tilts a table when colour is on and not when it is off.
let field_width = rows
.iter()
.filter_map(|row| match row {
MetadataRow::Field { name, .. } => Some(name.chars().count()),
MetadataRow::Other(_) => None,
})
.max()
.unwrap_or(0);
let mut result = String::new();
for row in &rows {
match row {
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(&metadata_value_cell(name, value, colored));
}
// The decision this row is rendered under, not the one the terminal
// would give: `colorize_line` asked `should_use_colors()` here, which is
// how escapes reached the board's detail view.
MetadataRow::Other(text) => result.push_str(&colorize_bold(text, colored)),
}
result.push('\n');
}
result
}
pub fn is_unknown_value(value: &str) -> bool {
let trimmed = value.trim();
trimmed == "_None_" || trimmed == "_Not set_" || trimmed == "-None-" || trimmed == "-Not set-"
}
/// Replace `**bold**` with colour, or leave the line exactly as it is.
///
/// Taking `enabled` rather than asking makes both paths testable, and the
/// disabled path matters: stripping the markers when there is no colour to
/// replace them with loses the emphasis altogether, which is what happens to
/// every piped `show` and to everything the opencode tools read.
fn colorize_bold(line: &str, enabled: bool) -> String {
if !enabled {
return line.to_string();
}
let chars: Vec<char> = line.chars().collect();
let mut result = String::new();
let mut i = 0;
while i < chars.len() {
if !is_delimiter(&chars, i) {
result.push(chars[i]);
i += 1;
continue;
}
match (i + 2..chars.len()).find(|&at| is_delimiter(&chars, at)) {
Some(close) => {
let bold: String = chars[i + 2..close].iter().collect();
// `enabled`, not `should_use_colors()`. Asking again here made the
// flag a lie: the early return above respected it and this did not.
result.push_str(&paint(&bold, Color::Magenta, enabled));
i = close + 2;
}
// Unterminated: the rest is literal. The old scan walked off the end
// here and dropped the final character.
None => {
result.extend(&chars[i..]);
return result;
}
}
}
result
}
fn is_delimiter(chars: &[char], at: usize) -> bool {
chars.get(at) == Some(&'*') && chars.get(at + 1) == Some(&'*')
}
const METADATA_HEADING: &str = "## Metadata";
fn is_metadata_heading(line: &str) -> bool {
line.trim_end() == METADATA_HEADING
}
/// The lines of the Metadata section, or nothing when the heading is absent.
///
/// Field lookup has to be anchored here. Prose above the section is free text, so a
/// description quoting a field marker would otherwise shadow the real value below it.
fn metadata_lines(content: &str) -> impl Iterator<Item = &str> {
content
.lines()
.skip_while(|line| !is_metadata_heading(line))
.skip(1)
.take_while(|line| !line.starts_with("## "))
}
/// A metadata line without its list marker, so lookup can match on a prefix rather
/// than searching the whole line.
fn metadata_field_body(line: &str) -> &str {
let line = line.trim_start();
line.strip_prefix("- ").unwrap_or(line)
}
pub fn parse_ticket_field(content: &str, field: &str) -> String {
let prefix = format!("**{}**:", field);
metadata_lines(content)
.find_map(|line| metadata_field_body(line).strip_prefix(&prefix))
.map(|value| value.trim().to_string())
.unwrap_or_else(|| "_Not set_".to_string())
}
fn is_status_line(line: &str) -> bool {
let body = metadata_field_body(line);
// The second spelling is what earlier versions wrote, repair it on the way through.
body.starts_with("**Status**:") || body.starts_with("**-Status**:")
}
/// Rewrite one field in the Metadata section, leaving every other line untouched.
///
/// Scoped to the section for the same reason as `parse_ticket_field`: a description
/// line shaped like a metadata field would otherwise be rewritten in its place,
/// corrupting the prose and leaving the real metadata stale.
///
/// The matcher is a parameter because Status has a legacy spelling to repair, which no
/// other field has.
fn set_metadata_line(
content: &str,
field: &str,
value: &str,
matches: impl Fn(&str) -> bool,
) -> Option<String> {
let mut updated = String::with_capacity(content.len());
let mut in_metadata = false;
let mut found = false;
for line in content.lines() {
if line.starts_with("## ") {
in_metadata = is_metadata_heading(line);
}
if in_metadata && !found && matches(line) {
updated.push_str("- **");
updated.push_str(field);
updated.push_str("**: ");
updated.push_str(value);
found = true;
} else {
updated.push_str(line);
}
updated.push('\n');
}
if found { Some(updated) } else { None }
}
pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Result<String> {
set_metadata_line(content, "Status", target_status, is_status_line).ok_or_else(|| {
anyhow!(
"Ticket '{}' has no Status field in its Metadata section",
title
)
})
}
/// Rewrite a metadata field other than Status.
///
/// A field that is not already in the file is an error rather than an insertion. Every
/// ticket `add` writes carries the full set in a fixed order, and nothing else writes
/// these files, so a missing field means a hand-made ticket and guessing where the line
/// belongs would be inventing a format.
pub fn set_metadata_field(content: &str, field: &str, value: &str, title: &str) -> Result<String> {
let prefix = format!("**{}**:", field);
set_metadata_line(content, field, value, |line| {
metadata_field_body(line).starts_with(&prefix)
})
.ok_or_else(|| {
anyhow!(
"Ticket '{}' has no {} field in its Metadata section",
title,
field
)
})
}
/// Rewrite the title heading, the first `# ` line in the file.
///
/// `## ` headings do not match: the second character has to be a space.
pub fn set_title(content: &str, title: &str) -> Result<String> {
let mut updated = String::with_capacity(content.len());
let mut found = false;
for line in content.lines() {
if !found && line.starts_with("# ") {
updated.push_str("# ");
updated.push_str(title);
found = true;
} else {
updated.push_str(line);
}
updated.push('\n');
}
if !found {
return Err(anyhow!("Ticket '{}' has no title heading", title));
}
Ok(updated)
}
// Format created_at for display: "YYYY-MM-DD HH:MM:SS" becomes "YY-MM-DD:HH".
//
// Parsed rather than sliced by byte offset: the value comes from a file nothing
// validates, and the old offsets panicked on any multibyte character before them.
// Anything unparseable yields an empty string, which drops the column.
pub fn format_created_at(created_at: &str) -> String {
match NaiveDateTime::parse_from_str(created_at, TIMESTAMP_FORMAT) {
Ok(created_at) => created_at.format("%y-%m-%d:%H").to_string(),
Err(_) => String::new(),
}
}
/// How a section stores the lines the tool owns.
pub enum SectionKind {
/// Lines as written, a blank one acting as a paragraph break.
Prose,
/// One `- [ ] ` item per line.
Checklist,
/// One `N. ` step per line.
Numbered,
}
/// A section of a ticket whose body `set` and `append` can rewrite.
///
/// A table rather than a match arm per section, so adding a section later is one entry
/// here instead of edits spread across both commands.
pub struct Section {
pub heading: &'static str,
/// How the section is named in output, lowercase so it reads the same way the
/// metadata field labels do.
pub label: &'static str,
/// What `add` writes when the section is left empty. Treated as no content, so
/// appending to an empty section replaces the placeholder rather than following it.
pub placeholder: &'static str,
pub kind: SectionKind,
}
pub const DESCRIPTION: Section = Section {
heading: "## Description",
label: "description",
placeholder: "_No description provided._",
kind: SectionKind::Prose,
};
pub const ACCEPTANCE: Section = Section {
heading: "## Acceptance Criteria",
label: "acceptance criteria",
placeholder: "_No acceptance criteria provided._",
kind: SectionKind::Checklist,
};
pub const PLAN: Section = Section {
heading: "## Implementation Plan",
label: "implementation plan",
placeholder: "_No implementation plan provided._",
kind: SectionKind::Numbered,
};
impl Section {
/// The values a caller supplied, reduced to the lines that belong in the body.
///
/// Prose keeps interior blanks, since those are paragraph breaks. A list has one
/// item per value, so a blank there is nothing at all.
pub fn normalise(&self, values: &[String]) -> Vec<String> {
match self.kind {
SectionKind::Prose => trim_blank_ends(values).to_vec(),
SectionKind::Checklist | SectionKind::Numbered => values
.iter()
.filter(|value| !value.trim().is_empty())
.cloned()
.collect(),
}
}
/// `items` as body lines, numbering from `first` where the section is numbered.
fn render(&self, items: &[String], first: usize) -> Vec<String> {
match self.kind {
SectionKind::Prose => items.to_vec(),
SectionKind::Checklist => items.iter().map(|i| format!("- [ ] {}", i)).collect(),
SectionKind::Numbered => items
.iter()
.enumerate()
.map(|(offset, step)| format!("{}. {}", first + offset, step))
.collect(),
}
}
}
/// Whether the line opens with `N. `, the shape a numbered step is stored in.
fn is_numbered_item(line: &str) -> bool {
let digits = line.chars().take_while(|c| c.is_ascii_digit()).count();
// ASCII digits are one byte each, so the count is also the byte offset.
digits > 0 && line[digits..].starts_with(". ")
}
/// 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<std::ops::Range<usize>> {
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)
}
/// Where the body's content ends, ignoring the blank lines that separate it from
/// whatever follows.
fn body_content_end(lines: &[&str], body: &std::ops::Range<usize>) -> usize {
let mut end = body.end;
while end > body.start && lines[end - 1].trim().is_empty() {
end -= 1;
}
end
}
fn join_lines(lines: &[String]) -> String {
let mut out = lines.join("\n");
out.push('\n');
out
}
/// Replace a section's body with `items`, leaving every line outside it untouched.
pub fn set_section_body(content: &str, section: &Section, items: &[String]) -> Result<String> {
let lines: Vec<&str> = content.lines().collect();
let body = section_body(&lines, section.heading)
.ok_or_else(|| anyhow!("Ticket has no {} section", section.label))?;
let mut out: Vec<String> = lines[..body.start].iter().map(|l| l.to_string()).collect();
out.extend(section.render(items, 1));
// One blank line before whatever section follows, matching how `add` writes it.
if body.end < lines.len() {
out.push(String::new());
}
out.extend(lines[body.end..].iter().map(|l| l.to_string()));
Ok(join_lines(&out))
}
/// Add `items` to the end of a section's body.
///
/// Prose gains a blank line first, so the addition reads as a new paragraph. A numbered
/// section continues from the count of steps already there rather than renumbering what
/// is above it, which keeps any handwritten line in the section exactly as it was.
pub fn append_section_body(content: &str, section: &Section, items: &[String]) -> Result<String> {
let lines: Vec<&str> = content.lines().collect();
let body = section_body(&lines, section.heading)
.ok_or_else(|| anyhow!("Ticket has no {} section", section.label))?;
let at = body_content_end(&lines, &body);
let existing: Vec<&&str> = lines[body.start..at]
.iter()
.filter(|line| !line.trim().is_empty())
.collect();
// An empty section is a placeholder, and following it with a paragraph would leave
// "_No description provided._" above the description.
if existing.len() == 1 && existing[0].trim() == section.placeholder {
return set_section_body(content, section, items);
}
let first = match section.kind {
SectionKind::Numbered => 1 + existing.iter().filter(|l| is_numbered_item(l)).count(),
_ => 1,
};
let mut out: Vec<String> = lines[..at].iter().map(|l| l.to_string()).collect();
if matches!(section.kind, SectionKind::Prose) && at > body.start {
out.push(String::new());
}
out.extend(section.render(items, first));
out.extend(lines[at..].iter().map(|l| l.to_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<Criterion> {
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), Color::Cyan, colored),
paint(
if criterion.checked { "[x]" } else { "[ ]" },
Color::Grey,
colored
),
criterion.text
)
})
.collect::<Vec<_>>()
.join("\n")
}
/// The whole list, numbered as `show` numbers it.
pub fn criteria_list(criteria: &[Criterion]) -> String {
numbered_criteria(criteria, &(0..criteria.len()).collect::<Vec<_>>())
}
/// 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::<usize>().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<usize> {
if let Ok(index) = search.trim().parse::<usize>() {
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(&current[..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(&current[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
/// caller spells a paragraph break. That makes the interior blanks content, while a
/// blank at either end would only open or close the section with a gap.
pub fn trim_blank_ends(values: &[String]) -> &[String] {
let first = values.iter().position(|v| !v.trim().is_empty());
match first {
None => &[],
Some(first) => {
// Guaranteed to find one, since `first` is itself non-blank.
let last = match values.iter().rposition(|v| !v.trim().is_empty()) {
Some(last) => last,
None => first,
};
&values[first..=last]
}
}
}
pub fn status_dirs() -> Vec<&'static str> {
vec!["backlog", "committed", "reviewing", DONE]
}
/// The end of the flow, and the one status both views treat differently: `ls` counts it
/// in the summary and leaves it out of the listing, and the board hides its column until
/// asked. Named because that rule now has two readers.
///
/// It is deliberately last in `status_dirs()`. The board leans on that: hiding done drops
/// the final column, so the other three keep their indices and the selection only has to
/// be handled when it is sitting on done itself.
pub const DONE: &str = "done";
/// Lowest and highest level a ticket can carry. 1 is the most urgent, which is
/// what the `p1` to `p3` tags this replaced already meant.
pub const PRIORITY_RANGE: std::ops::RangeInclusive<u8> = 1..=5;
/// A ticket's priority as it comes off disk.
///
/// Three states, not two: a value outside the range has to stay distinguishable
/// from no value at all, or a typo silently reads as "no priority".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Priority {
Level(u8),
Unset,
Invalid,
}
impl Priority {
/// Sort weight. Levels first in order, then anything wrong, then anything
/// absent, so a typo surfaces above the long tail of unset tickets.
pub fn rank(&self) -> u8 {
match self {
Priority::Level(level) => *level,
Priority::Invalid => u8::MAX - 1,
Priority::Unset => u8::MAX,
}
}
}
/// A priority from the value alone, for callers that already have it in hand.
pub fn priority_from_value(raw: &str) -> Priority {
let raw = raw.trim();
if is_unknown_value(raw) {
return Priority::Unset;
}
match raw.parse::<u8>() {
Ok(level) if PRIORITY_RANGE.contains(&level) => Priority::Level(level),
_ => Priority::Invalid,
}
}
pub fn parse_priority(content: &str) -> Priority {
priority_from_value(&parse_ticket_field(content, "Priority"))
}
pub struct TicketItem {
pub title: String,
pub owner: String,
pub due: String,
pub id: String,
pub created: String,
pub priority: Priority,
/// The file this came from. The listing ignores it; the TUI opens it for the
/// detail view rather than resolving the ticket a second time.
pub path: std::path::PathBuf,
}
/// Grey for a value that is not set, per the colour guideline.
///
/// `show` already did this in its metadata rendering, so the listing was the one
/// place that ignored the rule.
fn dim_if_unset(value: &str, colored: bool) -> String {
if is_unknown_value(value) {
paint(value, Color::Grey, colored)
} else {
value.to_string()
}
}
/// The mark and colour for a level, from one place.
///
/// A two-segment meter that empties as the level rises, so the level is legible
/// from shape alone: colour is off whenever output is piped, and NO_COLOR turns it
/// off in a terminal too, so colour accentuates and never encodes.
///
/// Only three glyphs, the ones frig uses for its status indicators and which are
/// therefore known to render here. The quadrant circles this first used are in a
/// quarter as many fonts, so terminals substituted them from a fallback font that
/// draws them oversized. Two cells of a three-level ramp gives five steps of ink,
/// 2, 1.5, 1, 0.5, 0, without leaving that safe set.
///
/// The number counts up while the mark empties out, because 1 is the most urgent.
/// That is the convention every tracker uses and what the p1 tags this replaced
/// already meant.
pub fn priority_mark(priority: Priority) -> (&'static str, Color) {
match priority {
Priority::Level(1) => ("\u{25cf}\u{25cf}", Color::BrightRed),
Priority::Level(2) => ("\u{25cf}\u{25d0}", Color::Red),
Priority::Level(3) => ("\u{25cf}\u{25cb}", Color::Orange),
Priority::Level(4) => ("\u{25d0}\u{25cb}", Color::Cyan),
Priority::Level(5) => ("\u{25cb}\u{25cb}", Color::Grey),
// Unreachable while Level is only built by parse_priority, which checks
// the range, but a level added later should not silently render blank.
Priority::Level(_) | Priority::Invalid => ("??", Color::BrightRed),
Priority::Unset => ("\u{b7}\u{b7}", Color::Grey),
}
}
/// The legend, for help text. Nothing else in a listing explains the glyphs.
pub fn priority_legend() -> String {
let levels = PRIORITY_RANGE
.map(|level| {
let (glyph, _) = priority_mark(Priority::Level(level));
format!("{} {}", glyph, level)
})
.collect::<Vec<_>>()
.join(" ");
let (unset, _) = priority_mark(Priority::Unset);
format!("Priority: {levels} {unset} unset 1 is most urgent")
}
fn show_priority(priority: Priority, colored: bool) -> String {
let (glyph, colour) = priority_mark(priority);
paint(glyph, colour, colored)
}
pub fn display_ticket_items(items: &[TicketItem]) {
let colored = should_use_colors();
for item in items {
let id = paint(&item.id, Color::Red, colored);
let owner = dim_if_unset(&item.owner, colored);
let due = dim_if_unset(&item.due, colored);
let priority = show_priority(item.priority, colored);
if item.created.is_empty() {
println!(
" {} ({}) {} | Owner: {} | Due: {}",
priority, id, item.title, owner, due
);
} else {
let created = paint(&item.created, Color::Cyan, colored);
println!(
" {} {} ({}) {} | Owner: {} | Due: {}",
priority, created, id, item.title, owner, due
);
}
}
}
pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketItem>> {
let entries: Vec<_> = fs::read_dir(status_path)?.filter_map(|e| e.ok()).collect();
let mut items: Vec<TicketItem> = entries
.iter()
.filter_map(|e| {
let content = fs::read_to_string(e.path()).ok()?;
let title = content
.lines()
.find(|l| l.starts_with("# "))
.map(|l| l[2..].trim().to_string())
.unwrap_or_else(|| "_No title_".to_string());
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();
let created_at = parse_ticket_field(&content, "Created At");
Some(TicketItem {
title,
owner,
due,
id: short_id(&filename).to_string(),
created: format_created_at(&created_at),
priority: parse_priority(&content),
path: e.path(),
})
})
.collect();
// Priority first, title as the tiebreak, which is what the sort used to be.
items.sort_by(|a, b| {
a.priority
.rank()
.cmp(&b.priority.rank())
.then_with(|| a.title.to_lowercase().cmp(&b.title.to_lowercase()))
});
Ok(items)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_color_disables_colour_on_a_terminal() {
assert!(!colors_wanted(true, Some("1"), Some("xterm-256color")));
// Any value at all, per the convention
assert!(!colors_wanted(true, Some("0"), Some("xterm-256color")));
assert!(!colors_wanted(true, Some("false"), Some("xterm-256color")));
}
/// An empty value counts as unset, so a wrapper script can clear one it
/// inherited.
#[test]
fn an_empty_no_color_is_ignored() {
assert!(colors_wanted(true, Some(""), Some("xterm-256color")));
}
#[test]
fn a_dumb_terminal_gets_no_colour() {
assert!(!colors_wanted(true, None, Some("dumb")));
assert!(!colors_wanted(true, None, Some("")));
}
#[test]
fn colour_needs_a_terminal() {
assert!(colors_wanted(true, None, Some("xterm-256color")));
assert!(!colors_wanted(false, None, Some("xterm-256color")));
// No TERM at all is fine as long as it is a terminal
assert!(colors_wanted(true, None, None));
}
#[test]
fn unset_values_are_dimmed_and_set_ones_are_not() {
// Both paths, now that the colour decision is a parameter: with colour off the
// text has to come back untouched, with it on only the unset values get wrapped
for unset in ["_Not set_", "_None_"] {
assert!(is_unknown_value(unset), "{unset} should count as unset");
assert_eq!(dim_if_unset(unset, false), unset);
assert_eq!(dim_if_unset(unset, true), paint(unset, Color::Grey, true));
}
for set in ["alice", "2026-12-31", "bug,frontend"] {
assert!(!is_unknown_value(set));
assert_eq!(dim_if_unset(set, false), set);
assert_eq!(dim_if_unset(set, true), set);
}
}
fn ticket_with_priority(raw: &str) -> String {
format!("# T\n\n## Metadata\n\n- **Priority**: {}\n", raw)
}
/// A ticket whose prose quotes the field markers it also carries as metadata,
/// as a list so the quoted lines start with the marker. This repo files tickets
/// about the metadata format, so it is the normal case here rather than a corner.
fn ticket_shadowing_its_own_metadata() -> String {
"# Shadow\n\
\n\
## Description\n\
The current format is:\n\
- **Owner**: nobody\n\
- **Status**: backlog\n\
\n\
## Metadata\n\
\n\
- **ID**: real-id\n\
- **Owner**: alice\n\
- **Status**: backlog\n"
.to_string()
}
#[test]
fn prose_quoting_a_field_marker_does_not_shadow_the_metadata() {
let content = ticket_shadowing_its_own_metadata();
assert_eq!(parse_ticket_field(&content, "Owner"), "alice");
assert_eq!(parse_ticket_field(&content, "ID"), "real-id");
assert_eq!(parse_ticket_field(&content, "Status"), "backlog");
}
#[test]
fn a_field_only_mentioned_in_prose_reads_as_unset() {
let content = "# T\n\n## Description\n- **Due**: 2026-12-31\n\n## Metadata\n\n- **ID**: x\n";
assert_eq!(parse_ticket_field(content, "Due"), "_Not set_");
}
#[test]
fn a_field_lookup_needs_the_metadata_heading() {
// No section, no fields: there is nothing to anchor to.
assert_eq!(
parse_ticket_field("# T\n\n- **Owner**: alice\n", "Owner"),
"_Not set_"
);
}
#[test]
fn a_field_lookup_stops_at_the_next_section() {
let content = "# T\n\n## Metadata\n\n- **ID**: x\n\n## Notes\n\n- **Owner**: alice\n";
assert_eq!(parse_ticket_field(content, "Owner"), "_Not set_");
assert_eq!(parse_ticket_field(content, "ID"), "x");
}
/// Matching on a prefix, not a substring: a field name inside another field's
/// value is not that field.
#[test]
fn a_field_marker_inside_another_value_is_not_matched() {
let content = "# T\n\n## Metadata\n\n- **Tags**: mentions **Owner**: bob\n";
assert_eq!(parse_ticket_field(content, "Owner"), "_Not set_");
assert_eq!(parse_ticket_field(content, "Tags"), "mentions **Owner**: bob");
}
#[test]
fn setting_the_status_leaves_prose_that_looks_like_metadata_alone() {
let content = ticket_shadowing_its_own_metadata();
let updated = set_status_field(&content, "committed", "Shadow").unwrap();
assert!(
updated.contains("## Description\nThe current format is:\n- **Owner**: nobody\n- **Status**: backlog\n"),
"the description was rewritten:\n{updated}"
);
assert_eq!(parse_ticket_field(&updated, "Status"), "committed");
assert_eq!(updated.matches("**Status**: committed").count(), 1);
}
#[test]
fn setting_the_status_needs_the_field_in_the_metadata_section() {
// A Status line above the section is prose, so this is a ticket without the field.
let content = "# T\n\n## Description\n- **Status**: backlog\n\n## Metadata\n\n- **ID**: x\n";
assert!(set_status_field(content, "committed", "T").is_err());
}
/// SGR escapes removed, so a rendered cell can be measured as it lands on screen.
/// Test-only: production never measures a styled string, which is the point.
fn unstyled(text: &str) -> String {
let mut out = String::new();
let mut chars = text.chars();
while let Some(c) = chars.next() {
if c != '\x1b' {
out.push(c);
continue;
}
// Drop everything up to and including the 'm' that closes the sequence.
for c in chars.by_ref() {
if c == 'm' {
break;
}
}
}
out
}
#[test]
fn the_metadata_table_aligns_values_in_one_column() {
// The leading blank line is what the ticket template writes under the heading.
let rendered = render_metadata_table(
&[
"",
"- **ID**: abc",
"- **Created At**: 2026-08-20",
"- **Owner**: alice",
],
false,
);
assert_eq!(
rendered,
"ID abc\n\
Created At 2026-08-20\n\
Owner alice\n"
);
}
#[test]
fn a_long_field_name_widens_the_column_for_every_row() {
let rendered =
render_metadata_table(&["- **ID**: abc", "- **Handled By Team**: ops"], false);
assert_eq!(
rendered,
"ID abc\n\
Handled By Team ops\n"
);
}
/// The trap the ticket names: field names are coloured, unset values are greyed
/// and Priority carries a mark, so measuring the styled text would tilt the table
/// with colour on and not with it off.
#[test]
fn colour_does_not_change_the_alignment() {
let lines = [
"- **ID**: abc",
"- **Priority**: 2",
"- **Due**: _Not set_",
"- **Owner**: Ansho Rei",
];
let plain = render_metadata_table(&lines, false);
let coloured = render_metadata_table(&lines, true);
assert_ne!(coloured, plain, "colour produced no escapes at all");
assert_eq!(unstyled(&coloured), plain);
}
#[test]
fn a_non_ascii_field_name_is_measured_in_characters() {
// "Créé à" is 6 characters and 8 bytes, so a byte-width column pads it short
let rendered = render_metadata_table(&["- **Créé à**: oui", "- **ID**: abc"], false);
assert_eq!(
rendered,
"Créé à oui\n\
ID abc\n"
);
}
#[test]
fn a_non_ascii_value_leaves_the_column_alone() {
let lines = ["- **Owner**: 日本語", "- **ID**: abc"];
let rendered = render_metadata_table(&lines, false);
assert_eq!(
rendered,
"Owner 日本語\n\
ID abc\n"
);
}
#[test]
fn a_field_the_tool_does_not_know_still_gets_a_row() {
let rendered = render_metadata_table(&["- **ID**: abc", "- **Sprint**: 14"], false);
assert!(rendered.contains("Sprint 14"), "{rendered:?}");
}
#[test]
fn a_line_that_is_not_a_field_is_carried_through() {
let rendered =
render_metadata_table(&["- **ID**: abc", "a hand written note"], false);
assert_eq!(
rendered,
"ID abc\n\
a hand written note\n"
);
}
#[test]
fn the_priority_cell_carries_the_mark_and_the_stored_number() {
let rendered = render_metadata_table(&["- **Priority**: 2"], false);
let (glyph, _) = priority_mark(Priority::Level(2));
assert_eq!(rendered, format!("Priority {glyph} 2\n"));
}
#[test]
fn an_unset_priority_reads_as_unset_in_the_table() {
let rendered = render_metadata_table(&["- **Priority**: _Not set_"], false);
let (glyph, _) = priority_mark(Priority::Unset);
assert_eq!(rendered, format!("Priority {glyph} _Not set_\n"));
}
/// A ticket with the two things that used to leak: a numbered plan, and a
/// hand-written line inside the Metadata section.
const BOTH_LEAKS: &str = "# T\n\n## Implementation Plan\n1. First step\n2. Second step\n\
\n## Metadata\n\n- **ID**: abc\nA **handwritten** note\n";
/// The bug: the board asks for `content_trim(content, false)` because a paragraph
/// 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);
assert!(
!rendered.contains('\x1b'),
"an escape survived colour being off: {rendered:?}"
);
// And the content is all still there, in plain form.
assert!(rendered.contains("1. First step"), "{rendered:?}");
assert!(rendered.contains("**handwritten**"), "{rendered:?}");
}
/// The other half of the pair, and the one that makes the first mean something:
/// with the flag on, both paths still colour. Without this, the passing test above
/// 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);
assert!(
rendered.contains(&format!("{}1.", Color::Cyan.ansi())),
"the plan number lost its colour: {rendered:?}"
);
assert!(
rendered.contains(&format!("{}handwritten", Color::Magenta.ansi())),
"the bold run lost its colour: {rendered:?}"
);
}
/// The flag has to be the only thing that decides, or the disabled path is just
/// the terminal's answer in disguise — which is why the leak survived a test
/// asserting the detail view holds no escapes. In a test binary there is no tty,
/// so `should_use_colors()` is false and the leaking branch was never taken.
#[test]
fn nothing_the_body_renders_asks_the_terminal_for_the_colour_decision() {
let callers = callers_of_color_text(include_str!("util.rs"));
// `ambiguous` is the one that may: it builds the candidate list for a failed
// search, reaches the user on stderr, and is not reachable from `content_trim`.
assert_eq!(
callers,
vec!["ambiguous".to_string()],
"`color_text` asks `should_use_colors()`. Everything reachable from \
`content_trim` has to take the decision as an argument and pass it to \
`paint` instead, because the board renders with colour off and an escape \
in a ratatui paragraph is drawn as literal bytes. If the new caller really \
is CLI-only, add it here and say why."
);
}
/// Which functions in this file call `color_text`, by name, definitions and the
/// test module excluded.
fn callers_of_color_text(source: &str) -> Vec<String> {
let body = match source.find("\n#[cfg(test)]") {
Some(end) => &source[..end],
None => source,
};
let mut current = String::new();
let mut callers = Vec::new();
for line in body.lines() {
if let Some(rest) = line.strip_prefix("fn ").or_else(|| line.strip_prefix("pub fn ")) {
current = rest.split('(').next().unwrap_or_default().to_string();
continue;
}
if line.contains("color_text(") && !callers.contains(&current) {
callers.push(current.clone());
}
}
callers
}
#[test]
fn a_section_rule_matches_the_width_of_its_name() {
let rendered = content_trim_colored("# T\n\n## Description\nbody\n");
// Eleven characters, not fourteen: the rule used to span "## Description"
assert!(
rendered.starts_with("Description\n───────────\n"),
"{rendered:?}"
);
}
#[test]
fn a_non_ascii_section_name_is_not_over_drawn() {
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");
assert!(!rendered.contains("Only Once"), "{rendered:?}");
// And no gap where it was
assert!(rendered.starts_with("Description"), "{rendered:?}");
}
#[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);
assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n");
}
#[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);
assert!(rendered.contains("ID abc"), "{rendered:?}");
assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}");
assert!(rendered.ends_with("after\n"), "{rendered:?}");
}
#[test]
fn blank_values_are_trimmed_from_the_ends_but_kept_inside() {
let owned = |values: &[&str]| -> Vec<String> {
values.iter().map(|v| v.to_string()).collect()
};
// A break between paragraphs is content
let two_paragraphs = owned(&["First.", "", "Second."]);
assert_eq!(trim_blank_ends(&two_paragraphs), two_paragraphs.as_slice());
// A run of them is kept verbatim rather than collapsed
let wide = owned(&["A", "", "", "B"]);
assert_eq!(trim_blank_ends(&wide), wide.as_slice());
// The ends are not
assert_eq!(
trim_blank_ends(&owned(&["", " ", "Only.", "", ""])),
owned(&["Only."]).as_slice()
);
// Nothing but blanks is nothing at all
assert!(trim_blank_ends(&owned(&["", " ", ""])).is_empty());
assert!(trim_blank_ends(&[]).is_empty());
// A single value survives either way
assert_eq!(trim_blank_ends(&owned(&["One."])), owned(&["One."]).as_slice());
}
#[test]
fn a_level_in_range_parses() {
for level in 1..=5u8 {
let content = ticket_with_priority(&level.to_string());
assert_eq!(parse_priority(&content), Priority::Level(level));
}
}
#[test]
fn a_missing_or_unset_level_is_unset() {
assert_eq!(parse_priority("# T\n\n## Metadata\n"), Priority::Unset);
assert_eq!(parse_priority(&ticket_with_priority("_Not set_")), Priority::Unset);
assert_eq!(parse_priority(&ticket_with_priority("_None_")), Priority::Unset);
}
/// Distinct from unset on purpose: a typo must not read as "no priority".
#[test]
fn an_out_of_range_or_unparseable_level_is_invalid() {
for raw in ["0", "6", "42", "high", "-1", "1.5", "999999999999"] {
assert_eq!(
parse_priority(&ticket_with_priority(raw)),
Priority::Invalid,
"for {raw:?}"
);
}
}
#[test]
fn levels_sort_ahead_of_invalid_which_sorts_ahead_of_unset() {
let mut ranks = [Priority::Unset, Priority::Level(5), Priority::Invalid, Priority::Level(1)]
.map(|p| p.rank());
ranks.sort();
assert_eq!(
ranks,
[
Priority::Level(1).rank(),
Priority::Level(5).rank(),
Priority::Invalid.rank(),
Priority::Unset.rank()
]
);
}
#[test]
fn each_level_gets_its_own_glyph_and_colour() {
let marks: Vec<_> = PRIORITY_RANGE
.map(|level| priority_mark(Priority::Level(level)))
.collect();
let glyphs: std::collections::HashSet<_> = marks.iter().map(|(g, _)| *g).collect();
assert_eq!(glyphs.len(), marks.len(), "two levels share a glyph");
let colours: std::collections::HashSet<_> = marks.iter().map(|(_, c)| *c).collect();
assert_eq!(colours.len(), marks.len(), "two levels share a colour");
}
/// The glyph has to carry the level with colour off, which is how every pipe
/// and every opencode tool reads it.
#[test]
fn the_glyph_alone_distinguishes_every_state() {
let mut seen = std::collections::HashSet::new();
for state in PRIORITY_RANGE.map(Priority::Level).chain([Priority::Unset, Priority::Invalid]) {
let (glyph, _) = priority_mark(state);
assert!(seen.insert(glyph), "{glyph} is used for more than one state");
}
}
#[test]
fn the_fullest_mark_is_the_most_urgent() {
assert_eq!(priority_mark(Priority::Level(1)).0, "\u{25cf}\u{25cf}");
assert_eq!(priority_mark(Priority::Level(5)).0, "\u{25cb}\u{25cb}");
}
/// Every mark is the same width, or the column stops lining up.
#[test]
fn every_mark_is_the_same_width() {
let widths: std::collections::HashSet<usize> = PRIORITY_RANGE
.map(Priority::Level)
.chain([Priority::Unset, Priority::Invalid])
.map(|p| priority_mark(p).0.chars().count())
.collect();
assert_eq!(widths, std::collections::HashSet::from([2]));
}
/// The marks are built only from what frig already renders in this terminal:
/// the quadrant circles are in a quarter as many fonts and got substituted
/// from a fallback font that drew them oversized.
#[test]
fn marks_use_only_the_glyphs_known_to_render() {
let allowed = ['\u{25cf}', '\u{25d0}', '\u{25cb}', '\u{b7}', '?'];
for state in PRIORITY_RANGE
.map(Priority::Level)
.chain([Priority::Unset, Priority::Invalid])
{
for ch in priority_mark(state).0.chars() {
assert!(allowed.contains(&ch), "{ch:?} is outside the safe set");
}
}
}
#[test]
fn the_meter_empties_as_the_level_rises() {
let ink = |p: Priority| -> f32 {
priority_mark(p)
.0
.chars()
.map(|c| match c {
'\u{25cf}' => 1.0,
'\u{25d0}' => 0.5,
_ => 0.0,
})
.sum()
};
let mut previous = f32::MAX;
for level in PRIORITY_RANGE {
let current = ink(Priority::Level(level));
assert!(current < previous, "level {level} does not empty further");
previous = current;
}
}
#[test]
fn an_invalid_level_is_marked_wrong_not_unset() {
assert_eq!(priority_mark(Priority::Invalid).0, "??");
assert_ne!(
priority_mark(Priority::Invalid),
priority_mark(Priority::Unset)
);
}
#[test]
fn the_legend_covers_every_level_and_says_which_way_it_runs() {
let legend = priority_legend();
for level in PRIORITY_RANGE {
let (glyph, _) = priority_mark(Priority::Level(level));
assert!(legend.contains(glyph), "{glyph} missing from the legend");
assert!(legend.contains(&level.to_string()));
}
assert!(legend.contains("most urgent"), "direction not spelled out");
}
/// Green means title; a priority must not borrow it.
#[test]
fn the_ramp_avoids_green() {
for level in PRIORITY_RANGE {
assert_ne!(priority_mark(Priority::Level(level)).1, Color::Green);
}
}
#[test]
fn every_colour_has_an_escape_and_a_ratatui_equivalent() {
// The old version of this test guarded against a name with no entry, which the
// enum now makes a compile error. What is left worth asserting is that no
// variant renders as nothing, and that the two renderers agree on the set.
let mut seen = std::collections::HashSet::new();
for colour in Color::ALL {
assert!(!colour.ansi().is_empty(), "{colour:?} has no escape");
assert!(
colour.ansi().starts_with("\x1b["),
"{colour:?} is not an SGR sequence"
);
assert!(seen.insert(ratatui::style::Color::from(colour)), "{colour:?} shares its ratatui colour");
}
assert_eq!(seen.len(), Color::ALL.len());
}
/// Pinned deliberately. Both SGR spellings of grey failed on a real palette,
/// 90 reading nearly as light as the foreground and 37 sitting on top of it.
/// This is the exact sequence crossterm emits for ratatui's Color::DarkGray,
/// so worklane's grey is the one frig and pantop already render.
#[test]
fn grey_matches_the_indexed_colour_frig_uses() {
assert_eq!(Color::Grey.ansi(), "\x1b[38;5;8m");
}
/// With no colour to carry the emphasis, the markers are the emphasis.
#[test]
fn bold_markers_survive_when_colour_is_off() {
let line = "Some **bold** text";
assert_eq!(colorize_bold(line, false), line);
}
#[test]
fn bold_markers_are_replaced_when_colour_is_on() {
let out = colorize_bold("Some **bold** text", true);
assert!(out.contains("bold"), "was {out:?}");
assert!(!out.contains("**"), "markers left behind in {out:?}");
}
/// The old scan ran past the end here and dropped the last character.
#[test]
fn an_unterminated_marker_keeps_the_whole_line() {
for line in ["a **bold", "**", "***", "trailing **"] {
assert_eq!(colorize_bold(line, true), line, "for {line:?}");
}
}
#[test]
fn several_bold_runs_on_one_line_all_survive() {
let out = colorize_bold("**one** and **two** and rest", true);
assert!(out.contains("one") && out.contains("two") && out.ends_with("and rest"));
assert!(!out.contains("**"), "was {out:?}");
}
#[test]
fn short_id_shortens_a_full_uuid() {
assert_eq!(short_id("c230d2c6-d78a-44a5-8f5f-88fb28f84493"), "c230d2c");
}
#[test]
fn short_id_leaves_anything_shorter_alone() {
assert_eq!(short_id("abc"), "abc");
assert_eq!(short_id(""), "");
assert_eq!(short_id("abcdefg"), "abcdefg");
}
/// The cut used to land inside a character and panic.
#[test]
fn short_id_counts_characters_not_bytes() {
assert_eq!(short_id("émigré-ticket"), "émigré-");
assert_eq!(short_id("日本語"), "日本語");
}
#[test]
fn created_at_is_shortened_for_display() {
assert_eq!(format_created_at("2026-08-20 13:06:34"), "26-08-20:13");
}
/// Every one of these reached the old byte offsets from an unvalidated file.
#[test]
fn unparseable_created_at_drops_the_column() {
for value in ["_Not set_", "", "2026-08-20", "日本語日本語日本語", "not a date at all"] {
assert_eq!(format_created_at(value), "", "for {value:?}");
}
}
}