//! What happened to a ticket, one file per entry. //! //! The comments directory was already an append-only log with exactly one event kind: //! one file per entry under a directory named by the ticket's uuid, stamped to the //! microsecond and written with `create_new` so two writers cannot clobber each other. //! This is that log with the kind named in it, so a status change, an owner change, a //! tag change and a campaign move are recorded beside what somebody said about them. //! //! What is deliberately not logged: ticking or unticking a criterion, and edits to the //! title, description, plan, priority or due. Those change often and a log of them is //! noise. When one of them matters, whoever made it adds a comment saying why, which is //! the record actually worth keeping. //! //! Every entry names its author, from [`resolve_actor`], so a board several agents write //! to says which of them did what. //! //! [`resolve_actor`]: crate::util::resolve_actor use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use anyhow::{Result, anyhow}; use chrono::Local; use crate::util::{ Cell, Color, MISSING, TIMESTAMP_FORMAT, is_unknown_value, paint_cells, quoted_cells, should_use_colors, tag_cells, tag_color, }; /// Where a ticket's history lives, under the board. /// /// Beside the status directories rather than among them, the way `campaigns_dir` is: an /// entry has no status of its own. Spelled once here, so the writer, the reader and the /// card's counter cannot disagree about the path. pub const HISTORY_DIR: &str = "history"; /// The name the same directory had while a comment was the only entry it could hold. /// /// Kept so a board written by an older version is adopted rather than migrated by hand. /// See [`adopt_comments`]. pub const COMMENTS_DIR: &str = "comments"; /// How an entry filename is stamped. /// /// Microseconds, not seconds: at second resolution two entries in the same second /// produced the same name and the second silently truncated the first. Fixed width and /// first in the name, so the lexicographic sort in [`read_history`] stays chronological /// whatever kind follows it. pub const ENTRY_FILE_FORMAT: &str = "%Y%m%d_%H%M%S_%6f"; /// The history root of a board. pub fn history_root(board: &Path) -> PathBuf { board.join(HISTORY_DIR) } /// The history directory for one ticket, named by its full uuid. pub fn history_dir(board: &Path, uuid: &str) -> PathBuf { history_root(board).join(uuid) } /// What an entry records. /// /// An enum rather than a string, so a kind the reader does not know is a compile error /// instead of a word that renders as itself. The variants are the five things worth /// keeping: what somebody said, and the four fields whose history answers a question. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { Comment, Status, Owner, Tags, Campaign, } impl Kind { /// Every kind, which is what the reader matches a marker against and what the /// counter matches a filename against. pub const ALL: [Kind; 5] = [ Kind::Comment, Kind::Status, Kind::Owner, Kind::Tags, Kind::Campaign, ]; /// The width the mechanical labels are padded to, `campaign` being the longest of /// the four. `comment` renders as a header and a body, not as a row, so it is not /// among them. const LABEL_WIDTH: usize = 8; /// The word in the filename, and the label a mechanical entry renders under. pub fn slug(self) -> &'static str { match self { Kind::Comment => "comment", Kind::Status => "status", Kind::Owner => "owner", Kind::Tags => "tags", Kind::Campaign => "campaign", } } /// The marker the file opens with, which is what the reader keys the kind off. /// /// The file is the record and the filename is an index into it: a name can be /// changed by anything that touches the directory, so the kind is read from the /// content and only counted from the name. fn marker(self) -> &'static str { match self { Kind::Comment => "**Comment**", Kind::Status => "**Status**", Kind::Owner => "**Owner**", Kind::Tags => "**Tags**", Kind::Campaign => "**Campaign**", } } } /// One entry: what happened, who wrote it and when. #[derive(Debug)] pub struct Entry { /// The file stem, which is what the entries are sorted by. pub filename: String, pub kind: Kind, pub author: String, pub time: String, /// A comment's text, or the before and after of the field a mechanical entry names. pub body: String, /// Why a mechanical entry happened, as `mv --reason` gave it. Empty for every entry /// that carries no such field, which is all of them but a reasoned move — including /// every entry written before reasons existed. pub reason: String, } /// Rename an old `comments` directory to `history`, before anything reads or writes it. /// /// One rename rather than a migration command: the entries themselves need no rewriting, /// since [`parse_entry`] reads a file with no marker as the comment it is. Called by the /// reader, the writer and the counter, so no caller has to remember it and a board can /// never be reached through a path that skips it. /// /// Both directories at once is refused rather than merged. Only the CLI writes there, so /// it cannot arrive at that state on its own, and choosing which of two entries with the /// same name survives is not a decision to make silently. pub fn adopt_comments(board: &Path) -> Result<()> { let old = board.join(COMMENTS_DIR); if !old.exists() { return Ok(()); } let new = history_root(board); if new.exists() { return Err(anyhow!( "Board holds both {} and {}. Only worklane writes there, so this needs a \ person: move the entries under {} into the matching directories in {}, \ then remove it.", old.display(), new.display(), COMMENTS_DIR, HISTORY_DIR, )); } fs::rename(&old, &new) .map_err(|e| anyhow!("Could not rename {} to {}: {}", old.display(), new.display(), e)) } /// One entry, from its filename and its content. /// /// Split out from the directory walk so the parse can be tested without a fixture, and /// because it is where the compatibility lives: a file with no marker is a comment, /// which is what every entry written before the kinds existed is. fn parse_entry(filename: &str, content: &str) -> Entry { let field = |name: &str| { let marker = format!("**{}**:", name); content .lines() .find(|line| line.starts_with(&marker)) .and_then(|line| line.split_once(&marker)) .map(|(_, value)| value.trim().to_string()) .unwrap_or_else(|| "unknown".to_string()) }; let kind = Kind::ALL .into_iter() .find(|kind| content.starts_with(&format!("{}\n", kind.marker()))) .unwrap_or(Kind::Comment); let body = content .strip_prefix(&format!("{}\n", kind.marker())) .map(|rest| match rest.find("\n\n**Author**") { Some(end) => rest[..end].trim(), None => rest.trim(), }) .unwrap_or(""); // A missing reason is legitimate rather than unreadable, which is why this does not // share the `unknown` fallback the two fields above carry: every entry written // before `mv --reason` existed has none. let reason = content .lines() .find_map(|line| line.strip_prefix("**Reason**:")) .map(str::trim) .unwrap_or_default() .to_string(); Entry { filename: filename.to_string(), kind, author: field("Author"), time: field("Time"), body: body.to_string(), reason, } } /// Every entry on a ticket, oldest first. /// /// Public for the TUI's detail view, which shows the same sequence `show` does. pub fn read_history(board: &Path, uuid: &str) -> Result> { adopt_comments(board)?; let dir = history_dir(board, uuid); if !dir.exists() { return Ok(vec![]); } let mut entries: Vec = Vec::new(); for entry in fs::read_dir(&dir)? { let path = entry?.path(); if path.extension().is_some_and(|ext| ext == "md") { let content = fs::read_to_string(&path)?; let filename = path .file_stem() .map(|stem| stem.to_string_lossy().to_string()) .unwrap_or_default(); entries.push(parse_entry(&filename, &content)); } } // The stamp is fixed width and leads the name, so this is chronological. entries.sort_by(|a, b| a.filename.cmp(&b.filename)); Ok(entries) } /// The kind a filename names, which is what the count reads instead of the file. /// /// A stem with no kind in it is a comment, the same compatibility [`parse_entry`] has. /// The collision suffix is a number and matches no slug, so it is skipped. fn kind_from_stem(stem: &str) -> Kind { stem.split('_') .find_map(|part| Kind::ALL.into_iter().find(|kind| kind.slug() == part)) .unwrap_or(Kind::Comment) } /// How many comments a ticket carries, counted off the directory rather than read. /// /// Comments only, so the card's counter still says how many things somebody said: a /// ticket that has moved three times has not been talked about. `.md` only, the filter /// [`read_history`] applies, so a stray file dropped in there is not counted. A missing /// directory is none, which is what a ticket nothing has happened to has. pub fn count_comments(board: &Path, uuid: &str) -> usize { // Swallowed, unlike the reader's: a count is drawn on every card and a board that // cannot be adopted has to draw as the zero it looks like rather than take the TUI // down. The next write reports the real reason. let _ = adopt_comments(board); let Ok(entries) = fs::read_dir(history_dir(board, uuid)) else { return 0; }; entries .filter_map(|entry| entry.ok()) .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "md")) .filter(|entry| { let stem = entry.path().file_stem().map(|s| s.to_string_lossy().to_string()); stem.is_some_and(|stem| kind_from_stem(&stem) == Kind::Comment) }) .count() } /// The file an entry is written as. /// /// A comment's file is byte for byte what `comment` wrote before the kinds existed, so /// nothing has to be rewritten and a board can be read by either version. /// /// The optional reason rides after **Time**, so the two fields every entry has always /// carried keep their places and an older binary reading this file finds its body and /// fields exactly where they were. Empty writes no line, which is what keeps a reasoned /// entry and one without reading as the same shape minus the field. fn entry_content(kind: Kind, body: &str, author: &str, time: &str, reason: &str) -> String { let mut content = format!( "{}\n\ {}\n\ \n\ **Author**: {}\n\ **Time**: {}\n", kind.marker(), body, author, time ); if !reason.is_empty() { content.push_str(&format!("**Reason**: {}\n", reason)); } content } /// Write an entry under the first free name derived from the stamp. /// /// `create_new` rather than `fs::write`: a name that already exists means another entry /// landed in the same microsecond, and truncating it is exactly the data loss this /// guards against. The suffix is zero padded so the names keep sorting in the order they /// were written. fn write_new(dir: &Path, stem: &str, content: &str) -> Result { for attempt in 0..100 { let filename = match attempt { 0 => format!("{}.md", stem), n => format!("{}_{:02}.md", stem, n), }; match fs::OpenOptions::new() .write(true) .create_new(true) .open(dir.join(&filename)) { Ok(mut file) => { file.write_all(content.as_bytes())?; return Ok(filename); } Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(e.into()), } } Err(anyhow!("No free entry filename for '{}' in {}", stem, dir.display())) } /// Record one entry on a ticket, returning the filename it landed under. /// /// Called after the edit it describes has been written, never before: an entry for a /// move that was refused would be a log of things that did not happen. The cost of that /// order is that a failed write here leaves the edit in place and reports the failure, /// which is the right way round — the ticket is the record and this is the story of it. /// /// `reason` is the why [`Kind::Status`] can carry, from `mv --reason`; every other kind /// passes the empty slice and gets no field written. pub fn write_entry( board: &Path, uuid: &str, kind: Kind, body: &str, author: &str, reason: &str, ) -> Result { adopt_comments(board)?; let dir = history_dir(board, uuid); fs::create_dir_all(&dir)?; let now = Local::now(); let stem = format!("{}_{}", now.format(ENTRY_FILE_FORMAT), kind.slug()); let content = entry_content(kind, body, author, &now.format(TIMESTAMP_FORMAT).to_string(), reason); write_new(&dir, &stem, &content) } /// What joins the two halves of a mechanical body, and the only thing that tells them /// apart. /// /// Spelled once, beside the writer that puts it in and the reader that takes it out, so /// the two cannot disagree about where one value ends and the next begins. A renderer /// carrying its own copy of the spacing would go on splitting on a separator this one no /// longer writes, and would say so by drawing a whole body as one half. const CHANGE_SEPARATOR: &str = " → "; /// What a mechanical entry records: the field before the edit and after it. /// /// The values as the ticket holds them, sentinels included, so `_Not set_` reads the way /// the field it came from does rather than being translated into a word this module /// invented. pub fn change(before: &str, after: &str) -> String { format!("{}{}{}", before, CHANGE_SEPARATOR, after) } /// The before and after of a mechanical body, or `None` for a body not shaped as one. /// /// Everything [`change`] writes splits, but an entry read off a board is whatever the /// file holds, and a body that does not split is drawn whole rather than as a half of /// something. `split_once`, so a value that carries the arrow itself keeps it: only the /// first separator is the one this module wrote. fn split_change(body: &str) -> Option<(&str, &str)> { body.split_once(CHANGE_SEPARATOR) } pub fn format_history(entries: &[Entry]) -> String { format_history_with(entries, should_use_colors()) } /// As above, with the colour decision passed in. pub fn format_history_with(entries: &[Entry], colored: bool) -> String { paint_cells(&history_cells(entries, colored), colored) } /// The cells one value in a mechanical body is drawn as, per the Color Guideline. /// /// Keyed on the kind, because the kind is what says which field the value came from: the /// same word is a status in one entry and a tag in another, and nothing in the value /// itself could tell them apart. Every meaning here is the one the value already carries /// in the metadata table three lines above, which is the whole point — the block is not /// worth scanning if it has a palette of its own to learn first. fn value_cells(kind: Kind, value: &str) -> Vec { // The sentinels first, whichever field they stand in. `_Not set_` in a tag colour // would read as a campaign somebody named that, and grey is what an absent value is // drawn in everywhere else. `_missing_` joins them here rather than in // `is_unknown_value`: the field was set, and what it pointed at is gone. if is_unknown_value(value) || value == MISSING { return vec![Cell::colored(value, Color::Grey)]; } match kind { Kind::Status => vec![Cell::colored(value, Color::Orange)], Kind::Tags => tag_cells(value), // The codename in the colour that groups it everywhere else, and without the `~` // a card's label carries: the kind at the head of the row has already said what // this is, which is the same reason the `Codename` field takes the colour bare. Kind::Campaign => vec![Cell::colored(value, tag_color(value))], // A name is a value the palette has no meaning for, and spending one on the field // that needs it least is how a colour stops meaning anything. `Comment` is here // for the compiler: a comment's body is not a value and never reaches this. Kind::Owner | Kind::Comment => vec![Cell::plain(value)], } } /// Who wrote an entry and when, as two spans rather than one. /// /// The actor through `tag_color`, the way a campaign codename is drawn. Not a new meaning /// for a reserved colour but the existing use of the tag slots — a name that groups rows /// — and it is what lets a reader see who has been working a ticket without reading the /// same name four times. Cyan goes back to meaning the timestamp alone, which is what it /// means everywhere else; it covered the name too while the two were one string. fn stamp_cells(entry: &Entry) -> Vec { vec![ Cell::colored(entry.author.as_str(), tag_color(&entry.author)), Cell::plain(" ("), Cell::colored(entry.time.as_str(), Color::Cyan), Cell::plain(")"), ] } /// One segment of the history block: what it is, and how a renderer lays it out. /// /// [`history_cells`] flattens these into the cells the CLI paints, and the board turns /// each segment into its own stretch of the overlay instead: the flow runs full width /// while a quoted run becomes a gutter column with the bar in it and the body beside it, /// so a row the body wraps keeps the mark. One segmentation, two shapes — neither /// renderer re-decides which runs are somebody's words. #[derive(Debug)] pub enum HistoryPart { /// Headers, mechanical rows and the blank lines between entries, as they stand. Flow(Vec), /// A comment's body or a move's reason: plain text, every line of it quoted, in /// whatever shape the renderer quotes with. Quoted(String), } /// The block as segments, one walk over the entries. /// /// The order is the entries' own, oldest first, and a quoted run always sits between two /// flow runs — the header or mechanical row before it and the blank line after it — so a /// renderer can treat each segment as one unbroken stretch of rows. pub fn history_parts(entries: &[Entry]) -> Vec { let mut parts = Vec::new(); // The flow accumulating until the next quote closes it, which is why the trailing // newline of every entry lands in the segment *after* a quote rather than being // dropped: flattened, the parts are byte for byte the block [`history_cells`] has // always built, which is what the CLI's pins hold it to. let mut flow: Vec = Vec::new(); if entries.is_empty() { flow.push(Cell::colored("No history yet.", Color::Grey)); parts.push(HistoryPart::Flow(flow)); return parts; } flow.push(Cell::plain("\n")); flow.push(Cell::colored("HISTORY", Color::Orange)); flow.push(Cell::plain(format!("\n{}\n", "─".repeat(20)))); for entry in entries { flow.push(Cell::plain("\n")); match entry.kind { // As it has always read: a header naming who said it, then the text. Kind::Comment => { flow.push(Cell::colored("From", Color::Grey)); flow.push(Cell::plain(" ")); flow.extend(stamp_cells(entry)); flow.push(Cell::plain("\n")); if !entry.body.is_empty() { parts.push(HistoryPart::Flow(std::mem::take(&mut flow))); parts.push(HistoryPart::Quoted(entry.body.clone())); } flow.push(Cell::plain("\n")); } // One line: a field change is one fact and a paragraph for it would bury the // comments it sits between. A reason draws behind the same bar the comments // draw, since it shares their shape and their gap, so it reads as attached // to the transition it explains rather than as the next entry. _ => { let padding = Kind::LABEL_WIDTH.saturating_sub(entry.kind.slug().chars().count()); // Grey, as chrome. It was orange, which means Status everywhere else, so // an `owner` or `tags` label claimed a meaning belonging to the value // beside it. The label is not a value at all: it names the row, which is // what grey already says. flow.push(Cell::colored(entry.kind.slug(), Color::Grey)); // Measured on the unpainted label and carried in a cell of its own, the // rule the metadata table follows: measuring a painted string counts its // escapes towards its width, which tilts the column when colour is on and // not when it is off. flow.push(Cell::plain(format!("{} ", " ".repeat(padding)))); match split_change(&entry.body) { Some((before, after)) => { flow.extend(value_cells(entry.kind, before)); flow.push(Cell::plain(CHANGE_SEPARATOR)); flow.extend(value_cells(entry.kind, after)); } None => flow.extend(value_cells(entry.kind, &entry.body)), } flow.push(Cell::plain(" ")); flow.extend(stamp_cells(entry)); flow.push(Cell::plain("\n")); // The newline is the quote's terminator, so it exists only when there is // one: a reasoned row draws the reason under itself and this closes it. if !entry.reason.is_empty() { parts.push(HistoryPart::Flow(std::mem::take(&mut flow))); parts.push(HistoryPart::Quoted(entry.reason.clone())); flow.push(Cell::plain("\n")); } } } } if !flow.is_empty() { parts.push(HistoryPart::Flow(flow)); } parts } /// The block laid out once, as [`Cell`]s: the CLI paints them and the board turns the /// same ones into styled spans, so the two views cannot draw two different blocks. /// /// The flatten of [`history_parts`], which is what makes the CLI's bytes a property of /// the segmentation rather than a second walk that can drift from it: the pins over this /// function's output are pins over the parts too. The colour decision rides in because /// the quote bar is a coloured decoration; with it off the cells carry the indent the /// bar would have provided. The board does not come through here — it lays each part in /// the shape the section builder gives it — but it reads the same parts. pub fn history_cells(entries: &[Entry], colored: bool) -> Vec { let mut cells = Vec::new(); for part in history_parts(entries) { match part { HistoryPart::Flow(run) => cells.extend(run), HistoryPart::Quoted(body) => cells.extend(quoted_cells(&body, colored)), } } cells } #[cfg(test)] mod tests { use super::*; use crate::util::{ BLOCKED_MARK, Fixture, NOT_SET, PRIORITY_RANGE, Priority, QUOTE_BAR, REGRESSION_MARK, RELATES_MARK, paint, priority_mark, status_dirs, status_mark, }; /// One entry, spelled the way a file on the board holds it. fn entry(kind: &str, body: &str, author: &str, time: &str) -> Entry { let marker = format!("**{}{}**", kind[..1].to_uppercase(), &kind[1..]); parse_entry( &format!("20260824_120000_000000_{kind}"), &format!("{marker}\n{body}\n\n**Author**: {author}\n**Time**: {time}\n"), ) } /// What a painted block reads as once the escapes are taken off, so a test can /// measure a column without counting sequences that occupy none. fn strip_escapes(text: &str) -> String { let mut out = String::with_capacity(text.len()); let mut rest = text; while let Some(at) = rest.find('\x1b') { out.push_str(&rest[..at]); match rest[at..].find('m') { Some(end) => rest = &rest[at + end + 1..], None => return out, } } out.push_str(rest); out } fn board() -> Fixture { Fixture::new("worklane-history") } #[test] fn an_entry_names_its_kind_in_the_file_and_in_the_filename() { let board = board(); let filename = write_entry(&board, "uuid", Kind::Status, "committed → reviewing", "claude", "") .unwrap(); assert!(filename.ends_with("_status.md"), "was {filename}"); let entries = read_history(&board, "uuid").unwrap(); assert_eq!(entries.len(), 1); assert_eq!(entries[0].kind, Kind::Status); assert_eq!(entries[0].body, "committed → reviewing"); assert_eq!(entries[0].author, "claude"); assert_eq!(entries[0].reason, ""); } /// One file, one event, its explanation: the reason rides in the entry that records /// the transition it explains, as a field after **Time**, and round-trips. #[test] fn a_reason_is_recorded_in_the_file_and_read_back() { let board = board(); let filename = write_entry( &board, "uuid", Kind::Status, "reviewing → backlog", "claude", "sent back: the first plan was wrong", ) .unwrap(); let content = fs::read_to_string(history_dir(&board, "uuid").join(filename)).unwrap(); assert!( content.ends_with("**Reason**: sent back: the first plan was wrong\n"), "{content}" ); // The fields every reader keys off keep their places above it assert!(content.contains("**Time**:"), "{content}"); assert!(content.find("**Author**").unwrap() < content.find("**Reason**").unwrap()); let entries = read_history(&board, "uuid").unwrap(); assert_eq!(entries.len(), 1); assert_eq!(entries[0].body, "reviewing → backlog"); assert_eq!(entries[0].reason, "sent back: the first plan was wrong"); } /// The stamp leads the name and is fixed width, so the kind that follows it cannot /// reorder the log. #[test] fn the_kind_in_the_name_does_not_disturb_the_order() { let mut names = [ "20260824_120000_000000_status", "20260824_115959_999999_tags", "20260824_120000_000001_comment", ]; names.sort(); assert_eq!( names, [ "20260824_115959_999999_tags", "20260824_120000_000000_status", "20260824_120000_000001_comment", ] ); } /// A file written before the kinds existed: no marker, so it is the comment it was, /// and nothing rewrites it. #[test] fn an_entry_with_no_marker_is_a_comment() { let legacy = parse_entry( "20260820_143012_123456", "**Comment**\nSomething said\n\n**Author**: Ansho Rei\n**Time**: 2026-08-20 14:30:12\n", ); assert_eq!(legacy.kind, Kind::Comment); assert_eq!(legacy.body, "Something said"); assert_eq!(legacy.author, "Ansho Rei"); // And one with no marker at all, which is what `read_comments` read as empty. let bare = parse_entry("20260820_143012_123457", "notes\n"); assert_eq!(bare.kind, Kind::Comment); assert_eq!(bare.body, ""); } /// The comment file is byte for byte what `comment` wrote before this module, which /// is what lets an old board be read without a migration. #[test] fn a_comment_file_is_shaped_as_it_always_was() { let content = entry_content(Kind::Comment, "A body", "claude", "2026-08-24 12:00:00", ""); assert_eq!( content, "**Comment**\nA body\n\n**Author**: claude\n**Time**: 2026-08-24 12:00:00\n" ); } /// Same microsecond, three entries: the guard is `create_new`, and the suffix keeps /// them in the order they were written. #[test] fn entries_in_one_microsecond_get_names_of_their_own() { let board = board(); let dir = history_dir(&board, "uuid"); fs::create_dir_all(&dir).unwrap(); let first = write_new(&dir, "20260820_143012_123456_comment", "first").unwrap(); let second = write_new(&dir, "20260820_143012_123456_comment", "second").unwrap(); let third = write_new(&dir, "20260820_143012_123456_comment", "third").unwrap(); assert_eq!(first, "20260820_143012_123456_comment.md"); assert_eq!(second, "20260820_143012_123456_comment_01.md"); assert_eq!(third, "20260820_143012_123456_comment_02.md"); // Nothing was truncated on the way through assert_eq!(fs::read_to_string(dir.join(&first)).unwrap(), "first"); assert_eq!(fs::read_to_string(dir.join(&second)).unwrap(), "second"); assert_eq!(fs::read_to_string(dir.join(&third)).unwrap(), "third"); // read_history sorts on the stem, so the names must sort in write order assert!(first < second && second < third, "the names lost their order"); } #[test] fn an_old_comments_directory_is_adopted_on_access() { let board = board(); let comments = board.join(COMMENTS_DIR).join("uuid"); fs::create_dir_all(&comments).unwrap(); fs::write( comments.join("20260820_143012_123456.md"), "**Comment**\nOld news\n\n**Author**: Ansho Rei\n**Time**: 2026-08-20 14:30:12\n", ) .unwrap(); let entries = read_history(&board, "uuid").unwrap(); assert_eq!(entries.len(), 1); assert_eq!(entries[0].body, "Old news"); assert!(!board.join(COMMENTS_DIR).exists(), "the old directory survived"); assert!(history_dir(&board, "uuid").exists(), "the entries did not arrive"); } /// Refused rather than merged: only the CLI writes there, so this is a board somebody /// has been in by hand, and picking a survivor per name is not a silent decision. #[test] fn a_board_holding_both_directories_is_refused() { let board = board(); fs::create_dir_all(board.join(COMMENTS_DIR).join("uuid")).unwrap(); fs::create_dir_all(history_dir(&board, "uuid")).unwrap(); let refused = read_history(&board, "uuid"); let message = refused.unwrap_err().to_string(); assert!( message.contains(COMMENTS_DIR) && message.contains(HISTORY_DIR), "{message}" ); } /// The count is the card's, and a card counts what somebody said. #[test] fn only_comments_are_counted() { let board = board(); write_entry(&board, "uuid", Kind::Comment, "said", "claude", "").unwrap(); write_entry(&board, "uuid", Kind::Status, "backlog → committed", "claude", "").unwrap(); write_entry(&board, "uuid", Kind::Owner, "_Not set_ → alice", "claude", "").unwrap(); write_entry(&board, "uuid", Kind::Tags, "bug → bug, cli", "claude", "").unwrap(); assert_eq!(read_history(&board, "uuid").unwrap().len(), 4); assert_eq!(count_comments(&board, "uuid"), 1); } /// A stem written before the kinds existed counts as the comment it is. #[test] fn a_legacy_name_counts_as_a_comment() { assert_eq!(kind_from_stem("20260820_143012_123456"), Kind::Comment); assert_eq!(kind_from_stem("20260820_143012_123456_01"), Kind::Comment); assert_eq!(kind_from_stem("20260820_143012_123456_status"), Kind::Status); assert_eq!(kind_from_stem("20260820_143012_123456_status_01"), Kind::Status); } /// The other half of the pair below: with colour off the block is words and spaces, /// and the flag is the only thing that decides. A renderer that painted regardless /// would pass the pin and fail here. #[test] fn a_mechanical_entry_renders_as_one_line_and_a_comment_under_its_author() { let entries = vec![ entry("status", "committed → reviewing", "claude", "2026-08-24 12:00:00"), entry("owner", "_Not set_ → alice", "claude", "2026-08-24 12:00:01"), entry("tags", "bug → bug, cli", "claude", "2026-08-24 12:00:02"), entry("campaign", "_Not set_ → v1", "claude", "2026-08-24 12:00:03"), entry( "comment", "The offset was never passed", "Ansho Rei", "2026-08-24 12:00:04", ), ]; let rendered = format_history_with(&entries, false); assert!(rendered.contains("HISTORY"), "{rendered}"); for row in [ "status committed → reviewing claude (2026-08-24 12:00:00)\n", "owner _Not set_ → alice claude (2026-08-24 12:00:01)\n", "tags bug → bug, cli claude (2026-08-24 12:00:02)\n", "campaign _Not set_ → v1 claude (2026-08-24 12:00:03)\n", ] { assert!(rendered.contains(row), "missing {row:?} in {rendered}"); } // The body keeps the width the bar occupied, and the author line did not move assert!( rendered .contains("From Ansho Rei (2026-08-24 12:00:04)\n The offset was never passed"), "{rendered}" ); // A single line draws no glyph in a pipe, and it is not spared the indent assert!(!rendered.contains(QUOTE_BAR), "{rendered:?}"); assert!(!rendered.contains('\x1b'), "colour off still painted: {rendered:?}"); } /// The pin: `show` prints the block byte for byte, every painted run spelled out, the /// way `show_prints_the_same_body_it_printed_before_the_cells_conversion` pins the /// body. /// /// Rewritten three times, deliberately. `campaign` widened the label column from 6 /// to 8 and put its own row in the pin (f774a33). Then 2733b10 painted the values: /// the label went grey as chrome, each value took the meaning it carries in the /// metadata table, and the actor and the timestamp came apart into two spans. Then /// d447e04 put the single-line body behind the grey quote bar, which is what the /// `{bar}` in the middle of the expected string is. /// /// Every kind is here rather than a representative one, since what each row proves is /// different: status is the orange it is three lines above, tags go through the same /// `tag_cells` the Tags field does, campaign takes its codename's colour, owner is the /// one value the palette says nothing about, and the sentinel in the owner row is grey /// on the same side of an arrow whose other side is not. #[test] fn colour_on_paints_every_value_by_what_the_kind_says_it_is() { let entries = vec![ entry("status", "committed → reviewing", "claude", "2026-08-24 12:00:00"), entry( "comment", "The offset was never passed", "Ansho Rei", "2026-08-24 12:00:01", ), entry("campaign", "_Not set_ → v1", "claude", "2026-08-24 12:00:02"), entry("owner", "_Not set_ → alice", "claude", "2026-08-24 12:00:03"), entry("tags", "bug → bug, cli", "claude", "2026-08-24 12:00:04"), ]; let stamp = |actor: &str, time: &str| { format!( "{} ({})", paint(actor, tag_color(actor), true), paint(time, Color::Cyan, true) ) }; let bar = paint(&format!("{QUOTE_BAR} "), Color::Grey, true); let expected = format!( "\n{}\n{}\n\n{} {} → {} {}\n\n{} {}\n{}The offset was never passed\n\n{} {} → {} {}\n\n{} {} → alice {}\n\n{} {} → {}, {} {}\n", paint("HISTORY", Color::Orange, true), "─".repeat(20), paint("status", Color::Grey, true), paint("committed", Color::Orange, true), paint("reviewing", Color::Orange, true), stamp("claude", "2026-08-24 12:00:00"), paint("From", Color::Grey, true), stamp("Ansho Rei", "2026-08-24 12:00:01"), bar, paint("campaign", Color::Grey, true), paint(NOT_SET, Color::Grey, true), paint("v1", tag_color("v1"), true), stamp("claude", "2026-08-24 12:00:02"), paint("owner", Color::Grey, true), paint(NOT_SET, Color::Grey, true), stamp("claude", "2026-08-24 12:00:03"), paint("tags", Color::Grey, true), paint("bug", tag_color("bug"), true), paint("bug", tag_color("bug"), true), paint("cli", tag_color("cli"), true), stamp("claude", "2026-08-24 12:00:04"), ); assert_eq!(format_history_with(&entries, true), expected); assert_eq!(format_history_with(&[], true), paint("No history yet.", Color::Grey, true)); } /// The actor groups its rows: one writer is one colour wherever it wrote, and it is /// not the timestamp's. Asserted through `tag_color` rather than against a literal, /// so the row has to use the mapping and not a colour that happens to match it today. #[test] fn the_actor_is_one_colour_in_every_entry_and_the_timestamp_keeps_cyan() { let entries = vec![ entry("status", "backlog → committed", "claude", "2026-08-24 12:00:00"), entry("comment", "Said something", "claude", "2026-08-24 12:00:01"), entry("owner", "_Not set_ → alice", "Ansho Rei", "2026-08-24 12:00:02"), ]; let rendered = format_history_with(&entries, true); let painted = paint("claude", tag_color("claude"), true); assert_eq!(rendered.matches(&painted).count(), 2, "{rendered}"); assert!( rendered.contains(&paint("Ansho Rei", tag_color("Ansho Rei"), true)), "{rendered}" ); // Two writers, two colours, and neither of them cyan: that is the timestamp's assert_ne!(tag_color("claude"), tag_color("Ansho Rei")); for time in [ "2026-08-24 12:00:00", "2026-08-24 12:00:01", "2026-08-24 12:00:02", ] { assert!(rendered.contains(&paint(time, Color::Cyan, true)), "{rendered}"); } assert!(!rendered.contains(&paint("claude (", Color::Cyan, true)), "still one span"); } /// The reason is the row's, so it renders behind the same bar the comments draw, /// under the row it explains and before whatever entry follows, in both renderers — /// this is the one layout they share. Paired with the pin above: an entry without a /// reason renders exactly as it always did. #[test] fn a_reason_renders_indented_under_its_row() { let entries = vec![ parse_entry( "20260824_120000_000000_status", "**Status**\nreviewing → backlog\n\n**Author**: claude\n**Time**: 2026-08-24 \ 12:00:00\n**Reason**: sent back, the first plan was wrong\n", ), entry("comment", "And why.", "Ansho Rei", "2026-08-24 12:00:01"), ]; let bar = paint(&format!("{QUOTE_BAR} "), Color::Grey, true); let expected = format!( "\n{}\n{}\n\n{} {} → {} {} ({})\n{}sent back, the first plan was wrong\n\n{} {} ({})\n{}And why.\n", paint("HISTORY", Color::Orange, true), "─".repeat(20), paint("status", Color::Grey, true), paint("reviewing", Color::Orange, true), paint("backlog", Color::Orange, true), paint("claude", tag_color("claude"), true), paint("2026-08-24 12:00:00", Color::Cyan, true), bar, paint("From", Color::Grey, true), paint("Ansho Rei", tag_color("Ansho Rei"), true), paint("2026-08-24 12:00:01", Color::Cyan, true), bar, ); assert_eq!(format_history_with(&entries, true), expected); // Colour off keeps the reason exactly where a pipe has always read it, at the // width the bar occupied, and carries no glyph doing it. let plain = format_history_with(&entries, false); assert!( plain.contains("claude (2026-08-24 12:00:00)\n sent back, the first plan was wrong"), "colour off lost the reason: {plain}" ); assert!(!plain.contains(QUOTE_BAR) && !plain.contains('\x1b'), "{plain:?}"); } /// The reported shape: every line of a run sits behind the bar, so a two-paragraph /// comment reads as one voice start to finish. This is what a single prefix got /// wrong — b304b17's symptom — with every line after the first back at column 0, /// which 2733b10 had just given a meaning to. #[test] fn a_multi_line_comment_draws_every_line_behind_the_bar() { let entries = vec![entry( "comment", "First paragraph.\n\nSecond one, still theirs.", "Ansho Rei", "2026-08-24 12:00:00", )]; let bar = paint(&format!("{QUOTE_BAR} "), Color::Grey, true); let bare = paint(QUOTE_BAR, Color::Grey, true); let rendered = format_history_with(&entries, true); // Both content lines prefixed, and the break between them inside the run as the // bare glyph rather than a gap running nowhere. let expected = format!( "\n{}\n{}\n\n{} {} ({})\n{}First paragraph.\n{}\n{}Second one, still theirs.\n", paint("HISTORY", Color::Orange, true), "─".repeat(20), paint("From", Color::Grey, true), paint("Ansho Rei", tag_color("Ansho Rei"), true), paint("2026-08-24 12:00:00", Color::Cyan, true), bar, bare, bar, ); assert_eq!(rendered, expected); } /// Paired with the one above, the way the guideline demands: colour off drops the /// glyph but keeps the width it occupied, derived from the drawn form, so every /// content line still starts at the same column and no escape byte reaches a pipe. /// The flag is the only thing that decides the bar. #[test] fn colour_off_keeps_the_indent_and_drops_the_glyph() { let entries = vec![entry( "comment", "First paragraph.\n\nSecond one, still theirs.", "Ansho Rei", "2026-08-24 12:00:00", )]; let rendered = format_history_with(&entries, false); let expected = format!( "\nHISTORY\n{}\n\nFrom Ansho Rei (2026-08-24 12:00:00)\n First paragraph.\n\n Second one, still theirs.\n", "─".repeat(20), ); assert_eq!(rendered, expected); } /// The bar is chrome like the kind label, so it takes grey; it is one cell wide; and /// it claims nothing another column already means: the circles and the dot belong to /// the priority meter, the cross and arrows to the relation rows, and the status /// marks reuse both sets. Pinned against the marks actually defined rather than a /// list written out here, so a mark added later fails this instead of sharing. #[test] fn the_quote_bar_claims_no_glyph_another_column_means() { assert_eq!(QUOTE_BAR.chars().count(), 1); let mut taken = String::new(); for level in PRIORITY_RANGE { taken.push_str(priority_mark(Priority::Level(level)).0); } taken.push_str(priority_mark(Priority::Unset).0); taken.push_str(BLOCKED_MARK); taken.push_str(RELATES_MARK); taken.push_str(REGRESSION_MARK); for status in status_dirs() { taken.push_str(status_mark(Some(status)).0); } assert!(!taken.contains(QUOTE_BAR), "{taken:?} already means something"); } /// Padded to the longest of the four, so every body starts in the same column /// however short the label above it is. /// /// Run both ways, which is the whole point of the pairing: the padding is measured on /// the unpainted label and carried in a cell of its own, so the column a value lands /// in cannot depend on the colour decision. Measuring a painted label would count its /// escapes towards its width and tilt the table with colour on and not with it off, /// which is exactly the bug the metadata table already learned. #[test] fn the_mechanical_labels_are_aligned_with_colour_on_and_off() { let bodies = [ ("status", "backlog → committed"), ("owner", "_Not set_ → alice"), ("tags", "bug → bug, cli"), ("campaign", "v1 → beaver"), ]; let entries: Vec = bodies .into_iter() .map(|(kind, body)| entry(kind, body, "claude", "2026-08-24 12:00:00")) .collect(); let columns = |colored: bool| -> Vec { // Stripped before it is measured, so an escape counts for the nothing it // occupies on screen and the two renderings are compared on what a reader sees let rendered = strip_escapes(&format_history_with(&entries, colored)); bodies .into_iter() .map(|(_, body)| rendered.find(body).expect("body missing")) .map(|at| { let line_start = rendered[..at].rfind('\n').map_or(0, |nl| nl + 1); at - line_start }) .collect() }; let plain = columns(false); assert_eq!(plain.len(), 4); assert!(plain.windows(2).all(|pair| pair[0] == pair[1]), "{plain:?}"); assert_eq!(columns(true), plain, "the colour decision moved the column"); } #[test] fn nothing_recorded_says_so() { assert_eq!(format_history_with(&[], false), "No history yet."); } /// The block as segments: the rows drawn as they stand are flow, a comment's body /// and a move's reason are quoted, and each quote sits between two flow runs — the /// row or header before it and the blank after it. This is the one segmentation both /// renderers read, so it is pinned here rather than left to be discovered on the /// board; the CLI's byte pins above hold its flatten to what it has always printed. #[test] fn the_block_splits_into_flow_and_quoted_parts() { let entries = vec![ entry("status", "committed → reviewing", "claude", "2026-08-24 12:00:00"), entry("comment", "First line.\n\nSecond.", "Ansho Rei", "2026-08-24 12:00:01"), entry("status", "reviewing → backlog", "claude", "2026-08-24 12:00:02"), ] .into_iter() .enumerate() .map(|(at, mut entry)| { if at == 2 { entry.reason = "sent back".to_string(); } entry }) .collect::>(); let parts = history_parts(&entries); let shapes: Vec<&str> = parts .iter() .map(|part| match part { HistoryPart::Flow(_) => "flow", HistoryPart::Quoted(_) => "quote", }) .collect(); assert_eq!(shapes, ["flow", "quote", "flow", "quote", "flow"], "{parts:?}"); // The quotes carry the bare words, newlines included; laying them out is the // renderer's decision. for part in &parts { if let HistoryPart::Quoted(body) = part { assert!(!body.contains(QUOTE_BAR), "{body:?}"); } } assert_eq!(parts.len(), 5); } }