From 528566d1037ec4768a841fc59b1cf819afc2d2f6 Mon Sep 17 00:00:00 2001 From: Ansho Rei Date: Sun, 23 Aug 2026 12:08:49 +0200 Subject: [PATCH] (61879a4) Surface campaigns on the board, and bump to 0.20.0 A card label and a frame, not a campaign tab. A tab had to say what its columns are, and a campaign groups across the flow rather than within one status, so the answer is the four columns filtered: a filter on the board it already has, not a fifth tab. So a card names its campaign on the label row, before the tags, marked ~ and bold, and the row drops the tags whole before it drops the campaign. `c` opens a picker; taking a campaign filters every column to its members and draws a frame above them carrying the id, the codename, the name, the opening line of the description and the standing. The standing comes from the columns, since while a campaign is selected the columns are its members. `q` takes off one layer at a time: the overlay, the filter, the board. The label needs something to say, which the stored uuid is not, so campaigns gained `Codename`: one word, `v1` or `beaver`, written by `campaign add --codename` and validated at parse time. `campaign ls` prints it and `resolve_in` gained an exact-codename tier above the uuid prefix, or it would be a field you can read and cannot type. Only campaigns carry the field, so the tier is empty for a ticket and ticket resolution is unchanged. The campaigns index is read once per project in `columns_of`, on the pass that already builds the cards, and `digest` now watches the campaigns directory: without it a campaign filed elsewhere never reached the picker. `frame_rows` grew a row, so the two bools deciding the geometry became one `Chrome` and the row indices are named. Left out and filed as d637288: nothing can give a codename to a campaign that is already on the board. Co-Authored-By: Claude Opus 5 (1M context) --- AGENTS.md | 29 +- Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 8 +- assets/PLAN.md | 11 +- assets/SKILL.md | 22 +- src/campaign.rs | 25 +- src/command.rs | 32 + src/handlers.rs | 23 +- src/main.rs | 15 +- src/tui.rs | 1547 +++++++++++++++++++++++++++++++++++++++-- src/util.rs | 119 +++- tests/cmd_campaign.rs | 214 ++++++ 13 files changed, 1945 insertions(+), 104 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c0b8459..bf07b84 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,6 +25,7 @@ - The three stamps are `mv`'s, written by `set_status_stamp` from `Status::stamp_field`, and they are mutually exclusive: entering a status writes its field, leaving removes it, re-entering restamps. So a ticket carries at most one, the one for the status it is sitting in, and a backward move under `-f` leaves no stale `Completed On` behind. They are current state, like `Status` itself; the trail of how the ticket got there is d4ce964's job and must not be grown here. `backlog` has no stamp, `Created At` already answers for it - Format: `**Field Name**: value` - Ticket structure: `# Title` → `## Description` → `## Acceptance Criteria` → `## Implementation Plan` → `## Metadata` +- A **campaign** file carries `ID`, `Codename`, `Owner` and `Created At`, in that order, and no `Status`. `Codename` sits directly under the ID because that is what it is, a second way to say which campaign this is; it is written by `campaign add --codename` alone and is `_Not set_` when the flag was not given. It is not in `METADATA_ORDER`, which is the anchor list for the *upsert* on a ticket, and nothing upserts a campaign - Comments stored in `.worklane/comments//.md` with `**Comment**`, `**Author**`, `**Time**` fields ## Status Workflow @@ -41,6 +42,7 @@ and this file is for what someone changing worklane's own code needs. - Tests use `assert_cmd` and `assert_fs` for CLI testing - `setup_worklane()` creates temp `.worklane/` with all four status folders pre-created, plus `campaigns/` in `cmd_campaign.rs`, which is also where the on-demand creation is tested from a board without it - `create_ticket()` writes fully-formed markdown files directly (no `--` separator for positional args in test commands) +- In `tui.rs`, `write_member_card` is `write_tagged_card` plus a Campaign field and `write_campaign` puts a campaign on disk, creating the campaigns directory as it goes — `board_dir()` deliberately does not, so every test that does not write one is also the test that a board with no campaigns draws. `picker_rows` cuts the picker's list out of the frame by its own geometry, for the reason `overlay_title_row` exists: a card carries the same campaign label, so a search over every row finds the board rather than the list - **`cargo clippy --all-targets` is clean. Keep it clean**, and do not silence a lint that is pointing at something real. The only two `allow`s in the tree sit on the `create_ticket` fixtures in `cmd_mv.rs` and `cmd_show.rs`, each carrying the reason and what would replace it - **`cargo fmt --check` is clean too, and `rustfmt.toml` is what makes that affordable.** rustfmt is the formatter here, run it. The config is four stable width settings and nothing else: @@ -74,6 +76,7 @@ and this file is for what someone changing worklane's own code needs. - **The shape is checked before chrono is asked.** `%Y-%m-%d` accepts an unpadded `2026-8-9`, which would be stored exactly as typed and sort before `2026-10-01` in any string comparison. Checking the length and the two dashes first is what lets a valid date be stored unchanged instead of normalised on the way in, which is the difference between validating and rewriting - **Strict on the way in, tolerant on the way out.** `util::due_date` still cuts `2026-12-31T09:30:00Z` down to its date. A file written before the parser existed, or by hand, can hold one and still has to render; refusing to display what is already stored would punish the reader for the writer's mistake - An empty `--due` keeps the clearing message rather than the date message. Somebody typing it is reaching for a way to clear the field, and the useful answer is the flag that does it +- **`campaign add --codename` is validated at parse time by `codename`**, which is `non_empty` plus one word. The board draws it as a label with a mark and no quoting, so `~beaver release` on that row reads as two labels and the second one is not a campaign; a title is where a sentence goes. Nothing else is checked: there is no registry of codenames, the same reason `ls --tag` refuses to validate a tag, and a length limit would be a number invented in the parser when the row that draws it already drops a label it cannot hold - **There are two empty-value parsers, and which one an argument takes is the point.** `non_empty` says only that the value cannot be empty, for the arguments with no empty form: the `ls` filters, `relate`'s targets, and `set --title`, which addresses the ticket and names its file. `clearable` names `--clear`, for the arguments whose field does have one: `set --tags`, `--due` through `iso_date`, and the `chown` user. One message for both would either lie about `ls --tag` or leave the useful half unsaid. `add --due` takes the second one because `iso_date` is shared, and the answer it points at is a command later rather than the omission that would do it now, which is close enough to be worth the shared parser - **A status is a `util::Status`, not a string.** `mv --status` and the `ls` positional take the value enum, so an unknown status is a usage error at parse time naming the four, exit 2, and no handler checks. That is the same bargain `--due` and `--priority` take, and it is what lets the shells complete the four for free. `Status::ALL` is the flow order, which `status_dirs()` and `cmd_mv` both read rather than spelling the names again, and `DONE` is defined from it - The ticket positionals (`show `, `mv `, `comment `) are also left alone, so a search term starting with a hyphen is a usage error. Reachable now that a hyphen-leading title can be stored: use the UUID, or put the flags first and separate with `--`, as in `mv --status committed -- -leading-title` @@ -167,12 +170,14 @@ and this file is for what someone changing worklane's own code needs. - **The full uuid is stored and the title is resolved for display**, as the Relations section already does. `reference_cell` is shared between the two, so a dangling campaign and a dangling relation target are both spelled `_missing_` rather than each inventing a spelling - **`add` does not write the field.** Every ticket written before campaigns existed has none, so the insertion path has to exist regardless; leaving it out of `add` means one path that is always exercised rather than two. Same reasoning as the Relations section - `set_or_insert_metadata_field()` is the upsert, and `METADATA_ORDER` is its anchor list, the way `SECTION_ORDER` is `ensure_section`'s. Campaign is placed before Status, so Status stays last where every file already keeps it. A file with no `## Metadata` heading is an **error, not an insertion**: per 641e3d5 such a file has no fields at all, and writing one above the prose would invent a shape nothing reads -- **The three tiers are `resolve_in()`, shared by tickets and campaigns.** A campaign is addressed exactly the way a ticket is, and a second resolver would be a second copy of the precedence rules to keep in step. `Found.dir` is the status for a ticket and empty for a campaign, which is what makes the ambiguity listing drop the bracket for one +- **The four tiers are `resolve_in()`, shared by tickets and campaigns.** A campaign is addressed exactly the way a ticket is, and a second resolver would be a second copy of the precedence rules to keep in step. `Found.dir` is the status for a ticket and empty for a campaign, which is what makes the ambiguity listing drop the bracket for one +- **An exact `Codename` is the top tier, and it lives in the shared resolver rather than in a campaign-only path.** Only campaigns carry the field, so `parse_codename` returns `None` for every ticket and the tier is always empty for one: ticket resolution is unchanged, which `a_ticket_search_is_unaffected_by_the_codename_tier` pins. It goes above the uuid prefix because it is an exact match on a field written for the purpose, where a substring can be a coincidence, and because a codename like `v1` is below `MIN_ID_SEARCH` and would never be tried as an id at all. A codename that a title also contains, `v2` against `v2 release`, has to win outright rather than be reported ambiguous against it - **`resolve_ticket` explains a search that names a campaign**, rather than each command doing it. One place, so `mv`, `show`, `chown` and everything else that takes a ticket give the same reason instead of a bare "no ticket found". Checked only on the zero-match path, so it costs nothing normally, and only when exactly one campaign matches: an ambiguous ticket error must not be replaced by a complaint about a directory the caller never mentioned - **`Resolved` carries what `content_trim` cannot render from the file.** The relations block and the campaign cell both come from elsewhere on the board. A struct rather than two more parameters, so the next such field is one entry here instead of an edit at every call site - `campaign show` lists **done** members, unlike `ls`, which leaves the done column out of its listing. What is finished against what is left is the whole question a campaign asks, so hiding half the answer is not an option. `ls --campaign` is the other way round: it is the ordinary board filtered, and keeps every rule `ls` already has - `campaign ls` scans the status directories **once per campaign** to count members. That is a scan per row rather than one walk reused, and it is deliberate: the map-from-uuid version is worth writing when a board has enough campaigns to notice -- **The TUI gets neither a campaign tab nor a card marker**, for now. The detail view resolves the field because it renders the body, and that is all. A marker on a card would want a campaigns read per reload, which is more than the blocked mark cost: that one reads the ticket's own Relations section on the pass that already builds the card, and a campaign title is in another directory +- **The TUI got a card label and a frame, not a campaign tab.** 61879a4 decided it. A tab would have had to answer what its columns are, and a campaign groups *across* the flow rather than within one status, so the honest answer is the four statuses filtered — which is a filter on the board it already has rather than a fifth tab. So: a label on the card, a frame above the columns while one is selected, and `c` for the picker. The cost the earlier decision balked at, a campaigns read per reload, is paid once per project in `columns_of` and is what names the label; see The Board View +- **A campaign is named by its codename on the board, and by its short id when it has none.** The uuid does not fit on a card and the title is a sentence, which is the gap `Codename` fills. `campaign_label` builds it in one place, as a `Cell`, so the CLI paints it and the board makes a span of it; the mark is `CAMPAIGN_MARK`, `~`, beside `#` for a tag - `campaign_body()` builds the file from `DESCRIPTION` and `METADATA_HEADING` rather than its own string literals, so the two file formats cannot drift apart on the spelling of a heading. A campaign has no acceptance criteria (its definition of done is derived), no implementation plan and no Status - The campaigns directory is created by `init` and **on demand** by `campaign add`, since every board made before campaigns existed has none and a `worklane init` over a live board to get one would be a strange thing to have to do @@ -212,6 +217,21 @@ and this file is for what someone changing worklane's own code needs. - **A card's height therefore depends on the column's width**, so `card_lines` and `card_height` both take it. `column_areas` is shared between the draw and `follow_selection` for the same reason: `Ratio` hands the remainder column to whichever slot it likes, and reproducing that arithmetic by hand is how the measurement and the draw come to disagree about where a card starts - **A corner that will not fit is dropped whole**, never truncated or wrapped: half a date reads as a different date, and a card that reflows in a narrow column changes height, which the scroll would then have to chase. The left corner is the ticket's identity and always stays - The criteria count is a field on `TicketItem`, filled in `collect_ticket_items` where the file is already being read, and counted through `criteria()` so a checkbox in a description is not counted here or numbered by `show`. Do not count per card: that re-reads every ticket body on every draw instead of on the tick that changed something. `None` rather than `[0/0]` for a ticket with no criteria +- **A card names its campaign on the label row, before the tags, in bold.** `labels_line` draws both, `CAMPAIGN_MARK` (`~`) for the campaign and `#` for a tag, and the campaign takes the row's width first: two cards in one campaign is what a reader looking for a campaign is looking for, and the tags are the context around it. So a row too narrow for both drops the tags whole and keeps the campaign, the order `corner_line` and `project_label` already follow, and a campaign the row will not hold at all goes whole too. A ticket in neither spends no row, so **a ticket in no campaign renders exactly as it did before campaigns reached the card** +- **`Card::campaign` is a resolved `Cell`, not a uuid**, settled at reload the way `project` and `blocked` are. `TicketItem::campaign` already carries the uuid off the pass that builds the card; the name is in another directory, so `columns_of` reads `CampaignIndex` once per project and hands it to every card. Never per draw, the rule `criteria` and `tags` already hold. The merge carries the resolved cell rather than looking it up again, for the reason it carries `blocked`: a campaign is addressed inside one `.worklane`, so a merged lookup could answer one project's uuid with another project's campaign +- **A campaign the board does not hold labels nothing**, the answer `mark_blocked` gives a dangling blocker. `campaign_cell` renders that case as `_missing_` because a metadata table is a place to report a dangling reference; a card is not +- **`c` opens the campaign picker, and taking a campaign filters the tab's columns to its members.** Not a fifth tab: a campaign groups across the flow, so the shape of the answer is the four statuses with fewer cards in them, which is what `campaign show` already answers the question in. Every column is kept, empty ones included. The filter is applied in `reload`, where the columns are built, so nothing downstream has to ask whether a campaign is selected — the board simply holds fewer cards, and `first_match`, `done_count` and the copy key all keep working unchanged +- **`Tab::campaign` is a uuid on the tab, not on the `Board`.** A campaign belongs to one `.worklane`, so a filter carried onto another project's tab would empty it and say nothing about why. It is looked up by uuid rather than held as an index, and a selection whose campaign has left the board is cleared by `reload` rather than left filtering the board to nothing +- **The frame above the columns is three rows, and `Chrome` is what every measurement takes.** `frame_rows` grew a row, so the two bools that decide the geometry became one `Chrome`, copied from `Board::chrome`: adjacent same-typed parameters are what the Rust Style rule warns about, and the draw and `follow_selection` have to measure one answer or a keypress scrolls against a board the next frame does not draw. The row indices are named (`TAB_ROW`, `CAMPAIGN_ROW`, `BOARD_ROW`, `FOOTER_ROW`), since an index written out by hand goes on meaning what it used to +- **The frame says the rest of what it has to say on its borders**, the trade the detail overlay makes with its title and its page indicator: `(id) ~codename · Name` on the top one, the standing on the bottom right, and `q board` on the bottom left. One text row, the opening line of the description. Every row spent here is a row of cards +- **The standing comes from the columns, not from a walk of the tree.** While a campaign is selected the columns *are* its members, done included, so `Tab::standing` counts what is already in hand rather than paying what `campaign ls` pays per campaign. Counted over every column, drawn or not: hiding done is a change to what is drawn and never to what is counted +- **The way out is on the frame's own border, not in the footer.** `q board` sits on the thing it takes away, and the footer row was already at its width naming eight keys. Dropped whole when it and the standing would meet, the rule the page indicator follows +- **`c` is named in the footer only on a closed board with nothing selected**, which is where a reader has to find it. Over an open ticket and on a filtered board it is left out: the frame's border then says how to put the campaign away, and the row has no cells to spare. Incomplete rather than wrong, which is the trade this row is allowed to make — what it must never do is name a key by what it used to do +- **`picker: Option` is the whole mode**, the shape `search` and `detail` use, and `Board::picker_key` runs beside `search_key` ahead of the action arms for the same reason: an open list owns the keyboard, so `d` must not toggle done and `q` must not quit while a campaign is being chosen. `ctrl-c` is the one key it declines and every other control combination is swallowed, or `ctrl-d` would reach the arm bound to `d` +- **The picker's rows are `Tab::campaigns`, not a copy taken when it opened**, so a campaign filed elsewhere appears in an open picker on the next tick. It opens on the campaign already selected, so `c` on a filtered board says where you are as well as offering somewhere to go, and a board with no campaigns gets a `Notice` rather than an empty box that has to be dismissed to learn it was empty +- **A picker row draws a real codename only.** The row opens with the short id, so the card's `~` fallback would print it twice and say nothing the second time +- **`q` takes off one layer at a time, in the order they were put on**: the overlay, then the campaign filter, then the board. `Board::dismiss` holds all three, and it takes the screen now because clearing the filter reloads and has to follow the selection. Selecting a campaign closes an open ticket, the answer hiding the done column already gives: the ticket may not be on the filtered board at all, and swapping it for a different one without saying so is how a person acts on the wrong ticket +- **`digest` watches the campaigns directory** as well as the statuses and the comments. A campaign filed elsewhere has to reach the picker and a codename edited by hand has to reach every card that names it, and a directory's own mtime would miss the edit - **The tags go under the title, dimmed, each prefixed with `#`.** The field was invisible on the board: nothing said a ticket was tagged `bug` without opening it. The marker is what stops the row reading as a third line of the title, since a tag is an ordinary word and the title sits directly above it. The row is dropped whole when the column will not hold it, the rule a corner follows, and an untagged ticket spends no row at all, the way a short title spends no second one - `tags` is a field on `TicketItem`, filled in `collect_ticket_items` through `parse_tags`, for the reason the criteria count is. `parse_tags` splits the comma-separated field into whole trimmed values, so a caller asking for `bug` is not answered by `bugfix`, and reads absent, `_None_` and empty as the same answer - **A held-up card carries `BLOCKED_MARK`, `×`, after its id, in brightred.** The constant lives in `util.rs` and the relations block draws the same one, since both say the same word. A ticket waiting on an open blocker looked exactly like one that is ready, and the board is where the next thing to pick up is chosen. Not a fourth circle from Geometric Shapes: those belong to the priority meter two cells away and would read as part of that ramp. The multiplication sign is Latin-1, like the middle dot the unset priority draws, so it renders wherever the meter does @@ -331,6 +351,8 @@ and this file is for what someone changing worklane's own code needs. - Relation kind mark → brightred `×` blocked by and blocks, cyan `→` relates to, orange `←` regression of and regressed by. A small ramp inside one column, the way the priority meter is: the mark says which kind of edge the row is, so none of these three is a colour standing in for the uuid or the title beside it. Brightred on the cross rather than red, because the id one cell to its right is red and the two would blend. It is the colour and the glyph a held-up card already carries, which is the point: one vocabulary for blocking - Relation status mark → grey `○` backlog, orange `◐` committed, cyan `◐` reviewing, green `●` done, grey `?` for a target the board does not hold. The second ramp in that column: the shape says how far the target has got and the colour tells the two middle stages apart, since both are half circles. **Green is here and deliberately absent from the priority ramp**, where it would sit on a whole line and read as a title; on a one-cell mark with no title behind it, it is the obvious colour for finished and nothing else wants it. Orange keeps the meaning it already has, Status, and grey keeps unset for the one row with no status to show - Chrome → grey. The footer's key names, a rendered `[ ]`, and the overlay's page indicator. Not a new slot: grey already means "what a reader skips", which is the other half of the unset-value meaning, and none of these is a value. The indicator in orange would read as the title it faces across the overlay, in cyan as a timestamp, and in the priority ramp's colours as a level +- Campaign label → its codename through `tag_color`, bold, marked `~`. The colour is what groups a campaign across the cards that carry it, which is exactly what a tag's colour is for, and one word is one colour in every view because `tag_color` is a pure function of it. The mark and the bold are what tell it from a tag on a row that holds both: the mark is not `#`, or the row would read as a list of tags with a stranger in it, and not `@`, which reads as a person on every board anyone has used. `Codename` in a metadata table takes the colour without the mark, since the field name has already said what it is +- Campaign label with no codename → grey. The label is then the short id, and grey keeps a reserved meaning off a `TAG_COLORS` slot in the one case where it would land on one: red is the uuid's everywhere else, and grey already means what a reader skips, which is what a campaign with no codename has to say for itself - **The palette splits in two: seven colours that each mean one thing, and `TAG_COLORS`, the eight a tag may be drawn in.** A tag in red would read as a uuid, in green as a title, in grey as an unset value, so the tag slots are reserved as a list rather than picked at the call site. Do not assign a new meaning to a colour in `TAG_COLORS`, and do not draw a tag in one outside it - `tag_color()` is a pure function of the tag string, so the same tag is the same colour on every card, in every view and on every board, with nothing stored. Case sensitive, because `Bug` and `bug` are two different tags to the field and to every search - **The hash is FNV-1a written out here, not `DefaultHasher`.** std does not promise its output is stable across releases, and a board that repaints itself on a toolchain upgrade has lost the only property the mapping is for. `the_tag_mapping_is_pinned` fails on any change to it, so a repaint is a decision rather than a surprise @@ -350,7 +372,8 @@ and this file is for what someone changing worklane's own code needs. ### Ticket Resolution - `resolve_ticket()` returns `(status, title, content)` tuple -- Three tiers, evaluated in order: UUID prefix > title substring > filename substring. The first non-empty tier wins outright and later tiers are not consulted. This is not cosmetic: ticket titles reference other tickets by id, so a flat OR of the three reported an exact prefix match as ambiguous against whichever title mentioned it +- Four tiers, evaluated in order: exact codename > UUID prefix > title substring > filename substring. The first non-empty tier wins outright and later tiers are not consulted. This is not cosmetic: ticket titles reference other tickets by id, so a flat OR of the tiers reported an exact prefix match as ambiguous against whichever title mentioned it +- The codename tier is a campaign's, and empty for a ticket, which has no such field. Case insensitive like the other three, so a codename typed back off a listing resolves whatever case it was read in. See Campaigns for why it sits above the uuid prefix - The UUID tier applies from `MIN_ID_SEARCH` (4) characters up. Not 8: `ls` prints `SHORT_ID_WIDTH` (7) characters, so a longer minimum would drop the printed id out of the UUID tier and let any title quoting it win instead. Below the minimum the search is text, so `show 641` is a title search - The filename tier earns its place by reaching the middle of a UUID, which the prefix tier cannot. It is also why a short UUID search still resolves under a longer minimum, just at the wrong precedence, so a test for the minimum needs a decoy title to be meaningful - Ambiguous matches (multiple results) print options and exit(1) diff --git a/Cargo.lock b/Cargo.lock index d9f86c5..0ae393c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1503,7 +1503,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.19.0" +version = "0.20.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index d6ef38b..878933b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.19.0" +version = "0.20.0" edition = "2024" [dependencies] diff --git a/README.md b/README.md index bed1582..b2606f7 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,11 @@ Worklane is a local Kanban flow for agentic software development. ## Commands | Command | Description | |---------|-------------| -| `worklane` or `worklane tui [path...]` | Opens the board: four status columns, redrawn when the tree changes. Read only. Opens on backlog, committed and reviewing; `d` shows or hides done, whose count stays in the footer either way. Arrows or `hjkl` to move, `enter` for detail, `pgup`/`pgdn` to scroll an open ticket, whose border carries a page indicator while there is more of it than fits, `/` to jump to the first ticket whose id or title matches, `y` to copy the selected ticket's short id to the clipboard, `q` to quit. Each path opens the first `.worklane` at or above it, the working directory by default. Several paths are monitored together, as a tab per project plus an `all` tab that merges them, with `tab` and `shift+tab` between them | +| `worklane` or `worklane tui [path...]` | Opens the board: four status columns, redrawn when the tree changes. Read only. Opens on backlog, committed and reviewing; `d` shows or hides done, whose count stays in the footer either way. Arrows or `hjkl` to move, `enter` for detail, `pgup`/`pgdn` to scroll an open ticket, whose border carries a page indicator while there is more of it than fits, `/` to jump to the first ticket whose id or title matches, `y` to copy the selected ticket's short id to the clipboard, `c` to pick a campaign and filter the columns to its members, `q` to close whatever is open and then to quit. A card carries its campaign beside its tags, marked `~` and bold; while one is selected a frame above the columns names it and says how far it has got, and `q` on its border gives the whole board back. Each path opens the first `.worklane` at or above it, the working directory by default. Several paths are monitored together, as a tab per project plus an `all` tab that merges them, with `tab` and `shift+tab` between them | | `worklane init` | Creates `.worklane/` with backlog, committed, reviewing, done directories | | `worklane add` | Creates a ticket in backlog with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--owner`, `--priority` flags. `--due` takes `YYYY-MM-DD` and refuses anything else at parse time | | `worklane ls [status]` | Lists tickets, sorted by priority then title. Optional positional status, and `--priority <1-5>`, `--tag ` and `--campaign `, which compose in any combination. `--tag` matches a whole value of the comma-separated Tags field, case sensitively, so `--tag bug` does not list a ticket tagged `bugfix` or one tagged `Bug`. `--ids` prints one ticket per line as its short id, a tab and its title, unstyled, done included, for a script or a completion | -| `worklane show ` | Shows ticket by UUID prefix (4+ chars), title substring, or filename substring | +| `worklane show ` | Shows ticket by UUID prefix (4+ chars), title substring, or filename substring. A campaign is addressed the same way, plus its exact codename, which wins over all three | | `worklane mv --status [-f]` | Moves ticket between statuses. Default: forward only, one stage at a time. `-f` bypasses both restrictions | | `worklane set ` | Replaces fields with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--priority`. At least one required. Changing the title renames the file, keeping the UUID. `--clear ` returns a field to unset instead, repeatable, taking `due`, `tags`, `priority`, `description`, `acceptance` or `plan`, and writing back exactly what `add` writes for a field it was never given. No `title`, which addresses the ticket, and no `owner`, which is `chown`'s. Replacing and clearing the same field in one call is refused | | `worklane append ` | Adds to a section with `--description`, `--acceptance`, `--plan`. At least one required. The description gains a paragraph; list items go on the end, steps numbered on from the last | @@ -18,6 +18,10 @@ Worklane is a local Kanban flow for agentic software development. | `worklane check [criteria...]` | Ticks acceptance criteria, each by number as shown by `show` or by a substring. Several in one call, or `all` for every one of them. Prompts with the numbered list if none is given, or errors with it when there is no terminal | | `worklane uncheck [criteria...]` | Unticks acceptance criteria, addressed the same way | | `worklane comment ` | Adds a comment to a ticket by UUID or title | +| `worklane campaign add` | Files a campaign in `.worklane/campaigns/` with `--title`, `--description`, `--codename` and `--owner`. A campaign has no status: its state is derived, open until every member is done. `--codename` is one word to call it by, `v1` or `beaver`, which is what the board draws on every card in it and what every command that takes a campaign will also resolve it by | +| `worklane campaign ls` | Lists the campaigns as their short id, their codename, their title and how many members are done. `--ids` prints one per line as the id, a tab and the title, unstyled, for a script or a completion | +| `worklane campaign show ` | Shows a campaign and its members grouped by status, done included, since what is finished against what is left is the question a campaign asks | +| `worklane assign ` | Puts a ticket in a campaign, the only command that writes the Campaign field. Campaign first and ticket second, after `chown`. A ticket is in at most one, so assigning one that already belongs somewhere moves it | | `worklane tags` | Lists the tags the board carries as the tag, a tab and how many tickets carry it, one per line, unstyled and alphabetical. Case sensitive like `ls --tag`, so `bug` and `Bug` list separately and land next to each other. Every status, done included. The one command that answers what tags exist rather than what carries a tag already known | | `worklane completions ` | Prints a completion script for `fish`, `bash`, `zsh`, `elvish` or `powershell`. See below | | `worklane install-skill [skill]` | Writes the embedded agent skills to `~/.claude/skills//SKILL.md`, which Claude Code and opencode both read. Three ship: `worklane` teaches the CLI, `worklane-review` reviews a finished ticket against the code that claims to close it, `worklane-plan` grooms the board as a whole, its priorities, due dates, tags and campaigns. Every document unless one is named. Leaves a modified copy alone unless `--force`; `--print` writes one to stdout instead and needs the name | diff --git a/assets/PLAN.md b/assets/PLAN.md index bad8529..f76239f 100644 --- a/assets/PLAN.md +++ b/assets/PLAN.md @@ -158,9 +158,9 @@ fields; a goal is a campaign. ``` worklane campaign ls -worklane campaign show "v1 release" -worklane campaign add --title "..." --description "..." -worklane assign "v1 release" 1b78a24 +worklane campaign show v1 +worklane campaign add --title "..." --codename v1 --description "..." +worklane assign v1 1b78a24 ``` A campaign is the tickets that have to be finished **together** for one outcome. The test @@ -177,6 +177,11 @@ tui is usable on a narrow terminal" is a campaign. "The tui tickets" is a tag. - **A campaign's state is derived**, open until every member is done. There is nothing to close and nothing to move. A campaign whose members are all done is finished already. - `assign` takes the **campaign first and the ticket second**, like `chown`. +- **Propose a codename with the campaign**, one word, `v1` or `beaver`. It is what the + board draws on every card in it and the shortest thing that addresses it at the command + line, and a campaign filed without one is drawn by its short id, which says nothing. A + campaign already on the board that has no codename is worth pointing out for the same + reason a near-duplicate tag is. Proposing a campaign means naming the goal, the members, and what is deliberately left out of it. The last part is what makes it a goal rather than a pile. diff --git a/assets/SKILL.md b/assets/SKILL.md index 0280d43..59d3e33 100644 --- a/assets/SKILL.md +++ b/assets/SKILL.md @@ -206,15 +206,21 @@ status directory. Its state is derived instead, open until every member is done, there is no such thing as a done campaign holding an open ticket. ``` -worklane campaign add --title "v1 release" \ +worklane campaign add --title "First public release" --codename v1 \ --description "Everything that has to ship before the tag." -worklane campaign ls # every campaign and how far it has got +worklane campaign ls # every campaign, its codename, how far it has got worklane campaign ls --ids # id and title, tab separated, like ls --ids -worklane campaign show "v1 release" # its body, then its members by status -worklane assign "v1 release" 1b78a24 # put a ticket in it -worklane ls --campaign "v1 release" # only that campaign's tickets +worklane campaign show v1 # its body, then its members by status +worklane assign v1 1b78a24 # put a ticket in it +worklane ls --campaign v1 # only that campaign's tickets ``` +**Give a campaign a `--codename`.** One word, `v1` or `beaver`. It is what the board +draws on every card in the campaign, because a uuid does not fit there and a title is a +sentence, and it is the shortest thing that addresses the campaign at the command line. +Optional: a campaign without one is drawn and listed by its short id instead, which +resolves but says nothing. + `assign` takes the **campaign first and the ticket second**, like `chown`, and is the only writer of the field. `add` has no `--campaign` and neither has `set`, so membership has one writer the way owner and status do. @@ -227,8 +233,10 @@ reports no change and writes nothing. its listing: a campaign is precisely the question of what is finished against what is left. -A campaign is addressed the way a ticket is, by uuid prefix, title or filename, but it -is not a ticket. Passing one where a ticket is expected is refused with a message saying +A campaign is addressed the way a ticket is, by uuid prefix, title or filename, and by +its exact codename, which wins over all three. So `assign v1 1b78a24` reaches the +campaign codenamed `v1` even if another campaign's title contains `v1`. It is not a +ticket, though. Passing one where a ticket is expected is refused with a message saying so, and there is no way to move a campaign, because it has no status to move. ## Search the backlog before filing diff --git a/src/campaign.rs b/src/campaign.rs index 8bfe600..a6afd0c 100644 --- a/src/campaign.rs +++ b/src/campaign.rs @@ -41,6 +41,12 @@ pub fn ensure_campaigns_dir(worklane_dir: &Path) -> Result { pub struct Campaign { pub uuid: String, pub title: String, + /// The word the campaign is called by, or `None` for one filed without a codename. + /// + /// Read here rather than parsed at each call site for the reason the title is: the + /// board draws it on every card that names this campaign, and the picker draws it on + /// every row, so it comes off the one read of the directory. + pub codename: Option, pub content: String, } @@ -80,6 +86,7 @@ pub fn resolve_campaign(search: &str, worklane_dir: &Path) -> Result { } Ok(Campaign { + codename: parse_codename(&found.content), uuid, title: found.title, content: found.content, @@ -103,6 +110,11 @@ pub fn campaign_named(search: &str, worklane_dir: &Path) -> Option { /// One pass for the same reason [`RelationIndex`] takes one: rendering a ticket's /// Campaign field or listing the campaigns both need every one of them, and a lookup /// per ticket would read the directory once per row. +/// +/// `Default` is the empty index, which is what a board whose campaigns directory cannot be +/// read has: it still draws, with no campaign on any card. A *missing* directory is already +/// not an error, per [`CampaignIndex::load`]; this is for the unreadable one. +#[derive(Default)] pub struct CampaignIndex { campaigns: Vec, } @@ -130,6 +142,7 @@ impl CampaignIndex { campaigns.push(Campaign { uuid: parse_ticket_field(&content, "ID"), title: heading_title(&content), + codename: parse_codename(&content), content, }); } @@ -250,6 +263,9 @@ impl Standing { /// The campaign file as it is written. /// +/// The codename sits directly under the ID, because that is what it is: a second way to +/// say which campaign this is, in a word rather than in thirty-six characters. +/// /// The same shape a ticket has, minus what a campaign has no use for: no acceptance /// criteria, because its definition of done is derived from its members rather than /// written down, no implementation plan, and no Status, because it sits in no status @@ -258,6 +274,7 @@ impl Standing { pub fn campaign_body( title: &str, description: &[String], + codename: Option<&str>, id: &uuid::Uuid, owner: Option<&str>, created_at: &str, @@ -279,11 +296,17 @@ pub fn campaign_body( {metadata_heading}\n\ \n\ - **ID**: {id}\n\ + - **{codename_field}**: {codename}\n\ - **Owner**: {owner}\n\ - **Created At**: {created_at}\n\ ", description_heading = DESCRIPTION.heading, metadata_heading = METADATA_HEADING, - owner = owner.unwrap_or("_Not set_"), + codename_field = CODENAME_FIELD, + // Written unset rather than left out, the way `add` writes an unset Due on every + // ticket: the line is then there to read and there to edit by hand, and one shape + // of file is one thing for the parser to be right about. + codename = codename.unwrap_or(NOT_SET), + owner = owner.unwrap_or(NOT_SET), ) } diff --git a/src/command.rs b/src/command.rs index 5013978..53d3648 100644 --- a/src/command.rs +++ b/src/command.rs @@ -109,6 +109,27 @@ fn iso_date(raw: &str) -> Result { Ok(raw.to_string()) } +/// Reject a codename that is not one word. +/// +/// At parse time, like `iso_date` and `priority_level`, so a mistyped value is a usage +/// error with nothing written. One word because the board draws it as a label beside the +/// tags, with a mark and no quoting: `~beaver release` on that row reads as two labels, and +/// the second one is not a campaign. A title is where a sentence goes. +/// +/// Nothing else is checked. There is no registry of codenames to check against, the same +/// reason `ls --tag` refuses to validate a tag, and a length limit would be a number +/// invented here: a label the column will not hold is dropped whole by the row that draws +/// it. +fn codename(raw: &str) -> Result { + let value = non_empty(raw)?; + + if value.split_whitespace().count() > 1 { + return Err("codename must be a single word, for example v1 or beaver".to_string()); + } + + Ok(value) +} + /// Arguments that carry prose, and therefore have to accept a value starting with /// a hyphen. /// @@ -299,6 +320,9 @@ pub enum CampaignCommand { /// and no implementation plan. Priority, tags and a due date are left out because /// nothing reads them yet, and a field written but never shown is a field that goes /// stale unnoticed. +/// +/// `--codename` is the exception to that last rule and earns it: the board draws it on +/// every card in the campaign, and it exists because the uuid does not fit there. #[derive(clap::Args)] pub struct CampaignAddArgs { /// Campaign title @@ -309,6 +333,14 @@ pub struct CampaignAddArgs { #[arg(short, long, allow_hyphen_values = PROSE)] pub description: Vec, + /// A single word to call the campaign by, for example v1 or beaver + /// + /// The uuid is what every command stores and the title is a sentence, so neither is + /// what a card has room to print. This is the short form the board draws, and it is + /// optional: a campaign without one is drawn by its short id instead. + #[arg(short, long, value_parser = codename)] + pub codename: Option, + /// Owner. Defaults to the git user #[arg(short, long)] pub owner: Option, diff --git a/src/handlers.rs b/src/handlers.rs index b67057a..a59f89b 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -1037,7 +1037,12 @@ pub fn cmd_relate(args: &RelateArgs, start: &Path) -> Result<()> { /// half-written campaign behind. `cmd_add` predates that primitive and still uses the /// plain write; the difference is noted on the ticket rather than fixed here. pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path) -> Result<()> { - let CampaignAddArgs { title, description, owner } = args; + let CampaignAddArgs { + title, + description, + codename, + owner, + } = args; let worklane_dir = find_worklane_dir(start)?; let dir = ensure_campaigns_dir(&worklane_dir)?; @@ -1054,6 +1059,7 @@ pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path) -> Result<()> { let body = campaign_body( title, description, + codename.as_deref(), &id, owner.as_deref(), &Local::now().format(TIMESTAMP_FORMAT).to_string(), @@ -1099,9 +1105,22 @@ pub fn cmd_campaign_ls(worklane_dir: &Path, ids: bool) -> Result<()> { None => String::new(), }; + // The codename between the id and the title, in the colour the board draws it in + // and with the same mark: the answer to "which campaign is this" is one word, and + // it should be the same word wherever it is read. A campaign filed without one + // spends nothing on it, the way an untagged card spends no row. + let codename = match campaign.codename.is_some() { + true => { + let label = campaign_label(&campaign.uuid, campaign.codename.as_deref()); + format!("{} ", paint_cells(&[label], colored)) + } + false => String::new(), + }; + println!( - " ({}) {} | {}{}", + " ({}) {}{} | {}{}", paint(short_id(&campaign.uuid), Color::Red, colored), + codename, campaign.title, standing.label(), state, diff --git a/src/main.rs b/src/main.rs index 34117d5..9416356 100644 --- a/src/main.rs +++ b/src/main.rs @@ -177,13 +177,22 @@ fn run_tui(paths: &[std::path::PathBuf], start: &std::path::Path) -> Result<()> continue; } + // The same contract for the campaign picker, which is the other mode that owns + // the keyboard while it is open. Two calls rather than one combined pre-branch, + // because only one of the two can be open at a time and each reports for + // itself; the rules are `Board::search_key` and `Board::picker_key`, where a + // test can reach them. + if board.picker_key(key, screen) { + continue; + } + match key.code { // One arm, because the two keys mean one thing: close what is open, and // quit when there is nothing left to close. Two arms carrying one rule // is how a later edit changes it for one key and not the other, which is // what `q` quitting out from under an open ticket already was. The rule // itself is `Board::dismiss`, where a test can reach it. - KeyCode::Esc | KeyCode::Char('q') => board.dismiss(), + KeyCode::Esc | KeyCode::Char('q') => board.dismiss(screen), // The only key that leaves the board from an open ticket, which is why // the footer names it there. KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => { @@ -215,6 +224,10 @@ fn run_tui(paths: &[std::path::PathBuf], start: &std::path::Path) -> Result<()> // left that a vim hand would reach for. The clipboard is handed in rather // than reached for inside `Board`, so the suite can drive both answers. KeyCode::Char('y') => board.copy_selected_id(clipboard::copy), + // The way in to the campaign picker, like `/` is to the search prompt: from + // the next keypress on `picker_key` above has the keyboard. Free of every + // other binding, and `ctrl-c` is matched above this so quitting still wins. + KeyCode::Char('c') => board.open_picker(), _ => {} } } diff --git a/src/tui.rs b/src/tui.rs index 6c1dd4a..5ee0be6 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -20,6 +20,7 @@ use ratatui::style::{Modifier, Style}; use ratatui::text::{Line, Span, Text}; use ratatui::widgets::{Block, Borders, Clear, Paragraph, Tabs, Wrap}; +use crate::campaign::{CAMPAIGNS_DIR, CampaignIndex, Standing}; use crate::handlers::read_comments; use crate::util::*; @@ -32,6 +33,38 @@ pub const POLL: Duration = Duration::from_millis(250); /// a label rather than a sentence. const ALL: &str = "all"; +/// The rows of chrome above the columns, which is what the geometry depends on. +/// +/// A struct rather than two bools threaded through `frame_rows`, `board_area`, +/// `card_width` and `column_text_height`: adjacent same-typed parameters are what the +/// Rust Style rule in AGENTS.md warns about, and a caller that swapped them would measure +/// a board nobody is looking at. Copied from `Board::chrome`, so the draw and the +/// keypress measure one answer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Chrome { + /// Whether the tab row is drawn, which is whether more than one board is monitored. + pub tabbed: bool, + /// Whether the campaign frame is drawn, which is whether a campaign is selected. + pub campaign: bool, +} + +impl Chrome { + /// The rows the campaign frame takes: a border either side of one row of prose. + /// + /// Three rather than four, because the frame says the rest of what it has to say on + /// its borders: the identity on the top one and the standing on the bottom, the trade + /// the detail overlay already makes with its title and its page indicator. Every row + /// spent here is a row of cards. + const CAMPAIGN_ROWS: u16 = 3; + + fn campaign_rows(self) -> u16 { + match self.campaign { + true => Self::CAMPAIGN_ROWS, + false => 0, + } + } +} + /// One monitored board: where it lives, and what to call it. #[derive(Debug)] pub struct Project { @@ -107,6 +140,21 @@ pub struct Card { /// carried into the merge unchanged — `relate` resolves its target against one /// `.worklane`, so there is no such thing as a blocker in another project. pub blocked: bool, + /// The campaign this ticket is in, as the label the card draws, or `None` for a ticket + /// in none. + /// + /// `TicketItem::campaign` already carries the uuid, off the pass that builds the card. + /// What is missing is a name for it, which lives in another directory, so this is + /// resolved at reload from the one read of the campaigns index — never per draw, the + /// rule `criteria` and `tags` already follow. + /// + /// A uuid no campaign carries resolves to `None` and the card says nothing, the answer + /// `mark_blocked` gives a dangling blocker: a uuid nothing holds is a bookkeeping + /// fault rather than a fact about this ticket. Resolved on the board the ticket came + /// from and carried into the merge unchanged, for the reason `blocked` is: a campaign + /// is addressed inside one `.worklane`, so one project's uuid must never be answered + /// by another project's campaign. + pub campaign: Option, } /// One status and the cards in it. @@ -115,6 +163,35 @@ pub struct Column { pub cards: Vec, } +/// A campaign as the board holds it: what the picker lists and what the frame draws. +/// +/// Read at reload from the one pass over the campaigns directory, the same pass that names +/// the campaign on each card. The description is cut to its opening line here rather than +/// at draw time, because the file is only in hand while the directory is being read. +/// +/// No member count. Counting them is a walk of the status directories per campaign, which +/// is what `campaign ls` pays and what a keypress should not; the standing of the *selected* +/// campaign is free, since the columns are then its members. +#[derive(Clone, Debug)] +pub struct CampaignRow { + pub uuid: String, + pub title: String, + pub codename: Option, + /// The opening line of the description, or empty for a campaign with none. + pub summary: String, + /// The project it was filed in, on the All tab only. A campaign is resolved inside one + /// `.worklane`, so across several boards the id alone does not say which board holds + /// it — the same reason a card carries its project there. + pub project: Option, +} + +impl CampaignRow { + /// The campaign as a label, the way a card carrying it is drawn. + pub fn label(&self) -> Cell { + campaign_label(&self.uuid, self.codename.as_deref()) + } +} + /// One tab: a monitored board, or the merge across all of them. /// /// The selection and the column offsets live here rather than on the board, so @@ -128,6 +205,15 @@ pub struct Tab { /// First visible line of each column, counted in card lines. Parallel to /// `columns`, so a tick that reshapes the board resizes it in step. pub offsets: Vec, + /// The campaigns this tab can be filtered to: the ones on its own board, or every + /// board's on the merge. Rebuilt at reload beside the columns. + pub campaigns: Vec, + /// The uuid of the campaign the columns are filtered to, or `None` for the whole board. + /// + /// Per tab rather than on the `Board`, the way the selection is. A campaign belongs to + /// one `.worklane`, so a filter carried across to another project's tab would empty it + /// and say nothing about why. + pub campaign: Option, } impl Tab { @@ -138,6 +224,36 @@ impl Tab { column: 0, card: 0, offsets: Vec::new(), + campaigns: Vec::new(), + campaign: None, + } + } + + /// The selected campaign, or nothing when the tab is showing the whole board. + /// + /// Looked up by uuid rather than held as an index, so a reload that adds or drops a + /// campaign cannot leave the frame pointing at a different one. A selection whose + /// campaign has since left the board resolves to nothing, which `reload` then clears. + fn selected_campaign(&self) -> Option<&CampaignRow> { + let uuid = self.campaign.as_deref()?; + self.campaigns.iter().find(|row| row.uuid == uuid) + } + + /// How far the selected campaign has got, from the columns rather than from a scan. + /// + /// The columns *are* its members while it is selected, done included, so this is the + /// same count `Standing::of` builds for `campaign ls` without the walk per campaign + /// that one pays. Counted over every column, drawn or not: hiding done is a change to + /// what is drawn and never to what is counted, the rule the footer's own count follows. + fn standing(&self) -> Standing { + Standing { + done: self + .columns + .iter() + .filter(|column| column.status == DONE) + .map(|column| column.cards.len()) + .sum(), + total: self.columns.iter().map(|column| column.cards.len()).sum(), } } @@ -274,6 +390,21 @@ impl Notice { } } +/// The open campaign picker: which row the highlight is on, and where the list is +/// scrolled to. +/// +/// `picker: Option` is the whole mode, the shape `search` and `detail` already +/// use: "the picker is open" and "what is highlighted in it" cannot disagree, and closing +/// it leaves nothing to reset. The rows are not held here — they are `Tab::campaigns`, +/// rebuilt on every tick, so a campaign filed elsewhere appears in an open picker rather +/// than in a copy of the list that has gone stale. +#[derive(Debug, Default)] +pub struct Picker { + pub row: usize, + /// First visible row, counted in rows, since a picker row is one line. + pub offset: u16, +} + /// What is on screen. pub struct Board { /// The monitored boards as tabs, the merge first when there is more than one. @@ -286,6 +417,8 @@ pub struct Board { pub offset: u16, /// The search prompt while it is open. `None` is the board reading keys as actions. pub search: Option, + /// The campaign picker while it is open, on the same terms as `search`. + pub picker: Option, /// What the last action said, until the next keypress takes it away. pub notice: Option, /// Whether the done column is drawn. Off at startup, and not remembered between @@ -320,6 +453,7 @@ impl Board { detail: None, offset: 0, search: None, + picker: None, notice: None, show_done: false, should_quit: false, @@ -338,6 +472,18 @@ impl Board { self.tabs.len() > 1 } + /// The chrome above the columns, which is what every measurement of the board takes. + /// + /// One answer, read by the draw and by `follow_selection` alike: the frame appearing + /// takes three rows off the columns, and a keypress that scrolled against the old + /// height would put the selection where the next frame does not draw it. + pub fn chrome(&self) -> Chrome { + Chrome { + tabbed: self.tabbed(), + campaign: self.current().campaign.is_some(), + } + } + pub fn current(&self) -> &Tab { &self.tabs[self.tab] } @@ -361,22 +507,46 @@ impl Board { } fn reload(&mut self) -> Result<()> { - // Each tree is read once. The merge is built from those cards rather than by - // scanning every project a second time. - let per_project: Vec> = self - .projects - .iter() - .map(|project| columns_of(&project.dir)) - .collect(); - - let mut built: Vec> = Vec::new(); - if self.projects.len() > 1 { - built.push(merge(&per_project, &self.projects)); + // Each tree is read once, cards and campaigns together, since the campaign a card + // names is resolved on that read. The merge is built from those cards rather than + // by scanning every project a second time. + // Two lists rather than a list of pairs, because `merge` takes every project's + // columns at once and nothing would be served by cloning them into it. + let merged = self.projects.len() > 1; + let mut per_columns: Vec> = Vec::new(); + let mut per_campaigns: Vec> = Vec::new(); + for project in &self.projects { + let (columns, campaigns) = columns_of(&project.dir); + // The project is named on a row only where it has to be. On a single board + // there is nothing to tell a campaign apart from, the bargain a card's project + // label already takes. + let label = match merged { + true => Some(project.name.as_str()), + false => None, + }; + per_columns.push(columns); + per_campaigns.push(campaign_rows(&campaigns, label)); } - built.extend(per_project); - for (tab, columns) in self.tabs.iter_mut().zip(built) { - tab.columns = columns; + let mut built: Vec<(Vec, Vec)> = Vec::new(); + if merged { + // Every board's campaigns under the merge, each carrying the project it was + // filed in: on that tab an id says which campaign but not which board holds it. + let campaigns = per_campaigns.iter().flatten().cloned().collect(); + built.push((merge(&per_columns, &self.projects), campaigns)); + } + built.extend(per_columns.into_iter().zip(per_campaigns)); + + for (tab, (columns, campaigns)) in self.tabs.iter_mut().zip(built) { + tab.campaigns = campaigns; + // A selection whose campaign has left the board goes back to the whole board + // rather than filtering it to nothing: the frame would have nothing to name and + // every column would be empty, which reads as a board that has lost its + // tickets. + if tab.selected_campaign().is_none() { + tab.campaign = None; + } + tab.columns = retain_campaign(columns, tab.campaign.as_deref()); // One scroll position per column, kept by index. A tick that adds or removes // columns is not a thing statuses do, but the resize keeps the two in step // regardless; `resize` both pads and truncates. @@ -525,8 +695,9 @@ impl Board { // height depends on how much of the title has to wrap and the tab row takes a // row off the columns. Measured before the borrows below. let column = self.current().column; - let width = card_width(screen, self.tabbed(), self.visible_count(), column); - let inner = column_text_height(screen, self.tabbed()); + let chrome = self.chrome(); + let width = card_width(screen, chrome, self.visible_count(), column); + let inner = column_text_height(screen, chrome); let tab = self.current_mut(); let Some(column) = tab.columns.get(tab.column) else { @@ -558,6 +729,134 @@ impl Board { }; } + /// The campaign the tab in view is filtered to, or nothing for the whole board. + pub fn campaign(&self) -> Option<&CampaignRow> { + self.current().selected_campaign() + } + + /// Open the picker on the campaign in view, or say there is nothing to pick from. + /// + /// A board with no campaigns gets a notice rather than an empty box: the box would + /// have to be dismissed to learn that it was empty, and `Notice` is what the board + /// already uses to say something in words. Failed, because the key was pressed and + /// nothing came of it, which is the same answer a copy off an empty column gives. + /// + /// It opens on the campaign already selected, so `c` on a filtered board is a way to + /// look at where you are as much as a way to move, and on the first row otherwise. + pub fn open_picker(&mut self) { + if self.current().campaigns.is_empty() { + self.notice = Some(Notice::failed("no campaigns on this board")); + return; + } + + let row = self + .current() + .campaign + .as_deref() + .and_then(|uuid| self.current().campaigns.iter().position(|row| row.uuid == uuid)) + .unwrap_or(0); + + self.picker = Some(Picker { row, offset: 0 }); + } + + /// Feed a keypress to the open picker, and say whether it was taken. + /// + /// The same contract as `search_key`, and it runs beside it for the same reason: an + /// open list has the keyboard, so `d` must not toggle the done column and `q` must not + /// quit while the reader is choosing a campaign. `ctrl-c` is the one key it declines, + /// and every other control combination is swallowed and does nothing, so `ctrl-d` + /// cannot fall through to the arm bound to `d`. + /// + /// Up and down only, and no `hjkl`: the list is one column, and a letter here would + /// have to be the letter that also selects nothing. `enter` takes the highlighted + /// campaign, `esc` and `q` leave the board as it was. + pub fn picker_key(&mut self, key: KeyEvent, screen: Size) -> bool { + if self.picker.is_none() { + return false; + } + + let control = key.modifiers.contains(KeyModifiers::CONTROL); + if control && key.code == KeyCode::Char('c') { + return false; + } + + match key.code { + KeyCode::Esc | KeyCode::Char('q') if !control => self.picker = None, + KeyCode::Up | KeyCode::Char('k') if !control => self.move_picker(-1, screen), + KeyCode::Down | KeyCode::Char('j') if !control => self.move_picker(1, screen), + KeyCode::Enter | KeyCode::Char(' ') if !control => self.take_picked(screen), + _ => {} + } + + true + } + + /// Move the highlight, clamped like a card rather than cycled like a tab. + /// + /// A list has a top and a bottom, and running off one end of a list of campaigns to + /// the other is how a reader loses their place in it. + fn move_picker(&mut self, delta: isize, screen: Size) { + let count = self.current().campaigns.len(); + let height = picker_text_area(Rect::new(0, 0, screen.width, screen.height)).height; + + let Some(picker) = &mut self.picker else { + return; + }; + if count == 0 { + return; + } + + picker.row = (picker.row as isize + delta).clamp(0, count as isize - 1) as usize; + + let start = picker.row as u16; + picker.offset = aligned_offset(picker.offset, start, start + 1, height, count as u16); + } + + /// Take the highlighted campaign and close the picker. + fn take_picked(&mut self, screen: Size) { + let Some(picker) = &self.picker else { return }; + let Some(row) = self.current().campaigns.get(picker.row) else { + return; + }; + + let uuid = row.uuid.clone(); + self.picker = None; + self.select_campaign(Some(uuid), screen); + } + + /// Filter the tab in view to one campaign, or back to the whole board. + /// + /// The filter is applied where the columns are built, so this reloads rather than + /// filtering what is already on the tab: a filtered column is not something the + /// unfiltered one can be recovered from, and the tree is what the board reads anyway. + /// Cheap for the same reason a tick is. + /// + /// An open detail view closes, the answer hiding the done column already gives: the + /// ticket it is showing may not be on the filtered board at all, and quietly swapping + /// it for a different ticket is worse than closing. + pub fn select_campaign(&mut self, campaign: Option, screen: Size) { + if self.current().campaign == campaign { + return; + } + + self.current_mut().campaign = campaign; + self.detail = None; + self.offset = 0; + // A selection kept from the unfiltered board would point at a card that is no + // longer in that column, so it goes back to the top of the first one. + let tab = self.current_mut(); + tab.column = 0; + tab.card = 0; + tab.offsets.iter_mut().for_each(|offset| *offset = 0); + + // Swallowed for the reason the tick's is not: there is nobody above a keypress to + // handle a failed read, and the board goes on being drawn either way. + if let Err(err) = self.reload() { + self.notice = Some(Notice::failed(format!("reload failed: {err}"))); + } + self.follow_selection(screen); + } + /// Put away what is open, and quit when there is nothing left to put away. /// /// What `esc` has always done, and now what `q` does too. `q` used to set @@ -569,13 +868,29 @@ impl Board { /// from a test, so a rule written into it is a rule nothing can check. The arm is /// left as the one line that names the keys. /// - /// `ctrl-c` is therefore the only key that leaves the board while a ticket is open, - /// and the footer says so rather than leaving the reader to find out. - pub fn dismiss(&mut self) { - match self.detail { - Some(_) => self.toggle_detail(), - None => self.should_quit = true, + /// `ctrl-c` is therefore the only key that leaves the board while a ticket is open or + /// a campaign is selected, and the footer says so rather than leaving the reader to + /// find out. + /// + /// The order is the order things were put on: the overlay, then the campaign filter, + /// then the board. One press takes off one layer, so nothing is skipped and nothing is + /// taken away that the reader cannot see. + pub fn dismiss(&mut self, screen: Size) { + if self.detail.is_some() { + self.toggle_detail(); + return; } + + // A campaign filter is the next thing open, under the overlay and above the board + // itself: it is a view the reader put on and has to be able to take off. Quitting + // out from under it instead is exactly what `q` used to do to an open ticket, and + // the footer says which of the two this key is about to do. + if self.current().campaign.is_some() { + self.select_campaign(None, screen); + return; + } + + self.should_quit = true; } /// Open the prompt on an empty query. @@ -832,8 +1147,16 @@ fn span_of(cell: Cell) -> Span<'static> { } } -/// The four columns of one board. -fn columns_of(worklane_dir: &Path) -> Vec { +/// The four columns of one board, with each card's campaign already named. +/// +/// The index is read once here and handed to every card, rather than looked up per card +/// or, worse, per draw: the uuid is on the ticket and the name is in another directory, +/// so the cheapest honest place for the join is the pass that is already building the +/// cards. An unreadable campaigns directory is an empty index, which leaves every card in +/// no campaign and the board drawable. +fn columns_of(worklane_dir: &Path) -> (Vec, CampaignIndex) { + let campaigns = CampaignIndex::load(worklane_dir).unwrap_or_default(); + let mut columns: Vec = status_dirs() .into_iter() .map(|status| { @@ -843,6 +1166,7 @@ fn columns_of(worklane_dir: &Path) -> Vec { .unwrap_or_default() .into_iter() .map(|ticket| Card { + campaign: campaign_of(&ticket, &campaigns), ticket, project: None, blocked: false, @@ -853,9 +1177,62 @@ fn columns_of(worklane_dir: &Path) -> Vec { .collect(); mark_blocked(&mut columns); + (columns, campaigns) +} + +/// The campaigns of one board as the picker and the frame hold them. +/// +/// Built off the index the cards were named from, so the list a reader picks out of and +/// the label on the card cannot come from two different reads of the directory. The order +/// is the index's, which is by title, so the list does not depend on what order the +/// directory handed its files back in. +fn campaign_rows(campaigns: &CampaignIndex, project: Option<&str>) -> Vec { + campaigns + .iter() + .map(|campaign| CampaignRow { + uuid: campaign.uuid.clone(), + title: campaign.title.clone(), + codename: campaign.codename.clone(), + summary: section_opening(&campaign.content, &DESCRIPTION).unwrap_or_default(), + project: project.map(|name| name.to_string()), + }) + .collect() +} + +/// The columns filtered to one campaign's members, or left as they are when none is +/// selected. +/// +/// Every column is kept, empty ones included, for the reason `campaign show` prints every +/// status: a campaign groups across the flow rather than within one status, so the shape of +/// the answer is the four columns and the question is how many are in each. Filtered here, +/// where the columns are built, so nothing downstream has to ask whether a campaign is +/// selected — the board simply holds fewer cards. +fn retain_campaign(mut columns: Vec, campaign: Option<&str>) -> Vec { + let Some(uuid) = campaign else { + return columns; + }; + + for column in columns.iter_mut() { + column + .cards + .retain(|card| card.ticket.campaign.as_deref() == Some(uuid)); + } + columns } +/// The label for the campaign a ticket names, or nothing when it names none. +/// +/// Nothing, too, for a uuid the index does not hold. `campaign_cell` renders that case as +/// `_missing_` because a metadata table is a place to report a dangling reference; a card +/// is not, and the answer here is the one `mark_blocked` gives a blocker nobody holds. +fn campaign_of(ticket: &TicketItem, campaigns: &CampaignIndex) -> Option { + let uuid = ticket.campaign.as_deref()?; + let campaign = campaigns.get(uuid)?; + + Some(campaign_label(&campaign.uuid, campaign.codename.as_deref())) +} + /// Set `blocked` on every card whose ticket waits on one that is not done. /// /// Two walks of what `columns_of` has just read, not a lookup per relation: the status @@ -911,6 +1288,10 @@ fn merge(per_project: &[Vec], projects: &[Project]) -> Vec { // over the merged columns would let one project's uuid resolve // against another's ticket, which is a relation nothing can record. blocked: card.blocked, + // The same, and for the same reason: a campaign is resolved inside one + // `.worklane`, so a merged lookup could answer one project's uuid with + // another project's campaign. + campaign: card.campaign.clone(), })); } @@ -964,11 +1345,14 @@ fn digest_of(projects: &[Project]) -> u64 { hasher.finish() } -/// A fingerprint of every ticket and comment file: name, length and modified time. +/// A fingerprint of every ticket, campaign and comment file: name, length and modified +/// time. /// /// Names alone would miss a ticket edited in place, and a directory's own mtime only /// moves on create and rename, so watching the directories would miss it too. Comment -/// files are included because a comment added elsewhere has to reach the detail view. +/// files are included because a comment added elsewhere has to reach the detail view, and +/// campaign files because a campaign filed elsewhere has to reach the picker and a codename +/// edited by hand has to reach every card that names it. /// /// Cheap enough on a tree of tens of small files that it needs no new dependency. If it /// ever stops being cheap, `notify` is the next step, and the reason belongs on the @@ -1001,6 +1385,10 @@ pub fn digest(worklane_dir: &Path) -> u64 { visit(worklane_dir.join(status)); } + // The campaigns, because the board draws them: a campaign filed elsewhere has to reach + // the picker, and a codename edited by hand has to reach every card that names it. + visit(worklane_dir.join(CAMPAIGNS_DIR)); + // Comments live one level deeper, a directory per ticket. let comments = worklane_dir.join("comments"); if let Ok(read) = std::fs::read_dir(&comments) { @@ -1019,30 +1407,52 @@ pub fn digest(worklane_dir: &Path) -> u64 { pub fn draw(frame: &mut Frame, board: &Board) { let area = frame.area(); - let rows = frame_rows(area, board.tabbed()); + let chrome = board.chrome(); + let rows = frame_rows(area, chrome); - if board.tabbed() { - draw_tabs(frame, board, rows[0]); + if chrome.tabbed { + draw_tabs(frame, board, rows[TAB_ROW]); } - draw_columns(frame, board, rows[1]); - draw_footer(frame, board, rows[2]); + if let Some(campaign) = board.campaign() { + draw_campaign(frame, campaign, &board.current().standing(), rows[CAMPAIGN_ROW]); + } + draw_columns(frame, board, rows[BOARD_ROW]); + draw_footer(frame, board, rows[FOOTER_ROW]); if let Some(detail) = &board.detail { draw_detail(frame, detail, board.offset, area); } + // Over the overlay as well as the board. Both are things the reader put on, and the + // picker is the one they are acting in: an overlay drawn on top of it would cover the + // list they are choosing from. + if let Some(picker) = &board.picker { + draw_picker(frame, board.current(), picker, area); + } } -/// The rows of the frame: the tab row, the columns, the footer. +/// The rows of the frame, in the order `frame_rows` lays them out. +/// +/// Named rather than counted at each call site: the campaign frame arrived between the tab +/// row and the columns, and an index written out by hand is an index that goes on meaning +/// what it used to. +const TAB_ROW: usize = 0; +const CAMPAIGN_ROW: usize = 1; +const BOARD_ROW: usize = 2; +const FOOTER_ROW: usize = 3; + +/// The rows of the frame: the tab row, the campaign frame, the columns, the footer. /// /// One place, shared with the measurement in `card_width` and `column_text_height`, for /// the same reason `column_areas` is shared: geometry reproduced by hand is geometry -/// that comes to disagree with the draw. With one board the tab row is zero rows high, -/// so the indices hold either way and rendering into it draws nothing. -fn frame_rows(area: Rect, tabbed: bool) -> std::rc::Rc<[Rect]> { +/// that comes to disagree with the draw. With one board the tab row is zero rows high and +/// with no campaign selected the frame is too, so the indices hold in every state and +/// rendering into a zero-height row draws nothing. +fn frame_rows(area: Rect, chrome: Chrome) -> std::rc::Rc<[Rect]> { Layout::default() .direction(Direction::Vertical) .constraints([ - Constraint::Length(u16::from(tabbed)), + Constraint::Length(u16::from(chrome.tabbed)), + Constraint::Length(chrome.campaign_rows()), Constraint::Min(3), Constraint::Length(1), ]) @@ -1069,6 +1479,111 @@ fn draw_tabs(frame: &mut Frame, board: &Board, area: Rect) { ); } +/// The selected campaign above the columns: what it is called, what it is for, and how far +/// it has got. +/// +/// The columns below are its members, so this is the row that says whose members they are. +/// Three rows for it, of which one is prose: the identity goes on the top border and the +/// standing on the bottom one, the trade the detail overlay already makes with its title +/// and its page indicator, and every row taken here is a row of cards. +/// +/// The title carries the id in red, the codename in its own colour and bold, and the name +/// in green, which is the colour guideline applied rather than a decision of its own. Cut +/// by hand, like `detail_title`, because ratatui truncates a block title at whatever cell +/// it reaches and would take the id with it. +fn draw_campaign(frame: &mut Frame, campaign: &CampaignRow, standing: &Standing, area: Rect) { + let mut block = Block::default() + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::Grey.into())) + .title(Line::from(campaign_title(campaign, area.width))); + + // Right-aligned on the bottom border, where the overlay already puts the one number it + // has to show. The count is plain and the derived state is orange, which is the two + // colours `campaign ls` prints the same pair in. + let mut standing_spans = vec![Span::raw(format!(" {}", standing.label()))]; + if let Some(state) = standing.state() { + standing_spans.push(Span::styled( + format!(" [{state}]"), + Style::default().fg(Color::Orange.into()), + )); + } + standing_spans.push(Span::raw(" ")); + + // The way out, on the border of the thing it undoes rather than in the footer. The + // footer row is already at its width naming eight keys, and this belongs beside the + // frame anyway: it is what takes the frame away. Grey because it is chrome, the colour + // the footer's own key names and the overlay's page indicator take. + // + // Dropped whole when the two would meet, the rule the page indicator follows: half of + // either reads as something else, and the footer still answers how to leave the board. + let hint = " q board "; + let room = area.width.saturating_sub(2) as usize; + if hint.chars().count() + spans_width(&standing_spans) <= room { + block = block + .title_bottom(Line::from(Span::styled(hint, Style::default().fg(Color::Grey.into())))); + } + + block = block.title_bottom(Line::from(standing_spans).right_aligned()); + + // The description's opening line, or the placeholder in grey for a campaign that has + // none: the row is spent either way, and a blank one reads as a frame that failed to + // draw. Wrapped off, so a long line is cut at the border rather than pushing the frame + // taller than the geometry says it is. + let summary = match campaign.summary.is_empty() { + true => Span::styled(DESCRIPTION.placeholder, Style::default().fg(Color::Grey.into())), + false => Span::raw(campaign.summary.clone()), + }; + + frame.render_widget(Paragraph::new(Line::from(summary)).block(block), area); +} + +/// The campaign frame's title: `(id) ~codename · Name`, cut to the border it sits on. +/// +/// The same shape and the same cut as `detail_title`, since both name one thing on a +/// border: the id first because that is how every view addresses a campaign, the codename +/// next because it is the id in a word, and the name last because it is what the two are +/// shorthand for. A campaign with no codename spends nothing on one. +fn campaign_title(campaign: &CampaignRow, frame_width: u16) -> Vec> { + let label = campaign.label(); + let codename = match campaign.codename.is_some() { + true => format!("{} ", label.text), + false => String::new(), + }; + + let prefix = format!(" ({}) {codename}· ", short_id(&campaign.uuid)); + let room = frame_width.saturating_sub(2) as usize; + + // The trailing space is part of what has to fit, so it is measured rather than added + // on afterwards: a title that filled the border exactly would otherwise be drawn one + // cell past it and cut by ratatui, taking the space and the last letter with it. + let whole = format!("{} ", campaign.title); + let name = match prefix.chars().count() + whole.chars().count() <= room { + true => whole, + // What is left after the prefix and the space that follows the cut name. + false => match room.saturating_sub(prefix.chars().count() + 1) { + 0 => String::new(), + keep => format!("{} ", with_ellipsis(&campaign.title, keep)), + }, + }; + + vec![ + Span::raw(" ("), + Span::styled( + short_id(&campaign.uuid).to_string(), + Style::default().fg(Color::Red.into()), + ), + Span::raw(") "), + Span::styled( + codename, + Style::default() + .fg(label.color.unwrap_or(Color::Grey).into()) + .add_modifier(Modifier::BOLD), + ), + Span::raw("· "), + Span::styled(name, Style::default().fg(Color::Green.into())), + ] +} + fn draw_columns(frame: &mut Frame, board: &Board, area: Rect) { // Only the drawn columns are measured, so hiding done gives its width back to the // three that are left rather than leaving a gap where it was. @@ -1156,8 +1671,8 @@ fn column_areas(area: Rect, count: usize) -> std::rc::Rc<[Rect]> { } /// The width a card has inside one column, as the next draw will lay it out. -fn card_width(screen: Size, tabbed: bool, count: usize, column: usize) -> u16 { - column_areas(board_area(screen, tabbed), count) +fn card_width(screen: Size, chrome: Chrome, count: usize, column: usize) -> u16 { + column_areas(board_area(screen, chrome), count) .get(column) .map(|area| area.inner(Margin::new(1, 1)).width) .unwrap_or(0) @@ -1167,13 +1682,13 @@ fn card_width(screen: Size, tabbed: bool, count: usize, column: usize) -> u16 { /// /// A border row on either side of the text. The draw measures the real inner rectangle /// instead, so a terminal too short for this arithmetic is corrected there. -fn column_text_height(screen: Size, tabbed: bool) -> u16 { - board_area(screen, tabbed).height.saturating_sub(2) +fn column_text_height(screen: Size, chrome: Chrome) -> u16 { + board_area(screen, chrome).height.saturating_sub(2) } /// The area the columns are drawn in, which is what `draw` hands to `draw_columns`. -fn board_area(screen: Size, tabbed: bool) -> Rect { - frame_rows(Rect::new(0, 0, screen.width, screen.height), tabbed)[1] +fn board_area(screen: Size, chrome: Chrome) -> Rect { + frame_rows(Rect::new(0, 0, screen.width, screen.height), chrome)[BOARD_ROW] } /// The offset that keeps the lines `start..end` in view, inside content `0..total`. @@ -1200,7 +1715,7 @@ fn aligned_offset(offset: u16, start: u16, end: u16, inner: u16, total: u16) -> /// ●◐ (1b78a24) 2026-12-31 /// The tui detail view cannot /// scroll, and the footer says… -/// #cli #tui +/// ~beaver #cli #tui /// Ansho Rei [3/9] /// ``` /// @@ -1213,8 +1728,8 @@ fn aligned_offset(offset: u16, start: u16, end: u16, inner: u16, total: u16) -> /// several boards the id alone is not an address: two projects can hold the same title, /// and seven characters do not say where they live. /// -/// The tags sit between the title and the bottom corners, on a row a ticket without -/// them does not spend. See [`tags_line`]. +/// The campaign and the tags sit between the title and the bottom corners, on a row a +/// ticket without either does not spend. See [`labels_line`]. /// /// A held-up ticket carries [`BLOCKED_MARK`] after its id, ahead of the project and the /// due date, both of which give way to it: those are context for a ticket somebody can @@ -1276,7 +1791,7 @@ fn card_lines(card: &Card, selected: bool, width: u16) -> Vec> { .map(|line| Line::from(Span::styled(line, Style::default().add_modifier(emphasis)))), ); - if let Some(row) = tags_line(&ticket.tags, width) { + if let Some(row) = labels_line(card.campaign.as_ref(), &ticket.tags, width) { lines.push(row); } @@ -1298,42 +1813,64 @@ fn card_lines(card: &Card, selected: bool, width: u16) -> Vec> { lines } -/// The ticket's tags under the title, or nothing when it has none. +/// The ticket's campaign and tags under the title, or nothing when it has neither. /// /// Each tag is prefixed with `#` and the row is dimmed like the owner and the criteria /// count: what a card is for is telling tickets apart at a glance, and colour here /// accentuates rather than encodes. Without the marker the row reads as a third line of /// the title, since a tag is an ordinary word and the title sits directly above it. /// +/// The campaign is the same kind of thing said the same way, with [`CAMPAIGN_MARK`] for +/// its marker and in bold. It comes **first and takes its space first**: two cards in one +/// campaign are what a reader is looking for when they are looking for a campaign at all, +/// and the tags are the context around that. So a row too narrow to hold both drops the +/// tags whole and keeps the campaign, the order `corner_line` and `project_label` already +/// use — the stronger fact takes the row and the weaker one gives way. Bold is what stops +/// it reading as another tag when a card carries five. +/// /// A row the column will not hold is dropped whole, the rule `corner_line` applies to a /// corner: a cut list reads as a shorter one, and `bug` and `bugfix` truncated to the -/// same width say the same thing. An untagged ticket spends no row at all, the way a -/// short title spends no second one. +/// same width say the same thing. A ticket with neither a campaign nor a tag spends no row +/// at all, the way a short title spends no second one, so a ticket in no campaign renders +/// exactly as it did before campaigns reached the card. /// /// Each tag carries its own colour, from `tag_color`, so the same tag is the same -/// colour on every card in every column. The row is spans rather than one string for +/// colour on every card in every column, and the campaign carries its own from +/// `campaign_label` for the same reason. The row is spans rather than one string for /// that reason alone; it is still measured as one string. -fn tags_line(tags: &[String], width: u16) -> Option> { - if tags.is_empty() { - return None; - } +fn labels_line(campaign: Option<&Cell>, tags: &[String], width: u16) -> Option> { + let width = width as usize; + // Measured on the raw text, before anything is styled. What fits must not depend on + // the colour decision, or a card would hold its labels in one render and drop them in + // the other. + let campaign = campaign.filter(|cell| cell.text.chars().count() <= width); + let used = campaign.map_or(0, |cell| cell.text.chars().count()); + + // The space between the campaign and the first tag, which the row has to hold too. + let room = width.saturating_sub(used + usize::from(campaign.is_some())); let row = tags .iter() .map(|tag| format!("#{tag}")) .collect::>() .join(" "); + let tags: &[String] = match !row.is_empty() && row.chars().count() <= room { + true => tags, + false => &[], + }; - // Measured on the raw row, before anything is styled. What fits must not depend on - // the colour decision, or a card would hold its tags in one render and drop them in - // the other. - if row.chars().count() > width as usize { + if campaign.is_none() && tags.is_empty() { return None; } - let mut spans = Vec::with_capacity(tags.len() * 2); - for (index, tag) in tags.iter().enumerate() { - if index > 0 { + let mut spans = Vec::with_capacity(tags.len() * 2 + 2); + if let Some(cell) = campaign { + spans + .push(span_of(cell.clone()).patch_style(Style::default().add_modifier(Modifier::BOLD))); + } + + for tag in tags { + if !spans.is_empty() { spans.push(Span::raw(" ")); } spans.push(Span::styled(format!("#{tag}"), Style::default().fg(tag_color(tag).into()))); @@ -1496,6 +2033,19 @@ fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { return; } + // And the picker takes it on the same terms: it owns the keyboard, so the list of keys + // the board answers to describes nothing that currently works either. + if board.picker.is_some() { + frame.render_widget( + Paragraph::new(Span::styled( + " ↑↓ select enter view esc cancel ", + Style::default().fg(Color::Grey.into()), + )), + area, + ); + return; + } + // And a notice takes it for the one keypress it lives, for a weaker reason than the // prompt's: every key still works while it is up. It is that a message squeezed in // beside the list would move every key in it, and the row is the only place on the @@ -1519,16 +2069,32 @@ fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { false => "", }; - // The last slot answers the same question in both states: how to get out of here. - // With a ticket open `q` closes it, so the honest answer there is `ctrl-c`, which is - // the only key left that quits in one press. Naming `q quit` over an open overlay - // would be the fault 1b78a24 was, a footer describing a key by what it used to do. + // The last slot answers the same question in every state: how to get out of here. `q` + // takes off whatever is on top, so with a ticket open or a campaign selected the honest + // answer is `ctrl-c`, the only key left that quits in one press. Naming `q quit` over + // either would be the fault 1b78a24 was, a footer describing a key by what it used to + // do — and with a campaign selected it names what that press actually does instead. + let quit = match board.detail.is_some() || board.campaign().is_some() { + true => "ctrl-c quit", + false => "q quit", + }; + + // `c` is named where a reader has to find it: on the board, with nothing selected. Over + // an open ticket and on a board already filtered to a campaign it is left out, because + // the frame's own border then says how to put the campaign away and the row is at its + // width naming eight keys. Incomplete rather than wrong, which is the trade this row is + // allowed to make: what it must never do is name a key by what it used to do. + let campaign = match board.campaign().is_some() { + true => "", + false => "c campaign ", + }; + let keys = match board.detail { Some(_) => format!( - " {tabs}←→↑↓ select pgup/pgdn scroll / search y copy id enter/q close {done} ctrl-c quit " + " {tabs}←→↑↓ select pgup/pgdn scroll / search y copy id enter/q close {done} {quit} " ), None => format!( - " {tabs}←→ column ↑↓ card / search y copy id enter detail {done} q quit " + " {tabs}←→ column ↑↓ card / search {campaign}y copy id enter detail {done} {quit} " ), }; @@ -1592,6 +2158,155 @@ fn done_count(board: &Board) -> usize { .map_or(0, |column| column.cards.len()) } +/// Where the campaign picker sits in the frame. +/// +/// Narrower than the detail overlay and no taller than it needs to be. A picker is a list +/// of short rows, and one stretched to the shape of a ticket would be mostly blank space +/// with the board hidden behind it. It grows with the list up to that ceiling, so a board +/// with two campaigns gets a box with two rows in it. +fn picker_overlay(area: Rect, rows: usize) -> Rect { + let width = area + .width + .saturating_mul(3) + .div_euclid(5) + .max(20) + .min(area.width); + // A border row either side of the list. + let wanted = u16::try_from(rows).unwrap_or(u16::MAX).saturating_add(2); + let height = wanted.min(picker_height(area)); + + Rect { + x: area.x + (area.width.saturating_sub(width)) / 2, + y: area.y + (area.height.saturating_sub(height)) / 2, + width, + height, + } +} + +/// The tallest the picker's box can be, whatever its list holds. +fn picker_height(area: Rect) -> u16 { + area.height + .saturating_sub(area.height / 4) + .max(4) + .min(area.height) +} + +/// The rows the picker draws its list in, the border taken off either side. +/// +/// Measured against the tallest box it can be rather than the box it currently is, because +/// the caller that scrolls is a keypress and has only the screen: a height that depended on +/// the number of rows would make the scroll step depend on the list it is scrolling. A list +/// short enough to fit anyway has nothing to scroll, so the two agree where it matters. +fn picker_text_area(area: Rect) -> Rect { + Rect { + height: picker_height(area).saturating_sub(2), + ..picker_overlay(area, 0) + } +} + +/// The campaign picker: one row per campaign, the highlighted one reversed. +/// +/// Each row is the short id, the campaign as a label, and the opening line of its +/// description cut to what is left, which is the same three things in the same order the +/// frame's title carries. The description is the field that gives way, because it is the +/// only one of the three that is prose. +/// +/// The rows come off the tab rather than off the picker, so a campaign filed while the +/// picker is open appears in it on the next tick instead of being missing from a copy of +/// the list taken when it opened. +fn draw_picker(frame: &mut Frame, tab: &Tab, picker: &Picker, area: Rect) { + let overlay = picker_overlay(area, tab.campaigns.len()); + let text = overlay.inner(Margin::new(1, 1)); + + let lines: Vec = tab + .campaigns + .iter() + .enumerate() + .map(|(at, campaign)| picker_line(campaign, at == picker.row, text.width)) + .collect(); + + let block = Block::default() + .borders(Borders::ALL) + .border_style(Style::default().fg(Color::Cyan.into())) + .title(Span::styled( + format!(" campaigns ({}) ", tab.campaigns.len()), + Style::default().fg(Color::Orange.into()), + )); + + // Capped against blank space past the last row, the way an unfocused column is. + let last = (lines.len() as u16).saturating_sub(text.height); + + frame.render_widget(Clear, overlay); + frame.render_widget( + Paragraph::new(lines) + .block(block) + .scroll((picker.offset.min(last), 0)), + overlay, + ); +} + +/// One picker row: `(1b78a24) ~beaver What the campaign is for`. +/// +/// The highlight is `REVERSED`, the way a selected card is, so the row reads the same +/// whatever colours are already on it. The summary is grey because it is context around the +/// two things being chosen between, and it is cut with an ellipsis rather than dropped: half +/// a sentence still says what a campaign is about, which is not true of half an id. +fn picker_line(campaign: &CampaignRow, selected: bool, width: u16) -> Line<'static> { + let emphasis = match selected { + true => Modifier::REVERSED, + false => Modifier::empty(), + }; + + let mut spans = vec![Span::styled( + format!("({})", short_id(&campaign.uuid)), + Style::default().fg(Color::Red.into()).add_modifier(emphasis), + )]; + + // Only a real codename, unlike a card, which falls back to the short id because it has + // no other way to name the campaign. Here the id is the first thing on the row, so the + // fallback would print it twice and say nothing the second time. + if campaign.codename.is_some() { + let label = campaign.label(); + spans.push(Span::raw(" ")); + spans.push(Span::styled( + label.text.clone(), + Style::default() + .fg(label.color.unwrap_or(Color::Grey).into()) + .add_modifier(emphasis | Modifier::BOLD), + )); + } + + // The project on the merge tab, where a campaign id does not say which board holds it. + if let Some(project) = &campaign.project { + spans.push(Span::raw(" ")); + spans.push(Span::styled( + project.clone(), + Style::default().fg(Color::Grey.into()).add_modifier(emphasis), + )); + } + + // What the campaign is *called* takes the row first, and the prose takes what is left. + // Under three characters there is nothing left to say, the bargain `project_label` makes. + let used = spans_width(&spans); + let summary = match campaign.summary.is_empty() { + true => campaign.title.as_str(), + false => campaign.summary.as_str(), + }; + if let Some(room) = (width as usize).checked_sub(used + 2).filter(|room| *room >= 3) { + let cut = match summary.chars().count() <= room { + true => summary.to_string(), + false => with_ellipsis(summary, room), + }; + spans.push(Span::raw(" ")); + spans.push(Span::styled( + cut, + Style::default().fg(Color::Grey.into()).add_modifier(emphasis), + )); + } + + Line::from(spans) +} + /// Where the detail overlay sits in the frame. /// /// Inset, so the board stays visible around the edges and the overlay reads as one. @@ -1833,6 +2548,9 @@ mod tests { /// same overlay. const SCREEN: Size = Size { width: 120, height: 20 }; + /// One board, no campaign selected: the chrome most of these tests measure against. + const PLAIN: Chrome = Chrome { tabbed: false, campaign: false }; + /// The rendered buffer as lines of text, escapes and styling dropped. fn render(board: &Board, width: u16, height: u16) -> Vec { let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); @@ -1856,7 +2574,7 @@ mod tests { /// through the layout rather than assumed to be row zero, since a tab row sits above /// it when more than one board is monitored. fn headings(board: &Board, width: u16, height: u16) -> String { - let top = board_area(Size { width, height }, board.tabbed()).y as usize; + let top = board_area(Size { width, height }, board.chrome()).y as usize; render(board, width, height).remove(top) } @@ -2125,10 +2843,53 @@ mod tests { .unwrap(); } + /// The same again, with the Campaign field a test can set. + /// + /// A separate fixture rather than a sixth parameter on `write_tagged_card`: the + /// callers that care about tags do not care about campaigns, and five string + /// arguments in a row is what the Rust Style rule in AGENTS.md warns about. + fn write_member_card(dir: &Path, title: &str, tags: &str, campaign: &str) { + let uuid = "11111111-0000-4000-8000-000000000000"; + std::fs::write( + dir.join("backlog").join(format!("{}_{}.md", uuid, slug(title))), + format!( + "# {title}\n\n## Description\nA description.\n\n## Acceptance Criteria\n\ + - [ ] One\n\n## Metadata\n\n- **ID**: {uuid}\n- **Priority**: 2\n\ + - **Tags**: {tags}\n- **Due**: 2026-12-31\n- **Owner**: alice\n\ + - **Created At**: 2026-08-21 02:00:00\n- **Campaign**: {campaign}\n\ + - **Status**: backlog\n" + ), + ) + .unwrap(); + } + + /// A campaign on disk, since the board reads the directory rather than being told. + /// + /// The codename is written as `_Not set_` when a test does not give one, which is what + /// `campaign add` writes for a campaign filed without one. + fn write_campaign(dir: &Path, uuid: &str, title: &str, codename: &str, description: &str) { + let campaigns = dir.join(CAMPAIGNS_DIR); + std::fs::create_dir_all(&campaigns).unwrap(); + + let codename = match codename.is_empty() { + true => NOT_SET, + false => codename, + }; + std::fs::write( + campaigns.join(format!("{}_{}.md", uuid, slug(title))), + format!( + "# {title}\n\n## Description\n{description}\n\n## Metadata\n\n\ + - **ID**: {uuid}\n- **Codename**: {codename}\n- **Owner**: alice\n\ + - **Created At**: 2026-08-21 02:00:00\n" + ), + ) + .unwrap(); + } + /// The rows of the only card on the board, at the width the column gives it. fn only_card(dir: &Path, width: u16, height: u16) -> Vec { let board = one_board(dir); - let inner = card_width(Size { width, height }, board.tabbed(), board.visible().len(), 0); + let inner = card_width(Size { width, height }, board.chrome(), board.visible().len(), 0); let ticket = board.selected().expect("no card"); card_lines(ticket, false, inner) .iter() @@ -2155,7 +2916,7 @@ mod tests { fn card_colour(dir: &Path, width: u16, needle: &str) -> Option { let board = one_board(dir); let inner = - card_width(Size { width, height: 20 }, board.tabbed(), board.visible().len(), 0); + card_width(Size { width, height: 20 }, board.chrome(), board.visible().len(), 0); let ticket = board.selected().expect("no card"); card_lines(ticket, false, inner) @@ -2181,7 +2942,7 @@ mod tests { ); let rows = only_card(&dir, 120, 20); - let inner = card_width(Size { width: 120, height: 20 }, false, 3, 0) as usize; + let inner = card_width(Size { width: 120, height: 20 }, PLAIN, 3, 0) as usize; assert_eq!(rows.len(), 5, "expected two title rows and a blank: {rows:?}"); assert!(rows[1].starts_with("A title long"), "{rows:?}"); @@ -2346,7 +3107,7 @@ mod tests { write_card(&dir, "Short", "2026-12-31", "- [ ] One"); let rows = only_card(&dir, 52, 14); - let inner = card_width(Size { width: 52, height: 14 }, false, 3, 0) as usize; + let inner = card_width(Size { width: 52, height: 14 }, PLAIN, 3, 0) as usize; assert!(rows[0].starts_with("\u{25cf}\u{25d0} (1111111)"), "{rows:?}"); assert!(!rows[0].contains("2026"), "the due overran the column: {rows:?}"); @@ -3040,7 +3801,7 @@ mod tests { board.toggle_detail(); assert!(board.detail.is_some(), "nothing was open to dismiss"); - board.dismiss(); + board.dismiss(SCREEN); assert!(board.detail.is_none(), "the overlay stayed open"); assert!(!board.should_quit, "closing a ticket took the board with it"); @@ -3056,7 +3817,7 @@ mod tests { write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); - board.dismiss(); + board.dismiss(SCREEN); assert!(board.should_quit, "the board stayed up with nothing to close"); } @@ -3075,7 +3836,7 @@ mod tests { .join(" "); assert!( - source.contains("KeyCode::Esc | KeyCode::Char('q') => board.dismiss(),"), + source.contains("KeyCode::Esc | KeyCode::Char('q') => board.dismiss(screen),"), "`q` and `esc` mean one thing and have to reach `Board::dismiss` from one \ arm. Two arms carrying one rule is how a later edit changes it for one key \ and not the other, which is what this ticket already was." @@ -4751,4 +5512,640 @@ mod tests { std::fs::remove_dir_all(&dir).ok(); } + + // ------------------------------------------------------------- campaigns -- + + /// The campaign uuid of the board's first campaign, so a test can name one without + /// writing a uuid out twice. + const V1: &str = "22222222-0000-4000-8000-000000000000"; + const BEAVER: &str = "33333333-0000-4000-8000-000000000000"; + + /// A board with two campaigns and a member in each, plus one ticket in neither. + fn campaign_board(dir: &Path) -> Board { + write_campaign(dir, V1, "First public release", "v1", "Everything for a public tag."); + write_campaign(dir, BEAVER, "Beaver migration", "beaver", "Move the store off one disk."); + + write_ticket( + dir, + "backlog", + "11111111-0000-4000-8000-000000000000", + "In v1", + &campaign_field(V1), + ); + write_ticket( + dir, + "committed", + "44444444-0000-4000-8000-000000000000", + "Also in v1", + &campaign_field(V1), + ); + write_ticket( + dir, + "backlog", + "55555555-0000-4000-8000-000000000000", + "In beaver", + &campaign_field(BEAVER), + ); + write_ticket(dir, "backlog", "66666666-0000-4000-8000-000000000000", "In neither", ""); + + one_board(dir) + } + + fn campaign_field(uuid: &str) -> String { + format!("- **Campaign**: {uuid}\n") + } + + /// The picker's rows, cut out of the frame by its own geometry. + /// + /// The whole screen will not do: a card carries the same campaign label, so a search + /// for one over every row finds the board rather than the list, which is the shape + /// `overlay_title_row` exists for on the other overlay. + fn picker_rows(board: &Board, width: u16, height: u16) -> Vec { + let rows = board.current().campaigns.len(); + let overlay = picker_overlay(Rect::new(0, 0, width, height), rows); + let inner = overlay.inner(Margin::new(1, 1)); + let lines = render(board, width, height); + + (inner.y..inner.y + inner.height) + .map(|y| { + lines[y as usize] + .chars() + .skip(inner.x as usize) + .take(inner.width as usize) + .collect() + }) + .collect() + } + + /// The card said nothing about which release a ticket belonged to, which is the one + /// thing a board is read to decide. + #[test] + fn a_card_names_the_campaign_it_is_in() { + let dir = board_dir(); + write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); + write_member_card(&dir, "Short", "cli, tui", V1); + + let rows = only_card(&dir, 120, 20); + assert_eq!(rows.len(), 5, "the label row is missing: {rows:?}"); + assert_eq!(rows[2], "~v1 #cli #tui", "the campaign is not on the row: {rows:?}"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The mark is not `#`, because the two sit on one row and the row would otherwise + /// read as a list of tags with a stranger in it. + #[test] + fn the_campaign_mark_is_not_the_tag_mark() { + assert_ne!(CAMPAIGN_MARK, "#"); + assert_eq!(CAMPAIGN_MARK.chars().count(), 1, "the mark has to fit a card's row"); + } + + /// The codename exists because a short id says nothing about what a campaign is for. + /// Without one there is nothing better to draw, so the id is what the card falls back + /// to: it says little, and it still resolves. + #[test] + fn a_campaign_with_no_codename_falls_back_to_its_short_id() { + let dir = board_dir(); + write_campaign(&dir, V1, "First public release", "", "For a public tag."); + write_member_card(&dir, "Short", "_None_", V1); + + let rows = only_card(&dir, 120, 20); + assert_eq!(rows[2], format!("~{}", short_id(V1)), "{rows:?}"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A ticket in no campaign renders exactly as it did before campaigns reached the + /// card: no row, no marker, nothing spent. + #[test] + fn a_ticket_in_no_campaign_spends_no_row() { + let dir = board_dir(); + write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); + write_member_card(&dir, "Short", "_None_", NOT_SET); + + let rows = only_card(&dir, 120, 20); + assert_eq!(rows.len(), 4, "a row was spent on nothing: {rows:?}"); + assert!(!rows.iter().any(|row| row.contains(CAMPAIGN_MARK)), "{rows:?}"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A campaign the board does not hold marks nothing, the answer `mark_blocked` gives + /// a blocker nobody holds: a uuid nothing carries is a bookkeeping fault rather than + /// a fact about this ticket, and a card is no place to report one. + #[test] + fn a_campaign_the_board_does_not_hold_marks_nothing() { + let dir = board_dir(); + write_member_card(&dir, "Short", "_None_", "99999999-0000-4000-8000-000000000000"); + + let rows = only_card(&dir, 120, 20); + assert_eq!(rows.len(), 4, "{rows:?}"); + assert!(!rows.iter().any(|row| row.contains("_missing_")), "{rows:?}"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The campaign takes the row first and the tags give way, the order a corner and a + /// project label already follow: two cards in one campaign is what a reader looking + /// for a campaign is looking for, and the tags are the context around it. + #[test] + fn the_campaign_keeps_the_row_and_the_tags_give_way() { + let dir = board_dir(); + write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); + write_member_card(&dir, "Short", "frontend, operations", V1); + + // One character short of "~v1 #frontend #operations", and one over it. + let narrow = only_card_at(&dir, 24); + assert_eq!(narrow[2], "~v1", "the tags took the row from the campaign: {narrow:?}"); + + let fits = only_card_at(&dir, 25); + assert_eq!(fits[2], "~v1 #frontend #operations", "{fits:?}"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// And a campaign the row will not hold goes whole, never cut: half a codename is a + /// different codename, which is the rule every other thing on a card follows. + #[test] + fn a_campaign_too_wide_for_the_column_is_dropped_whole() { + let dir = board_dir(); + write_campaign(&dir, V1, "First public release", "beaver", "For a public tag."); + write_member_card(&dir, "Short", "_None_", V1); + + let narrow = only_card_at(&dir, 6); + assert_eq!(narrow.len(), 4, "the label was kept: {narrow:?}"); + + let fits = only_card_at(&dir, 7); + assert_eq!(fits[2], "~beaver", "{fits:?}"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The colour groups a campaign across the cards that carry it, from the same pure + /// function a tag's colour comes from, and the bold is what stops it reading as a + /// sixth tag on a card that has five. + #[test] + fn the_campaign_label_is_bold_and_coloured_by_its_codename() { + let dir = board_dir(); + write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); + write_member_card(&dir, "Short", "cli", V1); + + let board = one_board(&dir); + let card = board.selected().expect("no card"); + let label = card_lines(card, false, 40) + .iter() + .flat_map(|line| line.spans.clone()) + .find(|span| span.content == "~v1") + .expect("no campaign span on the card"); + + assert_eq!(label.style.fg, Some(tag_color("v1").into()), "not the label colour"); + assert!( + label.style.add_modifier.contains(Modifier::BOLD), + "the campaign does not jump out: {:?}", + label.style + ); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A campaign with no codename is drawn in grey rather than in the red a uuid takes + /// everywhere else, so no reserved meaning lands on a tag slot and the one thing the + /// card has to say for itself is that this campaign has nothing to be called. + #[test] + fn a_codenameless_campaign_is_drawn_as_chrome() { + let label = campaign_label(V1, None); + assert_eq!(label.color, Some(Color::Grey)); + + let named = campaign_label(V1, Some("v1")); + assert_eq!(named.color, Some(tag_color("v1"))); + } + + /// An unreadable campaigns directory leaves every card in no campaign and the board + /// drawable, which is the same bargain an unreadable status directory takes. + #[test] + fn an_unreadable_campaigns_directory_leaves_the_board_drawable() { + let dir = board_dir(); + // A file where the directory should be: `read_dir` fails on it, which a missing + // directory does not, so this is the path the empty index is actually for. + std::fs::write(dir.join(CAMPAIGNS_DIR), "not a directory").unwrap(); + write_member_card(&dir, "Short", "cli", V1); + + let board = one_board(&dir); + assert!(board.current().campaigns.is_empty(), "campaigns came from a file"); + assert!( + board.selected().expect("no card").campaign.is_none(), + "a card was labelled" + ); + assert!(headings(&board, 100, 24).contains("backlog (1)"), "the board did not draw"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// Selecting a campaign turns the four columns into that campaign's members grouped + /// by status, which is the shape `campaign show` already answers the question in. + #[test] + fn selecting_a_campaign_filters_every_column_to_its_members() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + + let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); + assert_eq!(all, 4, "the fixture changed"); + + board.select_campaign(Some(V1.to_string()), SCREEN); + + let titles: Vec = board + .current() + .columns + .iter() + .flat_map(|column| column.cards.iter().map(|card| card.ticket.title.clone())) + .collect(); + assert_eq!(titles, vec!["In v1".to_string(), "Also in v1".to_string()], "{titles:?}"); + // Every column is kept, empty ones included: a campaign's shape is the flow. + assert_eq!(board.current().columns.len(), status_dirs().len()); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The frame says which campaign the columns belong to, and how far it has got, from + /// the columns rather than from a second walk of the tree. + #[test] + fn the_frame_names_the_campaign_and_its_standing() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.select_campaign(Some(V1.to_string()), SCREEN); + + let rows = render(&board, 100, 24); + assert!(rows[0].contains(short_id(V1)), "no id on the frame: {:?}", rows[0]); + assert!(rows[0].contains("~v1"), "no codename on the frame: {:?}", rows[0]); + assert!(rows[0].contains("First public release"), "no name: {:?}", rows[0]); + assert!( + rows[1].contains("Everything for a public tag."), + "no summary: {:?}", + rows[1] + ); + assert!(rows[2].contains("0/2 done"), "no standing: {:?}", rows[2]); + assert!(rows[2].contains("[open]"), "no derived state: {:?}", rows[2]); + // The way out, on the border of the thing it undoes. + assert!(rows[2].contains("q board"), "no way out named: {:?}", rows[2]); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The standing counts done whether the column is drawn or not: hiding done is a + /// change to what is drawn and never to what is counted. + #[test] + fn the_standing_counts_done_members_while_the_column_is_hidden() { + let dir = board_dir(); + write_campaign(&dir, V1, "First public release", "v1", "For a tag."); + write_ticket( + &dir, + "backlog", + "11111111-0000-4000-8000-000000000000", + "Open one", + &campaign_field(V1), + ); + write_ticket( + &dir, + "done", + "44444444-0000-4000-8000-000000000000", + "Finished one", + &campaign_field(V1), + ); + + let mut board = one_board(&dir); + board.select_campaign(Some(V1.to_string()), SCREEN); + + assert!(!board.show_done, "done is hidden at startup"); + let standing = board.current().standing(); + assert_eq!((standing.done, standing.total), (1, 2)); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The frame takes its three rows off the columns rather than off the footer, and + /// every measurement of the board has to agree about that: a keypress that scrolled + /// against the taller board would put the selection where the draw does not. + #[test] + fn the_frame_takes_its_rows_from_the_columns() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + let screen = Size { width: 100, height: 24 }; + + let plain = board_area(screen, board.chrome()); + board.select_campaign(Some(V1.to_string()), screen); + let framed = board_area(screen, board.chrome()); + + assert_eq!(framed.y, plain.y + Chrome::CAMPAIGN_ROWS, "the columns did not move down"); + assert_eq!( + framed.height, + plain.height - Chrome::CAMPAIGN_ROWS, + "the frame took its rows from somewhere else" + ); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// `q` takes off one layer at a time, in the order they were put on: the overlay, then + /// the campaign, then the board. Quitting out from under a filter is what `q` used to + /// do to an open ticket. + #[test] + fn dismiss_takes_off_the_campaign_before_the_board() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.select_campaign(Some(V1.to_string()), SCREEN); + + board.dismiss(SCREEN); + assert_eq!(board.current().campaign, None, "the campaign is still selected"); + assert!(!board.should_quit, "the board quit out from under the filter"); + // And the whole board is back, not an empty one. + let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); + assert_eq!(all, 4); + + board.dismiss(SCREEN); + assert!(board.should_quit, "nothing left to close and it did not quit"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// And the overlay comes off before the campaign, so one press takes off one layer. + #[test] + fn dismiss_closes_the_overlay_before_the_campaign() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.select_campaign(Some(V1.to_string()), SCREEN); + board.toggle_detail(); + assert!(board.detail.is_some(), "nothing opened"); + + board.dismiss(SCREEN); + assert!(board.detail.is_none(), "the overlay stayed open"); + assert_eq!(board.current().campaign, Some(V1.to_string()), "the filter came off too"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// Selecting a campaign closes an open ticket, the answer hiding the done column + /// already gives: the ticket may not be on the filtered board at all, and swapping it + /// for a different one without saying so is how a person acts on the wrong ticket. + #[test] + fn selecting_a_campaign_closes_an_open_ticket() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.toggle_detail(); + assert!(board.detail.is_some(), "nothing opened"); + + board.select_campaign(Some(BEAVER.to_string()), SCREEN); + assert!(board.detail.is_none(), "the overlay survived the filter"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The picker owns the keyboard while it is open, the rule the search prompt already + /// holds: `d` must not toggle done and `q` must not quit while a campaign is being + /// chosen. + #[test] + fn the_picker_swallows_every_key_it_is_given() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.open_picker(); + + for code in [KeyCode::Char('d'), KeyCode::Char('/'), KeyCode::Char('y')] { + assert!( + board.picker_key(KeyEvent::new(code, KeyModifiers::NONE), SCREEN), + "the picker let {code:?} through" + ); + } + assert!(!board.show_done, "d reached the done column"); + assert!(board.search.is_none(), "/ opened the prompt"); + assert!(board.picker.is_some(), "the picker closed on a key it does not use"); + + // Every other control combination is swallowed and does nothing, or `ctrl-d` would + // reach the arm bound to `d`. + board.picker_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL), SCREEN); + assert!(!board.show_done, "ctrl-d reached the done column"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// `ctrl-c` is the one key it declines, because a terminal application always honours + /// it and a picker that ate it would leave no way off the board. + #[test] + fn the_picker_declines_ctrl_c() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.open_picker(); + + assert!( + !board.picker_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL), SCREEN) + ); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The point of the list: move to a campaign, press enter, look at it. + #[test] + fn enter_in_the_picker_takes_the_highlighted_campaign() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.open_picker(); + + // By title, which is the index's order, so the first row is Beaver migration. + let first = board.current().campaigns[0].uuid.clone(); + assert_eq!(first, BEAVER, "the list is not in the index's order"); + + board.picker_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), SCREEN); + assert!(board.picker.is_none(), "the picker stayed open"); + assert_eq!(board.current().campaign, Some(BEAVER.to_string())); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// Esc leaves the board exactly as it was, so opening the list is never a commitment. + #[test] + fn esc_in_the_picker_changes_nothing() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.select_campaign(Some(V1.to_string()), SCREEN); + board.open_picker(); + board.picker_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), SCREEN); + board.picker_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), SCREEN); + + assert!(board.picker.is_none(), "the picker stayed open"); + assert_eq!(board.current().campaign, Some(V1.to_string()), "the filter moved"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// It opens on the campaign already selected, so `c` on a filtered board says where + /// you are as well as offering somewhere to go. + #[test] + fn the_picker_opens_on_the_campaign_in_view() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.select_campaign(Some(V1.to_string()), SCREEN); + board.open_picker(); + + let row = board.picker.as_ref().expect("no picker").row; + assert_eq!(board.current().campaigns[row].uuid, V1); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A board with no campaigns says so in words rather than opening an empty box that + /// has to be dismissed to learn it was empty. + #[test] + fn a_board_with_no_campaigns_says_so_rather_than_opening_an_empty_picker() { + let dir = board_dir(); + write_member_card(&dir, "Short", "cli", NOT_SET); + + let mut board = one_board(&dir); + board.open_picker(); + + assert!(board.picker.is_none(), "an empty picker opened"); + let notice = board.notice.as_ref().expect("nothing was said"); + assert!(notice.text.contains("no campaigns"), "{:?}", notice.text); + assert!(notice.failed, "a key that did nothing read as a key that worked"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The rows carry the three things a campaign is chosen by, and the description is the + /// one of them that gives way, since it is the only one that is prose. + #[test] + fn the_picker_rows_name_the_id_the_codename_and_the_description() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.open_picker(); + + let rows = picker_rows(&board, 100, 24); + let row = rows + .iter() + .find(|row| row.contains(short_id(BEAVER))) + .expect("no row for the campaign"); + + assert!(row.contains("~beaver"), "{row:?}"); + assert!(row.contains("Move the store off one disk."), "{row:?}"); + // And the footer is the picker's while it is open, for the reason the prompt takes + // it: the board's key list describes nothing that currently works. + assert!(footer(&board, 100, 24).contains("enter view"), "the footer is the board's"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A campaign with no codename shows the id once, not twice: the row already opens + /// with it, so the card's fallback would say nothing the second time. + #[test] + fn a_picker_row_does_not_repeat_the_id_as_a_codename() { + let dir = board_dir(); + write_campaign(&dir, V1, "First public release", "", "For a public tag."); + write_member_card(&dir, "Short", "cli", V1); + + let mut board = one_board(&dir); + board.open_picker(); + + let rows = picker_rows(&board, 100, 24); + let row = rows + .iter() + .find(|row| row.contains(short_id(V1))) + .expect("no row for the campaign"); + + assert_eq!(row.matches(short_id(V1)).count(), 1, "the id is on the row twice: {row:?}"); + assert!(!row.contains(CAMPAIGN_MARK), "a mark with nothing after it: {row:?}"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A campaign filed elsewhere has to reach the board, and the digest is what decides + /// whether anything is re-read. Without the campaigns directory in it a new campaign + /// was invisible until some ticket happened to change. + #[test] + fn the_digest_moves_when_a_campaign_is_filed_or_edited() { + let dir = board_dir(); + write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "A ticket", ""); + + let mut board = one_board(&dir); + assert!(board.current().campaigns.is_empty()); + + write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); + assert!(board.tick().unwrap(), "the tick saw nothing"); + assert_eq!(board.current().campaigns.len(), 1, "the campaign never arrived"); + + // And an edit in place, which a directory's own mtime would miss. + write_campaign(&dir, V1, "First public release", "beaver", "For a public tag."); + assert!(board.tick().unwrap(), "an edited campaign moved nothing"); + assert_eq!(board.current().campaigns[0].codename.as_deref(), Some("beaver")); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// A selection whose campaign has left the board goes back to the whole board rather + /// than filtering it to nothing, which would read as a board that had lost its + /// tickets. + #[test] + fn a_campaign_that_leaves_the_board_returns_the_tab_to_it() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + board.select_campaign(Some(V1.to_string()), SCREEN); + + std::fs::remove_dir_all(dir.join(CAMPAIGNS_DIR)).unwrap(); + board.reload().unwrap(); + + assert_eq!(board.current().campaign, None, "the filter outlived its campaign"); + let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); + assert_eq!(all, 4, "the board stayed filtered to nothing"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The key is named where a reader has to find it, and left out where the frame's own + /// border says how to put a campaign away. + #[test] + fn the_footer_names_the_campaign_key_where_it_is_found() { + let dir = board_dir(); + let mut board = campaign_board(&dir); + + assert!(footer(&board, 120, 24).contains("c campaign"), "the key is unfindable"); + + board.select_campaign(Some(V1.to_string()), SCREEN); + let footer = footer(&board, 120, 24); + assert!(footer.contains("ctrl-c quit"), "q still claims to quit: {footer:?}"); + assert!(!footer.contains("q quit"), "{footer:?}"); + + std::fs::remove_dir_all(&dir).ok(); + } + + /// The filter belongs to the tab, not the board: a campaign is resolved inside one + /// `.worklane`, so one carried across would empty another project's tab and say + /// nothing about why. + #[test] + fn the_campaign_filter_belongs_to_the_tab() { + let one = board_dir(); + let two = board_dir(); + write_campaign(&one, V1, "First public release", "v1", "For a public tag."); + write_ticket( + &one, + "backlog", + "11111111-0000-4000-8000-000000000000", + "In v1", + &campaign_field(V1), + ); + write_ticket(&two, "backlog", "44444444-0000-4000-8000-000000000000", "Elsewhere", ""); + + let mut board = boards(&[("one", &one), ("two", &two)]); + // The merge tab lists every board's campaigns, each carrying the project it was + // filed in, since an id there does not say which board holds it. + assert_eq!(board.current().campaigns.len(), 1); + assert_eq!(board.current().campaigns[0].project.as_deref(), Some("one")); + + board.select_campaign(Some(V1.to_string()), SCREEN); + assert_eq!(board.current().campaign, Some(V1.to_string())); + + board.select_tab(1, SCREEN); + assert_eq!(board.current().campaign, None, "the filter followed the tab change"); + // And the tab it was set on kept it. + board.select_tab(-1, SCREEN); + assert_eq!(board.current().campaign, Some(V1.to_string())); + + std::fs::remove_dir_all(&one).ok(); + std::fs::remove_dir_all(&two).ok(); + } } diff --git a/src/util.rs b/src/util.rs index 4a750f1..4293935 100644 --- a/src/util.rs +++ b/src/util.rs @@ -389,14 +389,22 @@ fn status_paths(worklane_dir: &Path) -> Vec<(String, std::path::PathBuf)> { .collect() } -/// The three-tier search, run over `dirs`, returning the first tier that matched +/// The four-tier search, run over `dirs`, returning the first tier that matched /// anything. /// -/// Three tiers, filled in one pass and consulted in order. A uuid prefix has to win +/// Four 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. /// +/// **An exact codename wins over all three.** It is the one tier that is an exact match on +/// a field written for the purpose, so it cannot be a coincidence the way a substring can, +/// and a codename of `v1` is too short to be tried as an id at all. Only campaigns carry +/// the field, so for a ticket the tier is always empty and resolution is exactly what it +/// was. It lives here rather than in a campaign-only path for the reason the rest of this +/// function is shared: that would be a second copy of the precedence rules and a second +/// ambiguity message. +/// /// Shared by tickets and campaigns rather than written twice. A campaign is addressed /// exactly the way a ticket is, and a second resolver would be a second copy of the /// precedence rules to keep in step. Each entry pairs the name a match is reported @@ -405,6 +413,7 @@ pub fn resolve_in(search: &str, dirs: &[(String, std::path::PathBuf)]) -> Result let search_lower = search.to_lowercase(); let long_enough_for_an_id = search.chars().count() >= MIN_ID_SEARCH; + let mut by_codename: Vec = Vec::new(); let mut by_id: Vec = Vec::new(); let mut by_title: Vec = Vec::new(); let mut by_filename: Vec = Vec::new(); @@ -429,12 +438,17 @@ pub fn resolve_in(search: &str, dirs: &[(String, std::path::PathBuf)]) -> Result .unwrap_or_default(); let uuid = filename.split('_').next().unwrap_or(""); + // Case insensitive like the other three: a codename typed back off a listing + // has to resolve whatever case it was read in, which is the bargain the id + // tier already takes. + let is_codename = parse_codename(&content) + .is_some_and(|codename| codename.to_lowercase() == search_lower); 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) { + if !(is_codename || by_prefix || in_title || in_filename) { continue; } @@ -444,7 +458,9 @@ pub fn resolve_in(search: &str, dirs: &[(String, std::path::PathBuf)]) -> Result content, uuid: uuid.to_string(), }; - if by_prefix { + if is_codename { + by_codename.push(found); + } else if by_prefix { by_id.push(found); } else if in_title { by_title.push(found); @@ -454,10 +470,11 @@ pub fn resolve_in(search: &str, dirs: &[(String, std::path::PathBuf)]) -> Result } } - Ok(match (by_id.is_empty(), by_title.is_empty()) { - (false, _) => by_id, - (true, false) => by_title, - (true, true) => by_filename, + Ok(match (by_codename.is_empty(), by_id.is_empty(), by_title.is_empty()) { + (false, _, _) => by_codename, + (true, false, _) => by_id, + (true, true, false) => by_title, + (true, true, true) => by_filename, }) } @@ -846,6 +863,13 @@ fn metadata_value_cell(name: &str, value: &str, colored: bool, campaign: &str) - return paint(value, Color::Grey, colored); } + // The same word in the same colour as the label a card draws, since `tag_color` is a + // pure function of it. No mark here: the field name has already said what this is, + // and the mark is what tells a campaign from a tag on a row that holds both. + if name == CODENAME_FIELD { + return paint(value, tag_color(value), colored); + } + if name == "Tags" { return paint_tags(value, colored); } @@ -1133,6 +1157,66 @@ pub fn set_metadata_field(content: &str, field: &str, value: &str, title: &str) /// board. pub const CAMPAIGN_FIELD: &str = "Campaign"; +/// The metadata field naming a campaign in a word, beside the uuid that addresses it. +/// +/// A campaign is filed for a release or a migration, and those have names people already +/// use: `v1`, `beaver`. The uuid is what everything stores and the title is a sentence, so +/// neither is what a card has room to print. This is the short form, written by +/// `campaign add --codename` and nothing else. +/// +/// Optional, and a campaign without one is not a lesser campaign: every campaign filed +/// before this existed has no field at all, which reads as unset the way an absent +/// Campaign field does. +pub const CODENAME_FIELD: &str = "Codename"; + +/// The mark a campaign carries where it is drawn as a label. +/// +/// Not `#`, which is the tag marker: the two sit on the same row of a card and the row +/// would read as one list of tags with a stranger in it. A tilde is ASCII, so it renders +/// wherever `#` does, and it is not `@`, which reads as a person on every board anyone +/// has used. +/// +/// One glyph, so the campaign on a card and the campaign in the picker are the same +/// thing said the same way. +pub const CAMPAIGN_MARK: &str = "~"; + +/// The campaign codename a file names, or nothing when it names none. +/// +/// Absent, unset and empty are one answer, the bargain [`parse_campaign`] and +/// [`parse_tags`] both take: a campaign filed before the field existed carries no line at +/// all, and one whose line reads `_Not set_` has no codename either. +pub fn parse_codename(content: &str) -> Option { + let value = parse_ticket_field(content, CODENAME_FIELD); + + match is_unknown_value(&value) || value.trim().is_empty() { + true => None, + false => Some(value.trim().to_string()), + } +} + +/// A campaign as a label: the mark, then the codename, or the short id when it has none. +/// +/// The id is the fallback rather than the title, which is a sentence and would not fit the +/// row this is drawn on. It says little, which is the whole reason the codename field +/// exists, but it is addressable: `campaign show` takes it. +/// +/// **A codename takes its own colour from [`tag_color`] and the fallback takes grey.** The +/// colour is what groups a campaign across the cards that carry it, and one word is one +/// colour in every view for the same reason a tag is. Grey on the id, rather than the red +/// a uuid is drawn in everywhere else, keeps a reserved meaning off a `TAG_COLORS` slot in +/// the one case where the label is an id: grey already means what a reader skips, which is +/// what a campaign with no codename has to say for itself. +/// +/// A `Cell`, not a string, so the CLI paints it and the board makes a span of it, the way +/// a relation row already works. The bold is the board's: it is there to win a row against +/// the tags, and nothing in the CLI shares a line with them. +pub fn campaign_label(uuid: &str, codename: Option<&str>) -> Cell { + match codename { + Some(codename) => Cell::colored(format!("{CAMPAIGN_MARK}{codename}"), tag_color(codename)), + None => Cell::colored(format!("{CAMPAIGN_MARK}{}", short_id(uuid)), Color::Grey), + } +} + /// The campaign uuid a ticket names, or nothing when it names none. /// /// Absent and unset are the same answer: a ticket that has never been assigned has no @@ -1574,6 +1658,25 @@ fn section_body(lines: &[&str], heading: &str) -> Option> Some(after..section_end(lines, after)) } +/// The first line of a section's body, or nothing when the section is absent or holds +/// only its placeholder. +/// +/// For a view with one row to spend on prose: the board's campaign frame and its picker +/// both want the opening line of a description and have no room for the rest. Through +/// [`section_body`] rather than a scan of its own, so what counts as the section is +/// decided in one place, and the placeholder reads as nothing here the way it does to +/// `append`. +pub fn section_opening(content: &str, section: &Section) -> Option { + let lines: Vec<&str> = content.lines().collect(); + let body = section_body(&lines, section.heading)?; + + lines[body] + .iter() + .map(|line| line.trim()) + .find(|line| !line.is_empty() && *line != section.placeholder) + .map(|line| line.to_string()) +} + /// 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 { diff --git a/tests/cmd_campaign.rs b/tests/cmd_campaign.rs index bf197d0..ff0ac48 100644 --- a/tests/cmd_campaign.rs +++ b/tests/cmd_campaign.rs @@ -642,3 +642,217 @@ fn an_ambiguous_campaign_lists_the_candidates() { assert!(message.contains("v1 release"), "{message}"); assert!(message.contains("v2 release"), "{message}"); } + +// ------------------------------------------------------------------ codenames -- + +/// The codename is what the board draws on every card in a campaign, since a uuid does +/// not fit there and a title is a sentence. +#[test] +fn campaign_add_writes_the_codename_under_the_id() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + + let out = run( + &temp, + &[ + "campaign", + "add", + "--title", + "First public release", + "--codename", + "v1", + ], + ); + assert!(out.status.success(), "{}", stderr(&out)); + + let name = campaigns(&worklane).remove(0); + let content = fs::read_to_string(worklane.join("campaigns").join(name)).unwrap(); + + assert!(content.contains("- **Codename**: v1"), "{content}"); + // Under the ID, because that is what it is: a second way to say which campaign this + // is, in a word rather than in thirty-six characters. + let id = content.find("- **ID**:").expect("no id"); + let codename = content.find("- **Codename**:").expect("no codename"); + let owner = content.find("- **Owner**:").expect("no owner"); + assert!(id < codename && codename < owner, "{content}"); +} + +/// A campaign filed without one carries the line unset rather than not at all, the way +/// `add` writes an unset Due on every ticket: one shape of file is one thing for the +/// parser to be right about, and the line is there to fill in by hand. +#[test] +fn a_campaign_filed_without_a_codename_carries_the_field_unset() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + + run(&temp, &["campaign", "add", "--title", "No codename here"]); + + let name = campaigns(&worklane).remove(0); + let content = fs::read_to_string(worklane.join("campaigns").join(name)).unwrap(); + + assert!(content.contains("- **Codename**: _Not set_"), "{content}"); +} + +/// One word, checked at parse time like `--due` and `--priority`, because the board draws +/// it as a label with a mark and no quoting: `~beaver release` on that row reads as two +/// labels and the second one is not a campaign. +#[test] +fn a_codename_of_more_than_one_word_is_a_usage_error() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + + let out = run( + &temp, + &[ + "campaign", + "add", + "--title", + "v1 release", + "--codename", + "beaver release", + ], + ); + + assert_eq!(out.status.code(), Some(2), "{}", stderr(&out)); + assert!(stderr(&out).contains("single word"), "{}", stderr(&out)); + assert!(campaigns(&worklane).is_empty(), "a campaign was filed anyway"); +} + +#[test] +fn an_empty_codename_is_a_usage_error() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + + let out = run(&temp, &["campaign", "add", "--title", "v1 release", "--codename", ""]); + + assert_eq!(out.status.code(), Some(2), "{}", stderr(&out)); + assert!(campaigns(&worklane).is_empty(), "a campaign was filed anyway"); +} + +/// The listing is where the codename is read back, so it goes between the id and the +/// title with the mark the board draws it with: one word for one campaign, spelled the +/// same wherever it is shown. +#[test] +fn campaign_ls_names_the_codename_between_the_id_and_the_title() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + create_campaign(&worklane, "No codename here", CAMP_B); + + run( + &temp, + &[ + "campaign", + "add", + "--title", + "First public release", + "-c", + "v1", + ], + ); + + let out = run(&temp, &["campaign", "ls"]); + let listing = stdout(&out); + + assert!(listing.contains("~v1 First public release"), "{listing}"); + // And a campaign without one spends nothing on it, the way an untagged card spends no + // row. + assert!(listing.contains(") No codename here"), "{listing}"); + assert!(!listing.contains("~No codename"), "{listing}"); + let _ = worklane; +} + +/// `campaign show` renders its metadata as a table, so the field is there to read without +/// anything being written twice. +#[test] +fn campaign_show_renders_the_codename_in_its_metadata() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + + run( + &temp, + &[ + "campaign", + "add", + "--title", + "First public release", + "-c", + "v1", + ], + ); + + let out = run(&temp, &["campaign", "show", "First public"]); + assert!(stdout(&out).contains("Codename"), "{}", stdout(&out)); + assert!(stdout(&out).contains("v1"), "{}", stdout(&out)); + let _ = worklane; +} + +/// A codename nobody can type is half a field, so it resolves a campaign the way its +/// uuid and its title do. Exact, and ahead of all three: it is a match on a field written +/// for the purpose rather than a substring that could be a coincidence. +#[test] +fn a_campaign_resolves_by_its_codename() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + // Same file, plus a codename, since `create_campaign` writes none. + let path = worklane + .join("campaigns") + .join(format!("{}_{}.md", CAMP_A, slug("v1 release"))); + let content = fs::read_to_string(&path).unwrap(); + fs::write( + &path, + content.replace("- **Owner**:", "- **Codename**: beaver\n- **Owner**:"), + ) + .unwrap(); + + let out = run(&temp, &["assign", "beaver", MEMBER]); + assert!(out.status.success(), "{}", stderr(&out)); + assert!( + ticket(&worklane, MEMBER).contains(&format!("- **Campaign**: {CAMP_A}")), + "{}", + ticket(&worklane, MEMBER) + ); + + // And every other command that takes a campaign, since they share one resolver. + let out = run(&temp, &["campaign", "show", "beaver"]); + assert!(stdout(&out).contains("v1 release"), "{}", stdout(&out)); + + let out = run(&temp, &["ls", "--campaign", "beaver"]); + assert!(stdout(&out).contains("The member"), "{}", stdout(&out)); +} + +/// An exact codename beats a title that merely contains the search, which is the whole +/// reason it is a tier of its own: `v2` is a substring of `v2 release` and the exact +/// match has to win outright rather than be reported as ambiguous against it. +#[test] +fn an_exact_codename_beats_a_title_that_contains_the_search() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + let path = worklane + .join("campaigns") + .join(format!("{}_{}.md", CAMP_A, slug("v1 release"))); + let content = fs::read_to_string(&path).unwrap(); + fs::write(&path, content.replace("- **Owner**:", "- **Codename**: v2\n- **Owner**:")).unwrap(); + + let out = run(&temp, &["assign", "v2", MEMBER]); + assert!(out.status.success(), "{}", stderr(&out)); + assert!( + ticket(&worklane, MEMBER).contains(&format!("- **Campaign**: {CAMP_A}")), + "the title tier won: {}", + ticket(&worklane, MEMBER) + ); +} + +/// A ticket carries no codename, so the tier is empty for one and ticket resolution is +/// exactly what it was. Pinned because the tier lives in the shared resolver: this is the +/// half of it that must not have changed. +#[test] +fn a_ticket_search_is_unaffected_by_the_codename_tier() { + let temp = TempDir::new().unwrap(); + let worklane = board(&temp); + + // The uuid prefix still wins over a title that quotes it, which is the precedence the + // three tiers were written for. + let out = run(&temp, &["show", "641e3d5"]); + assert!(stdout(&out).contains("The member"), "{}", stdout(&out)); + let _ = worklane; +}