Compare commits

...
41 Commits
Author SHA1 Message Date
Ansho Rei 07ac204829 Ignore sandbox device mounts in the release dirty-tree check, and bump to 0.33.11
An agent sandbox bind-mounts /dev/null over protected paths such as
.bashrc and files inside .claude/, so make patch refused a tree that
was clean outside the sandbox. Untracked character devices cannot be
committed, so the check skips them and lists only what blocks the
release. Untracked files are listed one by one rather than with
--directory, since the collapsed .claude/ entry is not a device.
2026-11-06 18:45:38 +01:00
Ansho Rei 19c666b5dc Close a review of landed work by filing its remaining issues as tickets, and bump to 0.33.10
Work already on the default branch cannot go back to committed without
reopening shipped code. The reviewer files each remaining issue as a new
ticket, related issues together, comments why the ticket is closing, and
moves it to done.
2026-11-06 18:43:07 +01:00
Ansho Rei 8e7a3f1425 Fix tags in tui on narrow screen, and bump to 0.33.9 2026-11-06 17:45:49 +01:00
Ansho ReiandClaude Opus 5 fbd752afc9 (8a7fe6c) Read a flag by either spelling, on the prompt and in the fish rules, and bump to 0.33.8
`:mv --status ` offered the five statuses on the board and `:mv -s `
offered nothing: argument_at read the typed word with strip_prefix("--"),
so a word spelled with one hyphen was not a flag to it and fell through to
the positional arm, which counted a position that was not there.

long_name translates the letter through the command that holds the flag, so
the tables stay keyed on the long name and nothing here keeps a second list
of every option's letter. One letter, never a cluster: `mv -fs done` would
make the last letter the honest answer, but --title, --acceptance and a
comment body all take a leading hyphen on purpose, and a criterion typed as
`-fixes the offset` must not be answered with statuses.

The fish half had the same hole in its dynamic rules alone, which were
written as `-l <flag>`: `append -g <TAB>` offered nothing where
`append --tags <TAB>` offered the board's tags. fish_option reads the letter
off the definition per command, so an option given one tomorrow is offered
under it the day it is given. Clap's own generated rules already carried
both spellings, which is why a shell answered `mv -s ` and the board did
not.

a_short_flag_answers_what_its_long_spelling_answers walks every option with
both spellings on every command and nested command and pins that the two
answer the same, so this cannot come back one flag at a time.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 17:00:35 +02:00
Ansho ReiandClaude Opus 5 298e00eb33 (d7e493e) Draw the command's own usage line while the prompt is open, and bump to 0.33.7
The reader knows the grammar approximately: that mv takes a status, not
whether it is a positional or --status, and that set has a flag per section,
not whether the criteria one is --acceptance or --criteria. In a shell fish
answers that as the line is typed. On the board there was nothing, and
getting it wrong cost a rejected line and a guess.

usage_of walks the typed verb against the clap definition and renders its
usage, so a flag added to a command is described here the day it is added.
A table of synopses kept beside it would be a second grammar, and it would
go stale silently: nothing but a reader typing that verb would ever see the
two disagree. The Usage: label is dropped, being the name of a block in a
help page of several where this is one line beside the line it describes.

It takes the keys' slot. esc and enter are two keys a reader learns once,
against a synopsis that is different for every verb; a refusal still wins
over both while it is up, being what was just said about the line that is
still on the row. refusal is the half that says what is wrong where this
says what would have been right.

A verb that resolves to nothing draws nothing and complains about nothing,
since the line is half typed most of the time the row is looked at. A
group's child is walked when the second word names one, so campaign set
describes set; while that word is half typed the group's own usage stands.

Grey, and cut with an ellipsis rather than wrapped: the footer is one row
and a second would reflow the columns every time a verb resolved. There is
always at least the keys' width to cut into, because that width comes off
the row before the line is windowed, so the usage never takes a cell from
what is being typed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 16:51:08 +02:00
Ansho ReiandClaude Opus 5 634a1f44c4 (07ac4e1) Filter campaign ls by state, and lay its listing out as a table, and bump to 0.33.6
campaign ls printed every campaign and offered no way to narrow it, and the
row was assembled by hand, so a long title pushed the standing out of line
with the row above it and the created date the file already carries was not
shown at all.

--state takes open, done or empty and matches against Standing::state(),
so the derived value keeps one definition: a campaign reads [open] in the
listing if and only if --state open lists it. --state rather than --status,
which names one of the five ticket statuses everywhere else and would
invite --state backlog here. empty is the third value because an empty
campaign derives None deliberately, and a filter that could not reach those
would leave what has been filed and forgotten answerable only by reading
the whole listing. A filter that matches nothing names the value back,
since a silent listing reads as the other empty case.

The filter reaches --ids as well, the way ls --ids keeps its own, and is
the only thing that makes that path count members: an unfiltered completion
is as cheap as it was.

The columns are measured on the raw values and padded before anything is
painted, the rule metadata_cells follows. The codename is measured with the
title rather than given a column of its own: a campaign filed without one
spends nothing on it, so a column for it would be one most rows pad into
and some leave empty, and what a reader lines up is where a name ends and
its progress begins.

A flag's possible values now come off the command that holds the flag, so
campaign ls --state reaches ls's own arguments rather than campaign's. The
prompt offered nothing there while fish offered the three values, which
made a liar of the rule that a ValueEnum added anywhere is typeable on the
board the day it is added.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 16:42:21 +02:00
Ansho ReiandClaude Opus 5 3e732535f8 (bc86c85) Attribute a command typed at the board to the person, not the variable, and bump to 0.33.5
WORKLANE_ACTOR is set once in the environment an agent runs in, which is
right for an agent and wrong for the board: a person who exports it where
their own shell picks it up, the obvious way to configure it for the agents
on that machine, then moved a ticket with ':' and the board recorded the
move as the agent's.

Nothing but the reader can type that line, so the prompt asks for
--actor-from-git's precedence without the flag. An explicit --actor still
wins, which is how the reader puts somebody else's name on their own
keystrokes, and a machine with no git user configured reads unknown rather
than falling back to the variable, for the reason the flag does.

The attribution is a parameter of dispatch rather than a field the prompt
writes into what clap parsed: rewriting the arguments would need an arm per
entry-writing command, and the command added after it would be attributed
to the agent until somebody noticed. no_handler_decides_its_own_attribution
reads src for a handler naming an Attribution of its own, which the
compiler cannot catch because it compiles.

The same command typed in a shell is unchanged, which is what keeps a board
several agents write to saying which of them wrote what.

Also closes a code fence in the skill that e26e589 left open, duplicating
the mv --actor example under it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 16:23:24 +02:00
Ansho ReiandClaude Opus 5 a885f81da5 (952a9f8) Complete the verb, the statuses, the tags and the campaigns in the prompt, and bump to 0.33.4
With the ticket suggested, the rest of the line was still typed blind. The
prompt now completes everything fish does: the verb and the verbs of a
group, the five statuses, the tags the board carries, the campaigns a
codename resolves against, and relate --clear's three kinds.

`ticket_argument` becomes `argument_at`, which answers what a position
names rather than whether it is a ticket. The tables say Ticket, Campaign
or Tag; clap says the rest, so the verbs, the statuses, `set --clear`'s
fields and the `completions` shells are never written down twice. Only
`relate --clear` needed a table of its own: the flag takes a kind and then
a target, so possible values on it would refuse every target.

The row draws the longest opening every candidate agrees on, which is
exactly what the next tab takes. One rule for one candidate and for many: a
ticket position has only the selected card, so the rest of its id is drawn
as before; the five statuses agree on nothing, so nothing is drawn and tab
steps through them one press at a time.

The walk holds the line as it stood before the first press, not the list
and not the candidate the last press chose, so every press re-derives the
candidates and stepping cannot narrow them to what it just typed. Every
edit ends it, beside `refused` and for the same reason.

193f9be is not inherited: `tags set` is offered only the tags the
vocabulary declares, and `tags add` and both `--tags` that take the whole
list are offered nothing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 15:18:59 +02:00
Ansho ReiandClaude Opus 5 c714c73a75 (00a14e7) Suggest the selected ticket where a ticket argument goes, and accept it with tab, and bump to 0.33.3
The reader has the ticket selected, which is the whole reason to type a
command on the board rather than in a shell, so where the line is naming a
ticket the selected card's short id is drawn after the cursor in grey and
tab takes it into the line.

Where a ticket goes is completions.rs's answer, through a new
`ticket_argument` over the three tables the fish half is generated from. A
copy of the positions on the board would go wrong the next time a command
grew a ticket argument, and silently, since the tests guarding the first
copy would not read the second.

TICKET_FLAGS holds (command, flag) pairs now, the shape TAG_FLAGS already
had, and the `chown --clear` rule the fish block wrote out by hand is
generated from it. Only chown's --clear names a ticket: relate's takes a
kind and set's a field, and the flag alone cannot tell the three apart.

The suggestion is derived on every call rather than held on the Prompt, so
what the row draws and what tab takes are one answer, and it is offered
only with the cursor at the end of the line, while a card is selected, and
while the id still starts with what is typed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 15:01:15 +02:00
Ansho ReiandClaude Opus 5 a017f9002e (c680e24) Write a warning through a second stream on the sink, and bump to 0.33.2
check_blockers reported a blocker the board does not hold with eprintln!,
the one print site fa5662a left behind: a helper had no sink to reach, and
what it wrote was stderr rather than stdout. Harmless while main was the
only caller, and since 53ffb94 the command prompt runs the same handlers,
where stderr is the alternate screen with the columns on it. ratatui does
not repaint a cell it believes is unchanged, so the fragment stayed until
something else redrew them.

Sink carries two writers instead of one, because the CLI's two streams are
two: Sink::std hands the answer to stdout and an aside to stderr, so a
shell reads the same line on the same stream, and the integration test now
asserts that stderr whole rather than searching it. Sink::buffer holds its
warnings instead, and Board::run reads them back with Sink::warnings and
puts them above the answer on both outcomes -- a mv that warns about a
dangling blocker and is then refused by a real one wrote the aside first,
and it says why the refusal names one blocker and the ticket records two.

check_blockers and check_dependents both take the sink now, so their
refusals take the colour from it as well, rather than asking the process
about a stdout the board is not writing to.

no_handler_or_helper_reaches_a_print_macro walks src for the next print
site, each file cut at its own test module, since the rule is about every
future site rather than the one that broke.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 11:53:10 +02:00
Ansho ReiandClaude Opus 5 ead3c4340d (2c95d38) Gate a blocker by the column it is in, not by whether it is done, and bump to 0.33.1
check_blockers refused every move while a blocked by target was still open, so a
dependent sat in backlog until its blocker landed even when the blocker was in
reviewing and its code was there to build on. The way out was -f, which also waives
the backward and skipping guard, on every move for as long as the pair existed.

The rule is now the columns: a ticket may stand level with what it waits on but never
ahead of it, so a blocker in reviewing lets the dependent be committed and reviewed
and gates only done. util::blocks_move is the one place it is decided, taking the
status moved into and the blocker's own, and mv passes the target through. A finished
blocker still holds up nothing, answered through is_open, and a target of discarded
is answered by name rather than by its place in Status::ALL, where it sits last.

The refusal now names the status moved into and only the blockers still behind it: a
dependent told to wait for work already ahead of it has nothing to act on. The board
asks the same function about the column one stage ahead, so the blocked mark means the
card cannot advance rather than that a dependency was ever recorded, which also takes
it off cards in the two terminal columns.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 11:38:17 +02:00
Ansho Rei 9c224fb768 Move AGENTS.md sections into docs folder 2026-09-04 14:10:50 +02:00
Ansho Rei f877e6dbf2 (c6a61b4) Resolve a board through a pointer file and a shared boards repo, and bump to 0.33.0 2026-09-01 17:41:05 +02:00
Ansho Rei 3892afe819 (2e05015) Show the campaign standing on its picker row, and bump to 0.32.21 2026-09-01 13:42:51 +02:00
Ansho ReiandClaude Opus 5 c81838efc6 Sort the backlog by due date, then priority
The backlog was the one column priority governed alone, which sat a p1
nobody had promised above a p3 due tomorrow. It has no entry stamp, so it
now takes the due date as the date `by_status_order` keys on: soonest
first, undated below every dated one, and priority then title as the
tiebreak, which is still the whole order among the undated ones.

`TicketItem::due_key` is where a due becomes an orderable date. Only a
plain `YYYY-MM-DD` counts, which is all `--due` has accepted since
daa0e79, with `due_date` cutting a legacy datetime back to its date.
Free text answers `None` and sinks with the unset ones rather than
sorting on its spelling: a due nobody can place on a calendar is
unknown, the same reading a missing stamp already gets.

The comparator stays the single function keyed on `Status`, so `ls`,
`ls --ids`, the board's columns and `campaign::members` move together.
The All tab keeps `by_priority_then_title`: that merge spans statuses,
so no single date governs it.

`ls_listed_tickets_sorted_alphabetically` gave its three tickets three
different due dates while asserting title order. They share one now, so
the case still tests the tiebreak it names rather than the new order.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 01:10:41 +02:00
Ansho ReiandClaude Opus 5 cd7c99fe39 (d5a8a3f) Add make check, one command for fmt, clippy and the suite, and bump to 0.32.20
AGENTS.md pins `cargo fmt --check` and `cargo clippy --all-targets` as
clean, and 83d31cd is what happens when only memory enforces that: fmt
drifted to about 160 places across every file with the tool installed and
configured by default the whole time.

The decision the ticket wanted, taken: mechanise it, as one command. Not
CI, which a single-author tool with no pipeline anywhere does not want,
and not a hook, which is a per-clone opt-in the way `blame.ignoreRevsFile`
is and so cannot be relied on either. What was missing was never a
mechanism, it was one name to type: "remember to run fmt, clippy and the
tests" becomes `make check`.

Cheapest first, so a formatting slip is reported in a second rather than
after the suite. `-D warnings` is what turns clippy's opinion into an exit
code, since a warning printed into a wall of cargo output is unread rather
than clean. Verified each gate fails on its own: a misformatted function
and a `&Vec<u8>` parameter each exit 2 before the tests run.

Completions are inside `cargo test` rather than a target of their own.
d93eca6 put the check that loads the generated script into a real fish
there, so "check tests, check completions" is already one command, and a
second target would be a second thing to remember, which is the problem
this is solving.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 23:56:44 +02:00
Ansho ReiandClaude Opus 5 b63b60eefc (4dea61c) Load the completion script into fish and ask it what it offers, and bump to 0.32.19
Every check over the completions read the script as text. A `contains`
cannot tell a rule that fires from one whose condition stopped matching,
and that is how a completion actually breaks: the clap definition moves,
a list or a `__worklane_command_is` scope stops naming anything, and the
rule sits in the file offering nothing while every assertion passes.

So the generated script is sourced into a throwaway fish standing in a
real board, with this build's directory on the front of PATH, and
`complete -C` is compared against the ticket and the tag that board was
given. Four deliberate breakages were used to size it: renaming the `ls`
status scope, dropping `append` from `TAG_FLAGS`, renaming a flag in
`TICKET_FLAGS` and dropping `show` from `TICKET_COMMANDS`. All four now
fail, each naming the list at fault.

**Assert the values, not the flag names.** clap emits every option's name
on its own, so `--tags` and `--blocked-by` are offered with the whole
dynamic half deleted; the first draft asserted those names and caught
only one of the four. What the hand-written rules add is the candidates
after the flag, and that is what a board under the shell makes checkable.

Two traps, both paid for once. `complete -C` autoloads
`~/.config/fish/completions/worklane.fish`, so the first draft passed
against a deliberately broken scope because the copy installed in August
still had the working rule: `set fish_complete_path` with no value is
what makes the sourced script the only source, and without that line the
test cannot fail. And the script is written beside the board rather than
in it, since a rule that fires nothing falls back to listing the
directory and the script would read as an answer.

`fish --no-execute` comes with it as the floor: it catches a script that
does not parse. Narrower than it sounds, and measured rather than
assumed, so the limit is written on the test. An apostrophe in a `-d`
description partway down re-balances against the next quote and parses,
corrupting every rule in between; the same apostrophe in the last rule
reaches the end unbalanced and is caught.

`every_listed_command_is_a_real_subcommand` widens to every list that
names a command, `CAMPAIGN_COMMANDS`, `TAG_FLAGS` and the two nested
lists, so a stale entry fails by name instead of through a rule count.
The counts themselves stay hardcoded and now say why: the walkers go
clap → list and never see an extra entry, so the count is what catches
one, and deriving it from the lists it checks would grow with the bogus
entry and pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 23:54:48 +02:00
Ansho ReiandClaude Opus 5 7470255a22 (a1a5d69) Add tags to a ticket with append --tags, keeping the ones it carries, and bump to 0.32.18
`set --tags` writes the whole field, so adding one tag to a ticket that
already carries some meant reading it first and retyping every one of
them. 30a2b34 wrote that down in the skill as the way to do it; this is
the flag that makes it unnecessary.

The merge is idempotent and ordered. A tag the ticket already carries is
reported as no change rather than added twice, which is the point of the
flag: the caller does not have to know what is there. A new one goes on
the end in the order it was given rather than sorting the field under
whoever last touched it. Values are split on commas the way the stored
field is, so `--tags "bug, tui"` names two tags and matches the two a
ticket carrying them already holds; without that the pair would land as
a single tag nothing can filter by and would not match itself on the
next call. `split_tags` is that rule, lifted out of `parse_tags` so the
argument and the field are separated by the same code.

It writes the same `Kind::Tags` entry `set --tags` writes, so `--actor`
and `--actor-from-git` come with it. Tags are logged wherever they move,
and the one command that adds to them without replacing them would
otherwise be the one tag change the log missed. The before and after are
read off the field rather than off the flag, so an append of `beta` onto
`alpha` reads as the pair and not as what the call asked for.

`non_empty` rather than the `clearable` that `set --tags` takes: that
message names `--clear`, and `append` has none, so it would send the
caller looking here for a flag that is `set`'s. A value that is only
separators reaches the handler and is refused there, in the words
`appended_items` refuses an all-blank section with. Emptying the field
stays `set --clear tags`.

`TAG_FLAGS` becomes pairs of command and flag, because `ls --tag` and
`append --tags` are spelled differently and one rule naming both options
would tell fish that each command accepts the other's. `add --tags` and
`set --tags` deliberately get no value rule and are recorded in the
test's `TAG_LIST_FLAGS` instead: they take the whole list, so the token
at the cursor is `bug,tui` and fish replaces a token entire, throwing
away what is already typed. The honesty test now walks `tag` and `tags`
both, so the next tag argument has to say which of the two it is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 23:37:33 +02:00
Ansho ReiandClaude Opus 5 b4534eb86d (a9bd6f0) Recall typed lines with up and down, kept in .wlhistory, and bump to 0.32.17
The lines typed at the command prompt are walked with up and down and kept
in .wlhistory in the board's own folder, so a recall spans runs rather than
one opening of the prompt.

One Recall per tab, parallel to Board::tabs, so the tab in view decides
which list up walks: a project's lines are the ones naming its ticket ids.
The merge tab is no board, so it keeps its lines for the run and writes no
file, the answer current_project already gives a command typed there.

The position sits on Prompt and the lines on Recall, so closing the prompt
forgets the position and not the lines. A failed write is silent and an
unreadable file is an empty recall: the line is in memory either way.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-28 12:40:21 +02:00
Ansho Rei 96cddc14ad (53ffb94) Run the command the prompt parsed, and redraw the board on what it wrote, and bump to 0.32.16
The prompt parsed a line and named what it resolved to. This is the half
that does it: the parsed command goes to the same cmd_* handler main.rs
hands it to, against the selected tab's own .worklane, with a Sink over a
buffer collecting what the handler says instead of stdout.

One dispatch table, not two. main.rs's match on Command is lifted into
`dispatch`, over the command, the start path and the sink, and both
callers go through it. A second copy in tui.rs would drift the first time
a command was added and would drift silently, since both halves go on
compiling; the match is exhaustive so a new verb cannot fall into an `_`
arm either. Only `tui` is matched outside it, in main, because the board
is that table's caller rather than an entry in it, and reached from the
prompt it is refused in those words.

Two things the board has to do that the CLI never had to. It reloads
unconditionally after a command returns rather than waiting for the
digest, so a reader does not watch their own mv take up to a poll
interval to appear, and either way, since a handler that failed part way
through has still written. And the selection is restored by uuid across
that reload: mv puts the card in another column, set --title renames its
file, and a filter can drop it out of view, so the slot is not the
ticket. Where the board cannot follow it, the notice says so and which
key shows it.

What the handler says is what the board reports, word for word. Notice
therefore holds as many lines as the command used, and notice_on_row is
the one rule for where they go: one line on the footer row where a copy's
notice has always gone, anything else as a box at the foot of the
columns. A box rather than more rows of footer, because a footer that
grew and shrank as notices came and went would reflow the columns on
every keypress. A handler that errors leaves the prompt open with the
line intact, the usual cause being an ambiguous id.

`without_escapes` in util.rs is the guard at the seam. A handler's own
output is plain because the sink is, but an error message is built with
color_text, which asks the process about its stdout and under the board
answers yes about a terminal the message is not going to; a ratatui
paragraph prints an escape rather than obeying it. That is 6d327df's
fault on a new path.

The merge tab is refused for now, resolved by index rather than by the
tab's name, which is a label two projects can share. Routing by the card
a command names is ebc5755.

Not done here, and both tracked: check with no criterion still reaches
ask_which_criterion and reads a raw-mode stdin, which is 6d37042's
criterion 4 and commented there; and check_blockers warns about a
dangling blocker with eprintln!, which reaches the alternate screen
because it never passes through dispatch's result, filed as c680e24.
2026-08-27 23:38:02 +02:00
Ansho ReiandClaude Opus 5 f16e2aba0c (3686dd6) Open a command prompt on the board with : and parse what is typed, and bump to 0.32.15
The board reads. Changing anything meant quitting it and retyping an id
that was already selected. So `:` opens a one line editor in the footer
and the line is a worklane command, spelled exactly as the shell spells
it.

This is the mode and the grammar check, not the doing. Enter tokenises
the line with split_line, prepends the binary's own name and hands the
arguments to the same Cli definition the shell reaches, so a flag added
to a command is typeable here the day it is added and no list of verbs
lives on the board to go stale. A line that resolves is named and the
prompt closes; a line that does not keeps the prompt open with the line
intact and clap's own message, cut back to what fits a row. Running it
is 53ffb94, and the notice and the `↵ check` key both say so rather than
reading like a move that happened.

The prompt owns the keyboard while it is open, the contract search_key
and picker_key already keep, and declines ctrl-c for the same reason
they do. A line that ends inside a quote never reaches clap, which is
what the splitter's Unclosed state is for. --help is caught, or clap's
page lands on the alternate screen the way an unsunk println! would.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 21:07:26 +02:00
Ansho ReiandClaude Opus 5 bf7d8e05d8 (54fde0b) Split a typed command line into arguments the way a shell does, and bump to 0.32.14
The command prompt reads one string and clap reads an argv, so a line has
to be tokenised before anything can parse it: `comment 1b78a24 the offset
was never passed` split on whitespace is five arguments and `comment`
takes two.

One pure function over the line and the cursor, in a module of its own
rather than in tui.rs. The rules are the shell's, because that is what
the prompt promises. Two answers a shell's own splitter does not owe
anybody come out of the same scan: what a half-typed line is still
inside, as a state to report rather than an error to raise, and which
argument the cursor is in with whether it begins one.

Nothing calls it yet. The prompt that will is 3686dd6, and the dead_code
allow on the module goes when it lands.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-27 20:13:01 +02:00
Ansho Rei 30a2b3429e Specify in skill that set overwrites and to use append when that is not desired 2026-08-27 14:11:59 +02:00
Ansho Rei 69bc2feef5 (fa5662a) Write handler output through a caller-supplied sink, and bump to 0.32.13 2026-08-27 08:13:32 +02:00
Ansho Rei 8675f22209 (21713c5) Follow the picker highlight in the draw, not only on the keypress, and bump to 0.32.12 2026-08-26 12:51:21 +02:00
Ansho Rei f183d4635a (e61619a) Stage a new ticket through write_then_replace like every other write, and bump to 0.32.11 2026-08-26 12:39:08 +02:00
Ansho Rei 668263605c (8a2abf1) Give the wrapper tools for relate, campaign, assign and tags, and bump to 0.32.10 2026-08-26 12:32:15 +02:00
Ansho Rei d0a8f9a284 (10a07b8) Filter the board to the tickets in no campaign, from the campaign picker, and bump to 0.32.9 2026-08-26 02:07:16 +02:00
Ansho Rei c3efebe9b3 (86c6d27) Say the statuses, not four, where completions.rs describes what clap emits 2026-08-26 01:17:36 +02:00
Ansho Rei e26e5893f7 (ca2a124) Add --actor-from-git beside every --actor, and bump to 0.32.8 2026-08-25 17:12:25 +02:00
Ansho Rei bfce4cf2f4 (5a46b59) Say campaign where a campaign write fails, and bump to 0.32.7 2026-08-25 16:14:15 +02:00
Ansho Rei b439ad9c41 (7f772a7) Repair a Status field that lags its directory on mv, and bump to 0.32.6 2026-08-25 16:14:05 +02:00
Ansho Rei 455f04d136 (3ca1d0c) Record the tag picker's design in the Board View section 2026-08-25 16:13:38 +02:00
Ansho Rei cac21a94f5 (8f650fc) Refuse a tab in a tag annotation, and bump to 0.32.5 2026-08-25 15:26:08 +02:00
Ansho Rei 8c599440e5 (8020e48) Quote a comment behind a gutter bar that survives wrapping, and bump to 0.32.4 2026-08-25 15:19:01 +02:00
Ansho Rei a92dbf552f Teach the skill to assume WORKLANE_ACTOR and reserve --actor for another's action 2026-08-25 13:57:36 +02:00
Ansho Rei b93b8e1b81 (d447e04) Render each comment behind a grey bar spanning its length, and bump to 0.32.3 2026-08-25 13:56:55 +02:00
Ansho ReiandClaude Opus 5 f0f88025f3 (938a887) Colour the footer's keys and merge them into their words, and bump to 0.32.2
Every key hint on the board was one flat grey string, `←→ column   ↑↓ card
/ search   y copy id   enter detail   d show done (3)   q quit`, so nothing
separated a key from what it does and a reader looking for one read the row word
by word. frig and pantop both colour the key, and the three are read side by
side.

`key_hint` is the only thing that draws a hint now: the key cyan and bold, the
description in the terminal's default foreground, one span each. The three
footer states, the prompt's two keys, the picker's row and the `q board` on the
frame's border all go through it, so the shape is learnt once and cannot drift
between rows. Cyan here and magenta in pantop is the rule and not an
inconsistency: one accent per tool, the one that tool already uses.

**A key that is its description's first letter is merged into it.** `q quit` is
drawn `quit` with the `q` coloured, `c campaign` is `campaign`, `t tag` is
`tag`. `y copy id`, `ctrl-c quit`, `d show done (2)` and every arrow row stay
split, so the row carries both forms at once, which is what the two cells are
worth on a row already at its width naming eight keys. The prefix test is case
sensitive, and that is not fussiness: a row naming both `r` and `R` would draw
one word for the two of them, and the merged form can only say which key it is
while the letter it colours is that key. frig has such a pair and needs it.

`enter` is written `↵` everywhere it is named, which is the other two cells.

The rows are lists of `(key, description)` pairs rather than format strings, so
the tab slot, the two filter keys and the `d` slot come and go by pushing a pair
or not. They were fragments carrying their own trailing spaces, spliced into
three format strings that had to agree about the spacing between them.

The frame's border hint is measured over its spans instead of one string, since
it is three of them now. It still drops the indicator first and then itself,
whole either way.

The grey was argued for in comments, and the argument is reversed rather than
deleted: the row is still chrome, but a key nobody can pick out of it is chrome
that has to be read word by word to be used. What that costs is on the prompt,
where the query now sits in the same foreground as the descriptions beside it.
The cursor is what says which half is an input, and it does that in a terminal
with no colour at all.

**The footer tests read cells, not text.** Three of the guards that keep
1b78a24 out were `!contains("q quit")`, and once `q quit` is spelled `quit`
every one of them passes whatever the row says, because the split `ctrl-c quit`
contains the merged form. `keys_on` answers with how many cells the word opens
with in the key colour: `Some(1)` is `q` quitting, `Some(0)` is the word sitting
in the tail of `ctrl-c quit`, and `None` is a key the row does not name at all.
`!contains("enter detail")` on the frame row would have joined them the moment
the spelling changed, and is now `↵ detail`.

AGENTS.md carries the rule, the merge and the case sensitivity, and the palette
gains the one colour it spends on something that is not a value.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 13:11:31 +02:00
Ansho ReiandClaude Opus 5 00a64adca8 (03bdc76) Draw a symmetric relation once, and refuse the mirror, and bump to 0.32.1
`relate` refused a relation the ticket already held but never looked at what
the target held, so both ends of a `relates to` could store a line. `show` then
drew the same neighbour twice under the same label, since `RelatesTo` maps to
itself in `inverse_label`: one row from the stored line and one derived from the
far ticket's mirror of it, indistinguishable. Live on this board, where 8556048
and 8c8a520 each stored the other.

Both ends of the fix, because they do different jobs. `relation_rows` drops a
derived row that reads exactly like a stored one, which repairs the boards that
already hold both directions without an edit. `cmd_relate` refuses to store the
mirror in the first place, reporting no change since the edge is already
recorded at the far end, which stops it recurring. Neither alone closes it.

The dedupe keys on the **label** and the target, not the kind and the target.
Two tickets each blocking the other is two facts and the block has to say both,
`blocked by` from this end and `blocks` from the other; keying on the kind would
fold them into one row and lose half of what the ticket says. Only a symmetric
kind can collide with its own stored line, and `RelationKind::is_symmetric`
derives that from `label() == inverse_label()` rather than naming `RelatesTo`,
so a kind added later answers by construction. The same gate is what keeps the
refusal off a cycle: a target holding `blocked by <this>` is not a duplicate.

The stored row is the survivor, not the derived one, because it is the line
`relate --clear` can address. The consequence is worth knowing and is written
down: with both ends holding a line, clearing one leaves the other's, which then
draws as the derived row. Correct, since the far end still asserts the relation.

4179958 decided that `relates to` is symmetric and "written once, not onto both
files". Nothing enforced it until now.

The board's own data is left alone. 8556048 and 8c8a520 still both store the
line and the block now draws it once, which is what the criterion asked for.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 12:41:49 +02:00
Ansho ReiandClaude Opus 5 0f0767ac00 (8556048) Take a relation off with relate --clear, and bump to 0.32.0
`relate` only added. A `--blocked-by` pointed at the wrong ticket was on that
ticket forever, refusing every move it made until the target was done or `-f`
was passed again, and a target that was deleted did not clean up either: the
board carried a dead edge that nothing could clear and every later read of the
ticket paid for.

`--clear <kind> <target>` takes one off. It is on `relate` rather than on `set`
for the reason `RELATIONS` is out of `section_args`: a relation names a target
that has to be resolved first, so one writer owns both directions, the way
`chown` owns setting an owner and clearing one. It names the target and not
just the kind, because a ticket can hold several relations of one kind and
emptying all of them is not what anybody is asking for. That is also why it is
not spelled the way `set --clear` is, which names a field and empties it whole.

Both spellings of the kind are taken, `blocked-by` from the flag and
`blocked by` from the label: both are in front of the reader, the flag being
what recorded the relation and the label what `show` prints and the file
stores, so refusing the printed form would trap anyone clearing a row they had
just read. `RelationKind::flag` is a match rather than a `replace` on the
label, so the flag, the `--clear` value and the completion list cannot drift.

`find_relation` searches the ticket's own edges by id prefix before it searches
the board, and that order is the feature rather than an optimisation: no search
of the board reaches a target whose ticket is gone, so the stored-target tier
is the only thing that can clear a dangling edge, which is the case most likely
to need clearing. Two stored targets under one prefix name the candidates
instead of guessing, as an ambiguous ticket search already does.

An edge the ticket does not hold reports no change, and a target naming nothing
at all is an error. The two are different facts: the first is the state the
caller asked for, and the second is a typo that a no-op would swallow. The
resolver's own reason is carried through, so an ambiguous search says it is
ambiguous rather than being reported as nothing found.

Recording and clearing the same relation in one call is refused, and the check
runs on what was *asked* for and not on what would be written. A relation
already in the file is not among the additions, so comparing against those
would have let `--blocked-by X --clear blocked-by X` quietly remove it.

Removals rewrite the section from what is left and additions are appended to
that, in that order and in two passes: a call with no `--clear` then takes
exactly the path it always took. The last edge leaves the placeholder, which is
the line `append` treats as no content, so the next `relate` replaces it rather
than writing underneath it.

The two values are one flag, so clap cannot type them apart. `num_args = 2` is
per occurrence, which makes an odd number a usage error and every chunk a full
pair, and `cleared` parses the kind before the ticket is resolved. Nothing is
logged, in either direction, since `relate` never has: a log recording only the
destructive half would read as though the additions had never happened.

`chowns_clear_is_completed_with_tickets_and_sets_is_not` found the first rule
carrying `-l clear` and there are now three, on three commands, each taking
something different. It is `each_clear_flag_is_completed_for_its_own_command`,
scoped per command, and `relate --clear` offers the kinds rather than a board
listing, since tickets where the kind goes would be candidates it refuses.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 12:13:37 +02:00
Ansho ReiandClaude Opus 5 7994d98913 (76d10d7) Strike through a relation to a discarded ticket, and bump to 0.31.5
The relations block marked a target `○ ◐ ●` or `?`, and none of those can say
the target was discarded: the status mark is one cell in a column of five
states, and `●` in grey against `●` in green is a colour a pipe does not get.
A row pointing at abandoned work therefore read as a live dependency, which is
exactly what it is not.

The row is struck through instead, the whole of it, gutter and padding
included, so the line runs unbroken from the label to the end of the title.
The relation stays recorded, for completeness and for the case the target is
moved back out of discarded, and reads at a glance as no longer standing for
anything. The mark column is untouched: 451fb83 already gave a discarded
target the full circle of done in the grey of the untouched pile, and the
strike is additive on top of that.

`Cell` learns a modifier, the first style on it that is not a colour. Same
trick as the palette, one step further: `Modifier::ansi()` is SGR 9 and
`From<Modifier> for ratatui::style::Modifier` is `CROSSED_OUT`, so a style
that exists for one renderer and not the other is a compile error. Bold stays
out of it, because bold rides inside `Color::Magenta.ansi()` and `span_from`
adds it back from the colour alone; a second modifier goes beside this one.

`paint_cell` opens the modifier ahead of the colour and closes both with one
reset, which is why the reset is now a constant the two writers share rather
than a literal in `paint`. `span_from` takes the modifier too and has no early
return for the uncoloured case any more: a struck plain run is a styled span
with no foreground. `Cell::struck` is a builder, because the strike is decided
a whole row at a time by the layout that already chose the colours.

`Body::push_cell` merges on the whole style rather than the colour alone.
Nothing outside the relations block carries a modifier today, and a merge
keyed on the colour would silently strike a plain run through the moment one
did.

The strike is under the same flag every other escape is, so a piped `show`
carries none of it. That is the bargain committed and reviewing already take
for being told apart by colour alone, and `assets/SKILL.md` says so outright
rather than leaving an agent to infer that a plain-looking row may point at
abandoned work.

Tests are paired both ways, and both halves are load bearing: a renderer that
struck nothing fails the presence, and one that struck every row fails the
absence. `the_status_marks_are_pinned` had never listed discarded, so it does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 11:53:45 +02:00
51 changed files with 13110 additions and 1483 deletions
+31 -508
View File
@@ -1,520 +1,43 @@
# AGENTS.md
## Project Structure
- `src/main.rs` - dispatch, the SIGPIPE reset, and the TUI event loop
- `src/command.rs` - CLI argument definitions using clap derive
- `src/completions.rs` - the generated completion script and the fish half that asks the board
- `src/handlers.rs` - one `cmd_*` per subcommand
- `src/util.rs` - the ticket format, resolution, rendering and the palette
- `src/campaign.rs` - the campaign file format, its resolution, its index and its members
- `src/history.rs` - the history log: the path, the kinds, the reader, the writer, the card's counter and the block `show` and the board both render
- `src/tui.rs` - board state, the change digest, and the ratatui draw
- `src/clipboard.rs` - the OSC 52 write and the base64 it carries, the board's only way out to the clipboard
- `src/install.rs` - the embedded agent assets and the compare-and-refuse install
- `assets/SKILL.md` - the agent skill for the CLI itself, embedded with `include_str!`
- `assets/REVIEW.md` - the agent skill for reviewing a finished ticket, shipped the same way. Assets are named after the role they teach; `SKILL.md` keeps its name because the role it teaches is the CLI
- `assets/PLAN.md` - the agent skill for grooming the whole board: priorities, due dates, tags and campaigns
- `assets/ADMIN.md` - the agent skill for the board itself: designing and annotating the tag vocabulary, and repairing a board whose files and fields have come apart. The one asset written to hold for a board that tracks no software, so its examples span three subjects on purpose. It draws the line against `PLAN.md` in both directions: this one decides the vocabulary, that one applies it
- `assets/TOOL.ts` - the opencode tool definitions wrapping the CLI, embedded the same way and installed by `install-tool`. The only asset that is not a document and the only one that reaches a single agent
- `tests/` - Integration tests using `assert_cmd` and `assert_fs`, one file per command
- Unit tests live beside the code in `#[cfg(test)] mod tests`, in `util.rs`, `history.rs` and `tui.rs`
- Ticket files stored as `.md` in `.worklane/<status>/` directories
- History entries stored as `.md` in `.worklane/history/<ticket_uuid>/`, one file per entry, beside the status directories for the reason campaigns are
- Campaign files stored as `.md` in `.worklane/campaigns/`, which is beside the status directories and deliberately not in `status_dirs()`
worklane is a local kanban board: a Rust CLI and a ratatui TUI over markdown files in a
`.worklane/` directory. `src/main.rs` maps a parsed command to its handler, `src/tui.rs`
draws the board, and `assets/` holds the agent documents the binary embeds and installs.
## Ticket File Format
- Filenames: `<uuid_v4>_<slug>.md`
- The slug is the title through `slug()`: lowercased, alphanumerics plus `-` and `_` kept, spaces turned into dashes. `Ticket 06` lands as `<uuid>_ticket-06.md`. Derive fixture filenames through `slug()`, never by hand
- Metadata fields parsed by `parse_ticket_field()`: `ID`, `Priority`, `Tags`, `Due`, `Owner`, `Created At`, `Committed On`, `Submitted On`, `Completed On`, `Discarded On`, `Campaign`, `Status`. The last five are the ones no ticket is born with: `add` writes none of them, so they are inserted on demand, against `METADATA_ORDER`, which is also what keeps `Status` last
- The four stamps are `mv`'s, written by `set_status_stamp` from `Status::stamp_field`, and they **accumulate**: entering a status writes its field, re-entering restamps, and arriving anywhere removes the fields of every status *after* the target. One arrival rule keyed off `Status::ALL`, not a case per move, which is why a backward move truncates the journey at the target (`done` back to `reviewing` drops `Completed On`, anything back to `backlog` drops all three) and a forward skip under `-f` stamps only where it lands rather than fabricating the stages it jumped. A ticket that walks the whole flow ends with `Created At`, `Committed On`, `Submitted On` and `Completed On` side by side, so presence means *got this far and has not been sent back past it*, not *is here now* — `Status` is what says where it is. Not the history log either: these answer how far and when, once per stage, and every change along the way is the log's. `backlog` has no stamp, `Created At` already answers for it
- **`Discarded` is last in `Status::ALL`, and that placement is what makes the stamp rule fall out right.** Nothing sits after it, so a discard clears nothing: a ticket abandoned from reviewing keeps `Committed On` and `Submitted On`, and the file still says how far it got before it was dropped. It also makes every move out of discarded a backward move, so un-discarding needs `-f` without a rule of its own. `Discarded On` is its stamp, and `Completed On` stays untouched, because a discarded ticket was never done
- **Each status column is ordered by its own entry stamp, through `by_status_order`.** Priority is the clock in the backlog and that column keeps priority then title; past it the question changes, so committed sorts by `Committed On` ascending, reviewing by `Submitted On` ascending, and done and discarded by their stamp descending. Said once: the head of every column is what the reader acts on next. An unstamped ticket sinks below every stamped one in its column, because a missing time is unknown rather than ancient and unknown must not claim the head of a queue; equal stamps and both-unstamped fall through to `by_priority_then_title`. One function keyed on the `Status`, taken by both `cmd_ls` branches, `list_ids`, `columns_of` and `campaign::members`, which is why those loops walk `Status::ALL` rather than `status_dirs()`. The stamps are read in `collect_ticket_items`' existing pass, the rule `criteria` and `tags` already hold, and compared as strings: `%Y-%m-%d %H:%M:%S` is lexicographic in chronological order, the property `Due` already relies on, so nothing parses a date at sort time
- 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
- History entries stored in `.worklane/history/<ticket_uuid>/<stamp>_<kind>.md`, with the kind's marker (`**Comment**`, `**Status**`, `**Owner**`, `**Tags**`, `**Campaign**`), then the body, then `**Author**` and `**Time**`. See The History Log
## Where the documentation is
## Status Workflow
`backlog` → `committed` → `reviewing` → `done`, and `discarded` off to one side
- **`Status::ALL` is every directory that can hold a ticket, and that is the only list left.** It is what the tree walkers want: `status_dirs`, `RelationIndex::load`, `collect_ticket_items`' callers, `cmd_tags`, `list_ids`, the resolver, the digest and the board's own columns all have to see a discarded ticket or it becomes unaddressable. There was a second list, `FLOW`, the four stages work moves through, which used to be what the board drew from; a136d13 drew the discarded column behind a visibility prefix instead, which took FLOW's last reader away, so it is gone. Hiding is decided by `Visibility`, never by leaving a status out of the walk: what is drawn changes, what is read does not. The prefix property survives on the order alone — done and discarded are deliberately the last two in `ALL` — and `the_terminal_columns_are_last_in_the_order_drawn` pins it
- **Discarding is not a stage, so the walk rules do not apply to entering it.** `mv --status discarded` is allowed from any status with no `-f`, because a backlog ticket that turns out to be a duplicate should not have to be walked through committed and reviewing to be abandoned. Leaving it needs `-f`, which comes free from the backward-move rule
- **The two dependency guards look opposite ways, and `mv` picks by direction.** `check_blockers` asks what this ticket waits on and gates work moves; `check_dependents` asks who waits on this ticket and gates the discard. A ticket being abandoned owes nothing to its own blockers, but the tickets blocked *by* it recorded a dependency on work that is about to be declared never-happening, so those plans get a look before the ground moves. `-f` is the caller saying they looked. Both name every offender rather than the first, and both skip targets that are themselves done or discarded
- **Discarded satisfies a block the way done does.** There is nothing left to wait for, and whether the dependent still makes sense was asked at discard time by the guard above, which is what makes it safe to pass here rather than a second place to re-ask
- **Both terminal statuses are hidden by default and counted anyway.** `ls` leaves done and discarded out of the decorated listing and keeps them in the summary counts, and `--ids` and the status positional still reach both: a ticket nobody will work still has to be nameable by a completion or a script
- **A campaign counts a discarded member as finished.** The work was decided out of the campaign rather than left in it, and counting it outstanding would hold a campaign open forever over a ticket nobody will ever do
- **`mv` creates the target directory before moving into it.** A board made before a status existed has no directory for it, and the first move into one is the wrong place to refuse. `init` gets all five from `status_dirs()`
**How to use worklane is in `assets/SKILL.md`, not here.** That document is what
**How to use worklane is in `assets/SKILL.md`.** That document is what
`worklane install-skill` ships, so it is the one place the flow, the move-as-you-work
rule and the argument traps are written down. Read it before working a ticket in this
repo. Do not restate any of it in this file: a second copy is a copy that goes stale,
and this file is for what someone changing worklane's own code needs.
repo. `assets/REVIEW.md`, `assets/PLAN.md` and `assets/ADMIN.md` are the same for
reviewing a ticket, grooming the board and administering it.
## Testing
- Run: `cargo test`
- Tests use `assert_cmd` and `assert_fs` for CLI testing
- `setup_worklane()` creates temp `.worklane/` with the four flow 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. **The fixtures deliberately do not create `discarded/`**, so every discard test runs against a board that predates the status and `mv_creates_the_discarded_directory_on_a_board_that_predates_it` is not the only thing exercising the on-demand creation
- `create_ticket()` writes fully-formed markdown files directly (no `--` separator for positional args in test commands)
- **Every unit-test fixture directory goes through `util::Fixture`, and nothing calls `remove_dir_all` at the end of a test.** `Fixture::new(prefix)` makes a uuid-named directory under the system temp dir and its `Drop` removes it, which is the only shape that also runs when an assertion fails — a trailing line does not, and a failing test is exactly when a fixture is most likely to be stranded. That was b74dc5a: `/tmp` reached 18363 of these and filled the disk, failing a link step and then a `git add` with "No space left on device", an error naming neither the tests nor what they left behind
- **`Fixture` derefs to `Path` and also implements `AsRef<Path>`**, because the two reach different call sites: a parameter typed `&Path` is a coercion site and one bound by `impl AsRef<Path>` is not. `Fixture::child(name)` points the fixture at a directory inside itself while still removing the parent, which is the tree `project_tree` needs. The prefix earns its place on the one path that is ever left behind, which is why this is a small guard rather than `assert_fs::TempDir` — that names its directories `.tmpXXXXXX`, which says nothing about whose they are
- **`WORKLANE_KEEP_FIXTURES=1 cargo test` keeps the fixtures and prints each path.** Opt-in rather than kept-automatically-on-failure, because the assertions here carry the state they are about: a failing board test prints the rendered rows. The flag is read once when a fixture is made rather than at drop time, so the answer cannot change mid-test, and `Fixture::swept()` turns it off for the three tests that are about the guard itself and must not be failed by a reader's environment
- **Verify a claim about leaked fixtures against a clean temp dir, not against `/tmp`.** `TMPDIR=/tmp/scratch cargo test` then count what is left in it: `/tmp` still holds the historical leak, so counting there measures the past rather than the change
- 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:
**Why worklane is built the way it is, is in `docs/`.** Start at
[docs/INDEX.md](docs/INDEX.md), which says which file answers what. Read the entry for
the subject you are changing before you change it: each one carries the reason a rule
exists and what broke without it, and a rule undone by accident is the failure this
split exists to prevent.
| setting | value | why |
|---|---|---|
| `max_width` | 100 | The tree's own habit, and the measured optimum: 90 costs 268 hunks and 120 costs 194, against 161 at 100 |
| `fn_call_width` | 75 | A call stays whole if it fits in three quarters of the line. rustfmt's default of 60 is what expanded 276 of the 305 hunks the default config wanted |
| `chain_width` | 65 | The same for a method chain |
| `struct_lit_width` | 30 | A small struct literal stays whole, so `Size { width: 120, height: 20 }` is not six lines |
Do not restate any of it here, and do not add a second copy anywhere else. A copy is a
copy that goes stale, which is what happened to the skill document under `.opencode/`
before b2c5531 deleted it. This file is the map and nothing else.
**The numbers were measured, not chosen.** Default rustfmt wanted 305 hunks and would have added 1418 lines of pure layout, because its sub-widths sit far below the 100 columns this tree is written to. `use_small_heuristics = "Max"` went the other way, 308 hunks and 796 lines *removed*, one-lining `if`/`else` and collapsing struct literals that were split on purpose. Coordinate descent over the stable width knobs landed here, at 161 hunks, and 98 of those are rustfmt *joining* calls that fit rather than breaking them. Sweeping any one of these four in either direction makes the diff bigger, so do not adjust one by eye; measure it the same way, with `cargo fmt --check | grep -c '^Diff in'`
- What this does not buy: rustfmt has no rule for "keep parallel arms parallel", so a match whose arms are one line and four lines depending on the length of their contents is what it produces, and that is accepted. Reach for `#[rustfmt::skip]` only where the layout carries meaning a reader needs, not to win an argument about density
- Do not add an unstable option. `cargo fmt` on stable ignores them with a warning, so the tree would format differently for whoever ran nightly
- **Sixteen lines still run past 100 columns and every one of them is a single string literal**, a test fixture or an error message rustfmt cannot break. `format_strings` is deliberately left at its default: turning it on would let the formatter rewrite message text, and a message is prose. So `max_width` is where rustfmt breaks lines, not a limit the tree keeps
- The reformat is `73ffcad`, and `.git-blame-ignore-revs` names it so `git blame` looks through it. Turn that on once per clone with `git config blame.ignoreRevsFile .git-blame-ignore-revs`. A commit belongs in that file only if its diff is pure layout
## The three rules that have no home but this one
## Coding Guidelines
- **Run `make check` before committing**: `cargo fmt --check`, then
`cargo clippy --all-targets -- -D warnings`, then `cargo test`, cheapest first. This
repo has no CI and does not want any, so that command is the whole of the enforcement.
See [docs/testing.md](docs/testing.md).
- **Commit format is `([ticketID]) [short description]`**, and `--fixup` for incremental
changes. See [docs/releasing.md](docs/releasing.md).
- **Before every commit, decide whether the change warrants a version bump, and ask the
user to confirm the bump and its kind before making it.** Never bump silently, and
never skip the question because the answer looks obvious. `make patch`, `make minor`
and `make major` do the mechanics. See [docs/releasing.md](docs/releasing.md).
### Rust Style
- Use `if matches!(expr, Variant)` instead of `if let Some(Variant) = expr` for enum variant matching
- Use `if let Some(x) = expr` instead of `if let Some(Some(x)) = expr` — drop unnecessary nesting
- Prefer explicit `match` over `unwrap_or_default()` for clarity
- Use `unwrap_or_else(|| expr)` for lazy defaults, `unwrap_or(val)` for eager defaults
- Use `anyhow!()` with context strings that include identifying info (e.g. UUID, title) not bare values
- A command whose arguments run past a handful takes a clap `Args` struct, not an inline variant with a matching parameter list: `AddArgs`, `SetArgs`, `AppendArgs`, `CheckArgs`. `add` was nine positional parameters threaded from `main` before it became `AddArgs`, and the handler destructures the struct so the body reads the same as before
## Adding to the documentation
### CLI Arguments
- The prose arguments carry `allow_hyphen_values`, via the `PROSE` constant in `command.rs`: `add --title`, `--description`, `--acceptance`, `--plan`, and the `comment` body. Ticket text quotes flag names constantly, and without it a criterion reading `--print is supported` is parsed as a flag and the whole ticket is refused with nothing written
- **The trade:** on those five arguments a genuinely mistyped flag now lands as content rather than raising a usage error. That is the right way round for prose and the wrong way round for anything else, which is why `due`, `priority`, `tags`, `owner` and `status` are deliberately left without it. A mistyped flag there is still a usage error, exit 2, and no ticket is written. Do not add `PROSE` to a new argument unless it holds prose
- **`--due` is validated at parse time by `iso_date`, the way `--priority` is by `priority_level`.** A date that is not real is a usage error, exit 2, with nothing written, which is the whole point of leaving the scalars without `PROSE`. One parser serves `add` and `set`: the field has one definition of what it accepts, and validating only `add` would leave `set` open, which is the command a grooming sweep actually uses
- **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 <id>`, `mv <ticket>`, `comment <ticket>`) 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`
- A bare `--` is a value when it follows an option (`--title -- ` stores `--`) and clap's end-of-options marker when it sits in a positional. So a `comment` body of exactly `--` needs its own separator, `comment <ticket> -- --`. Without it the body is reported missing and nothing is written, which is a clear failure rather than a silent drop
- `add` has no positionals, so anything after a bare `--` is an unexpected argument and fails
- **A paragraph break in a description is an empty `--description` value.** `cmd_add` joins the values with a single newline, so `-d "First." -d "" -d "Second."` writes the blank line. `trim_blank_ends()` drops blank values at either end, so a break never lands against a section heading, and an all-blank description reads as no description. Interior runs are kept verbatim rather than collapsed
- `--acceptance` and `--plan` are lists, one criterium or step per value, so a blank there is spacing rather than content and the opencode wrapper drops it. Only `--description` preserves blanks
### Completions
- **Two halves, and the split is the point.** `clap_complete` generates the structure from the clap definition, so a new flag or subcommand is completed without anyone touching `completions.rs`. Only fish gets the second half, appended by `fish_dynamic()`, and it holds exactly what clap cannot know: the tickets on the board
- **The dynamic values come from worklane itself**, as `worklane ls --ids` in a command substitution, one run per keypress at 2.5ms in release. So the completions are only as current as the binary on PATH: an older one without `--ids` completes nothing, which is a reinstall rather than a bug
- **What clap does and does not emit.** It emits the possible values of an *option*, which is why `mv --status <TAB>` needs nothing here, and nothing for a *positional*, which is why the `ls` status and the `completions` shell are listed in the fish half. Both lists are read off the enums with `possible_values`, never written out, so a fifth status appears in the script on its own
- **Position is counted, not inferred.** The four `__worklane_*` predicates all read `$tokens[2]` and the token count rather than using `__fish_seen_subcommand_from`, because `campaign ls` and `campaign show` are also an `ls` and a `show` that fish has seen, and because matching against the ticket list would run worklane again inside the condition. `first_arg_of` and `second_arg_of` count a top-level command's arguments, `nested_arg_of` matches a parent and a child so `campaign show <TAB>` can be told from `chown alice <TAB>`, which sit at the same token count, and `command_is` asks only which command this is, at any position in it
- **Every rule carrying `-l` needs a `__worklane_command_is`, and `every_rule_naming_an_option_is_scoped_to_a_command` is what enforces it.** A bare `complete -c worklane -l tag` does not just complete that option's values, it tells fish the whole tool accepts `--tag`: `worklane init --<TAB>` offered six options that only `relate` and `ls` have. Fixed in 55ee6e3. `__fish_seen_subcommand_from ls` is not the scope to use, for the nesting reason above
- **The five completion lists are kept honest by tests** that walk the clap definition and fail on an argument left out of them. `TICKET_COMMANDS` and `TICKET_SECOND_COMMANDS` by position, `TICKET_FLAGS`, `CAMPAIGN_COMMANDS`, `CAMPAIGN_NESTED_COMMANDS`, `CAMPAIGN_FLAGS` and `TAG_FLAGS` likewise. The walk is one function, `every_argument`, since the tests differ only in the id they look for. Each also asserts *how many* it found, so a walker that stopped finding arguments fails rather than passing every assertion by never running them
- **A campaign is named in three shapes and a tag in one**, which is why the lists are not one list: a campaign is `assign`'s first positional, the first argument of `campaign show` and `campaign set`, and `ls --campaign`'s value, and each needs a different fish rule. A tag is only ever an option value, and its values come from a different command
- **`ls --ids` is the machine-readable listing**, and one of the three outputs in the tree meant to be parsed: the short id, a tab, the title, unstyled. Two fields because fish reads what follows a tab as the description and a script reads `cut -f1`. It includes done, which the decorated listing leaves out, because a completion has to be able to name a finished ticket, and it skips a missing status directory rather than refusing, because an error printed over a shell prompt is worse than no candidates. The filters still apply, and an unknown `--campaign` is still refused
- **`campaign ls --ids` is the same flag and the same two fields for the other object**, and it deliberately skips the member counting the decorated listing does: `members()` reads every ticket on the board, and the caller here is a shell filling in candidates on a keypress. It also prints nothing on an empty board, where the decorated listing prints a sentence, because a sentence offered as a candidate is worse than no candidates
- **`worklane tags` is the third, and it is a command rather than a mode on `ls`.** Two reasons: `ls --tag <tag>` answers what carries a tag and cannot answer what tags exist, which is the question a grooming sweep starts from, and a `--tags` beside a `--tag` is one letter from a filter that means something else. Alphabetical and case sensitive, matching the filter, so `bug` and `Bug` list separately and land next to each other, which is where a near-duplicate is spotted. Every status, done included: a tag that has fallen out of use is still part of what the vocabulary has been. `assets/PLAN.md` used to tell the agent to count tags with a `show` per ticket, and now points here
### Filtering the Listing
- **The filters are one call, `filtered`,** because `ls` collects a column in three places (a named status, the counts, and the grouped listing) and three call sites are three chances to apply a different set. Every filter is an `Option` and none asked for keeps everything, which is what makes them compose in any combination without a rule per pair
- **`--tag` matches whole values, not the field.** `parse_tags` has already split the comma-separated field, so the filter compares against those trimmed values: `--tag bug` is not answered by a ticket tagged `bugfix`, and `--tag "cli, filter"` matches nothing, because the field as written is not itself a tag. A ticket with no tags matches none
- **Case sensitive**, the opinion the field already takes: `tag_color` draws `Bug` and `bug` in two colours because they are two tags. A filter that folded them would list tickets carrying a tag nobody asked for, and would hide exactly the split a grooming sweep is looking for
- **One tag per invocation.** Several would have to decide between and and or, and neither reading is obviously right for a board this size. That decision is its own ticket, along with a substring or regex match and a tag filter on the tui
- **A tag nothing carries lists nothing rather than being refused**, which is the opposite of `--campaign`. A campaign is an object that either exists or does not, so it is resolved before anything is read and an unknown one is an error. A tag is free text with no registry: there is nothing to resolve against, and refusing an unknown one would mean maintaining a vocabulary the format deliberately does not have. `assets/PLAN.md` tells the agent to check the spelling when a listing comes back empty, and `worklane tags` is what it checks against, since that is the failure this trades for
- An emptied status keeps the message `ls` already gives, `No tickets in '<status>' status.`, rather than one per filter naming what excluded them. That is pre-existing behaviour for `--priority` and `--campaign`, and one message for every filter is the consistent half of it. If it should name the filter, that is a change to what the CLI prints for three flags at once and belongs in its own ticket
- **`cmd_ls` takes an `LsArgs`**, which is what the boundary in the Rust Style rule came to: four filters, an output mode and the directory, two of them adjacent `Option<String>` values a caller could swap silently. `--ids` was the argument that tipped it, the way `add` became `AddArgs`. A new filter is a field there, not a parameter
### Editing a Ticket
- `set` replaces a field, `append` adds to a section. The verb carries the meaning, so no flag needs a replace-or-append prefix, and `append` only offers the sections that hold multiple lines
- **One field, one writer.** `set` has no `--owner` (that is `chown`'s) and no `--status` (that is `mv`'s), and neither `add`, `set`, `append` nor `chown` can reach the three status stamps, which `mv` writes as a side effect of the move. Do not add any of them
- `chown` takes the **user first and the ticket second**, after Unix `chown`, and is the only command that does not start with the ticket. Deliberate: the name borrows the Unix association, so the order borrows it too. A swap is left to `resolve_ticket`, which refuses a bare username as a ticket. No argument is inspected to see whether it *also* names a ticket, since such a check would only fire where resolution already fails and would stay silent on the one case it cannot catch, a ticket whose title is the username
- `cmd_chown` is `set_metadata_field` plus `save_ticket`, with the same whole-file no-op comparison `set` uses and the same `report()` output, so nothing about writing a field lives twice
- `apply()` is the one place an edit is taken or dropped, shared by `set`'s replaced list and its cleared one. It was a closure over the single list until there were two, and two closures carrying one rule is how a later edit changes it for one and not the other
- Sections are a table in `util.rs`: `DESCRIPTION`, `ACCEPTANCE`, `PLAN`, each with a heading, a label, the placeholder `add` writes when empty, a `SectionKind` and the `--clear` value that empties it. Adding a section later is one entry, not edits in both commands
- Everything is targeted line surgery, never a regenerated file. That is what keeps a ticked criterion ticked and a handwritten `## Notes` section intact when an unrelated field changes. `section_body()` finds the lines to touch, `set_metadata_line()` does the metadata, and every other byte is copied through
- Appending to a numbered section continues from the count of steps already there and does not renumber what is above it, so a handwritten line in the section survives exactly as written
- Appending to an empty section replaces the placeholder rather than following it, or the ticket would read `_No description provided._` above its description
- An empty value is a paragraph break for the three sections and a usage error for the scalars, via `non_empty` and `clearable` in `command.rs`. Neither spells clearing, and both errors name the flag that does
- **A call whose values are *every one* blank is refused, by `replaced_items` for `set` and `appended_items` for `append`.** The check is the section's rather than the object's, so `campaign set --description` shares it. What differs is the way out, which is why `replaced_items` takes it as an argument: a ticket's section is emptied with `--clear <field>` and a campaign's description cannot be emptied at all, so a single hard-coded tail would name a flag that does not exist on one of the two
### Clearing a Field
- **`set --clear <field>` is the one way to take a value away, and it is a flag with the field as its value.** Not a per-field `--clear-due`, which is a flag per field to keep in step with the field it undoes, and not an empty value, which is already a paragraph break for a section and would make an accidentally empty variable a silent delete. Repeatable, so one call empties as many fields as it likes
- **`Clearable` is a `ValueEnum` in `util.rs`**, so an unknown field is a usage error at the door listing the six that are not, and the shells complete them for free. It is also the whole table of what can be cleared: `Due`, `Tags` and `Priority` clear to a sentinel, `Description`, `Acceptance` and `Plan` to their section's placeholder. `Title` is absent because it addresses the ticket and names its file, so there is no state to go back to; `Owner`, `Status`, `Campaign` and the stamps because clearing them through `set` is exactly the second writer the missing `set --owner` exists to prevent
- **What is written is `NOT_SET` and `NONE`, the constants `add` writes.** A cleared ticket and one that was never given the field have to read the same, or clearing would be a third state that every parser then has to know about. `a_cleared_ticket_reads_like_one_filed_without_the_fields` compares the two files byte for byte, which is what keeps a new field honest
- **The placeholder goes into a section bare, via `clear_section_body`.** `set_section_body` runs its items through `Section::render`, which would write `- [ ] _No acceptance criteria provided._`. Both are `replace_section_body` underneath, so the line surgery and the trailing blank line live once
- **The pairing between a section and its `--clear` value is stored on both**, `Clearable::unset` one way and `Section::clear` the other, because the error for an empty value has to name the flag for *that* section and the section's label ("acceptance criteria") is not the flag's value ("acceptance"). `every_clearable_section_points_back_at_the_field_that_clears_it` keeps the two directions from drifting. `RELATIONS.clear` is `None`, the same rule that keeps it out of `section_args`
- **Cleared fields are reported apart from replaced ones**, as `Cleared due on '...'` beside `Updated priority on '...'`. One list would say `Updated` of a field that was emptied, which is the opposite of what a caller needs to read back. The labels are the ones `set` already prints when it *writes* the field, so the two lines name a field the same way
- **Replacing and clearing one field in a single call is refused**, by `SetArgs::contested`. clap cannot express it, because the field arrives as `--clear`'s value rather than in its name, and answering by whichever was applied last is a silent answer to a contradictory call
- **Clearing the owner is `chown --clear <ticket>`, and `--clear` carries the ticket.** Owner has one writer and clearing it cannot introduce a second, so it lives on `chown`; but the ticket is `chown`'s *second* positional, and a bare flag would land it in the user's slot for the handler to read back out, which is hand-parsing what clap can state. The typed call is identical either way. `ChownArgs::target` returns the one shape the constraints allow, and an error rather than a panic for the combination they already refuse
- **Clearing the owner writes `NOT_SET`, not the git user.** `add` falls back to the git user because it is filing something new; an owner taken away says nobody owns this, and putting the person running the command there instead hands them a ticket they were giving up
- Clearing a field that is already unset writes the sentinel that is already there, so the whole-file comparison below reports no change and nothing is written. That is not a special case, and must not become one
- No-op detection compares the whole file before and after each edit, so a field set to the value it already holds is reported unchanged and nothing is written
- `find_ticket_file()` matches on the uuid, never the title. Duplicate titles are allowed, so a title scan can land on a different ticket than the one resolved: `mv <uuid-of-second>` used to move the first ticket sharing its title
- `write_then_replace()` is the only way a ticket file is written. Content first, rename second, so a failure leaves a correct ticket under a stale name rather than a half-written one
### Checking Off a Criterion
- `check` and `uncheck` are separate commands, not one verb with a flag. They share `CheckArgs` and `cmd_check(args, checked)`
- `criteria()` is scoped to the Acceptance Criteria section and counts only checkbox lines, so a checkbox written into a description is not a criterion and a handwritten line inside the section takes no number
- `set_criteria()` splices only the character between the brackets, and takes every line in one pass. Rebuilding the line would normalise its indentation and whatever spacing followed the checkbox
- Each criterion term is the keyword `all` first, an index second, a substring third. So a criterion whose text is literally `2` is reachable only by substring, and one whose text merely contains "all" only by its number or a longer substring. `is_all_criteria()` and `is_index()` sit beside each other in `util.rs` for that reason
- **The keyword wins over the text on purpose.** Ticking every box is the reason the word is typed, and a board where `all` sometimes means one criterion and sometimes means the lot would be worse than one that can be addressed another way. `all_is_the_keyword_and_not_a_substring_of_the_text` pins it against its own fixture, so the shared one keeps its three criteria and its numbering
- **A number out of range is a bad index, not a failed substring search**, and says so. `is_index()` makes that distinction
- Any listing of a subset must keep the real numbers, via `numbered_criteria()`. Renumbering the matches from one contradicts the advice to use the number and points at the wrong criterion
- With the criterion omitted: prompt when stdin is a terminal, otherwise return the numbered list as an error. Never prompt unconditionally, the opencode wrapper has no tty and would block on a stdin that never closes. This is the same choice `resolve_ticket` makes for an ambiguous match, and for the same reason
- **The criterion positional is variadic**, so `check <ticket> 1 3 "the footer"` is one call and one write. Variadic rather than a repeated flag: the terms address criteria that are already there, the way the ticket positional does, instead of carrying content the way `--acceptance` does. The prompt path is unchanged and fires on an empty list
- **`resolve_criteria()` resolves every term before a byte is written, and one bad term refuses the whole batch.** A call that ticked the terms it understood and then failed would leave the ticket half-marked with nothing in the file to say which half was meant. It names the offending term alone rather than every failure at once, since each message carries the criteria listing and a batch of them would repeat the list per bad term
- The chosen offsets are sorted and deduped, so the report reads in `show`'s order whatever order the terms arrived in, and a criterion named twice, or by both `all` and its own number, is marked and reported once
- **Every named criterion gets a line, in `show`'s order, printed after the write.** A criterion already in the target state reads `Already checked 2: text` and does not count towards the write, so a batch where every box is already ticked writes nothing, which is the whole-file no-op rule the editing commands keep. The number is on the unchanged line too: without it a batch cannot be read back against `show`
- `show` numbers the criteria as `1. [x] text`, so the index is visible where the ticket is read. The number replaces the list marker rather than joining it
### Relating Tickets
- **The Relations section is `relate`'s alone.** `RELATIONS` is in the section table but deliberately out of `section_args`, so `set` and `append` cannot reach it: a relation names a target that has to be resolved to a uuid first, and a prose flag would let an unresolvable line into the one section that is read back by machine. Same rule as Owner and Status, one field one writer
- **`add` does not write the section.** The plan on 4179958 asked for it in the ticket writer; it is out on purpose. A `_No relations._` block in every new ticket is noise in every `show`, and the insertion path has to exist regardless for every ticket written before the section did, so leaving it out means one path that is always exercised rather than two
- **The full uuid is stored, not the seven characters `ls` prints.** It resolves without a scan and cannot turn ambiguous as the board grows. `show` renders the short id and the target's title instead: the file is the machine's copy, the output is the reader's
- **One direction is stored and the inverse is derived.** `blocked by` goes on the gated ticket rather than `blocks` on the blocker, because the gated ticket is the one whose move is refused and whose author knows about the dependency. `relates to` is symmetric and is written once, on whichever end the caller ran it from. `RelationIndex::inbound` finds the far end by scanning, which is what keeps `relate` a single-file write
- **A line in the section that is not a relation is an error naming the ticket**, not a line quietly dropped. Nothing but `relate` writes there, so a bad line means a hand-edited file. The TUI is the deliberate exception: `detail_of` falls back to no block, since one corrupt ticket must not take the whole board down
- **The block is built outside `content_trim` and passed in.** Half of it comes from other tickets and `content_trim` has only the body. It is spliced over the stored lines where the file has the section, and injected ahead of the metadata where it does not, because a ticket that is only pointed at has no section of its own and still has relations to show
- `ensure_section` inserts against `SECTION_ORDER`, before the first following section that is actually in the file, and adds no blank line that was not already there. A handwritten `## Notes` between the plan and the metadata therefore keeps its place, and Metadata is in that list as an anchor rather than as something anything appends to
- **The blocker check runs on every move**, after the already-in-that-status return and behind `force`. An open blocker is a reason not to start and a reason not to finish, and one rule is easier to hold than a table of which transitions care. A move to the status the ticket is already in is not a move, so it is not refused. `-f` now bypasses three rules, which is the right home for it: each one is a deliberate override of something the board would otherwise keep true
- **A blocker that is not on the board warns and allows the move.** Refusing would wedge the ticket with no way out but `-f`, and a uuid nothing carries is a bookkeeping fault rather than a dependency. The refusal names **every** open blocker, since clearing the one that happened to be printed would leave the ticket blocked
- Left out on purpose: removing a relation, which 4179958 assigns to 74904dc. The blocked marker on the card landed in b8ce18c, and it cost no scan of the board: the blockers ride along on the read that already builds the cards. See The Board View
### Campaigns
- **A campaign's state is derived, never stored.** Open until every member is done, computed by `Standing` from the members. A `Status` field on the campaign would be the same state in two places, and the two would disagree the moment a member moved. It is also why there is no `campaign mv` and no forward-only ruleset beside `mv`'s
- **A campaign with no members is neither open nor done.** `Standing::state()` returns `None` there, and both callers print `no members`. Calling it done would make a container nothing has been filed against the most complete thing on the board; calling it open would claim work that does not exist
- **Membership is one field on the member**, `Campaign` in the ticket Metadata, written only by `assign`. The member list is deliberately *not* on the campaign: that would put membership in two places, and would make one file that every assignment edits, which is contended the moment two agents share a board. So `add` has no `--campaign` and `set` has no `--campaign`, the same rule as Owner and Status
- **The full uuid is stored and the title is resolved for display**, as the Relations section already does. `reference_cells` 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 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 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 set` and `campaign append` are the only writers of a filed campaign's fields.** d637288 decided the command: a `set` rather than a flag on something narrower, because the file has more than one editable thing and the moment somebody wants to fix a typo in a title there would be a second command to design. `set` carries `--title`, which renames the file the way `set --title` does, `--description` and `--codename`; `append` carries `--description` alone. `campaign add` writing a field at creation is not a second writer, exactly as `add --title` and `set --title` coexist
- **Replacing a codename the campaign already has needs `--force`.** Once a campaign has one it is referred to by it: it is on every card in the campaign, it is what resolves the campaign at the command line, and it is in somebody's shell history. Changing it silently is the mistake `install-skill --force` exists to prevent, so it is refused and the refusal names both words and the flag rather than leaving it to be found. Checked before any edit is applied, like `SetArgs::contested`, so a call also carrying `--title` writes neither field. Setting the codename a campaign already carries stays a **no-op, not a refusal** — `--force` is about overwriting a *different* word, which is the same division `install::Outcome` draws between `Unchanged` and `Refused`. `--force` guards the codename alone: a campaign always has a title, so guarding that would mean the flag was always required
- **The description arrived as a pair, `set --description` and `campaign append`, 32e98ab.** Never one without the other: for a prose section `set` replaces and `append` adds, and a way to replace a description with no way to add a paragraph is the half that is easy to reach for and wrong, since replacing a description to add a sentence to it is how the rest of it gets lost. The two scalars have no append form at all, which is the same line `append` already draws for a ticket, and `campaign_append_offers_only_the_description` pins that. Neither flag takes `--force`: a description is prose written to be revised, the same reason `tags set --annotation` has none
- **`append` is a campaign's own subcommand, not the top-level `append`.** That one resolves a ticket, and one positional naming either object is the ambiguity `resolve_in` makes real: its tiers are the same over both directories, so a search can resolve in each and nothing but a flag could say which was meant. It would also make a liar of `resolve_ticket`, which explains a ticket search that *names* a campaign. Under `campaign` the object is settled by the command, as it is for `set`, `show` and `ls`
- **Still no `--owner` and still no `--clear`.** No `--owner`, because nothing writes a campaign's Owner today and giving `set` one would settle by accident whether `chown` grows a campaign. No `--clear`, which 32e98ab settled rather than deferred: a codename is replaced rather than emptied, and emptying the description of a container six tickets are filed against is not a thing anybody has asked for, so the only spellings left would be `Clearable` on a campaign, whose variants are a ticket's fields, or a second enum with one variant in it. `campaign_set_offers_no_owner_and_no_clear` pins both
- **An empty `--description ""` is a paragraph break here too, and the refusal for an all-blank value names no flag.** Every prose argument in the tool reads a blank value that way, `add`, `set` and `tags --annotation` alike, so a campaign reading it as *empty the section* would be the one exception. With no `--clear` to point at, the refusal says a campaign's description has no cleared form instead of naming a flag that does not exist. `replaced_items` is where the check lives, shared with `set`, and the way out is the caller's argument for exactly that reason
- **`SECTION_ORDER` needs no campaign variant, and that is what the one-section file proves.** A campaign holds Description and Metadata where a ticket holds four sections and Metadata. Every consumer of the list looks for the headings that follow, *filtered by what is actually in the file*, so a campaign's description anchors against `## Metadata` — which is where `campaign_body` writes it. `the_description_is_edited_in_place_in_a_file_with_one_section` pins that no section a campaign does not have gets inserted to anchor against
- **A campaign whose Description heading is gone is refused, not given the section back.** No `ensure_section` on this path: every campaign the tool has ever filed carries the heading, so an insertion here would be reachable only from a hand-edited file, which is the opposite of the Relations case, where `add` writes nothing and the insertion is the only path there is. The refusal therefore names the section and **not** the object — "There is no description section to write to" — because both a ticket and a campaign reach `replace_section_body` now. `write_then_replace` still carries the noun, where the message is about a file
- **The codename is written through `set_or_insert_metadata_field`, not `set_metadata_field`.** Every campaign filed before the field existed has no such line, and those are exactly the campaigns the command is for, which is the same reasoning that puts `assign` on the upsert. **`Codename` is therefore in `METADATA_ORDER`, directly after ID**, so an inserted one lands where `campaign_body` writes it and a campaign given a codename later is the same file as one filed with it. Nothing upserts it on a ticket, so its place in a ticket's order costs nothing
- **One write path for tickets and campaigns.** `save_entry` is the body, `save_ticket` and `save_campaign` are the named wrappers, and `write_then_replace` and `find_entry_file` take the noun as a `&str` so a failure says "campaign" where it is one. A campaign file is a ticket file in every way that matters here, `<uuid>_<slug>.md` in a directory, and the rename happens only after the write has landed. Every message puts the noun mid-sentence so there is no capital to case
- `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
### The Board View
- **The board is for a person, and only for a person.** Scripts and agents drive worklane through the CLI, which is what `assets/SKILL.md` teaches and what the integration tests pin. Nothing parses the drawn frame, so its layout is free to change: a new row on a card, a moved corner, a different colour or a hidden column breaks no caller. Judge a change here on whether it reads well, not on what it might break, and do not preserve a layout for compatibility's sake. What the CLI prints is the opposite case and is not covered by this
- `worklane` with no subcommand and `worklane tui` both open it, the way a bare `frig` does. `Cli::command` is therefore an `Option`
- The worklane directory is looked for **before** the terminal, so running outside one gives the usual "No .worklane directory found" rather than a complaint about the tty. Both errors stay reachable and both are testable without a pty
- A missing tty is refused with a message naming a subcommand. Raw mode on a pipe fails with a bare "No such device or address (os error 6)", which explains nothing
- **The watch looks at files, not directories.** A directory's mtime only moves on create and rename, so a ticket edited in place would be missed. `digest()` hashes every ticket and comment file's path, length and mtime. Comment files are in it because a comment added elsewhere has to reach the detail view
- The digest guards the *rescan*, not the draw. ratatui diffs its buffer, so drawing every iteration is free; reading the tree every iteration is not
- `notify` is deliberately not a dependency. Polling a tree of tens of small files on the 250ms tick is enough, and the reason is recorded on f6af387
- Cards come from `collect_ticket_items`, the same source `ls` uses, so there is no second parser. `TicketItem::path` exists for the detail view
- **The detail view scrolls on `pgup` and `pgdn`, not on up and down.** Up and down stay on the selection with the modal open, so a whole column can be read without closing it, and the modal follows. That is worth more than the two keys, which is why the scroll went elsewhere rather than taking them
- **The campaign frame scrolls on the same two keys, and `Board::scroll_page` is where the precedence lives.** An open ticket wins, whatever holds the selection behind it; the frame takes them only when there is no overlay to take them first. In `Board` rather than in the `main.rs` arm for the reason `dismiss` is: a layering rule written into that dispatch is a rule nothing can check
- The scroll offset is clamped against the *wrapped* line count, from `Paragraph::line_count`, which is why `ratatui` carries the `unstable-rendered-line-info` feature. The paragraph wraps on words, so a clamp on the raw lines would stop short of the end or scroll past it into blank space. Counting the wrapping by hand would only agree with the widget until one of the two changed
- The clamp runs on the keypress and again in the draw. The terminal can be resized between the two, and a tick can shorten the ticket under a reader who is already at the end
- The offset resets when the selection moves and when the modal is closed, so a ticket opens at its top. It deliberately does *not* reset on a tick: an edit elsewhere in the tree must not throw the reader back to the top of what they are reading
- **The overlay carries a page indicator on the bottom right of its border**, `pg 2/8`, so a long ticket does not open looking exactly like a short one. `Block::title_bottom` with a right-aligned `Line`, which spends no text row, the trade the title already makes on the top border. The two cannot crowd each other: they are on opposite borders
- **`wrapped_height` is the one measurement.** `last_offset` is it less the viewport and `page_indicator` takes the same two numbers, so the clamp and the indicator cannot disagree. A second `line_count` call, or a count of the raw lines, is a number free to drift, and an indicator that says there is more to read where the scroll refuses to move is worse than none
- **The furthest offset is the last page by definition, not by division.** The clamp stops at the wrapped height less the viewport, which is not a page boundary, so the final screenful is partial: `offset / step + 1` reads `pg 2/3` at the bottom of a 25 row ticket in a 10 row viewport and claims there is more below
- **The pages are counted in `scroll_step`, a screenful less the overlap line, not in whole screenfuls.** The step is what the keys take, so counting in it names only pages `pgdn` can land on. Counting by screenfuls puts a 30 row ticket in a 10 row viewport at `pg 3/3` two rows short of its end, since three presses are what it takes to get there
- The indicator is dropped whole on an overlay too narrow for it, the rule a corner and the tags row already follow, and absent entirely when nothing scrolls, the way an untagged card spends no row on tags
- `page_indicator` takes four numbers and returns an `Option<String>`, so every case above is pinned without a terminal. The drawn tests exist for the two things arithmetic cannot answer: which border it landed on and what colour it reached the screen in
- **Columns scroll to keep the selected card in view.** `Board::offsets` holds one offset per column, parallel to `columns` and resized in step by `reload`, so a column you leave stays where it was. The keypress aligns the focused column via `follow_selection(screen)`, taking the screen size for the same reason `scroll_detail` does: the visible height belongs to the terminal, which only the caller measures between draws
- Card heights are measured on `card_lines`, never assumed, on both the keypress and the draw side (`card_height`, and the `starts` vec as the cards are built). An alignment that trusted a fixed card height would drift from the renderer the first time the card changed shape
- The draw aligns the focused column again on its own geometry, so a resize between keypress and frame cannot hide the selection, and caps every column against blank space past its last card. The stored value may go stale after a tick shrinks the column; that is fine, because what is drawn is corrected immediately and the next navigation writes the correction back
- Entering another column follows the selection rather than resetting to its top. The card index carries across columns, so a reset would open the column with the highlight below the fold whenever it was — the opposite of the detail view's reset-on-selection-move, where each ticket genuinely starts at its own top. The index is shared and clamps permanently when a shorter column pulls it down, so a column you return to follows the selection to where it now sits rather than holding your old place
- **The footer names only keys that work.** It read `↑↓ scroll` when nothing scrolled at all, which sends the reader looking for their own mistake. A UI that misdescribes itself is worse than one that is merely incomplete
- **`q` and `esc` are one key: close what is open, quit when there is nothing left to close.** `q` used to set `should_quit` outright, so a reader who pressed it to put a ticket away lost the board instead, which is not what `q` does anywhere else that lays a document over a list. One match arm in `main.rs`, not two: two arms carrying one rule is how a later edit changes it for one key and not the other
- **The rule is `Board::dismiss`, not the match arm.** The dispatch in `main.rs` is not reachable from a test, so anything decided there is undecidable by the suite. The arm is the line that names the keys and nothing else. `the_dispatch_gives_q_and_esc_one_arm_and_leaves_ctrl_c_quitting` scans `main.rs` for what the arm cannot say for itself, over whitespace-collapsed source so rustfmt cannot fail it
- **The footer's last slot always answers how to get out**, and with a ticket open the honest answer is `ctrl-c`, the only key left that quits in one press. Going on saying `q quit` there would be 1b78a24 in the other direction: a footer describing a key by what it used to do
- **The overlay names its ticket on the border, not at the head of the paragraph.** `Board::detail` is a `Detail` carrying the title, the id and the text, because the name has to travel beside the body rather than inside it: `content_trim` drops the `# ` heading on purpose, since `cmd_show` prints it, and anything in the paragraph scrolls away
- `detail_title` cuts the string itself instead of leaving it to ratatui, which truncates an overlong block title at whatever cell it reaches and would take the id with it. Cut against the inner width, so the id survives whole and the name ends in an ellipsis. The id goes first because that is how every other view addresses a ticket
- The detail view renders from cells, never from painted strings: ratatui draws styled spans, so an escape sequence in a paragraph would be printed as literal bytes. `content_trim` and `format_history_with` take the colour decision for the CLI's side of the same layouts
- Read only. Moving a card by keypress is a follow-up, deliberately kept out until the watch and render loop were solid
- **A card is four corners with the title between them:** mark and short id top left, due top right, owner bottom left, comment count then criteria count bottom right. The numbers are in corners because that is where the eye goes for one, and they were invisible at the end of a line of prose
- The title takes one row or two, wrapped on spaces, with an ellipsis when even two are not enough. One row when one is enough: a second, blank row on every short ticket spends the column's height on nothing
- **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
- **`corner_line`'s right side is a group, single-spaced, and it gives up its items from the front.** The item nearest the edge is what the corner is *about*; anything to its left has been added beside it. So the bottom row loses its comment count before its criteria count, and the top row, with one item, behaves exactly as it did when the parameter was an `Option`. The spacing between the items lives in `corner_line` with the gap arithmetic rather than in a caller, for the reason `column_areas` is shared: geometry reproduced by hand drifts from the draw. `due_span` returns a `Span` and not an `Option<Span>` now, since the `Option` only ever existed to satisfy the old signature and the function cannot fail
- 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
- **The comment count is the same field discipline and the one entry on that pass that costs a directory listing.** The history lives outside the ticket file, so `count_comments` is a `read_dir` rather than a parse: `.md` only, the filter `read_history` applies, and no body is read, because a count needs none of them. **It counts comments and not entries**, off the kind in the filename, so a card still says how many things somebody said: a ticket that has moved three times has not been talked about, and counting the moves would put a number on every card on the board. `collect_ticket_items` derives the board from `status_path.parent()` instead of taking it as a second argument, so a status directory from one board cannot arrive with the history of another. `history_dir` spells the path once for the writer, the reader and the counter, the way `campaigns_dir` does. Zero draws nothing, not a `0` and not a blank: an uncommented card is the row it has always been, which `a_card_with_no_comments_spends_nothing_on_the_corner` pins to the exact spacing
- **The count is cyan and the mark is `COMMENT_MARK`, U+275E, a Dingbat.** It is the only coloured thing on a row whose owner and criteria count are grey, because two counts side by side otherwise read as one number in brackets and another that lost its brackets. Not U+1F4AC SPEECH BALLOON: emoji presentation and East Asian Width Wide, so it draws two cells where `spans_width` counts one character and every corner on the card lands a cell out. Not U+1F5E8 LEFT SPEECH BUBBLE either: text presentation and Neutral, but in a pictograph block most terminal fonts leave as tofu. Check both properties before swapping the glyph
- **`the_count_is_read_when_the_items_are_collected_and_not_per_draw` takes the history directory away after the board is built**, and is paired with `a_comment_added_after_the_board_was_built_reaches_the_card_on_reload`, because a count that never asks the filesystem again would pass the first test by never changing. The digest already moves when a comment lands, so the reload is what recounts
- **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_cells` 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 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`, `column_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 has two heights, and `Chrome` is what every measurement takes.** `Chrome::frame` is an `Option<FrameSize>`, not a bool: `None` for a tab showing the whole board, and `Collapsed` or `Expanded` for one filtered to a campaign or a tag, because both heights have to be measured the same way by everything that measures the board. `screen_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`, `FRAME_ROW`, `BOARD_ROW`, `FOOTER_ROW`), since an index written out by hand goes on meaning what it used to. **Nothing in the geometry is named after campaigns**, because the slot is the tag filter's too: `Chrome::frame` says how tall the frame is and never which filter filled it, so a measurement of the board never has to ask
- **The whole description is carried off the one read, and the cut is on the view.** `section_prose` replaced `section_opening`, which cut to the opening line at read time: the campaign file is only in hand while the campaigns directory is being read, so what that read has to carry is everything a view might want, and `CampaignRow::summary` takes the one line the picker draws back off it. Two fields, one cut from the other, are two strings free to come from different reads of the same file
- **`FRAME_PROSE_ROWS` is the collapsed height, and it is a constant rather than a height fitted to the description.** Three rows of prose plus a border either side. A frame that grew and shrank with the campaign would resize every column whenever the filter changed, and a reader would look for a card where the previous campaign's description had put it. It does not have to be right for the longest description, because scrolling is what covers the rest — which is also why three was affordable where one row was not
- **The expanded height is a share, not a second constant: half of what the frame and the columns divide.** That is the screen less the tab row and the footer, so the split is even between the two of them rather than even against rows neither gets all of. Half rather than most of it for the same reason the frame is not an overlay: the columns below are the campaign's members, and a reader inspecting the campaign has to go on seeing what it is made of. Floored, so the odd row goes to the cards. `Chrome::frame_rows` takes the height because of this, and `screen_rows` is where it is called, since that is the one place that already has an area to take a share of — which is what keeps `Chrome` itself pure and copyable from `Board::chrome` with no screen to hand
- **The share is bounded at both ends, and `COLUMN_MIN_ROWS` is why.** `Constraint::Min(COLUMN_MIN_ROWS)` would take rows back from a frame that asked for too many, silently, and the frame's own measurement would then disagree with what is drawn — the fault `Chrome` exists to prevent. So the share is capped at what leaves the columns those rows, and floored at `FRAME_ROWS`, since expanding must never shrink the frame. On a board too short to divide, `enter` gives the collapsed height back rather than a height nothing measured. `the_expanded_share_is_bounded_at_both_ends` sweeps every height from 4 to 60, tabbed and not, because one screen that happens to work says nothing about the arithmetic
- **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` then the page indicator on the bottom left. Every row spent here is a row of cards
- **The frame slot is shared between the two filters, not doubled.** One filter is on at a time, per `Filter`, so a tag frame is the campaign frame with its three slots filled differently: `#tag` in `tag_color` on the top border where the campaign's identity goes, how many tickets carry it on the bottom right where the standing goes, and the annotation in the prose rows. `FrameContent` is what the two are told apart into, and **`frame_content` is the one place they are told apart at all** — the borders, the colour, `q board`, the page indicator, the scroll and the focus are all the campaign frame's, and a second `match` on the filter below that is how the two frames come to behave differently in a way nobody decided
- **A tag frame draws the annotation, which is the payoff for declaring a tag.** Whoever is browsing a tag is deciding whether the next ticket belongs in it, and the sentence saying when the tag is appropriate is then on the screen at that moment rather than in `tags.md`, which they would have to know to open. An undeclared tag draws `NO_ANNOTATION` in grey, which is also the frame saying the word was never agreed on — the vocabulary file's own placeholder rather than the description section's, so the frame and the file say the same thing about the same tag. A tag declared with nothing said about it draws the same, since here the two have the same nothing to show; the picker's sections are where the difference is actionable
- **A tag has no id, so `y` on its frame copies the word.** A tag *is* its name, matched whole by `ls --tag`, so there are no seven characters to shorten and the `#` the border draws is not part of it — `--tag "#bug"` matches nothing. The footer says `y copy tag` there for the same reason: naming it an id would send the reader looking for a short id on a border that prints a word
- **The count on a tag frame is every column's, drawn or not**, the rule the standing holds. With the filter on, those columns *are* the tickets carrying the tag, so it counts what is below it without counting it a second way. The noun is spelled out and pluralised, because a bare number on a border says nothing about what was counted, and there is no derived state beside it: a tag is a word and not a piece of work, so there is no `[open]` to be in
- **The frame's page indicator goes on the bottom border beside `q board`, not on the top beside the title.** The title is cut against the border it sits on, so an indicator up there would shorten a long campaign name the moment its description grew past three rows; and the bottom right is the standing's, which is what the frame is *about* where the indicator is only where the reader has got to in it. Dropped before `q board` when the two cannot both fit, since with either filter on the footer's last slot names `ctrl-c quit` and the border is the only place that says `q` gives the board back
- **`Focus` is the third place the selection can be, and `Tab` is what holds it.** The board had a column and a card and `select_card` clamped at zero; up from the top card now reaches the frame and down returns to the column it left, since the column index is never what changed. Per tab beside the filter and the offset, so switching away and back returns to where the tab was left. `Focus::Frame` while no filter is on is the one state that must never exist — `select_filter` and `reload` are what keep it from arising, off `Filter::is_whole` rather than off which filter it is, since either draws a frame to hold it
- **`Tab::selected` hands back nothing while the frame holds the selection.** Every key that acts on a card has to answer for the frame. `←→` are inert, because the frame spans the width of the board and moving the column underneath would change nothing on screen. `y` is the exception that earns its place: it copies the campaign's short id, so `y copy id` means the id of the selected thing in every state the selection can be in. No card is drawn reversed there either, since that highlight is what says which ticket a key is about
- **`enter` routes on the focus through `Board::toggle_focused`: the frame's height on the frame, the overlay on a card.** It used to be inert on the frame for free, because `Tab::selected` hands back nothing and `toggle_detail` therefore had nothing to open. That is no longer an answer, and the routing is in `Board` rather than in the `main.rs` arm for the reason `dismiss` and `scroll_page` are
- **`q` does not gain a layer for the expanded frame, and up and down do not take it back.** The expanded frame is the frame at its other height, not a thing laid over the board, so `q` goes on taking the campaign filter off from either height and `enter` is the only key that undoes what `enter` did. The height outlives the selection for the same reason: it is a view of the campaign the reader chose, so the columns stay short with the selection on a card. `Tab::expanded` sits beside the filter and resets where `select_campaign` and `reload` reset the focus and the offset — a different campaign opens collapsed and at the top of its own description
- **The toggle re-clamps the frame offset, through `scroll_frame(0, screen)`.** A taller viewport has a smaller last offset than a shorter one, so where the reader was can end up past the end of the frame they just asked for. The draw clamps on its own geometry either way, but the stored value has to be clamped too or the next `pgup` counts down from a number the frame never showed. A scroll of no pages is that clamp and nothing else, which keeps it in the one place it lives
- **The frame is out of reach from under an open ticket.** With the overlay open, up and down step through the tickets and it follows, so a selection that reached the frame would have to either close it on an arrow key or leave it showing a ticket nothing is selecting. `an_open_ticket_keeps_the_scroll_keys_from_the_frame` builds that state by hand for exactly this reason: the precedence has to hold whether or not a keypress can reach it
- **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` and `t` are named in the footer only on a closed board with nothing filtered**, which is where a reader has to find them. Over an open ticket and on a filtered board they are left out: the frame's border then says how to put the filter away, and the row has no cells to spare. The tag used to be drawn on that row in its own colour, for want of a frame to draw it in, and 2a83bd4 took that away rather than saying it twice. 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
- **The footer has three states, because the selection has three places to be.** An open ticket, the frame, and the cards. On the frame it names `↓ board`, `enter expand` or `enter collapse`, the two scroll keys and `y copy id` — `y copy tag` on a tag frame — and leaves out `←→` because they do nothing there. It has to say which way `enter` goes, since the key is a toggle and the frame is always at one of its two heights. `↑ frame` is not named on the board, on the same trade `c` is dropped on: the frame is drawn directly above the columns and up is the key that reaches it. Nor is the way to collapse an expanded frame named from the cards, which is the same trade again — the frame is right there and `↑` reaches it
- **`picker: Option<Picker>` 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 `~<id>` fallback would print it twice and say nothing the second time
- **The picker draws two sections, open campaigns above completed, and truncates the completed tail.** One flat list by title put the finished campaigns among the open ones forever, and the tail only grows, so on a board that has run for a while the campaigns worth picking were pushed towards the bottom of the box and eventually off it. Open keeps the index's order, which is by title; completed is by `Created At` newest first, because what a reader recognises about a finished campaign is that it was finished recently. `COMPLETED_SHOWN` of them survive, behind a grey line naming how many older ones are being kept back — rows that are simply gone read as a board that never held them. An unstamped campaign sinks below every stamped one, the rule `by_status_order` holds for a column
- **`picker_list` is the one place that decides what a picker row is**, and `Picker::row` counts *drawn* rows. The sections reorder the campaigns and add rows of their own, so `Tab::campaigns` and the drawn list agree about no number past the first heading, and a row number that meant one thing to the draw and another to a keypress is how a highlight comes to name a campaign nobody chose. The list is derived on every draw and every keypress and never held, which is what keeps a campaign filed elsewhere reaching an open picker on the next tick
- **A heading is drawn only over rows that exist**, the bargain an untagged card's label row already makes, and it says which kind its rows are for as long as they are there — which is what a query filtering down to completed campaigns alone has to go on saying
- **`open` and `completed`, not `open` and `done`.** The split is taken from `Standing::state`, so the section a campaign lands in and the state the frame draws cannot come to disagree about what finished means, but the word is the section's own: a campaign sits in no status directory, so it is not *in* done the way a ticket under that heading is. A campaign with no members is neither, per that method, and lists as open — completed means every member is done, and it holds none to be done
- **Headings and the truncation line take no number: the highlight moves over campaigns only.** `stepped_picker_row` walks past the chrome rather than stopping on it, since a highlight resting on a heading gives `enter` nothing to do, and a step that runs out of campaigns is no move at all, the way a card at the end of a column clamps rather than cycling
- **`/` in the picker is the key it already is on the board**, and `picker_key` can take it because printable keys used to fall through `_ => {}`. Typing filters case insensitively against the short id, the codename and the title — the three things the row draws and the three a campaign is chosen by. Not the summary: a query that matched prose would answer `disk` with every campaign whose description mentions one. **An empty query matches everything**, the opposite of `first_match`'s answer and right for the opposite reason: a jump with nothing typed has nowhere to go, while a filter with nothing typed is not filtering, and pressing `/` must not empty the list
- **A query turns the truncation off**, which is the point of having one: the campaign a reader is searching for is exactly the one the truncation hid
- **The query is a layer, and `esc` takes it off before it takes the picker off**, the order `dismiss` closes the board's own layers in. So the list is whole again after that press, not still filtered with nothing on screen saying why. Movement and `enter` stay live under an open query, because a filtered list nothing can move in is a list nothing can be chosen from; every *printable* key goes into the buffer, so `q` types and so does `j`
- **The highlight follows its campaign, not its row number.** `place_picker` takes a uuid, the answer `Tab::campaign` already gives for the filter: typing, clearing the query and a tick that finishes a campaign all reshape the list, and a number kept across that names whichever campaign now sits at it. One the list no longer holds drops the highlight to the first row that does, which is where an incremental filter puts it. `reload` reads the highlighted uuid before the lists are rebuilt and puts it back after
- **A miss is a row in the box, `no match` in brightred**, where the search prompt puts its own, and `enter` on it leaves the picker and the query exactly as they are so the query can be corrected in place. An empty box says nothing about why it is empty
- **The picker's footer becomes its query**, the trade `draw_search` makes: with every printable key going into a buffer, a list of keys describes nothing that works. `/ search` is named only on the closed query, and the open one names what `esc` does to *it* rather than what it does to the picker
- **The title says both counts while a query is open**, `campaigns (2 of 6)`. The bare total is what the box is, but over a list a query has cut down it is a lie about what is on screen
- **Every campaign's standing is settled at reload, in one pass over the cards.** `standings_of` counts the cards naming each uuid off the columns the reload is already holding, which is what `Standing::of` builds for `campaign ls` without the walk of the status directories that one pays *per campaign*. A keypress must not pay that, and the picker needs every campaign's standing rather than just the selected one's, since the split is what it decides. Counted before the campaign filter is applied: how far a campaign has got is not a question about what the tab is showing
- **`Tab::standing` is gone with it.** The frame's standing is the row's, because two counts of one number are two numbers free to drift — the rule `wrapped_height` holds for the scroll. `the_standings_are_read_when_the_cards_are_and_not_per_draw` takes the status directories away after the board is built, paired with `a_member_finished_after_the_board_was_built_completes_its_campaign` for the reason the comment count's two tests are paired: a standing that never asked the filesystem again would pass the first by never changing
- **`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 history. 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
- **The mark goes after the id, not before it.** Ahead of the id it would push every id in the column out of line whenever one card was blocked, which costs more than one card's state is worth. It is measured before the project label and the due date, so both give way to it: those are context for a ticket somebody can start, and this is the one thing on a card that says not to. Dropped whole when the row cannot hold the identity and the mark together, the rule a corner follows
- **`blocked` is on `Card`, not on `TicketItem`.** The answer lives on two tickets at once, so no card can reach it alone, and it is settled at reload the way `project` is. What `collect_ticket_items` fills is the ticket's own `uuid` and its `blockers`, both read off the file it is already holding; `mark_blocked` then walks the columns once for a uuid-to-status map and once to answer every card. No file is read twice and nothing is asked per draw
- **A blocker the board does not hold marks nothing**, the answer `mv` already gives a dangling uuid. A Relations section that cannot be parsed reads as no blockers, the exception `detail_of` makes for the same reason: `show` and `mv` are where a hand-edited file is reported, and a board that will not draw because one ticket is malformed is the worse failure
- **The merge carries the flag rather than recomputing it.** `relate` resolves its target inside one `.worklane`, so a blocker in another project is not a relation anything can record; resolving over the merged columns would let one project's uuid match another project's ticket. That is b8ce18c's fourth plan step and the answer is no
- `project_label` takes the width the row has already spent, measured off the spans, rather than adding up the widths those spans are supposed to have. The hand-written version left out the space after the priority mark, so a cut label was handed one cell more than the column had; `the_project_label_leaves_the_row_inside_the_column` pins it
- `due_date` cuts a due value back to its date only when it has one. The field is not validated (daa0e79), so it can hold a time or free text, and taking the first word regardless would turn "next friday" into "next"
- **The terminal columns are hidden until `d` asks for them, one step at a time.** Not a new opinion: `ls` already counts both in its summary and leaves them out of the listing. Done only grows, so a quarter of the width was going to the column least often read, and discarded arriving made it two. So `d` rotates three states — hide both, show done, show both, and back around — through the `Visibility` enum on `Board`, discarded last in the rotation because it is the least likely thing to be looking for. The footer names what the *next* press does and carries the count of the column still hidden, which is the board's version of that summary line. Hiding is a prefix of the columns: done and discarded are the last two in what the board draws, so revealing either appends it and the columns before keep their indices
- **Hiding is a change to what is drawn, never to what is read.** `reload` still scans the done and discarded directories and `digest` still watches them, so the footer counts are right and revealing either column needs no rescan. Do not "optimise" that into a conditional scan
- `visible()` returns a prefix of `columns`, not a filter, which is what keeps `column` and `offsets` valid as indices into either. It is derived from where `DONE` and `DISCARDED` actually sit rather than assuming positions, and `the_terminal_columns_are_last_in_the_order_drawn` pins the assumption. A status inserted after discarded would otherwise hide two columns in silence
- Hiding the column under the selection moves the selection to the last drawn column and **closes an open detail view**. The alternative, refreshing the modal onto whichever ticket the selection landed on, swaps what someone is reading without saying so, which is how a person acts on the wrong ticket. Showing another column is a no-op for the selection, since a column is appended rather than inserted
- The choice is not remembered between runs. worklane has no config file and one flag is not a reason to start one; if it should persist, that is its own ticket
- **Assert a column heading against the top border row, not the whole screen.** The footer names done too, so `screen.contains("done (0)")` passes on the footer whether the column is drawn or not. Three tests went vacuous that way the moment done was hidden; `headings()` and `footer()` exist so the next one does not. `headings()` locates the row through `board_area()` rather than taking row zero, since the tab row sits above it when more than one board is monitored
### The Search Prompt
- **`search: Option<Search>` is the whole mode**, the shape `detail` uses: "the prompt is open" and "what is in it" cannot disagree, and closing it leaves nothing to reset. `Search` also carries `missed`, set when enter found nothing and cleared by the next edit, since the message is about the query that missed
- **The prompt swallows every key it is given.** `Board::search_key` runs ahead of the action arms in `main.rs` and reports what it took, rather than every arm below asking whether a search is open. Typing `d` into a query must not toggle done and `q` must not quit; with no prompt open it takes nothing, so the dispatch is unchanged for every other state. The rule is on `Board` for the reason `dismiss` is: the arm is not reachable from a test
- **`ctrl-c` is the one key it declines**, because a terminal application always honours it and a prompt that ate it would leave no way off the board. Every *other* control combination is swallowed and does nothing: it must not type its letter, and it must not fall through either, since the action arms match on the code alone and `ctrl-d` would reach the one bound to `d`
- **Esc is consumed by the search before it can mean anything else**, which is the collision e7612de left behind: `esc` and `q` close the overlay, and both have to lose to an open prompt. It falls out of the pre-branch rather than being ordered by hand
- **`first_match` searches the *visible columns*, every card in them, not the rows on screen.** A query that answered differently on a tall terminal and a short one is not a search, and the jump scrolls the match into view anyway. Hidden columns stay out: with done hidden, a match there would put the highlight on a ticket that is not on the board. Reading order is column by column, then top to bottom
- Id and title only, per 3b16540, both lowercased. The title has to be case insensitive to be worth typing, and giving the id the same treatment lets a pasted id match whatever case it was copied in. An empty or all-space query matches **nothing** rather than everything
- **The jump goes through `select_at`, the tail `select_card` already used.** `follow_selection` scrolls the column the card is in, and the offsets are per column and on the `Tab`, so a jump across columns moves the right one; `refresh_detail` keeps an open overlay on the ticket the selection names. A second version of either is how a jump comes to scroll differently from the arrow keys
- **A hit closes the prompt and a miss keeps it open**, marked, with the selection untouched. The query can then be corrected in place instead of retyped from `/`. Doing nothing visible is what makes a reader retype a query that was already right
- **The prompt takes the whole footer row**, because the key list it replaces describes nothing that currently works while every key is going into the buffer. The typed query is drawn in the default foreground and the keys in grey: one is content, the other is chrome. `no match` is brightred beside the query it is about, since grey chrome is what a reader skips
- **The real terminal cursor goes after the query**, not a glyph standing in for one. ratatui shows the cursor only for a frame that asked for it, so `set_cursor_position` is also what says "you are typing" while the query is still empty. Clamped to the row, so a query longer than the terminal leaves it on the last cell
- Both closed footers name `/`, since the jump works with a ticket open as well: it moves the selection and the overlay follows
- Out of scope on purpose, each its own ticket once the input mode exists: `n` and `N` for the next and previous match, searching the description, tags or owner, regex, and filtering the board down to matches rather than selecting one
### The Copy Key
- **`y` copies the selected card's short id, over OSC 52 written by hand.** The board is where a ticket is found and the CLI is where it is acted on, and the only thing joining them was seven characters retyped off the screen. `y` reads as yank to the readers a keyboard board is for, and was the letter left: `q`, `esc`, `enter`, `space`, `hjkl`, the arrows, `pgup`, `pgdn`, `tab`, `backtab`, `d` and `/` were taken
- **The mechanism was chosen against ssh**, which is where a board is often read. An escape sequence is the only one of the three ways that crosses the connection, since it is the terminal at the reader's end that owns the clipboard. A crate (`arboard` and its kind) wants X11 and Wayland libraries at build time, and on X11 the selection belongs to the process that set it: copy an id, quit, and the paste buffer is empty, which is precisely this flow. Shelling out to `wl-copy`, `xclip` or `pbcopy` is platform sniffing plus a process spawn, and does nothing on a machine where none of them is installed or on the far end of a connection. crossterm 0.28 is what ratatui 0.29 pins and it ships no clipboard command, and the backend types have to match whatever ratatui pins, so a newer crossterm cannot be picked up on its own
- **The cost is paid knowingly: a terminal that ignores OSC 52 ignores it silently**, and tmux needs `set-clipboard on`. What `clipboard::copy` reports is whether the sequence was written, not whether it was honoured, and the footer message says no more than that. There is no reply to read: the query form of OSC 52 is refused by most emulators as a security matter, so nothing better is available to us
- Base64 is twenty lines here rather than a dependency, because the only thing that goes through it is a seven-character id. Pinned on the RFC 4648 vectors, which cover both padding forms, since a wrong encoder would put plausible-looking rubbish on the clipboard
- **`c` and not `p`**: the clipboard proper, not the X11 primary selection, since this is pasted into a command line. Terminated with BEL, which is what tmux documents and what every emulator that implements this at all accepts
- **What is copied is `ticket.id`, the seven characters the card prints**, not the full uuid: they are what stops the retyping and what `show`, `mv` and `comment` all resolve. Decided by `Board::copy_text` rather than inside the arm that copies, so the string is a question the suite can ask without a clipboard. `None` on an empty column, since an empty string would take away whatever the reader had there and give nothing back
- The project is left off even on the merge tab, where the id alone is not an address. This goes onto a clipboard to be pasted into a command line, and a second word in it would have to be deleted every time; running the command in the wrong project fails to resolve rather than acting on the wrong ticket
- **The clipboard is handed to `Board::copy_selected_id` as an argument**, `clipboard::copy` from the dispatch and a closure from a test. That is what makes both answers drivable, and it keeps the terminal write out of the board state
- **A failure is said in the footer, not returned.** There is nobody above it to handle one: the board goes on being drawn, and an error swallowed there would look exactly like a copy that worked until the paste came out wrong
- **`Notice` is the board's one channel for saying something in words**, since a copy leaves nothing on screen to look at. `failed` means "nothing reached the clipboard" rather than "an error occurred", so an empty column and a refused write are one answer to the reader, both in brightred for the reason `no match` is
- **It takes the whole footer row**, on a weaker reason than the prompt's: every key still works while a notice is up. It is that a message squeezed in beside the key list would move every key in it, and the row is the only part of the board that is not a ticket. Drawn after the prompt, which is an input and cannot be covered
- **The notice is cleared by the next keypress, not by a timer.** No clock on the board and no wakeup in the loop, and the moment the reader does anything else the message has been read or was never going to be. Doing nothing leaves it up, which is the one state where it is still worth reading. `Board::clear_notice` runs ahead of `search_key` as well as the arms, since a key typed into a query is still a key, and it must never move into `tick`: the board redraws four times a second and a notice cleared there would never be read
### The Relations Block
- **One builder, two painters.** `relation_rows` decides which edges there are, what they are called and which direction comes first; `relation_cells` decides the layout, the mark and the colours; `paint_cells` turns cells into escapes for the CLI and `span_of` turns the same cells into ratatui spans for the board. Two builders producing one block in two shapes is a pair free to disagree about ordering or padding, which is what this shape exists to prevent
- **`Cell` is the unit both renderers take**: a run of text and the colour it is drawn in, `None` for the default foreground. The same trick as the palette itself, where `Color::ansi()` and `From<Color> for ratatui::style::Color` keep one colour from existing for one renderer and not the other
- **`reference_cells` is the one spelling of a cross reference.** The relations block and the Campaign field both go through it, so a dangling reference reads the same way wherever it is shown. There was a `reference_cell` beside it that painted the cells for the CLI; once the whole body became cells the Campaign field stopped needing a string and it was the last caller, so it is gone
- **A row carries two marks, kind then status**: what sort of edge this is, then how far the ticket at the other end has got. `blocked by × ◐ (6ce2c47) Title`. Two questions are asked of this block and one glyph could not answer both: which rows hold this ticket up, and whether the ones that do are finished
- The status went through one bad shape first. It was a rising bar, `▁▄▆█`, as the only mark, which read as an undifferentiated column of blocks and left the kind to five long words that blur when a ticket carries several. Then the kind took the column alone and the status was lost. Both, in that order, is the answer
- **Both directions of a kind carry one mark.** `blocked by` and `blocks` are the same edge read from two ends, and the label is what says which end you are on. `both_directions_of_a_kind_carry_one_mark` pins it
- **`×` is `BLOCKED_MARK`, the same constant a held-up card draws**, in the same brightred. On a card it says this ticket is held up and in the block it says this edge is what holds one, which is one word, so one glyph and one definition. It lives in `util.rs` for that reason, not in `tui.rs` where the card is
- **The kind marks stay out of the priority vocabulary**, which owns `●◐○·`, and `no_relation_mark_is_a_priority_glyph` pins that against every level. They are the arrows the footer already draws, so they render wherever it does
- **The status marks are those very circles, and what keeps them from reading as a level is width**: the meter is always two cells and a status mark is one. `the_status_mark_is_one_cell_where_the_meter_is_two` pins both halves. A card carries the meter and never a status mark, and the block carries the status mark and never a meter, so the two never sit in one column
- **Both marks go ahead of the id**, where they describe the target rather than the row. Every row carries both, so nothing is pushed out of line the way the card's blocked mark would have been, which is why that one sits after the id and these before it
- **The kind mark survives a target the board cannot find and the status mark cannot**, since a kind is read from the ticket's own file and a status from the board. `?` holds the column so the id does not move, and `_missing_` in grey is what says the target is gone
- **Committed and reviewing are told apart by colour alone**, both being `◐`, so a pipe cannot tell them apart: `should_use_colors` is false and both read as under way. Accepted, because `●` and `○` are the two answers usually wanted and `show` on the target settles the rest, and `assets/SKILL.md` says so outright rather than leaving an agent to infer it. Do not fix this by giving one of them a colour that means something else
- `RelationTarget` carries the title and the status in one `Option`, because they come from the same lookup and are absent together. It was taken out when the mark keyed on the kind alone and put back one commit later, which is the cost of a field nothing reads: correct at the time, and churn either way
- **`show` and the board carry the same mark**, decided rather than left to be discovered: the rows are one builder, so giving the CLI the mark cost nothing, and two views disagreeing about what a relation shows would be the kind of difference nobody can explain later. That makes it a change to what the CLI prints, so it is a minor
- **`Resolved.relations` is rows, not a rendered block, and `Resolved.campaign` is cells for the same reason.** An escape sequence in a ratatui paragraph is drawn as literal bytes (6d327df), so nothing in `Resolved` can arrive pre-painted. This was the asymmetry the two renderers needed while the rest of the body was a painted string; there is no asymmetry left, since `content_parts` paints nothing at all
- **`BodyPart` splits the body rather than building it twice.** It is `Cells` or `Relations`: everything outside the block is laid out once, by `content_parts`, and `content_trim` is that run through `paint_cells` while the board is the same cells run through `span_from`. `Body` is the accumulator, so a caller pushes cells and rows without tracking which it pushed last, and it merges a run into the trailing cell when the colour matches, because the board draws a span per cell and the body is pushed a character at a time in places
- **`Detail.body` is a `Text`, and it is the only thing measured.** `last_offset` and the `Paragraph` both take it, so the clamp cannot wrap the body differently from the draw. `Detail::plain()` flattens it for the suite and is `#[cfg(test)]`: a second representation carried alongside the spans is a second thing to disagree
- `detail_body` closes a line only where the text says, so a part that does not end on a newline runs on into the next one. The seam between text and rows is wherever the body put it rather than wherever a part happened to end. It now splits **per cell** rather than per part, since a `Cells` part holds many runs and a newline can fall inside any of them
- **The whole overlay body is coloured now, and `content_parts` paints nothing.** The block used to be the only coloured part, because it arrived as rows while everything else arrived as a painted string; e4d0bb7 gave the rest the same `Cell` treatment. So the headings, the plan numbers, the criteria numbers and marks, the bold runs, the field names, the priority glyph, the tags and the grey unset values are one layout that `show` paints and the board styles. Do not reintroduce a `paint` call in `content_parts`: the flat overlay was exactly that, a renderer forced to ask for the unpainted string because the painted one held escapes
- **`colored` still reaches `content_parts`, and it no longer means paint.** It says whether *this* renderer can carry a colour at all, and one thing turns on it: `**bold**` gives its markers up to the colour that replaces them, so a renderer with none has to keep them or the emphasis is lost rather than moved. The board passes `true`, `content_trim` passes the CLI's decision, and a piped `show` still reads its markers. Nothing else in the body consults it
- **Magenta means bold, and `span_from` is where the board learns that.** `Color::Magenta.ansi()` is `\x1b[1;35m`, so the CLI draws every bold run bold as well as magenta, and `From<Color>` can carry only the colour. Without the modifier added on the board's side the same cell would be painted two ways, which is the one thing the shared layout exists to prevent
- **The conversion is pinned from both ends.** `show_prints_the_same_body_it_printed_before_the_cells_conversion` holds a body with one of every painted run and asserts the CLI's output byte for byte, written from what it printed before the change, so the risk in sharing a layout, the CLI's output drifting to suit the board, fails the suite. `the_whole_body_is_styled_in_the_overlay_and_no_escape_reached_it` is the other end and is paired the way the guideline demands: a renderer that dropped every colour passes the absence, and one that went back to painting strings passes the presence
- **The history block arrives as cells too, so nothing in the overlay is flat.** `history_cells` lays the block out once; `format_history` is those cells through `paint_cells` and the board pushes the same ones as a `Cells` part after the body, since the log lives outside the ticket file and `content_parts` never sees it. Pinned from both ends the way the body is: `show_prints_the_same_history_it_printed_before_the_cells_conversion` holds the CLI's output byte for byte, and `the_history_block_is_styled_in_the_overlay_and_no_escape_reached_it` pairs the presence with the absence (f3e099e, closing the gap e4d0bb7 left)
### Finding the Board
- **`find_worklane_dir` classifies the entry before it follows it.** `exists()` follows a link, so a `.worklane` that was a dangling symlink answered the same as no `.worklane` at all: the walk carried on up the tree and the first board above the project became the one every write landed in, silently. `classify` reads `symlink_metadata` first and answers one of four, `Absent`, `Board`, `Dangling` or `NotADirectory`, and **`Absent` is the only one the walk carries on from**. A `.worklane` that is there but unusable is this project's board and is reported, not handed upward
- Anything other than `NotFound` from `symlink_metadata` is an error rather than an `Absent`. Reading a filesystem that could not answer as nothing-there is how the walk-past worked in the first place
- The dangling failure **names the target and says the boards repo may not be cloned**, and deliberately does not say to run `worklane init`. Once the boards live outside the project a dangling link is an ordinary state, what you have before the boards repo is cloned and after a board directory is renamed, so "no board found, run init" points at the wrong problem
- **A link that resolves is indistinguishable from a real directory, and what comes back is the link rather than its target.** `.worklane/backlog/*.md` has to read the same either way and nothing downstream learns whether the board is local, which is the property the shared-boards layout rests on
- A regular file at that path is an error as well. It is a plausible future pointer form, and reading it as one is that change's decision to make; stepping over it and writing to a board above is the one answer that is wrong today
### Monitoring Several Boards
- `worklane tui <path>...` takes any number of paths, each resolved through `find_worklane_dir` the way the working directory is: the first `.worklane` at or above it. No path is the working directory, so a bare `worklane` and `worklane tui` are unchanged
- The failure **names the path** that had no board, since with several arguments "No .worklane directory found" does not say which one was wrong. Only when a path was given: a bare `worklane` has no path to name and keeps the message every other command gives, which is what its integration test asserts
- Two paths inside one project resolve to the same `.worklane` and are monitored once. `projects()` dedupes on the resolved directory, not on the argument
- **`Tab` owns the selection**, `column`, `card` and `offsets`, not `Board`. Sharing them across projects would point the selection at whatever unrelated ticket sat at the same place in the tab you switched to. `Board::current()` is the tab in view, and `visibility` stays on the board because it is a preference about the flow rather than about a project
- The tabs are fixed for the run: a project cannot be added or dropped without restarting, so `Board::new` builds the tab list once and `reload` only refills each tab's columns. `reload` clamps **every** tab, and `select_tab` clamps again on arrival, because done may have been hidden while another tab was in view
- The merge tab goes **first** and is where the view opens: it is the reason to monitor several boards at once. It is materialised in `reload`, from the cards already read, rather than computed per draw — the same reason the criteria count is filled in `collect_ticket_items`
- The merge is **sorted**, through `by_priority_then_title` in `util.rs`, not concatenated. An overview whose order depended on the order of the arguments would bury one project's p1 under another's p5. It keeps priority then title where every other column takes `by_status_order`: the merge spans statuses, so no single entry stamp governs it
- `Card` wraps a `TicketItem` with the project it came from, `Some` only on the merge tab. Decided at reload rather than passed down to `card_lines` as a "which tab is this" flag. `TicketItem` is therefore `Clone`: the merge holds a second copy rather than re-reading every tree
- **The project follows the id, on the card and on the overlay border.** Across boards the id is not an address: two projects can hold the same title, and seven characters do not say where they live. `project_label` takes what the row has left after the mark and the id and ends in an ellipsis, and it is measured before the due date, so on the merge the project wins the narrow column and the date is what `corner_line` drops
- `tab` and `shift+tab` cycle rather than clamp, unlike the cards and columns: a row of tabs is a ring, and there is no end of a list to run off. Both were free of every other binding — the columns took `hjkl` and the arrows
- **The tab row is drawn only when there is more than one board**, so a single board is the view it has always been. `screen_rows()` gives it `Length(0)` otherwise, which keeps the row indices the same for both cases and is shared with `card_width` and `column_text_height` for the reason `column_areas` is: geometry reproduced by hand drifts from the draw
- `digest_of` hashes each board's `digest` into one value, so a change in any of them redraws. Do not watch only the first
### Who Wrote an Entry
- **Identity is supplied, not detected.** Every option that needs no cooperation fails: a harness variable such as `CLAUDECODE` names the tool rather than the instance and breaks across versions, walking the parent process is platform specific and also only names the harness, and a terminal check separates interactive from not, which a human piping output is too. So the actor is `WORKLANE_ACTOR`, set once per session, with `--actor` as the per-call override
- **Precedence: flag, then `WORKLANE_ACTOR`, then `get_git_user()`, then `unknown`.** `resolve_actor` is the only caller of `get_git_user` for an entry's author, and every entry the CLI writes goes through it. The two halves are separate pure functions, `session_actor` and `entry_actor`, tested without touching the process environment for the reason `colors_wanted` is split that way
- **The session half is cached in a `OnceLock`, the way `should_use_colors` is:** neither the variable nor the git user can change mid-run, and the fallback costs a `git config` subprocess. `session_actor` takes the git user as a closure so that subprocess is not run when the variable already answered
- An **empty `WORKLANE_ACTOR` counts as unset**, the convention `colors_wanted` follows for `NO_COLOR`, so a wrapper script can clear an inherited one. Whitespace counts the same, since a shell quoting a missing value writes one
- **The actor is free text, checked against nothing**, like the `chown` user: there is no registry of actors, and the same reason `ls --tag` refuses to validate a tag
- **It was `comment --owner`, renamed with no alias.** Owner is the ticket's assignee and has one writer, `chown`; this names the writer of the entry, which is a different field. Pre-1.0, and two names for one thing is what splitting `set` and `chown` avoided. `the_owner_flag_is_gone` pins the refusal, since an alias kept "for now" is what makes the wrong name permanent
- **`add --owner` and `campaign add --owner` still default to the git user, deliberately.** Those write the assignee, and a ticket an agent files is work for the person whose board it is; attributing it to the agent would put its name in the Owner column of everything it reported
- **An entry does not record whether the call had a terminal.** It is the one agent signal that needs no cooperation, so it was worth considering, and it was rejected: it cannot name an actor, a human piping output produces the same value, and once the actor is explicit the extra field answers no question anybody asks
- **Set it in the agent's configuration, not per call.** `env` in `~/.claude/settings.json` reaches every command Claude Code runs. opencode has no equivalent: its config is JSON with no `env` block for the tools it spawns, so it inherits the environment it was started with, which means a wrapper or a shell function around `opencode`. Both are documented in `assets/SKILL.md` rather than assumed
### The History Log
- **The log is the comments directory with the kind named in it.** It was already an append-only log with one event kind: one file per entry under `.worklane/history/<uuid>/`, stamped to the microsecond and written with `create_new`. Adding `status`, `owner` and `tags` beside `comment` needed no new mechanism, which is why there is no separate journal file and no database
- **What is not logged, deliberately:** ticking or unticking a criterion, and edits to the title, description, plan, priority or due. Those change often and a log of them is noise. When one of them matters, whoever made it adds a comment saying why. Do not add a kind for a field on the grounds that it is cheap to record: the cost is that the log stops being worth reading
- **`--clear` is logged, since it is the same field going somewhere.** `chown --clear` and `set --clear tags` write an entry whose after-value is the sentinel the ticket now holds, `_Not set_` or `_None_`. The values are recorded verbatim rather than translated into words this module invented, so an entry reads the way the field it came from does
- **The kind is read from the file and only counted from the filename.** `parse_entry` matches the leading marker; `kind_from_stem` splits the stem for the card's counter, which must not read four hundred files to draw a board. A name says what a file is for a listing, and the file says what it is for a reader
- **A file with no marker is a comment**, which is what every entry written before the kinds existed is. That is the whole of the compatibility, and it is why there is no migration command: `entry_content(Kind::Comment, ..)` is byte for byte what `cmd_comment` wrote before this module, so nothing is rewritten and either version can read the other's board
- **The old directory is adopted, not migrated.** `adopt_comments` renames `comments` to `history` on the first access, and the reader, the writer and the counter all call it, so no caller has to remember it and no path reaches the log without it. **A board holding both is refused**, naming both paths: only worklane writes there, so it cannot reach that state on its own, and picking which of two entries with one name survives is not a decision to make silently. The counter swallows that error, because a count is drawn per card and a board that cannot be adopted must not take the TUI down; the next write reports it
- **An entry is written after the edit it describes, never before.** A refused move, a refused chown and a failed save log nothing, which is what `a_refused_move_writes_nothing` and `a_failed_edit_writes_nothing` pin. The cost of that order is that a failed entry write leaves the edit in place and reports the failure, which is the right way round: the ticket is the record and the log is the story of it
- **A no-op edit writes nothing either, and `apply` is what decides that** for `set`: a field it did not record as changed was already what the call asked for. `cmd_mv` and `cmd_chown` have their own early returns and sit behind them
- **The stamp leads the filename and the kind follows it**, so the lexicographic sort in `read_history` stays chronological however many kinds there are. The collision suffix goes last, after the kind, and is a number, so it matches no slug and the counter skips it
- **A mechanical entry renders as one line and a comment as it always did.** A field change is one fact, and a paragraph for it would bury the comments it sits between. The labels are padded to `Kind::LABEL_WIDTH`, `campaign` being the longest of the four, so the bodies line up under each other
- **A campaign entry records `Campaign::name`, the codename or failing that the title, never the uuid the field holds.** Settled when the entry is written, not left to the renderer: a log is a record, and resolving at read time would let an entry change meaning when a campaign is renamed. A `before` uuid the board no longer has reads `_missing_`, the way the Campaign field itself renders a dangling one, and a ticket never assigned starts from `_Not set_` (f774a33)
- **`--actor` is on every command that writes an entry**, spelled from one `ACTOR_HELP` in `command.rs`: a flag documented differently on each command reads as four flags. On `chown` it sits beside `user`, which is the ticket's new assignee — the two are different questions and that command answers both
- **`set --actor` reaches only the entry `--tags` writes**, since tags are the one field of that command's that is logged. Documented on the flag rather than left for a reader to notice from the absence of entries
### Shipping the Agent Assets
- The skill is embedded with `include_str!` from `assets/SKILL.md`, not copied by an install script. `cargo install` places binaries and nothing else, so an installed document that is not in the binary is a document that drifts from it
- **`assets/SKILL.md` is the only worklane skill document in this repo, and nothing may reintroduce a second.** There was one: `.opencode/skill/worklane-kanban-skill/SKILL.md`, 223 lines of the same document that nothing shipped and no test checked, and it drifted exactly as far as a copy nobody reads does. Its frontmatter still called the skill `worklane_kanban`, its examples still used short flags the CLI had stopped accepting, and it knew nothing about `relate`, `campaign`, `chown`, `check` or the four-status flow. It was **not** inert while it existed: `opencode debug skill` listed it, so an agent working in this repo saw two worklane skills and could load either. Deleted by b2c5531. A copy under `.opencode/`, in a second assets file, or in the README is the same mistake; the document has one home and `install-skill` is how it travels
- **One install path serves both agents:** `~/.claude/skills/worklane/SKILL.md`. Claude Code reads it, and opencode loads that directory as an external skill source alongside its own `~/.config/opencode/skill/`. Verified against opencode 1.15.10, whose built-in `customize-opencode` skill documents the table and whose `opencode debug skill` lists what it found there. Do not add the second path: it is two copies of one document, free to drift, for no gain
- `Asset` carries the content, the path under its root and the word used in messages, so `install-tool` adds an entry and its own root rather than a second copy of the compare-and-refuse logic. That is why the module is `install.rs` and not `skill.rs`
- `install()` takes the root as an argument. That is what lets the tests install into a temp directory instead of the home of whoever runs the suite, and the integration test redirects `HOME` for the same reason
- **A modified copy is refused, not overwritten.** Someone may have edited it on purpose, and the message names `--print` so it can be diffed and `--force` so it can be replaced. A read error is not treated as absent either: the write reports the real reason
- Three tests guard the document rather than the mechanism, and they are the ones that earn their keep: the frontmatter has to parse (both agents silently ignore a document without it), every `worklane <x>` the skill shows has to be a real subcommand, and every subcommand outside `NOT_FOR_AGENTS` has to appear in the skill. The last one catches a new command that nothing tells an agent about
- `install-skill` looks for no board. The skill is what teaches an agent worklane, so needing a `.worklane` to install it would put it out of reach exactly when it is wanted
- The **agent files** under `.opencode/` are the user's, not this repo's to ship. Do not embed or install them. `reviewing-agent.md` there is the prior art the review skill grew out of and is deliberately **left in place**: its content is now in `assets/REVIEW.md`, but deleting a file under `.opencode/` is not this repo's call. Whether the stale copies there go is b2c5531's question. The tool file is the exception and no longer lives there: it was `.opencode/tools/worklane.ts`, which meant it existed only inside a checkout, and it is now `assets/TOOL.ts` and shipped like every other asset
- **`install-skill` writes every shipped document, and the name narrows it.** One document teaches the CLI and the others teach a job done with it, so a person who learned the invocation before a document existed still receives it. Requiring a name per document would mean a new skill silently never arrives for anyone who does not read the changelog
- **`--print` requires the name.** It exists so a modified copy can be diffed, and a diff is against one document; printing them concatenated would be neither of them. The unnamed case errors with the list of names rather than guessing, the same choice the `comment --` body makes
- The refusal message names the document it is about, `install-skill worklane --print`, since with several installed "compare with --print" does not say compare what
- **A refused document does not stop the ones behind it.** The loop reports an outcome per document and the "pick it up on their next session" line is printed once, and only when something was actually written
- **A role skill is its own document, not a section of `SKILL.md`.** The frontmatter description is the whole of what decides whether a skill loads, and one description cannot name both "anything touching a ticket" and "only when a review is asked for" without fitting neither. It is also why the review document does not restate the CLI: it says to read the `worklane` skill too
- The review skill's own rules are guarded by `the_review_skill_keeps_the_decisions_that_define_it`, because each of them is a line an edit could drop without breaking anything: **the reviewer never ticks a criterion** (a tick is the implementer's claim, unticking is the review disagreeing, and one mark for both loses the disagreement), **never moves the ticket** (`mv` belongs to whoever does the work, the reviewer's half is the recommendation), and **never reviews the working tree when no commit names the ticket** (it says what it searched for and stops, since an untraceable ticket in `reviewing` is itself the finding)
- **The plan skill is the one that can do damage, so its rules are the ones under test.** `set --tags` replaces the whole field, so a sweep that restates a ticket's tags incompletely deletes the rest, and a due date is neither validated nor clearable. `the_plan_skill_keeps_the_rules_that_bound_a_sweep` pins propose-then-apply and those two traps, because a document that loses them still reads like a plan
- `.opencode/agent/feature-planner-agent.md` is **deliberately not folded into `PLAN.md`**. It decomposes a feature request into new tickets, which is intake; `PLAN.md` orders the tickets that already exist. Merging them would give one document two jobs and a frontmatter description that fits neither, which is the same reason the review skill is its own document
- **`install-tool` is a second command, not a flag on `install-skill`, because the two artifacts are not alike.** A skill is inert markdown that any agent can read and it reaches both from one path; the tool is executable TypeScript that reaches opencode alone. Claude Code has no directory it scans for a tool definition at all: `claude mcp add` with a `stdio`, `sse` or `http` transport is the only way a tool enters its tool list, and its plugin system adopts `agents`, `hooks`, `monitors`, `workflows`, `output-styles` and `themes` and nothing named tools. So an MCP server, a different artifact, would be what reached it. Verified against Claude Code 2.1.238
- **`tools_root()` follows `XDG_CONFIG_HOME`, `skills_root()` does not.** `~/.claude` is not an XDG path and opencode's config root is: `opencode debug paths` reports `$XDG_CONFIG_HOME/opencode` with the variable set and `~/.config/opencode` without. An empty value counts as unset, the convention `colors_wanted` follows for `NO_COLOR`. `opencode_tool_dir` takes both variables as arguments for the reason `colors_wanted` does, since a threaded test binary cannot mutate the process environment to reach one branch at a time
- **Singular `tool`, and it was measured, not guessed.** opencode 1.15.10 loads `~/.config/opencode/tool/` and `~/.config/opencode/tools/` both: each was served in turn from a directory outside any project and `/experimental/tool/ids` registered all eleven worklane tools. The singular is the spelling opencode's own documentation puts first, the way it writes `agent(s)` and `skill(s)`. `opencode serve` plus that endpoint is how to check this again; there is no `opencode debug tool` to ask
- **`worklane.ts` is the file name the tool ids are built from.** opencode names each tool as the file then the export, so the file's eleven `export const` lines become `worklane_add` through `worklane_uncheck`. Renaming the file renames every tool and every permission rule that mentions one, which is why `TOOL.relative` is pinned by a test rather than left as a detail
- **The tool needs nothing installed beside opencode**, which is worth stating because the file is executable and reads as though it wants a toolchain. It is loaded into opencode's own Bun runtime and the `@opencode-ai/plugin` import resolves there: a copy in a project with no `node_modules` anywhere above it registered all eleven tools, on a machine with no `bun` on `PATH`. c092ea7's criterion 6 named those two as runtime requirements and it was wrong about both
- **The closing line differs from the skills', and that is not a wording choice.** opencode reads its config once at startup and never reloads it, so a running one keeps the tools it began with; the skills' "on their next session" would be a claim that is not true here
- **The wrapper is behind the CLI and nothing guards it.** It has no tool for `relate`, `campaign`, `assign` or `tags`, so an agent holding the tools cannot reach campaigns or relations at all. `every_tool_the_wrapper_exports_is_a_real_subcommand` catches the drift in the direction that breaks at call time, a tool for a command that no longer exists, and deliberately not the reverse: the gap is real, nobody has decided to close it, and a test asserting it would fail on that decision rather than on a mistake
- **Installing it globally reproduces fb3dec6 for the wrapper.** Global tools apply in every project including this one, so once `install-tool` has run, an agent working on worklane uses the installed copy of `assets/TOOL.ts` and not the tree it is editing. Same trap as the `worklane` on `PATH`, second instance
- `every_agent_facing_subcommand_is_documented` stays on `SKILL` alone. It owns the CLI surface; a role document uses the handful of commands its job needs, and requiring the rest would fill a review document with `init` and campaigns to satisfy a test. The two checks that do run over every document are the frontmatter and that no document shows a command that does not exist
- **The README command table has the same guard, `every_subcommand_has_a_row_in_the_readme_command_table` in `command.rs`.** The skill and the table are the two places a command is discovered, one by an agent and one by a person, and the skill was the only one under test: `campaign` and `assign` shipped in 0.12.0 and were still absent from the table at 0.20.0, e6e3a1b, along with the `--campaign` flag on the `ls` row. It walks clap's own subcommands, one level of nesting included, against the `|` lines of `README.md`, so a new command fails the suite until the table lists it. `help` is excluded, being clap's. The tag subcommands are named in a `PENDING` list rather than skipped, since f7dd1a1 rewrites that row and emptying the list is part of closing it
### Color and Output
- Use `color_text()` for coloured output — it respects `should_use_colors()` (terminal detection), and `paint()` is the same with the decision passed in
- **`color_text()` is for the CLI's own printing only. Anything reachable from `content_trim` takes the decision as an argument and calls `paint()`**, because the board renders with colour off and an escape sequence in a ratatui paragraph is drawn as literal bytes. `nothing_the_body_renders_asks_the_terminal_for_the_colour_decision` scans this file and fails on a new caller; the allowlist is `ambiguous`, which builds a failed-search message for stderr
- A function that takes an `enabled` flag must use it all the way down. The inline pass honoured its flag on the early return and then asked `should_use_colors()` for the bold run, which made the flag a lie in half the function. The better answer, where it fits, is to take no flag: `ordered_cells` and `metadata_value_cells` return the colour rather than a decision about it
- **A test that asserts an absence has to be paired with one that asserts the presence.** The guard for this, an assert that the detail view holds no escape byte, could not fail: a test binary has no tty, so `should_use_colors()` was false and the leaking branch was never taken. The pair is now `content_trim(.., false)` has no escape and `content_trim(.., true)` still colours, which pins the flag as the only thing that decides
- **The palette is the `Color` enum, not a string.** `Color::ansi()` gives the CLI its SGR sequence and `From<Color> for ratatui::style::Color` gives the TUI its equivalent, so a colour that exists for one renderer and not the other is a compile error. The stringly-typed version needed a test for exactly that, and a missing entry silently produced an empty prefix, which is how `magenta` came to be undefined
- Reset color with `\x1b[0m` after colored text
- Bold uses `\x1b[1;35m` (magenta bold)
- Always test color output works correctly in both terminal and pipe modes
- `quiet_broken_pipe()` runs first in `main`, restoring the default `SIGPIPE` disposition. A truncated pipe therefore kills the process with signal 13, which a shell reports as 141, instead of making `println!` panic. Do not wrap prints to handle write errors and do not reinstate `SIG_IGN`; the exit codes are documented in the README
### Color Guideline
- UUID → red (31)
- Status → orange (33)
- Timestamp → cyan (36)
- Title → green (32)
- Unknown values (`_None_`, `_Not set_`) → grey (38;5;8)
- Priority ramp → brightred (1), red (2), orange (3), cyan (4), grey (5). Green is deliberately absent: it means title
- 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 `●` discarded, grey `?` for a target the board does not hold. Discarded takes the full circle of done in the grey of the untouched pile: nothing is left to do, and it is not an achievement. The *pair* is what has to be unique, which is the same bargain the two half circles already take, and `every_status_has_a_mark` pins it against `status_dirs`. 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
- Markdown link → cyan, markers and url kept. Not a new meaning for the colour: the plan numbers, the criterion numbers and the `relates to` mark are already cyan inside a rendered body, and a link is the same kind of thing, a pointer the reader may follow rather than a value. The url is not hidden behind the text the way a renderer would hide it, because `show` prints to a terminal worklane cannot assume will make it clickable, and a link whose target cannot be read is worse than a long line
- 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
- Chrome → grey, in the history block too: the kind label at the head of a mechanical row, and the `From` on a comment's author line. Both name their row rather than holding a value, which is what grey already says. The label was orange, which means Status everywhere else, so an `owner` or `tags` label claimed a meaning belonging to the value beside it
- **A value in the history block takes the colour it has in the metadata table three lines above.** A status is orange, a tags entry goes through the same `tag_cells` the Tags field does, a campaign codename takes `tag_color` bare the way `Codename` does, and `_Not set_`, `_None_` and `_missing_` are grey. An owner stays plain: a person's name is the one value the palette has no meaning for, and spending a colour on the field that needs it least is how a colour stops meaning anything. The block's job is to be scanned, and it is not worth scanning if it has a palette of its own to learn first
- History actor → its name through `tag_color`, the way a campaign codename is. Not a new meaning for a reserved colour but the existing use of the tag slots, a name that groups rows: one writer is one colour in every entry it wrote, so a reader sees who has been working a ticket without reading the same name four times. `claude`, `opencode` and a person each get their own
- History timestamp → cyan, and its own span. It shared one with the actor while the two were formatted as `name (time)`, which spent the timestamp's colour on a name. The parentheses are plain: they are punctuation, not chrome with something to say
- 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
- **The index is multiply-shift, not `% TAG_COLORS.len()`.** The length is a power of two, so a modulus keeps only the low three bits of the hash, and FNV-1a's low bits carry only the low bits of the input bytes: multiplication cannot move information downwards. Under a modulus every pair of tags differing above bit 2, `bug` and `BUG` among them, landed in one slot regardless of the rest of the string. It looked like a *good* palette on this board, two colliding cards out of sixty-four, because the vocabulary had been folded into a handful of slots. Taking the top bits of a 128-bit product uses the whole hash
- Eight tag colours means roughly one card in five shows two tags alike. That is arithmetic and is accepted: the colour groups a tag across cards, it does not tell two tags apart within one, and the tag text is beside it either way. Do not widen the list to chase the number on one board
- Grey is indexed colour 8 in the 256-colour form, not SGR 90 or 37. Both of those failed on a real palette: 90 leans on the bright-black slot and 37 can sit on top of the default foreground. `\x1b[38;5;8m` is byte for byte what crossterm emits for ratatui's `Color::DarkGray`, the grey frig and pantop use for dimmed rows
### Code Organization
- **`change` and `split_change` are a pair, and they live beside each other in `history.rs`.** The mechanical body is stored as one string, `before → after`, so painting the halves means splitting it, and the separator is a constant the writer and the reader share. A renderer with its own copy of the spacing would go on splitting on a separator the writer no longer emits, and would say so by drawing a whole body as one half. The split is `split_once`, so a value carrying the arrow itself keeps it
- **The history block indents by who is talking.** A comment's body sits at four spaces and the reason under a mechanical row at two; the author line stays at column 0 and is told from a mechanical row by its `From` and its colour instead. The rule a reader learns is that an indented line is somebody's own words and a line of values at column 0 is the tool reporting itself
- **`history.rs` owns the log end to end**: the path, the kinds, the parse, the write, the count and the render. It came out of `util.rs` and `handlers.rs`, where the reader, the writer, the counter and the renderer sat in three files and one of them was 5,500 lines. The test for the reason is the module doc: a reader asking what an entry is has one file to open, the way `campaign.rs` and `tag.rs` answer their own questions
- The body's painters return cells, not strings: `ordered_cells`, `inline_cells`, `metadata_cells`, `metadata_value_cells`, `tag_cells` and `push_heading`. `content_trim_colored` is the CLI entry point and `paint_cells` is the only thing that writes an escape. `colorize_line` is gone: it was a `pub` alias for the bold pass with one caller, and the only thing it added was asking the terminal
- **`inline_cells` walks the line once for both inline markers**, `**bold**` and `[text](url)`, rather than running one pass over the output of the other. A second pass would be scanning text that already holds escape sequences, and `\x1b[36m` carries an opening bracket, so the link scan would take the escape for markup. The source is the only string in which either marker means what it says. It was `colorize_bold` while links lived in a branch of their own in `content_parts`; that branch is gone, which is also what gives the criteria text and the metadata `Other` rows their links, since those already went through this function
- `show` renders the Metadata section as a two column table via `metadata_cells`, not line by line. Column width is measured on the raw field names in characters and the padding goes into a cell of its own, so nothing is ever measured with a colour on it: measuring a painted string counts its escapes towards its width. `paint()` is `color_text()` with the colour decision passed in, which is what lets a test render both ways in one process
- The title is printed once, by `cmd_show`. `content_trim_colored` skips the `# ` heading in the file content
- Rules under headings are measured on the displayed name in characters, never on the raw line or in bytes
- `resolve_ticket()` scans all status directories — it's the single source for ticket lookup by UUID prefix, title, or filename
- `parse_ticket_field()` handles extracting metadata values from markdown format
- `move_ticket_file()` stages the updated content in a temp file under `.worklane/`, renames it over the source, and only then renames the file into the target directory. Do not reorder these: renaming first and writing second leaves a ticket in its new directory claiming the old status, and writing to the target then deleting the source puts it in two directories at once. The temp lives outside the status directories so a leftover is never read as a ticket. A failure at the last step leaves the ticket in its old directory with a Status one move ahead, which the next `mv` corrects
- Field lookup, read and write, is scoped to the lines under the `## Metadata` heading and anchored to the start of the line. Prose above it is free text: tickets in this repo quote field markers in their descriptions, and an unscoped search reads or rewrites those instead. `set_status_field()` carries the same scoping
### Ticket Resolution
- `resolve_ticket()` returns `(status, title, content)` tuple
- 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)
- Never return empty strings for required fields — use the `NOT_SET` and `NONE` constants in `util.rs`, which are what `add` writes and what `--clear` puts back. `is_unknown_value` reads those two and nothing else
- **`-None-` and `-Not set-` are not unset, and re-adding them would be a mistake with a plausible story behind it.** They were accepted by `is_unknown_value` from the day it was written, by analogy with the `**-Status**` field name the `mv` splicing bug really did produce, c230d2c. But no version of this tool ever wrote a hyphenated *value*: `git log -S` finds both spellings in exactly one commit, the one that added them to the check. Dead from birth, and dropped by bdddc09. `a_hyphenated_marker_is_not_unset` is what stops the analogy being drawn a second time
- **The `**-Status**` repair in `is_status_line` is the opposite case and stays.** That corruption was real, `mv` wrote it, and the repair is what fixes a damaged ticket as it moves. Do not tidy the two away together on the grounds that they look alike
### Git Workflow
- Commit format: `([ticketID]) [short description]`
- Use `--fixup` for incremental changes
- Test before moving to reviewing status
### Version Bumps
- Before every commit, decide whether the change warrants a version bump in `Cargo.toml`
- Always ask the user to confirm the bump and its kind before making it — never bump silently, and never skip the question because the answer looks obvious
- **`make patch`, `make minor` and `make major` do the mechanics**, run after the commit is in: each bumps `Cargo.toml` and the `worklane` entry in `Cargo.lock`, appends `, and bump to <version>` to the commit's subject, folds the bump into that commit, and tags it. Bumping by hand is how a version comes to be left untagged, which is what the one action is for. It refuses on a dirty tree, on an already-tagged `HEAD` and on a `HEAD` that is already pushed, since each of those makes the amend lose work, orphan a tag or need a force push
- Pre-1.0, so: patch for fixes and internal changes, minor for a new command, flag or changed output, major only for a deliberate 1.0
- **Changed output means the CLI's output.** That is the surface scripts and agents read, so a changed listing, message or exit code is a minor. A change to what the board draws is a patch however visible it is, since nothing consumes the frame. See The Board View
- **Settling output that shipped one version ago is a patch**, not a second minor. 0.15.1 changed the relation mark 0.15.0 had just introduced, and 0.15.2 added the status mark beside it: the minor was the arrival of a marked relations block, and settling what it marks belongs to that. Three minors in an hour would tell anyone reading the tags that there were three features
- No bump for docs-only, tests-only or `--fixup` commits
- When one body of work spans several commits, bump once on the final commit rather than on each
- Every bump gets a matching annotated tag, `v<version>`, on the bump commit — a bumped version is never left untagged
- Tag locally only; never push a tag unless asked
- `worklane --version` reports the crate version alongside the build sha, so the bump is what makes one release distinguishable from another
A new rule goes in the `docs/` file for its subject, as a bullet saying what the rule is
and why it exists. A new subject gets its own file and a row in
[docs/INDEX.md](docs/INDEX.md). A rule about how worklane is *used* goes in
`assets/SKILL.md` instead, and reaches its readers through `install-skill`.
Generated
+63 -1
View File
@@ -896,6 +896,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
@@ -931,6 +932,15 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_spanned"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
dependencies = [
"serde",
]
[[package]]
name = "shlex"
version = "1.3.0"
@@ -1055,6 +1065,47 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683"
[[package]]
name = "toml"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
"serde_spanned",
"toml_datetime",
"toml_edit",
]
[[package]]
name = "toml_datetime"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
dependencies = [
"serde",
]
[[package]]
name = "toml_edit"
version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap",
"serde",
"serde_spanned",
"toml_datetime",
"toml_write",
"winnow",
]
[[package]]
name = "toml_write"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
[[package]]
name = "unicode-ident"
version = "1.0.24"
@@ -1407,6 +1458,15 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winnow"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
dependencies = [
"memchr",
]
[[package]]
name = "wit-bindgen"
version = "0.51.0"
@@ -1503,7 +1563,7 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.31.4"
version = "0.33.11"
dependencies = [
"anyhow",
"assert_cmd",
@@ -1514,7 +1574,9 @@ dependencies = [
"crossterm",
"libc",
"ratatui",
"serde",
"tempfile",
"toml",
"uuid",
]
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "worklane"
version = "0.31.4"
version = "0.33.11"
edition = "2024"
[dependencies]
@@ -15,6 +15,8 @@ libc = "0.2"
ratatui = { version = "0.29", features = ["unstable-rendered-line-info"] }
crossterm = "0.28"
clap_complete = "4.6.9"
serde = { version = "1", features = ["derive"] }
toml = "0.8"
[dev-dependencies]
assert_cmd = "2"
+34 -3
View File
@@ -5,15 +5,37 @@
# release cannot end up half-done: no version bump left untagged, no tag without
# a bump.
.PHONY: help patch minor major version release install
.PHONY: help check patch minor major version release install
help:
@echo "make check fmt, clippy and the suite, in that order"
@echo "make patch bump $(CURRENT) -> next patch, amend into HEAD, tag"
@echo "make minor bump $(CURRENT) -> next minor, amend into HEAD, tag"
@echo "make major bump $(CURRENT) -> next major, amend into HEAD, tag"
@echo "make version print the current version"
@echo "make install cargo install --path . && worklane install-skill"
# The one command to run before committing. docs/testing.md pins fmt and clippy as clean and
# 83d31cd is what happens when only memory enforces that: fmt drifted to about 160 places
# across every file with the tool installed and configured the whole time. This is not CI,
# which a single-author tool with no pipeline anywhere does not want, and not a hook, which
# is a per-clone opt-in the way `blame.ignoreRevsFile` is. It is one name to type, so
# "remember to run fmt, clippy and the tests" becomes "run make check".
#
# Cheapest first, so a formatting slip is reported in a second rather than after the suite.
# `--all-targets` on clippy, matching the rule in docs/testing.md, so the tests are linted too.
# `-D warnings` is what makes clippy's opinion an exit code: the rule says clean, and a
# warning printed into a wall of cargo output is not clean, it is unread.
#
# Completions are in the suite rather than a step of their own. `cargo test` sources the
# generated script into a real fish and asks it for candidates, so "check tests, check
# completions" is one command already, and a second target would be a second thing to
# remember. The fish tests skip when fish is not installed, printing that they did.
check:
cargo fmt --check
cargo clippy --all-targets -- -D warnings
cargo test
# Read from the [package] table of Cargo.toml, which is the version the binary
# reports through `--version`, so it is the single source of truth. The name is
# what finds this crate's own entry in Cargo.lock.
@@ -34,15 +56,24 @@ patch minor major: release
# A release rewrites the last commit, so refuse anything that would make that
# rewrite lose work or orphan a tag.
#
# Untracked character devices are not work: an agent sandbox bind-mounts /dev/null over
# protected paths such as .bashrc, and git cannot commit a device anyway. Untracked files
# are listed one by one, not with --directory, because the sandbox also mounts devices
# inside an untracked .claude/, and a collapsed directory entry is never a device.
release:
@set -e; \
if ! git rev-parse -q --verify HEAD >/dev/null 2>&1; then \
echo "error: no commits yet, so there is no commit to fold a version bump into. Commit first." >&2; \
exit 1; \
fi; \
if [ -n "$$(git status --porcelain)" ]; then \
dirty=$$( { git status --porcelain --untracked-files=no; \
git ls-files --others --exclude-standard | while IFS= read -r f; do \
[ -c "$$f" ] || echo "?? $$f"; \
done; } ); \
if [ -n "$$dirty" ]; then \
echo "error: working tree is dirty. Commit or stash first, and decide whether that work belongs in this version:" >&2; \
git status --short >&2; \
echo "$$dirty" >&2; \
exit 1; \
fi; \
if [ -n "$$(git tag --points-at HEAD)" ]; then \
+56 -9
View File
@@ -6,34 +6,34 @@ Worklane is a local Kanban flow for agentic software development.
| Command | Description |
|---------|-------------|
| `worklane` or `worklane tui [path...]` | Opens the board: one column per status, redrawn when the tree changes. Read only. Opens with done and discarded hidden, their counts in the footer; `d` rotates hide both, show done, show both, and back around. Arrows or `hjkl` to move, `enter` for detail, `pgup`/`pgdn` to scroll an open ticket or the campaign frame, whichever the selection is on, with a page indicator on its border 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, and a comment count in its bottom right corner, the number then `❞` in cyan, before the criteria count and absent entirely when nobody has commented; while one is selected a frame above the columns names it, shows three rows of its description and says how far it has got, and `q` on its border gives the whole board back; up from the top card of a column moves the selection to that frame, where the scroll keys page through the description, `enter` gives it half the board and takes the rows back again, and down returns to the column it came from, leaving the frame at whatever height it was. 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, discarded directories |
| `worklane init` | Creates `.worklane/` with backlog, committed, reviewing, done, discarded directories. On a machine with a boards config, or in a project that already carries a `.worklane.toml`, it puts the project on the shared layout instead: the board lives in a boards directory under the machine's data dir and `.worklane` becomes a symlink into it. `--create` makes a new board under a pointer that names a missing one, the only way to do so. See Shared Boards |
| `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 <tag>` and `--campaign <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 ls [status]` | Lists tickets, each column in its own order: the backlog by due date, soonest first, then priority then title, with an undated ticket below every dated one; committed and reviewing by when the ticket entered them, oldest first; done and discarded newest first. Optional positional status, and `--priority <1-5>`, `--tag <tag>` and `--campaign <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 <id>` | 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. Ends with the ticket's history: every comment on it and every change to its status, owner or tags, oldest first, each naming who made it |
| `worklane mv <id> --status <target> [-f]` | Moves ticket between statuses. Default: forward only, one stage at a time. `-f` bypasses both restrictions. `--status discarded` is exempt and reachable from anywhere, for a ticket that will not be done; leaving `discarded` is a backward move and needs `-f`. Discarding is refused while open tickets are blocked by the ticket, `-f` overrides. Records a `status` entry in the ticket's history, after the move: a refused or no-op move records nothing. `--actor` names the writer of that entry |
| `worklane mv <id> --status <target> [-f]` | Moves ticket between statuses. Default: forward only, one stage at a time. `-f` bypasses both restrictions. `--status discarded` is exempt and reachable from anywhere, for a ticket that will not be done; leaving `discarded` is a backward move and needs `-f`. A move that would put the ticket ahead of one it is blocked by is refused, naming the target status and every blocker still behind it; standing level with a blocker is allowed, so only the last stage waits for it to land. Discarding is refused while open tickets are blocked by the ticket. `-f` overrides both. Records a `status` entry in the ticket's history, after the move: a refused or no-op move records nothing. `--actor` names the writer of that entry |
| `worklane set <ticket>` | Replaces fields with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--priority`. At least one required. Changing the title renames the file, keeping the UUID. `--clear <field>` 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. `--tags` records a `tags` entry in the ticket's history, with the tags before and after, and it is the only field of this command's that is logged; `--actor` names the writer of that entry |
| `worklane append <ticket>` | Adds to a section with `--description`, `--acceptance`, `--plan`. At least one required. The description gains a paragraph; list items go on the end, steps numbered on from the last |
| `worklane relate <ticket>` | Records an edge to another ticket with `--blocked-by`, `--regression-of` or `--relates-to`, each repeatable. At least one required. Only the ticket named is written; `show` derives the other end by scanning. `mv` refuses to move a ticket blocked by one that is not done, unless `-f` |
| `worklane append <ticket>` | Adds to a section with `--description`, `--acceptance`, `--plan`, or to the tags with `--tags`. At least one required. The description gains a paragraph; list items go on the end, steps numbered on from the last. `--tags` keeps the tags the ticket already carries, ignores one it already has, and takes several as a repeated flag or separated by commas, the way the field itself is written; it is the counterpart to `set --tags`, which replaces the whole field. It records a `tags` entry in the ticket's history, and `--actor` names the writer of that entry, this command's only logged field as it is `set`'s. Emptying a field is `set --clear`, which has no counterpart here |
| `worklane relate <ticket>` | Records an edge to another ticket with `--blocked-by`, `--regression-of` or `--relates-to`, each repeatable. At least one required. Only the ticket named is written; `show` derives the other end by scanning, and a derived row that reads exactly like a stored one is drawn once. `relates to` on a ticket whose target already stores it reports no change, since it is the same edge; `blocked by` and `regression of` read differently from the far end, so a mutual pair is two rows. `mv` refuses to move a ticket to a status ahead of one it is blocked by, unless `-f`: level is allowed, so a blocker in reviewing gates only the move to done. `--clear <kind> <target>` takes an edge off instead, repeatable, the kind spelled either way, `blocked-by` or `blocked by`. The target resolves against the edges the ticket holds first, by id prefix, which is the only way to reach one whose ticket has been deleted, then as an ordinary ticket search. An edge the ticket does not hold reports no change; a target naming nothing at all is an error. Recording and clearing the same edge in one call is refused |
| `worklane chown <user> <ticket>` | Sets the Owner field, the only command that writes it. Free text, checked against nothing. User first and ticket second, after Unix `chown`. `worklane chown --clear <ticket>` returns the field to unset, taking the ticket in the flag since there is no user to give, and not to the git user `add` falls back to. Records an `owner` entry in the ticket's history, with the owner before and after; `--actor` names who made the change, which is not the same as the user argument |
| `worklane check <ticket> [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 <ticket> [criteria...]` | Unticks acceptance criteria, addressed the same way |
| `worklane comment <ticket> <body>` | Adds a comment to a ticket by UUID or title. The author is `--actor`, or `WORKLANE_ACTOR`, or the git user, in that order |
| `worklane comment <ticket> <body>` | Adds a comment to a ticket by UUID or title. The author is `--actor`, or `WORKLANE_ACTOR`, or the git user, in that order; `--actor-from-git` lifts the git user over `WORKLANE_ACTOR`, for acting on the person's behalf without knowing how they spell themselves, and is refused beside `--actor` |
| `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 set <campaign>` | Replaces `--title`, which renames the file keeping the uuid, `--description` and `--codename`. At least one required. The way a campaign filed before codenames existed gets one, and the way a description filed with a typo in it gets fixed. Replacing a codename the campaign already has needs `--force`, since that is the word it is referred to by everywhere; setting the one it already has is a no-op either way. A description needs no `--force`: it is prose written to be revised. No `--clear` and no `--owner` |
| `worklane campaign append <campaign>` | Adds a paragraph to a campaign's description with `--description`, which is required. The other half of `campaign set --description`, so adding a line to a description does not mean retyping the rest of it. Repeat the flag for more lines within the one paragraph. Its own subcommand rather than the top-level `append`, which resolves a ticket |
| `worklane campaign ls` | Lists the campaigns as their short id, their codename, their title, how many members are done, and the state that count derives: `[open]` until every member is done and `[done]` after. A campaign nothing has been filed against reads `no members` and carries no state, being neither. `--ids` prints one per line as the id, a tab and the title, unstyled and without the counts, which read every ticket on the board, for a script or a completion |
| `worklane campaign ls` | Lists the campaigns as a table: when each was created, its short id, its codename, its title, how many members are done, and the state that count derives: `[open]` until every member is done and `[done]` after. A campaign nothing has been filed against reads `no members` and carries no state, being neither. The columns are padded to the widest value in each, so the rows line up whatever the titles are, and the codename is measured with the title rather than given a column of its own, since a campaign filed without one spends nothing on it. `--state` lists only the campaigns in one state, `open`, `done` or `empty` for one nothing has been filed against, and says so by name when nothing matches. `--ids` prints one per line as the id, a tab and the title, unstyled and without the counts, which read every ticket on the board, for a script or a completion; `--state` applies there too, and is the only thing that makes that path count members |
| `worklane campaign show <campaign>` | 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 <campaign> <ticket>` | 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 <shell>` | 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>/SKILL.md`, which Claude Code and opencode both read. Four 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, and `worklane-admin` sets a board up and repairs one, its tag vocabulary and the faults a board can develop. Every document unless one is named. Leaves a modified copy alone unless `--force`; `--print` writes one to stdout instead and needs the name |
| `worklane install-tool` | Writes the embedded opencode tool definitions to `$XDG_CONFIG_HOME/opencode/tool/worklane.ts`, or `~/.config/opencode/tool/` without it, where opencode loads them for every project. One file and so no name to pass. `--force` and `--print` behave as they do for a skill. opencode only: it registers the eleven `worklane_*` tools from the file name and its exports, and Claude Code has no directory it scans for a tool definition, so reaching it would mean an MCP server rather than this. Restart opencode after installing, since it reads its config at startup and never reloads it. Nothing else to install: the file runs inside opencode's own runtime, so neither Bun nor `@opencode-ai/plugin` has to be on the machine |
| `worklane install-tool` | Writes the embedded opencode tool definitions to `$XDG_CONFIG_HOME/opencode/tool/worklane.ts`, or `~/.config/opencode/tool/` without it, where opencode loads them for every project. One file and so no name to pass. `--force` and `--print` behave as they do for a skill. opencode only: it registers the twenty-one `worklane_*` tools from the file name and its exports, and Claude Code has no directory it scans for a tool definition, so reaching it would mean an MCP server rather than this. Restart opencode after installing, since it reads its config at startup and never reloads it. Nothing else to install: the file runs inside opencode's own runtime, so neither Bun nor `@opencode-ai/plugin` has to be on the machine |
## Environment
| Variable | Effect |
|----------|--------|
| `WORKLANE_ACTOR` | Who every entry the CLI writes is attributed to: a comment, and the `status`, `owner` and `tags` entries `mv`, `chown` and `set --tags` record. Set it once, in the environment an agent runs in, and every call it makes is attributed to it instead of to the git user of whoever's machine it is on. `--actor` overrides it per call, an empty value counts as unset, and with neither supplied the author is the git user and then `unknown`. Free text, checked against nothing |
| `WORKLANE_ACTOR` | Who every entry the CLI writes is attributed to: a comment, and the `status`, `owner` and `tags` entries `mv`, `chown` and `set --tags` record. Set it once, in the environment an agent runs in, and every call it makes is attributed to it instead of to the git user of whoever's machine it is on. `--actor` overrides it per call and `--actor-from-git` lifts the git user over it per call (the two flags are refused together), an empty value counts as unset, and with neither supplied the author is the git user and then `unknown`. A command typed at the board's `:` prompt is attributed to the person instead, the git user and then `unknown`, never this variable: nothing but whoever is sitting at the board can type one. Free text, checked against nothing |
| `NO_COLOR` | Set and non-empty turns colour off, whatever the value, per no-color.org. Colour is also off when output is not a terminal, and when `TERM` is `dumb` or empty |
| `XDG_CONFIG_HOME` | Where `install-tool` looks for opencode's config root, `$XDG_CONFIG_HOME/opencode`, defaulting to `~/.config`. `install-skill` does not follow it: `~/.claude` is not an XDG path |
@@ -55,6 +55,7 @@ worklane mv <TAB> the same, then --status <TAB> for the five
worklane chown alice <TAB> the ticket, which is the second argument here
worklane chown --clear <TAB> the ticket, which the flag carries here
worklane relate x --blocked-by <TAB>
worklane relate x --clear <TAB> the three kinds, not a ticket: the kind comes first
worklane campaign show <TAB> the campaigns, from `campaign ls --ids`
worklane assign <TAB> the same, since a campaign comes first here
worklane ls --campaign <TAB> and again
@@ -69,6 +70,35 @@ installed binary to be current**: an older one without `--ids` completes nothing
`tui` is the one command whose argument is a path, so it is the one place fish still offers
directories.
## Shared Boards
A board exists on exactly one machine: `.worklane` is gitignored and not itself a git repo, so cloning
a project elsewhere gives you no board. The shared layout answers that: one boards repo is cloned once
per machine to `~/.local/share/worklane/boards`, holding a directory per board named `uuid_slug` after
the ticket filename convention; the project commits a `.worklane.toml` naming its board by uuid; and
`.worklane` in the project becomes a symlink into it. The symlink is what keeps every other tool
working — with no `.worklane` directory, `cat .worklane/backlog/*.md` stops.
The boards repo url lives in the machine config at `~/.config/worklane/config.toml`, so a client repo
never carries a hostname. The pointer names the board, not the server.
`init` decides where a project is on by the following table, and `--create` is the only way to make a
board under a pointer that names a missing one:
| pointer | boards repo | `.worklane` | outcome |
|---|---|---|---|
| none | irrelevant | none | local `.worklane`, as always |
| none | on this machine (config) | none | create the board, write the pointer, symlink |
| present | board found | none | symlink, and nothing is created |
| present | board absent | none | refuse: an unsynced machine, fetch and look again |
| present | repo not cloned | any | refuse, saying the repo is not cloned here |
| present | board found | link to it | no change, nothing written |
| present | board found | link to another | refuse rather than repoint |
| present | board found | dangling link | refuse rather than replace |
| present | board found | real directory | refuse, and name the adopt path |
Resolution is a uuid prefix match, so renaming a board's slug breaks no committed pointer.
## Exit codes
| Code | Meaning |
|------|---------|
@@ -87,6 +117,23 @@ the command. A pipe holds 64 KiB, so a listing that fits lands in the buffer who
and the writer never learns the reader left, giving 0. Only output past that gets far
enough to be cut off. Either way nothing is printed to stderr.
## Design notes
`docs/` holds why worklane is built the way it is, one file per subject, with
[docs/INDEX.md](docs/INDEX.md) saying which file answers what. Read the entry for a
subject before changing what it describes.
## Checking
```sh
make check # cargo fmt --check, clippy -D warnings, cargo test
```
One command, cheapest first, and the whole of what enforces the formatting and lint rules:
there is no CI here and no hook. The completion tests inside it source the generated script
into a real fish and ask it what it would offer, so they skip, saying so, on a machine
without fish.
## Releasing
```sh
+21 -12
View File
@@ -233,17 +233,25 @@ two exceptions below are files no command owns, and they are marked as such.
first check `worklane ls done`. If it is there and should not be, its file has been moved
into the wrong directory by hand or by a restore.
The repair is two moves, not one:
`mv` reads the current status from the *directory*, so one move puts both halves right:
move the ticket to the status it belongs in and the field travels with it.
```
worklane mv 1b78a24 --status reviewing -f
worklane mv 1b78a24 --status done -f
```
`mv` reads the current status from the *directory*, so moving it to the status the
directory already says it is in is refused as a no-op and the field stays wrong. Moving it
away and back rewrites the field. Check with `worklane show 1b78a24`, whose `Status` line
is read from the file rather than from where it sits.
If the file is where it belongs and only the `Status` field inside is stale — a hand move
that forgot the field, or a half-finished restore — name the directory the file actually
sits in: a move there finds the field disagreeing with the directory and rewrites just
the field, reporting the correction instead of refusing as a no-op.
```
worklane mv 1b78a24 --status done
```
That repair changes only the field: no stamp is written and no history entry either,
because the work went nowhere. Check either repair with `worklane show 1b78a24`, whose
`Status` line is read from the file rather than from where it sits.
### A command says the id matches several tickets
@@ -264,15 +272,16 @@ as above. Then confirm with `worklane show`.
### A move is refused by a blocker
```
Cannot move 'Beta' while it is blocked by:
Cannot move 'Beta' to reviewing while it is blocked by:
...
Use --force (-f) to move it anyway.
A ticket cannot move ahead of what it waits on. Use --force (-f) to move it anyway.
```
Working as intended: a ticket cannot advance while something it waits on is unfinished.
Finish the blocker, or use `-f` if the dependency is no longer real. Note that the
relation stays on the ticket and will refuse the next move too, and there is no way to
take a relation off, so `-f` is the answer every time until the blocker is done.
Working as intended: a ticket may stand level with what it waits on but not ahead of it,
so this move was one column too far. Advance the blocker to that column, which is usually
the answer and costs nothing, or use `-f` if the dependency is no longer real. If it is
not real at all, take the edge off instead of forcing every move:
`worklane relate <ticket> --clear blocked-by <blocker>`.
If the message says `is blocked by X, which is not on the board`, the blocker has been
deleted. That is a warning rather than a refusal and the move goes through.
+11 -2
View File
@@ -113,8 +113,10 @@ wrong by however much the guess was wrong.
The rules a dating plan has to keep:
- **Nothing is dated before the ticket it is blocked by.** Read the Relations first and
date blockers ahead of their dependents. A dependent dated before its blocker is a date
`mv` will refuse to honour anyway.
date blockers ahead of their dependents, or on the same day: a dependent may be worked
and reviewed alongside its blocker, so the two can share a date, but a dependent dated
earlier is a date `mv` will refuse to honour anyway, since only the blocker's own
landing lets it land.
- **A blocker left undated makes its dependent's date a fiction.** Either date both or
neither.
- **Date what fits, not what exists.** Ask how much capacity the week holds, or take the
@@ -166,6 +168,7 @@ fields; a goal is a campaign.
```
worklane campaign ls
worklane campaign ls --state empty # filed against nothing, which is the one to ask about
worklane campaign show v1
worklane campaign add --title "..." --codename v1 --description "..."
worklane campaign set v1 --title "..." # or --description or --codename, on one already filed
@@ -181,6 +184,12 @@ tui is usable on a narrow terminal" is a campaign. "The tui tickets" is a tag.
them in a container says nothing that the tag did not already say.
- **Check what exists first.** `campaign ls` before proposing a new one, or you will
propose a second container for a goal that already has one.
- **`--state empty` finds the containers nothing was ever filed against.** A campaign with
no members is neither open nor done, so it is invisible to `--state open` and reads as
just another row in the full listing. Either the tickets for that goal exist and were
never assigned to it, which is an `assign` away, or the goal is one nobody is working,
which is worth saying out loud. A campaign cannot be discarded, so an empty one stays on
the board until it has members.
- **A ticket is in at most one campaign**, and `assign` moves it rather than adding a
second. So two proposed campaigns that overlap are really one proposal to take members
out of the other, and it has to say so.
+81 -9
View File
@@ -1,6 +1,6 @@
---
name: worklane-review
description: Review a finished worklane ticket against the code that claims to close it, and record the verdict on the board. Use when asked to review a ticket, to check whether a ticket is really done, or to verify that an implementation matches its acceptance criteria, whether the ticket is named by id, by title or as "the one in reviewing". Covers finding the commits, judging each criterion against the code, and what a reviewer may and may not write back to the board.
description: Review a finished worklane ticket against the code that claims to close it, and record the verdict on the board. Use when asked to review a ticket, to check whether a ticket is really done, or to verify that an implementation matches its acceptance criteria, whether the ticket is named by id, by title or as "the one in reviewing". Covers finding the commits, judging each criterion against the code, what a reviewer may and may not write back to the board, and how to close a ticket whose work is already on master by filing its remaining issues as new tickets.
---
# Reviewing a worklane ticket
@@ -14,14 +14,21 @@ addressed and the argument traps, is the `worklane` skill; read that too.
## What a review produces
Three things, in this order, and nothing else:
Steps 1 to 3 are the same for every review. What you write back depends on one question
answered in step 2: **is the work already on the default branch** (master or main)?
**Not yet landed** (on a branch, or not merged): steps 4 and 5, which produce
1. **One comment** on the ticket, in the structure below.
2. **Unticked criteria**, for the ones the code does not actually meet.
3. **Appended criteria**, for work the review found that the ticket never asked for.
You do not tick a criterion, you do not move the ticket, and you do not fix the code.
Each of those has a reason, given where it comes up.
and nothing else. You do not tick a criterion, you do not move the ticket, and you do not
fix the code. Each of those has a reason, given where it comes up.
**Already landed**: skip steps 4 and 5 and follow step 6 instead. The findings become new
tickets rather than appended criteria, and the review ends with you moving the ticket to
done. You still never tick a criterion and never fix the code.
## 1. Read the ticket before the code
@@ -35,8 +42,12 @@ comments are where the intent moved after filing. A criterion that contradicts a
is one of the more useful things you can find: it means the ticket was not updated when
the plan changed, and one of the two is now lying to whoever reads the board.
Read the Relations too. A `blocked by` that is not done, or a `regression of`, changes
what the change was allowed to do and what the review has to check twice.
Read the Relations too. A `blocked by` that has not landed, or a `regression of`, changes
what the change was allowed to do and what the review has to check twice. A ticket
reaching review while its blocker is still in review is allowed by the board, so it is
normal rather than a fault, and it is exactly the case where the code under review may be
resting on work that has not landed: check that it does not assume the blocker is
finished.
## 2. Find the work
@@ -55,6 +66,16 @@ Widen it with the files the description names, since a ticket that names
`src/tui.rs` is reviewable through `git log -p -- src/tui.rs` even when no commit
message mentions it.
Once you have the commits, check whether each one is on the default branch. This decides
whether you go on to steps 4 and 5 or to step 6, so settle it now:
```
git merge-base --is-ancestor 6d327df master && echo landed # use main if the repo has no master
```
The work has landed only if **every** reviewed commit is on the default branch. If some
are and some are still on a branch, it has not landed: follow steps 4 and 5.
**If nothing names the ticket, that is the finding.** Do not review the working tree on
the assumption that whatever is uncommitted must be the work, and do not report a pass
you could not check. Comment what you searched for and stop: a ticket sitting in
@@ -83,17 +104,21 @@ Then the two questions the criteria cannot ask themselves:
- **What did this change break that no criterion covers?** Silent behaviour changes,
a message or exit code something else reads, an edge case the ticket never named.
- **What did the ticket never think of?** That is what you append in step 5.
- **What did the ticket never think of?** That is what you append in step 5, or file as a
ticket in step 6.
## 4. Write one comment
**If the work has landed, skip to step 6 now.** It uses this comment's structure, but only
after the new tickets exist, so their ids can go in it.
One call, one comment. Not one per criterion: the board renders comments in the order
they were written, and a review split over eight of them cannot be read as a verdict.
```
worklane comment 1b78a24 "**Verdict**: two criteria unmet, the scroll clamp is off by the header
**Work reviewed**: 4edc7fa, 6d327df on master
**Work reviewed**: 4edc7fa, 6d327df on feature/tui-scroll, not merged
**Criteria**
1. met - PageUp and PageDown reach detail_scroll, src/tui.rs:412
@@ -138,7 +163,54 @@ without making it clearer.
**Do not move the ticket.** `mv` belongs to whoever does the work, the same way ticking
does. Your half is the recommendation in the comment; acting on it is theirs. A reviewer
that reviews and closes in one breath leaves nobody to disagree with.
that reviews and closes in one breath leaves nobody to disagree with. This rule holds
for work that has not landed; landed work follows step 6.
## 6. When the work is already on master
Use this step instead of steps 4 and 5 when step 2 found every reviewed commit on the
default branch. Do not do steps 4 and 5 as well.
Landed work is not sent back to committed. That would reopen code that has shipped, and
whatever fixes the findings is a new change anyway. So every remaining issue moves to a
new ticket, and this ticket is closed.
An **issue** is any of these: a criterion you judged not met, a finding from the two
questions in step 3, and a "cannot tell" whose answer needs work, such as a missing test.
A "cannot tell" you settle by reading or running something is not an issue: settle it.
Do these in order, and do not skip ahead:
1. **File a ticket for every issue**, the way the `worklane` skill says, searching the
backlog first. Issues that are related, because they touch the same function or one
fix would close them all, go into one ticket together. Unrelated issues get a ticket
each. An issue that already has an open ticket gets a comment there, not a new one.
2. **Link each new ticket back** to the one under review:
`worklane relate <new> --relates-to 1b78a24`, or `worklane relate <new>
--regression-of 1b78a24` when the reviewed change broke something that used to work.
3. **Write the review comment**, in the structure of step 4. List each issue under
`**Findings**` with the id of the ticket that now holds it, and recommend done.
4. **Untick every unmet criterion** with `worklane uncheck`, as in step 5, so the closed
ticket does not claim what the code does not do. **Do not append criteria**: work for
a later commit belongs to the ticket that commit will close, and nobody works a done
ticket.
5. **Write a closing comment**, separate from the review comment, immediately before the
move. It says why the ticket is closing and names the ticket that holds each remaining
issue:
```
worklane comment 1b78a24 "Moving to done: the work is on master, and every remaining issue has its own ticket: 7bfb9fc (wrapped-line clamp), 4179958 (footer keys)"
```
With no issues at all, steps 1, 2 and 4 have nothing to do, and the closing comment
says that: `Moving to done: the work is on master and the review found no remaining
issues`. The review comment is the verdict; the closing comment is the reason for the
status change, and it sits in the history right above the move. Without it, a done
ticket with unticked criteria looks closed by mistake.
6. **Move it to done**: `worklane mv 1b78a24 --status done`. This is the only move a
reviewer makes. Make it last: an issue without a ticket is lost once this one is done.
With every issue in its own ticket, nothing is left here for the implementer, and
leaving the ticket in `reviewing` only hides that the review is finished.
## What a reviewer does not touch
+106 -30
View File
@@ -32,8 +32,9 @@ go straight to `reviewing` and has to be walked through `committed` anyway. Doin
front is the same two commands in a more useful order. `-f` allows a backward or
skipping move, for correcting a mistake.
A move is also refused while the ticket is blocked by one that is not done yet, see
[Relating tickets](#relating-tickets).
A move is also refused while it would take the ticket a column ahead of one it is
blocked by: a pair can be committed together and reviewed together, and only the move to
`done` waits for the blocker to land. See [Relating tickets](#relating-tickets).
`mv` stamps the time as it goes: `Committed On`, `Submitted On`, `Completed On` and
`Discarded On`, shown by `show` among the rest of the metadata. They **accumulate**, so a
@@ -63,7 +64,7 @@ What it means everywhere else:
`ls discarded` and `--ids` still reach it
- A campaign counts a discarded member as **finished**: the work left the campaign rather
than sitting in it unfinished
- A discarded ticket **blocks nothing**, so a ticket waiting on it can move
- A discarded ticket **blocks nothing**, so a ticket waiting on it can move anywhere
- Discarding a ticket that open tickets are blocked by is **refused**, naming them: their
plans depended on this work, so they need a look first. `-f` says you looked
- Getting it back is a backward move, so it needs `-f`:
@@ -169,14 +170,21 @@ worklane set 1b78a24 --clear due # take a value away again
worklane set 1b78a24 --clear tags --clear plan # as many fields as you like
worklane append 1b78a24 --acceptance "One more criterion"
worklane append 1b78a24 --description "What was learned since."
worklane append 1b78a24 --tags tui # add a tag, keeping the ones there
worklane chown alice 1b78a24 # hand the ticket to someone
worklane chown --clear 1b78a24 # hand it back to nobody
```
`set` replaces, `append` adds, `--clear` empties. Neither `set` nor `append` has
`--owner` or `--status`: owner is `chown`'s and status is `mv`'s, so each field has
exactly one writer. A field set to the value it already holds is reported unchanged and
nothing is written, and so is a field cleared that was already unset.
`set` replaces, `append` adds, `--clear` empties. `set --tags` overwrites the whole
field, so **use `append --tags` to add a tag to a ticket that already carries some**: it
keeps what is there, and a tag the ticket already has is reported as no change rather
than added twice, so you do not have to read the ticket first. Several in one call by
repeating the flag or by separating them with commas, `--tags "bug, tui"`, since that is
how the field itself is written. Reach for `set --tags` when the whole list is being
replaced, and `set --clear tags` to empty it: `append` has neither. Neither `set` nor
`append` has `--owner` or `--status`: owner is `chown`'s and status is `mv`'s, so each
field has exactly one writer. A field set to the value it already holds is reported
unchanged and nothing is written, and so is a field cleared that was already unset.
**`--clear` takes the field as its value**, one of `due`, `tags`, `priority`,
`description`, `acceptance` or `plan`, and repeats. It writes back exactly what `add`
@@ -195,24 +203,71 @@ resolve as a ticket. `--clear` replaces both arguments with the ticket alone.
`worklane init` creates `.worklane/` with the five status directories and the campaigns
directory beside them, for a repo that has no board yet.
**A board can be shared across machines.** `.worklane` is gitignored and not itself a git
repo, so a clone elsewhere has no board. The shared layout keeps one boards repo cloned
once per machine, a committed `.worklane.toml` in the project naming its board, and
`.worklane` as a symlink into the boards directory — transparent to every command. Where
to run `init` decides the layout: a project whose machine carries a boards config, or
whose repo already shows a `.worklane.toml`, lands on the shared board, and everything
else gets the ordinary local `.worklane`. A pointer whose board is missing is an unsynced
machine and `init` refuses rather than creating a second board that would have to be
merged by hand; `worklane init --create` is the deliberate exception for a genuinely new
board. You only need the layout in mind when a `.worklane.toml` appears in a repo you
are working in: it says the board is another machine's, and a missing one means pull the
boards repo, not that the board never existed.
## Relating tickets
```
worklane relate 1b78a24 --blocked-by 4179958 # this one waits on that one
worklane relate 1b78a24 --regression-of 6d327df # this one broke that one's fix
worklane relate 1b78a24 --relates-to 7bfb9fc # neighbours, no dependency
worklane relate 1b78a24 --clear blocked-by 4179958 # take that edge off again
```
One flag per kind, and each repeats. The ticket comes first and the flag says what it is
to the target, so read the call as a sentence: `relate A --blocked-by B` means A waits
on B. **Only one side is stored**, on the ticket you name, and `show` derives the other
on B.
**`--clear` is how an edge comes off, and it names the kind and the target**, because a
ticket can hold several relations of one kind and emptying all of them is rarely what is
wanted. Repeat the flag for more. The kind is spelled either way, `blocked-by` as the flag
records it or `blocked by` as `show` prints it. `set --clear` does not reach relations:
`relate` is the only writer of the section, so it owns both directions.
The target is resolved against the edges the ticket already holds first, by id prefix,
and only then as an ordinary ticket search. That order is what lets you clear an edge
whose target has been **deleted**, which is the case most likely to need it: `show` draws
it as `_missing_` with a `?` mark and `mv` warns about it on every move, and no search of
the board can reach a ticket that is gone.
An edge the ticket does not hold reports no change. A target that names nothing at all is
an error rather than a no-op, so a mistyped id does not read as success. Recording and
clearing the same edge in one call is refused outright, the way `set` refuses a field it
is also replacing, and nothing is written. **Only one side is stored**, on the ticket you name, and `show` derives the other
end for the ticket at the far side, so never record both directions.
`--blocked-by` is enforced: `mv` refuses to move a ticket while a ticket it is blocked by
is not in `done` or `discarded`, whichever move it is, and names every open blocker. `-f`
moves it anyway, beside the backward and skipping moves it already allows. It is enforced
from the other end too: discarding a ticket that open tickets are blocked by is refused,
naming them. The other two kinds are reference data and never refuse anything.
`relates to` reads the same from both ends, so recording it on the second ticket is
refused as no change: the edge is already there, from the far side. `blocked by` and
`regression of` are different: the far end reads as `blocks` and `regressed by`, so two
tickets each blocking the other is two facts and the block shows both. A symmetric edge
comes off with `--clear` at the end that stores it, since that is the only end holding a
line to remove.
`--blocked-by` is enforced by the column: **a ticket cannot move to a status ahead of
the one its blocker is in**, and standing level with it is allowed. So a blocker in
`reviewing` lets the dependent be committed and submitted for review and refuses only
`done`; a blocker still in `backlog` holds the dependent in `backlog`. With several
blockers the least advanced one sets the ceiling, and the refusal names the status you
tried to move to and every blocker still behind it. A blocker in `done` or `discarded`
holds up nothing at all.
That is what makes it worth recording an edge on work you are about to start rather than
work you have finished: waiting on a ticket in review costs nothing until the last move.
`-f` moves past it anyway, beside the backward and skipping moves it already allows. It
is enforced from the other end too: discarding a ticket that open tickets are blocked by
is refused, naming them. The other two kinds are reference data and never refuse
anything.
Recording a relation the ticket already holds reports no change. A ticket cannot relate
to itself, and a target that later disappears shows as `_missing_` rather than silently
@@ -231,6 +286,10 @@ pair shares a glyph, and **your output is a pipe, so you do not get the colour**
`◐` as under way and `●` as nothing left to do, and if it matters which of the two,
`worklane show` on that target says so in its Status field. `○` is unambiguous without it.
A row pointing at a **discarded** target is struck through on a terminal, since a
relation to abandoned work otherwise reads as a live dependency. That is a style rather
than a character, so a pipe does not get it either: ask the target's Status field.
## Campaigns
A campaign groups the tickets that have to be finished together: a release, a migration,
@@ -243,6 +302,7 @@ there is no such thing as a done campaign holding an open ticket.
worklane campaign add --title "First public release" --codename v1 \
--description "Everything that has to ship before the tag."
worklane campaign ls # every campaign, its codename, how far it has got
worklane campaign ls --state open # only the ones with work left: open, done, empty
worklane campaign ls --ids # id and title, tab separated, like ls --ids
worklane campaign show v1 # its body, then its members by status
worklane campaign set v1 --title "..." # replace the title, description or codename
@@ -308,8 +368,8 @@ existing ticket will have been written from a different angle.
`show` ends with a HISTORY block: every comment on the ticket and every change to its
status, owner, tags or campaign, oldest first, each naming who made it. You do not write
these by hand. `mv`, `chown`, `set --tags` and `assign` record themselves, and a call
that changes nothing records nothing. A campaign move is recorded by codename, or by
these by hand. `mv`, `chown`, `set --tags`, `append --tags` and `assign` record
themselves, and a call that changes nothing records nothing. A campaign move is recorded by codename, or by
title for a campaign that has none, not by the uuid the field holds.
```
@@ -336,29 +396,45 @@ Read the block before picking a ticket up: it says whether somebody has already
## Who your entries are attributed to
Every comment carries an author, and by default that is the git user of the machine you
are running on, which is the human whose checkout it is and not you. Set
`WORKLANE_ACTOR` in your own environment and it becomes the author of every entry you
write, so a board several agents write to says which of them said what:
Every entry carries an author, and yours comes from `WORKLANE_ACTOR`, which your harness
sets before you run anything. **Assume it is set for you, and never spell yourself out on
a call** — a plain `worklane comment` is already attributed to you, which is what keeps a
board several agents write to saying which of them said what. It is configured once,
where your session's environment lives: `env` in `~/.claude/settings.json` for Claude
Code, and the environment opencode is started with for opencode, since it passes its own
environment to the tools it runs.
**Reach for `--actor` only when the entry is somebody else's action**: the person asked
you to move a ticket, or to put words on the board as their comment, so name them on
the flag — the move was theirs and the words are theirs, and an entry carrying your name
reads later as though you decided both. Otherwise leave it off, unless your instructions
say to use it. It is spelled the same on every command that writes an entry: `comment`,
`mv`, `chown`, `set`, `append` and `assign`. On the last two it reaches only the entry
`--tags` writes, since that is the one field either of them logs.
Acting for the person without knowing how they spell themselves? `--actor-from-git`
attributes the entry to the detected git user instead of `WORKLANE_ACTOR`, so their name
is never needed. It cannot be combined with `--actor`, and a machine with no git user
configured has nobody to name: the entry reads `unknown` rather than falling back to your
variable.
```
WORKLANE_ACTOR=claude worklane comment 1b78a24 "The offset was never passed to the widget."
worklane mv 1b78a24 --status done --actor "Ansho Rei"
```
Set it once where your session's environment is configured, not on each call: `env` in
`~/.claude/settings.json` for Claude Code, and the environment opencode is started with
for opencode, since it passes its own environment to the tools it runs. `--actor`
overrides it for one call and is spelled the same on every command that writes an entry,
`comment`, `mv`, `chown`, `set` and `assign`. An empty value counts as unset and falls
back to the
git user, and with nothing at all the author is `unknown`. It is free text, checked
against nothing: name yourself something a person reading the board will recognise.
Under a missing or empty variable the author falls back to the git user of the machine —
the human whose checkout it is — and with neither, `unknown`. It is free text, checked
against nothing: whatever name you pass, make it one a person reading the board will
recognise.
On `chown`, `--actor` is not the user argument: `worklane chown alice 1b78a24` makes alice
the ticket's owner, and `--actor` says who made that change.
If the variable is not set and you cannot set it, pass `--actor` rather than letting the
comment claim to be the user's.
**An entry made from the board is the person's, not yours.** A command typed at the
board's `:` prompt is attributed to the git user of that machine whatever `WORKLANE_ACTOR`
is set to, because nothing but the person sitting at the board can type one. So an entry
can appear under a name no agent is configured with, and reading it as somebody else's
agent is reading it wrong: that is the person whose board it is, acting for themselves.
## Shell completions
+396 -3
View File
@@ -358,7 +358,7 @@ export const set = tool({
export const append = tool({
description:
"Add to a section of an existing worklane ticket without replacing what is there. The description gains a new paragraph; acceptance criteria and plan steps are added to the end of their lists, with steps numbered on from the last. Ticked criteria and handwritten content are left alone. To replace a section outright, use set.",
"Add to an existing worklane ticket without replacing what is there. The description gains a new paragraph; acceptance criteria and plan steps are added to the end of their lists, with steps numbered on from the last; tags are added to the ones the ticket already carries. Ticked criteria and handwritten content are left alone. To replace a section or the whole tag list outright, use set.",
args: {
ticket: tool.schema
.string()
@@ -375,6 +375,14 @@ export const append = tool({
.string()
.describe("Implementation plan steps to add, one per line.")
.optional(),
tags: tool.schema
.string()
.describe("Tags to add, comma separated, keeping the ones the ticket already carries. A tag it already has is reported as no change rather than added twice, so the ticket does not have to be read first.")
.optional(),
actor: tool.schema
.string()
.describe("Who the entry is attributed to. Only reaches the entry tags writes, since that is the one field of this command's that is logged. If omitted, WORKLANE_ACTOR is used, then the git user.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.ticket) {
@@ -395,9 +403,14 @@ export const append = tool({
if (args.plan) {
itemLines(args.plan).forEach((line: string) => cmd.push("--plan", line));
}
if (args.tags) cmd.push("--tags", args.tags);
// Last, and not counted as a field: the length check below is what refuses a call
// that names nothing to add, and an actor alone adds nothing. Same shape as set.
const fields = cmd.length;
if (args.actor) cmd.push("--actor", args.actor);
if (cmd.length === 2) {
return "Error appending: give at least one section to add to";
if (fields === 2) {
return "Error appending: give at least one field to add to";
}
try {
@@ -497,3 +510,383 @@ function checkboxTool(verb: "check" | "uncheck") {
export const check = checkboxTool("check");
export const uncheck = checkboxTool("uncheck");
/**
* relate is the only writer of the Relations section, so the tool mirrors it rather
* than folding relations into set.
*
* The clear half is one argument per kind rather than a free-text "kind target" line,
* which is what the CLI's single --clear flag would force here. A kind inside a value
* cannot be typed by the schema, a target is a search that may itself contain spaces,
* and splitting the pair apart by hand re-parses what clap already refuses to guess at.
* Per kind the target stays a plain line, the way every other list argument works.
*/
export const relate = tool({
description:
"Record a relation from one ticket to another, or take one off. Kinds: blocked-by means this one waits on that one and cannot move to a status ahead of it, so it may be committed and reviewed alongside the target and only lands once the target does; regression-of means this one broke that one's fix; relates-to is a neighbour with no dependency. The edge is stored on the ticket you name alone, and show derives the other end for the target, so never record both directions.",
args: {
ticket: tool.schema
.string()
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
blocked_by: tool.schema
.string()
.describe("Target tickets this one waits on, one per line.")
.optional(),
regression_of: tool.schema
.string()
.describe("Target tickets whose fix this one broke, one per line.")
.optional(),
relates_to: tool.schema
.string()
.describe("Target tickets this one merely relates to, one per line.")
.optional(),
clear_blocked_by: tool.schema
.string()
.describe("Targets whose blocked-by edge comes off this ticket, one per line.")
.optional(),
clear_regression_of: tool.schema
.string()
.describe("Targets whose regression-of edge comes off this ticket, one per line.")
.optional(),
clear_relates_to: tool.schema
.string()
.describe("Targets whose relates-to edge comes off this ticket, one per line.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.ticket) {
return "Error relating tickets: ticket is required";
}
const cmd: string[] = ["relate", args.ticket];
if (args.blocked_by) itemLines(args.blocked_by).forEach((line) => cmd.push("--blocked-by", line));
if (args.regression_of) {
itemLines(args.regression_of).forEach((line) => cmd.push("--regression-of", line));
}
if (args.relates_to) itemLines(args.relates_to).forEach((line) => cmd.push("--relates-to", line));
// The kind is spelled the way the flag records it, not the way show prints it:
// the CLI takes either, and the flag spelling is the one with no space in it.
if (args.clear_blocked_by) {
itemLines(args.clear_blocked_by).forEach((line) => cmd.push("--clear", "blocked-by", line));
}
if (args.clear_regression_of) {
itemLines(args.clear_regression_of).forEach((line) => cmd.push("--clear", "regression-of", line));
}
if (args.clear_relates_to) {
itemLines(args.clear_relates_to).forEach((line) => cmd.push("--clear", "relates-to", line));
}
if (cmd.length === 2) {
return "Error relating tickets: name a relation to record or one to clear";
}
try {
return await run(cmd, context);
} catch (err: any) {
return `Error relating tickets: ${err.message}`;
}
},
});
/**
* Five tools for the five campaign subcommands, one export each.
*
* One tool taking an action argument would mirror the CLI nesting, but the schema
* could then no longer say which arguments belong to which action: campaign_set's
* force only means something beside --codename, and campaign_append's description is
* required where add's is not. Separate exports keep each schema true, and the ids
* read as the CLI path anyway, since opencode builds them from this file name plus
* the export: worklane_campaign_set.
*/
export const campaign_add = tool({
description:
"File a new campaign: several separate tickets that have to be finished together for one goal. Its state is derived from its members, so there is nothing to move or close. Give a codename when you can: one word the board draws on every card in the campaign and the shortest thing that addresses it.",
args: {
title: tool.schema
.string()
.describe("Campaign title (required)"),
description: tool.schema
.string()
.describe("What the campaign is for. Use newlines between paragraphs.")
.optional(),
codename: tool.schema
.string()
.describe("One word to call the campaign by, e.g. 'v1' or 'beaver'.")
.optional(),
owner: tool.schema
.string()
.describe("Campaign owner name. If omitted, defaults to the git user.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.title) {
return "Error adding campaign: title is required";
}
const cmd: string[] = ["campaign", "add", "--title", args.title];
if (args.description) {
descriptionLines(args.description).forEach((line: string) =>
cmd.push("--description", line),
);
}
if (args.codename) cmd.push("--codename", String(args.codename));
if (args.owner) cmd.push("--owner", args.owner);
try {
return await run(cmd, context);
} catch (err: any) {
return `Error adding campaign: ${err.message}`;
}
},
});
export const campaign_set = tool({
description:
"Replace fields on an existing campaign: its title, its description or its codename. Replacing a codename the campaign already has needs force, since everything refers to the campaign by that word once it exists; setting the codename it already carries is a no-op either way. Membership is not set here, use assign.",
args: {
campaign: tool.schema
.string()
.describe("Campaign UUID prefix, codename or title substring (required)"),
title: tool.schema
.string()
.describe("New title. The file is renamed to match, keeping the UUID.")
.optional(),
description: tool.schema
.string()
.describe("New description, replacing the whole section. Use newlines between paragraphs.")
.optional(),
codename: tool.schema
.string()
.describe("New codename, one word. Replacing an existing one needs force.")
.optional(),
force: tool.schema
.boolean()
.describe("Allow replacing a codename the campaign already has.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.campaign) {
return "Error setting campaign fields: campaign is required";
}
const cmd: string[] = ["campaign", "set", args.campaign];
if (args.title) cmd.push("--title", args.title);
if (args.description) {
descriptionLines(args.description).forEach((line: string) =>
cmd.push("--description", line),
);
}
if (args.codename) cmd.push("--codename", String(args.codename));
if (args.force) cmd.push("--force");
if (cmd.length === 3) {
return "Error setting campaign fields: give at least one field to change";
}
try {
return await run(cmd, context);
} catch (err: any) {
return `Error setting campaign fields: ${err.message}`;
}
},
});
export const campaign_append = tool({
description:
"Add a paragraph to a campaign's description without replacing what is already written. To replace the whole description, use campaign_set.",
args: {
campaign: tool.schema
.string()
.describe("Campaign UUID prefix, codename or title substring (required)"),
description: tool.schema
.string()
.describe("Text to add as a new paragraph at the end of the description (required)."),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.campaign) {
return "Error appending to campaign: campaign is required";
}
if (!args.description) {
return "Error appending to campaign: description is required";
}
const cmd: string[] = ["campaign", "append", args.campaign];
descriptionLines(args.description).forEach((line: string) =>
cmd.push("--description", line),
);
try {
return await run(cmd, context);
} catch (err: any) {
return `Error appending to campaign: ${err.message}`;
}
},
});
export const campaign_ls = tool({
description:
"List campaigns with how far each has got: created, id, codename or title, and done members against total. Open until every member is done or discarded.",
args: {
state: tool.schema
.enum(["open", "done", "empty"])
.describe(
"Only campaigns in this state. A campaign with no members is neither open nor done, which is what 'empty' reaches.",
)
.optional(),
ids: tool.schema
.boolean()
.describe("Print only id and title, tab separated, one per line, for parsing.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
const cmd = ["campaign", "ls"];
if (args.state) cmd.push("--state", String(args.state));
if (args.ids) cmd.push("--ids");
try {
return await run(cmd, context);
} catch (err: any) {
return `Error listing campaigns: ${err.message}, Dir: ${resolveWorklaneDir(context)}`;
}
},
});
export const campaign_show = tool({
description:
"Show a campaign's body and its members grouped by status, done included, so what is finished against what is left is one answer.",
args: {
campaign: tool.schema
.string()
.describe("Campaign UUID prefix, codename or title substring (required)"),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.campaign) {
return "Error showing campaign: campaign is required";
}
try {
return await run(["campaign", "show", args.campaign], context);
} catch (err: any) {
return `Error showing campaign: ${err.message}`;
}
},
});
export const assign = tool({
description:
"Put a ticket in a campaign, moving it out of whichever campaign it was in: a ticket is in at most one. Note the order, campaign first and ticket second, after chown.",
args: {
campaign: tool.schema
.string()
.describe("Campaign UUID prefix, codename or title substring (required)"),
ticket: tool.schema
.string()
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
actor: tool.schema
.string()
.describe("Who the entry is attributed to. If omitted, WORKLANE_ACTOR is used, then the git user, then \"unknown\". Set WORKLANE_ACTOR in the environment opencode is started with rather than passing this on every call.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.campaign) {
return "Error assigning ticket: campaign is required";
}
if (!args.ticket) {
return "Error assigning ticket: ticket is required";
}
const cmd: string[] = ["assign", args.campaign, args.ticket];
if (args.actor) cmd.push("--actor", args.actor);
try {
return await run(cmd, context);
} catch (err: any) {
return `Error assigning ticket: ${err.message}`;
}
},
});
/**
* Three tools for tags, and none for `tags ls`: it prints exactly what the bare
* `worklane tags` listing prints, which the tags tool runs.
*
* The annotation lines go through descriptionLines, not itemLines: an empty value is
* a paragraph break in an annotation, exactly as it is in a description, because the
* value_parser on the CLI side accepts one and the vocabulary file stores prose under
* the tag heading.
*/
export const tags = tool({
description:
"List the tags the board carries: the tag, how many tickets carry it, and the opening line of its declared meaning. Read this before inventing a tag. Case sensitive, so bug and Bug list separately and land next to each other, which is where a near-duplicate is spotted.",
args: {},
async execute(_args: Record<string, any>, context: ToolContext) {
try {
return await run(["tags"], context);
} catch (err: any) {
return `Error listing tags: ${err.message}, Dir: ${resolveWorklaneDir(context)}`;
}
},
});
export const tags_add = tool({
description:
"Declare a tag and what it means: when the next ticket belongs in it. The tag is spelled exactly the way ls --tag matches it, one word with no comma in it.",
args: {
tag: tool.schema
.string()
.describe("The tag to declare (required), e.g. 'bug' or 'frontend'."),
annotation: tool.schema
.string()
.describe("What the tag means and when it is appropriate. Use newlines between paragraphs.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.tag) {
return "Error declaring tag: tag is required";
}
const cmd: string[] = ["tags", "add", args.tag];
if (args.annotation) {
descriptionLines(args.annotation).forEach((line: string) =>
cmd.push("--annotation", line),
);
}
try {
return await run(cmd, context);
} catch (err: any) {
return `Error declaring tag: ${err.message}`;
}
},
});
export const tags_set = tool({
description:
"Replace what a declared tag means, keeping the tickets carrying it. There is no rename: changing the word itself means rewriting the Tags field of every ticket that carries it, which is a migration and not this call.",
args: {
tag: tool.schema
.string()
.describe("The tag to change, spelled the way it was declared (required)."),
annotation: tool.schema
.string()
.describe("What the tag means, replacing whatever it said before. Use newlines between paragraphs (required)."),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.tag) {
return "Error setting tag meaning: tag is required";
}
if (!args.annotation) {
return "Error setting tag meaning: annotation is required";
}
const cmd: string[] = ["tags", "set", args.tag];
descriptionLines(args.annotation).forEach((line: string) =>
cmd.push("--annotation", line),
);
try {
return await run(cmd, context);
} catch (err: any) {
return `Error setting tag meaning: ${err.message}`;
}
},
});
+46
View File
@@ -0,0 +1,46 @@
# worklane docs
Why worklane is built the way it is, one file per subject. This is the reference for
someone changing worklane's own code: every rule here carries the reason it exists and
what broke without it, so read the entry before changing what it describes.
**How to *use* worklane is not here.** That is `assets/SKILL.md`, the document
`worklane install-skill` ships, along with `assets/REVIEW.md`, `assets/PLAN.md` and
`assets/ADMIN.md` for the three jobs done with it. Do not restate any of them here: a
second copy is a copy that goes stale.
## The data
| File | What it answers |
|---|---|
| [ticket-format.md](ticket-format.md) | What a ticket file holds, the metadata fields and the four stamps, how the statuses move it, how a column is ordered, and the four tiers that resolve a search to one ticket |
| [campaigns.md](campaigns.md) | The container that groups tickets across the flow, why its state is derived rather than stored, and where membership lives |
| [relations.md](relations.md) | Recording an edge between two tickets, which direction is stored, the two dependency guards, and how the block is drawn in both renderers |
| [history.md](history.md) | Who an entry is attributed to, the kinds, what is deliberately not logged, and how the old comments directory is adopted |
| [shared-boards.md](shared-boards.md) | The two board layouts, the machine config, the committed pointer, `decide_init`'s table, and how `find_worklane_dir` classifies what it finds |
## The CLI
| File | What it answers |
|---|---|
| [cli-arguments.md](cli-arguments.md) | Which arguments carry `allow_hyphen_values` and which deliberately do not, the empty-value parsers, and the `ls` filters |
| [editing-tickets.md](editing-tickets.md) | `set` against `append`, the one-field-one-writer rule, `--clear`, and ticking a criterion |
| [completions.md](completions.md) | The clap half and the fish half, what the dynamic values cost, and the tests that keep the lists honest |
| [color.md](color.md) | The palette, what each colour is reserved for, the tag colours, and why `color_text` must not be reached from the body |
## The board
| File | What it answers |
|---|---|
| [tui-board.md](tui-board.md) | The columns, the cards, the campaign and tag frames, the pickers, the footer, the hidden terminal columns, and the tabs when several boards are monitored |
| [tui-prompts.md](tui-prompts.md) | The search prompt, the command prompt and its recall, the line splitter behind them, and the copy key |
## The repo
| File | What it answers |
|---|---|
| [architecture.md](architecture.md) | What each `src/` file owns, and the organisation rules that put a function where it is |
| [testing.md](testing.md) | `make check`, the fixtures, and the measured rustfmt and clippy settings |
| [rust-style.md](rust-style.md) | The small conventions this tree keeps in its Rust, including when a command takes an `Args` struct |
| [agent-assets.md](agent-assets.md) | The documents and the opencode tool file the binary embeds, and how `install-skill` and `install-tool` place them |
| [releasing.md](releasing.md) | The commit format, and which changes warrant which version bump |
+32
View File
@@ -0,0 +1,32 @@
# Shipping the Agent Assets
The documents and the opencode tool file the binary carries, and how they are installed.
- The skill is embedded with `include_str!` from `assets/SKILL.md`, not copied by an install script. `cargo install` places binaries and nothing else, so an installed document that is not in the binary is a document that drifts from it
- **`assets/SKILL.md` is the only worklane skill document in this repo, and nothing may reintroduce a second.** There was one: `.opencode/skill/worklane-kanban-skill/SKILL.md`, 223 lines of the same document that nothing shipped and no test checked, and it drifted exactly as far as a copy nobody reads does. Its frontmatter still called the skill `worklane_kanban`, its examples still used short flags the CLI had stopped accepting, and it knew nothing about `relate`, `campaign`, `chown`, `check` or the four-status flow. It was **not** inert while it existed: `opencode debug skill` listed it, so an agent working in this repo saw two worklane skills and could load either. Deleted by b2c5531. A copy under `.opencode/`, in a second assets file, or in the README is the same mistake; the document has one home and `install-skill` is how it travels
- **One install path serves both agents:** `~/.claude/skills/worklane/SKILL.md`. Claude Code reads it, and opencode loads that directory as an external skill source alongside its own `~/.config/opencode/skill/`. Verified against opencode 1.15.10, whose built-in `customize-opencode` skill documents the table and whose `opencode debug skill` lists what it found there. Do not add the second path: it is two copies of one document, free to drift, for no gain
- `Asset` carries the content, the path under its root and the word used in messages, so `install-tool` adds an entry and its own root rather than a second copy of the compare-and-refuse logic. That is why the module is `install.rs` and not `skill.rs`
- `install()` takes the root as an argument. That is what lets the tests install into a temp directory instead of the home of whoever runs the suite, and the integration test redirects `HOME` for the same reason
- **A modified copy is refused, not overwritten.** Someone may have edited it on purpose, and the message names `--print` so it can be diffed and `--force` so it can be replaced. A read error is not treated as absent either: the write reports the real reason
- Three tests guard the document rather than the mechanism, and they are the ones that earn their keep: the frontmatter has to parse (both agents silently ignore a document without it), every `worklane <x>` the skill shows has to be a real subcommand, and every subcommand outside `NOT_FOR_AGENTS` has to appear in the skill. The last one catches a new command that nothing tells an agent about
- `install-skill` looks for no board. The skill is what teaches an agent worklane, so needing a `.worklane` to install it would put it out of reach exactly when it is wanted
- The **agent files** under `.opencode/` are the user's, not this repo's to ship. Do not embed or install them. `reviewing-agent.md` there is the prior art the review skill grew out of and is deliberately **left in place**: its content is now in `assets/REVIEW.md`, but deleting a file under `.opencode/` is not this repo's call. Whether the stale copies there go is b2c5531's question. The tool file is the exception and no longer lives there: it was `.opencode/tools/worklane.ts`, which meant it existed only inside a checkout, and it is now `assets/TOOL.ts` and shipped like every other asset
- **`install-skill` writes every shipped document, and the name narrows it.** One document teaches the CLI and the others teach a job done with it, so a person who learned the invocation before a document existed still receives it. Requiring a name per document would mean a new skill silently never arrives for anyone who does not read the changelog
- **`--print` requires the name.** It exists so a modified copy can be diffed, and a diff is against one document; printing them concatenated would be neither of them. The unnamed case errors with the list of names rather than guessing, the same choice the `comment --` body makes
- The refusal message names the document it is about, `install-skill worklane --print`, since with several installed "compare with --print" does not say compare what
- **A refused document does not stop the ones behind it.** The loop reports an outcome per document and the "pick it up on their next session" line is printed once, and only when something was actually written
- **A role skill is its own document, not a section of `SKILL.md`.** The frontmatter description is the whole of what decides whether a skill loads, and one description cannot name both "anything touching a ticket" and "only when a review is asked for" without fitting neither. It is also why the review document does not restate the CLI: it says to read the `worklane` skill too
- The review skill's own rules are guarded by `the_review_skill_keeps_the_decisions_that_define_it`, because each of them is a line an edit could drop without breaking anything: **the reviewer never ticks a criterion** (a tick is the implementer's claim, unticking is the review disagreeing, and one mark for both loses the disagreement), **never moves the ticket** (`mv` belongs to whoever does the work, the reviewer's half is the recommendation) **unless the work is already on master** (then each finding gets its own ticket, related ones sharing one, and the reviewer moves the original to done once all of them are filed, after a comment saying which ticket holds each remaining issue, since a done ticket with unticked criteria otherwise reads as closed by mistake: sending landed work back to committed reopens shipped code, and leaving it in reviewing with nothing left to do only hides that the review is over), and **never reviews the working tree when no commit names the ticket** (it says what it searched for and stops, since an untraceable ticket in `reviewing` is itself the finding)
- **The plan skill is the one that can do damage, so its rules are the ones under test.** `set --tags` replaces the whole field, so a sweep that restates a ticket's tags incompletely deletes the rest, and a due date is neither validated nor clearable. `the_plan_skill_keeps_the_rules_that_bound_a_sweep` pins propose-then-apply and those two traps, because a document that loses them still reads like a plan
- `.opencode/agent/feature-planner-agent.md` is **deliberately not folded into `PLAN.md`**. It decomposes a feature request into new tickets, which is intake; `PLAN.md` orders the tickets that already exist. Merging them would give one document two jobs and a frontmatter description that fits neither, which is the same reason the review skill is its own document
- **`install-tool` is a second command, not a flag on `install-skill`, because the two artifacts are not alike.** A skill is inert markdown that any agent can read and it reaches both from one path; the tool is executable TypeScript that reaches opencode alone. Claude Code has no directory it scans for a tool definition at all: `claude mcp add` with a `stdio`, `sse` or `http` transport is the only way a tool enters its tool list, and its plugin system adopts `agents`, `hooks`, `monitors`, `workflows`, `output-styles` and `themes` and nothing named tools. So an MCP server, a different artifact, would be what reached it. Verified against Claude Code 2.1.238
- **`tools_root()` follows `XDG_CONFIG_HOME`, `skills_root()` does not.** `~/.claude` is not an XDG path and opencode's config root is: `opencode debug paths` reports `$XDG_CONFIG_HOME/opencode` with the variable set and `~/.config/opencode` without. An empty value counts as unset, the convention `colors_wanted` follows for `NO_COLOR`. `opencode_tool_dir` takes both variables as arguments for the reason `colors_wanted` does, since a threaded test binary cannot mutate the process environment to reach one branch at a time
- **Singular `tool`, and it was measured, not guessed.** opencode 1.15.10 loads `~/.config/opencode/tool/` and `~/.config/opencode/tools/` both: each was served in turn from a directory outside any project and `/experimental/tool/ids` registered every worklane tool the file carried, eleven at the time and twenty-one at the recheck after the wrapper caught up with the CLI. The singular is the spelling opencode's own documentation puts first, the way it writes `agent(s)` and `skill(s)`. `opencode serve` plus that endpoint is how to check this again; there is no `opencode debug tool` to ask
- **`worklane.ts` is the file name the tool ids are built from.** opencode names each tool as the file then the export, so the file's twenty-one `export const` lines become `worklane_add` through `worklane_tags_set`. Renaming the file renames every tool and every permission rule that mentions one, which is why `TOOL.relative` is pinned by a test rather than left as a detail
- **The tool needs nothing installed beside opencode**, which is worth stating because the file is executable and reads as though it wants a toolchain. It is loaded into opencode's own Bun runtime and the `@opencode-ai/plugin` import resolves there: a copy in a project with no `node_modules` anywhere above it registered all of its tools, on a machine with no `bun` on `PATH`. c092ea7's criterion 6 named those two as runtime requirements and it was wrong about both
- **The closing line differs from the skills', and that is not a wording choice.** opencode reads its config once at startup and never reloads it, so a running one keeps the tools it began with; the skills' "on their next session" would be a claim that is not true here
- **The wrapper walks clap in both directions now; until this ticket nothing did.** It was behind by four commands — `relate`, `campaign`, `assign` and `tags` had no tool, so an agent holding the tools could not reach campaigns or relations at all — and nothing compared the file to the CLI, which is how the gap opened and stayed open. `every_tool_the_wrapper_exports_is_a_real_subcommand` catches a tool for a command that has been renamed or dropped, which fails only when an agent finally calls it; `every_subcommand_outside_the_exceptions_has_a_tool` catches the other direction, a subcommand with no tool, through the same walk off clap the completion lists take. Its exception list carries a reason per entry rather than being bare, and one of those reasons was learned from the test's first run: a bare `worklane campaign` is refused by the CLI, its subcommand required, so there is no command for a `campaign` tool to wrap and the five `campaign_*` tools are the command
- **Installing it globally reproduces fb3dec6 for the wrapper.** Global tools apply in every project including this one, so once `install-tool` has run, an agent working on worklane uses the installed copy of `assets/TOOL.ts` and not the tree it is editing. Same trap as the `worklane` on `PATH`, second instance
- `every_agent_facing_subcommand_is_documented` stays on `SKILL` alone. It owns the CLI surface; a role document uses the handful of commands its job needs, and requiring the rest would fill a review document with `init` and campaigns to satisfy a test. The two checks that do run over every document are the frontmatter and that no document shows a command that does not exist
- **The README command table has the same guard, `every_subcommand_has_a_row_in_the_readme_command_table` in `command.rs`.** The skill and the table are the two places a command is discovered, one by an agent and one by a person, and the skill was the only one under test: `campaign` and `assign` shipped in 0.12.0 and were still absent from the table at 0.20.0, e6e3a1b, along with the `--campaign` flag on the `ls` row. It walks clap's own subcommands, one level of nesting included, against the `|` lines of `README.md`, so a new command fails the suite until the table lists it. `help` is excluded, being clap's. The tag subcommands are named in a `PENDING` list rather than skipped, since f7dd1a1 rewrites that row and emptying the list is part of closing it
+44
View File
@@ -0,0 +1,44 @@
# Architecture
Where the code lives and what each file owns.
## Project Structure
- `src/main.rs` - `dispatch`, the one mapping from a parsed command to its handler, the SIGPIPE reset, and the TUI event loop
- `src/command.rs` - CLI argument definitions using clap derive
- `src/completions.rs` - the generated completion script and the fish half that asks the board
- `src/handlers.rs` - one `cmd_*` per subcommand
- `src/util.rs` - the ticket format, resolution, rendering and the palette
- `src/campaign.rs` - the campaign file format, its resolution, its index and its members
- `src/history.rs` - the history log: the path, the kinds, the reader, the writer, the card's counter and the block `show` and the board both render
- `src/board.rs` - the shared-board layout: the machine config, the boards directory, the `.worklane.toml` pointer and the `init` decision table that decides which layout a project is on
- `src/tui.rs` - board state, the change digest, and the ratatui draw
- `src/split.rs` - one pure function turning a typed line into arguments the way a shell does, plus what the half-typed line is still inside and where the cursor sits among them
- `src/clipboard.rs` - the OSC 52 write and the base64 it carries, the board's only way out to the clipboard
- `src/install.rs` - the embedded agent assets and the compare-and-refuse install
- `assets/SKILL.md` - the agent skill for the CLI itself, embedded with `include_str!`
- `assets/REVIEW.md` - the agent skill for reviewing a finished ticket, shipped the same way. Assets are named after the role they teach; `SKILL.md` keeps its name because the role it teaches is the CLI
- `assets/PLAN.md` - the agent skill for grooming the whole board: priorities, due dates, tags and campaigns
- `assets/ADMIN.md` - the agent skill for the board itself: designing and annotating the tag vocabulary, and repairing a board whose files and fields have come apart. The one asset written to hold for a board that tracks no software, so its examples span three subjects on purpose. It draws the line against `PLAN.md` in both directions: this one decides the vocabulary, that one applies it
- `assets/TOOL.ts` - the opencode tool definitions wrapping the CLI, embedded the same way and installed by `install-tool`. The only asset that is not a document and the only one that reaches a single agent
- `tests/` - Integration tests using `assert_cmd` and `assert_fs`, one file per command
- Unit tests live beside the code in `#[cfg(test)] mod tests`, in `util.rs`, `history.rs` and `tui.rs`
- Ticket files stored as `.md` in `.worklane/<status>/` directories
- History entries stored as `.md` in `.worklane/history/<ticket_uuid>/`, one file per entry, beside the status directories for the reason campaigns are
- Campaign files stored as `.md` in `.worklane/campaigns/`, which is beside the status directories and deliberately not in `status_dirs()`
## Code Organization
- **`change` and `split_change` are a pair, and they live beside each other in `history.rs`.** The mechanical body is stored as one string, `before → after`, so painting the halves means splitting it, and the separator is a constant the writer and the reader share. A renderer with its own copy of the spacing would go on splitting on a separator the writer no longer emits, and would say so by drawing a whole body as one half. The split is `split_once`, so a value carrying the arrow itself keeps it
- **The history block quotes who is talking.** Every line of a comment's body draws behind a grey bar spanning the whole run, paragraph breaks included, the way quoted text is drawn — d447e04, taking the review of 2733b10's answer over that ticket's uniform prefix and b304b17's per-line indent, both of which left the continuation at column 0. The reason under a mechanical row draws the same bar. The author line stays at column 0 and is told from a mechanical row by its `From` and its colour instead; the rule a reader learns is that a barred line is somebody's own words and a line of values at column 0 is the tool reporting itself. With colour off the glyph goes but the width it occupied stays, as spaces derived from the drawn form in `quoted_cells`, so a pipe keeps the column without an escape byte
- **A quote is one segmentation, two shapes, and the shapes split on wrapping.** The CLI prefixes each stored line — `quoted_cells`, which is why a terminal soft-wrapping a wide line draws continuations bare: a pipe has no width to honour, and `show` does not wrap by hand. The board quotes as geometry instead (8020e48): a `HistoryPart::Quoted` run becomes an overlay section laid out as two columns, a two-cell gutter holding the grey bar top to bottom and the body beside it, so a row the prose wraps onto inherits the mark from the gutter rather than from its own first characters. `Detail` holds sections for this reason — flow stretches full width, quotes beside their gutters — and the clamp sums the sections' wrapped heights, so scroll and draw measure one total. The newline history writes after every quote is consumed by the section builder rather than drawn: it used to close the quote's last line and the section boundary does that now, so drawing it would bank a blank row no entry ever had. `QUOTE_BAR` lives in `util.rs` because both renderers draw it, not because they draw it the same way
- **`history.rs` owns the log end to end**: the path, the kinds, the parse, the write, the count and the render. It came out of `util.rs` and `handlers.rs`, where the reader, the writer, the counter and the renderer sat in three files and one of them was 5,500 lines. The test for the reason is the module doc: a reader asking what an entry is has one file to open, the way `campaign.rs` and `tag.rs` answer their own questions
- The body's painters return cells, not strings: `ordered_cells`, `inline_cells`, `metadata_cells`, `metadata_value_cells`, `tag_cells` and `push_heading`. `content_trim_colored` is the CLI entry point and `paint_cells` is the only thing that writes an escape. `colorize_line` is gone: it was a `pub` alias for the bold pass with one caller, and the only thing it added was asking the terminal
- **`inline_cells` walks the line once for both inline markers**, `**bold**` and `[text](url)`, rather than running one pass over the output of the other. A second pass would be scanning text that already holds escape sequences, and `\x1b[36m` carries an opening bracket, so the link scan would take the escape for markup. The source is the only string in which either marker means what it says. It was `colorize_bold` while links lived in a branch of their own in `content_parts`; that branch is gone, which is also what gives the criteria text and the metadata `Other` rows their links, since those already went through this function
- `show` renders the Metadata section as a two column table via `metadata_cells`, not line by line. Column width is measured on the raw field names in characters and the padding goes into a cell of its own, so nothing is ever measured with a colour on it: measuring a painted string counts its escapes towards its width. `paint()` is `color_text()` with the colour decision passed in, which is what lets a test render both ways in one process
- The title is printed once, by `cmd_show`. `content_trim_colored` skips the `# ` heading in the file content
- Rules under headings are measured on the displayed name in characters, never on the raw line or in bytes
- `resolve_ticket()` scans all status directories — it's the single source for ticket lookup by UUID prefix, title, or filename
- `parse_ticket_field()` handles extracting metadata values from markdown format
- `move_ticket_file()` stages the updated content in a temp file under `.worklane/`, renames it over the source, and only then renames the file into the target directory. Do not reorder these: renaming first and writing second leaves a ticket in its new directory claiming the old status, and writing to the target then deleting the source puts it in two directories at once. The temp lives outside the status directories so a leftover is never read as a ticket. A failure at the last step leaves the ticket in its old directory with a Status one move ahead, which the next `mv` corrects
- **A move whose target equals the directory the file already sits in repairs a Status field that disagrees with it, instead of refusing as a no-op.** `resolve_ticket` reads the current status off the directory, so the old comparison was the directory agreeing with itself and could never see the field; a hand-moved file was stuck with moving it away and back to fix it. Now the field is compared first: agreement is the ordinary already-in-status report with nothing written, disagreement rewrites the field alone through the same in-place save every edit uses, and reports it as a correction rather than a move. It is gated on neither `-f` nor the dependency guards behind them, because it is not a transition; it writes no stamp, since presence still answers how far the work got and the work arrived nowhere new; and it logs nothing, because an entry shaped like a transition would record a journey the ticket never took. The mirror case is unchanged: a field ahead of its directory after a crash mid-move is corrected by the next real `mv`, because there the target is a status the ticket is not sitting in
- Field lookup, read and write, is scoped to the lines under the `## Metadata` heading and anchored to the start of the line. Prose above it is free text: tickets in this repo quote field markers in their descriptions, and an unscoped search reads or rewrites those instead. `set_status_field()` carries the same scoping
+36
View File
@@ -0,0 +1,36 @@
# Campaigns
The container that groups tickets across the flow, and why its state is derived.
- **A campaign's state is derived, never stored.** Open until every member is done, computed by `Standing` from the members. A `Status` field on the campaign would be the same state in two places, and the two would disagree the moment a member moved. It is also why there is no `campaign mv` and no forward-only ruleset beside `mv`'s
- **A campaign with no members is neither open nor done.** `Standing::state()` returns `None` there, and both callers print `no members`. Calling it done would make a container nothing has been filed against the most complete thing on the board; calling it open would claim work that does not exist
- **Membership is one field on the member**, `Campaign` in the ticket Metadata, written only by `assign`. The member list is deliberately *not* on the campaign: that would put membership in two places, and would make one file that every assignment edits, which is contended the moment two agents share a board. So `add` has no `--campaign` and `set` has no `--campaign`, the same rule as Owner and Status
- **The full uuid is stored and the title is resolved for display**, as the Relations section already does. `reference_cells` 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 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
- **`campaign ls --state` filters on `Standing::state()`, never on the counters.** The derived value has one definition, so a campaign reads `[open]` in the listing if and only if `--state open` lists it. `--state` and not `--status`: the word names one of the five ticket statuses everywhere else in the tool, and a campaign sits in no status directory. The third value is `empty`, matching the `None` an empty campaign derives, because a filter that could not reach those would leave "what has been filed and forgotten" answerable only by reading the whole listing. A filter that matches nothing says so and repeats the value back, since a silent listing reads as the other empty case, a board with no campaigns on it
- **The filter reaches `--ids` as well, and is the only thing that makes that path count members.** `ls --ids` keeps its own filters, so this one keeps its. An unfiltered completion is as cheap as it was: `kept` returns true without reading a ticket when there is no filter to answer
- **The listing is a table, measured on the raw values and padded before anything is painted**, the rule `metadata_cells` follows. A column sized on a painted value counts its escape sequences towards its width, which is what tilts a table when colour is on and leaves it straight when it is off — the one combination an integration test running through a pipe can never see, which is why `the_campaign_table_stands_in_the_same_columns_coloured_or_not` renders both ways in one process and compares them with the escapes taken back off
- **The codename is measured with the title rather than given a column of its own.** A campaign filed without one spends nothing on it, so a column for it would be a column most rows pad into and some rows leave empty. What a reader lines up is where one campaign's name ends and its progress begins, which is one field: the name is the codename and the title together
- **The created stamp is `format_created_at`'s, the same form `ls` prints**, rather than a second spelling of a date. An unparseable one is empty there and the column goes, exactly as it does for a ticket
- **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](tui-board.md)
- **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 set` and `campaign append` are the only writers of a filed campaign's fields.** d637288 decided the command: a `set` rather than a flag on something narrower, because the file has more than one editable thing and the moment somebody wants to fix a typo in a title there would be a second command to design. `set` carries `--title`, which renames the file the way `set --title` does, `--description` and `--codename`; `append` carries `--description` alone. `campaign add` writing a field at creation is not a second writer, exactly as `add --title` and `set --title` coexist
- **Replacing a codename the campaign already has needs `--force`.** Once a campaign has one it is referred to by it: it is on every card in the campaign, it is what resolves the campaign at the command line, and it is in somebody's shell history. Changing it silently is the mistake `install-skill --force` exists to prevent, so it is refused and the refusal names both words and the flag rather than leaving it to be found. Checked before any edit is applied, like `SetArgs::contested`, so a call also carrying `--title` writes neither field. Setting the codename a campaign already carries stays a **no-op, not a refusal** — `--force` is about overwriting a *different* word, which is the same division `install::Outcome` draws between `Unchanged` and `Refused`. `--force` guards the codename alone: a campaign always has a title, so guarding that would mean the flag was always required
- **The description arrived as a pair, `set --description` and `campaign append`, 32e98ab.** Never one without the other: for a prose section `set` replaces and `append` adds, and a way to replace a description with no way to add a paragraph is the half that is easy to reach for and wrong, since replacing a description to add a sentence to it is how the rest of it gets lost. The two scalars have no append form at all, which is the same line `append` already draws for a ticket, and `campaign_append_offers_only_the_description` pins that. Neither flag takes `--force`: a description is prose written to be revised, the same reason `tags set --annotation` has none
- **`append` is a campaign's own subcommand, not the top-level `append`.** That one resolves a ticket, and one positional naming either object is the ambiguity `resolve_in` makes real: its tiers are the same over both directories, so a search can resolve in each and nothing but a flag could say which was meant. It would also make a liar of `resolve_ticket`, which explains a ticket search that *names* a campaign. Under `campaign` the object is settled by the command, as it is for `set`, `show` and `ls`
- **Still no `--owner` and still no `--clear`.** No `--owner`, because nothing writes a campaign's Owner today and giving `set` one would settle by accident whether `chown` grows a campaign. No `--clear`, which 32e98ab settled rather than deferred: a codename is replaced rather than emptied, and emptying the description of a container six tickets are filed against is not a thing anybody has asked for, so the only spellings left would be `Clearable` on a campaign, whose variants are a ticket's fields, or a second enum with one variant in it. `campaign_set_offers_no_owner_and_no_clear` pins both
- **An empty `--description ""` is a paragraph break here too, and the refusal for an all-blank value names no flag.** Every prose argument in the tool reads a blank value that way, `add`, `set` and `tags --annotation` alike, so a campaign reading it as *empty the section* would be the one exception. With no `--clear` to point at, the refusal says a campaign's description has no cleared form instead of naming a flag that does not exist. `replaced_items` is where the check lives, shared with `set`, and the way out is the caller's argument for exactly that reason
- **`SECTION_ORDER` needs no campaign variant, and that is what the one-section file proves.** A campaign holds Description and Metadata where a ticket holds four sections and Metadata. Every consumer of the list looks for the headings that follow, *filtered by what is actually in the file*, so a campaign's description anchors against `## Metadata` — which is where `campaign_body` writes it. `the_description_is_edited_in_place_in_a_file_with_one_section` pins that no section a campaign does not have gets inserted to anchor against
- **A campaign whose Description heading is gone is refused, not given the section back.** No `ensure_section` on this path: every campaign the tool has ever filed carries the heading, so an insertion here would be reachable only from a hand-edited file, which is the opposite of the Relations case, where `add` writes nothing and the insertion is the only path there is. The refusal therefore names the section and **not** the object — "There is no description section to write to" — because both a ticket and a campaign reach `replace_section_body` now. `write_then_replace` still carries the noun, where the message is about a file
- **The codename is written through `set_or_insert_metadata_field`, not `set_metadata_field`.** Every campaign filed before the field existed has no such line, and those are exactly the campaigns the command is for, which is the same reasoning that puts `assign` on the upsert. **`Codename` is therefore in `METADATA_ORDER`, directly after ID**, so an inserted one lands where `campaign_body` writes it and a campaign given a codename later is the same file as one filed with it. Nothing upserts it on a ticket, so its place in a ticket's order costs nothing
- **One write path for tickets and campaigns.** `save_entry` is the body, `save_ticket` and `save_campaign` are the named wrappers, and `write_then_replace` and `find_entry_file` take the noun as a `&str` so a failure says "campaign" where it is one. A campaign file is a ticket file in every way that matters here, `<uuid>_<slug>.md` in a directory, and the rename happens only after the write has landed. Every message puts the noun mid-sentence so there is no capital to case
- `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
+29
View File
@@ -0,0 +1,29 @@
# The Command Line Surface
How arguments are defined and validated, and how the listing is filtered.
## CLI Arguments
- The prose arguments carry `allow_hyphen_values`, via the `PROSE` constant in `command.rs`: `add --title`, `--description`, `--acceptance`, `--plan`, and the `comment` body. Ticket text quotes flag names constantly, and without it a criterion reading `--print is supported` is parsed as a flag and the whole ticket is refused with nothing written
- **The trade:** on those five arguments a genuinely mistyped flag now lands as content rather than raising a usage error. That is the right way round for prose and the wrong way round for anything else, which is why `due`, `priority`, `tags`, `owner` and `status` are deliberately left without it. A mistyped flag there is still a usage error, exit 2, and no ticket is written. Do not add `PROSE` to a new argument unless it holds prose
- **`--due` is validated at parse time by `iso_date`, the way `--priority` is by `priority_level`.** A date that is not real is a usage error, exit 2, with nothing written, which is the whole point of leaving the scalars without `PROSE`. One parser serves `add` and `set`: the field has one definition of what it accepts, and validating only `add` would leave `set` open, which is the command a grooming sweep actually uses
- **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. **`append --tags` is the one place the field has an empty form and the argument still takes `non_empty`**: `append` has no `--clear` of its own, so naming one would send the caller looking on this command for a flag that is `set`'s
- **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 <id>`, `mv <ticket>`, `comment <ticket>`) 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`
- A bare `--` is a value when it follows an option (`--title -- ` stores `--`) and clap's end-of-options marker when it sits in a positional. So a `comment` body of exactly `--` needs its own separator, `comment <ticket> -- --`. Without it the body is reported missing and nothing is written, which is a clear failure rather than a silent drop
- `add` has no positionals, so anything after a bare `--` is an unexpected argument and fails
- **A paragraph break in a description is an empty `--description` value.** `cmd_add` joins the values with a single newline, so `-d "First." -d "" -d "Second."` writes the blank line. `trim_blank_ends()` drops blank values at either end, so a break never lands against a section heading, and an all-blank description reads as no description. Interior runs are kept verbatim rather than collapsed
- `--acceptance` and `--plan` are lists, one criterium or step per value, so a blank there is spacing rather than content and the opencode wrapper drops it. Only `--description` preserves blanks
## Filtering the Listing
- **The filters are one call, `filtered`,** because `ls` collects a column in three places (a named status, the counts, and the grouped listing) and three call sites are three chances to apply a different set. Every filter is an `Option` and none asked for keeps everything, which is what makes them compose in any combination without a rule per pair
- **`--tag` matches whole values, not the field.** `parse_tags` has already split the comma-separated field, so the filter compares against those trimmed values: `--tag bug` is not answered by a ticket tagged `bugfix`, and `--tag "cli, filter"` matches nothing, because the field as written is not itself a tag. A ticket with no tags matches none
- **Case sensitive**, the opinion the field already takes: `tag_color` draws `Bug` and `bug` in two colours because they are two tags. A filter that folded them would list tickets carrying a tag nobody asked for, and would hide exactly the split a grooming sweep is looking for
- **One tag per invocation.** Several would have to decide between and and or, and neither reading is obviously right for a board this size. That decision is its own ticket, along with a substring or regex match and a tag filter on the tui
- **A tag nothing carries lists nothing rather than being refused**, which is the opposite of `--campaign`. A campaign is an object that either exists or does not, so it is resolved before anything is read and an unknown one is an error. A tag is free text with no registry: there is nothing to resolve against, and refusing an unknown one would mean maintaining a vocabulary the format deliberately does not have. `assets/PLAN.md` tells the agent to check the spelling when a listing comes back empty, and `worklane tags` is what it checks against, since that is the failure this trades for
- An emptied status keeps the message `ls` already gives, `No tickets in '<status>' status.`, rather than one per filter naming what excluded them. That is pre-existing behaviour for `--priority` and `--campaign`, and one message for every filter is the consistent half of it. If it should name the filter, that is a change to what the CLI prints for three flags at once and belongs in its own ticket
- **`cmd_ls` takes an `LsArgs`**, which is what the boundary in the [Rust Style](rust-style.md) rule came to: four filters, an output mode and the directory, two of them adjacent `Option<String>` values a caller could swap silently. `--ids` was the argument that tipped it, the way `add` became `AddArgs`. A new filter is a field there, not a parameter
+42
View File
@@ -0,0 +1,42 @@
# Colour
The palette, what each colour means, and the rule that keeps one layout for two renderers.
## Color and Output
- Use `color_text()` for coloured output — it respects `should_use_colors()` (terminal detection), and `paint()` is the same with the decision passed in
- **`color_text()` is for the CLI's own printing only. Anything reachable from `content_trim` takes the decision as an argument and calls `paint()`**, because the board renders with colour off and an escape sequence in a ratatui paragraph is drawn as literal bytes. `nothing_the_body_renders_asks_the_terminal_for_the_colour_decision` scans this file and fails on a new caller; the allowlist is `ambiguous`, which builds a failed-search message for stderr
- A function that takes an `enabled` flag must use it all the way down. The inline pass honoured its flag on the early return and then asked `should_use_colors()` for the bold run, which made the flag a lie in half the function. The better answer, where it fits, is to take no flag: `ordered_cells` and `metadata_value_cells` return the colour rather than a decision about it
- **A test that asserts an absence has to be paired with one that asserts the presence.** The guard for this, an assert that the detail view holds no escape byte, could not fail: a test binary has no tty, so `should_use_colors()` was false and the leaking branch was never taken. The pair is now `content_trim(.., false)` has no escape and `content_trim(.., true)` still colours, which pins the flag as the only thing that decides
- **The palette is the `Color` enum, not a string.** `Color::ansi()` gives the CLI its SGR sequence and `From<Color> for ratatui::style::Color` gives the TUI its equivalent, so a colour that exists for one renderer and not the other is a compile error. The stringly-typed version needed a test for exactly that, and a missing entry silently produced an empty prefix, which is how `magenta` came to be undefined
- Reset color with `\x1b[0m` after colored text
- Bold uses `\x1b[1;35m` (magenta bold)
- Always test color output works correctly in both terminal and pipe modes
- `quiet_broken_pipe()` runs first in `main`, restoring the default `SIGPIPE` disposition. A truncated pipe therefore kills the process with signal 13, which a shell reports as 141, instead of making `println!` panic. Do not wrap prints to handle write errors and do not reinstate `SIG_IGN`; the exit codes are documented in the README
## Color Guideline
- UUID → red (31)
- Status → orange (33)
- Timestamp → cyan (36)
- Title → green (32)
- Unknown values (`_None_`, `_Not set_`) → grey (38;5;8)
- Priority ramp → brightred (1), red (2), orange (3), cyan (4), grey (5). Green is deliberately absent: it means title
- 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 `●` discarded, grey `?` for a target the board does not hold. Discarded takes the full circle of done in the grey of the untouched pile: nothing is left to do, and it is not an achievement. The *pair* is what has to be unique, which is the same bargain the two half circles already take, and `every_status_has_a_mark` pins it against `status_dirs`. 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
- **Relation row to a discarded target → struck through, the whole row.** The one thing in the palette that is not a colour, and it is here because the status mark cannot carry it: that mark is one cell in a column of five states, so a row pointing at abandoned work reads as a live dependency, which is exactly what it is not. The strike says the relation no longer stands for anything while the row stays on the ticket, for completeness and for the case the target is moved back out of discarded. Only discarded: a done target still stands for the fact that it was a blocker, and a `_missing_` one says something different again, that the row cannot be resolved at all. Gutter and padding included, so the line runs unbroken from the label to the end of the title, and every cell opens its own SGR 9 since each is closed by its own `RESET`
- **The strike is under the colour flag, like every other escape.** A piped `show` carries none of it, the same bargain committed and reviewing already take for being told apart by colour alone, and the board draws it as a style instead. Do not answer the pipe by changing the glyph in the mark column: the pair there has to stay unique, and `every_status_has_a_mark` is what says so
- Markdown link → cyan, markers and url kept. Not a new meaning for the colour: the plan numbers, the criterion numbers and the `relates to` mark are already cyan inside a rendered body, and a link is the same kind of thing, a pointer the reader may follow rather than a value. The url is not hidden behind the text the way a renderer would hide it, because `show` prints to a terminal worklane cannot assume will make it clickable, and a link whose target cannot be read is worse than a long line
- Chrome → grey. A rendered `[ ]`, the overlay's page indicator and the frame's. 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
- **A key name → cyan, and bold; what pressing it does → the default foreground.** The one place the palette spends a colour on something that is not a value: a key is what a reader is hunting for on a row they otherwise skip, and with the key merged into its description the colour is the only thing saying which letter to press. Not a second meaning for the timestamp's cyan in any place the two could be confused — nothing on the footer, the prompt or a border hint holds a value at all — and it is the accent frig draws the same row in, which is the point. Grey stays on the chrome around it: the page indicator, and the row's gaps
- Chrome → grey, in the history block too: the kind label at the head of a mechanical row, and the `From` on a comment's author line. Both name their row rather than holding a value, which is what grey already says. The label was orange, which means Status everywhere else, so an `owner` or `tags` label claimed a meaning belonging to the value beside it
- **A value in the history block takes the colour it has in the metadata table three lines above.** A status is orange, a tags entry goes through the same `tag_cells` the Tags field does, a campaign codename takes `tag_color` bare the way `Codename` does, and `_Not set_`, `_None_` and `_missing_` are grey. An owner stays plain: a person's name is the one value the palette has no meaning for, and spending a colour on the field that needs it least is how a colour stops meaning anything. The block's job is to be scanned, and it is not worth scanning if it has a palette of its own to learn first
- History actor → its name through `tag_color`, the way a campaign codename is. Not a new meaning for a reserved colour but the existing use of the tag slots, a name that groups rows: one writer is one colour in every entry it wrote, so a reader sees who has been working a ticket without reading the same name four times. `claude`, `opencode` and a person each get their own
- History timestamp → cyan, and its own span. It shared one with the actor while the two were formatted as `name (time)`, which spent the timestamp's colour on a name. The parentheses are plain: they are punctuation, not chrome with something to say
- 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
- **The index is multiply-shift, not `% TAG_COLORS.len()`.** The length is a power of two, so a modulus keeps only the low three bits of the hash, and FNV-1a's low bits carry only the low bits of the input bytes: multiplication cannot move information downwards. Under a modulus every pair of tags differing above bit 2, `bug` and `BUG` among them, landed in one slot regardless of the rest of the string. It looked like a *good* palette on this board, two colliding cards out of sixty-four, because the vocabulary had been folded into a handful of slots. Taking the top bits of a 128-bit product uses the whole hash
- Eight tag colours means roughly one card in five shows two tags alike. That is arithmetic and is accepted: the colour groups a tag across cards, it does not tell two tags apart within one, and the tag text is beside it either way. Do not widen the list to chase the number on one board
- Grey is indexed colour 8 in the 256-colour form, not SGR 90 or 37. Both of those failed on a real palette: 90 leans on the bright-black slot and 37 can sit on top of the default foreground. `\x1b[38;5;8m` is byte for byte what crossterm emits for ratatui's `Color::DarkGray`, the grey frig and pantop use for dimmed rows
+26
View File
@@ -0,0 +1,26 @@
# Shell Completions
The generated half, the fish half, and what keeps the two honest.
- **Two halves, and the split is the point.** `clap_complete` generates the structure from the clap definition, so a new flag or subcommand is completed without anyone touching `completions.rs`. Only fish gets the second half, appended by `fish_dynamic()`, and it holds exactly what clap cannot know: the tickets on the board
- **The dynamic values come from worklane itself**, as `worklane ls --ids` in a command substitution, one run per keypress at 2.5ms in release. So the completions are only as current as the binary on PATH: an older one without `--ids` completes nothing, which is a reinstall rather than a bug
- **What clap does and does not emit.** It emits the possible values of an *option*, which is why `mv --status <TAB>` needs nothing here, and nothing for a *positional*, which is why the `ls` status and the `completions` shell are listed in the fish half. Both lists are read off the enums with `possible_values`, never written out, so a fifth status appears in the script on its own
- **Position is counted, not inferred.** The four `__worklane_*` predicates all read `$tokens[2]` and the token count rather than using `__fish_seen_subcommand_from`, because `campaign ls` and `campaign show` are also an `ls` and a `show` that fish has seen, and because matching against the ticket list would run worklane again inside the condition. `first_arg_of` and `second_arg_of` count a top-level command's arguments, `nested_arg_of` matches a parent and a child so `campaign show <TAB>` can be told from `chown alice <TAB>`, which sit at the same token count, and `command_is` asks only which command this is, at any position in it
- **Every rule carrying `-l` needs a `__worklane_command_is`, and `every_rule_naming_an_option_is_scoped_to_a_command` is what enforces it.** A bare `complete -c worklane -l tag` does not just complete that option's values, it tells fish the whole tool accepts `--tag`: `worklane init --<TAB>` offered six options that only `relate` and `ls` have. Fixed in 55ee6e3. `__fish_seen_subcommand_from ls` is not the scope to use, for the nesting reason above
- **The strongest completion check loads the script into fish and asks it for candidates.** `fish_offers_the_commands_the_statuses_and_the_values` in `tests/cmd_completions.rs` sources the generated script into a throwaway shell standing in a real board, with this build's directory on the front of PATH, and compares `complete -C` against the ticket and the tag it put there. Every other test in the file reads the script as text, which cannot tell a rule that fires from one whose condition stopped matching, and that is how a completion actually breaks. **Assert the values, not the flag names**: clap emits every option's name on its own, so `--tags` and `--blocked-by` are offered with every hand-written rule deleted; what the dynamic half adds is what comes *after* the flag. Two traps, both paid for once: the shell must have `fish_complete_path` emptied, or `complete -C` autoloads `~/.config/fish/completions/worklane.fish` and answers from whatever version wrote that, which is a guard that cannot fail; and the script is written beside the board rather than in it, since a rule that fires nothing falls back to listing the directory
- **`fish --no-execute` is the floor under that, not an oracle.** It catches a script that does not parse, quotes still open at the end of the file or an unclosed block. Measured, not assumed: an apostrophe interpolated into a `-d` description partway down re-balances against the next quote and parses, corrupting every rule in between while the check passes; the same apostrophe in the last rule reaches the end unbalanced and is caught. Only fish gets this, because only fish gets a hand-written half
- **The rule counts in the completion tests are hardcoded on purpose.** The walkers go clap → list and never see an entry naming something that does not exist, so a bogus pair in `TAG_FLAGS` is caught by `every_tag_rule_takes_the_annotation_as_its_description` counting one rule too many. Deriving that number from the lists it checks would grow with the bogus entry and pass. The `seen` totals in the walkers are hardcoded for the mirror reason, and both carry the note
- **The completion lists are kept honest by tests** that walk the clap definition and fail on an argument left out of them. `TICKET_COMMANDS` and `TICKET_SECOND_COMMANDS` by position, `TICKET_FLAGS`, `CAMPAIGN_COMMANDS`, `CAMPAIGN_NESTED_COMMANDS`, `CAMPAIGN_FLAGS` and `TAG_FLAGS` likewise, the last against the test-local `TAG_LIST_FLAGS` and `TAG_NEW_COMMANDS` for the tag arguments that deliberately get no rule. The walk is one function, `every_argument`, since the tests differ only in the id they look for. Each also asserts *how many* it found, so a walker that stopped finding arguments fails rather than passing every assertion by never running them
- **A campaign is named in three shapes and a tag in one**, which is why the lists are not one list: a campaign is `assign`'s first positional, the first argument of `campaign show` and `campaign set`, and `ls --campaign`'s value, and each needs a different fish rule. A tag is only ever an option value, and its values come from a different command
- **`TICKET_FLAGS` holds pairs, the command and the flag, and every ticket rule in the fish half is generated from it.** Three commands carry a `--clear` and each takes something different: `chown`'s names the ticket, since with no user to give there is no positional for it; `relate`'s takes the kind and then the target; `set`'s takes a field name clap already offers. So the command is half of the fact, and a list of bare flag names could only be scoped by hand, which is what the `chown --clear` rule used to be. `every_ticket_flag_is_a_real_option` walks each pair against the command it names, which a flat list could not do
- **The lists answer the board as well as the shell.** `argument_at` reads every one of them to say what the argument at a given index of a typed line names — a ticket, a campaign, a tag, or a fixed list it takes off clap — which is what the command prompt completes against, see [tui-prompts.md](tui-prompts.md). Position is counted there exactly as it is counted here, so the two cannot come to disagree about `mv --status done <ticket>`; a second table on the board would be a copy the tests above never read. The values are the one half that is not shared: fish runs `worklane ls --ids` and the board reads the rows the tab already holds
- **`TAG_FLAGS` holds pairs where the others hold names**, because the two options that take one tag are spelled differently: `ls --tag` filters on one and `append --tags` adds them, so a single rule naming both would tell fish that each command accepts the other's flag. One rule per pair, generated in `fish_dynamic`. `add --tags` and `set --tags` are in the test's `TAG_LIST_FLAGS` instead and get no rule: they take the *whole* list, so the token at the cursor is `bug,tui` and fish replaces a token entire, which would throw away what is already typed. The test walks both `tag` and `tags`, so the next one has to say which of the two it is
- **A `ValueEnum` is never listed twice, and `argument_at` is why the fish half's two hand-written value lists are the only ones.** clap emits the possible values of an *option*, so `mv --status` and `set --clear` need nothing here and the board reads them off the same definition with `Arg::get_possible_values`. The `ls` status and the `completions` shell are positionals, which the fish generator emits nothing for, so those two are written into the block from the enums — and the board reaches them through `get_positionals`, which needs no `Command::build` the way `get_index` would
- **`RELATION_KIND_FLAGS` is the one position clap cannot answer for.** `relate --clear` takes a kind and then a target, two values of different kinds under one flag, so possible values on it would refuse every target. Both renderers therefore say so themselves: the fish rule lists `RelationKind::ALL` and the table names the pair
- **`ls --ids` is the machine-readable listing**, and one of the three outputs in the tree meant to be parsed: the short id, a tab, the title, unstyled. Two fields because fish reads what follows a tab as the description and a script reads `cut -f1`. It includes done, which the decorated listing leaves out, because a completion has to be able to name a finished ticket, and it skips a missing status directory rather than refusing, because an error printed over a shell prompt is worse than no candidates. The filters still apply, and an unknown `--campaign` is still refused
- **A flag is recognised by either spelling, `--status` and `-s` alike.** `long_name` translates the letter through the command that holds the flag, so every table above stays keyed on the long name and nothing here keeps a second list of the letters. The prompt read a flag by its two hyphens until then: `mv --status ` offered the five statuses and `mv -s ` offered nothing. **One letter, never a cluster** — `mv -fs done` would be the honest reading of the last letter, but `--title`, `--acceptance` and a comment body all take a leading hyphen on purpose, and a criterion typed as `-fixes the offset` must not be answered with statuses. `a_short_flag_answers_what_its_long_spelling_answers` walks every option with both spellings on every command and nested command, so an option given a letter tomorrow is covered the day it is given one
- **The fish rules name the letter too, `-s g -l tags`.** The same hole on the other half: `append -g <TAB>` offered nothing where `append --tags <TAB>` offered the board's tags, because the dynamic rules were rendered with `-l` alone. `fish_option` reads the letter off the definition per command, so a rule for an option with none is what it always was. Clap's own generated half already emitted both spellings, which is why only the dynamic rules were short
- **A flag's possible values are read off the command that *holds* the flag, nested or not.** `argument_at` resolves the group's child when the second word names one, so `campaign ls --state` reaches `ls`'s own arguments rather than `campaign`'s, which carry no such flag. Without that the prompt offered nothing where fish offered the three values, and the promise that a `ValueEnum` added anywhere is typeable on the board the day it is added held only for a top-level command
- **`campaign ls --ids` is the same flag and the same two fields for the other object**, and it deliberately skips the member counting the decorated listing does: `members()` reads every ticket on the board, and the caller here is a shell filling in candidates on a keypress. It also prints nothing on an empty board, where the decorated listing prints a sentence, because a sentence offered as a candidate is worse than no candidates
- **`worklane tags` is the third, and it is a command rather than a mode on `ls`.** Two reasons: `ls --tag <tag>` answers what carries a tag and cannot answer what tags exist, which is the question a grooming sweep starts from, and a `--tags` beside a `--tag` is one letter from a filter that means something else. Alphabetical and case sensitive, matching the filter, so `bug` and `Bug` list separately and land next to each other, which is where a near-duplicate is spotted. Every status, done included: a tag that has fallen out of use is still part of what the vocabulary has been. `assets/PLAN.md` used to tell the agent to count tags with a `show` per ticket, and now points here
+47
View File
@@ -0,0 +1,47 @@
# Writing to a Ticket
The writers of a field, the one way to take a value away, and ticking a criterion.
## Editing a Ticket
- `set` replaces a field, `append` adds to a section. The verb carries the meaning, so no flag needs a replace-or-append prefix, and `append` only offers the sections that hold multiple lines
- **One field, one writer.** `set` has no `--owner` (that is `chown`'s) and no `--status` (that is `mv`'s), and neither `add`, `set`, `append` nor `chown` can reach the three status stamps, which `mv` writes as a side effect of the move. Do not add any of them
- `chown` takes the **user first and the ticket second**, after Unix `chown`, and is the only command that does not start with the ticket. Deliberate: the name borrows the Unix association, so the order borrows it too. A swap is left to `resolve_ticket`, which refuses a bare username as a ticket. No argument is inspected to see whether it *also* names a ticket, since such a check would only fire where resolution already fails and would stay silent on the one case it cannot catch, a ticket whose title is the username
- `cmd_chown` is `set_metadata_field` plus `save_ticket`, with the same whole-file no-op comparison `set` uses and the same `report()` output, so nothing about writing a field lives twice
- `apply()` is the one place an edit is taken or dropped, shared by `set`'s replaced list and its cleared one. It was a closure over the single list until there were two, and two closures carrying one rule is how a later edit changes it for one and not the other
- Sections are a table in `util.rs`: `DESCRIPTION`, `ACCEPTANCE`, `PLAN`, each with a heading, a label, the placeholder `add` writes when empty, a `SectionKind` and the `--clear` value that empties it. Adding a section later is one entry, not edits in both commands
- Everything is targeted line surgery, never a regenerated file. That is what keeps a ticked criterion ticked and a handwritten `## Notes` section intact when an unrelated field changes. `section_body()` finds the lines to touch, `set_metadata_line()` does the metadata, and every other byte is copied through
- Appending to a numbered section continues from the count of steps already there and does not renumber what is above it, so a handwritten line in the section survives exactly as written
- Appending to an empty section replaces the placeholder rather than following it, or the ticket would read `_No description provided._` above its description
- An empty value is a paragraph break for the three sections and a usage error for the scalars, via `non_empty` and `clearable` in `command.rs`. Neither spells clearing, and both errors name the flag that does
- **A call whose values are *every one* blank is refused, by `replaced_items` for `set` and `appended_items` for `append`.** The check is the section's rather than the object's, so `campaign set --description` shares it. What differs is the way out, which is why `replaced_items` takes it as an argument: a ticket's section is emptied with `--clear <field>` and a campaign's description cannot be emptied at all, so a single hard-coded tail would name a flag that does not exist on one of the two
## Clearing a Field
- **`set --clear <field>` is the one way to take a value away, and it is a flag with the field as its value.** Not a per-field `--clear-due`, which is a flag per field to keep in step with the field it undoes, and not an empty value, which is already a paragraph break for a section and would make an accidentally empty variable a silent delete. Repeatable, so one call empties as many fields as it likes
- **`Clearable` is a `ValueEnum` in `util.rs`**, so an unknown field is a usage error at the door listing the six that are not, and the shells complete them for free. It is also the whole table of what can be cleared: `Due`, `Tags` and `Priority` clear to a sentinel, `Description`, `Acceptance` and `Plan` to their section's placeholder. `Title` is absent because it addresses the ticket and names its file, so there is no state to go back to; `Owner`, `Status`, `Campaign` and the stamps because clearing them through `set` is exactly the second writer the missing `set --owner` exists to prevent
- **What is written is `NOT_SET` and `NONE`, the constants `add` writes.** A cleared ticket and one that was never given the field have to read the same, or clearing would be a third state that every parser then has to know about. `a_cleared_ticket_reads_like_one_filed_without_the_fields` compares the two files byte for byte, which is what keeps a new field honest
- **The placeholder goes into a section bare, via `clear_section_body`.** `set_section_body` runs its items through `Section::render`, which would write `- [ ] _No acceptance criteria provided._`. Both are `replace_section_body` underneath, so the line surgery and the trailing blank line live once
- **The pairing between a section and its `--clear` value is stored on both**, `Clearable::unset` one way and `Section::clear` the other, because the error for an empty value has to name the flag for *that* section and the section's label ("acceptance criteria") is not the flag's value ("acceptance"). `every_clearable_section_points_back_at_the_field_that_clears_it` keeps the two directions from drifting. `RELATIONS.clear` is `None`, the same rule that keeps it out of `section_args`
- **Cleared fields are reported apart from replaced ones**, as `Cleared due on '...'` beside `Updated priority on '...'`. One list would say `Updated` of a field that was emptied, which is the opposite of what a caller needs to read back. The labels are the ones `set` already prints when it *writes* the field, so the two lines name a field the same way
- **Replacing and clearing one field in a single call is refused**, by `SetArgs::contested`. clap cannot express it, because the field arrives as `--clear`'s value rather than in its name, and answering by whichever was applied last is a silent answer to a contradictory call
- **Clearing the owner is `chown --clear <ticket>`, and `--clear` carries the ticket.** Owner has one writer and clearing it cannot introduce a second, so it lives on `chown`; but the ticket is `chown`'s *second* positional, and a bare flag would land it in the user's slot for the handler to read back out, which is hand-parsing what clap can state. The typed call is identical either way. `ChownArgs::target` returns the one shape the constraints allow, and an error rather than a panic for the combination they already refuse
- **Clearing the owner writes `NOT_SET`, not the git user.** `add` falls back to the git user because it is filing something new; an owner taken away says nobody owns this, and putting the person running the command there instead hands them a ticket they were giving up
- Clearing a field that is already unset writes the sentinel that is already there, so the whole-file comparison below reports no change and nothing is written. That is not a special case, and must not become one
- No-op detection compares the whole file before and after each edit, so a field set to the value it already holds is reported unchanged and nothing is written
- `find_ticket_file()` matches on the uuid, never the title. Duplicate titles are allowed, so a title scan can land on a different ticket than the one resolved: `mv <uuid-of-second>` used to move the first ticket sharing its title
- `write_then_replace()` is the only way a ticket file is written. Content first, rename second, so a failure leaves a correct ticket under a stale name rather than a half-written one
## Checking Off a Criterion
- `check` and `uncheck` are separate commands, not one verb with a flag. They share `CheckArgs` and `cmd_check(args, checked)`
- `criteria()` is scoped to the Acceptance Criteria section and counts only checkbox lines, so a checkbox written into a description is not a criterion and a handwritten line inside the section takes no number
- `set_criteria()` splices only the character between the brackets, and takes every line in one pass. Rebuilding the line would normalise its indentation and whatever spacing followed the checkbox
- Each criterion term is the keyword `all` first, an index second, a substring third. So a criterion whose text is literally `2` is reachable only by substring, and one whose text merely contains "all" only by its number or a longer substring. `is_all_criteria()` and `is_index()` sit beside each other in `util.rs` for that reason
- **The keyword wins over the text on purpose.** Ticking every box is the reason the word is typed, and a board where `all` sometimes means one criterion and sometimes means the lot would be worse than one that can be addressed another way. `all_is_the_keyword_and_not_a_substring_of_the_text` pins it against its own fixture, so the shared one keeps its three criteria and its numbering
- **A number out of range is a bad index, not a failed substring search**, and says so. `is_index()` makes that distinction
- Any listing of a subset must keep the real numbers, via `numbered_criteria()`. Renumbering the matches from one contradicts the advice to use the number and points at the wrong criterion
- With the criterion omitted: prompt when stdin is a terminal, otherwise return the numbered list as an error. Never prompt unconditionally, the opencode wrapper has no tty and would block on a stdin that never closes. This is the same choice `resolve_ticket` makes for an ambiguous match, and for the same reason
- **The criterion positional is variadic**, so `check <ticket> 1 3 "the footer"` is one call and one write. Variadic rather than a repeated flag: the terms address criteria that are already there, the way the ticket positional does, instead of carrying content the way `--acceptance` does. The prompt path is unchanged and fires on an empty list
- **`resolve_criteria()` resolves every term before a byte is written, and one bad term refuses the whole batch.** A call that ticked the terms it understood and then failed would leave the ticket half-marked with nothing in the file to say which half was meant. It names the offending term alone rather than every failure at once, since each message carries the criteria listing and a batch of them would repeat the list per bad term
- The chosen offsets are sorted and deduped, so the report reads in `show`'s order whatever order the terms arrived in, and a criterion named twice, or by both `all` and its own number, is marked and reported once
- **Every named criterion gets a line, in `show`'s order, printed after the write.** A criterion already in the target state reads `Already checked 2: text` and does not count towards the write, so a batch where every box is already ticked writes nothing, which is the whole-file no-op rule the editing commands keep. The number is on the unchanged line too: without it a batch cannot be read back against `show`
- `show` numbers the criteria as `1. [x] text`, so the index is visible where the ticket is read. The number replaces the list marker rather than joining it
+33
View File
@@ -0,0 +1,33 @@
# History and Attribution
Who an entry is attributed to, and what the log does and does not record.
## Who Wrote an Entry
- **Identity is supplied, not detected.** Every option that needs no cooperation fails: a harness variable such as `CLAUDECODE` names the tool rather than the instance and breaks across versions, walking the parent process is platform specific and also only names the harness, and a terminal check separates interactive from not, which a human piping output is too. So the actor is `WORKLANE_ACTOR`, set once per session, with `--actor` as the per-call override
- **Precedence: flag, then `WORKLANE_ACTOR`, then `get_git_user()`, then `unknown`.** With `--actor-from-git` and no explicit value the git user is lifted *above* the variable rather than added beneath it — the flag says attribute this to the human, and a machine with no git user configured reads `unknown` instead of quietly attributing back to the agent. An explicit `--actor` wins outright either way. `resolve_actor` is the only caller of `get_git_user` for an entry's author, and every entry the CLI writes goes through it. The halves are separate pure functions, `session_actor` (the variable alone now) and `entry_actor`, tested without touching the process environment for the reason `colors_wanted` is split that way
- **A command typed at the board is the person's, not the session's.** `dispatch` takes an `Attribution`, `Session` from `main` and `Person` from the command prompt, and `Person` asks for `--actor-from-git`'s lift without the flag: nothing but the reader can type that line, and a person who exported `WORKLANE_ACTOR` where their own shell picks it up — the obvious way to configure it for the agents on that machine — would otherwise watch their own `mv` recorded as the agent's. An explicit `--actor` still wins there, which is how the reader puts somebody else's name on their own keystrokes, and with no git user configured the entry reads `unknown` rather than falling back to the variable, for the reason the flag does. `entry_actor` takes it beside `from_git` and the two are one branch, since `--actor-from-git` typed at the prompt asks for what the prompt does anyway
- **The attribution is a parameter of `dispatch`, not a field the prompt writes into the parsed arguments.** Rewriting what clap produced would need an arm per entry-writing command, and the command added after it would be attributed to the agent until somebody noticed. A parameter is one edit for both callers, and `no_handler_decides_its_own_attribution` reads `src` for a handler naming an `Attribution` of its own, which the compiler cannot catch because it compiles
- **The variable half is cached in a `OnceLock` and the git user in another**, the way `should_use_colors` is: neither input can change mid-run, and the git user costs a subprocess. Two caches rather than one is the whole point: baking the git user into the session's answer would make `--actor-from-git` read whatever the run's *first* call produced, since with the variable set that call never fetched git at all. `entry_actor` takes the git user as a closure so the subprocess is not run when something ahead of it already answered
- **The two flags are refused together at parse time**, clap `conflicts_with`: both answer who the entry is attributed to, and last-wins would be a silent answer to a contradictory call. `every_actor_command_takes_actor_from_git` walks the clap definition so the pair travels together onto any command that grows an `--actor`
- An **empty `WORKLANE_ACTOR` counts as unset**, the convention `colors_wanted` follows for `NO_COLOR`, so a wrapper script can clear an inherited one. Whitespace counts the same, since a shell quoting a missing value writes one
- **The actor is free text, checked against nothing**, like the `chown` user: there is no registry of actors, and the same reason `ls --tag` refuses to validate a tag
- **It was `comment --owner`, renamed with no alias.** Owner is the ticket's assignee and has one writer, `chown`; this names the writer of the entry, which is a different field. Pre-1.0, and two names for one thing is what splitting `set` and `chown` avoided. `the_owner_flag_is_gone` pins the refusal, since an alias kept "for now" is what makes the wrong name permanent
- **`add --owner` and `campaign add --owner` still default to the git user, deliberately.** Those write the assignee, and a ticket an agent files is work for the person whose board it is; attributing it to the agent would put its name in the Owner column of everything it reported
- **An entry does not record whether the call had a terminal.** It is the one agent signal that needs no cooperation, so it was worth considering, and it was rejected: it cannot name an actor, a human piping output produces the same value, and once the actor is explicit the extra field answers no question anybody asks
- **Set it in the agent's configuration, not per call.** `env` in `~/.claude/settings.json` reaches every command Claude Code runs. opencode has no equivalent: its config is JSON with no `env` block for the tools it spawns, so it inherits the environment it was started with, which means a wrapper or a shell function around `opencode`. Both are documented in `assets/SKILL.md` rather than assumed
## The History Log
- **The log is the comments directory with the kind named in it.** It was already an append-only log with one event kind: one file per entry under `.worklane/history/<uuid>/`, stamped to the microsecond and written with `create_new`. Adding `status`, `owner` and `tags` beside `comment` needed no new mechanism, which is why there is no separate journal file and no database
- **What is not logged, deliberately:** ticking or unticking a criterion, and edits to the title, description, plan, priority or due. Those change often and a log of them is noise. When one of them matters, whoever made it adds a comment saying why. Do not add a kind for a field on the grounds that it is cheap to record: the cost is that the log stops being worth reading
- **`--clear` is logged, since it is the same field going somewhere.** `chown --clear` and `set --clear tags` write an entry whose after-value is the sentinel the ticket now holds, `_Not set_` or `_None_`. The values are recorded verbatim rather than translated into words this module invented, so an entry reads the way the field it came from does
- **The kind is read from the file and only counted from the filename.** `parse_entry` matches the leading marker; `kind_from_stem` splits the stem for the card's counter, which must not read four hundred files to draw a board. A name says what a file is for a listing, and the file says what it is for a reader
- **A file with no marker is a comment**, which is what every entry written before the kinds existed is. That is the whole of the compatibility, and it is why there is no migration command: `entry_content(Kind::Comment, ..)` is byte for byte what `cmd_comment` wrote before this module, so nothing is rewritten and either version can read the other's board
- **The old directory is adopted, not migrated.** `adopt_comments` renames `comments` to `history` on the first access, and the reader, the writer and the counter all call it, so no caller has to remember it and no path reaches the log without it. **A board holding both is refused**, naming both paths: only worklane writes there, so it cannot reach that state on its own, and picking which of two entries with one name survives is not a decision to make silently. The counter swallows that error, because a count is drawn per card and a board that cannot be adopted must not take the TUI down; the next write reports it
- **An entry is written after the edit it describes, never before.** A refused move, a refused chown and a failed save log nothing, which is what `a_refused_move_writes_nothing` and `a_failed_edit_writes_nothing` pin. The cost of that order is that a failed entry write leaves the edit in place and reports the failure, which is the right way round: the ticket is the record and the log is the story of it
- **A no-op edit writes nothing either, and `apply` is what decides that** for `set`: a field it did not record as changed was already what the call asked for. `cmd_mv` and `cmd_chown` have their own early returns and sit behind them
- **The stamp leads the filename and the kind follows it**, so the lexicographic sort in `read_history` stays chronological however many kinds there are. The collision suffix goes last, after the kind, and is a number, so it matches no slug and the counter skips it
- **A mechanical entry renders as one line and a comment as it always did.** A field change is one fact, and a paragraph for it would bury the comments it sits between. The labels are padded to `Kind::LABEL_WIDTH`, `campaign` being the longest of the four, so the bodies line up under each other
- **A campaign entry records `Campaign::name`, the codename or failing that the title, never the uuid the field holds.** Settled when the entry is written, not left to the renderer: a log is a record, and resolving at read time would let an entry change meaning when a campaign is renamed. A `before` uuid the board no longer has reads `_missing_`, the way the Campaign field itself renders a dangling one, and a ticket never assigned starts from `_Not set_` (f774a33)
- **`--actor` is on every command that writes an entry**, spelled from one `ACTOR_HELP` in `command.rs`: a flag documented differently on each command reads as four flags. `--actor-from-git` rides beside it from its own one string, the same way. On `chown` it sits beside `user`, which is the ticket's new assignee — the two are different questions and that command answers both
- **`set --actor` reaches only the entry `--tags` writes**, since tags are the one field of that command's that is logged. Documented on the flag rather than left for a reader to notice from the absence of entries. `append --actor` is the same flag for the same reason: `append --tags` moves the same field, so it writes the same `Kind::Tags` entry, and a tag added without replacing the rest would otherwise be the one tag change the log missed
+60
View File
@@ -0,0 +1,60 @@
# Relations
Recording an edge between two tickets, and drawing the block that reports them.
## Relating Tickets
- **The Relations section is `relate`'s alone.** `RELATIONS` is in the section table but deliberately out of `section_args`, so `set` and `append` cannot reach it: a relation names a target that has to be resolved to a uuid first, and a prose flag would let an unresolvable line into the one section that is read back by machine. Same rule as Owner and Status, one field one writer
- **`relate --clear <kind> <target>` is the removal, and it is on `relate` rather than on `set`** for the same reason the section is absent from `section_args`: one writer owns both directions, the way `chown` owns setting an owner and clearing one. It names the target and not just the kind, because a ticket can hold several relations of one kind and emptying all of them is not what anybody is asking for. That is also why it is not spelled like `set --clear`, which names a field and empties the whole of it
- **The two values are one flag, so clap cannot type them apart.** `num_args = 2` is per occurrence, which is what makes an odd number a usage error and every chunk a full pair; `RelateArgs::cleared` splits the pairs and parses the kind, so a bad kind is refused before the ticket is resolved. It exits 1 rather than clap's 2, which is the price of a two-value flag and the reason `RelationKind::parse_value` names the three in its message
- **Both spellings of the kind are accepted**, `blocked-by` from the flag and `blocked by` from the label. Both are in front of the reader: the flag is what recorded the relation and the label is what `show` prints and what the file stores, so refusing the printed form would be a trap for anyone clearing a row they just read. `RelationKind::flag` is a match rather than `label().replace(' ', "-")`, so the flag, the `--clear` value and the completion list cannot drift apart
- **`find_relation` searches the ticket's own edges before the board, and that order is the feature.** A dangling edge is the case most likely to need clearing, and no search of the board can reach a target whose ticket is gone, so the id-prefix tier over the stored targets is the only one that finds it. `MIN_ID_SEARCH` is the floor `resolve_in` puts under its own id tier and the comparison is case insensitive for the same reason. Two stored targets under one prefix name the candidates rather than guessing, which is what an ambiguous ticket search already does
- **An edge the ticket does not hold reports no change; a target naming nothing at all is an error.** The two are different facts: the first is the state the caller asked for, and the second is a typo that reporting no change would swallow. The resolver's own reason is carried through, so an ambiguous search says so instead of being reported as nothing found
- **Recording and clearing the same relation in one call is refused, and the check runs on what was *asked* for.** `items` drops the additions already in the file, so comparing against that would let `--blocked-by X --clear blocked-by X` quietly remove an existing X. `requested` is the full list for exactly that reason. The refusal is `set --clear`'s: nothing is written rather than one direction silently winning
- **Removals rewrite the section and additions are appended to the result, in that order.** Two passes rather than one rebuild, so a call with no `--clear` takes exactly the path it always took and `append_section_body` goes on deciding where a new line lands. Rewriting from the parsed relations is lossless because a line that is not a relation is already an error. The last edge leaves `clear_section_body`'s placeholder, which is the line `append` treats as no content, so the next `relate` replaces it instead of writing under it
- **A relation is not logged, either direction.** `relate` writes no history entry and neither does `--clear`, which keeps the two consistent; per the history rule, an edge that matters enough to explain gets a comment. Do not add an entry for the removal alone: a log that recorded only the destructive half would read as though the additions had never happened
- **`add` does not write the section.** The plan on 4179958 asked for it in the ticket writer; it is out on purpose. A `_No relations._` block in every new ticket is noise in every `show`, and the insertion path has to exist regardless for every ticket written before the section did, so leaving it out means one path that is always exercised rather than two
- **The full uuid is stored, not the seven characters `ls` prints.** It resolves without a scan and cannot turn ambiguous as the board grows. `show` renders the short id and the target's title instead: the file is the machine's copy, the output is the reader's
- **One direction is stored and the inverse is derived.** `blocked by` goes on the gated ticket rather than `blocks` on the blocker, because the gated ticket is the one whose move is refused and whose author knows about the dependency. `relates to` is symmetric and is written once, on whichever end the caller ran it from. `RelationIndex::inbound` finds the far end by scanning, which is what keeps `relate` a single-file write
- **A derived row that reads exactly like a stored one is dropped, and the stored one is kept.** Both ends of a symmetric relation could hold a line, since nothing stopped it until 03bdc76, and the block then drew the same neighbour twice under the same label. The stored row survives because it is the line `relate --clear` can address; the derived one is on a file this ticket does not own
- **The dedupe keys on the label and the target, not the kind and the target.** Two tickets each blocking the other is two facts and the block says both, `blocked by` from this end and `blocks` from the other; keying on the kind would fold them into one row and lose half of what the ticket says. Only a symmetric kind can collide with its own stored line, and `RelationKind::is_symmetric` derives that from `label() == inverse_label()` rather than naming `RelatesTo`, so a kind added later answers by construction
- **`relate` also refuses to store the mirror, which is the other half of the same fix.** The dedupe repairs a board that already holds both directions; the refusal stops it recurring. `mirrored` in `cmd_relate` reads the target's own relations and reports no change, gated on `is_symmetric` because a target holding `blocked by <this>` is a cycle rather than a duplicate. 4179958 decided `relates to` is written once and not onto both files; for six months nothing enforced it
- **A symmetric edge is cleared from the end that stores it.** With both ends holding a line, `--clear` on one leaves the other's, which then draws as the derived row: correct, since the far end still asserts the relation, and the reason the dedupe keeps the stored row rather than the derived one
- **A line in the section that is not a relation is an error naming the ticket**, not a line quietly dropped. Nothing but `relate` writes there, so a bad line means a hand-edited file. The TUI is the deliberate exception: `detail_of` falls back to no block, since one corrupt ticket must not take the whole board down
- **The block is built outside `content_trim` and passed in.** Half of it comes from other tickets and `content_trim` has only the body. It is spliced over the stored lines where the file has the section, and injected ahead of the metadata where it does not, because a ticket that is only pointed at has no section of its own and still has relations to show
- `ensure_section` inserts against `SECTION_ORDER`, before the first following section that is actually in the file, and adds no blank line that was not already there. A handwritten `## Notes` between the plan and the metadata therefore keeps its place, and Metadata is in that list as an anchor rather than as something anything appends to
- **A dependent may stand level with its blocker but never ahead of it.** `blocks_move` is the rule: the move is refused exactly when the status moved into is further down `Status::ALL` than the blocker's own, so a blocker in reviewing lets the dependent be committed and reviewed and gates only done. The first shape of this refused every move while a blocker was not done, which read as one rule rather than a table of transitions but stopped the work it was meant to order: a pair is usually built and reviewed together, and waiting for the blocker to land cost a `-f` on every move and left the rule enforcing nothing
- **A finished blocker is answered by `is_open`, and a discard target by name.** Done landed and discarded never will, so neither holds anything up, and that is the one place the board decides what finished means. Discarded is last in `Status::ALL` for the stamp rule's sake, so a comparison of positions alone would read a discard as the furthest move of all: `blocks_move` returns false for it outright, since abandoning a ticket is not carrying it along the flow and owes nothing to what it waits on. A status that is not one of the five holds up every move, the direction `is_open` already takes with such a value: a fault surfaces rather than quietly letting a dependent past
- **The blocker check runs on every move**, after the already-in-that-status return and behind `force`, with the target status passed in as what decides the answer. A move to the status the ticket is already in is not a move, so it is not refused. A backward move never is either, being at or behind everything, and it needs `-f` for its own reason anyway. `-f` bypasses three rules, which is the right home for it: each one is a deliberate override of something the board would otherwise keep true
- **A blocker that is not on the board warns and allows the move.** Refusing would wedge the ticket with no way out but `-f`, and a uuid nothing carries is a bookkeeping fault rather than a dependency. The warning goes through the sink `check_blockers` is handed, which is why a guard that says nothing on the happy path takes one at all: the same helper runs from the board's command prompt, where the process's stderr is the alternate screen. See [The Command Prompt](tui-prompts.md). The refusal names **every** blocker still behind the move and the status it was for, since advancing the one that happened to be printed would leave the ticket held up, and a ticket refused the next stage after moving once is otherwise told nothing about what changed. A blocker further along than the move is left out of the list entirely: a dependent told to wait for work already ahead of it has nothing to act on
- Left out on purpose: removing a relation, which 4179958 assigns to 74904dc. The blocked marker on the card landed in b8ce18c, and it cost no scan of the board: the blockers ride along on the read that already builds the cards. It asks `blocks_move` about the status one stage ahead of the column the card is in, so the mark means the card cannot advance and not that a dependency was ever recorded. See [The Board View](tui-board.md)
## The Relations Block
- **One builder, two painters.** `relation_rows` decides which edges there are, what they are called and which direction comes first; `relation_cells` decides the layout, the mark and the colours; `paint_cells` turns cells into escapes for the CLI and `span_of` turns the same cells into ratatui spans for the board. Two builders producing one block in two shapes is a pair free to disagree about ordering or padding, which is what this shape exists to prevent
- **`Cell` is the unit both renderers take**: a run of text, the colour it is drawn in and the modifier it carries, `None` for the default foreground and for text drawn as it stands. The same trick as the palette itself, where `Color::ansi()` and `From<Color> for ratatui::style::Color` keep one colour from existing for one renderer and not the other, and `Modifier` is that trick a second time for the styles that are not colours
- **`Modifier` is the first style on a cell that is not a colour**, and it is an enum with one variant for the reason the palette is one: `Modifier::ansi()` is SGR 9 and `From<Modifier> for ratatui::style::Modifier` is `CROSSED_OUT`, so a style that exists for one renderer and not the other is a compile error. Bold is not in it, because bold rides inside `Color::Magenta.ansi()` and `span_from` adds it back from the colour alone; a second modifier goes here beside the strike. It is independent of the colour, so a struck run keeps whatever colour its column already gave it
- **`Cell::struck` is a builder, not a third constructor.** The strike is decided a whole row at a time and the cells of that row are built by the layout that already chose their colours, so `relation_cells` maps it over the row it has just finished rather than threading the decision through every cell it makes
- **`RESET` is a constant both writers share.** `paint` opens a colour and `paint_cell` may open a modifier ahead of one, and a reset that only knew about the colour would leave the strike running to the end of the line
- **`Body::push_cell` merges on the whole style, not the colour alone.** Nothing outside the relations block carries a modifier today, and a merge keyed on the colour would silently strike a plain run through the moment one did
- **`reference_cells` is the one spelling of a cross reference.** The relations block and the Campaign field both go through it, so a dangling reference reads the same way wherever it is shown. There was a `reference_cell` beside it that painted the cells for the CLI; once the whole body became cells the Campaign field stopped needing a string and it was the last caller, so it is gone
- **A row carries two marks, kind then status**: what sort of edge this is, then how far the ticket at the other end has got. `blocked by × ◐ (6ce2c47) Title`. Two questions are asked of this block and one glyph could not answer both: which rows hold this ticket up, and whether the ones that do are finished
- The status went through one bad shape first. It was a rising bar, `▁▄▆█`, as the only mark, which read as an undifferentiated column of blocks and left the kind to five long words that blur when a ticket carries several. Then the kind took the column alone and the status was lost. Both, in that order, is the answer
- **Both directions of a kind carry one mark.** `blocked by` and `blocks` are the same edge read from two ends, and the label is what says which end you are on. `both_directions_of_a_kind_carry_one_mark` pins it
- **`×` is `BLOCKED_MARK`, the same constant a held-up card draws**, in the same brightred. On a card it says this ticket is held up and in the block it says this edge is what holds one, which is one word, so one glyph and one definition. It lives in `util.rs` for that reason, not in `tui.rs` where the card is
- **The kind marks stay out of the priority vocabulary**, which owns `●◐○·`, and `no_relation_mark_is_a_priority_glyph` pins that against every level. They are the arrows the footer already draws, so they render wherever it does
- **The status marks are those very circles, and what keeps them from reading as a level is width**: the meter is always two cells and a status mark is one. `the_status_mark_is_one_cell_where_the_meter_is_two` pins both halves. A card carries the meter and never a status mark, and the block carries the status mark and never a meter, so the two never sit in one column
- **Both marks go ahead of the id**, where they describe the target rather than the row. Every row carries both, so nothing is pushed out of line the way the card's blocked mark would have been, which is why that one sits after the id and these before it
- **The kind mark survives a target the board cannot find and the status mark cannot**, since a kind is read from the ticket's own file and a status from the board. `?` holds the column so the id does not move, and `_missing_` in grey is what says the target is gone
- **Committed and reviewing are told apart by colour alone**, both being `◐`, so a pipe cannot tell them apart: `should_use_colors` is false and both read as under way. Accepted, because `●` and `○` are the two answers usually wanted and `show` on the target settles the rest, and `assets/SKILL.md` says so outright rather than leaving an agent to infer it. Do not fix this by giving one of them a colour that means something else
- `RelationTarget` carries the title and the status in one `Option`, because they come from the same lookup and are absent together. It was taken out when the mark keyed on the kind alone and put back one commit later, which is the cost of a field nothing reads: correct at the time, and churn either way
- **`show` and the board carry the same mark**, decided rather than left to be discovered: the rows are one builder, so giving the CLI the mark cost nothing, and two views disagreeing about what a relation shows would be the kind of difference nobody can explain later. That makes it a change to what the CLI prints, so it is a minor
- **`Resolved.relations` is rows, not a rendered block, and `Resolved.campaign` is cells for the same reason.** An escape sequence in a ratatui paragraph is drawn as literal bytes (6d327df), so nothing in `Resolved` can arrive pre-painted. This was the asymmetry the two renderers needed while the rest of the body was a painted string; there is no asymmetry left, since `content_parts` paints nothing at all
- **`BodyPart` splits the body rather than building it twice.** It is `Cells` or `Relations`: everything outside the block is laid out once, by `content_parts`, and `content_trim` is that run through `paint_cells` while the board is the same cells run through `span_from`. `Body` is the accumulator, so a caller pushes cells and rows without tracking which it pushed last, and it merges a run into the trailing cell when the colour matches, because the board draws a span per cell and the body is pushed a character at a time in places
- **`Detail.body` is a `Text`, and it is the only thing measured.** `last_offset` and the `Paragraph` both take it, so the clamp cannot wrap the body differently from the draw. `Detail::plain()` flattens it for the suite and is `#[cfg(test)]`: a second representation carried alongside the spans is a second thing to disagree
- `detail_body` closes a line only where the text says, so a part that does not end on a newline runs on into the next one. The seam between text and rows is wherever the body put it rather than wherever a part happened to end. It now splits **per cell** rather than per part, since a `Cells` part holds many runs and a newline can fall inside any of them
- **The whole overlay body is coloured now, and `content_parts` paints nothing.** The block used to be the only coloured part, because it arrived as rows while everything else arrived as a painted string; e4d0bb7 gave the rest the same `Cell` treatment. So the headings, the plan numbers, the criteria numbers and marks, the bold runs, the field names, the priority glyph, the tags and the grey unset values are one layout that `show` paints and the board styles. Do not reintroduce a `paint` call in `content_parts`: the flat overlay was exactly that, a renderer forced to ask for the unpainted string because the painted one held escapes
- **`colored` still reaches `content_parts`, and it no longer means paint.** It says whether *this* renderer can carry a colour at all, and one thing turns on it: `**bold**` gives its markers up to the colour that replaces them, so a renderer with none has to keep them or the emphasis is lost rather than moved. The board passes `true`, `content_trim` passes the CLI's decision, and a piped `show` still reads its markers. Nothing else in the body consults it
- **Magenta means bold, and `span_from` is where the board learns that.** `Color::Magenta.ansi()` is `\x1b[1;35m`, so the CLI draws every bold run bold as well as magenta, and `From<Color>` can carry only the colour. Without the modifier added on the board's side the same cell would be painted two ways, which is the one thing the shared layout exists to prevent
- **The conversion is pinned from both ends.** `show_prints_the_same_body_it_printed_before_the_cells_conversion` holds a body with one of every painted run and asserts the CLI's output byte for byte, written from what it printed before the change, so the risk in sharing a layout, the CLI's output drifting to suit the board, fails the suite. `the_whole_body_is_styled_in_the_overlay_and_no_escape_reached_it` is the other end and is paired the way the guideline demands: a renderer that dropped every colour passes the absence, and one that went back to painting strings passes the presence
- **The history block arrives as segments too, so nothing in the overlay is flat.** `history_parts` splits the entries into flow runs and quoted runs in one walk; `history_cells` is their flatten, which is what makes the CLI's bytes a property of the segmentation rather than a second walker free to drift from it, and the board reads the same parts and lays each out itself. Pinned from both ends the way the body is: the pins over `format_history` hold the flatten byte for byte, and `the_block_splits_into_flow_and_quoted_parts` pins which runs are whose
+23
View File
@@ -0,0 +1,23 @@
# Committing and Releasing
The commit convention and the version bump that goes with it.
## Git Workflow
- Commit format: `([ticketID]) [short description]`
- Use `--fixup` for incremental changes
- Test before moving to reviewing status
## Version Bumps
- Before every commit, decide whether the change warrants a version bump in `Cargo.toml`
- Always ask the user to confirm the bump and its kind before making it — never bump silently, and never skip the question because the answer looks obvious
- **`make patch`, `make minor` and `make major` do the mechanics**, run after the commit is in: each bumps `Cargo.toml` and the `worklane` entry in `Cargo.lock`, appends `, and bump to <version>` to the commit's subject, folds the bump into that commit, and tags it. Bumping by hand is how a version comes to be left untagged, which is what the one action is for. It refuses on a dirty tree, on an already-tagged `HEAD` and on a `HEAD` that is already pushed, since each of those makes the amend lose work, orphan a tag or need a force push
- **Untracked character devices do not make the tree dirty.** An agent sandbox bind-mounts `/dev/null` over protected paths such as `.bashrc`, `.gitconfig` and files inside `.claude/`, so git sees untracked entries that do not exist outside the sandbox, and `make patch` refused a clean tree. A device cannot be committed, so the check skips them. Untracked files are listed one by one rather than with `--directory`: the collapsed `.claude/` entry is a directory, not a device, and kept the refusal alive
- Pre-1.0, so: patch for fixes and internal changes, minor for a new command, flag or changed output, major only for a deliberate 1.0
- **Changed output means the CLI's output.** That is the surface scripts and agents read, so a changed listing, message or exit code is a minor. A change to what the board draws is a patch however visible it is, since nothing consumes the frame. See [The Board View](tui-board.md)
- **Settling output that shipped one version ago is a patch**, not a second minor. 0.15.1 changed the relation mark 0.15.0 had just introduced, and 0.15.2 added the status mark beside it: the minor was the arrival of a marked relations block, and settling what it marks belongs to that. Three minors in an hour would tell anyone reading the tags that there were three features
- No bump for docs-only, tests-only or `--fixup` commits
- When one body of work spans several commits, bump once on the final commit rather than on each
- Every bump gets a matching annotated tag, `v<version>`, on the bump commit — a bumped version is never left untagged
- Tag locally only; never push a tag unless asked
- `worklane --version` reports the crate version alongside the build sha, so the bump is what makes one release distinguishable from another
+11
View File
@@ -0,0 +1,11 @@
# Rust Style
The small conventions this tree keeps in its Rust.
- Use `if matches!(expr, Variant)` instead of `if let Some(Variant) = expr` for enum variant matching
- Use `if let Some(x) = expr` instead of `if let Some(Some(x)) = expr` — drop unnecessary nesting
- Prefer explicit `match` over `unwrap_or_default()` for clarity
- Use `unwrap_or_else(|| expr)` for lazy defaults, `unwrap_or(val)` for eager defaults
- Use `anyhow!()` with context strings that include identifying info (e.g. UUID, title) not bare values
- A command whose arguments run past a handful takes a clap `Args` struct, not an inline variant with a matching parameter list: `AddArgs`, `SetArgs`, `AppendArgs`, `CheckArgs`, `MvArgs`. `add` was nine positional parameters threaded from `main` before it became `AddArgs`, and the handler destructures the struct so the body reads the same as before. `mv` was the last inline variant to carry an `--actor`, and `--actor-from-git` pushed its list past the line
+73
View File
@@ -0,0 +1,73 @@
# Boards on Disk
The two board layouts, the pointer file, and how a board is found from a working directory.
## Shared Boards
- **A project's board is on one of two layouts, and `src/board.rs` is the whole of the
second one.** The local layout is the `.worklane` directory a project has always had.
The shared layout answers `.worklane` being gitignored and not a git repo so a clone
elsewhere has no board: the project commits a `.worklane.toml` naming its board by
uuid, one boards repo is cloned once per machine, and `.worklane` in the project
becomes a *symlink* into it. The symlink is the point: with no `.worklane` directory
`cat .worklane/backlog/*.md` and `ls .worklane/reviewing` would stop working, and that
is the belief the whole file format exists to serve. Because the link is transparent,
`find_worklane_dir` gains no resolution code at all (c6a61b4 AC 14).
- **The machine config lives at `$XDG_CONFIG_HOME/worklane/config.toml`** (default
`~/.config`, empty counts as unset). It carries a `[boards]` section holding the *url*
of the boards repo and an optional `dir` overriding where the boards directory sits —
the config is *this machine's* answer, and the pointer carries no server address, so a
client repo never holds an internal hostname. The boards directory itself defaults to
`$XDG_DATA_HOME/worklane/boards` (`~/.local/share` without it).
- **The pointer is `.worklane.toml`, committed at the project root:**
`[worklane] board = "<uuid>"`, and nothing else. Read and written by `read_pointer` /
`write_pointer`. `write_pointer` leaves a pointer that already names the same board
alone — it is a committed file and rewriting it writes nothing new, which is what keeps
"init symlinks it and creates nothing" true for a fresh clone.
- **A board directory is `<uuid>_<slug>`, named after the ticket files.** The slug is
`util::slug` of the project's directory name, and resolution (`resolve_board`) is a
uuid prefix match, the bargain the ticket filenames already make: the directory stays
readable to `ls`, identity is stable, and renaming a board breaks no committed pointer.
- **The decision table is `decide_init`, one match.** The reason it is a table rather
than a fallback is that no branch may fall through into creating a board, so each row
returns its own outcome. The rows:
- no pointer, no `[boards]` config → local `.worklane`, exactly as `init` always made
it (AC 12);
- no pointer, config present → create the board, write the pointer, symlink `.worklane`
to it (AC 4);
- pointer present, board found → symlink it and create nothing (AC 5);
- pointer present, board absent → refuse. A committed pointer is proof the board exists
somewhere, so a missing board is an unsynced machine, and creating a second board
there produces two boards with one name and a manual merge — the worst outcome in the
design. The refusal says so and names `init --create` as the only way to make one
(AC 6/7). The fetch-and-look-again half of the ticket is deferred: nothing pulls the
boards repo yet, and the refusal names it rather than doing it. **`--create` is the
`create` field on `Command::Init`**, the escape hatch under that row;
- the boards directory itself missing → a distinct refusal saying the boards repo is
not cloned here (AC 8);
- the correct symlink already in place → no change, nothing written (AC 9);
- a symlink to a *different* board → refuse rather than repoint it: changing what a
project is on without asking is how two machines come to disagree about the work
(AC 10);
- a symlink that dangles → refuse rather than replace it without asking;
- a real `.worklane` directory under a pointer → refuse and name the adopt path
(aa80db4), never walk over it (AC 11).
- **The three symlink states are told apart by `classify_worklane`:** `Absent`,
`RealDir`, `Symlink`, `Dangling` and `NotADirectory`. The `Symlink` comparison is
canonicalized, the `Dangling` one is lexical (a dangling link cannot be canonicalized)
and checks for the relative spelling this tool writes or the absolute board path.
- **The symlink target is relative** to the link's own parent, so it uses no home
directory path and the link is portable in that limited sense; an absolute target
appearing anywhere is how a home directory leaks into a write. Because a relative
target depends on how deep a repo sits, `init` still runs once per project per machine,
which is the price of transparent access.
- **Everything under `.worklane` is layout-agnostic.** `create_board_contents` makes the
same status directories, `campaigns/` and `tags.md` for a local and a shared board,
and every reader below `find_worklane_dir` works through the link unchanged.
## Finding the Board
- **`find_worklane_dir` classifies the entry before it follows it.** `exists()` follows a link, so a `.worklane` that was a dangling symlink answered the same as no `.worklane` at all: the walk carried on up the tree and the first board above the project became the one every write landed in, silently. `classify` reads `symlink_metadata` first and answers one of four, `Absent`, `Board`, `Dangling` or `NotADirectory`, and **`Absent` is the only one the walk carries on from**. A `.worklane` that is there but unusable is this project's board and is reported, not handed upward
- Anything other than `NotFound` from `symlink_metadata` is an error rather than an `Absent`. Reading a filesystem that could not answer as nothing-there is how the walk-past worked in the first place
- The dangling failure **names the target and says the boards repo may not be cloned**, and deliberately does not say to run `worklane init`. Once the boards live outside the project a dangling link is an ordinary state, what you have before the boards repo is cloned and after a board directory is renamed, so "no board found, run init" points at the wrong problem
- **A link that resolves is indistinguishable from a real directory, and what comes back is the link rather than its target.** `.worklane/backlog/*.md` has to read the same either way and nothing downstream learns whether the board is local, which is the property the shared-boards layout rests on
- A regular file at that path is an error as well. It is a plausible future pointer form, and reading it as one is that change's decision to make; stepping over it and writing to a board above is the one answer that is wrong today
+30
View File
@@ -0,0 +1,30 @@
# Testing
What to run before committing, the fixtures, and what rustfmt and clippy are set to.
- **Run `make check` before committing**: `cargo fmt --check`, then `cargo clippy --all-targets -- -D warnings`, then `cargo test`, cheapest first. That is the whole of the enforcement, and it is deliberate rather than a stopgap: this repo has no CI and does not want any, and a git hook is a per-clone opt-in the way `blame.ignoreRevsFile` is, so neither can be relied on. What was missing was one name to type, so the two rules below are a command and not a memory. `-D warnings` is what makes clippy's opinion an exit code; a warning printed into a wall of cargo output is unread, not clean. The completion checks are inside `cargo test` rather than a target of their own, since a second thing to remember is the problem this solves
- Run one suite: `cargo test`
- Tests use `assert_cmd` and `assert_fs` for CLI testing
- `setup_worklane()` creates temp `.worklane/` with the four flow 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. **The fixtures deliberately do not create `discarded/`**, so every discard test runs against a board that predates the status and `mv_creates_the_discarded_directory_on_a_board_that_predates_it` is not the only thing exercising the on-demand creation
- `create_ticket()` writes fully-formed markdown files directly (no `--` separator for positional args in test commands)
- **Every unit-test fixture directory goes through `util::Fixture`, and nothing calls `remove_dir_all` at the end of a test.** `Fixture::new(prefix)` makes a uuid-named directory under the system temp dir and its `Drop` removes it, which is the only shape that also runs when an assertion fails — a trailing line does not, and a failing test is exactly when a fixture is most likely to be stranded. That was b74dc5a: `/tmp` reached 18363 of these and filled the disk, failing a link step and then a `git add` with "No space left on device", an error naming neither the tests nor what they left behind
- **`Fixture` derefs to `Path` and also implements `AsRef<Path>`**, because the two reach different call sites: a parameter typed `&Path` is a coercion site and one bound by `impl AsRef<Path>` is not. `Fixture::child(name)` points the fixture at a directory inside itself while still removing the parent, which is the tree `project_tree` needs. The prefix earns its place on the one path that is ever left behind, which is why this is a small guard rather than `assert_fs::TempDir` — that names its directories `.tmpXXXXXX`, which says nothing about whose they are
- **`WORKLANE_KEEP_FIXTURES=1 cargo test` keeps the fixtures and prints each path.** Opt-in rather than kept-automatically-on-failure, because the assertions here carry the state they are about: a failing board test prints the rendered rows. The flag is read once when a fixture is made rather than at drop time, so the answer cannot change mid-test, and `Fixture::swept()` turns it off for the three tests that are about the guard itself and must not be failed by a reader's environment
- **Verify a claim about leaked fixtures against a clean temp dir, not against `/tmp`.** `TMPDIR=/tmp/scratch cargo test` then count what is left in it: `/tmp` still holds the historical leak, so counting there measures the past rather than the change
- 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, and `make check` is what says so. 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, `make check` runs it first, 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:
| setting | value | why |
|---|---|---|
| `max_width` | 100 | The tree's own habit, and the measured optimum: 90 costs 268 hunks and 120 costs 194, against 161 at 100 |
| `fn_call_width` | 75 | A call stays whole if it fits in three quarters of the line. rustfmt's default of 60 is what expanded 276 of the 305 hunks the default config wanted |
| `chain_width` | 65 | The same for a method chain |
| `struct_lit_width` | 30 | A small struct literal stays whole, so `Size { width: 120, height: 20 }` is not six lines |
**The numbers were measured, not chosen.** Default rustfmt wanted 305 hunks and would have added 1418 lines of pure layout, because its sub-widths sit far below the 100 columns this tree is written to. `use_small_heuristics = "Max"` went the other way, 308 hunks and 796 lines *removed*, one-lining `if`/`else` and collapsing struct literals that were split on purpose. Coordinate descent over the stable width knobs landed here, at 161 hunks, and 98 of those are rustfmt *joining* calls that fit rather than breaking them. Sweeping any one of these four in either direction makes the diff bigger, so do not adjust one by eye; measure it the same way, with `cargo fmt --check | grep -c '^Diff in'`
- What this does not buy: rustfmt has no rule for "keep parallel arms parallel", so a match whose arms are one line and four lines depending on the length of their contents is what it produces, and that is accepted. Reach for `#[rustfmt::skip]` only where the layout carries meaning a reader needs, not to win an argument about density
- Do not add an unstable option. `cargo fmt` on stable ignores them with a warning, so the tree would format differently for whoever ran nightly
- **Sixteen lines still run past 100 columns and every one of them is a single string literal**, a test fixture or an error message rustfmt cannot break. `format_strings` is deliberately left at its default: turning it on would let the formatter rewrite message text, and a message is prose. So `max_width` is where rustfmt breaks lines, not a limit the tree keeps
- The reformat is `73ffcad`, and `.git-blame-ignore-revs` names it so `git blame` looks through it. Turn that on once per clone with `git config blame.ignoreRevsFile .git-blame-ignore-revs`. A commit belongs in that file only if its diff is pure layout
+38
View File
@@ -0,0 +1,38 @@
# Tickets on Disk
What a ticket file holds, how the statuses move it, and how a search finds it.
## Ticket File Format
- Filenames: `<uuid_v4>_<slug>.md`
- The slug is the title through `slug()`: lowercased, alphanumerics plus `-` and `_` kept, spaces turned into dashes. `Ticket 06` lands as `<uuid>_ticket-06.md`. Derive fixture filenames through `slug()`, never by hand
- Metadata fields parsed by `parse_ticket_field()`: `ID`, `Priority`, `Tags`, `Due`, `Owner`, `Created At`, `Committed On`, `Submitted On`, `Completed On`, `Discarded On`, `Campaign`, `Status`. The last five are the ones no ticket is born with: `add` writes none of them, so they are inserted on demand, against `METADATA_ORDER`, which is also what keeps `Status` last
- The four stamps are `mv`'s, written by `set_status_stamp` from `Status::stamp_field`, and they **accumulate**: entering a status writes its field, re-entering restamps, and arriving anywhere removes the fields of every status *after* the target. One arrival rule keyed off `Status::ALL`, not a case per move, which is why a backward move truncates the journey at the target (`done` back to `reviewing` drops `Completed On`, anything back to `backlog` drops all three) and a forward skip under `-f` stamps only where it lands rather than fabricating the stages it jumped. A ticket that walks the whole flow ends with `Created At`, `Committed On`, `Submitted On` and `Completed On` side by side, so presence means *got this far and has not been sent back past it*, not *is here now* — `Status` is what says where it is. Not the history log either: these answer how far and when, once per stage, and every change along the way is the log's. `backlog` has no stamp, `Created At` already answers for it
- **`Discarded` is last in `Status::ALL`, and that placement is what makes the stamp rule fall out right.** Nothing sits after it, so a discard clears nothing: a ticket abandoned from reviewing keeps `Committed On` and `Submitted On`, and the file still says how far it got before it was dropped. It also makes every move out of discarded a backward move, so un-discarding needs `-f` without a rule of its own. `Discarded On` is its stamp, and `Completed On` stays untouched, because a discarded ticket was never done
- **Each status column is ordered by its own date, through `by_status_order`.** Past the backlog that date is the entry stamp, so committed sorts by `Committed On` ascending, reviewing by `Submitted On` ascending, and done and discarded by their stamp descending. The backlog has no stamp of its own, so it sorts by `Due` ascending, through `TicketItem::due_key`. Said once: the head of every column is what the reader acts on next, and in the backlog that is the nearest deadline rather than the loudest priority — priority alone sat a p1 nobody had promised above a p3 due tomorrow. A ticket carrying no date sinks below every dated one in its column, because a missing time is unknown rather than ancient and unknown must not claim the head of a queue; equal dates and both-undated fall through to `by_priority_then_title`, which is still the whole order among undated backlog tickets. One function keyed on the `Status`, taken by both `cmd_ls` branches, `list_ids`, `columns_of` and `campaign::members`, which is why those loops walk `Status::ALL` rather than `status_dirs()`. The dates are read in `collect_ticket_items`' existing pass, the rule `criteria` and `tags` already hold, and compared as strings: `%Y-%m-%d %H:%M:%S` and `%Y-%m-%d` are both lexicographic in chronological order, so nothing parses a date at sort time. `due_key` answers `None` for a `Due` that is not a plain `YYYY-MM-DD` after `due_date` has cut a legacy datetime back — free text is unknown, not a date, and sorting on its spelling would rank it against real deadlines
- 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
- History entries stored in `.worklane/history/<ticket_uuid>/<stamp>_<kind>.md`, with the kind's marker (`**Comment**`, `**Status**`, `**Owner**`, `**Tags**`, `**Campaign**`), then the body, then `**Author**` and `**Time**`. See [The History Log](history.md)
## Status Workflow
`backlog` → `committed` → `reviewing` → `done`, and `discarded` off to one side
- **`Status::ALL` is every directory that can hold a ticket, and that is the only list left.** It is what the tree walkers want: `status_dirs`, `RelationIndex::load`, `collect_ticket_items`' callers, `cmd_tags`, `list_ids`, the resolver, the digest and the board's own columns all have to see a discarded ticket or it becomes unaddressable. There was a second list, `FLOW`, the four stages work moves through, which used to be what the board drew from; a136d13 drew the discarded column behind a visibility prefix instead, which took FLOW's last reader away, so it is gone. Hiding is decided by `Visibility`, never by leaving a status out of the walk: what is drawn changes, what is read does not. The prefix property survives on the order alone — done and discarded are deliberately the last two in `ALL` — and `the_terminal_columns_are_last_in_the_order_drawn` pins it
- **Discarding is not a stage, so the walk rules do not apply to entering it.** `mv --status discarded` is allowed from any status with no `-f`, because a backlog ticket that turns out to be a duplicate should not have to be walked through committed and reviewing to be abandoned. Leaving it needs `-f`, which comes free from the backward-move rule
- **The two dependency guards look opposite ways, and `mv` picks by direction.** `check_blockers` asks what this ticket waits on and gates work moves, refusing the ones that would put it ahead of a blocker; `check_dependents` asks who waits on this ticket and gates the discard. A ticket being abandoned owes nothing to its own blockers, but the tickets blocked *by* it recorded a dependency on work that is about to be declared never-happening, so those plans get a look before the ground moves. `-f` is the caller saying they looked. Both name every offender rather than the first, and both skip targets that are themselves done or discarded; `check_blockers` also skips a blocker already further along than the move being made
- **Discarded satisfies a block the way done does.** There is nothing left to wait for, and whether the dependent still makes sense was asked at discard time by the guard above, which is what makes it safe to pass here rather than a second place to re-ask. It is also why `blocks_move` answers a discard by name and not by position: discarded is last in `Status::ALL`, so comparing positions alone would read the two terminal statuses as the furthest stages of the flow rather than the ends of it
- **Both terminal statuses are hidden by default and counted anyway.** `ls` leaves done and discarded out of the decorated listing and keeps them in the summary counts, and `--ids` and the status positional still reach both: a ticket nobody will work still has to be nameable by a completion or a script
- **A campaign counts a discarded member as finished.** The work was decided out of the campaign rather than left in it, and counting it outstanding would hold a campaign open forever over a ticket nobody will ever do
- **`mv` creates the target directory before moving into it.** A board made before a status existed has no directory for it, and the first move into one is the wrong place to refuse. `init` gets all five from `status_dirs()`
## Ticket Resolution
- `resolve_ticket()` returns `(status, title, content)` tuple
- 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](campaigns.md) 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)
- Never return empty strings for required fields — use the `NOT_SET` and `NONE` constants in `util.rs`, which are what `add` writes and what `--clear` puts back. `is_unknown_value` reads those two and nothing else
- **`-None-` and `-Not set-` are not unset, and re-adding them would be a mistake with a plausible story behind it.** They were accepted by `is_unknown_value` from the day it was written, by analogy with the `**-Status**` field name the `mv` splicing bug really did produce, c230d2c. But no version of this tool ever wrote a hyphenated *value*: `git log -S` finds both spellings in exactly one commit, the one that added them to the check. Dead from birth, and dropped by bdddc09. `a_hyphenated_marker_is_not_unset` is what stops the analogy being drawn a second time
- **The `**-Status**` repair in `is_status_line` is the opposite case and stays.** That corruption was real, `mv` wrote it, and the repair is what fixes a damaged ticket as it moves. Do not tidy the two away together on the grounds that they look alike
+134
View File
@@ -0,0 +1,134 @@
# The TUI
The TUI: the columns, the cards, the frame, the pickers and the footer.
## The Board View
- **The board is for a person, and only for a person.** Scripts and agents drive worklane through the CLI, which is what `assets/SKILL.md` teaches and what the integration tests pin. Nothing parses the drawn frame, so its layout is free to change: a new row on a card, a moved corner, a different colour or a hidden column breaks no caller. Judge a change here on whether it reads well, not on what it might break, and do not preserve a layout for compatibility's sake. What the CLI prints is the opposite case and is not covered by this
- `worklane` with no subcommand and `worklane tui` both open it, the way a bare `frig` does. `Cli::command` is therefore an `Option`
- The worklane directory is looked for **before** the terminal, so running outside one gives the usual "No .worklane directory found" rather than a complaint about the tty. Both errors stay reachable and both are testable without a pty
- A missing tty is refused with a message naming a subcommand. Raw mode on a pipe fails with a bare "No such device or address (os error 6)", which explains nothing
- **The watch looks at files, not directories.** A directory's mtime only moves on create and rename, so a ticket edited in place would be missed. `digest()` hashes every ticket and comment file's path, length and mtime. Comment files are in it because a comment added elsewhere has to reach the detail view
- The digest guards the *rescan*, not the draw. ratatui diffs its buffer, so drawing every iteration is free; reading the tree every iteration is not
- `notify` is deliberately not a dependency. Polling a tree of tens of small files on the 250ms tick is enough, and the reason is recorded on f6af387
- Cards come from `collect_ticket_items`, the same source `ls` uses, so there is no second parser. `TicketItem::path` exists for the detail view
- **The detail view scrolls on `pgup` and `pgdn`, not on up and down.** Up and down stay on the selection with the modal open, so a whole column can be read without closing it, and the modal follows. That is worth more than the two keys, which is why the scroll went elsewhere rather than taking them
- **The campaign frame scrolls on the same two keys, and `Board::scroll_page` is where the precedence lives.** An open ticket wins, whatever holds the selection behind it; the frame takes them only when there is no overlay to take them first. In `Board` rather than in the `main.rs` arm for the reason `dismiss` is: a layering rule written into that dispatch is a rule nothing can check
- The scroll offset is clamped against the *wrapped* line count, from `Paragraph::line_count`, which is why `ratatui` carries the `unstable-rendered-line-info` feature. The paragraph wraps on words, so a clamp on the raw lines would stop short of the end or scroll past it into blank space. Counting the wrapping by hand would only agree with the widget until one of the two changed
- The clamp runs on the keypress and again in the draw. The terminal can be resized between the two, and a tick can shorten the ticket under a reader who is already at the end
- The offset resets when the selection moves and when the modal is closed, so a ticket opens at its top. It deliberately does *not* reset on a tick: an edit elsewhere in the tree must not throw the reader back to the top of what they are reading
- **The overlay carries a page indicator on the bottom right of its border**, `pg 2/8`, so a long ticket does not open looking exactly like a short one. `Block::title_bottom` with a right-aligned `Line`, which spends no text row, the trade the title already makes on the top border. The two cannot crowd each other: they are on opposite borders
- **`wrapped_height` is the one measurement.** `last_offset` is it less the viewport and `page_indicator` takes the same two numbers, so the clamp and the indicator cannot disagree. A second `line_count` call, or a count of the raw lines, is a number free to drift, and an indicator that says there is more to read where the scroll refuses to move is worse than none
- **The furthest offset is the last page by definition, not by division.** The clamp stops at the wrapped height less the viewport, which is not a page boundary, so the final screenful is partial: `offset / step + 1` reads `pg 2/3` at the bottom of a 25 row ticket in a 10 row viewport and claims there is more below
- **The pages are counted in `scroll_step`, a screenful less the overlap line, not in whole screenfuls.** The step is what the keys take, so counting in it names only pages `pgdn` can land on. Counting by screenfuls puts a 30 row ticket in a 10 row viewport at `pg 3/3` two rows short of its end, since three presses are what it takes to get there
- The indicator is dropped whole on an overlay too narrow for it, the rule a corner follows, and absent entirely when nothing scrolls, the way an untagged card spends no row on tags
- `page_indicator` takes four numbers and returns an `Option<String>`, so every case above is pinned without a terminal. The drawn tests exist for the two things arithmetic cannot answer: which border it landed on and what colour it reached the screen in
- **Columns scroll to keep the selected card in view.** `Board::offsets` holds one offset per column, parallel to `columns` and resized in step by `reload`, so a column you leave stays where it was. The keypress aligns the focused column via `follow_selection(screen)`, taking the screen size for the same reason `scroll_detail` does: the visible height belongs to the terminal, which only the caller measures between draws
- Card heights are measured on `card_lines`, never assumed, on both the keypress and the draw side (`card_height`, and the `starts` vec as the cards are built). An alignment that trusted a fixed card height would drift from the renderer the first time the card changed shape
- The draw aligns the focused column again on its own geometry, so a resize between keypress and frame cannot hide the selection, and caps every column against blank space past its last card. The stored value may go stale after a tick shrinks the column; that is fine, because what is drawn is corrected immediately and the next navigation writes the correction back
- Entering another column follows the selection rather than resetting to its top. The card index carries across columns, so a reset would open the column with the highlight below the fold whenever it was — the opposite of the detail view's reset-on-selection-move, where each ticket genuinely starts at its own top. The index is shared and clamps permanently when a shorter column pulls it down, so a column you return to follows the selection to where it now sits rather than holding your old place
- **The footer names only keys that work.** It read `↑↓ scroll` when nothing scrolled at all, which sends the reader looking for their own mistake. A UI that misdescribes itself is worse than one that is merely incomplete
- **A hint is a key and what pressing it does, and `key_hint` is the only thing that draws one.** The key is cyan and bold, the description takes the terminal's default foreground, and the row keeps its three-space gaps. Everything that names a key goes through it: the three footer states, the prompt's two keys, the picker's row and the `q board` on the frame's border, so a reader learns the shape once. Same division in frig and pantop, each in its own accent colour, cyan here and magenta there — the three tools are read side by side and used to look like three programs
- **A key that is its description's first letter is merged into it**, so the board draws `quit`, `campaign` and `tag` with the letter coloured and no letter in front, while `y copy id`, `ctrl-c quit`, `d show done (2)` and every arrow row stay split. Two cells back on a row already at its width naming eight keys, and the coloured letter *is* the key either way. The prefix test in `key_hint` is case sensitive for exactly that reason: a row naming both `r` and `R` would otherwise draw one word for the two of them, and the merged form can only say which key it is while the letter on screen is that key. It also means the row carries both forms at once, which is the cost of the two cells
- **What the row is cannot be read off its text any more, so the tests read its cells.** `footer_cells`, `footer_at`, `keys_on` and `footer_style` in the test module: `keys_on(.., "quit")` is `Some(1)` where `q` quits and `Some(0)` on a row whose only `quit` is the tail of `ctrl-c quit`. A `contains("q quit")` cannot tell those apart, and three of the guards that keep 1b78a24 out were written that way
- **`q` and `esc` are one key: close what is open, quit when there is nothing left to close.** `q` used to set `should_quit` outright, so a reader who pressed it to put a ticket away lost the board instead, which is not what `q` does anywhere else that lays a document over a list. One match arm in `main.rs`, not two: two arms carrying one rule is how a later edit changes it for one key and not the other
- **The rule is `Board::dismiss`, not the match arm.** The dispatch in `main.rs` is not reachable from a test, so anything decided there is undecidable by the suite. The arm is the line that names the keys and nothing else. `the_dispatch_gives_q_and_esc_one_arm_and_leaves_ctrl_c_quitting` scans `main.rs` for what the arm cannot say for itself, over whitespace-collapsed source so rustfmt cannot fail it
- **The footer's last slot always answers how to get out**, and with a ticket open the honest answer is `ctrl-c`, the only key left that quits in one press. Going on drawing the merged `quit` there would be 1b78a24 in the other direction: a footer describing a key by what it used to do. `ctrl-c quit` is split by the same rule that merges the other, being no word's first letter
- **The overlay names its ticket on the border, not at the head of the paragraph.** `Board::detail` is a `Detail` carrying the title, the id and the text, because the name has to travel beside the body rather than inside it: `content_trim` drops the `# ` heading on purpose, since `cmd_show` prints it, and anything in the paragraph scrolls away
- `detail_title` cuts the string itself instead of leaving it to ratatui, which truncates an overlong block title at whatever cell it reaches and would take the id with it. Cut against the inner width, so the id survives whole and the name ends in an ellipsis. The id goes first because that is how every other view addresses a ticket
- The detail view renders from cells, never from painted strings: ratatui draws styled spans, so an escape sequence in a paragraph would be printed as literal bytes. `content_trim` and `format_history_with` take the colour decision for the CLI's side of the same layouts
- Read only. Moving a card by keypress is a follow-up, deliberately kept out until the watch and render loop were solid
- **A card is four corners with the title between them:** mark and short id top left, due top right, owner bottom left, comment count then criteria count bottom right. The numbers are in corners because that is where the eye goes for one, and they were invisible at the end of a line of prose
- The title takes one row or two, wrapped on spaces, with an ellipsis when even two are not enough. One row when one is enough: a second, blank row on every short ticket spends the column's height on nothing
- **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
- **`corner_line`'s right side is a group, single-spaced, and it gives up its items from the front.** The item nearest the edge is what the corner is *about*; anything to its left has been added beside it. So the bottom row loses its comment count before its criteria count, and the top row, with one item, behaves exactly as it did when the parameter was an `Option`. The spacing between the items lives in `corner_line` with the gap arithmetic rather than in a caller, for the reason `column_areas` is shared: geometry reproduced by hand drifts from the draw. `due_span` returns a `Span` and not an `Option<Span>` now, since the `Option` only ever existed to satisfy the old signature and the function cannot fail
- 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
- **The comment count is the same field discipline and the one entry on that pass that costs a directory listing.** The history lives outside the ticket file, so `count_comments` is a `read_dir` rather than a parse: `.md` only, the filter `read_history` applies, and no body is read, because a count needs none of them. **It counts comments and not entries**, off the kind in the filename, so a card still says how many things somebody said: a ticket that has moved three times has not been talked about, and counting the moves would put a number on every card on the board. `collect_ticket_items` derives the board from `status_path.parent()` instead of taking it as a second argument, so a status directory from one board cannot arrive with the history of another. `history_dir` spells the path once for the writer, the reader and the counter, the way `campaigns_dir` does. Zero draws nothing, not a `0` and not a blank: an uncommented card is the row it has always been, which `a_card_with_no_comments_spends_nothing_on_the_corner` pins to the exact spacing
- **The count is cyan and the mark is `COMMENT_MARK`, U+275E, a Dingbat.** It is the only coloured thing on a row whose owner and criteria count are grey, because two counts side by side otherwise read as one number in brackets and another that lost its brackets. Not U+1F4AC SPEECH BALLOON: emoji presentation and East Asian Width Wide, so it draws two cells where `spans_width` counts one character and every corner on the card lands a cell out. Not U+1F5E8 LEFT SPEECH BUBBLE either: text presentation and Neutral, but in a pictograph block most terminal fonts leave as tofu. Check both properties before swapping the glyph
- **`the_count_is_read_when_the_items_are_collected_and_not_per_draw` takes the history directory away after the board is built**, and is paired with `a_comment_added_after_the_board_was_built_reaches_the_card_on_reload`, because a count that never asks the filesystem again would pass the first test by never changing. The digest already moves when a comment lands, so the reload is what recounts
- **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 gives up tags until the two fit 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_cells` 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 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`, `column_count` and the copy key all keep working unchanged
- **A campaign filter is a uuid on the tab, not on the `Board`.** `Tab::filter` is a `Filter`, and 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 has two heights, and `Chrome` is what every measurement takes.** `Chrome::frame` is an `Option<FrameSize>`, not a bool: `None` for a tab showing the whole board, and `Collapsed` or `Expanded` for one filtered to a campaign or a tag, because both heights have to be measured the same way by everything that measures the board. `screen_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](rust-style.md) 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`, `FRAME_ROW`, `BOARD_ROW`, `FOOTER_ROW`), since an index written out by hand goes on meaning what it used to. **Nothing in the geometry is named after campaigns**, because the slot is the tag filter's too: `Chrome::frame` says how tall the frame is and never which filter filled it, so a measurement of the board never has to ask
- **The whole description is carried off the one read, and the cut is on the view.** `section_prose` replaced `section_opening`, which cut to the opening line at read time: the campaign file is only in hand while the campaigns directory is being read, so what that read has to carry is everything a view might want, and `CampaignRow::summary` takes the one line the picker draws back off it. Two fields, one cut from the other, are two strings free to come from different reads of the same file
- **`FRAME_PROSE_ROWS` is the collapsed height, and it is a constant rather than a height fitted to the description.** Three rows of prose plus a border either side. A frame that grew and shrank with the campaign would resize every column whenever the filter changed, and a reader would look for a card where the previous campaign's description had put it. It does not have to be right for the longest description, because scrolling is what covers the rest — which is also why three was affordable where one row was not
- **The expanded height is a share, not a second constant: half of what the frame and the columns divide.** That is the screen less the tab row and the footer, so the split is even between the two of them rather than even against rows neither gets all of. Half rather than most of it for the same reason the frame is not an overlay: the columns below are the campaign's members, and a reader inspecting the campaign has to go on seeing what it is made of. Floored, so the odd row goes to the cards. `Chrome::frame_rows` takes the height because of this, and `screen_rows` is where it is called, since that is the one place that already has an area to take a share of — which is what keeps `Chrome` itself pure and copyable from `Board::chrome` with no screen to hand
- **The share is bounded at both ends, and `COLUMN_MIN_ROWS` is why.** `Constraint::Min(COLUMN_MIN_ROWS)` would take rows back from a frame that asked for too many, silently, and the frame's own measurement would then disagree with what is drawn — the fault `Chrome` exists to prevent. So the share is capped at what leaves the columns those rows, and floored at `FRAME_ROWS`, since expanding must never shrink the frame. On a board too short to divide, `enter` gives the collapsed height back rather than a height nothing measured. `the_expanded_share_is_bounded_at_both_ends` sweeps every height from 4 to 60, tabbed and not, because one screen that happens to work says nothing about the arithmetic
- **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` then the page indicator on the bottom left. Every row spent here is a row of cards
- **The frame slot is shared between the filters, not doubled.** One filter is on at a time, per `Filter`, so a tag frame is the campaign frame with its three slots filled differently: `#tag` in `tag_color` on the top border where the campaign's identity goes, how many tickets carry it on the bottom right where the standing goes, and the annotation in the prose rows. `FrameContent` is what they are told apart into, and **`frame_content` is the one place they are told apart at all** — the borders, the colour, `q board`, the page indicator, the scroll and the focus are all the campaign frame's, and a second `match` on the filter below that is how the frames come to behave differently in a way nobody decided
- **A tag frame draws the annotation, which is the payoff for declaring a tag.** Whoever is browsing a tag is deciding whether the next ticket belongs in it, and the sentence saying when the tag is appropriate is then on the screen at that moment rather than in `tags.md`, which they would have to know to open. An undeclared tag draws `NO_ANNOTATION` in grey, which is also the frame saying the word was never agreed on — the vocabulary file's own placeholder rather than the description section's, so the frame and the file say the same thing about the same tag. A tag declared with nothing said about it draws the same, since here the two have the same nothing to show; the picker's sections are where the difference is actionable
- **A tag has no id, so `y` on its frame copies the word.** A tag *is* its name, matched whole by `ls --tag`, so there are no seven characters to shorten and the `#` the border draws is not part of it — `--tag "#bug"` matches nothing. The footer says `y copy tag` there for the same reason: naming it an id would send the reader looking for a short id on a border that prints a word
- **The count on a tag frame is every column's, drawn or not**, the rule the standing holds. With the filter on, those columns *are* the tickets carrying the tag, so it counts what is below it without counting it a second way. The noun is spelled out and pluralised, because a bare number on a border says nothing about what was counted, and there is no derived state beside it: a tag is a word and not a piece of work, so there is no `[open]` to be in
- **The frame's page indicator goes on the bottom border beside `q board`, not on the top beside the title.** The title is cut against the border it sits on, so an indicator up there would shorten a long campaign name the moment its description grew past three rows; and the bottom right is the standing's, which is what the frame is *about* where the indicator is only where the reader has got to in it. Dropped before `q board` when the two cannot both fit, since with either filter on the footer's last slot names `ctrl-c quit` and the border is the only place that says `q` gives the board back
- **`Focus` is the third place the selection can be, and `Tab` is what holds it.** The board had a column and a card and `select_card` clamped at zero; up from the top card now reaches the frame and down returns to the column it left, since the column index is never what changed. Per tab beside the filter and the offset, so switching away and back returns to where the tab was left. `Focus::Frame` while no filter is on is the one state that must never exist — `select_filter` and `reload` are what keep it from arising, off `Filter::is_whole` rather than off which filter it is, since either draws a frame to hold it
- **`Tab::selected` hands back nothing while the frame holds the selection.** Every key that acts on a card has to answer for the frame. `←→` are inert, because the frame spans the width of the board and moving the column underneath would change nothing on screen. `y` is the exception that earns its place: it copies the campaign's short id, so `y copy id` means the id of the selected thing in every state the selection can be in. No card is drawn reversed there either, since that highlight is what says which ticket a key is about
- **`enter` routes on the focus through `Board::toggle_focused`: the frame's height on the frame, the overlay on a card.** It used to be inert on the frame for free, because `Tab::selected` hands back nothing and `toggle_detail` therefore had nothing to open. That is no longer an answer, and the routing is in `Board` rather than in the `main.rs` arm for the reason `dismiss` and `scroll_page` are
- **`q` does not gain a layer for the expanded frame, and up and down do not take it back.** The expanded frame is the frame at its other height, not a thing laid over the board, so `q` goes on taking the campaign filter off from either height and `enter` is the only key that undoes what `enter` did. The height outlives the selection for the same reason: it is a view of the campaign the reader chose, so the columns stay short with the selection on a card. `Tab::expanded` sits beside the filter and resets where `select_campaign` and `reload` reset the focus and the offset — a different campaign opens collapsed and at the top of its own description
- **The toggle re-clamps the frame offset, through `scroll_frame(0, screen)`.** A taller viewport has a smaller last offset than a shorter one, so where the reader was can end up past the end of the frame they just asked for. The draw clamps on its own geometry either way, but the stored value has to be clamped too or the next `pgup` counts down from a number the frame never showed. A scroll of no pages is that clamp and nothing else, which keeps it in the one place it lives
- **The frame is out of reach from under an open ticket.** With the overlay open, up and down step through the tickets and it follows, so a selection that reached the frame would have to either close it on an arrow key or leave it showing a ticket nothing is selecting. `an_open_ticket_keeps_the_scroll_keys_from_the_frame` builds that state by hand for exactly this reason: the precedence has to hold whether or not a keypress can reach it
- **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, and measured over its spans rather than one string since it is a key hint like any other. Drawn through `key_hint` and not as grey chrome: it is the one key on the board named anywhere but the footer, and a reader who has learnt to look for the cyan letter should not need a second convention to find it. The indicator beside it stays grey, having no key in it
- **`c` and `t` are named in the footer only on a closed board with nothing filtered**, which is where a reader has to find them. Over an open ticket and on a filtered board they are left out: the frame's border then says how to put the filter away, and the row has no cells to spare. The tag used to be drawn on that row in its own colour, for want of a frame to draw it in, and 2a83bd4 took that away rather than saying it twice. 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
- **The footer has three states, because the selection has three places to be.** An open ticket, the frame, and the cards. On the frame it names `↓ board`, `↵ expand` or `↵ collapse`, the two scroll keys and `y copy id` — `y copy tag` on a tag frame — and leaves out `←→` because they do nothing there. It has to say which way `↵` goes, since the key is a toggle and the frame is always at one of its two heights. `↑ frame` is not named on the board, on the same trade `c` is dropped on: the frame is drawn directly above the columns and up is the key that reaches it. Nor is the way to collapse an expanded frame named from the cards, which is the same trade again — the frame is right there and `↑` reaches it
- **`picker: Option<Picker>` 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
- **`t` opens the same picker over the tags instead, and taking a tag filters every column to the cards carrying it.** Every tag the board declares or carries, matched whole and case sensitively the way `ls --tag` matches — the box completes the filter, so offering what the filter would refuse is the one bug it must not have. It opens on the tag already applied, the courtesy `c` pays a campaign-filtered board, and a board carrying no tag gets the same `Notice` a board with no campaigns gets
- **A picker row draws a real codename only.** The row opens with the short id, so the card's `~<id>` fallback would print it twice and say nothing the second time
- **One picker serves both lists, and `PickerRow::key` is what keeps it one.** A second picker would have been a second keyboard, query and highlight to keep in step with the first; instead `PickerKind` decides only which list is built, and everything between the keypress and the filter runs once against the key — which since the pile arrived is a `PickerKey` enum rather than a bare string, because one of the answers filters on an *absence* and carries no string to hand back. `take_picked` reads the kind off the answer rather than off which list was open. Picking any of them clears the others without either setter remembering to, because `select_filter` replaces one `Filter`: one field, which is the same reason the frame slot is shared
- **The campaign picker opens with a row for the tickets in no campaign**, above both sections and never truncated: the pile is the one question about a board of campaigns that no single campaign answers, and on a board whose completed tail is being kept back it would be pushed off the box if it listed among them. It draws its count where a campaign row draws its standing, so picking an empty pile is seen coming; under a query it answers "no campaign" and "none" and hides like any other row. **It selects `Filter::NoCampaign`, its own variant** — `retain_campaign` compares the field to the uuid it is given, so the absence case is a different predicate beside it (`retain_no_campaign`) and not a different value in it, and a magic uuid meaning none is exactly the thing that later matches a real one. A dangling uuid is *set* wrongly and stays out of the view, as it draws `_missing_` on its card rather than nothing at all
- **The pile crosses boards where a campaign cannot, so it is pickable on the merge tab.** An unset field means the same thing in every `.worklane`, the property that lets a tag filter travel there; the count adds across boards, taken at reload off the unfiltered columns like the standings are (`Tab::no_campaign`), never per draw and never off the filtered columns, which would answer zero about themselves
- **The opening highlight still lands on the first campaign, not on the pile.** Campaigns are what this list opens for; the row sits above the list without claiming it — one step up reaches it, it holds the highlight whenever it was the row selected, and only when every campaign is hidden does it take the opening one
- **The frame speaks for the pile in its own words, because the frame question stays `is_whole()`.** Exempting one variant from either half of that rule would be a state where the selection rests on a frame that is not drawn — the one thing `Focus` exists to make unrepresentable. So the title is grey `no campaign` (no id to shorten and no mark, which keeps `~` meaning a campaign and `#` a tag), the standing corner takes the count, and the prose is one grey sentence the board owns, since no file holds words for an absence
- **`y` has nothing to copy from the pile's frame** — no id to shorten and no word a command line takes, `ls --campaign` being unable to say none — so the footer leaves the key out rather than naming it into a notice, and pressing it anyway still answers "nothing to copy"
- **The picker draws two sections, open campaigns above completed, and truncates the completed tail.** One flat list by title put the finished campaigns among the open ones forever, and the tail only grows, so on a board that has run for a while the campaigns worth picking were pushed towards the bottom of the box and eventually off it. Open keeps the index's order, which is by title; completed is by `Created At` newest first, because what a reader recognises about a finished campaign is that it was finished recently. `COMPLETED_SHOWN` of them survive, behind a grey line naming how many older ones are being kept back — rows that are simply gone read as a board that never held them. An unstamped campaign sinks below every stamped one, the rule `by_status_order` holds for a column
- **The tag sections are declared above undeclared, and truncate neither.** The same two-section shape with the opposite reason for the second: a completed campaign is finished with, so its tail is kept back before it pushes the pickable campaigns off the box, while an undeclared tag — a word somebody typed onto a ticket that the board never agreed on — is the row a reader most wants to see. A declared tag no ticket carries stays a row too: `tags.md` is what the board intends, and the vocabulary the listing reports is the one the picker offers. `campaign` and `campaigns` would have sat one under the other here, in different sections, the day the second was invented
- **`picker_list` is the one place that decides what a picker row is**, and `Picker::row` counts *drawn* rows. The sections reorder the campaigns and add rows of their own, so `Tab::campaigns` and the drawn list agree about no number past the first heading, and a row number that meant one thing to the draw and another to a keypress is how a highlight comes to name a campaign nobody chose. The list is derived on every draw and every keypress and never held, which is what keeps a campaign filed elsewhere reaching an open picker on the next tick
- **A heading is drawn only over rows that exist**, the bargain an untagged card's label row already makes, and it says which kind its rows are for as long as they are there — which is what a query filtering down to completed campaigns alone has to go on saying
- **`open` and `completed`, not `open` and `done`.** The split is taken from `Standing::state`, so the section a campaign lands in and the state the frame draws cannot come to disagree about what finished means, but the word is the section's own: a campaign sits in no status directory, so it is not *in* done the way a ticket under that heading is. A campaign with no members is neither, per that method, and lists as open — completed means every member is done, and it holds none to be done
- **Headings and the truncation line take no number: the highlight moves over campaigns only.** `stepped_picker_row` walks past the chrome rather than stopping on it, since a highlight resting on a heading gives `enter` nothing to do, and a step that runs out of campaigns is no move at all, the way a card at the end of a column clamps rather than cycling
- **`/` in the picker is the key it already is on the board**, and `picker_key` can take it because printable keys used to fall through `_ => {}`. Typing filters case insensitively against the short id, the codename and the title — the three things the row draws and the three a campaign is chosen by. Not the summary: a query that matched prose would answer `disk` with every campaign whose description mentions one. A tag answers by itself or by its annotation, which is a reader who cannot remember the word finding it by what it was for — case insensitive here though `--tag` is not, because matching a tag is the filter and searching for one is a reader typing. **An empty query matches everything**, the opposite of `first_match`'s answer and right for the opposite reason: a jump with nothing typed has nowhere to go, while a filter with nothing typed is not filtering, and pressing `/` must not empty the list
- **A query turns the truncation off**, which is the point of having one: the campaign a reader is searching for is exactly the one the truncation hid
- **The query is a layer, and `esc` takes it off before it takes the picker off**, the order `dismiss` closes the board's own layers in. So the list is whole again after that press, not still filtered with nothing on screen saying why. Movement and `enter` stay live under an open query, because a filtered list nothing can move in is a list nothing can be chosen from; every *printable* key goes into the buffer, so `q` types and so does `j`
- **The highlight follows its row, not its row number.** `place_picker` takes a key — whichever answer `PickerRow::key` hands back, the same shape `Tab::filter` holds for any of them: typing, clearing the query and a tick that finishes a campaign all reshape the list, and a number kept across that names whichever campaign now sits at it. One the list no longer holds drops the highlight to the first row that does, which is where an incremental filter puts it. `reload` reads the highlighted key before the lists are rebuilt and puts it back after
- **Both ends bring the highlight into the window.** Opening aligns against the screen the dispatch hands `open_picker`, and the draw follows the highlight again through `aligned_offset` on the geometry it is actually drawing — a resize between that keypress and the frame, or a tick that put the highlight back without touching the scroll, cannot leave it below the fold until some later keypress fixes it. The stored offset is left alone, the way a column's is: what is drawn is corrected immediately and the next navigation writes the correction back
- **A miss is a row in the box, `no match` in brightred**, where the search prompt puts its own, and `enter` on it leaves the picker and the query exactly as they are so the query can be corrected in place. An empty box says nothing about why it is empty
- **The picker's footer becomes its query**, the trade `draw_search` makes: with every printable key going into a buffer, a list of keys describes nothing that works. `/ search` is named only on the closed query, and the open one names what `esc` does to *it* rather than what it does to the picker
- **The title says both counts while a query is open**, `campaigns (2 of 6)`. The bare total is what the box is, but over a list a query has cut down it is a lie about what is on screen
- **Every campaign's standing is settled at reload, in one pass over the cards.** `standings_of` counts the cards naming each uuid off the columns the reload is already holding, which is what `Standing::of` builds for `campaign ls` without the walk of the status directories that one pays *per campaign*. A keypress must not pay that, and the picker needs every campaign's standing rather than just the selected one's, since the split is what it decides. Counted before the campaign filter is applied: how far a campaign has got is not a question about what the tab is showing
- **`Tab::standing` is gone with it.** The frame's standing is the row's, because two counts of one number are two numbers free to drift — the rule `wrapped_height` holds for the scroll. `the_standings_are_read_when_the_cards_are_and_not_per_draw` takes the status directories away after the board is built, paired with `a_member_finished_after_the_board_was_built_completes_its_campaign` for the reason the comment count's two tests are paired: a standing that never asked the filesystem again would pass the first by never changing
- **`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 history. 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. An untagged ticket spends no row at all, the way a short title spends no second one
- **A row the column will not hold draws the tags that fit and ends in `(+n)`**, the count of the ones it left out. Whole tags only, the rule a corner follows: `bug` and `bugfix` cut to the same width say the same thing. What changed in 39be95b2 is the other half of that rule — the row used to go whole, so a narrow column, which is exactly where a reader is scanning cards for a tag, showed no tags at all. A short row is allowed as long as it says it is short, and the indicator is the entire difference between a cut list and one that reads as the ticket's whole list. So a row with no room for one tag beside the count is still dropped whole: `(+3)` alone tells nobody anything, and a tag drawn without the count would lie. `tags_that_fit` measures the indicator as part of the row it counts rather than reserving it up front, because `(+9)` and `(+10)` are different widths and a list of under ten should not pay for the tenth
- **The count is grey and parenthesised**, not a colour of its own and not bracketed: it is a fact about the row rather than another tag on it, and `[n/m]` two rows below is the criteria count
- `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 its blocker has not moved out of the way of looked exactly like one that is ready, and the board is where the next thing to pick up is chosen. The mark is `mv`'s own rule asked one column ahead, so it says this cannot advance rather than that a dependency was ever recorded: a card in committed whose blocker is in reviewing is unmarked, because reviewing is where it may go, and the same card is marked once it sits in reviewing and only done is left. The two terminal columns have no next stage and nothing in them is drawn blocked. 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
- **The mark goes after the id, not before it.** Ahead of the id it would push every id in the column out of line whenever one card was blocked, which costs more than one card's state is worth. It is measured before the project label and the due date, so both give way to it: those are context for a ticket somebody can start, and this is the one thing on a card that says not to. Dropped whole when the row cannot hold the identity and the mark together, the rule a corner follows
- **`blocked` is on `Card`, not on `TicketItem`.** The answer lives on two tickets at once, so no card can reach it alone, and it is settled at reload the way `project` is. What `collect_ticket_items` fills is the ticket's own `uuid` and its `blockers`, both read off the file it is already holding; `mark_blocked` then walks the columns once for a uuid-to-status map and once to answer every card. No file is read twice and nothing is asked per draw
- **A blocker the board does not hold marks nothing**, the answer `mv` already gives a dangling uuid. A Relations section that cannot be parsed reads as no blockers, the exception `detail_of` makes for the same reason: `show` and `mv` are where a hand-edited file is reported, and a board that will not draw because one ticket is malformed is the worse failure
- **The merge carries the flag rather than recomputing it.** `relate` resolves its target inside one `.worklane`, so a blocker in another project is not a relation anything can record; resolving over the merged columns would let one project's uuid match another project's ticket. That is b8ce18c's fourth plan step and the answer is no
- `project_label` takes the width the row has already spent, measured off the spans, rather than adding up the widths those spans are supposed to have. The hand-written version left out the space after the priority mark, so a cut label was handed one cell more than the column had; `the_project_label_leaves_the_row_inside_the_column` pins it
- `due_date` cuts a due value back to its date only when it has one. The field is not validated (daa0e79), so it can hold a time or free text, and taking the first word regardless would turn "next friday" into "next"
- **The terminal columns are hidden until `d` asks for them, one step at a time.** Not a new opinion: `ls` already counts both in its summary and leaves them out of the listing. Done only grows, so a quarter of the width was going to the column least often read, and discarded arriving made it two. So `d` rotates three states — hide both, show done, show both, and back around — through the `Visibility` enum on `Board`, discarded last in the rotation because it is the least likely thing to be looking for. The footer names what the *next* press does and carries the count of the column still hidden, which is the board's version of that summary line. Hiding is a prefix of the columns: done and discarded are the last two in what the board draws, so revealing either appends it and the columns before keep their indices
- **Hiding is a change to what is drawn, never to what is read.** `reload` still scans the done and discarded directories and `digest` still watches them, so the footer counts are right and revealing either column needs no rescan. Do not "optimise" that into a conditional scan
- `visible()` returns a prefix of `columns`, not a filter, which is what keeps `column` and `offsets` valid as indices into either. It is derived from where `DONE` and `DISCARDED` actually sit rather than assuming positions, and `the_terminal_columns_are_last_in_the_order_drawn` pins the assumption. A status inserted after discarded would otherwise hide two columns in silence
- Hiding the column under the selection moves the selection to the last drawn column and **closes an open detail view**. The alternative, refreshing the modal onto whichever ticket the selection landed on, swaps what someone is reading without saying so, which is how a person acts on the wrong ticket. Showing another column is a no-op for the selection, since a column is appended rather than inserted
- The choice is not remembered between runs. worklane has no config file and one flag is not a reason to start one; if it should persist, that is its own ticket
- **Assert a column heading against the top border row, not the whole screen.** The footer names done too, so `screen.contains("done (0)")` passes on the footer whether the column is drawn or not. Three tests went vacuous that way the moment done was hidden; `headings()` and `footer()` exist so the next one does not. `headings()` locates the row through `board_area()` rather than taking row zero, since the tab row sits above it when more than one board is monitored
## Monitoring Several Boards
- `worklane tui <path>...` takes any number of paths, each resolved through `find_worklane_dir` the way the working directory is: the first `.worklane` at or above it. No path is the working directory, so a bare `worklane` and `worklane tui` are unchanged
- The failure **names the path** that had no board, since with several arguments "No .worklane directory found" does not say which one was wrong. Only when a path was given: a bare `worklane` has no path to name and keeps the message every other command gives, which is what its integration test asserts
- Two paths inside one project resolve to the same `.worklane` and are monitored once. `projects()` dedupes on the resolved directory, not on the argument
- **`Tab` owns the selection**, `column`, `card` and `offsets`, not `Board`. Sharing them across projects would point the selection at whatever unrelated ticket sat at the same place in the tab you switched to. `Board::current()` is the tab in view, and `visibility` stays on the board because it is a preference about the flow rather than about a project
- The tabs are fixed for the run: a project cannot be added or dropped without restarting, so `Board::new` builds the tab list once and `reload` only refills each tab's columns. `reload` clamps **every** tab, and `select_tab` clamps again on arrival, because done may have been hidden while another tab was in view
- The merge tab goes **first** and is where the view opens: it is the reason to monitor several boards at once. It is materialised in `reload`, from the cards already read, rather than computed per draw — the same reason the criteria count is filled in `collect_ticket_items`
- The merge is **sorted**, through `by_priority_then_title` in `util.rs`, not concatenated. An overview whose order depended on the order of the arguments would bury one project's p1 under another's p5. It keeps priority then title where every other column takes `by_status_order`: the merge spans statuses, so no single date governs it
- `Card` wraps a `TicketItem` with the project it came from, `Some` only on the merge tab. Decided at reload rather than passed down to `card_lines` as a "which tab is this" flag. `TicketItem` is therefore `Clone`: the merge holds a second copy rather than re-reading every tree
- **The project follows the id, on the card and on the overlay border.** Across boards the id is not an address: two projects can hold the same title, and seven characters do not say where they live. `project_label` takes what the row has left after the mark and the id and ends in an ellipsis, and it is measured before the due date, so on the merge the project wins the narrow column and the date is what `corner_line` drops
- `tab` and `shift+tab` cycle rather than clamp, unlike the cards and columns: a row of tabs is a ring, and there is no end of a list to run off. Both were free of every other binding — the columns took `hjkl` and the arrows
- **The tab row is drawn only when there is more than one board**, so a single board is the view it has always been. `screen_rows()` gives it `Length(0)` otherwise, which keeps the row indices the same for both cases and is shared with `card_width` and `column_text_height` for the reason `column_areas` is: geometry reproduced by hand drifts from the draw
- `digest_of` hashes each board's `digest` into one value, so a change in any of them redraws. Do not watch only the first
+98
View File
@@ -0,0 +1,98 @@
# The Board Prompts
The three input modes on the board and the key that copies an id off it.
## The Search Prompt
- **`search: Option<Search>` is the whole mode**, the shape `detail` uses: "the prompt is open" and "what is in it" cannot disagree, and closing it leaves nothing to reset. `Search` also carries `missed`, set when enter found nothing and cleared by the next edit, since the message is about the query that missed
- **The prompt swallows every key it is given.** `Board::search_key` runs ahead of the action arms in `main.rs` and reports what it took, rather than every arm below asking whether a search is open. Typing `d` into a query must not toggle done and `q` must not quit; with no prompt open it takes nothing, so the dispatch is unchanged for every other state. The rule is on `Board` for the reason `dismiss` is: the arm is not reachable from a test
- **`ctrl-c` is the one key it declines**, because a terminal application always honours it and a prompt that ate it would leave no way off the board. Every *other* control combination is swallowed and does nothing: it must not type its letter, and it must not fall through either, since the action arms match on the code alone and `ctrl-d` would reach the one bound to `d`
- **Esc is consumed by the search before it can mean anything else**, which is the collision e7612de left behind: `esc` and `q` close the overlay, and both have to lose to an open prompt. It falls out of the pre-branch rather than being ordered by hand
- **`first_match` searches the *visible columns*, every card in them, not the rows on screen.** A query that answered differently on a tall terminal and a short one is not a search, and the jump scrolls the match into view anyway. Hidden columns stay out: with done hidden, a match there would put the highlight on a ticket that is not on the board. Reading order is column by column, then top to bottom
- Id and title only, per 3b16540, both lowercased. The title has to be case insensitive to be worth typing, and giving the id the same treatment lets a pasted id match whatever case it was copied in. An empty or all-space query matches **nothing** rather than everything
- **The jump goes through `select_at`, the tail `select_card` already used.** `follow_selection` scrolls the column the card is in, and the offsets are per column and on the `Tab`, so a jump across columns moves the right one; `refresh_detail` keeps an open overlay on the ticket the selection names. A second version of either is how a jump comes to scroll differently from the arrow keys
- **A hit closes the prompt and a miss keeps it open**, marked, with the selection untouched. The query can then be corrected in place instead of retyped from `/`. Doing nothing visible is what makes a reader retype a query that was already right
- **The prompt takes the whole footer row**, because the key list it replaces describes nothing that currently works while every key is going into the buffer. Its two keys are drawn as every other key is, cyan on the key and the default foreground on the word. That the query then sits in the same foreground as the descriptions is what the house style costs on this row, and the cursor is what says which half is an input — which it does in a terminal with no colour at all. `no match` stays brightred beside the query it is about, being the one thing on the row that is neither a key nor what was typed
- **The real terminal cursor goes after the query**, not a glyph standing in for one. ratatui shows the cursor only for a frame that asked for it, so `set_cursor_position` is also what says "you are typing" while the query is still empty. Clamped to the row, so a query longer than the terminal leaves it on the last cell
- Both closed footers name `/`, since the jump works with a ticket open as well: it moves the selection and the overlay follows
- Out of scope on purpose, each its own ticket once the input mode exists: `n` and `N` for the next and previous match, searching the description, tags or owner, regex, and filtering the board down to matches rather than selecting one
## The Command Prompt
- **`prompt: Option<Prompt>` is the whole mode**, the shape `search` and `detail` use: open and content cannot disagree, and closing it leaves nothing to reset. `Prompt` carries the line, the cursor as a byte offset into it, and `refused`, which is `Search::missed` with something to say
- **`Board::prompt_key` is third in the pre-dispatch**, beside `search_key` and `picker_key` and on the same contract: while a command is being typed `q` is a letter, `d` leaves the columns alone and `tab` stays out of the project tabs, and `ctrl-c` is the one key declined. It takes a `Size` for enter's sake: running a command reloads the board and then has to bring the ticket it moved back into view, which is the measurement `follow_selection` takes. Only one of the two prompts can be open at once: `:` is reachable from the action arms alone, and while either has the keyboard the other's key is a character in a line
- **`esc` and `enter` are the mode's own keys and are answered in `prompt_key`; everything else belongs to the line and goes to `Prompt::key`.** That is also what keeps the borrow straight, since closing the prompt takes the whole board and editing takes only the prompt. Left, right, home, end, backspace and `ctrl-w` behave as they do in a shell, and `ctrl-w` eats the separators behind the cursor before the word behind those, so one press at the end of `mv 1b78a24 ` takes the id. `tab` is the mode's too, for the reason the recall walk is: what it takes is made of the selected card and the line is only where it lands
- **The grammar is clap's, with nothing restated.** The line is tokenised by `split_line`, the binary's own name goes in front, and the arguments go to the same `Cli` definition the shell reaches, so a flag added to a command is typeable here the day it is added. Through `Cli::command().try_get_matches_from_mut` rather than `try_parse_from`, for what the matches give back: `command_name` walks the subcommands to name what resolved (`campaign show`, not `campaign`) instead of a `match` over every variant, which would be a second list of every verb the CLI has and one that goes stale silently
- **`refused` is cleared by an edit and not by a movement.** The message is about the line, and moving the cursor does not change the line. `Prompt::key` clears it in the three arms that write to the line
- **A line that ends inside a quote never reaches clap.** That is what `Unclosed` is for: a grammar complaint about a sentence nobody finished describes the wrong thing. Enter on an empty line, or one of nothing but separators, closes the prompt with nothing said, the way `esc` does — the bare form of the CLI opens a board and there is one on the screen
- **Enter runs it, through `main.rs`'s `dispatch` and never through a handler this file names.** That match is the one mapping from a parsed command to the function that performs it: `main` calls it with its own stdout and the working directory, `Board::run` calls it with a buffer and the selected tab's root. A second copy inside `tui.rs` would drift the first time a command was added, and it would drift *silently*, since both halves go on compiling. The match is exhaustive so a new verb cannot fall into an `_` arm and do nothing, and `main_and_the_prompt_run_one_dispatch_table` reads both files as text to pin it. Only `tui` is matched outside the table, in `main`, because the board is that table's caller rather than an entry in it; reached from the prompt it is refused in those words
- **What it writes is attributed to the person at the board**, through the same `dispatch` parameter, because a line nothing but the reader can type is the reader's action. The rule and its precedence are in [history.md](history.md), which owns attribution; what belongs here is that the board is the one caller that asks for it
- **`from_arg_matches` on the same matches gives `run` the typed values.** One parse, two readings: `command_name` walks the subcommands to name what resolved and `from_arg_matches` reconstructs the `Cli`. A `match` over every `Command` variant to get one or the other would be a second list of every verb the CLI has
- **The handler's own words are what the board reports, word for word.** Those messages are written for a person already, and a second set kept here would go stale the first time one of them changed. The sink is a buffer, so the words come back as text and the board styles them; it is plain for the same reason `Detail` holds spans, since a ratatui paragraph prints an escape rather than obeying it. An error never goes through a sink at all — `color_text` asks the *process* about its stdout, which under the board answers yes about a terminal the message is not going to — so `error_lines` runs `without_escapes` over it and puts each cause on a line of its own
- **A warning goes through the sink's second stream, and never through `eprintln!`.** `Sink` carries two writers because the CLI's two streams are two: `Sink::std` hands the answer to stdout and an aside to stderr, and a shell has to go on reading the same line on the same stream. Under the board neither is a stream at all — stderr is the alternate screen with the columns on it — so `Sink::buffer` *holds* its warnings and `Board::run` reads them back with `Sink::warnings` and puts them above the answer, on both outcomes: a `mv` that warns about a dangling blocker and is then refused by a real one wrote the aside first, and it is the half that says why the refusal names one blocker and the ticket records two. That is c680e24: one `eprintln!` in `check_blockers` outlived fa5662a because a helper had no sink to reach, and ratatui does not repaint a cell it believes is unchanged, so the fragment stayed on the columns until something else redrew them. `no_handler_or_helper_reaches_a_print_macro` walks `src` for the next one, each file cut at its test module, so a print site in a module added tomorrow is caught the day it is added
- **A handler that errors leaves the prompt open with the line intact.** The usual cause is an ambiguous id, and the fix is two more characters rather than the whole line retyped from `:`. Ambiguity is an `Err` carrying the candidates, not a print and an `exit`, which is what makes it safe to reach from here at all
- **The reload after a command is unconditional, and runs whether it failed or not.** `tick` reloads on the digest, which is right for a change made in another pane and needless latency for one the board just made: the reader would watch their own `mv` take up to a poll interval to appear. Either way, because a handler that failed part way through has still written
- **The selection is restored by uuid across that reload, never by index.** `mv` puts the card in another column, `set --title` renames its file, and a filter can drop it out of view entirely, so the slot is not the ticket. `Board::reselect` has three answers: the card is in a drawn column and the selection goes to it; it is on the board but in a column the rotation is hiding, which is where `--status done` lands by default, so the notice says where it went and which key shows it; or the filter no longer holds it, which is said too, since a card vanishing from under the highlight reads as a bug in the board
- **The merge tab is refused, for now.** It is the one tab that is not a board — its cards came from several `.worklane` directories and it is none of them — so `Board::current_project` answers `None` there and the command is refused rather than landing on whichever project came first. Routing by the card a command names is ebc5755. The project is resolved by index and not by the tab's name, which is a label two projects can share: e1d79c3 is exactly that, and a write routed by name would be that bug with a file changing at the end of it
- **`Notice` holds as many lines as the command used, and `Board::notice_on_row` decides where they go.** One line with nothing else holding the row draws on the footer, where a copy's notice has always drawn. Anything else — several lines, or any answer at all while the prompt is still open on an error — draws as a box at the foot of the columns, cut to what the columns leave with the dropped count on its last row. A box rather than more rows of footer, and that is the whole reason it is an overlay: a footer that grew and shrank as notices came and went would reflow the columns on every keypress, moving every card the reader is looking at. `draw` and `draw_footer` both ask `notice_on_row`, so the two cannot come to disagree and draw the message twice or not at all
- **The command's own usage line takes the keys' slot as soon as the verb resolves.** The reader knows the grammar approximately — that `mv` takes a status, not whether it is a positional or a flag, and that `set` has a flag per section, not whether the criteria one is `--acceptance` or `--criteria` — which is what a shell answers as the line is typed and the board answered with nothing. `usage_of` walks the typed verb against the clap definition and renders *its* usage, so a flag added to a command is described here the day it is added; a table of synopses kept beside it would be a second grammar going stale silently, since nothing but a reader typing that verb would see the two disagree. The `Usage: ` label is dropped, being a block name in a help page of several where this is one line beside the line it describes
- **`esc` and `enter` are what the row gives up for it.** Two keys a reader learns once, against a synopsis that is different for every verb. A refusal still wins over both while it is up, being what was just said about the line that is still on the row, and `refusal` is the half that says what is *wrong* where this says what would have been right
- **A verb that resolves to nothing draws nothing, and complains about nothing.** The line is half typed most of the time the row is looked at, so an error about `com` is noise where a reader is still typing. A group's child is walked when the second word names one, so `campaign set` describes `set`; while that second word is half typed the group's own `campaign <COMMAND>` stands, which is what has been typed so far
- **Grey, and cut with an ellipsis rather than wrapped.** Grey is the chrome colour and says the same thing the suggestion's does: this is not in your line. The footer is one row, and a second one would reflow the columns every time a verb resolved — the reason a notice of several lines is a box. There is always at least the keys' width to cut into, because that width comes off the row before the line is windowed, so the usage never takes a cell from what is being typed
- **What a refused line shows is clap's own message with the usage block cut off**, which is also what drops the `--help` line after it. `--help` is the exception: it parses as an error of the kind that means *print this* and what it would print is a page, so it is caught and answered in a row's worth of words, or clap's help lands on the alternate screen the way an unsunk `println!` would. `--version` goes through the ordinary path, because what it prints is one line by construction. `ColorChoice::Never` on the command, so nothing that reaches the row carries an escape
- **The keys' width comes off the row before the line is windowed**, so a long command does not push them off the end; a message takes the row from the keys instead, since the reader has just been told something and `esc` and `enter` still do what they did. `prompt_window` anchors the window on the cursor's right edge, which costs the text *after* the cursor on a long line: keeping both ends needs a scroll offset in state, and the draw is where the width is known and the state is not writable
- `: command` is named in every footer state, because the key works in every one of them, and the prompt's own key is drawn as `↵ run`
## The Prompt's Recall
- **`up` and `down` walk the lines already typed, and the lines are on disk.** `.wlhistory` in the board's own folder, appended as each line is entered. It is the one file under `.worklane` the board writes rather than a command, and the only one that is not markdown, which is the cost of a recall worth having: a board is opened and closed all day, and one that emptied on quit would only help inside a single sitting
- **`Recall` is per tab, parallel to `Board::tabs`**, so the tab in view decides which list `up` walks. A project's lines are the ones naming its ticket ids, and handing another board's `mv` back on this one would offer an id that resolves to nothing there. The tabs are fixed for the run, so the two vectors cannot drift, and the same index that picks the tab picks the recall
- **The merge tab has no file.** It is the one tab that is not a board, `current_project` answers `None` there and a command typed there is refused for that reason, so there is nothing to attribute a line to. Those lines are still recalled for the run: every one of them was refused, and a refused line is the one most worth getting back. When ebc5755 routes a merge line to the board its card names, that board's file is the one to append to
- **The position is on `Prompt` and the lines are on `Recall`**, so closing the prompt forgets the position and not the lines: the next `:` opens at the end of the list again, which is where a shell opens. `pending` holds the half typed line `up` walked away from, and walking `down` past the newest entry puts it back, so leaving a command to look for an older one never costs it
- **The ends are stops, not wraps.** `up` on the oldest line leaves it up rather than cycling round to the newest, which is what a shell does with it; `down` with no walk under way does nothing, since there is nothing in front of a line still being typed and emptying the row would be a keypress that destroys work. **An empty recall does nothing at all**, and that includes leaving the line alone, or `up` on a board nobody has typed at would be a way to lose what is half written
- **The line is kept before anything can refuse it.** A refused line never reached a handler and the fix is usually two characters, which is what the walk exists to save. Consecutive duplicates are kept once, against what is already held, so the rule spans runs as well as one sitting; a blank line is no command and is not kept. Nothing is trimmed
- **A failed write is silent, and an unreadable file is an empty recall.** The line is in memory either way, so the walk works for the run on a board whose folder cannot be written, and a board with no history yet is the ordinary case rather than something to say. A notice about a history file would be about the one thing the reader did not ask for
- **`.wlhistory` is not in `digest`.** Appending to it must not read as the tree moving, or every command typed would provoke a reload of every board on top of the one `run` already does
## The Prompt's Completion
- **The reader has the ticket selected, which is the whole reason to type a command on the board rather than in a shell.** So where the line is naming a ticket, the selected card's short id is drawn after the cursor and `tab` takes it into the line. Retyping seven characters off the card in front of you is the friction the prompt exists to remove
- **Where a ticket goes is `completions.rs`'s answer, not a table written here.** `argument_at` reads `TICKET_COMMANDS`, `TICKET_SECOND_COMMANDS` and `TICKET_FLAGS`, which `no_ticket_taking_subcommand_is_missing` and `every_ticket_flag_is_a_real_option` keep honest against clap's own definition, and the campaign and tag lists beside them. A second copy of the positions on the board would go wrong the next time a command grew a ticket argument, and it would go wrong *silently*, since the test guarding the first copy would not read the second
- **The ticket is not always the first argument, which is what a naive version gets wrong.** `chown alice <ticket>` and `assign v1 <ticket>` put it second on purpose, `relate x --blocked-by <ticket>` puts it in a flag, and `chown --clear <ticket>` does too, since with no user to give there is no positional for it. Nothing is offered where the argument is something else: `relate --clear` wants a kind, `set --clear` wants a field name, and `chown`'s first argument is a user
- **Position is counted, exactly as the fish half counts it**, so `mv --status done <ticket>` is not recognised: the ticket is `mv`'s first positional and the third argument on the line. That is the fish rules' limit as well, and one table answering both is worth more than two tables disagreeing about the corner
- **`TICKET_FLAGS` holds pairs, command and flag, where it used to hold bare flag names.** Three commands carry a `--clear` and only `chown`'s names a ticket, so the command is half of the fact. It also took the last hand-written ticket rule out of the fish block: every one of them is generated from the table now, and `every_ticket_flag_is_a_real_option` walks each pair against the command it names
- **It is derived on every call and held nowhere.** `Board::completion` is asked once by the draw and once by `tab`, so what is on the row and what the key takes cannot disagree, and there is no list to go stale when the line is edited or the board reloads under it. That is also what "any other key drops it" means: nothing is dropped, because nothing was kept
- **Only with the cursor at the end of the line.** The suggestion is drawn after the cursor and `tab` inserts it there, so with a command continuing past the cursor both would land in the middle of something already typed. A shell's own suggestion keeps the same rule
- **Only while a candidate still starts with what is typed**, and what is drawn is the rest of it rather than the whole. An offer that no longer matches the argument under it describes nothing, and once the whole of it is typed there is nothing left to add
- **Nothing with no card under the selection.** On the frame the selection is on a campaign or a tag, and neither is a ticket: `y` copies what the frame names there, and this deliberately does not
- **Everything else worklane can name is completed the same way**, which is what makes it one mechanism rather than a ticket suggestion with four more bolted on. `Argument` says what a position takes — a ticket, a campaign, a tag, or a fixed list — and `Board::candidates` says what the board currently holds of it. The verbs and the enum values are clap's own, so a command, a status, a shell or a clearable field added anywhere is typeable here the day it is added, and the campaigns and the tags are the tab's own rows, rebuilt at every reload beside the columns and drawn by the `c` and `t` pickers. **Nothing here reads the tree**: a keypress that went to disk would be a second source for what is already in memory
- **A campaign is offered by codename, and by its short id where it has none.** The codename is what the board draws on every card in the campaign and the shortest thing that addresses it; a campaign without one is labelled by its short id in both renderers, and leaving it out would hide it from the only place a reader can reach it by typing
- **`tags set` is offered only the declared tags.** It changes what a declared tag means and refuses one the vocabulary file does not declare, so the carried-but-undeclared ones are exactly the values it rejects. That is 193f9be in the fish half, which reads one listing for both, and the prompt does not inherit it. `tags add` gets nothing for the mirror reason, and neither `--tags` that takes the whole list does, since one tag offered into `bug,tui` is not what the field asked for
- **The clap definition is rebuilt on every call**, at 32µs in release against a board that redraws four times a second. A definition cached beside the board would be a second copy of what `Cli::command()` already answers; the fish half spends 2.5ms per keypress running worklane itself for the same values
- **What is drawn is the longest opening every candidate agrees on, which is exactly what the next `tab` takes.** One rule for one candidate and for many: a ticket position has only the selected card, so the rest of its id is drawn; the five statuses agree on nothing, so nothing is drawn and `tab` steps through them instead. The row never shows something a press would not do
- **`tab` again steps through the candidates in place, and wraps.** A shell does the same and it needs no list drawn over the columns, which is the trade — the board behind the prompt is what the reader is reading. Wrapping loses nothing typed, unlike the recall's walk, because every candidate still starts with the stem the walk was built from, which is why there is no `pending` here
- **Each press rebuilds the row from the line as it stood before the first**, so the candidates are read fresh every press and the only thing `Completing` holds is that line and how many presses have landed. Holding the list would be a copy going stale between two presses; holding the candidate the last press chose would narrow the list to it, and the walk would step once and stand still
- **Every edit ends the walk**, beside `refused` and for the same reason: the walk is about one argument and a line that has changed is a different argument. What the last press put on the row stays there, which is what makes `tab` then a letter the ordinary way to take a candidate
- **Nothing is drawn while a walk is on the row.** What is there is a whole candidate already, and a second offer drawn against it would read as part of the same word
- **Grey, which is what the palette already spends on a value that is not one.** It is not in the line until `tab` puts it there, and the reader has to tell the two apart at a glance. It takes what the line leaves of the field rather than a field of its own, so a long command loses the offer instead of pushing `esc` and `enter` off the row. The terminal cursor sits on its first cell, which is where the cursor already was
- **The row does not name `tab`.** The prompt names its two mode keys and no more — `ctrl-w`, the arrows and home and end are unnamed there as well — and the suggestion under the cursor is its own affordance
## Splitting a Typed Line
- **`split_line` is the whole module, and it knows nothing about `Board`.** The command prompt reads one string and clap reads an argv, so `comment 1b78a24 the offset was never passed` has to be tokenised before anything can parse it: split on whitespace it is five arguments and `comment` takes two. A pure function over the line and the cursor is what makes every rule reachable from a unit test, and it is in a file of its own rather than in `tui.rs`, which is eleven thousand lines already
- **The rules are the shell's, because that is what the prompt promises**: the line is spelled there exactly as it is spelled in the shell. Runs of whitespace separate arguments, single and double quotes group one, a backslash escapes the next character *except* inside single quotes where it is a backslash, and an explicitly empty `''` is an argument that exists and is empty — which is what `--title ""` being a usage error rather than a silent clear depends on. A leading hyphen is not special here: whether `--foo` is a flag or the text of a criterion is clap's question, and `PROSE` already answers it
- **Written rather than pulled in, for the two answers a shell's own splitter does not owe anybody.** A line being typed is half finished, so an unterminated quote is a state to report and not an error to raise: `Unclosed` says which quote is open, or that the line ends on a backslash with nothing yet to escape, and the arguments up to that point are handed back anyway, because that is what a hint or a completion has to work from. And completion needs the cursor: which argument it is in counting from the verb, and whether nothing of that argument lies before it, which is the difference between completing an argument and starting one. Both fall out of the one scan and neither is reachable afterwards from the arguments alone
- **`Some("")` is an argument that has been opened and is still empty**, which is the only thing that tells `''` from nothing typed at all. The cursor's answer is taken *before* the last argument is pushed, so a cursor at the end of the line is in the argument being typed rather than one past it
- The cursor is a byte offset, because that is what the prompt's own cursor is: a `String` inserts and removes at byte indices. Past the end reads as the end and inside a multi-byte character reads as after it, so nothing panics and no caller has to clamp first
- `Unclosed::Escape` wins over an open quote, being the inner of the two, and either answer refuses the line
- The binary's own name is not among the arguments: prepending it before `Cli::try_parse_from` is the caller's, since only the caller knows what it is calling
## The Copy Key
- **`y` copies the selected card's short id, over OSC 52 written by hand.** The board is where a ticket is found and the CLI is where it is acted on, and the only thing joining them was seven characters retyped off the screen. `y` reads as yank to the readers a keyboard board is for, and was the letter left: `q`, `esc`, `enter`, `space`, `hjkl`, the arrows, `pgup`, `pgdn`, `tab`, `backtab`, `d` and `/` were taken
- **The mechanism was chosen against ssh**, which is where a board is often read. An escape sequence is the only one of the three ways that crosses the connection, since it is the terminal at the reader's end that owns the clipboard. A crate (`arboard` and its kind) wants X11 and Wayland libraries at build time, and on X11 the selection belongs to the process that set it: copy an id, quit, and the paste buffer is empty, which is precisely this flow. Shelling out to `wl-copy`, `xclip` or `pbcopy` is platform sniffing plus a process spawn, and does nothing on a machine where none of them is installed or on the far end of a connection. crossterm 0.28 is what ratatui 0.29 pins and it ships no clipboard command, and the backend types have to match whatever ratatui pins, so a newer crossterm cannot be picked up on its own
- **The cost is paid knowingly: a terminal that ignores OSC 52 ignores it silently**, and tmux needs `set-clipboard on`. What `clipboard::copy` reports is whether the sequence was written, not whether it was honoured, and the footer message says no more than that. There is no reply to read: the query form of OSC 52 is refused by most emulators as a security matter, so nothing better is available to us
- Base64 is twenty lines here rather than a dependency, because the only thing that goes through it is a seven-character id. Pinned on the RFC 4648 vectors, which cover both padding forms, since a wrong encoder would put plausible-looking rubbish on the clipboard
- **`c` and not `p`**: the clipboard proper, not the X11 primary selection, since this is pasted into a command line. Terminated with BEL, which is what tmux documents and what every emulator that implements this at all accepts
- **What is copied is `ticket.id`, the seven characters the card prints**, not the full uuid: they are what stops the retyping and what `show`, `mv` and `comment` all resolve. Decided by `Board::copy_text` rather than inside the arm that copies, so the string is a question the suite can ask without a clipboard. `None` on an empty column, since an empty string would take away whatever the reader had there and give nothing back
- The project is left off even on the merge tab, where the id alone is not an address. This goes onto a clipboard to be pasted into a command line, and a second word in it would have to be deleted every time; running the command in the wrong project fails to resolve rather than acting on the wrong ticket
- **The clipboard is handed to `Board::copy_selected_id` as an argument**, `clipboard::copy` from the dispatch and a closure from a test. That is what makes both answers drivable, and it keeps the terminal write out of the board state
- **A failure is said in the footer, not returned.** There is nobody above it to handle one: the board goes on being drawn, and an error swallowed there would look exactly like a copy that worked until the paste came out wrong
- **`Notice` is the board's one channel for saying something in words**, since a copy leaves nothing on screen to look at. `failed` means "nothing reached the clipboard" rather than "an error occurred", so an empty column and a refused write are one answer to the reader, both in brightred for the reason `no match` is
- **It takes the whole footer row**, on a weaker reason than the prompt's: every key still works while a notice is up. It is that a message squeezed in beside the key list would move every key in it, and the row is the only part of the board that is not a ticket. Drawn after the prompt, which is an input and cannot be covered
- **The notice is cleared by the next keypress, not by a timer.** No clock on the board and no wakeup in the loop, and the moment the reader does anything else the message has been read or was never going to be. Doing nothing leaves it up, which is the one state where it is still worth reading. `Board::clear_notice` runs ahead of `search_key` as well as the arms, since a key typed into a query is still a key, and it must never move into `tick`: the board redraws four times a second and a notice cleared there would never be read
+2 -1
View File
@@ -1,7 +1,8 @@
# rustfmt is the formatter for this tree, and these four widths are what make it agree
# with how the tree is already written. Measured, not chosen: the default config wanted
# 305 hunks and +1418 lines of layout, `use_small_heuristics = "Max"` wanted 308 the
# other way, and this lands at 161. The reasoning is in AGENTS.md beside the clippy rule.
# other way, and this lands at 161. The reasoning is in
# docs/testing.md beside the clippy rule.
#
# Sweeping any one of these in either direction makes the diff bigger. Measure before
# changing one: `cargo fmt --check | grep -c '^Diff in'`.
+615
View File
@@ -0,0 +1,615 @@
//! Shared boards: the `.worklane.toml` pointer, the machine config, the boards
//! directory and the symlink that makes a shared board transparent.
//!
//! A board exists on exactly one machine: `.worklane` is gitignored and not itself a
//! git repo, so a project cloned elsewhere has no board. The shared layout answers that
//! with a boards repo cloned once per machine, holding one directory per board named
//! `<uuid>_<slug>` after the ticket filename convention. The project carries a
//! committed `.worklane.toml` naming its board by uuid, and `.worklane` in the project
//! becomes a *symlink* into the boards directory. A symlink rather than resolving the
//! pointer inside the CLI, because with no `.worklane` directory `cat
//! .worklane/backlog/*.md` and `ls .worklane/reviewing` would stop working, and that is
//! the belief the whole file format exists to serve. The symlink keeps every other tool
//! working and `find_worklane_dir` needs no resolution code, because it already follows
//! a link.
//!
//! The pointer names the board, not the server: the boards repo url lives in the
//! machine config, so a client repo never carries an internal hostname for anyone with
//! access to it to read.
use anyhow::{Result, anyhow};
use std::fs;
use std::path::{Path, PathBuf};
use crate::util::slug;
/// The one file that decides whether this project's board is shared or local.
const POINTER_FILE: &str = ".worklane.toml";
/// Where the machine-level config lives, under `$XDG_CONFIG_HOME`, or `~/.config`
/// without it, the same resolution `install::tools_root` follows.
fn config_path() -> PathBuf {
xdg_config().join("worklane/config.toml")
}
/// The boards directory, under `$XDG_DATA_HOME`, or `~/.local/share` without it.
///
/// The ticket's spelling is `~/.local/share/worklane/boards`.
fn default_boards_dir() -> PathBuf {
xdg_data().join("worklane/boards")
}
/// `$XDG_CONFIG_HOME` or `~/.config`, the convention `install::tools_root` already
/// follows. An empty value counts as unset, like `NO_COLOR` in `colors_wanted`.
fn xdg_config() -> PathBuf {
match std::env::var_os("XDG_CONFIG_HOME") {
Some(value) if !value.is_empty() => PathBuf::from(value),
_ => home().join(".config"),
}
}
/// `$XDG_DATA_HOME` or `~/.local/share`.
fn xdg_data() -> PathBuf {
match std::env::var_os("XDG_DATA_HOME") {
Some(value) if !value.is_empty() => PathBuf::from(value),
_ => home().join(".local/share"),
}
}
fn home() -> PathBuf {
std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default()
}
/// The machine's boards configuration, `None` when neither the file nor a `[boards]`
/// section exists.
///
/// Holding the boards repo url and the board directory path. The directory defaults
/// under `$XDG_DATA_HOME` but is overridable here.
pub fn read_config() -> Result<Option<MachineConfig>> {
let path = config_path();
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(anyhow!("Could not read the machine config {}: {error}", path.display()));
}
};
let parsed: ConfigFile = toml::from_str(&text).map_err(|error| {
anyhow!("Could not parse the machine config {}: {error}", path.display())
})?;
Ok(parsed.boards.option())
}
/// The effective boards directory, config override or default.
pub fn boards_dir() -> Result<PathBuf> {
Ok(read_config()?
.and_then(|config| config.boards_dir)
.unwrap_or_else(default_boards_dir))
}
#[derive(Default)]
pub struct MachineConfig {
/// The boards repo url. Read and held so the config carries it (the pointer names
/// the board, the machine names the server), and not yet read anywhere further:
/// the fetch that would use it is deferred.
#[allow(dead_code)]
pub url: Option<String>,
pub boards_dir: Option<PathBuf>,
}
#[derive(serde::Deserialize, Default)]
struct ConfigFile {
#[serde(default)]
boards: BoardsSection,
}
#[derive(serde::Deserialize, Default)]
struct BoardsSection {
#[serde(default)]
url: Option<String>,
#[serde(default)]
dir: Option<PathBuf>,
}
impl BoardsSection {
/// `None` when the section is absent or entirely empty, which is what makes "this
/// machine uses shared boards" a property of the config rather than of an empty
/// file.
fn option(self) -> Option<MachineConfig> {
let BoardsSection { url, dir } = self;
if url.is_none() && dir.is_none() {
None
} else {
Some(MachineConfig { url, boards_dir: dir })
}
}
}
/// The committed pointer in a project: `.worklane.toml`, naming the board by uuid.
pub struct Pointer {
pub board: String,
}
/// Where the pointer lives, at the project root beside `.worklane`.
pub fn pointer_path(project: &Path) -> PathBuf {
project.join(POINTER_FILE)
}
/// The pointer a project carries, `None` when there is none or it names nothing.
pub fn read_pointer(project: &Path) -> Result<Option<Pointer>> {
let path = pointer_path(project);
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(anyhow!("Could not read the board pointer {}: {error}", path.display()));
}
};
let parsed: PointerFile = toml::from_str(&text).map_err(|error| {
anyhow!("Could not parse the board pointer {}: {error}", path.display())
})?;
Ok(parsed
.worklane
.board
.filter(|board| !board.trim().is_empty())
.map(|board| Pointer { board }))
}
#[derive(serde::Deserialize, Default)]
struct PointerFile {
#[serde(default)]
worklane: PointerSection,
}
#[derive(serde::Deserialize, Default)]
struct PointerSection {
#[serde(default)]
board: Option<String>,
}
/// Write `.worklane.toml` naming `uuid`, creating or replacing the pointer.
///
/// A pointer that already names the same board is left alone: it is a committed file,
/// and rewriting what is already committed writes nothing new.
pub fn write_pointer(project: &Path, uuid: &str) -> Result<PathBuf> {
let path = pointer_path(project);
let text = format!("[worklane]\nboard = \"{uuid}\"\n");
match fs::read_to_string(&path) {
Ok(existing) if existing == text => return Ok(path),
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(anyhow!("Could not read the board pointer {}: {error}", path.display()));
}
}
fs::write(&path, text).map_err(|error| {
anyhow!("Could not write the board pointer {}: {}", path.display(), error)
})?;
Ok(path)
}
/// A board directory's name for a fresh board, `<uuid>_<slug>` after the ticket
/// filename convention.
pub fn board_dir_name(uuid: &str, title: &str) -> String {
format!("{uuid}_{}", slug(title))
}
/// An existing board directory's uuid, the segment before the first underscore.
fn dir_uuid(name: &str) -> &str {
name.split('_').next().unwrap_or(name)
}
/// The board directory in `boards` that `search` names, by uuid prefix, `None` when
/// nothing matches.
///
/// A uuid prefix rather than the full pointer value, so renaming a board's slug breaks
/// no committed pointer, the bargain the ticket filenames already make. Matches only
/// the uuid, never the slug: a directory named `_my-board` carries no uuid to match.
pub fn resolve_board(boards: &Path, search: &str) -> Result<Option<PathBuf>> {
let search = search.to_lowercase();
let matches = match fs::read_dir(boards) {
Ok(entries) => entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.file_type().is_ok_and(|t| t.is_dir()))
.map(|entry| entry.path())
.filter(|path| {
path.file_name()
.and_then(|name| name.to_str())
.map(|name| dir_uuid(name).to_lowercase().starts_with(&search))
.unwrap_or(false)
})
.collect::<Vec<_>>(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => {
return Err(anyhow!(
"Could not read the boards directory {}: {error}",
boards.display()
));
}
};
match matches.len() {
0 => Ok(None),
1 => Ok(Some(matches.into_iter().next().unwrap())),
_ => Err(anyhow!(
"'{search}' is ambiguous across {} boards in {}",
matches.len(),
boards.display()
)),
}
}
/// What `init` decided, for the handler to say.
pub enum Init {
/// `.worklane` was already a board for this project, so nothing was written.
AlreadyInitialized(PathBuf),
/// A local `.worklane`, the layout every project had before the shared one.
CreatedLocal(PathBuf),
/// A shared board: pointer written, board directory made, `.worklane` symlinked to
/// it.
CreatedShared {
pointer: PathBuf,
board: PathBuf,
link: PathBuf,
},
/// A deliberate refusal with a reason: the caller looked and decided not to change
/// what a pointer or an existing `.worklane` commits to.
Refused(String),
}
/// The decision table for `init`, one match so no branch can fall through into
/// creating a board.
///
/// `dir` is the canonical project root. `create` is `--create`, the only way to make a
/// board under a pointer that names a missing one.
pub fn decide_init(dir: &Path, create: bool) -> Result<Init> {
let worklane_dir = dir.join(".worklane");
let pointer = read_pointer(dir)?;
match pointer {
// No pointer: this project has never been put on the shared layout.
None => init_no_pointer(dir, &worklane_dir),
Some(pointer) => init_with_pointer(dir, &worklane_dir, &pointer, create),
}
}
fn init_no_pointer(dir: &Path, worklane_dir: &Path) -> Result<Init> {
match classify_worklane(worklane_dir) {
Worklane::Absent => {}
// An existing board of the local layout, or a shared one reached through a link
// whose pointer is missing; either way it is a board already.
Worklane::RealDir => return Ok(Init::AlreadyInitialized(worklane_dir.to_path_buf())),
Worklane::Symlink(_) | Worklane::Dangling(_) => {
return Ok(Init::AlreadyInitialized(worklane_dir.to_path_buf()));
}
Worklane::NotADirectory => {
return Ok(Init::Refused(format!(
"{} is not a directory; refusing to replace what is there.",
worklane_dir.display()
)));
}
}
// The machine config decides the layout. A `[boards]` section means a shared board
// here; none means the local layout, exactly as worklane always created it.
if read_config()?.is_some() {
let boards = boards_dir()?;
let uuid = uuid::Uuid::new_v4().to_string();
let board = boards.join(board_dir_name(&uuid, &project_title(dir)));
fs::create_dir_all(&board).map_err(|error| {
anyhow!("Could not create the board directory {}: {error}", board.display())
})?;
create_board_contents(&board)?;
let link = symlink_board(&board, worklane_dir)?;
let pointer = write_pointer(dir, &uuid)?;
return Ok(Init::CreatedShared { pointer, board, link });
}
Ok(Init::CreatedLocal(create_local(worklane_dir)?))
}
fn init_with_pointer(
dir: &Path,
worklane_dir: &Path,
pointer: &Pointer,
create: bool,
) -> Result<Init> {
let boards = boards_dir()?;
// The boards repo itself must be here: a committed pointer is proof the board
// exists somewhere, and a missing repo is an unsynced machine, not a missing board.
if !boards.is_dir() {
return Ok(Init::Refused(format!(
"The boards directory {} does not exist.\n\
This project names board {} in {},\n\
so its board lives in a boards repo that is not cloned here.\n\
Clone the boards repo (or run `worklane init --create` to make a new one).",
boards.display(),
pointer.board,
pointer_path(dir).display(),
)));
}
let resolved = resolve_board(&boards, &pointer.board)?;
// An existing `.worklane` must not be repointed or walked over. This is where a
// project that predates the shared layout, or one that points at the wrong board,
// is caught.
match classify_worklane(worklane_dir) {
Worklane::Absent => {}
Worklane::RealDir => {
return Ok(Init::Refused(format!(
"{} is a real directory, not the shared board {} names.\n\
This may be a board from before the shared layout, which worklane can \
adopt later (see the migration); refusing to walk over it. Remove it \
first, then run `worklane init` to link the board {} names.",
worklane_dir.display(),
pointer_path(dir).display(),
pointer_path(dir).display(),
)));
}
Worklane::Symlink(target) => {
// A link to exactly the board the pointer names is the layout already in
// place; a link to anything else is not to be repointed.
let board_named = resolved
.as_deref()
.and_then(|board| same(&target, board).then_some(board));
return match board_named {
Some(_) => Ok(Init::AlreadyInitialized(worklane_dir.to_path_buf())),
None => Ok(Init::Refused(format!(
"{} already links to {}, and not to the board {} names.\n\
Refusing to repoint it: changing what a project is on without \
asking is how two machines come to disagree about where the work is.\n\
Remove {} and run `worklane init` again to link {}.",
worklane_dir.display(),
target.display(),
pointer_path(dir).display(),
worklane_dir.display(),
resolved
.map(|p| p.display().to_string())
.unwrap_or_else(|| pointer.board.clone()),
))),
};
}
Worklane::Dangling(target) => {
// A link that resolves nowhere: if it is spelled as the board the pointer
// names — the relative form this tool writes, or the absolute board path —
// the board is out of this machine and the missing-board answer is the
// right one; anything else is not to be replaced without asking. Compared
// lexically, since a dangling link cannot be canonicalized.
let points_at_board = resolved.as_deref().is_some_and(|board| {
let base = worklane_dir.parent().unwrap_or(Path::new(""));
target == relative_path(base, board) || target == board
});
if points_at_board {
return Ok(missing_board(pointer, &boards));
}
return Ok(Init::Refused(format!(
"{} is a link to {}, which does not exist; refusing to replace it \
without asking.",
worklane_dir.display(),
target.display(),
)));
}
Worklane::NotADirectory => {
return Ok(Init::Refused(format!(
"{} is not a directory; refusing to replace what is there.",
worklane_dir.display()
)));
}
}
match resolved {
Some(board) => {
let link = symlink_board(&board, worklane_dir)?;
Ok(Init::CreatedShared {
pointer: pointer_path(dir),
board,
link,
})
}
None => {
if create {
let board = boards.join(board_dir_name(&pointer.board, &project_title(dir)));
fs::create_dir_all(&board).map_err(|error| {
anyhow!("Could not create the board directory {}: {error}", board.display())
})?;
create_board_contents(&board)?;
let link = symlink_board(&board, worklane_dir)?;
Ok(Init::CreatedShared {
pointer: pointer_path(dir),
board,
link,
})
} else {
Ok(missing_board(pointer, &boards))
}
}
}
}
/// The missing-board refusal, shared by the dangling-symlink-to-the-board and the
/// nothing-linking cases, so the board's being out of this machine is told once.
fn missing_board(pointer: &Pointer, boards: &Path) -> Init {
Init::Refused(format!(
"The boards directory {} holds no board for {}.\n\
The boards repo may need pulling; run a fetch there and try again.\n\
To deliberately start a new board under this pointer, run `worklane init --create`.",
boards.display(),
pointer.board,
))
}
/// The slug a newly created board takes: the project directory's name, so a board is
/// named after the project it lives in. Sharing a name keeps a reader looking at the
/// boards directory able to tell which project a board belongs to.
fn project_title(dir: &Path) -> String {
dir.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_default()
}
/// Classify an existing `.worklane` entry, distinguishing a real directory from a link
/// that resolves and a link that dangles, so each is answered differently.
enum Worklane {
/// Nothing at that path.
Absent,
/// A directory, not a link: a local board, or one that predates the shared layout.
RealDir,
/// A link that resolves to a directory, carrying the resolved target.
Symlink(PathBuf),
/// A link that resolves to nothing, carrying the target it names.
Dangling(PathBuf),
/// There, and neither a directory nor a link to one.
NotADirectory,
}
/// The four-way answer `init` needs from a `.worklane` path.
fn classify_worklane(path: &Path) -> Worklane {
let entry = match fs::symlink_metadata(path) {
Ok(entry) => entry,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Worklane::Absent,
Err(_) => return Worklane::NotADirectory,
};
if !entry.is_symlink() {
return match entry.is_dir() {
true => Worklane::RealDir,
false => Worklane::NotADirectory,
};
}
let target = fs::read_link(path).unwrap_or_else(|_| path.to_path_buf());
match fs::metadata(path) {
Ok(resolved) if resolved.is_dir() => {
Worklane::Symlink(fs::canonicalize(path).unwrap_or(path.to_path_buf()))
}
Ok(_) => Worklane::NotADirectory,
Err(_) => Worklane::Dangling(target),
}
}
/// Whether two paths are the same directory, through canonicalization and following
/// links.
fn same(a: &Path, b: &Path) -> bool {
match (fs::canonicalize(a), fs::canonicalize(b)) {
(Ok(a), Ok(b)) => a == b,
_ => false,
}
}
/// Symlink `worklane_dir` to `board`, the one way `.worklane` becomes a board reached
/// through a link.
///
/// The target is made relative to the link's own parent so the link is portable (it
/// uses no home directory path), and the link's parent directory is created since the
/// project may not exist as a directory yet.
fn symlink_board(board: &Path, worklane_dir: &Path) -> Result<PathBuf> {
if let Some(parent) = worklane_dir.parent() {
fs::create_dir_all(parent)
.map_err(|error| anyhow!("Could not create {}: {error}", parent.display()))?;
}
let target = relative_path(worklane_dir.parent().unwrap_or(Path::new("")), board);
make_symlink(&target, worklane_dir)?;
Ok(worklane_dir.to_path_buf())
}
/// A relative path from `base` (a directory) to `target`.
fn relative_path(base: &Path, target: &Path) -> PathBuf {
let base = base.to_path_buf();
let target = target.to_path_buf();
// The common prefix gives how far up `base` the link must climb. When they share a
// root device but no component they have no common ancestor expressible in a
// relative path, and the absolute target is the honest answer.
let common = base
.components()
.zip(target.components())
.take_while(|(a, b)| a == b)
.count();
let mut result = PathBuf::new();
for _ in common..base.components().count() {
result.push("..");
}
for component in target.components().skip(common) {
result.push(component);
}
result
}
/// Create a symlink at `link` to `target`, refusing to replace a different file or link.
fn make_symlink(target: &Path, link: &Path) -> Result<()> {
match fs::symlink_metadata(link) {
// Nothing there: place it.
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
return Err(anyhow!("Could not inspect {} before linking: {error}", link.display()));
}
Ok(_) => {
return Err(anyhow!(
"{} already exists; refusing to replace what is there",
link.display()
));
}
}
#[cfg(unix)]
std::os::unix::fs::symlink(target, link).map_err(|error| {
anyhow!("Could not symlink {} to {}: {error}", link.display(), target.display())
})?;
#[cfg(not(unix))]
{
let _ = (target, link);
return Err(anyhow!(
"shared boards need symlinks, which this platform does not support"
));
}
Ok(())
}
/// The local board layout, as `init` always created it: the status directories, the
/// campaigns directory and the tag vocabulary.
///
/// Shared boards call the same helper on their directory. Returns the worklane
/// directory for the message.
fn create_local(worklane_dir: &Path) -> Result<PathBuf> {
fs::create_dir_all(worklane_dir)
.map_err(|error| anyhow!("Could not create {}: {error}", worklane_dir.display()))?;
create_board_contents(worklane_dir)?;
Ok(worklane_dir.to_path_buf())
}
/// The contents every board gets, whatever layout holds it.
fn create_board_contents(worklane_dir: &Path) -> Result<()> {
for folder in crate::util::status_dirs() {
fs::create_dir_all(worklane_dir.join(folder)).map_err(|error| {
anyhow!("Could not create {}: {error}", worklane_dir.join(folder).display())
})?;
}
fs::create_dir_all(crate::campaign::campaigns_dir(worklane_dir)).map_err(|error| {
anyhow!(
"Could not create {}: {error}",
crate::campaign::campaigns_dir(worklane_dir).display()
)
})?;
fs::write(
crate::tag::tags_path(worklane_dir),
crate::tag::TagIndex::default().render(),
)
.map_err(|error| {
anyhow!(
"Could not write {}: {error}",
crate::tag::tags_path(worklane_dir).display()
)
})?;
Ok(())
}
+55 -1
View File
@@ -238,6 +238,13 @@ pub fn members(worklane_dir: &Path, uuid: &str) -> Result<Vec<(&'static str, Vec
Ok(grouped)
}
/// A campaign with work outstanding, beside [`DONE`] for one with none left.
///
/// Not a [`Status`]: no ticket is ever in it and no directory is named for it. It is the
/// campaign's own two-word vocabulary, and it is a const because the listing prints it,
/// [`Standing::state`] derives it and [`CampaignState`] filters on it.
pub const OPEN: &str = "open";
/// How far a campaign has got: members done against members held.
///
/// `Copy` because the board carries one on every `CampaignRow`, settled at reload: two
@@ -282,7 +289,54 @@ impl Standing {
match (self.total, self.done == self.total) {
(0, _) => None,
(_, true) => Some(DONE),
(_, false) => Some("open"),
(_, false) => Some(OPEN),
}
}
}
/// The state a campaign is in, as `campaign ls --state` accepts it.
///
/// A `ValueEnum` for the reason [`Status`] is one: an unknown value is clap's to refuse
/// at parse time with the three listed, no handler has to check, and every shell that
/// completes possible values gets them for free.
///
/// `--state` and not `--status`, which names one of the five ticket statuses everywhere
/// else in the tool. A campaign sits in no status directory, and borrowing the word for
/// a different vocabulary is how a reader comes to type `--status backlog` here.
///
/// `Empty` is the third value because [`Standing::state`] answers `None` for a campaign
/// nothing has been filed against, deliberately, and a filter that could not reach those
/// would leave the one question a grooming sweep asks — what has been filed and forgotten
/// — answerable only by reading the whole listing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum CampaignState {
/// Holds members, and at least one of them is not finished
Open,
/// Holds members, and every one of them is done or discarded
Done,
/// Holds no members at all, so it is neither open nor done
Empty,
}
impl CampaignState {
/// The value as it is typed, which is what a message naming the filter repeats back.
pub fn as_str(self) -> &'static str {
match self {
Self::Open => OPEN,
Self::Done => DONE,
Self::Empty => "empty",
}
}
/// Whether a campaign in this standing is the one the filter asked for.
///
/// Matched against [`Standing::state`] rather than against the counters, so the
/// derived value has one definition: a campaign reads `[open]` in the listing if and
/// only if `--state open` lists it.
pub fn holds(self, standing: &Standing) -> bool {
match self {
Self::Empty => standing.state().is_none(),
wanted => standing.state() == Some(wanted.as_str()),
}
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
//! Putting text on the clipboard of whatever terminal is drawing the board.
//!
//! OSC 52, written by hand, and the reasoning is in AGENTS.md under The Copy Key. The
//! OSC 52, written by hand, and the reasoning is in docs/tui-prompts.md under The Copy Key. The
//! short of it: the board is often being read over ssh, and an escape sequence is the
//! only one of the three ways that crosses the connection. crossterm 0.28 is what
//! ratatui 0.29 pins and it ships no clipboard command, so the sequence and the base64
+182 -35
View File
@@ -4,6 +4,7 @@ use std::sync::LazyLock;
use chrono::NaiveDate;
use crate::campaign::CampaignState;
use crate::util::{Clearable, PRIORITY_RANGE, RelationKind, Status, priority_legend};
/// clap wants a `&str` with a long enough lifetime, and the legend is built from
@@ -162,22 +163,35 @@ fn tag_value(raw: &str) -> Result<String, String> {
Ok(value.to_string())
}
/// Reject an annotation line that would be read back as a tag of its own.
/// Reject an annotation the vocabulary file or the listing cannot carry.
///
/// The vocabulary is one heading per tag with its prose under it, so a line of prose
/// starting with the section marker would split the annotation and declare whatever
/// followed. Refused at parse time, where nothing has been written, rather than escaped on
/// the way in: an annotation is prose, and quietly rewriting prose is worse than asking for
/// a different line.
/// followed. A tab anywhere in the value is refused for the listing's sake rather than the
/// file's: `tags ls` prints one tag, its count and the annotation's opening line as three
/// tab-separated fields, so an annotation holding a tab reads as the start of a fourth
/// field and everything after it is silently gone.
///
/// Both are refused at parse time, where nothing has been written, rather than escaped on
/// the way in: an annotation is prose, and quietly rewriting prose is worse than asking
/// for a different line.
fn annotation_line(raw: &str) -> Result<String, String> {
match raw.lines().any(|line| line.starts_with(crate::tag::SECTION)) {
true => Err(format!(
if raw.lines().any(|line| line.starts_with(crate::tag::SECTION)) {
return Err(format!(
"an annotation line cannot start with '{}', which is how the vocabulary file \
starts a tag",
crate::tag::SECTION
)),
false => Ok(raw.to_string()),
));
}
if raw.contains('\t') {
return Err(
"an annotation cannot contain a tab, which is how `tags ls` separates its fields"
.to_string(),
);
}
Ok(raw.to_string())
}
/// What `--actor` says on every command that writes a history entry.
@@ -186,12 +200,19 @@ fn annotation_line(raw: &str) -> Result<String, String> {
/// command reads as five flags.
const ACTOR_HELP: &str = "Who the entry is attributed to, overriding WORKLANE_ACTOR and the git user. Free text, checked against nothing";
/// What `--actor-from-git` says on every command that writes a history entry.
///
/// The counterpart to [`ACTOR_HELP`]: where that one names somebody specific, this one
/// says attribute it to the human whose checkout this is, without knowing how they spell
/// themselves.
const ACTOR_FROM_GIT_HELP: &str = "Attribute the entry to the detected git user instead of WORKLANE_ACTOR, for acting on the person's behalf. Cannot be combined with --actor";
/// Arguments that carry prose, and therefore have to accept a value starting with
/// a hyphen.
///
/// Ticket text quotes flag names constantly, and without this a criterion reading
/// "--print is supported" is parsed as a flag and the whole ticket is refused. The
/// trade, spelled out in AGENTS.md: on these arguments a genuinely mistyped flag
/// trade, spelled out in docs/cli-arguments.md: on these arguments a genuinely mistyped flag
/// now lands as content instead of raising a usage error. That is the right way
/// round for prose, and it is why `due`, `priority`, `tags`, `owner` and `status`
/// are deliberately left without it.
@@ -200,7 +221,11 @@ const PROSE: bool = true;
#[derive(clap::Subcommand)]
pub enum Command {
/// Initialize worklane in the current project
Init,
Init {
/// Create a board even where a committed pointer names one that is not here
#[arg(long)]
create: bool,
},
/// Add a new ticket to the backlog
Add(AddArgs),
@@ -216,26 +241,7 @@ pub enum Command {
},
/// Move a ticket to a different status
Mv {
/// Ticket UUID or title
ticket: String,
/// Target status
#[arg(short, long)]
status: Status,
/// Force move (allows backward or non-sequential moves)
#[arg(short, long)]
force: bool,
#[arg(long, help = ACTOR_HELP)]
actor: Option<String>,
/// Why the ticket moved, recorded in the history entry beside the transition
/// it explains. Prose, so it takes a leading hyphen
#[arg(long, allow_hyphen_values = PROSE)]
reason: Option<String>,
},
Mv(MvArgs),
/// Replace fields on an existing ticket
Set(SetArgs),
@@ -285,6 +291,9 @@ pub enum Command {
/// is `chown`'s. It was `--owner`, which said the wrong one of the two.
#[arg(long, help = ACTOR_HELP)]
actor: Option<String>,
#[arg(long, conflicts_with = "actor", help = ACTOR_FROM_GIT_HELP)]
actor_from_git: bool,
},
/// Group tickets that have to be finished together
@@ -310,6 +319,9 @@ pub enum Command {
#[arg(long, help = ACTOR_HELP)]
actor: Option<String>,
#[arg(long, conflicts_with = "actor", help = ACTOR_FROM_GIT_HELP)]
actor_from_git: bool,
},
/// The tag vocabulary: what the board carries, and what each tag means
@@ -419,6 +431,17 @@ pub enum CampaignCommand {
/// candidate list on a keypress
#[arg(long)]
ids: bool,
/// Only campaigns in this state: open, done, or empty for one nothing has been
/// filed against
///
/// A campaign's state is derived from its members, so this is a match against the
/// value the listing already computes and shows in brackets. `--state` rather than
/// `--status`, which names one of the five ticket statuses everywhere else; a
/// campaign sits in no status directory. It applies to `--ids` as well, where the
/// member counts it needs are read only because a filter was given
#[arg(long, value_name = "STATE")]
state: Option<CampaignState>,
},
/// Show a campaign and its members grouped by status
@@ -620,7 +643,7 @@ pub struct TagSetArgs {
}
/// `ls` holds four filters, an output mode and nothing else, which is the boundary the
/// Rust Style rule in AGENTS.md names: two of the filters are adjacent `Option<String>`
/// Rust Style rule in docs/rust-style.md names: two of the filters are adjacent `Option<String>`
/// values that a caller can swap silently, so the mode that joined them came as a
/// struct rather than a sixth parameter, the way `add` became [`AddArgs`].
#[derive(clap::Args)]
@@ -687,6 +710,33 @@ pub struct AddArgs {
pub priority: Option<u8>,
}
/// `mv` grew past a handful of parameters when `--actor-from-git` arrived, so it is a
/// struct like `set` and `append` rather than an inline variant.
#[derive(clap::Args)]
pub struct MvArgs {
/// Ticket UUID or title
pub ticket: String,
/// Target status
#[arg(short, long)]
pub status: Status,
/// Force move (allows backward or non-sequential moves)
#[arg(short, long)]
pub force: bool,
#[arg(long, help = ACTOR_HELP)]
pub actor: Option<String>,
#[arg(long, conflicts_with = "actor", help = ACTOR_FROM_GIT_HELP)]
pub actor_from_git: bool,
/// Why the ticket moved, recorded in the history entry beside the transition
/// it explains. Prose, so it takes a leading hyphen
#[arg(long, allow_hyphen_values = PROSE)]
pub reason: Option<String>,
}
/// `set` replaces a field outright. Owner is deliberately absent: `chown` owns that
/// field, and status is `mv`'s, so no field has two writers.
///
@@ -751,6 +801,9 @@ pub struct SetArgs {
/// command's that is logged
#[arg(long, help = ACTOR_HELP)]
pub actor: Option<String>,
#[arg(long, conflicts_with = "actor", help = ACTOR_FROM_GIT_HELP)]
pub actor_from_git: bool,
}
impl SetArgs {
@@ -801,6 +854,9 @@ pub struct ChownArgs {
/// change. Both are on this command because it writes both.
#[arg(long, help = ACTOR_HELP)]
pub actor: Option<String>,
#[arg(long, conflicts_with = "actor", help = ACTOR_FROM_GIT_HELP)]
pub actor_from_git: bool,
}
impl ChownArgs {
@@ -818,14 +874,15 @@ impl ChownArgs {
}
}
/// `append` only offers the sections that hold multiple lines, since appending to a
/// scalar has no meaning.
/// `append` offers the fields something can be added to without disturbing what is
/// already in them: the three sections that hold multiple lines, and Tags, which is a
/// list. Appending to a scalar has no meaning, so there is no `--priority` or `--due`.
#[derive(clap::Args)]
#[command(group(
clap::ArgGroup::new("append_fields")
.required(true)
.multiple(true)
.args(["description", "acceptance", "plan"])
.args(["description", "acceptance", "plan", "tags"])
))]
pub struct AppendArgs {
/// Ticket UUID or title
@@ -842,6 +899,24 @@ pub struct AppendArgs {
/// Add implementation plan steps, numbered on from the last. Repeat the flag
#[arg(short, long, allow_hyphen_values = PROSE)]
pub plan: Vec<String>,
/// Add tags, keeping the ones the ticket already carries. Repeat the flag, or
/// separate them with commas
///
/// `non_empty` rather than the `clearable` that `set --tags` takes. That message
/// names `--clear`, and this command has none: emptying the field is
/// `set --clear tags`, so pointing at a flag that is not here would send the caller
/// looking for it on `append`.
#[arg(short = 'g', long, value_parser = non_empty)]
pub tags: Vec<String>,
/// Only reaches the entry `--tags` writes, since that is the one field of this
/// command's that is logged, exactly as on `set`
#[arg(long, help = ACTOR_HELP)]
pub actor: Option<String>,
#[arg(long, conflicts_with = "actor", help = ACTOR_FROM_GIT_HELP)]
pub actor_from_git: bool,
}
/// `relate` is the only writer of the Relations section, the way `chown` is the only
@@ -852,12 +927,17 @@ pub struct AppendArgs {
/// Each flag repeats, so several relations of one kind land in a single call. The
/// targets are ticket searches, resolved by the same three tiers every other ticket
/// argument is, and stored as the target's uuid.
///
/// `--clear` is the other direction, and it is here rather than on `set` for the reason
/// Relations is absent from `section_args`: a relation names a target that has to be
/// resolved first, so its one writer owns both adding and removing, the way `chown` owns
/// both setting an owner and clearing one.
#[derive(clap::Args)]
#[command(group(
clap::ArgGroup::new("relation_kinds")
.required(true)
.multiple(true)
.args(["blocked_by", "regression_of", "relates_to"])
.args(["blocked_by", "regression_of", "relates_to", "clear"])
))]
pub struct RelateArgs {
/// Ticket UUID or title
@@ -874,6 +954,18 @@ pub struct RelateArgs {
/// Ticket this one is merely related to. Symmetric, so it is recorded once
#[arg(long, value_parser = non_empty)]
pub relates_to: Vec<String>,
/// Take a relation off: the kind, then the ticket it points at. Repeat the flag
///
/// Two values rather than one, because a ticket can hold several relations of one
/// kind and emptying every `blocked by` on it is not usually what is wanted. That is
/// also why this is not `set --clear`, which names a field and empties the whole of
/// it: the "value" here is one edge among several, so the target has to be named too.
///
/// A `Vec<String>` because clap cannot type the two values of one flag apart.
/// [`RelateArgs::cleared`] is where the pairs are split and the kind is parsed.
#[arg(long, num_args = 2, value_names = ["KIND", "TARGET"], value_parser = non_empty)]
pub clear: Vec<String>,
}
impl RelateArgs {
@@ -886,6 +978,18 @@ impl RelateArgs {
(RelationKind::RelatesTo, &self.relates_to),
]
}
/// The relations asked to be taken off, as a kind and the search naming the target.
///
/// `num_args = 2` is per occurrence, so clap has already refused an odd number of
/// values and every chunk is a full pair. A kind that is not one of the three is
/// refused here, before the ticket is resolved and long before anything is written.
pub fn cleared(&self) -> anyhow::Result<Vec<(RelationKind, &str)>> {
self.clear
.chunks(2)
.map(|pair| Ok((RelationKind::parse_value(&pair[0])?, pair[1].as_str())))
.collect()
}
}
/// `check` and `uncheck` are separate commands rather than one verb with a flag,
@@ -973,4 +1077,47 @@ mod tests {
for two minor versions."
);
}
/// `--actor` and `--actor-from-git` are one pair that has to travel together: every
/// command that takes one takes the other, documented by the same string, because
/// the second is the first's spelling for "the human whose checkout this is".
///
/// A walker rather than five named commands, so a sixth entry-writing command fails
/// this on its own `--actor` instead of being forgotten here too.
#[test]
fn every_actor_command_takes_actor_from_git() {
let cli = Cli::command();
let mut seen = 0;
for sub in cli.get_subcommands() {
if sub.get_name() == "help" {
continue;
}
if !sub.get_arguments().any(|arg| arg.get_id().as_str() == "actor") {
continue;
}
seen += 1;
let from_git = sub
.get_arguments()
.find(|arg| arg.get_id().as_str() == "actor_from_git")
.unwrap_or_else(|| {
panic!("`{}` takes --actor but not --actor-from-git", sub.get_name())
});
assert_eq!(
from_git.get_help().map(|help| help.to_string()),
Some(ACTOR_FROM_GIT_HELP.to_string()),
"`{}` documents --actor-from-git differently",
sub.get_name()
);
}
// A guard on the walker itself: if it stopped finding commands, every assertion
// above would pass by never running.
assert_eq!(
seen, 6,
"expected comment, mv, chown, set, append and assign to carry --actor"
);
}
}
+664 -64
View File
@@ -11,10 +11,10 @@
//! costs one `worklane ls --ids` per keypress, which measured at 2.5ms in release on a
//! board of seventy-five tickets, comfortably below anything a person notices.
//!
//! The four statuses are half clap's: `Status` is a `ValueEnum`, so it emits them for
//! `mv --status`, but the fish generator does not emit possible values for a *positional*
//! and `ls <status>` gets nothing. Same for `completions <shell>`. So the block below
//! lists those two, from the enums rather than by hand.
//! Status values are half clap's: `Status` is a `ValueEnum`, so clap emits every one
//! of them for `mv --status`, but the fish generator does not emit possible values for
//! a *positional* and `ls <status>` gets nothing. Same for `completions <shell>`. So
//! the block below lists those two, from the enums rather than by hand.
use std::io;
@@ -22,7 +22,7 @@ use clap::{CommandFactory, ValueEnum};
use clap_complete::Shell;
use crate::install::SKILLS;
use crate::util::Status;
use crate::util::{RelationKind, Status};
/// Subcommands whose first positional is a ticket.
///
@@ -35,12 +35,23 @@ pub const TICKET_COMMANDS: [&str; 8] = [
/// Subcommands whose *second* positional is the ticket, because they name two things.
///
/// `chown alice <ticket>` and `assign "v1 release" <ticket>`, which put the ticket
/// second deliberately, see AGENTS.md. The first argument of each is a user or a
/// second deliberately, see docs/editing-tickets.md. The first argument of each is a user or a
/// campaign, and neither is completed.
pub const TICKET_SECOND_COMMANDS: [&str; 2] = ["chown", "assign"];
/// Options whose value is a ticket, as `relate` takes three of.
pub const TICKET_FLAGS: [&str; 3] = ["blocked-by", "regression-of", "relates-to"];
/// Options whose value is a ticket, as the command that takes it and the flag's long name.
///
/// Pairs rather than the flat list this was, for the reason [`TAG_FLAGS`] holds pairs: the
/// commands spell their flags differently and one of the spellings is shared. `relate`'s
/// three take a ticket, `chown --clear` takes one because there is no user to give it, and
/// `set --clear` takes a field name and `relate --clear` a relation kind — so a list of
/// bare flag names would offer tickets to those two as well.
pub const TICKET_FLAGS: [(&str, &str); 4] = [
("relate", "blocked-by"),
("relate", "regression-of"),
("relate", "relates-to"),
("chown", "clear"),
];
/// Subcommands whose first positional is a campaign.
///
@@ -64,12 +75,22 @@ pub const CAMPAIGN_NESTED_COMMANDS: [(&str, &str); 3] = [
/// Options whose value is a campaign.
pub const CAMPAIGN_FLAGS: [&str; 1] = ["campaign"];
/// Options whose value is a tag.
/// Options whose value is a tag, as the command that takes it and the flag's long name.
///
/// Its own list rather than a line in the block below, because the values come from a
/// different command: a tag is not an object with an id, so `worklane tags` answers this
/// one where `ls --ids` answers the tickets.
pub const TAG_FLAGS: [&str; 1] = ["tag"];
///
/// Pairs rather than the flat list the other flag lists are, because the two spellings
/// differ: `ls --tag` filters on one and `append --tags` adds them, so a single rule
/// naming both options would tell fish that each command takes the other's flag. One
/// rule per pair instead.
///
/// `add --tags` and `set --tags` are deliberately absent. Both take the *whole* list, so
/// the token being completed is `bug,tui` and fish replaces a token entire: offering one
/// tag there would throw away the ones already typed. `append --tags` is the one where
/// naming a single tag is the ordinary call.
pub const TAG_FLAGS: [(&str, &str); 2] = [("ls", "tag"), ("append", "tags")];
/// Nested commands whose first argument is a tag the board already has.
///
@@ -80,6 +101,198 @@ pub const TAG_FLAGS: [&str; 1] = ["tag"];
/// `no_tag_taking_option_is_missing` makes somebody decide.
pub const TAG_NESTED_COMMANDS: [(&str, &str); 1] = [("tags", "set")];
/// Options whose first value is a relation kind.
///
/// `relate --clear` alone, and it is a list rather than a line in [`argument_at`] for the
/// reason every other position is: what an argument names belongs beside the tables that
/// answer the same question about the rest of them. It cannot come off clap the way a
/// status does, which is why it is here at all — the flag takes a kind and then a target,
/// two values of different kinds under one name, so possible values on it would refuse
/// every target.
pub const RELATION_KIND_FLAGS: [(&str, &str); 1] = [("relate", "clear")];
/// The long name of the flag a typed word spells, or nothing where it is not a flag.
///
/// `--status` is its own name and `-s` is clap's to translate, off the command that holds
/// the flag: a table of the shorts kept here would be a second list of every option the
/// tool has, and it would go wrong the first time one was given a letter.
///
/// **One letter, never a cluster.** `mv -fs done` is force and status and it is `status`
/// that takes the word after it, so the last letter of a cluster would be the honest
/// answer — but `--title`, `--description`, `--acceptance`, `--plan` and a comment body all
/// take a leading hyphen on purpose, and reading `-fixes the offset` as a cluster would
/// offer statuses inside a criterion. A clustered short is rare on a board where the line
/// is typed a word at a time; a hyphen-leading prose value is a documented feature.
fn long_name(arg: &str, holder: Option<&clap::Command>) -> Option<String> {
if let Some(long) = arg.strip_prefix("--") {
return (!long.is_empty()).then(|| long.to_string());
}
let mut letters = arg.strip_prefix('-')?.chars();
let short = match (letters.next(), letters.next()) {
(Some(letter), None) => letter,
_ => return None,
};
holder?
.get_arguments()
.find(|option| option.get_short() == Some(short))
.and_then(|option| option.get_long())
.map(str::to_string)
}
/// What an argument of a typed line names, where worklane can answer what goes there.
///
/// The board's command prompt completes against this: the tables above say *what* the
/// position takes and the prompt says what the board currently holds of it. A ticket and a
/// campaign and a tag are all "a word off the board" to clap and three different questions
/// to the reader, which is why this is an enum rather than a candidate list — the values
/// live where the board is and the positions live here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Argument {
/// A ticket on the board. One candidate, the card the reader has selected.
Ticket,
/// A campaign, which is named by its codename and drawn by it on every card it holds.
Campaign,
/// A tag. `declared` is `tags set`'s: it changes what a declared tag means and refuses
/// one the vocabulary file does not declare, so offering a carried-but-undeclared tag
/// there would offer exactly the values the command rejects. That is 193f9be in the
/// fish half, and this is the prompt not inheriting it.
Tag { declared: bool },
/// Values the tool itself holds: the subcommand names at a verb position, the possible
/// values of an argument clap built from a `ValueEnum`, and the relation kinds.
///
/// Read off the clap definition rather than written out, so a command, a status or a
/// clearable field added anywhere is typeable on the board the day it is added.
Fixed(Vec<String>),
}
/// What the argument at `index` of a typed line names, `index` counting from the verb at 0,
/// or nothing where worklane has nothing to offer.
///
/// The tables above are what answer it, reached rather than restated: a second copy of the
/// positions on the board would go wrong the next time a command grew a ticket argument, and
/// it would go wrong silently, since the tests that keep these honest against clap would
/// not read the copy.
///
/// Position is counted rather than inferred, exactly as the fish half counts it, so
/// `mv --status done <ticket>` is not recognised: the ticket is `mv`'s first *positional*
/// and the third argument on the line. That is the fish rules' limit too, and one answer
/// for both is worth more than two that disagree about the corner.
///
/// The clap definition is rebuilt on every call, at 32µs in release, and the caller is a
/// board that redraws four times a second: a definition cached beside the board would be a
/// second copy of what `Cli::command()` already answers, for a cost nothing can measure.
/// The fish half spends 2.5ms per keypress running worklane itself for the same answers.
pub fn argument_at(args: &[String], index: usize) -> Option<Argument> {
let cli = crate::command::Cli::command();
// The verb itself, which is every subcommand the tool has. Hidden ones are left out:
// they are not in the help either, and a candidate nobody can read about is one a
// reader has to go and look up.
if index == 0 {
return Some(Argument::Fixed(subcommand_names(&cli)));
}
let verb = args.first().map(String::as_str)?;
let group = cli.find_subcommand(verb);
// The command a flag belongs to, which is the *nested* one where a group's child
// carries it: `--state` is `campaign ls`'s and clap holds it on `ls`, not on
// `campaign`. Falls back to the group itself, which is where every other flag is, and
// to nothing for a line whose second word names no subcommand — `mv 1b78a24 --status`
// reaches `mv`'s own arguments as it always did.
let holder = args
.get(1)
.and_then(|child| group.and_then(|group| group.find_subcommand(child)))
.or(group);
// A flag's value is the argument after it, which is where the flag sits whether the
// value is half typed or has not been started. Spelled long or short: `-s` is the same
// flag as `--status` and the row has to answer both, which is what `long_name` is for.
if let Some(flag) = args.get(index - 1).and_then(|arg| long_name(arg, holder)) {
let flag = flag.as_str();
if TICKET_FLAGS.contains(&(verb, flag)) {
return Some(Argument::Ticket);
}
if CAMPAIGN_FLAGS.contains(&flag) {
return Some(Argument::Campaign);
}
if TAG_FLAGS.contains(&(verb, flag)) {
return Some(Argument::Tag { declared: false });
}
if RELATION_KIND_FLAGS.contains(&(verb, flag)) {
let kinds = RelationKind::ALL.iter().map(|kind| kind.flag().to_string());
return Some(Argument::Fixed(kinds.collect()));
}
// And everything else the flag could take, which is whatever clap knows: `--status`
// and `set --clear` are both `ValueEnum`s, so their values are already written down
// once, in the enum.
let arg = holder?
.get_arguments()
.find(|arg| arg.get_long() == Some(flag))?;
return fixed(arg);
}
// The positionals, at the index each table records.
match index {
1 if TICKET_COMMANDS.contains(&verb) => return Some(Argument::Ticket),
1 if CAMPAIGN_COMMANDS.contains(&verb) => return Some(Argument::Campaign),
2 if TICKET_SECOND_COMMANDS.contains(&verb) => return Some(Argument::Ticket),
_ => {}
}
let group = group?;
// The verb of a group, `campaign show` and `tags set`, which is a subcommand name
// exactly as the top-level verb is.
if index == 1 && group.has_subcommands() {
return Some(Argument::Fixed(subcommand_names(group)));
}
// And the first argument of one, which is where a campaign and a declared tag are named.
if index == 2
&& let Some(child) = args.get(1).map(String::as_str)
{
if CAMPAIGN_NESTED_COMMANDS.contains(&(verb, child)) {
return Some(Argument::Campaign);
}
if TAG_NESTED_COMMANDS.contains(&(verb, child)) {
return Some(Argument::Tag { declared: true });
}
}
// And whatever else the positional itself knows, which is the `ls` status and the
// `completions` shell: both are `ValueEnum`s that the fish generator has to list by
// hand, because it emits possible values for an option and none for a positional.
fixed(group.get_positionals().nth(index - 1)?)
}
/// The names a command answers to, hidden ones left out.
fn subcommand_names(command: &clap::Command) -> Vec<String> {
command
.get_subcommands()
.filter(|sub| !sub.is_hide_set())
.map(|sub| sub.get_name().to_string())
.collect()
}
/// The possible values of one argument, or nothing for an argument that takes free text.
///
/// `get_positionals` and `get_long` both read what the derive wrote, so nothing here needs
/// the command built the way `get_index` would.
fn fixed(arg: &clap::Arg) -> Option<Argument> {
let values: Vec<String> = arg
.get_possible_values()
.iter()
.filter(|value| !value.is_hide_set())
.map(|value| value.get_name().to_string())
.collect();
(!values.is_empty()).then_some(Argument::Fixed(values))
}
pub fn generate(shell: Shell, out: &mut dyn io::Write) -> io::Result<()> {
let mut command = crate::command::Cli::command();
clap_complete::generate(shell, &mut command, "worklane", out);
@@ -97,15 +310,40 @@ pub fn generate(shell: Shell, out: &mut dyn io::Write) -> io::Result<()> {
fn fish_dynamic() -> String {
let ticket_commands = TICKET_COMMANDS.join(" ");
let ticket_second_commands = TICKET_SECOND_COMMANDS.join(" ");
let ticket_flags = flag_list(&TICKET_FLAGS);
let ticket_flags = TICKET_FLAGS
.iter()
.map(|(command, flag)| {
let option = fish_option(command, flag);
format!(
"complete -c worklane -n '__worklane_command_is {command}' {option} \\\n \
-x -a '(worklane ls --ids)'"
)
})
.collect::<Vec<_>>()
.join("\n");
let relation_kinds = RelationKind::ALL
.iter()
.map(|kind| kind.flag())
.collect::<Vec<_>>()
.join(" ");
let campaign_commands = CAMPAIGN_COMMANDS.join(" ");
let campaign_nested = CAMPAIGN_NESTED_COMMANDS
.iter()
.map(|(parent, child)| format!("__worklane_nested_arg_of {parent} {child}"))
.collect::<Vec<_>>()
.join("; or ");
let campaign_flags = flag_list(&CAMPAIGN_FLAGS);
let tag_flags = flag_list(&TAG_FLAGS);
let campaign_flags = flag_list("ls", &CAMPAIGN_FLAGS);
let tag_flags = TAG_FLAGS
.iter()
.map(|(command, flag)| {
let option = fish_option(command, flag);
format!(
"complete -c worklane -n '__worklane_command_is {command}' {option} \\\n \
-x -a '(worklane tags | cut -f1,3)'"
)
})
.collect::<Vec<_>>()
.join("\n");
let tag_nested = TAG_NESTED_COMMANDS
.iter()
.map(|(parent, child)| format!("__worklane_nested_arg_of {parent} {child}"))
@@ -183,10 +421,20 @@ complete -c worklane \
-n '__worklane_first_arg_of {ticket_commands}; or __worklane_second_arg_of {ticket_second_commands}' \
-a '(worklane ls --ids)'
# `relate` takes its targets as option values, so they are completed by flag rather
# than by position.
complete -c worklane -n '__worklane_command_is relate' {ticket_flags} \
-x -a '(worklane ls --ids)'
# The options whose value is a ticket, one rule per command so that a flag is offered
# only under the command that has it. `relate` takes its three targets this way rather
# than by position, and `chown --clear` names the ticket in the flag because with no user
# to give there is no second positional to put it in. Its `--clear` is scoped like every
# other: `set` has one that takes a field name, which clap already offers.
{ticket_flags}
# `relate --clear` is the one `--clear` whose first value is not a ticket, which is why
# that pair is not in `TICKET_FLAGS`: it takes the kind and then the target, and offering a
# board listing where the kind goes would be offering values it refuses. The kinds come
# from `RelationKind` rather than being spelled again. The target gets no rule at all,
# deliberately: fish completes the value after the flag, and the case this flag exists for
# is a target whose ticket is gone, which no listing of the board can offer.
complete -c worklane -n '__worklane_command_is relate' -l clear -x -a '{relation_kinds}'
# Campaigns, from `campaign ls --ids`, in the three places one is named: `assign`'s first
# argument, `campaign show`'s only one, and `ls --campaign`.
@@ -205,20 +453,17 @@ complete -c worklane -n '__worklane_command_is ls' {campaign_flags} \
# What is left is the annotation, and a tag the board carries but has never declared has
# none: it is offered with no description at all, which is the near-duplicate the file was
# added to catch. The count used to be the description and said the same thing more weakly.
complete -c worklane -n '__worklane_command_is ls' {tag_flags} \
-x -a '(worklane tags | cut -f1,3)'
#
# One rule per command, from `TAG_FLAGS`: `ls --tag` and `append --tags` are spelled
# differently, so a single rule naming both options would offer each under the other.
{tag_flags}
# And `tags set` names one that is already declared, so it reads the same listing. `tags
# add` has no rule on purpose: it takes a tag the board does not have, so the candidates
# here are the values it refuses.
complete -c worklane -n '{tag_nested}' -a '(worklane tags | cut -f1,3)'
# `chown --clear` names the ticket in the flag too, since with no user to give there is
# no second positional to put it in. Scoped to `chown`, unlike the rule above: `set`
# has a `--clear` of its own that takes a field name, and clap already offers those.
complete -c worklane -n '__worklane_command_is chown' -l clear -x -a '(worklane ls --ids)'
# clap emits the four for `mv --status`, which is an option, but the fish generator
# clap emits the statuses for `mv --status`, which is an option, but the fish generator
# emits nothing for the possible values of a positional. So the one place a status is
# positional needs them listed, and the same goes for the shell below.
complete -c worklane -n '__worklane_first_arg_of ls' -a '{statuses}' -d status
@@ -231,15 +476,40 @@ complete -c worklane -n '__worklane_first_arg_of install-skill' -a '{skills}' -d
)
}
/// Option names as fish wants them on a `complete` line, `-l one -l two`.
fn flag_list(flags: &[&str]) -> String {
/// Option names as fish wants them on a `complete` line, `-s o -l one -l two`, for the
/// options of one command.
fn flag_list(command: &str, flags: &[&str]) -> String {
flags
.iter()
.map(|flag| format!("-l {flag}"))
.map(|flag| fish_option(command, flag))
.collect::<Vec<_>>()
.join(" ")
}
/// One option as fish names it: its long name, and its letter where clap gave it one.
///
/// `-s g -l tags` rather than `-l tags` alone, or `append -g <TAB>` offers nothing where
/// `append --tags <TAB>` offers the board's tags — the same hole the board's own prompt had
/// until `long_name`, and the reason one table answers both halves is that neither may
/// answer a spelling the other does not. The letter is read off the definition and never
/// written here, so an option given one tomorrow is offered under it the day it is given.
fn fish_option(command: &str, flag: &str) -> String {
let cli = crate::command::Cli::command();
let short = cli
.find_subcommand(command)
.and_then(|command| {
command
.get_arguments()
.find(|option| option.get_long() == Some(flag))
})
.and_then(|option| option.get_short());
match short {
Some(letter) => format!("-s {letter} -l {flag}"),
None => format!("-l {flag}"),
}
}
/// The names a `ValueEnum` accepts, for a fish `-a` list.
///
/// Read off the enum rather than written out, so a status or a shell added to either one
@@ -397,14 +667,28 @@ mod tests {
/// about what the fish block is missing, which is a test's question.
const TAG_NEW_COMMANDS: [(&str, &str); 1] = [("tags", "add")];
/// Options taking a whole comma-separated list of tags rather than one.
///
/// `add --tags` and `set --tags` write the field entire, so what is being typed at the
/// cursor is `bug,tui` and fish replaces a token whole: a rule offering one tag there
/// would throw away the ones already in the token. `append --tags` adds to what is
/// there, so a single tag is the ordinary value and it earns a rule. Recorded rather
/// than skipped, for the reason `TAG_NEW_COMMANDS` is: the next `--tags` has to say
/// which of the two it is.
const TAG_LIST_FLAGS: [(&str, &str); 2] = [("add", "tags"), ("set", "tags")];
/// Tags have their own list because their values come from `worklane tags` rather than
/// from a listing of objects, so a second tag-taking option would need that rule and
/// not the campaign one.
///
/// Both spellings are walked, `tag` and `tags`: they are the same object under two
/// argument names, and looking at only the singular is how `set --tags` went years
/// without anybody deciding whether it wanted a rule.
#[test]
fn no_tag_taking_option_is_missing() {
let mut seen = 0;
for (path, arg) in every_argument() {
if arg.get_id().as_str() != "tag" {
if !matches!(arg.get_id().as_str(), "tag" | "tags") {
continue;
}
seen += 1;
@@ -427,13 +711,253 @@ mod tests {
continue;
};
let pair = (name.as_str(), long);
assert!(
TAG_FLAGS.contains(&long),
"`worklane {name} --{long}` takes a tag but is not in TAG_FLAGS"
TAG_FLAGS.contains(&pair) || TAG_LIST_FLAGS.contains(&pair),
"`worklane {name} --{long}` takes a tag, so it belongs in TAG_FLAGS if one \
tag is the ordinary value and TAG_LIST_FLAGS if the value is the whole list"
);
}
assert_eq!(seen, 3, "expected ls --tag, tags add and tags set");
assert_eq!(
seen, 6,
"expected ls --tag, tags add, tags set, add --tags, set --tags and append --tags"
);
}
/// One line, split the way the prompt splits it, and what the cursor's argument names.
///
/// The splitter is the prompt's own, so a row below states a line as a reader types it
/// rather than as a hand-written argument vector, and the two cannot come apart.
fn at_cursor(line: &str) -> Option<Argument> {
let split = crate::split::split_line(line, line.len());
argument_at(&split.args, split.cursor_arg)
}
/// The fixed values offered at the cursor, or nothing where what goes there is not a
/// fixed list.
fn values(line: &str) -> Option<Vec<String>> {
match at_cursor(line) {
Some(Argument::Fixed(values)) => Some(values),
_ => None,
}
}
/// Every position a ticket is taken in, as the line that reaches it.
#[test]
fn a_ticket_is_recognised_in_every_position_a_command_takes_one() {
for line in [
// The first positional, begun and half typed.
"show ",
"mv 1b7",
"comment ",
"check ",
// The second, where the first argument is a user or a campaign.
"chown alice ",
"assign v1 1b7",
// The three of `relate`'s flags, and `chown --clear`, which names the ticket
// in the flag because there is no user to give.
"relate 1b78a24 --blocked-by ",
"relate 1b78a24 --regression-of 417",
"relate 1b78a24 --relates-to ",
"chown --clear ",
] {
assert_eq!(
at_cursor(line),
Some(Argument::Ticket),
"`{line}` takes a ticket at the cursor and was not offered one"
);
}
}
/// The three places a campaign is named, and the two a tag is, which are why the lists
/// are not one list.
#[test]
fn a_campaign_and_a_tag_are_recognised_where_each_is_named() {
for line in [
"assign ",
"campaign show ",
"campaign set v1",
"ls --campaign ",
] {
assert_eq!(at_cursor(line), Some(Argument::Campaign), "`{line}`");
}
for line in ["ls --tag ", "append 1b78a24 --tags bu"] {
assert_eq!(at_cursor(line), Some(Argument::Tag { declared: false }), "`{line}`");
}
// `tags set` changes what a declared tag means and refuses one the file does not
// declare, so only the declared ones may be offered there. That is the fish half's
// 193f9be, which this deliberately does not inherit.
assert_eq!(at_cursor("tags set "), Some(Argument::Tag { declared: true }));
}
/// The verbs, which are clap's own subcommands at the top level and inside a group.
#[test]
fn the_verb_position_is_offered_the_subcommands() {
let top = values("").expect("the empty line names a verb");
for command in ["add", "ls", "mv", "relate", "campaign", "tags"] {
assert!(top.contains(&command.to_string()), "`{command}` is not offered: {top:?}");
}
// A group's own verb sits where a top-level command's first argument does, which is
// why `campaign show` needs a rule of its own in the fish half as well. In the
// order the definition spells them, since that is the order tab steps through.
let nested = values("campaign ").expect("a group names a verb");
assert_eq!(nested, ["add", "set", "append", "ls", "show"], "{nested:?}");
// `help` is clap's own and is added when the command is built, which nothing here
// does. That suits the board: what `help` prints is a page, and the prompt has a
// row.
assert!(!top.contains(&"help".to_string()), "{top:?}");
}
/// The values clap itself holds, which is every `ValueEnum` in the tool: nothing here
/// writes a status or a clearable field down a second time.
#[test]
fn an_enum_valued_argument_is_offered_the_enums_own_values() {
let statuses = values("mv 1b78a24 --status ").expect("--status takes a status");
let listed: Vec<String> = Status::ALL.iter().map(|s| s.as_str().to_string()).collect();
assert_eq!(statuses, listed, "the five statuses are not what `--status` offers");
// The one place a status is positional, which clap emits nothing for and the fish
// half lists by hand.
assert_eq!(values("ls "), Some(listed));
// And the other two enums a reader types: the fields `set --clear` empties and the
// shells `completions` writes for.
let fields = values("set 1b78a24 --clear ").expect("--clear takes a field");
assert!(fields.contains(&"acceptance".to_string()), "{fields:?}");
let shells = values("completions ").expect("completions takes a shell");
assert!(shells.contains(&"fish".to_string()), "{shells:?}");
}
/// The fish half names an option by its letter too, wherever clap gave it one, so a
/// dynamic rule answers both spellings the way the prompt does.
#[test]
fn a_fish_rule_names_the_option_by_its_letter_as_well() {
let script = fish_dynamic();
// `append --tags` is the one flag in these tables with a letter, and it is the
// whole reason the rule is rendered rather than written: `-g` offered nothing.
assert!(
script.contains("-s g -l tags"),
"the tags rule does not name its letter:\n{script}"
);
// And one without stays as it was, rather than gaining an empty `-s`.
assert!(script.contains("-l campaign"), "{script}");
assert!(!script.contains("-s "), "an option with no letter got one:\n{script}");
// Read off the definition, never written here.
assert_eq!(fish_option("append", "tags"), "-s g -l tags");
assert_eq!(fish_option("ls", "tag"), "-l tag");
assert_eq!(fish_option("ls", "nosuchflag"), "-l nosuchflag");
}
/// A flag spelled short answers exactly what the same flag spelled long answers, on
/// every command and every option that has both.
///
/// Walked off the clap definition rather than listed, so an option given a letter
/// tomorrow is covered the day it is given one. `-s` was the report: `mv --status `
/// offered the five statuses and `mv -s ` offered nothing, because the row read a flag
/// by its two hyphens. A boolean's two spellings agree as well, both answering nothing,
/// which is the same statement about a value that is not there.
#[test]
fn a_short_flag_answers_what_its_long_spelling_answers() {
let cli = crate::command::Cli::command();
let mut seen = 0;
for command in cli.get_subcommands() {
let children: Vec<(String, &clap::Command)> = command
.get_subcommands()
.map(|child| (format!("{} {}", command.get_name(), child.get_name()), child))
.collect();
for (line, holder) in
std::iter::once((command.get_name().to_string(), command)).chain(children)
{
for option in holder.get_arguments() {
let (Some(short), Some(long)) = (option.get_short(), option.get_long()) else {
continue;
};
seen += 1;
assert_eq!(
at_cursor(&format!("{line} -{short} ")),
at_cursor(&format!("{line} --{long} ")),
"`-{short}` and `--{long}` answer differently on `{line}`"
);
}
}
}
assert!(seen > 20, "only {seen} options had both spellings, which is too few");
}
/// The two the report named, spelled out, so the walk above cannot pass by finding
/// nothing on either spelling.
#[test]
fn a_short_flag_reaches_the_values_and_the_board() {
let listed: Vec<String> = Status::ALL.iter().map(|s| s.as_str().to_string()).collect();
assert_eq!(values("mv -s "), Some(listed), "`-s` offers no statuses");
assert_eq!(values("mv -s bac"), values("mv --status bac"), "half typed");
// A tag, which comes off the board rather than out of the enum.
assert_eq!(at_cursor("append -g "), Some(Argument::Tag { declared: false }));
// And a cluster is deliberately not read, because `--title`, `--acceptance` and a
// comment body all take a leading hyphen: a value spelled `-fixes the offset` must
// not be read as `-s` and answered with statuses.
assert_eq!(at_cursor("mv -fs "), None);
assert_eq!(at_cursor("comment 1b78a24 -fs "), None);
}
/// The flag on a nested command is answered the same way, from the enum: nothing here
/// knows what a campaign's states are, and the values reach the prompt and fish alike
/// the day a fourth one is added to `CampaignState`.
#[test]
fn campaign_ls_state_is_offered_the_enums_own_values() {
let states = values("campaign ls --state ").expect("--state takes a state");
assert_eq!(states, vec!["open", "done", "empty"], "{states:?}");
}
/// `relate --clear` takes the kind and then the target, which is the one argument clap
/// cannot answer for: possible values on the flag would refuse every target.
#[test]
fn relate_clear_is_offered_the_relation_kinds_and_no_ticket() {
let kinds = values("relate 1b78a24 --clear ").expect("--clear takes a kind");
let listed: Vec<String> = RelationKind::ALL
.iter()
.map(|kind| kind.flag().to_string())
.collect();
assert_eq!(kinds, listed, "{kinds:?}");
// And the second value is a target the board may no longer hold, which is what the
// flag exists for, so nothing is offered there at all.
assert_eq!(at_cursor("relate 1b78a24 --clear blocked-by "), None);
}
/// The positions that take free text, where offering anything would be offering a guess.
#[test]
fn nothing_is_recognised_where_the_argument_is_free_text() {
for line in [
// `chown`'s first argument is a user, checked against nothing.
"chown ",
// `mv` has no second positional, and a comment body is prose.
"mv 1b78a24 ",
"comment 1b78a24 the ",
// `tags add` declares a word the board does not have yet, so the tags it does
// have are exactly the values it refuses.
"tags add ",
// And both `--tags` that take the whole list, where a single tag offered into
// `bug,tui` would be one the field never asked for.
"add --tags ",
"set 1b78a24 --tags bug,",
] {
assert_eq!(at_cursor(line), None, "`{line}` was offered a candidate where none goes");
}
}
/// **Every rule naming an option has to say which command it belongs to.** A bare
@@ -459,47 +983,117 @@ mod tests {
fn every_listed_command_is_a_real_subcommand() {
let cli = command();
let known: Vec<&str> = cli.get_subcommands().map(|c| c.get_name()).collect();
for name in TICKET_COMMANDS.iter().chain(TICKET_SECOND_COMMANDS.iter()) {
assert!(known.contains(name), "no such subcommand: {name}");
// Every list that names a top-level command, not only the ticket ones. The others
// were reachable only through the rule counts below, which fail with `expected 3,
// got 4` and name nothing: a stale entry is a `complete` line whose condition never
// matches, so fish offers nothing and says nothing about why.
let top = TICKET_COMMANDS
.iter()
.chain(TICKET_SECOND_COMMANDS.iter())
.chain(CAMPAIGN_COMMANDS.iter())
.copied()
.chain(TICKET_FLAGS.iter().map(|(command, _)| *command))
.chain(TAG_FLAGS.iter().map(|(command, _)| *command));
for name in top {
assert!(known.contains(&name), "no such subcommand: {name}");
}
for (parent, child) in CAMPAIGN_NESTED_COMMANDS.iter().chain(TAG_NESTED_COMMANDS.iter()) {
let sub = cli
.find_subcommand(parent)
.unwrap_or_else(|| panic!("no such subcommand: {parent}"));
assert!(
sub.find_subcommand(child).is_some(),
"`worklane {parent}` has no `{child}` subcommand"
);
}
}
/// `chown --clear` takes a ticket, so it is completed like one, and only under
/// `chown`: `set --clear` is the same flag name carrying a field.
/// Three commands carry a `--clear` and each one takes something different: `chown`
/// takes the ticket, `relate` takes the kind and then the target, and `set` takes a
/// field name clap already offers. So each rule is scoped to its own command, and a
/// bare search for `-l clear` cannot tell them apart, which is what this used to do.
#[test]
fn chowns_clear_is_completed_with_tickets_and_sets_is_not() {
let script = fish_dynamic();
let rule = script
.lines()
.find(|line| line.starts_with("complete") && line.contains("-l clear"))
.expect("chown --clear has a rule of its own");
assert!(rule.contains("__worklane_command_is chown"), "{rule}");
assert!(rule.contains("worklane ls --ids"), "{rule}");
let chown = command().find_subcommand("chown").expect("chown exists").clone();
fn each_clear_flag_is_completed_for_its_own_command() {
// Continuations joined first: a rule is one logical line, and the generated ones
// put the flag and its values on either side of a trailing backslash.
let script = fish_dynamic().replace("\\\n", " ");
let cli = command();
let rule_for = |name: &str| {
let scope = format!("__worklane_command_is {name}");
script
.lines()
.find(|line| {
line.starts_with("complete")
&& line.contains("-l clear")
&& line.contains(&scope)
})
.unwrap_or_else(|| panic!("no --clear rule for {name}:\n{script}"))
.to_string()
};
let has_clear = |name: &str| {
cli.find_subcommand(name)
.unwrap_or_else(|| panic!("no such subcommand: {name}"))
.get_arguments()
.any(|arg| arg.get_long() == Some("clear"))
};
// `chown --clear` names the ticket in the flag, so the flag completes tickets.
assert!(has_clear("chown"), "`chown` has no --clear for the rule to complete");
assert!(rule_for("chown").contains("worklane ls --ids"), "{}", rule_for("chown"));
// `relate --clear` takes the kind first, so it offers the kinds and not a board
// listing: tickets there would be candidates the flag refuses. The target, the
// second value, is deliberately left uncompleted.
assert!(has_clear("relate"), "`relate` has no --clear for the rule to complete");
let relate = rule_for("relate");
for kind in RelationKind::ALL {
assert!(relate.contains(kind.flag()), "{kind:?} is not offered: {relate}");
}
assert!(
chown.get_arguments().any(|arg| arg.get_long() == Some("clear")),
"`chown` has no --clear for the rule to complete"
!relate.contains("worklane ls --ids"),
"tickets offered where the kind goes: {relate}"
);
// `set --clear` takes a field name, which clap already offers, and `relate --clear`
// takes a kind. Only `chown`'s names a ticket, so only that pair is in the table.
assert!(
!TICKET_FLAGS.contains(&("set", "clear")),
"`set --clear` in TICKET_FLAGS would offer tickets where a field name goes"
);
assert!(
!TICKET_FLAGS.contains(&"clear"),
"--clear in TICKET_FLAGS would offer tickets to `set --clear`, which takes a field"
!TICKET_FLAGS.contains(&("relate", "clear")),
"`relate --clear` in TICKET_FLAGS would offer tickets where the kind goes"
);
assert!(
TICKET_FLAGS.contains(&("chown", "clear")),
"`chown --clear` names the ticket in the flag, so it belongs in TICKET_FLAGS"
);
}
/// The flags completed as tickets have to be `relate`'s actual flags, or the rule
/// completes an option nothing accepts.
/// Each flag completed as a ticket has to be an option its own command actually takes,
/// or the rule completes something nothing accepts.
///
/// The command is half of what is checked, which is what the pairs bought: a flat list
/// could only be walked against one command, and `--clear` is spelled the same on three.
#[test]
fn every_ticket_flag_is_a_real_option() {
let relate = command()
.find_subcommand("relate")
.expect("relate exists")
.clone();
let known: Vec<String> = relate
.get_arguments()
.filter_map(|arg| arg.get_long().map(str::to_string))
.collect();
for flag in TICKET_FLAGS {
assert!(known.contains(&flag.to_string()), "`relate` has no --{flag}");
let cli = command();
for (name, flag) in TICKET_FLAGS {
let subcommand = cli
.find_subcommand(name)
.unwrap_or_else(|| panic!("no such subcommand: {name}"));
assert!(
subcommand
.get_arguments()
.any(|arg| arg.get_long() == Some(flag)),
"`worklane {name}` has no --{flag}"
);
}
}
@@ -545,10 +1139,16 @@ mod tests {
.filter(|line| line.contains("(worklane tags"))
.collect();
// **Hardcoded on purpose, and not derivable from the lists above.** This number is
// what catches an entry naming a command or a flag that does not exist: the walkers
// go clap → list and never see an extra, so a bogus `("bogus", "nope")` in
// `TAG_FLAGS` produces a fourth rule and only this count notices. Writing it as
// `TAG_FLAGS.len() + TAG_NESTED_COMMANDS.len()` would grow with the bogus entry and
// pass, which is the improvement to not make.
assert_eq!(
reading.len(),
2,
"expected the ls --tag rule and the tags set one: {reading:?}"
3,
"expected the ls --tag rule, the append --tags one and the tags set one: {reading:?}"
);
for line in reading {
assert!(line.contains("(worklane tags | cut -f1,3)"), "{line}");
@@ -574,7 +1174,7 @@ mod tests {
}
}
/// The four for `mv --status` are clap's, which is half of why `Status` is a
/// The statuses for `mv --status` are clap's, which is half of why `Status` is a
/// `ValueEnum`. If clap ever stops emitting them, the fish half has to carry them
/// too, and this is what says so.
#[test]
+1013 -229
View File
File diff suppressed because it is too large Load Diff
+238 -66
View File
@@ -24,8 +24,8 @@ use anyhow::{Result, anyhow};
use chrono::Local;
use crate::util::{
Cell, Color, MISSING, TIMESTAMP_FORMAT, is_unknown_value, paint_cells, should_use_colors,
tag_cells, tag_color,
Cell, Color, MISSING, TIMESTAMP_FORMAT, is_unknown_value, paint_cells, quoted_cells,
should_use_colors, tag_cells, tag_color,
};
/// Where a ticket's history lives, under the board.
@@ -402,24 +402,9 @@ pub fn format_history(entries: &[Entry]) -> String {
/// As above, with the colour decision passed in.
pub fn format_history_with(entries: &[Entry], colored: bool) -> String {
paint_cells(&history_cells(entries), colored)
paint_cells(&history_cells(entries, colored), colored)
}
/// How far the reason under a mechanical row sits from the margin.
///
/// One step, which is where a comment's body used to sit too. It stays here because the
/// reason belongs to the row above it: it is read as part of that transition, not as an
/// entry of its own.
const REASON_INDENT: &str = " ";
/// How far a comment's body sits from the margin.
///
/// One step deeper than a reason, so the column says who is talking: a line indented this
/// far is somebody's own words and a line of values at column 0 is the tool reporting
/// itself. The author line stays at column 0 and is told from a mechanical row by its
/// `From` and its colour instead, which is the trade this shape accepts.
const COMMENT_INDENT: &str = " ";
/// The cells one value in a mechanical body is drawn as, per the Color Guideline.
///
/// Keyed on the kind, because the kind is what says which field the value came from: the
@@ -466,79 +451,135 @@ fn stamp_cells(entry: &Entry) -> Vec<Cell> {
]
}
/// The block laid out once, as [`Cell`]s: the CLI paints them and the board turns the
/// same ones into styled spans, so the two views cannot draw two different blocks.
pub fn history_cells(entries: &[Entry]) -> Vec<Cell> {
/// One segment of the history block: what it is, and how a renderer lays it out.
///
/// [`history_cells`] flattens these into the cells the CLI paints, and the board turns
/// each segment into its own stretch of the overlay instead: the flow runs full width
/// while a quoted run becomes a gutter column with the bar in it and the body beside it,
/// so a row the body wraps keeps the mark. One segmentation, two shapes — neither
/// renderer re-decides which runs are somebody's words.
#[derive(Debug)]
pub enum HistoryPart {
/// Headers, mechanical rows and the blank lines between entries, as they stand.
Flow(Vec<Cell>),
/// A comment's body or a move's reason: plain text, every line of it quoted, in
/// whatever shape the renderer quotes with.
Quoted(String),
}
/// The block as segments, one walk over the entries.
///
/// The order is the entries' own, oldest first, and a quoted run always sits between two
/// flow runs — the header or mechanical row before it and the blank line after it — so a
/// renderer can treat each segment as one unbroken stretch of rows.
pub fn history_parts(entries: &[Entry]) -> Vec<HistoryPart> {
let mut parts = Vec::new();
// The flow accumulating until the next quote closes it, which is why the trailing
// newline of every entry lands in the segment *after* a quote rather than being
// dropped: flattened, the parts are byte for byte the block [`history_cells`] has
// always built, which is what the CLI's pins hold it to.
let mut flow: Vec<Cell> = Vec::new();
if entries.is_empty() {
return vec![Cell::colored("No history yet.", Color::Grey)];
flow.push(Cell::colored("No history yet.", Color::Grey));
parts.push(HistoryPart::Flow(flow));
return parts;
}
let mut cells = Vec::new();
cells.push(Cell::plain("\n"));
cells.push(Cell::colored("HISTORY", Color::Orange));
cells.push(Cell::plain(format!("\n{}\n", "─".repeat(20))));
flow.push(Cell::plain("\n"));
flow.push(Cell::colored("HISTORY", Color::Orange));
flow.push(Cell::plain(format!("\n{}\n", "─".repeat(20))));
for entry in entries {
cells.push(Cell::plain("\n"));
flow.push(Cell::plain("\n"));
match entry.kind {
// As it has always read: a header naming who said it, then the text.
Kind::Comment => {
// Grey on the word, for the reason the kind label is grey: `From` names
// the line, it is not a value in it.
cells.push(Cell::colored("From", Color::Grey));
cells.push(Cell::plain(" "));
cells.extend(stamp_cells(entry));
cells.push(Cell::plain("\n"));
flow.push(Cell::colored("From", Color::Grey));
flow.push(Cell::plain(" "));
flow.extend(stamp_cells(entry));
flow.push(Cell::plain("\n"));
if !entry.body.is_empty() {
cells.push(Cell::plain(format!("{}{}", COMMENT_INDENT, entry.body)));
parts.push(HistoryPart::Flow(std::mem::take(&mut flow)));
parts.push(HistoryPart::Quoted(entry.body.clone()));
}
cells.push(Cell::plain("\n"));
flow.push(Cell::plain("\n"));
}
// One line: a field change is one fact and a paragraph for it would bury the
// comments it sits between. A reason grows an indented line under the row,
// the way a comment's text sits under its From header, so it reads as
// attached to the transition it explains rather than as the next entry.
// comments it sits between. A reason draws behind the same bar the comments
// draw, since it shares their shape and their gap, so it reads as attached
// to the transition it explains rather than as the next entry.
_ => {
let padding = Kind::LABEL_WIDTH.saturating_sub(entry.kind.slug().chars().count());
// Grey, as chrome. It was orange, which means Status everywhere else, so
// an `owner` or `tags` label claimed a meaning belonging to the value
// beside it. The label is not a value at all: it names the row, which is
// what grey already says.
cells.push(Cell::colored(entry.kind.slug(), Color::Grey));
flow.push(Cell::colored(entry.kind.slug(), Color::Grey));
// Measured on the unpainted label and carried in a cell of its own, the
// rule the metadata table follows: measuring a painted string counts its
// escapes towards its width, which tilts the column when colour is on and
// not when it is off.
cells.push(Cell::plain(format!("{} ", " ".repeat(padding))));
flow.push(Cell::plain(format!("{} ", " ".repeat(padding))));
match split_change(&entry.body) {
Some((before, after)) => {
cells.extend(value_cells(entry.kind, before));
cells.push(Cell::plain(CHANGE_SEPARATOR));
cells.extend(value_cells(entry.kind, after));
flow.extend(value_cells(entry.kind, before));
flow.push(Cell::plain(CHANGE_SEPARATOR));
flow.extend(value_cells(entry.kind, after));
}
None => cells.extend(value_cells(entry.kind, &entry.body)),
None => flow.extend(value_cells(entry.kind, &entry.body)),
}
cells.push(Cell::plain(" "));
cells.extend(stamp_cells(entry));
cells.push(Cell::plain("\n"));
flow.push(Cell::plain(" "));
flow.extend(stamp_cells(entry));
flow.push(Cell::plain("\n"));
// The newline is the quote's terminator, so it exists only when there is
// one: a reasoned row draws the reason under itself and this closes it.
if !entry.reason.is_empty() {
cells.push(Cell::plain(format!("{}{}", REASON_INDENT, entry.reason)));
cells.push(Cell::plain("\n"));
parts.push(HistoryPart::Flow(std::mem::take(&mut flow)));
parts.push(HistoryPart::Quoted(entry.reason.clone()));
flow.push(Cell::plain("\n"));
}
}
}
}
if !flow.is_empty() {
parts.push(HistoryPart::Flow(flow));
}
parts
}
/// The block laid out once, as [`Cell`]s: the CLI paints them and the board turns the
/// same ones into styled spans, so the two views cannot draw two different blocks.
///
/// The flatten of [`history_parts`], which is what makes the CLI's bytes a property of
/// the segmentation rather than a second walk that can drift from it: the pins over this
/// function's output are pins over the parts too. The colour decision rides in because
/// the quote bar is a coloured decoration; with it off the cells carry the indent the
/// bar would have provided. The board does not come through here — it lays each part in
/// the shape the section builder gives it — but it reads the same parts.
pub fn history_cells(entries: &[Entry], colored: bool) -> Vec<Cell> {
let mut cells = Vec::new();
for part in history_parts(entries) {
match part {
HistoryPart::Flow(run) => cells.extend(run),
HistoryPart::Quoted(body) => cells.extend(quoted_cells(&body, colored)),
}
}
cells
}
#[cfg(test)]
mod tests {
use super::*;
use crate::util::{Fixture, NOT_SET, paint};
use crate::util::{
BLOCKED_MARK, Fixture, NOT_SET, PRIORITY_RANGE, Priority, QUOTE_BAR, REGRESSION_MARK,
RELATES_MARK, paint, priority_mark, status_dirs, status_mark,
};
/// One entry, spelled the way a file on the board holds it.
fn entry(kind: &str, body: &str, author: &str, time: &str) -> Entry {
@@ -775,12 +816,14 @@ mod tests {
] {
assert!(rendered.contains(row), "missing {row:?} in {rendered}");
}
// The body sits a step deeper than a reason does, and the author line did not move
// The body keeps the width the bar occupied, and the author line did not move
assert!(
rendered
.contains("From Ansho Rei (2026-08-24 12:00:04)\n The offset was never passed"),
.contains("From Ansho Rei (2026-08-24 12:00:04)\n The offset was never passed"),
"{rendered}"
);
// A single line draws no glyph in a pipe, and it is not spared the indent
assert!(!rendered.contains(QUOTE_BAR), "{rendered:?}");
assert!(!rendered.contains('\x1b'), "colour off still painted: {rendered:?}");
}
@@ -788,10 +831,12 @@ mod tests {
/// way `show_prints_the_same_body_it_printed_before_the_cells_conversion` pins the
/// body.
///
/// Rewritten twice, deliberately. `campaign` widened the label column from 6 to 8 and
/// put its own row in the pin (f774a33). Then 2733b10 painted the values: the label
/// went grey as chrome, each value took the meaning it carries in the metadata table,
/// and the actor and the timestamp came apart into two spans.
/// Rewritten three times, deliberately. `campaign` widened the label column from 6
/// to 8 and put its own row in the pin (f774a33). Then 2733b10 painted the values:
/// the label went grey as chrome, each value took the meaning it carries in the
/// metadata table, and the actor and the timestamp came apart into two spans. Then
/// d447e04 put the single-line body behind the grey quote bar, which is what the
/// `{bar}` in the middle of the expected string is.
///
/// Every kind is here rather than a representative one, since what each row proves is
/// different: status is the orange it is three lines above, tags go through the same
@@ -820,8 +865,9 @@ mod tests {
paint(time, Color::Cyan, true)
)
};
let bar = paint(&format!("{QUOTE_BAR} "), Color::Grey, true);
let expected = format!(
"\n{}\n{}\n\n{} {} → {} {}\n\n{} {}\n The offset was never passed\n\n{} {} → {} {}\n\n{} {} → alice {}\n\n{} {} → {}, {} {}\n",
"\n{}\n{}\n\n{} {} → {} {}\n\n{} {}\n{}The offset was never passed\n\n{} {} → {} {}\n\n{} {} → alice {}\n\n{} {} → {}, {} {}\n",
paint("HISTORY", Color::Orange, true),
"─".repeat(20),
paint("status", Color::Grey, true),
@@ -830,6 +876,7 @@ mod tests {
stamp("claude", "2026-08-24 12:00:00"),
paint("From", Color::Grey, true),
stamp("Ansho Rei", "2026-08-24 12:00:01"),
bar,
paint("campaign", Color::Grey, true),
paint(NOT_SET, Color::Grey, true),
paint("v1", tag_color("v1"), true),
@@ -878,10 +925,10 @@ mod tests {
assert!(!rendered.contains(&paint("claude (", Color::Cyan, true)), "still one span");
}
/// The reason is the row's, so it renders indented under the row it explains and
/// before whatever entry follows, in both renderers — this is the one layout they
/// share. Paired with the pin above: an entry without a reason renders exactly as
/// it always did.
/// The reason is the row's, so it renders behind the same bar the comments draw,
/// under the row it explains and before whatever entry follows, in both renderers —
/// this is the one layout they share. Paired with the pin above: an entry without a
/// reason renders exactly as it always did.
#[test]
fn a_reason_renders_indented_under_its_row() {
let entries = vec![
@@ -893,8 +940,9 @@ mod tests {
entry("comment", "And why.", "Ansho Rei", "2026-08-24 12:00:01"),
];
let bar = paint(&format!("{QUOTE_BAR} "), Color::Grey, true);
let expected = format!(
"\n{}\n{}\n\n{} {} → {} {} ({})\n sent back, the first plan was wrong\n\n{} {} ({})\n And why.\n",
"\n{}\n{}\n\n{} {} → {} {} ({})\n{}sent back, the first plan was wrong\n\n{} {} ({})\n{}And why.\n",
paint("HISTORY", Color::Orange, true),
"─".repeat(20),
paint("status", Color::Grey, true),
@@ -902,18 +950,100 @@ mod tests {
paint("backlog", Color::Orange, true),
paint("claude", tag_color("claude"), true),
paint("2026-08-24 12:00:00", Color::Cyan, true),
bar,
paint("From", Color::Grey, true),
paint("Ansho Rei", tag_color("Ansho Rei"), true),
paint("2026-08-24 12:00:01", Color::Cyan, true),
bar,
);
assert_eq!(format_history_with(&entries, true), expected);
// Colour off keeps the reason exactly where a pipe has always read it, at the
// width the bar occupied, and carries no glyph doing it.
let plain = format_history_with(&entries, false);
assert!(
format_history_with(&entries, false)
.contains("claude (2026-08-24 12:00:00)\n sent back, the first plan was wrong"),
"colour off lost the reason: {}",
format_history_with(&entries, false)
plain.contains("claude (2026-08-24 12:00:00)\n sent back, the first plan was wrong"),
"colour off lost the reason: {plain}"
);
assert!(!plain.contains(QUOTE_BAR) && !plain.contains('\x1b'), "{plain:?}");
}
/// The reported shape: every line of a run sits behind the bar, so a two-paragraph
/// comment reads as one voice start to finish. This is what a single prefix got
/// wrong — b304b17's symptom — with every line after the first back at column 0,
/// which 2733b10 had just given a meaning to.
#[test]
fn a_multi_line_comment_draws_every_line_behind_the_bar() {
let entries = vec![entry(
"comment",
"First paragraph.\n\nSecond one, still theirs.",
"Ansho Rei",
"2026-08-24 12:00:00",
)];
let bar = paint(&format!("{QUOTE_BAR} "), Color::Grey, true);
let bare = paint(QUOTE_BAR, Color::Grey, true);
let rendered = format_history_with(&entries, true);
// Both content lines prefixed, and the break between them inside the run as the
// bare glyph rather than a gap running nowhere.
let expected = format!(
"\n{}\n{}\n\n{} {} ({})\n{}First paragraph.\n{}\n{}Second one, still theirs.\n",
paint("HISTORY", Color::Orange, true),
"─".repeat(20),
paint("From", Color::Grey, true),
paint("Ansho Rei", tag_color("Ansho Rei"), true),
paint("2026-08-24 12:00:00", Color::Cyan, true),
bar,
bare,
bar,
);
assert_eq!(rendered, expected);
}
/// Paired with the one above, the way the guideline demands: colour off drops the
/// glyph but keeps the width it occupied, derived from the drawn form, so every
/// content line still starts at the same column and no escape byte reaches a pipe.
/// The flag is the only thing that decides the bar.
#[test]
fn colour_off_keeps_the_indent_and_drops_the_glyph() {
let entries = vec![entry(
"comment",
"First paragraph.\n\nSecond one, still theirs.",
"Ansho Rei",
"2026-08-24 12:00:00",
)];
let rendered = format_history_with(&entries, false);
let expected = format!(
"\nHISTORY\n{}\n\nFrom Ansho Rei (2026-08-24 12:00:00)\n First paragraph.\n\n Second one, still theirs.\n",
"─".repeat(20),
);
assert_eq!(rendered, expected);
}
/// The bar is chrome like the kind label, so it takes grey; it is one cell wide; and
/// it claims nothing another column already means: the circles and the dot belong to
/// the priority meter, the cross and arrows to the relation rows, and the status
/// marks reuse both sets. Pinned against the marks actually defined rather than a
/// list written out here, so a mark added later fails this instead of sharing.
#[test]
fn the_quote_bar_claims_no_glyph_another_column_means() {
assert_eq!(QUOTE_BAR.chars().count(), 1);
let mut taken = String::new();
for level in PRIORITY_RANGE {
taken.push_str(priority_mark(Priority::Level(level)).0);
}
taken.push_str(priority_mark(Priority::Unset).0);
taken.push_str(BLOCKED_MARK);
taken.push_str(RELATES_MARK);
taken.push_str(REGRESSION_MARK);
for status in status_dirs() {
taken.push_str(status_mark(Some(status)).0);
}
assert!(!taken.contains(QUOTE_BAR), "{taken:?} already means something");
}
/// Padded to the longest of the four, so every body starts in the same column
@@ -961,4 +1091,46 @@ mod tests {
fn nothing_recorded_says_so() {
assert_eq!(format_history_with(&[], false), "No history yet.");
}
/// The block as segments: the rows drawn as they stand are flow, a comment's body
/// and a move's reason are quoted, and each quote sits between two flow runs — the
/// row or header before it and the blank after it. This is the one segmentation both
/// renderers read, so it is pinned here rather than left to be discovered on the
/// board; the CLI's byte pins above hold its flatten to what it has always printed.
#[test]
fn the_block_splits_into_flow_and_quoted_parts() {
let entries = vec![
entry("status", "committed → reviewing", "claude", "2026-08-24 12:00:00"),
entry("comment", "First line.\n\nSecond.", "Ansho Rei", "2026-08-24 12:00:01"),
entry("status", "reviewing → backlog", "claude", "2026-08-24 12:00:02"),
]
.into_iter()
.enumerate()
.map(|(at, mut entry)| {
if at == 2 {
entry.reason = "sent back".to_string();
}
entry
})
.collect::<Vec<_>>();
let parts = history_parts(&entries);
let shapes: Vec<&str> = parts
.iter()
.map(|part| match part {
HistoryPart::Flow(_) => "flow",
HistoryPart::Quoted(_) => "quote",
})
.collect();
assert_eq!(shapes, ["flow", "quote", "flow", "quote", "flow"], "{parts:?}");
// The quotes carry the bare words, newlines included; laying them out is the
// renderer's decision.
for part in &parts {
if let HistoryPart::Quoted(body) = part {
assert!(!body.contains(QUOTE_BAR), "{body:?}");
}
}
assert_eq!(parts.len(), 5);
}
}
+133 -26
View File
@@ -162,7 +162,8 @@ pub fn skills_root() -> Result<PathBuf> {
/// `NO_COLOR`. Checked against opencode 1.15.10.
///
/// Singular `tool`, though 1.15.10 loads `tools` as well: each was served in turn from a
/// directory outside any project and registered all eleven worklane tools. The singular
/// directory outside any project and registered every worklane tool the file carried,
/// eleven at the time and twenty-one at the recheck. The singular
/// is the spelling opencode's own documentation puts first, the way it writes `agent(s)`
/// and `skill(s)`.
///
@@ -489,10 +490,10 @@ mod tests {
///
/// The domain examples are the first thing an edit would quietly drop, since every
/// other skill here is written around this repo, and dropping them leaves a document
/// that teaches a household board to file `cli` tickets. The two-step repair is the
/// second: it looks like a typo until you have watched `mv` refuse the one-step
/// version, which is why the ticket for this skill demanded every repair be run rather
/// than reasoned about.
/// that teaches a household board to file `cli` tickets. The one-move correction is
/// the second: it is the repair `mv` actually performs since it learned to fix a
/// Status field that lags its directory, and an edit back to the old two-step recipe
/// would be teaching a workaround for a bug that no longer exists.
#[test]
fn the_admin_skill_stays_domain_neutral_and_keeps_its_verified_repairs() {
for required in [
@@ -500,7 +501,8 @@ mod tests {
"product strategy", //
"worklane tags add", // the vocabulary is declared through the CLI
"--tags` replaces the whole field", // the destructive one, restated where it bites
"two moves, not one", // the repair `mv` cannot do in one step
"reporting the correction instead of refusing as a no-op", // the repair `mv` does in one step
"no stamp is written and no history entry", // because the work went nowhere
"do not edit a ticket file",
"File exception", // and the three places that rule does not reach
"worklane-plan", // the boundary against the sweep document
@@ -524,6 +526,9 @@ mod tests {
"nothing names the ticket", // and the no-work-found case is answered
"Never tick a criterion",
"Do not move the ticket",
"already on master", // landed work: findings become tickets, then done
"File a ticket for every issue",
"Write a closing comment", // and says so before the move
"worklane uncheck",
"worklane append",
"cannot tell",
@@ -568,7 +573,7 @@ mod tests {
}
/// The file name is the tool id prefix, not decoration: opencode names each tool as
/// the file then the export, so a renamed file renames all eleven tools and every
/// the file then the export, so a renamed file renames all twenty-one tools and every
/// permission rule that mentions one.
#[test]
fn the_tool_lands_flat_in_the_root_under_the_name_that_prefixes_its_ids() {
@@ -578,31 +583,18 @@ mod tests {
assert_eq!(TOOL.relative, "worklane.ts");
}
/// Every tool the file exports names a real subcommand.
/// Every tool the file exports names a real subcommand path.
///
/// The guard the fish completion lists already have, pointed the other way: this
/// catches a tool wrapping a command that has been renamed or dropped, which would
/// fail only when an agent finally called it. It cannot catch the reverse, a
/// subcommand the wrapper never grew a tool for, and the wrapper is behind by
/// several: `relate`, `campaign`, `assign` and `tags` have no tool. That is its own
/// ticket, and asserting it here would fail on a gap nobody has decided to close.
/// fail only when an agent finally called it. The converse, a subcommand the wrapper
/// never grew a tool for, is [`every_subcommand_outside_the_exceptions_has_a_tool`].
#[test]
fn every_tool_the_wrapper_exports_is_a_real_subcommand() {
use clap::CommandFactory;
let commands: Vec<String> = subcommand_paths();
let exported = exported_tools();
let commands: Vec<String> = crate::Cli::command()
.get_subcommands()
.map(|command| command.get_name().to_string())
.collect();
let exported: Vec<&str> = TOOL
.content
.lines()
.filter_map(|line| line.strip_prefix("export const "))
.filter_map(|rest| rest.split_whitespace().next())
.collect();
assert_eq!(exported.len(), 11, "{exported:?}");
assert_eq!(exported.len(), 21, "{exported:?}");
for name in exported {
assert!(
commands.iter().any(|command| command == name),
@@ -610,4 +602,119 @@ mod tests {
);
}
}
/// The export names in the tool file: one per `export const`, which is what makes
/// them tool ids once opencode prefixes its file name.
fn exported_tools() -> Vec<&'static str> {
TOOL.content
.lines()
.filter_map(|line| line.strip_prefix("export const "))
.filter_map(|rest| rest.split_whitespace().next())
.collect()
}
/// Every subcommand as the wrapper spells it: the CLI path joined with `_`, since
/// that is how an export name has to be spelled to be an identifier. So
/// `campaign set` is `campaign_set`, and the hyphen in `install-skill` becomes one.
///
/// Walked off clap rather than written out, the way every other guard here is:
/// a hand-maintained list is the very drift this exists to catch.
fn subcommand_paths() -> Vec<String> {
use clap::CommandFactory;
fn walk(command: &clap::Command, prefix: Option<&str>, paths: &mut Vec<String>) {
for sub in command.get_subcommands() {
let name = sub.get_name();
if name == "help" {
continue;
}
let path = match prefix {
Some(prefix) => format!("{prefix}_{name}"),
None => name.to_string(),
};
let path = path.replace('-', "_");
walk(sub, Some(&path), paths);
paths.push(path);
}
}
let mut paths = Vec::new();
walk(&crate::Cli::command(), None, &mut paths);
paths
}
/// Subcommands the wrapper deliberately does not carry, each with why it is left out.
///
/// Spelled the way [`subcommand_paths`] spells a path, so a renamed command leaves a
/// stale entry behind rather than silently exempting nothing.
const NO_TOOL: [(&str, &str); 6] = [
(
"campaign",
"a bare `worklane campaign` is refused by the CLI, its subcommand is required: the five campaign_* tools are the command",
),
(
"tui",
"the board view is for a person: it takes over the terminal and returns only when quit",
),
(
"completions",
"writes a person's shell configuration, which is not an agent's call to make",
),
(
"install_skill",
"installs the skill documents themselves, so an agent running it would rewrite its own instructions mid-session",
),
(
"install_tool",
"installs this very wrapper, which opencode reads once at startup, so reinstalling from inside changes nothing until restart",
),
(
"tags_ls",
"prints exactly what the bare `worklane tags` listing prints, and the tags tool runs that",
),
];
/// The direction that went unguarded until now: every subcommand outside the
/// exception list has a tool.
///
/// This is the gap e6e3a1b taught the README about and the completion lists have
/// never had: a new subcommand reached clap, the completions and the skill, and
/// stopped there, so an agent holding the tools could not call it at all and its
/// only way to the command was to shell out, which is the thing the wrapper exists
/// to avoid. Nothing else walks the wrapper against clap, so without this test the
/// next command lands in the same silence.
#[test]
fn every_subcommand_outside_the_exceptions_has_a_tool() {
let paths = subcommand_paths();
let exported = exported_tools();
// Guard on the walker itself: if it stopped finding subcommands, both filters
// below would pass on nothing.
assert_eq!(paths.len(), 27, "{paths:?}");
assert_eq!(exported.len(), 21, "{exported:?}");
let missing: Vec<&String> = paths
.iter()
.filter(|path| !NO_TOOL.iter().any(|(name, _)| name == path))
.filter(|path| !exported.iter().any(|tool| tool == path))
.collect();
assert!(
missing.is_empty(),
"no tool for {missing:?}. A new subcommand reaches the CLI, the completions \
and the skill, and stops there: give it a tool in assets/TOOL.ts, or name \
it in NO_TOOL with why it should not have one."
);
// An exception naming a subcommand that has gone, or carrying no reason, is
// drift of exactly the kind this test is for.
for (name, reason) in NO_TOOL {
assert!(
paths.iter().any(|path| path == name),
"the exception {name:?} names no subcommand clap has"
);
assert!(!reason.trim().is_empty(), "the exception for {name} carries no reason");
}
}
}
+109 -45
View File
@@ -1,6 +1,9 @@
use std::path::Path;
use anyhow::Result;
use clap::Parser;
mod board;
mod campaign;
mod clipboard;
mod command;
@@ -8,6 +11,11 @@ mod completions;
mod handlers;
mod history;
mod install;
/// The command prompt reads `split_line` and `unclosed`; `cursor_arg` and `at_new_arg` are
/// what completing an argument needs and nothing reads them yet, so the allow stays until
/// 00a14e7 and 952a9f8 land. The tests are what drive them in the meantime.
#[cfg_attr(not(test), allow(dead_code))]
mod split;
mod tag;
mod tui;
mod util;
@@ -42,77 +50,118 @@ fn main() -> Result<()> {
let start = std::env::current_dir()?;
match cli.command {
let mut sink = Sink::std();
let result = match cli.command {
// The board is the one thing `dispatch` does not run, and it is matched here
// rather than there because it is the *caller* of that table rather than an entry
// in it: a `tui` reached from the command prompt would enter the alternate screen
// a second time from inside the draw loop. `dispatch` refuses it in those words.
//
// No subcommand opens the board, the way a bare `frig` does, and with no path
// it opens the board above the working directory.
None => run_tui(&[], &start),
Some(Command::Tui { paths }) => run_tui(&paths, &start),
Some(Command::Init) => cmd_init(&start),
Some(Command::Add(args)) => cmd_add(&args, &start),
Some(Command::Ls(args)) => {
let worklane_dir = find_worklane_dir(&start)?;
cmd_ls(&args, &worklane_dir)
// Every call `main` dispatches came from a shell or a script, so the session's
// own chain answers: `WORKLANE_ACTOR` first, which is what it is set for.
Some(command) => dispatch(&command, &start, Attribution::Session, &mut sink),
};
// The board (and every handler) own their own writing, so flush what the last one
// handed the sink before returning; an error path printed nothing to flush.
sink.flush()?;
result
}
/// Run one parsed command against the board at or above `start`, saying what it did
/// through `sink`.
///
/// **The one mapping from a parsed command to the function that performs it.** `main`
/// calls it with the process's stdout and the working directory; the command prompt on
/// the board calls it with a buffer and the selected tab's own root, and reads back what
/// the handler said. A second copy of this match inside `tui.rs` would be a copy that
/// drifted the first time a command was added, and it would drift *silently*, since both
/// halves would go on compiling.
///
/// A command added to [`Command`] therefore lands here once and is runnable from both.
/// The match is exhaustive for exactly that reason: there is no `_` arm for a new verb to
/// fall into and do nothing.
///
/// `by` is who the call is being made by, and it is a parameter here rather than a field
/// the prompt writes into the parsed arguments: an entry-writing command added tomorrow
/// is attributed correctly from both callers without an arm anywhere rewriting what clap
/// produced. `main` is the session, the prompt is the person at the board.
pub fn dispatch(command: &Command, start: &Path, by: Attribution, sink: &mut Sink) -> Result<()> {
match command {
// Reachable only from the prompt, since `main` takes this arm before it gets
// here. A board is not something a board can open.
Command::Tui { .. } => Err(anyhow::anyhow!("`tui` opens a board, and you are on one")),
Command::Init { create } => cmd_init(*create, start, sink),
Command::Add(args) => cmd_add(args, start, sink),
Command::Ls(args) => {
let worklane_dir = find_worklane_dir(start)?;
cmd_ls(args, &worklane_dir, sink)
}
Some(Command::Show { id }) => {
let worklane_dir = find_worklane_dir(&start)?;
cmd_show(&id, &worklane_dir)
Command::Show { id } => {
let worklane_dir = find_worklane_dir(start)?;
cmd_show(id, &worklane_dir, sink)
}
Some(Command::Mv {
Command::Mv(args) => cmd_mv(args, start, by, sink),
Command::Set(args) => cmd_set(args, start, by, sink),
Command::Append(args) => cmd_append(args, start, by, sink),
Command::Relate(args) => cmd_relate(args, start, sink),
Command::Chown(args) => cmd_chown(args, start, by, sink),
Command::Check(args) => cmd_check(args, true, start, sink),
Command::Uncheck(args) => cmd_check(args, false, start, sink),
Command::Comment {
ticket,
status,
force,
body,
actor,
reason,
}) => cmd_mv(&ticket, status, force, &actor, &reason, &start),
Some(Command::Set(args)) => cmd_set(&args, &start),
Some(Command::Append(args)) => cmd_append(&args, &start),
Some(Command::Relate(args)) => cmd_relate(&args, &start),
Some(Command::Chown(args)) => cmd_chown(&args, &start),
Some(Command::Check(args)) => cmd_check(&args, true, &start),
Some(Command::Uncheck(args)) => cmd_check(&args, false, &start),
Some(Command::Comment { ticket, body, actor }) => {
cmd_comment(&ticket, &body, &actor, &start)
}
Some(Command::Campaign { command }) => match command {
CampaignCommand::Add(args) => cmd_campaign_add(&args, &start),
CampaignCommand::Ls { ids } => {
let worklane_dir = find_worklane_dir(&start)?;
cmd_campaign_ls(&worklane_dir, ids)
actor_from_git,
} => cmd_comment(ticket, body, actor, *actor_from_git, start, by, sink),
Command::Campaign { command } => match command {
CampaignCommand::Add(args) => cmd_campaign_add(args, start, sink),
CampaignCommand::Ls { ids, state } => {
let worklane_dir = find_worklane_dir(start)?;
cmd_campaign_ls(&worklane_dir, *ids, *state, sink)
}
CampaignCommand::Set(args) => cmd_campaign_set(&args, &start),
CampaignCommand::Append(args) => cmd_campaign_append(&args, &start),
CampaignCommand::Set(args) => cmd_campaign_set(args, start, sink),
CampaignCommand::Append(args) => cmd_campaign_append(args, start, sink),
CampaignCommand::Show { campaign } => {
let worklane_dir = find_worklane_dir(&start)?;
cmd_campaign_show(&campaign, &worklane_dir)
let worklane_dir = find_worklane_dir(start)?;
cmd_campaign_show(campaign, &worklane_dir, sink)
}
},
Some(Command::Assign { campaign, ticket, actor }) => {
cmd_assign(&campaign, &ticket, &actor, &start)
}
Command::Assign {
campaign,
ticket,
actor,
actor_from_git,
} => cmd_assign(campaign, ticket, actor, *actor_from_git, start, by, sink),
// The bare form and `ls` are one arm: `worklane tags` was the listing before the
// group existed and the fish completion still calls it that way, so the two
// spellings cannot be allowed to drift into two behaviours.
Some(Command::Tags { command }) => match command {
Command::Tags { command } => match command {
None | Some(TagCommand::Ls) => {
let worklane_dir = find_worklane_dir(&start)?;
cmd_tags(&worklane_dir)
let worklane_dir = find_worklane_dir(start)?;
cmd_tags(&worklane_dir, sink)
}
Some(TagCommand::Add(args)) => cmd_tag_add(&args, &start),
Some(TagCommand::Set(args)) => cmd_tag_set(&args, &start),
Some(TagCommand::Add(args)) => cmd_tag_add(args, start, sink),
Some(TagCommand::Set(args)) => cmd_tag_set(args, start, sink),
},
// No board either, for the reason `install-skill` has none: a completion script
// is generated from the clap definition and is the same wherever it is run.
Some(Command::Completions { shell }) => {
completions::generate(shell, &mut std::io::stdout()).map_err(Into::into)
Command::Completions { shell } => {
completions::generate(*shell, sink.as_write()).map_err(Into::into)
}
// No board is looked for: the point of the skill is to teach an agent worklane
// before there is a `.worklane` anywhere.
Some(Command::InstallSkill { skill, force, print }) => {
cmd_install_skill(skill.as_deref(), force, print)
Command::InstallSkill { skill, force, print } => {
cmd_install_skill(skill.as_deref(), *force, *print, sink)
}
// No board either, and one agent rather than both: opencode loads the tool file,
// Claude Code has no path for one.
Some(Command::InstallTool { force, print }) => cmd_install_tool(force, print),
Command::InstallTool { force, print } => cmd_install_tool(*force, *print, sink),
}
}
@@ -208,6 +257,15 @@ fn run_tui(paths: &[std::path::PathBuf], start: &std::path::Path) -> Result<()>
continue;
}
// And the command prompt, third, on the same contract: while a command is being
// typed `q` is a letter, `d` leaves the columns alone and `tab` stays out of the
// project tabs. It takes the screen because enter runs the command and then has
// to bring the ticket it moved back into view. The rule is `Board::prompt_key`,
// where a test can reach it.
if board.prompt_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
@@ -251,6 +309,12 @@ fn run_tui(paths: &[std::path::PathBuf], start: &std::path::Path) -> Result<()>
// at an open picker is taken by `picker_key` to open the picker's own
// query, so this arm is only ever the way in to the board's prompt.
KeyCode::Char('/') => board.open_search(),
// The way in to the command prompt, and the same single-shot arm `/` is:
// from the next keypress on, `prompt_key` above has the keyboard. A `:`
// typed into either open prompt is a character there and one pressed at an
// open picker is swallowed by it, so this arm is only ever the way in from
// the board itself. Free of every existing binding.
KeyCode::Char(':') => board.open_prompt(),
// `y` as in yank, for the readers this board is for, and the only letter
// 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.
+453
View File
@@ -0,0 +1,453 @@
//! Splitting a typed line into the arguments a parser wants.
//!
//! The prompt on the board takes one string and clap takes an argv, so something has to
//! turn `comment 1b78a24 the offset was never passed` into a verb, a ticket and one body
//! with spaces in it. Splitting on whitespace hands clap five arguments where `comment`
//! takes two, which is not a grammar error to report but a tokenising step nobody ran.
//!
//! The rules are the shell's, because that is what the prompt promises: a line is spelled
//! there exactly as it is spelled in the shell. Runs of whitespace separate arguments,
//! single and double quotes group one, a backslash escapes the next character except
//! inside single quotes where it is a backslash, and an explicitly empty `''` is an
//! argument that exists and is empty — which is what `--title ""` being a usage error
//! rather than a silent clear depends on. A leading hyphen is not special here: whether
//! `--foo` is a flag or the text of a criterion is clap's question, and the prose
//! arguments already accept one.
//!
//! Two things a shell's own splitter does not have to answer, and both are why this is
//! written rather than pulled in:
//!
//! - **A line being typed is half finished.** An unterminated quote is a state to report,
//! not an error to raise, because the prompt has to keep taking characters and refuse
//! only enter. See [`Unclosed`].
//! - **Completion needs to know where the cursor is.** Which argument it sits in, counting
//! from the verb, and whether nothing of that argument lies before it. Both fall out of
//! the scan for free and neither is reachable afterwards from the arguments alone.
//!
//! One pure function over the line and the cursor, and nothing here knows about `Board`.
/// What a line is still inside when it ends.
///
/// A half-typed line is not a line that failed: `comment 1b78a24 "the offset` is a
/// sentence somebody is in the middle of, and the arguments before the quote are already
/// right. So this is a state the caller reports, and the reason enter is refused while it
/// is anything but [`Unclosed::Closed`] — the arguments up to that point are still handed
/// back, because that is what a completion or a hint has to work from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unclosed {
/// Nothing. The arguments are whole and the line can go to a parser.
Closed,
/// A `'` with no `'` after it.
Single,
/// A `"` with no `"` after it.
Double,
/// A trailing `\`, which has nothing yet to escape.
///
/// Not a quote, and reported the same way for the same reason: the character it will
/// escape is the next one typed. It wins over an open quote, being the inner of the
/// two, and either answer refuses the line.
Escape,
}
/// Which quote the scan is inside.
///
/// Private, because what a caller needs is [`Unclosed`], which also carries the state no
/// quote can. Two public spellings of one fact is how they come to disagree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Quote {
Single,
Double,
}
/// One scan of a line: its arguments, where the cursor sits among them, and what the line
/// is still inside.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Split {
/// The arguments, in order, with the quotes and escapes taken off. The binary's own
/// name is not among them: prepending it is the caller's, since only the caller knows
/// what it is calling.
pub args: Vec<String>,
/// Which argument the cursor is in, counting from the verb at 0. Equal to
/// `args.len()` when the cursor is past the last one, which is the index an argument
/// typed next would take.
pub cursor_arg: usize,
/// Whether nothing of `cursor_arg` lies before the cursor, because the line up to it
/// ends in a separator or has nothing in it at all. That is the difference between
/// completing an argument and starting one.
pub at_new_arg: bool,
/// What the line is still inside, and therefore whether it can be run at all.
pub unclosed: Unclosed,
}
/// Split `line` into arguments, reading the cursor at `cursor` as a byte offset into it.
///
/// Bytes because that is what the prompt's own cursor is: a `String` inserts and removes
/// at byte indices. A cursor past the end of the line reads as the end, and one inside a
/// multi-byte character reads as being after that character, so neither can panic and
/// neither needs the caller to have clamped it first.
pub fn split_line(line: &str, cursor: usize) -> Split {
let mut args: Vec<String> = Vec::new();
// `Some("")` is an argument that has been opened and is still empty, which is what
// tells `''` from nothing at all: a bare `take()` cannot make that distinction.
let mut arg: Option<String> = None;
let mut quote: Option<Quote> = None;
let mut escape = false;
// The cursor's answer, taken at the character it falls on and never revised.
let mut at: Option<(usize, bool)> = None;
for (offset, c) in line.char_indices() {
if at.is_none() && offset >= cursor {
at = Some((args.len(), arg.is_none()));
}
if escape {
arg.get_or_insert_default().push(c);
escape = false;
continue;
}
match (quote, c) {
// The shell's exception, and the reason a criterion reading `a\b` survives
// being typed as `'a\b'`: single quotes are literal, backslash included.
(Some(Quote::Single), '\\') => arg.get_or_insert_default().push(c),
(_, '\\') => escape = true,
(None, '\'') => {
quote = Some(Quote::Single);
arg.get_or_insert_default();
}
(None, '"') => {
quote = Some(Quote::Double);
arg.get_or_insert_default();
}
(Some(Quote::Single), '\'') | (Some(Quote::Double), '"') => quote = None,
// A run of separators closes the open argument once and then finds none.
(None, ws) if ws.is_whitespace() => {
if let Some(done) = arg.take() {
args.push(done);
}
}
_ => arg.get_or_insert_default().push(c),
}
}
// Before the last argument is pushed, so a cursor at the end of the line is still in
// the argument it is typing rather than one past it.
let (cursor_arg, at_new_arg) = at.unwrap_or((args.len(), arg.is_none()));
if let Some(last) = arg {
args.push(last);
}
Split {
args,
cursor_arg,
at_new_arg,
unclosed: match (escape, quote) {
(true, _) => Unclosed::Escape,
(false, Some(Quote::Single)) => Unclosed::Single,
(false, Some(Quote::Double)) => Unclosed::Double,
(false, None) => Unclosed::Closed,
},
}
}
#[cfg(test)]
mod tests {
use super::*;
/// One line and everything the scan is supposed to say about it.
///
/// The defaults are the empty line's own answers, so a row states the rule it is about
/// and stays quiet about the rest.
struct Case {
line: &'static str,
/// Where the cursor is, or the end of the line, which is where it sits while a
/// line is being typed. Only the cursor rows move it.
cursor: Option<usize>,
args: &'static [&'static str],
cursor_arg: usize,
at_new_arg: bool,
unclosed: Unclosed,
}
impl Default for Case {
fn default() -> Self {
Case {
line: "",
cursor: None,
args: &[],
cursor_arg: 0,
at_new_arg: true,
unclosed: Unclosed::Closed,
}
}
}
/// Every field of every row, each named in its own failure: a table that reports only
/// the first mismatch makes the next run tell a different story than this one.
fn check(cases: &[Case]) {
for case in cases {
let cursor = case.cursor.unwrap_or(case.line.len());
let split = split_line(case.line, cursor);
let args: Vec<&str> = split.args.iter().map(String::as_str).collect();
let at = format!("{:?} with the cursor at {cursor}", case.line);
assert_eq!(args, case.args, "arguments of {at}");
assert_eq!(split.cursor_arg, case.cursor_arg, "cursor argument of {at}");
assert_eq!(split.at_new_arg, case.at_new_arg, "new argument of {at}");
assert_eq!(split.unclosed, case.unclosed, "unclosed state of {at}");
}
}
#[test]
fn a_line_splits_into_arguments_the_way_a_shell_splits_one() {
check(&[
// Nothing typed yet, which is the state the prompt opens in.
Case::default(),
Case {
line: "tags",
args: &["tags"],
at_new_arg: false,
..Case::default()
},
Case {
line: "mv 1b78a24 --status committed",
args: &["mv", "1b78a24", "--status", "committed"],
cursor_arg: 3,
at_new_arg: false,
..Case::default()
},
// Runs of separators collapse, at either end and in the middle, and a tab is
// one of them.
Case {
line: " mv 1b78a24 ",
args: &["mv", "1b78a24"],
cursor_arg: 2,
..Case::default()
},
Case {
line: "mv\t1b78a24",
args: &["mv", "1b78a24"],
cursor_arg: 1,
at_new_arg: false,
..Case::default()
},
// What the ticket for this was written about: one body, spaces and all.
Case {
line: "comment 1b78a24 \"the offset was never passed\"",
args: &["comment", "1b78a24", "the offset was never passed"],
cursor_arg: 2,
at_new_arg: false,
..Case::default()
},
// Single quotes group the same, and a run of spaces inside one is not a
// separator to collapse.
Case {
line: "comment 1b78a24 'two spaces'",
args: &["comment", "1b78a24", "two spaces"],
cursor_arg: 2,
at_new_arg: false,
..Case::default()
},
// A quote in the middle of an argument groups part of it, which is how a
// `--flag=value` carrying a space is typed.
Case {
line: "set 1b78a24 --title=\"a b\"",
args: &["set", "1b78a24", "--title=a b"],
cursor_arg: 2,
at_new_arg: false,
..Case::default()
},
// A backslash escapes the next character: a separator, a quote, itself.
Case {
line: "comment 1b78a24 a\\ b",
args: &["comment", "1b78a24", "a b"],
cursor_arg: 2,
at_new_arg: false,
..Case::default()
},
Case {
line: "comment 1b78a24 \"she said \\\"no\\\"\"",
args: &["comment", "1b78a24", "she said \"no\""],
cursor_arg: 2,
at_new_arg: false,
..Case::default()
},
Case {
line: "comment 1b78a24 a\\\\b",
args: &["comment", "1b78a24", "a\\b"],
cursor_arg: 2,
at_new_arg: false,
..Case::default()
},
// Except inside single quotes, where it is a character like any other.
Case {
line: "comment 1b78a24 'a\\b'",
args: &["comment", "1b78a24", "a\\b"],
cursor_arg: 2,
at_new_arg: false,
..Case::default()
},
// A leading hyphen is clap's business, not the splitter's.
Case {
line: "add --title --print is supported",
args: &["add", "--title", "--print", "is", "supported"],
cursor_arg: 4,
at_new_arg: false,
..Case::default()
},
// An empty quoted value is an argument that exists and is empty. Losing it
// here would turn a usage error into a silent clear.
Case {
line: "set 1b78a24 --title \"\"",
args: &["set", "1b78a24", "--title", ""],
cursor_arg: 3,
at_new_arg: false,
..Case::default()
},
Case {
line: "''",
args: &[""],
at_new_arg: false,
..Case::default()
},
]);
}
#[test]
fn a_half_typed_line_says_what_it_is_still_inside_and_hands_back_the_rest() {
check(&[
// The arguments before the open quote are already right, and the open one is
// as far as it has been typed.
Case {
line: "comment 1b78a24 \"the offset",
args: &["comment", "1b78a24", "the offset"],
cursor_arg: 2,
at_new_arg: false,
unclosed: Unclosed::Double,
..Case::default()
},
Case {
line: "comment 1b78a24 'the offset",
args: &["comment", "1b78a24", "the offset"],
cursor_arg: 2,
at_new_arg: false,
unclosed: Unclosed::Single,
..Case::default()
},
// A quote just opened is an argument that exists and is empty, the same shape
// a closed `''` leaves.
Case {
line: "comment 1b78a24 \"",
args: &["comment", "1b78a24", ""],
cursor_arg: 2,
at_new_arg: false,
unclosed: Unclosed::Double,
..Case::default()
},
// A trailing backslash has nothing yet to escape. It opened no argument, so
// the cursor is starting one.
Case {
line: "mv 1b78a24 \\",
args: &["mv", "1b78a24"],
cursor_arg: 2,
unclosed: Unclosed::Escape,
..Case::default()
},
// Inside a quote the escape is the inner of the two, and it is what the line
// is waiting on.
Case {
line: "comment 1b78a24 \"a\\",
args: &["comment", "1b78a24", "a"],
cursor_arg: 2,
at_new_arg: false,
unclosed: Unclosed::Escape,
..Case::default()
},
// A closed quote reopened is open again: the state is where the scan ended,
// not how many quotes were typed.
Case {
line: "comment 1b78a24 'a' 'b",
args: &["comment", "1b78a24", "a", "b"],
cursor_arg: 3,
at_new_arg: false,
unclosed: Unclosed::Single,
..Case::default()
},
]);
}
#[test]
fn the_split_says_which_argument_the_cursor_is_in_and_whether_it_begins_one() {
check(&[
// The line is split whole whatever the cursor is doing: only the two cursor
// answers move.
Case {
line: "mv 1b78a24",
cursor: Some(0),
args: &["mv", "1b78a24"],
..Case::default()
},
Case {
line: "mv 1b78a24",
cursor: Some(1),
args: &["mv", "1b78a24"],
at_new_arg: false,
..Case::default()
},
// At the end of the verb, still in the verb: the cursor is completing it.
Case {
line: "mv 1b78a24",
cursor: Some(2),
args: &["mv", "1b78a24"],
at_new_arg: false,
..Case::default()
},
// Past the separator, so the argument at 1 has nothing before the cursor even
// though the line goes on to hold one.
Case {
line: "mv 1b78a24",
cursor: Some(3),
args: &["mv", "1b78a24"],
cursor_arg: 1,
..Case::default()
},
// A cursor past the end of the line reads as the end of it.
Case {
line: "mv",
cursor: Some(99),
args: &["mv"],
at_new_arg: false,
..Case::default()
},
// Inside a quoted argument the cursor is in that argument, not in a fourth
// one the quotes might look like they opened.
Case {
line: "comment 1b78a24 \"the offset\"",
cursor: Some(20),
args: &["comment", "1b78a24", "the offset"],
cursor_arg: 2,
at_new_arg: false,
..Case::default()
},
// Byte offsets, so a multi-byte character before the cursor counts for its
// width and not for one: 8 is where `é` starts and 9 is inside it.
Case {
line: "comment é",
cursor: Some(8),
args: &["comment", "é"],
cursor_arg: 1,
..Case::default()
},
// A cursor inside a character reads as being after it, which is the answer
// that cannot claim an argument has not started when it has.
Case {
line: "comment é",
cursor: Some(9),
args: &["comment", "é"],
cursor_arg: 1,
at_new_arg: false,
..Case::default()
},
]);
}
}
+4824 -295
View File
File diff suppressed because it is too large Load Diff
+1338 -120
View File
File diff suppressed because it is too large Load Diff
+14
View File
@@ -574,6 +574,12 @@ fn chmod(path: &Path, mode: u32) {
/// itself, and it is named with the ticket and the path rather than raised as a bare io
/// error. The branch this replaces could not fire at all: the filename carries a fresh
/// uuid, and its message claimed the title was taken.
///
/// The add stages through `write_then_replace` like every other write, so the temp
/// lives under `.worklane/`, outside the directory the chmod keeps closed, and the
/// rename is the step that fails here. Both halves have to be gone afterwards: no half
/// ticket in backlog, and no `.wl-*.tmp` beside it, which is what `stray_files` checks
/// for a move.
#[test]
fn add_names_the_ticket_and_the_path_when_the_write_fails() {
let temp = TempDir::new().unwrap();
@@ -596,6 +602,14 @@ fn add_names_the_ticket_and_the_path_when_the_write_fails() {
chmod(&backlog, 0o755);
assert_eq!(fs::read_dir(&backlog).unwrap().count(), 0);
let strays: Vec<String> = fs::read_dir(&worklane)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().into_string().unwrap())
.filter(|name| name.starts_with(".wl-"))
.collect();
assert_eq!(strays, Vec::<String>::new(), "the staging file was left behind");
}
/// The board above the project is real and empty, and stays empty: a dangling
+160 -5
View File
@@ -131,6 +131,21 @@ fn stderr(out: &std::process::Output) -> String {
String::from_utf8_lossy(&out.stderr).to_string()
}
/// A listing with its column padding collapsed, for an assertion about what a row says
/// rather than about where its columns sit.
///
/// The alignment is the subject of `campaign_ls_lines_its_columns_up_whatever_the_titles_are`
/// and of the colour test beside `cmd_campaign_ls`; every other test is about the words,
/// and one that spelled the padding out would have to be edited whenever a fixture gained
/// a longer title.
fn squeezed(listing: &str) -> String {
listing
.lines()
.map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
.collect::<Vec<_>>()
.join("\n")
}
fn find(worklane: &Path, uuid: &str) -> PathBuf {
for status in ["backlog", "committed", "reviewing", "done"] {
for entry in fs::read_dir(worklane.join(status))
@@ -247,7 +262,17 @@ fn nothing_is_created_without_a_title() {
fn init_creates_the_campaigns_directory() {
let temp = TempDir::new().unwrap();
let out = run(&temp, &["init"]);
// Isolated HOME and XDG so `init` cannot decide on a real machine's boards config:
// the board has to be local no matter whose machine runs the suite.
let mut init = Command::cargo_bin(BIN_NAME).unwrap();
let out = init
.current_dir(temp.path())
.env("HOME", temp.path())
.env("XDG_CONFIG_HOME", temp.path().join("config"))
.env("XDG_DATA_HOME", temp.path().join("data"))
.arg("init")
.output()
.unwrap();
assert!(out.status.success(), "{}", stderr(&out));
assert!(temp.child(".worklane").child("campaigns").path().is_dir());
@@ -423,7 +448,7 @@ fn campaign_ls_lists_campaigns_with_their_member_counts() {
let out = run(&temp, &["campaign", "ls"]);
assert!(out.status.success(), "{}", stderr(&out));
let listing = stdout(&out);
let listing = squeezed(&stdout(&out));
// One of the two members is in done, so the campaign is open and half finished.
assert!(listing.contains("v1 release | 1/2 done [open]"), "{listing}");
// Nothing has been filed against the other one.
@@ -471,6 +496,136 @@ fn campaign_ls_ids_says_nothing_on_a_board_with_no_campaigns() {
assert!(stdout(&run(&temp, &["campaign", "ls"])).contains("No campaigns yet"));
}
/// The state filter, against the same three answers `Standing::state` gives: a campaign
/// with work left, one with none, and one nothing has been filed against.
#[test]
fn campaign_ls_state_lists_only_the_campaigns_in_that_state() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
// v1 holds a backlog member and v2 holds a done one, so the two are open and done.
run(&temp, &["assign", "v1 release", MEMBER]);
run(&temp, &["assign", "v2 release", OTHER]);
run(&temp, &["campaign", "add", "--title", "Nothing filed yet"]);
let open = squeezed(&stdout(&run(&temp, &["campaign", "ls", "--state", "open"])));
assert!(open.contains("v1 release | 0/1 done [open]"), "{open}");
assert!(!open.contains("v2 release"), "a done campaign was listed as open: {open}");
assert!(!open.contains("Nothing filed yet"), "{open}");
let done = squeezed(&stdout(&run(&temp, &["campaign", "ls", "--state", "done"])));
assert!(done.contains("v2 release | 1/1 done [done]"), "{done}");
assert!(!done.contains("v1 release"), "{done}");
// The third value, which is what makes every campaign on the board reachable: a
// memberless one is neither open nor done, deliberately, and it is the one a
// grooming sweep is looking for.
let empty = squeezed(&stdout(&run(&temp, &["campaign", "ls", "--state", "empty"])));
assert!(empty.contains("Nothing filed yet | no members"), "{empty}");
assert!(!empty.contains("v1 release"), "{empty}");
assert!(!empty.contains("v2 release"), "{empty}");
// And it reaches the machine-readable listing the way `ls --ids` keeps its filters.
let ids = stdout(&run(&temp, &["campaign", "ls", "--ids", "--state", "empty"]));
assert_eq!(ids.lines().count(), 1, "{ids}");
assert!(ids.contains("Nothing filed yet"), "{ids}");
}
/// A value the enum does not hold is clap's to refuse, so nothing is read and the exit
/// code is the usage error's.
#[test]
fn campaign_ls_refuses_a_state_that_is_not_one() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
let out = run(&temp, &["campaign", "ls", "--state", "backlog"]);
assert_eq!(out.status.code(), Some(2), "{}", stderr(&out));
let said = stderr(&out);
assert!(said.contains("open"), "{said}");
assert!(said.contains("empty"), "{said}");
}
/// A filter that matches nothing says so and names what was asked for. Going silent
/// would read as the other empty case, a board with no campaigns on it, which has a
/// message of its own.
#[test]
fn campaign_ls_says_when_the_filter_matched_nothing() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
let out = run(&temp, &["campaign", "ls", "--state", "done"]);
assert!(out.status.success(), "{}", stderr(&out));
let said = stdout(&out);
assert!(said.contains("--state done"), "the filter is not named: {said}");
assert!(!said.contains("No campaigns yet"), "the other empty case: {said}");
// The completion path stays silent, filtered or not.
assert_eq!(stdout(&run(&temp, &["campaign", "ls", "--ids", "--state", "done"])), "");
}
/// The columns line up whatever the titles are, which is what the padding is for. The
/// fixture's two titles are the same length, so this one files a third with a long title
/// and a codename: the row that pushes the column is the row that proves it moved for
/// every other row too.
#[test]
fn campaign_ls_lines_its_columns_up_whatever_the_titles_are() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
run(
&temp,
&[
"campaign",
"add",
"--title",
"A campaign with a much longer title than the others",
"--codename",
"beaver",
],
);
run(&temp, &["assign", "v1 release", MEMBER]);
let listing = stdout(&run(&temp, &["campaign", "ls"]));
let rows: Vec<&str> = listing.lines().filter(|line| line.contains(" | ")).collect();
assert_eq!(rows.len(), 3, "{listing}");
for column in [" (", " | "] {
let offsets: Vec<Option<usize>> = rows.iter().map(|row| row.find(column)).collect();
assert!(
offsets.iter().all(|at| *at == offsets[0]),
"`{column}` is ragged across the rows:\n{listing}"
);
}
// The state sits at one offset too, on the rows that have one: a campaign with no
// members has nothing in brackets and pads to where the next row's bracket is.
let states: Vec<Option<usize>> = rows
.iter()
.filter(|row| row.contains('['))
.map(|row| row.find('['))
.collect();
assert!(!states.is_empty(), "no row carried a state: {listing}");
assert!(
states.iter().all(|at| *at == states[0]),
"the state column is ragged:\n{listing}"
);
}
/// The created stamp the campaign file already carries, in the form `ls` prints one in
/// rather than a second spelling of a date.
#[test]
fn campaign_ls_shows_the_created_date() {
let temp = TempDir::new().unwrap();
let _worklane = board(&temp);
let listing = stdout(&run(&temp, &["campaign", "ls"]));
assert!(listing.contains("26-08-21:02"), "no created stamp: {listing}");
// Not in the machine-readable listing, which is the id and the title and nothing else.
let ids = stdout(&run(&temp, &["campaign", "ls", "--ids"]));
assert!(!ids.contains("26-08-21"), "{ids}");
}
/// A campaign is done when it holds members and every one of them is done. An empty one
/// is neither, which is why it reads `no members` rather than `0/0 done`.
#[test]
@@ -480,7 +635,7 @@ fn a_campaign_whose_every_member_is_done_reads_done() {
run(&temp, &["assign", "v1 release", OTHER]);
let listing = stdout(&run(&temp, &["campaign", "ls"]));
let listing = squeezed(&stdout(&run(&temp, &["campaign", "ls"])));
assert!(listing.contains("v1 release | 1/1 done [done]"), "{listing}");
}
@@ -1716,13 +1871,13 @@ fn a_discarded_member_counts_as_finished() {
run(&temp, &["assign", "v1 release", OTHER]);
// Two members, one done and one in the backlog: open and half finished.
let listing = stdout(&run(&temp, &["campaign", "ls"]));
let listing = squeezed(&stdout(&run(&temp, &["campaign", "ls"])));
assert!(listing.contains("v1 release | 1/2 done [open]"), "{listing}");
let discarded = run(&temp, &["mv", MEMBER, "--status", "discarded"]);
assert!(discarded.status.success(), "{}", stderr(&discarded));
let listing = stdout(&run(&temp, &["campaign", "ls"]));
let listing = squeezed(&stdout(&run(&temp, &["campaign", "ls"])));
assert!(listing.contains("v1 release | 2/2 done [done]"), "{listing}");
}
+46
View File
@@ -262,6 +262,52 @@ fn the_actor_flag_overrides_the_variable() {
assert!(only_comment(&worklane, &uuid).contains("**Author**: opencode"));
}
/// The flag for acting on the person's behalf: their name is what the machine already
/// knows, so the entry does not have to wait for the agent to know it too.
#[test]
fn the_actor_from_git_flag_names_the_git_user_over_the_variable() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let uuid = create_ticket(&worklane, "backlog", "From Git Test");
Command::cargo_bin(BIN_NAME)
.unwrap()
.current_dir(temp.path())
.env("WORKLANE_ACTOR", "claude")
.env("GIT_CONFIG_GLOBAL", git_config_naming(&temp, "Configured User"))
.env("GIT_CONFIG_NOSYSTEM", "1")
.arg("comment")
.args([&uuid, "Written for the person"])
.arg("--actor-from-git")
.assert()
.success();
assert!(only_comment(&worklane, &uuid).contains("**Author**: Configured User"));
}
/// The lift is not a fallback: with no git user configured there is nobody to name, and
/// the entry reads unknown rather than quietly attributing back to the agent.
#[test]
fn from_git_with_no_git_user_is_unknown_even_with_the_variable() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let uuid = create_ticket(&worklane, "backlog", "No Git User Test");
Command::cargo_bin(BIN_NAME)
.unwrap()
.current_dir(temp.path())
.env("WORKLANE_ACTOR", "claude")
.env("GIT_CONFIG_GLOBAL", temp.path().join("no-such-gitconfig"))
.env("GIT_CONFIG_NOSYSTEM", "1")
.arg("comment")
.args([&uuid, "Written with nobody to name"])
.arg("--actor-from-git")
.assert()
.success();
assert!(only_comment(&worklane, &uuid).contains("**Author**: unknown"));
}
/// An empty variable counts as unset, the convention `NO_COLOR` follows, so a wrapper
/// script can clear an inherited one and get the git user back.
#[test]
+234
View File
@@ -68,6 +68,240 @@ fn fish_is_offered_every_status() {
assert!(out.contains("-a 'backlog committed reviewing done discarded' -d status"));
}
/// A board holding one ticket and one tag, for the rules whose values come off a board.
///
/// Returned with the ticket's id and the tag, since the assertions are that those exact
/// strings are what fish offers.
fn board() -> (assert_fs::TempDir, String, String) {
let temp = assert_fs::TempDir::new().unwrap();
let mut init = Command::cargo_bin(BIN_NAME).unwrap();
// Isolated HOME and XDG so `init` cannot decide on a real machine's boards config:
// the board has to be local no matter whose machine runs the suite.
init.current_dir(temp.path())
.env("HOME", temp.path())
.env("XDG_CONFIG_HOME", temp.path().join("config"))
.env("XDG_DATA_HOME", temp.path().join("data"))
.arg("init")
.assert()
.success();
let mut add = Command::cargo_bin(BIN_NAME).unwrap();
add.current_dir(temp.path())
.args(["add", "--title", "A ticket to complete", "--tags", "atag"])
.assert()
.success();
let mut ls = Command::cargo_bin(BIN_NAME).unwrap();
let listed = ls
.current_dir(temp.path())
.args(["ls", "--ids"])
.assert()
.success();
let listed = String::from_utf8(listed.get_output().stdout.clone()).unwrap();
let id = listed.split('\t').next().unwrap().trim().to_string();
(temp, id, "atag".to_string())
}
/// What fish would actually offer for a half-typed line, or `None` when fish is absent.
///
/// `complete -C` is fish's own answer to "what are the candidates here", so this asks the
/// question a person at a prompt asks rather than searching the script for the rule that
/// ought to produce the answer. Each candidate is a name and, after a tab, its description.
///
/// **The shell is pointed at the binary under test and stood in a real board**, which is
/// what makes the dynamic half testable at all: its rules are command substitutions calling
/// `worklane ls --ids` and `worklane tags`, so with no board and no binary they return
/// nothing and every assertion about them would pass on an empty answer. The directory of
/// `CARGO_BIN_EXE_worklane` goes on the front of PATH so the substitution runs this build
/// rather than whatever is installed.
///
/// **`fish_complete_path` is emptied first, and without that line this test cannot fail.**
/// `complete -C` autoloads completions for the command it is asked about, so a developer
/// who has ever run `worklane completions fish > ~/.config/fish/completions/worklane.fish`
/// gets that file merged into the answer. It was written by some earlier version of this
/// binary and answers for whatever the rules used to be: the first draft of this test
/// passed against a deliberately broken scope because the installed copy still had the
/// working one. Emptying the path is what makes the sourced script the only source.
fn candidates(board: &assert_fs::TempDir, line: &str) -> Option<Vec<String>> {
// Beside the board rather than in it: a rule that fires nothing falls back to listing
// the directory, and a script sitting in there would appear among the candidates and
// read like an answer.
let holder = assert_fs::TempDir::new().unwrap();
let path = holder.path().join("worklane.fish");
std::fs::write(&path, script("fish")).unwrap();
let bin_dir = std::path::Path::new(BIN_NAME).parent().unwrap();
let inherited = std::env::var("PATH").unwrap_or_default();
let asked = std::process::Command::new("fish")
.current_dir(board.path())
.env("PATH", format!("{}:{inherited}", bin_dir.display()))
.arg("-c")
.arg(format!(
"set fish_complete_path; source {}; complete -C '{line}'",
path.display()
))
.output();
match asked {
Ok(out) => Some(
String::from_utf8_lossy(&out.stdout)
.lines()
.map(str::to_string)
.collect(),
),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
Err(err) => panic!("could not run fish: {err}"),
}
}
/// The name half of a candidate, dropping the description fish takes after the tab.
fn names(candidates: &[String]) -> Vec<&str> {
candidates
.iter()
.map(|line| line.split('\t').next().unwrap_or(line))
.collect()
}
/// **Ask fish what it offers, instead of asserting that the rule that should make it
/// offer that is in the file.**
///
/// Every other test here reads the script as text, which cannot tell a rule that fires
/// from one whose condition stopped matching. That is how a completion actually breaks:
/// the clap definition moves, a list or a `__worklane_command_is` scope no longer names
/// anything, and the rule sits in the file offering nothing. Loading it into a real fish
/// and asking for the candidates is the only check that can see the difference.
///
/// **Asserting the values, not only the names, is the point.** clap emits every option's
/// name on its own, so `--tags` and `--blocked-by` are offered whether or not the dynamic
/// half loaded: an assertion that they appear passes with every hand-written rule deleted.
/// What those rules add is the candidates *after* the flag, and that is what is pinned
/// here, against the board `board()` puts under the shell.
///
/// Descriptions are read off deliberately and not asserted: every option carrying a
/// hand-written rule currently loses the help text clap gave it, which is its own ticket
/// rather than something to pin as correct here.
///
/// **Skipped when fish is not on PATH, and it says so.** There is no CI here and fish is
/// the shell this tool is written for, so failing a machine that never had it would be a
/// guard nobody could satisfy. A missing fish means the check did not run, not that it
/// passed.
#[test]
fn fish_offers_the_commands_the_statuses_and_the_values() {
let (temp, id, tag) = board();
let Some(commands) = candidates(&temp, "worklane ") else {
eprintln!("skipped: fish is not on PATH, so nothing asked it for candidates");
return;
};
for command in [
"add", "ls", "show", "mv", "set", "append", "relate", "campaign",
] {
assert!(
names(&commands).contains(&command),
"`worklane <TAB>` never offers {command}"
);
}
// The `ls` status positional, which clap emits nothing for, so this answer comes from
// the dynamic half alone and an empty one means that half stopped loading.
let statuses = candidates(&temp, "worklane ls ").unwrap();
for status in ["backlog", "committed", "reviewing", "done", "discarded"] {
assert!(
names(&statuses).contains(&status),
"`worklane ls <TAB>` never offers {status}"
);
}
let shells = candidates(&temp, "worklane completions ").unwrap();
for shell in ["fish", "bash", "zsh"] {
assert!(
names(&shells).contains(&shell),
"`worklane completions <TAB>` never offers {shell}"
);
}
// Every rule whose values come off the board, one per list it is generated from.
let ticket_value = [
("worklane show ", "TICKET_COMMANDS"),
("worklane chown alice ", "TICKET_SECOND_COMMANDS"),
("worklane relate --blocked-by ", "TICKET_FLAGS"),
("worklane chown --clear ", "the chown --clear rule"),
];
for (line, list) in ticket_value {
let offered = candidates(&temp, line).unwrap();
assert!(
names(&offered).contains(&id.as_str()),
"`{line}<TAB>` never offers the one ticket on the board, so {list} is not reaching it: {offered:?}"
);
}
let tag_value = [
("worklane ls --tag ", "TAG_FLAGS"),
("worklane append --tags ", "TAG_FLAGS"),
("worklane tags set ", "TAG_NESTED_COMMANDS"),
];
for (line, list) in tag_value {
let offered = candidates(&temp, line).unwrap();
assert!(
names(&offered).contains(&tag.as_str()),
"`{line}<TAB>` never offers the one tag on the board, so {list} is not reaching it: {offered:?}"
);
}
}
/// **The script is handed to fish, which parses it without running it.**
///
/// The fish half is a hand-written `format!` string carrying single quotes, command
/// substitutions and backslash line continuations, and every text assertion in this file
/// is a `contains`, which a broken script satisfies exactly as well as a correct one.
/// `--no-execute` is the parse without the run.
///
/// **What it catches is a script that does not parse**: quotes still open at the end of
/// the file, an unclosed block. That is narrower than it sounds and the limit is worth
/// writing down, because it was measured rather than assumed. An apostrophe interpolated
/// into a `-d` description partway down the file re-balances against the next quote and
/// parses, corrupting every rule in between while this test passes; the same apostrophe in
/// the *last* rule reaches the end unbalanced and is caught. So this is a floor, not an
/// oracle, and `fish_offers_the_commands_the_statuses_and_the_flags` is the one that reads
/// what the rules actually do.
///
/// Only fish, because only fish gets a hand-written half. What the other four shells are
/// given is clap's output whole, which `no_other_shell_gets_the_fish_half` pins, so a
/// syntax error there would be clap's bug and not this repo's to catch.
///
/// **Skipped when fish is not on PATH, and it says so.** The trade is deliberate: there is
/// no CI here and fish is the shell this tool is written for, so failing a machine that
/// never had it would be a guard nobody could satisfy. A missing fish means the check did
/// not run, not that it passed.
#[test]
fn fish_parses_the_script_it_is_given() {
let temp = assert_fs::TempDir::new().unwrap();
let path = temp.path().join("worklane.fish");
std::fs::write(&path, script("fish")).unwrap();
let parsed = std::process::Command::new("fish")
.arg("--no-execute")
.arg(&path)
.output();
let out = match parsed {
Ok(out) => out,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
eprintln!("skipped: fish is not on PATH, so the generated script went unparsed");
return;
}
Err(err) => panic!("could not run fish: {err}"),
};
assert!(
out.status.success(),
"fish refuses the script `worklane completions fish` writes:\n{}",
String::from_utf8_lossy(&out.stderr)
);
}
#[test]
fn an_unknown_shell_is_a_usage_error() {
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
+359
View File
@@ -0,0 +1,359 @@
//! `worklane init` and the shared-board decision table (c6a61b4).
//!
//! A project is on one of two layouts: the local `.worklane` directory every project
//! always had, or the shared one where the project carries a committed `.worklane.toml`,
//! the board lives in a machine-level boards directory, and `.worklane` is a symlink
//! into it. The machine config decides the default, and the pointer decides where the
//! project already is. The tests below walk the whole table: one per row, the three
//! symlink states, and the standalone path.
//!
//! Every test runs on an isolated machine: `HOME` and the XDG variables point into the
//! temp directory, so the suite can never read or write a real config or boards
//! directory, and a `find_worklane_dir` walk from the project can never climb into one.
use assert_cmd::Command;
use assert_fs::TempDir;
use assert_fs::fixture::{PathChild, PathCreateDir};
use std::fs;
use std::path::{Path, PathBuf};
const BIN_NAME: &str = env!("CARGO_BIN_EXE_worklane");
/// A project with no pointer and no board, ready for `init` to decide on.
fn project(temp: &TempDir) -> PathBuf {
temp.child("project").create_dir_all().unwrap();
temp.child("project").path().to_path_buf()
}
fn run(project: &Path, machine: &TempDir, args: &[&str]) -> std::process::Output {
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(project)
.env("HOME", machine.path())
.env("XDG_CONFIG_HOME", machine.path().join(".config"))
.env("XDG_DATA_HOME", machine.path().join(".local/share"))
.args(args);
cmd.assert().get_output().clone()
}
fn stdout(out: &std::process::Output) -> String {
String::from_utf8_lossy(&out.stdout).to_string()
}
fn stderr(out: &std::process::Output) -> String {
String::from_utf8_lossy(&out.stderr).to_string()
}
/// The boards directory of a machine, under its data dir.
fn boards_dir(machine: &TempDir) -> PathBuf {
machine.path().join(".local/share/worklane/boards")
}
/// The board a pointer names when the machine holds it.
fn board_path(machine: &TempDir, uuid: &str, slug: &str) -> PathBuf {
boards_dir(machine).join(format!("{uuid}_{slug}"))
}
/// The machine config, without which a no-pointer project stays on the local layout.
///
/// Carries only the boards repo url; the boards directory defaults under the machine's
/// data dir, which is where these tests put it.
fn with_boards_config(machine: &TempDir) {
let config = machine.path().join(".config/worklane/config.toml");
fs::create_dir_all(config.parent().unwrap()).unwrap();
fs::write(config, "[boards]\nurl = \"git@example:worklane/boards\"\n").unwrap();
}
/// The committed pointer naming a board by uuid. This is the only thing that puts a
/// project on the shared layout.
fn write_pointer(project: &Path, uuid: &str) {
fs::write(project.join(".worklane.toml"), format!("[worklane]\nboard = \"{uuid}\"\n")).unwrap();
}
/// A board directory in the machine's boards repo, named `<uuid>_<slug>`.
fn with_board(machine: &TempDir, uuid: &str, slug: &str) -> PathBuf {
let board = board_path(machine, uuid, slug);
fs::create_dir_all(&board).unwrap();
board
}
/// The relative spelling init gives a `.worklane` symlink, used to build the states a
/// project can already be in.
fn link_target(project: &Path, board: &Path) -> String {
let base = project;
let common = base
.components()
.zip(board.components())
.take_while(|(a, b)| a == b)
.count();
let mut up = String::new();
for _ in common..base.components().count() {
up.push_str("../");
}
let mut rest = String::new();
for component in board.components().skip(common) {
rest.push_str(&component.as_os_str().to_string_lossy());
rest.push('/');
}
format!("{up}{rest}").trim_end_matches('/').to_string()
}
fn symlink_to(project: &Path, target: &str) {
std::os::unix::fs::symlink(target, project.join(".worklane")).unwrap();
}
fn boards_of(machine: &TempDir) -> Vec<PathBuf> {
fs::read_dir(boards_dir(machine))
.unwrap()
.map(|entry| entry.unwrap().path())
.collect()
}
/// The standalone path, and the reason it has to stay: every project written before the
/// shared layout existed, and every project whose machine has no boards config, must
/// still get exactly the board `init` always made.
#[test]
fn no_pointer_no_config_and_no_boards_repo_makes_a_local_board() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(
stdout(&out),
format!("Initialized worklane in: {}\n", project.join(".worklane").display())
);
assert!(
fs::symlink_metadata(project.join(".worklane")).unwrap().is_dir(),
".worklane must be a real directory"
);
assert!(!project.join(".worklane.toml").exists(), "no pointer on a local board");
for dir in [
"backlog",
"committed",
"reviewing",
"done",
"discarded",
"campaigns",
] {
assert!(project.join(".worklane").join(dir).is_dir(), "local board missing {dir}");
}
}
/// The pointer is committed and carries only the board by uuid, nowhere for a home
/// directory or a server address to hide.
#[test]
fn a_shared_init_commits_a_pointer_carrying_only_the_uuid() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
let output = stdout(&out);
assert!(output.contains("Initialized shared worklane in: "), "{output}");
assert!(output.contains("Board pointer: "), "{output}");
assert!(
output.contains(&format!("Linked {} to it", project.join(".worklane").display())),
"{output}"
);
let board = output
.lines()
.next()
.unwrap()
.trim_start_matches("Initialized shared worklane in: ")
.to_string();
let uuid = Path::new(&board)
.file_name()
.unwrap()
.to_str()
.unwrap()
.split('_')
.next()
.unwrap();
let pointer = fs::read_to_string(project.join(".worklane.toml")).unwrap();
assert_eq!(pointer, format!("[worklane]\nboard = \"{uuid}\"\n"));
assert!(
!pointer.contains(machine.path().to_str().unwrap()),
"no home path in the pointer"
);
assert!(!pointer.contains("git@"), "no server address in the pointer");
}
/// A pointer whose board is present is the state a fresh clone is in: `.worklane` is
/// missing and nothing else is. init links it and creates nothing.
#[test]
fn pointer_with_the_board_present_symlinks_it_and_creates_nothing() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
let board = with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
let before = fs::read_to_string(project.join(".worklane.toml")).unwrap();
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
assert!(
stdout(&out).contains(&format!("Linked {} to it", project.join(".worklane").display()))
);
assert_eq!(
fs::canonicalize(project.join(".worklane")).unwrap(),
fs::canonicalize(&board).unwrap()
);
assert_eq!(fs::read_to_string(project.join(".worklane.toml")).unwrap(), before);
assert_eq!(boards_of(&machine).len(), 1, "no second board was created");
}
/// A pointer whose board is absent is an unsynced machine, and creating a second board
/// there is the worst outcome in the design. init refuses, and `--create` is the only
/// way to make one.
#[test]
fn pointer_with_the_board_absent_refuses_and_create_is_the_only_way() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "abcd5678-abcd-4bcd-abcd-abcdabcdabcd");
with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "other");
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(
err.contains("holds no board for abcd5678-abcd-4bcd-abcd-abcdabcdabcd."),
"{err}"
);
assert!(err.contains("`worklane init --create`"), "{err}");
assert!(!project.join(".worklane").exists(), "nothing was linked");
assert_eq!(boards_of(&machine).len(), 1, "no board was created");
let out = run(&project, &machine, &["init", "--create"]);
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(
fs::canonicalize(project.join(".worklane")).unwrap(),
fs::canonicalize(board_path(&machine, "abcd5678-abcd-4bcd-abcd-abcdabcdabcd", "project"))
.unwrap()
);
}
/// The boards directory itself is gone: that is an uncloned boards repo, not a missing
/// board, and the two must be told apart.
#[test]
fn boards_repo_missing_is_said_as_such() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(err.contains("does not exist"), "{err}");
assert!(err.contains("boards repo that is not cloned here"), "{err}");
}
/// The correct symlink in place is the layout already there: init reports no change and
/// writes nothing.
#[test]
fn correct_symlink_already_in_place_reports_no_change() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
let board = with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
symlink_to(&project, &link_target(&project, &board));
let before = fs::read_to_string(project.join(".worklane.toml")).unwrap();
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
assert!(stdout(&out).starts_with("worklane already initialized in: "));
assert_eq!(fs::read_to_string(project.join(".worklane.toml")).unwrap(), before);
assert_eq!(boards_of(&machine).len(), 1, "nothing was written");
}
/// A symlink pointing at a different board is a project on the wrong board, and changing
/// what a project is on without asking is how two machines disagree about the work.
#[test]
fn symlink_to_a_different_board_refuses_rather_than_repointing() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
let other = with_board(&machine, "99999999-9999-4999-8999-999999999999", "other");
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
let other_target = link_target(&project, &other);
symlink_to(&project, &other_target);
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(err.contains("already links to"), "{err}");
assert!(err.contains("not to the board"), "{err}");
assert_eq!(
fs::read_link(project.join(".worklane")).unwrap(),
PathBuf::from(&other_target)
);
}
/// A symlink that resolves to nothing is neither the layout init places nor a board: it
/// is not replaced without asking.
#[test]
fn symlink_that_dangles_is_not_replaced() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
symlink_to(&project, "nowhere-anyone-knows");
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(err.contains("nowhere-anyone-knows, which does not exist"), "{err}");
assert_eq!(
fs::read_link(project.join(".worklane")).unwrap(),
PathBuf::from("nowhere-anyone-knows")
);
}
/// A real `.worklane` directory under a pointer is a board from before the shared
/// layout, and it is never walked over; the refusal names the adopt path.
#[test]
fn real_worklane_directory_under_a_pointer_refuses_and_names_the_adopt_path() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "project");
fs::create_dir_all(project.join(".worklane").join("backlog")).unwrap();
fs::write(project.join(".worklane").join("backlog").join("b.md"), "# anything\n").unwrap();
let out = run(&project, &machine, &["init"]);
assert!(!out.status.success());
let err = stderr(&out);
assert!(err.contains("is a real directory"), "{err}");
assert!(err.contains("adopt"), "{err}");
assert!(
project.join(".worklane").join("backlog").join("b.md").is_file(),
"the pre-existing board was left intact"
);
}
/// The slug, and only the slug, may change: resolution is a uuid prefix match, so
/// renaming a board breaks no committed pointer.
#[test]
fn renaming_a_board_slug_breaks_no_pointer() {
let machine = TempDir::new().unwrap();
let project = project(&machine);
with_boards_config(&machine);
write_pointer(&project, "12345678-1234-1234-1234-1234567890ab");
let renamed = with_board(&machine, "12345678-1234-1234-1234-1234567890ab", "new-name");
let out = run(&project, &machine, &["init"]);
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(
fs::canonicalize(project.join(".worklane")).unwrap(),
fs::canonicalize(&renamed).unwrap()
);
}
+81 -2
View File
@@ -114,14 +114,16 @@ fn ls_with_invalid_status_fails() {
.failure();
}
/// Title is the last tiebreak, so the three share a due date and a priority: anything
/// else here would be testing the due order instead, which has its own case.
#[test]
fn ls_listed_tickets_sorted_alphabetically() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane, "backlog", "Zebra", "alice", "2026-06-01");
create_ticket(&worklane, "backlog", "Apple", "bob", "2026-07-01");
create_ticket(&worklane, "backlog", "Mango", "charlie", "2026-08-01");
create_ticket(&worklane, "backlog", "Apple", "bob", "2026-06-01");
create_ticket(&worklane, "backlog", "Mango", "charlie", "2026-06-01");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path())
@@ -744,6 +746,32 @@ fn create_stamped_ticket(
.unwrap();
}
/// A backlog ticket with the due date that column is ordered by.
///
/// Backlog only, the way [`create_stamped_ticket`] is one status at a time: the due is
/// what stands in for an entry stamp in the one column that has none, and `_Not set_`
/// passed here is the undated case rather than a separate helper.
fn create_due_ticket(
worklane_dir: &std::path::Path,
title: &str,
uuid: &str,
priority: &str,
due: &str,
) {
let body = format!(
"# {title}\n\n## Metadata\n\n- **ID**: {uuid}\n- **Priority**: {priority}\n\
- **Tags**: test\n- **Due**: {due}\n- **Owner**: alice\n\
- **Status**: backlog\n"
);
fs::write(
worklane_dir
.join("backlog")
.join(format!("{uuid}_{}.md", slug(title))),
body,
)
.unwrap();
}
fn positions(stdout: &str, titles: [&str; 3]) -> Vec<usize> {
titles
.iter()
@@ -828,6 +856,57 @@ fn ls_orders_done_by_the_newest_entry_stamp() {
assert!(seen[0] < seen[1] && seen[1] < seen[2], "{stdout}");
}
/// The backlog has no entry stamp, so the due date is its clock and the soonest deadline
/// heads the column. The p1 here is due last and is listed last, which is exactly what
/// priority alone got wrong.
#[test]
fn ls_orders_the_backlog_by_the_soonest_due_date() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let at = |n: u8| format!("dddd000{n}-0000-0000-0000-000000000001");
create_due_ticket(&worklane, "Soonest", &at(1), "5", "2026-09-01");
create_due_ticket(&worklane, "Latest", &at(2), "1", "2026-09-03");
create_due_ticket(&worklane, "Between", &at(3), "3", "2026-09-02");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path()).args(["ls", "backlog"]);
let stdout = get_stdout(&mut cmd);
let seen = positions(&stdout, ["Soonest", "Between", "Latest"]);
assert!(seen[0] < seen[1] && seen[1] < seen[2], "{stdout}");
// The overview lists the same column, so it has to agree with the narrowed listing
// rather than falling back to priority for the same tickets.
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path()).arg("ls");
let overview = get_stdout(&mut cmd);
let seen = positions(&overview, ["Soonest", "Between", "Latest"]);
assert!(seen[0] < seen[1] && seen[1] < seen[2], "{overview}");
}
/// A due nobody promised must not outrank one somebody did. The undated ticket here is
/// the most urgent of the three and still trails both, and among the dated ones the
/// equal due falls through to priority.
#[test]
fn ls_sinks_an_undated_backlog_ticket_below_the_dated_ones() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let at = |n: u8| format!("eeee000{n}-0000-0000-0000-000000000001");
create_due_ticket(&worklane, "Undated", &at(1), "1", "_Not set_");
create_due_ticket(&worklane, "Urgent", &at(2), "3", "2026-09-01");
create_due_ticket(&worklane, "Relaxed", &at(3), "5", "2026-09-01");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(temp.path()).args(["ls", "backlog"]);
let stdout = get_stdout(&mut cmd);
let seen = positions(&stdout, ["Urgent", "Relaxed", "Undated"]);
assert!(seen[0] < seen[1] && seen[1] < seen[2], "{stdout}");
}
/// A missing stamp is unknown, not ancient, so it sinks below every stamped ticket
/// rather than claiming the head of the queue. Every ticket on a board older than the
/// stamps is one of these.
+200 -13
View File
@@ -702,9 +702,10 @@ fn move_ticket(temp: &TempDir, ticket: &str, status: &str, force: bool) -> std::
}
/// Refused, and nothing written: not the rename, not the Status field, not a stray
/// temp file. The blocker is named with its status, since that is what has to change.
/// temp file. The blocker is named with its status, since that is what has to change,
/// and the move names the status it was for, since that is what decides the refusal.
#[test]
fn mv_refuses_a_move_while_a_blocker_is_open() {
fn mv_refuses_a_move_past_a_blocker() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = create_gated_pair(&worklane, &temp, "backlog");
@@ -715,6 +716,7 @@ fn mv_refuses_a_move_while_a_blocker_is_open() {
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("blocked by"), "{stderr}");
assert!(stderr.contains("to committed"), "the move is not named: {stderr}");
assert!(stderr.contains("The Blocker"), "{stderr}");
assert!(stderr.contains("backlog"), "{stderr}");
assert!(stderr.contains("--force"), "{stderr}");
@@ -729,16 +731,19 @@ fn mv_refuses_a_move_while_a_blocker_is_open() {
assert_eq!(stray_files(&worklane), Vec::<String>::new());
}
/// Every open blocker, not the first: clearing the one the message happened to name
/// would leave the ticket blocked and the reader surprised.
/// Every blocker still behind the move, not the first: advancing the one the message
/// happened to name would leave the ticket held up and the reader surprised.
///
/// The gated ticket is in reviewing and both blockers are behind it, so the move to done
/// is ahead of both. A blocker further along than the move is a separate case, below.
#[test]
fn mv_names_every_open_blocker() {
fn mv_names_every_blocker_behind_the_move() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_gated_pair(&worklane, &temp, "backlog");
create_gated_pair(&worklane, &temp, "reviewing");
create_ticket(
&worklane,
"reviewing",
"committed",
"The Second Blocker",
"Also not done.",
"cccc3333cccc3333cccc3333cccc3333cccc",
@@ -754,12 +759,95 @@ fn mv_names_every_open_blocker() {
.assert()
.success();
let out = move_ticket(&temp, "aaaa1111", "committed", false);
let out = move_ticket(&temp, "aaaa1111", "done", false);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("The Blocker"), "{stderr}");
assert!(stderr.contains("The Second Blocker"), "{stderr}");
}
/// A blocker that has moved on is not in the way, and it is left out of the message
/// rather than listed with the ones that are: a ticket told to wait for work that is
/// already ahead of it has nothing to act on.
#[test]
fn mv_leaves_out_a_blocker_the_move_does_not_pass() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_gated_pair(&worklane, &temp, "backlog");
create_ticket(
&worklane,
"reviewing",
"The Second Blocker",
"Further along than the move.",
"cccc3333cccc3333cccc3333cccc3333cccc",
"bob",
"_Not set_",
"test",
);
Command::cargo_bin(BIN_NAME)
.unwrap()
.current_dir(temp.path())
.args(["relate", "aaaa1111", "--blocked-by", "cccc3333"])
.assert()
.success();
// Refused by the backlog blocker, which is the only one the move passes.
let out = move_ticket(&temp, "aaaa1111", "committed", false);
assert!(!out.status.success());
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(stderr.contains("The Blocker"), "{stderr}");
assert!(
!stderr.contains("The Second Blocker"),
"a blocker ahead of the move was named: {stderr}"
);
}
/// The walk the change is for: a dependent follows its blocker one column at a time,
/// standing level with it and never ahead, and none of it costs a `-f`.
#[test]
fn mv_walks_a_dependent_up_behind_its_blocker() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = create_gated_pair(&worklane, &temp, "backlog");
// Level is allowed: the blocker is committed, so the dependent may be committed too,
// and reviewing is the stage it may not reach yet.
assert!(
move_ticket(&temp, "bbbb2222", "committed", false)
.status
.success()
);
let out = move_ticket(&temp, "aaaa1111", "committed", false);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(worklane.join("committed").join(&filename).exists());
let refused = move_ticket(&temp, "aaaa1111", "reviewing", false);
assert!(
!refused.status.success(),
"the dependent moved a column ahead of its blocker"
);
// The blocker submits, and reviewing opens for the dependent while done does not.
assert!(
move_ticket(&temp, "bbbb2222", "reviewing", false)
.status
.success()
);
let out = move_ticket(&temp, "aaaa1111", "reviewing", false);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let refused = move_ticket(&temp, "aaaa1111", "done", false);
assert!(!refused.status.success(), "the dependent landed before its blocker");
assert!(worklane.join("reviewing").join(&filename).exists());
// And the last stage, which is the one that was ever worth waiting for.
assert!(move_ticket(&temp, "bbbb2222", "done", false).status.success());
let out = move_ticket(&temp, "aaaa1111", "done", false);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(worklane.join("done").join(&filename).exists());
}
/// `-f` is where the deliberate overrides live, beside the backward and skipping moves.
#[test]
fn mv_moves_a_blocked_ticket_with_force() {
@@ -790,8 +878,8 @@ fn mv_allows_the_move_once_the_blocker_is_done() {
assert!(worklane.join("committed").join(&filename).exists());
}
/// Every move, not only the one into committed. An open blocker is a reason not to
/// finish as much as a reason not to start.
/// Every move is asked, not only the one into committed: a blocker that has not started
/// is a reason not to finish as much as a reason not to start.
#[test]
fn mv_checks_the_blockers_on_every_move() {
let temp = TempDir::new().unwrap();
@@ -818,6 +906,11 @@ fn mv_does_not_check_the_blockers_on_a_no_op() {
/// A dangling target is a bookkeeping fault, not a dependency. Refusing there would
/// wedge the ticket with no way out but `--force`.
///
/// The stderr is asserted whole rather than searched, and that is the point of the
/// assertion: c680e24 moved this warning off `eprintln!` and onto the sink's second
/// stream so the board could collect it, and a shell has to go on reading the line it
/// always read, on the stream it always read it from.
#[test]
fn mv_warns_and_allows_when_a_blocker_is_not_on_the_board() {
let temp = TempDir::new().unwrap();
@@ -832,10 +925,16 @@ fn mv_warns_and_allows_when_a_blocker_is_not_on_the_board() {
let out = move_ticket(&temp, "aaaa1111", "committed", false);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(
String::from_utf8_lossy(&out.stderr),
"Warning: ticket 'Gated Task' is blocked by bbbb222, which is not on the board.\n",
"the warning is not the line it was, on the stream it was on"
);
// And it stays off stdout, which is what a caller reads the answer from.
assert!(
String::from_utf8_lossy(&out.stderr).contains("not on the board"),
"{}",
String::from_utf8_lossy(&out.stderr)
!String::from_utf8_lossy(&out.stdout).contains("not on the board"),
"the warning landed in the answer: {}",
String::from_utf8_lossy(&out.stdout)
);
assert!(worklane.join("committed").join(&filename).exists());
}
@@ -1145,6 +1244,94 @@ fn mv_does_not_restamp_a_no_op_move() {
assert_eq!(ticket_at(&worklane, "committed", &filename), before);
}
/// A ticket whose file sits in one status directory while its Status field says another
/// is a hand-moved file or a partial restore. Moving it to the status it already sits in
/// is the repair: the field is rewritten to agree with the directory and reported as a
/// correction rather than refused as a no-op.
#[test]
fn mv_repairs_a_lagging_status_field_instead_of_refusing() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = stamped_ticket(&worklane, "done");
let drifted = ticket_at(&worklane, "done", &filename)
.replace("- **Status**: done", "- **Status**: backlog");
fs::write(worklane.join("done").join(&filename), &drifted).unwrap();
let out = move_ticket(&temp, "cccc3333", "done", false);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{stderr}");
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("Corrected Status field"), "{stdout}");
assert!(stdout.contains("backlog"), "{stdout}");
// Not a move: nothing was relocated and only the field changed, byte for byte.
assert!(worklane.join("done").join(&filename).exists());
assert_eq!(md_files(&worklane.join("backlog")), Vec::<String>::new());
assert_eq!(
ticket_at(&worklane, "done", &filename),
drifted.replace("- **Status**: backlog", "- **Status**: done")
);
}
/// The repair corrects bookkeeping rather than moving work, so it stamps nothing and
/// logs nothing: an entry shaped like a transition would record a journey the ticket
/// never took.
#[test]
fn a_repair_writes_no_stamp_and_no_history_entry() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = stamped_ticket(&worklane, "backlog");
// A real move first, so the ticket carries the stamp and the log entry that a
// repair has to leave alone.
let out = move_ticket(&temp, "cccc3333", "committed", false);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let history = worklane
.join("history")
.join("cccc3333cccc3333cccc3333cccc3333cccc");
assert_eq!(md_files(&history).len(), 1);
let content = ticket_at(&worklane, "committed", &filename);
assert!(content.contains("Committed On"), "{content}");
let drifted = content.replace("- **Status**: committed", "- **Status**: done");
fs::write(worklane.join("committed").join(&filename), &drifted).unwrap();
let out = move_ticket(&temp, "cccc3333", "committed", false);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let repaired = ticket_at(&worklane, "committed", &filename);
assert!(repaired.contains("Committed On"), "{repaired}");
assert!(!repaired.contains("Submitted On"), "{repaired}");
assert_eq!(md_files(&history).len(), 1, "the repair logged an entry");
}
/// The mirror drift, a field ahead of its directory from a crash mid-move, repairs the
/// same way when the caller keeps the ticket where it sits rather than moving it on to
/// where the field claims.
#[test]
fn mv_repairs_a_field_ahead_of_its_directory_too() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = stamped_ticket(&worklane, "backlog");
let drifted = ticket_at(&worklane, "backlog", &filename)
.replace("- **Status**: backlog", "- **Status**: done");
fs::write(worklane.join("backlog").join(&filename), &drifted).unwrap();
let out = move_ticket(&temp, "cccc3333", "backlog", false);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{stderr}");
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("Corrected Status field"), "{stdout}");
assert!(worklane.join("backlog").join(&filename).exists());
assert!(
ticket_at(&worklane, "backlog", &filename).contains("- **Status**: backlog"),
"{}",
ticket_at(&worklane, "backlog", &filename)
);
}
// ---------------------------------------------------------------- discarded --
/// Discarding is not a stage of work, so it is reachable from wherever the ticket
+412
View File
@@ -388,3 +388,415 @@ fn a_line_that_is_not_a_relation_is_an_error() {
assert!(stderr.contains("is not a relation"), "{stderr}");
assert!(stderr.contains("The gated one"), "{stderr}");
}
// --------------------------------------------------------------- clearing --
/// Two blockers, one taken off by name. The other survives, which is the whole reason
/// `--clear` names the target and not just the kind: a ticket can hold several of one
/// kind, and emptying all of them is not usually what is wanted.
#[test]
fn a_relation_is_taken_off_by_its_kind_and_its_target() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(
&temp,
&[
"relate",
GATED,
"--blocked-by",
BLOCKER,
"--blocked-by",
FIXED,
],
);
let out = run(&temp, &["relate", GATED, "--clear", "blocked-by", BLOCKER]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(stdout(&out).contains("Cleared blocked by"), "{}", stdout(&out));
let content = ticket(&worklane, GATED);
assert!(
!content.contains(BLOCKER),
"the cleared relation is still there: {content}"
);
assert!(
content.contains(&format!("- blocked by {}", FIXED)),
"the other one went too: {content}"
);
}
/// Both spellings of the kind, because both are in front of the reader: `blocked-by` is
/// the flag that recorded it and `blocked by` is what `show` prints and what the file
/// stores. Refusing the form the tool itself prints would be a trap.
#[test]
fn the_kind_takes_the_flag_spelling_and_the_label_spelling() {
for kind in ["blocked-by", "blocked by", "Blocked-By"] {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
let out = run(&temp, &["relate", GATED, "--clear", kind, BLOCKER]);
assert!(out.status.success(), "{kind}: {}", String::from_utf8_lossy(&out.stderr));
assert!(!ticket(&worklane, GATED).contains(BLOCKER), "{kind} did not clear it");
}
}
/// The target is a ticket argument like any other, so it resolves by title too.
#[test]
fn a_cleared_target_resolves_by_title() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
let out = run(&temp, &["relate", GATED, "--clear", "blocked-by", "blocker"]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(!ticket(&worklane, GATED).contains(BLOCKER));
}
/// A relation the ticket does not hold is the state the caller asked for, so it reports
/// no change rather than failing. The target resolves; the edge is simply not there.
#[test]
fn clearing_a_relation_the_ticket_does_not_hold_reports_no_change() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
let before = ticket(&worklane, GATED);
// A kind it does not hold at all, and a target it holds under another kind.
for args in [["relates-to", BLOCKER], ["blocked-by", FIXED]] {
let out = run(&temp, &["relate", GATED, "--clear", args[0], args[1]]);
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
assert!(stdout(&out).contains("No changes"), "{args:?}: {}", stdout(&out));
assert_eq!(ticket(&worklane, GATED), before, "{args:?} wrote something");
}
}
/// A search naming nothing at all is a typo, not a state to report. Reporting no change
/// for it would swallow it, which is the one thing the no-change rule must not do.
#[test]
fn clearing_a_target_that_names_nothing_is_an_error() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
let before = ticket(&worklane, GATED);
let out = run(&temp, &["relate", GATED, "--clear", "blocked-by", "9999zzzz"]);
assert!(!out.status.success(), "{}", stdout(&out));
assert_eq!(ticket(&worklane, GATED), before);
}
/// The inverse is derived by a scan rather than stored, so taking the stored line off is
/// what takes it off both ends. The other ticket's own file was never touched either way.
#[test]
fn the_derived_inverse_goes_with_the_stored_line() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
let untouched = ticket(&worklane, BLOCKER);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
let shown = stdout(&run(&temp, &["show", BLOCKER]));
assert!(shown.contains("blocks"), "the inverse was never derived: {shown}");
run(&temp, &["relate", GATED, "--clear", "blocked-by", BLOCKER]);
let after = stdout(&run(&temp, &["show", BLOCKER]));
assert!(!after.contains("blocks"), "the inverse outlived the stored line: {after}");
assert_eq!(ticket(&worklane, BLOCKER), untouched, "the other ticket was written to");
}
/// The case most likely to need clearing, and the only one no search of the board can
/// reach: the target's ticket is gone, so the prefix tier over the stored targets is what
/// finds it. `show` renders it as `_missing_` until it is cleared, and `mv` warns about it
/// on every move.
#[test]
fn a_dangling_relation_can_be_cleared() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
fs::remove_file(find(&worklane, BLOCKER)).unwrap();
assert!(
stdout(&run(&temp, &["show", GATED])).contains("_missing_"),
"the fixture is not dangling"
);
// By the short id, which is all a reader has once the title is gone.
let out = run(&temp, &["relate", GATED, "--clear", "blocked-by", &BLOCKER[..7]]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(!ticket(&worklane, GATED).contains(BLOCKER), "{}", ticket(&worklane, GATED));
assert!(!stdout(&run(&temp, &["show", GATED])).contains("_missing_"));
}
/// A prefix short enough to reach two stored targets names the candidates rather than
/// guessing, the way an ambiguous ticket search does, and writes nothing.
#[test]
fn an_ambiguous_prefix_over_the_stored_targets_names_the_candidates() {
const ONE: &str = "aaaa1111-0000-4000-8000-000000000000";
const TWO: &str = "aaaa2222-0000-4000-8000-000000000000";
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
create_ticket(&worklane, "backlog", "Twin one", ONE);
create_ticket(&worklane, "backlog", "Twin two", TWO);
run(&temp, &["relate", GATED, "--blocked-by", ONE, "--blocked-by", TWO]);
let before = ticket(&worklane, GATED);
let out = run(&temp, &["relate", GATED, "--clear", "blocked-by", "aaaa"]);
assert!(!out.status.success(), "{}", stdout(&out));
// The stored-target tier and not the board search, which would find the same two
// tickets by their own uuid prefix and report them the same way. The wording is what
// tells the two apart, so it is what this asserts.
let reason = String::from_utf8_lossy(&out.stderr);
assert!(
reason.contains("'blocked by' relations on"),
"the board answered instead: {reason}"
);
assert!(reason.contains(&ONE[..7]) && reason.contains(&TWO[..7]), "{reason}");
assert_eq!(ticket(&worklane, GATED), before);
}
/// The last edge leaves the placeholder `add` writes, not an empty body, so the section
/// can be written to again without the placeholder ending up above what follows it.
#[test]
fn clearing_the_last_relation_leaves_the_placeholder() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
run(&temp, &["relate", GATED, "--clear", "blocked-by", BLOCKER]);
let content = ticket(&worklane, GATED);
assert!(
content.contains(
"## Relations
_No relations._
"
),
"{content}"
);
// And it is written to again without the placeholder being left behind.
run(&temp, &["relate", GATED, "--relates-to", FIXED]);
let again = ticket(&worklane, GATED);
assert!(again.contains(&format!("- relates to {}", FIXED)), "{again}");
assert!(
!again.contains("_No relations._"),
"the placeholder outlived the edge: {again}"
);
}
/// The same file surgery `relate` already does, so the tick, the handwritten section and
/// the prose survive a clear the way they survive a record.
#[test]
fn clearing_leaves_everything_it_was_not_asked_about_alone() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(
&temp,
&[
"relate",
GATED,
"--blocked-by",
BLOCKER,
"--relates-to",
FIXED,
],
);
run(&temp, &["relate", GATED, "--clear", "blocked-by", BLOCKER]);
let content = ticket(&worklane, GATED);
assert!(content.contains("- [x] Crit one"), "the tick was lost: {content}");
assert!(
content.contains("## Notes\nA handwritten note the tool knows nothing about.\n"),
"the unknown section was lost: {content}"
);
assert!(content.contains("1. Step one"), "{content}");
assert!(content.contains("- **Owner**: alice"), "{content}");
assert!(content.contains("- **Status**: backlog"), "{content}");
}
/// One call does both, and each half reports itself in its own words.
#[test]
fn one_call_records_and_clears_different_relations() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
let out = run(
&temp,
&[
"relate",
GATED,
"--clear",
"blocked-by",
BLOCKER,
"--relates-to",
FIXED,
],
);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let reported = stdout(&out);
assert!(reported.contains("Recorded relates to"), "{reported}");
assert!(reported.contains("Cleared blocked by"), "{reported}");
let content = ticket(&worklane, GATED);
assert!(!content.contains(BLOCKER), "{content}");
assert!(content.contains(&format!("- relates to {}", FIXED)), "{content}");
}
/// Recording and clearing the same relation in one call is refused outright, the way
/// `set` refuses a field it is also replacing: nothing is written rather than one of the
/// two silently winning.
///
/// It has to be caught on what the call *asked* for and not on what it would write. A
/// relation already in the file is not among the additions, so comparing against those
/// would let this call quietly remove one.
#[test]
fn recording_and_clearing_the_same_relation_is_refused() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
let before = ticket(&worklane, GATED);
let out = run(
&temp,
&[
"relate",
GATED,
"--blocked-by",
BLOCKER,
"--clear",
"blocked-by",
BLOCKER,
],
);
assert!(!out.status.success(), "{}", stdout(&out));
assert!(
String::from_utf8_lossy(&out.stderr).contains("nothing was written"),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(ticket(&worklane, GATED), before, "the relation was removed anyway");
}
/// A kind that is not one of the three is refused before the ticket is resolved, so
/// nothing is written. Exit 1 rather than clap's 2: the value is one of a pair clap
/// cannot type apart, so the kind is parsed by `RelateArgs::cleared`.
#[test]
fn an_unknown_kind_in_a_clear_is_refused() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
let before = ticket(&worklane, GATED);
let out = run(&temp, &["relate", GATED, "--clear", "depends-on", BLOCKER]);
assert!(!out.status.success(), "{}", stdout(&out));
let reason = String::from_utf8_lossy(&out.stderr);
assert!(reason.contains("not a relation kind"), "{reason}");
// The message names the three, in the spelling the flags and the completions use.
for kind in ["blocked-by", "regression-of", "relates-to"] {
assert!(reason.contains(kind), "{reason}");
}
assert_eq!(ticket(&worklane, GATED), before);
}
/// `--clear` takes exactly two values per occurrence, so clap refuses an odd number with
/// a usage error and nothing reaches the handler.
#[test]
fn a_clear_with_one_value_is_a_usage_error() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
let before = ticket(&worklane, GATED);
let out = run(&temp, &["relate", GATED, "--clear", "blocked-by"]);
assert_eq!(out.status.code(), Some(2), "{}", stdout(&out));
assert_eq!(ticket(&worklane, GATED), before);
}
/// The far end already stores it, so the edge is already recorded: `show` derives it onto
/// this ticket by scanning. A line here would be the same edge on two files, which
/// 4179958 decided against and nothing enforced until 03bdc76.
#[test]
fn a_relates_to_the_target_already_stores_is_not_stored_again() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
run(&temp, &["relate", BLOCKER, "--relates-to", GATED]);
let before = ticket(&worklane, GATED);
let out = run(&temp, &["relate", GATED, "--relates-to", BLOCKER]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(stdout(&out).contains("No changes"), "{}", stdout(&out));
assert_eq!(ticket(&worklane, GATED), before, "the mirror was stored anyway");
// Still shown, since it was recorded at the other end.
let shown = stdout(&run(&temp, &["show", GATED]));
assert_eq!(shown.matches("relates to").count(), 1, "{shown}");
}
/// A board that already holds both directions draws the edge once. The refusal above
/// stops it recurring; this is what repairs a ticket that already has it, without an edit.
#[test]
fn a_relates_to_stored_at_both_ends_is_drawn_once() {
let temp = TempDir::new().unwrap();
let worklane = board(&temp);
// Both lines written directly, which is the state a board recorded before the refusal
// is in. The CLI will not produce it any more, so nothing else can set this up.
for (holder, target) in [(GATED, BLOCKER), (BLOCKER, GATED)] {
let path = find(&worklane, holder);
let content = fs::read_to_string(&path).unwrap().replace(
"## Metadata",
&format!("## Relations\n- relates to {target}\n\n## Metadata"),
);
fs::write(&path, content).unwrap();
}
let shown = stdout(&run(&temp, &["show", GATED]));
assert_eq!(shown.matches("relates to").count(), 1, "the edge is drawn twice:\n{shown}");
assert_eq!(shown.matches(&BLOCKER[..7]).count(), 1, "{shown}");
// And from the other end, which stores its own line and derives this one.
let far = stdout(&run(&temp, &["show", BLOCKER]));
assert_eq!(far.matches("relates to").count(), 1, "{far}");
}
/// Only where the row reads the same. Two tickets each blocking the other is two facts,
/// and the block says both: `blocked by` from this end, `blocks` from the other.
#[test]
fn a_mutual_block_is_still_drawn_from_both_ends() {
let temp = TempDir::new().unwrap();
board(&temp);
run(&temp, &["relate", GATED, "--blocked-by", BLOCKER]);
let out = run(&temp, &["relate", BLOCKER, "--blocked-by", GATED]);
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(
!stdout(&out).contains("No changes"),
"the second was refused: {}",
stdout(&out)
);
let shown = stdout(&run(&temp, &["show", GATED]));
assert!(shown.contains("blocked by"), "{shown}");
assert!(shown.contains("blocks"), "the derived direction was dropped:\n{shown}");
}
/// The same for the other asymmetric kind, whose inverse label also differs from its own.
#[test]
fn a_mutual_regression_is_still_drawn_from_both_ends() {
let temp = TempDir::new().unwrap();
board(&temp);
run(&temp, &["relate", GATED, "--regression-of", BLOCKER]);
run(&temp, &["relate", BLOCKER, "--regression-of", GATED]);
let shown = stdout(&run(&temp, &["show", GATED]));
assert!(shown.contains("regression of"), "{shown}");
assert!(
shown.contains("regressed by"),
"the derived direction was dropped:\n{shown}"
);
}
+134
View File
@@ -676,6 +676,140 @@ fn append_requires_at_least_one_section() {
assert_eq!(run(&temp, &["append", UUID]).status.code(), Some(2));
}
/// The reason the flag exists: `set --tags` writes the whole field, so adding one tag to
/// a ticket that already carries some meant knowing and retyping every one of them.
#[test]
fn append_adds_a_tag_and_keeps_the_ones_already_there() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane);
let out = run(&temp, &["append", UUID, "--tags", "beta"]);
assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr));
let content = ticket(&worklane);
assert!(content.contains("- **Tags**: alpha, beta"), "{content}");
// The sections and the other fields are as untouched as they are by any other append
assert!(content.contains("- [x] Crit one\n- [ ] Crit two\n"), "{content}");
assert!(content.contains("- **Priority**: 3"), "{content}");
}
/// Idempotent on purpose: the caller of an append does not have to know what is there
/// already, so naming a tag the ticket carries is reported as no change and writes
/// nothing, the way an unchanged field is everywhere else.
#[test]
fn append_ignores_a_tag_the_ticket_already_carries() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane);
let before = ticket(&worklane);
let out = run(&temp, &["append", UUID, "--tags", "alpha"]);
assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr));
assert!(
String::from_utf8_lossy(&out.stdout).contains("No changes to"),
"{:?}",
String::from_utf8_lossy(&out.stdout)
);
assert_eq!(ticket(&worklane), before);
// And the one already there is not added a second time beside a new one
run(&temp, &["append", UUID, "--tags", "alpha", "--tags", "beta"]);
assert!(
ticket(&worklane).contains("- **Tags**: alpha, beta"),
"{}",
ticket(&worklane)
);
}
/// Two spellings for the same call, because the stored field is comma separated too and
/// `set --tags` takes that form on this very field: refusing it on the counterpart would
/// be a trap. New tags land in the order they were given, after the ones already there.
#[test]
fn append_takes_several_tags_by_repeated_flag_or_by_comma() {
for args in [
vec!["append", UUID, "--tags", "bug", "--tags", "tui"],
vec!["append", UUID, "--tags", "bug, tui"],
vec!["append", UUID, "-g", "bug,tui"],
] {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane);
let out = run(&temp, &args);
assert!(
out.status.success(),
"{args:?}: {:?}",
String::from_utf8_lossy(&out.stderr)
);
assert!(ticket(&worklane).contains("- **Tags**: alpha, bug, tui"), "{args:?}");
}
}
/// A value that names no tag is refused rather than written, the way an all-blank section
/// value is: `--tags ","` adds nothing, and writing the field back unchanged would report
/// an append that never happened. Emptying the field is `set --clear tags`.
#[test]
fn append_refuses_a_tags_value_that_names_nothing() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane);
let before = ticket(&worklane);
// Empty at the parser, before the ticket is even resolved
let empty = run(&temp, &["append", UUID, "--tags", ""]);
assert_eq!(empty.status.code(), Some(2));
assert!(
String::from_utf8_lossy(&empty.stderr).contains("value cannot be empty"),
"{:?}",
String::from_utf8_lossy(&empty.stderr)
);
// The message must not name a `--clear` this command does not have
assert!(
!String::from_utf8_lossy(&empty.stderr).contains("use --clear"),
"{:?}",
String::from_utf8_lossy(&empty.stderr)
);
// Separators only, which the parser cannot see is empty
let blank = run(&temp, &["append", UUID, "--tags", ", ,"]);
assert_eq!(blank.status.code(), Some(1));
assert!(
String::from_utf8_lossy(&blank.stderr).contains("Nothing to append to the tags"),
"{:?}",
String::from_utf8_lossy(&blank.stderr)
);
assert_eq!(ticket(&worklane), before);
}
/// A ticket with no tags starts the list rather than appending to the sentinel.
#[test]
fn append_writes_the_first_tag_over_the_unset_sentinel() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let mut add = Command::cargo_bin(BIN_NAME).unwrap();
add.current_dir(temp.path())
.args(["add", "--title", "Untagged"])
.assert()
.success();
let uuid = fs::read_dir(worklane.join("backlog"))
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().into_string().unwrap())
.next()
.map(|name| name.split('_').next().unwrap().to_string())
.unwrap();
run(&temp, &["append", &uuid, "--tags", "bug"]);
let content = ticket(&worklane);
assert!(content.contains("- **Tags**: bug"), "{content}");
assert!(!content.contains("_None_"), "{content}");
}
/// Owner belongs to chown and status to mv, so neither command offers them.
#[test]
fn neither_command_can_write_owner_or_status() {
+76 -1
View File
@@ -316,6 +316,71 @@ fn an_annotation_that_would_read_as_a_heading_is_refused() {
assert!(!temp.path().join(".worklane").join("tags.md").exists());
}
/// A tab anywhere in an annotation is refused by `tags add`, because the listing's fields
/// are tab separated: past the first tab everything after it reads as a fourth field. The
/// refusal says why, and nothing is written — the value parser refuses before the handler
/// runs, so not even a placeholder file is left behind.
#[test]
fn an_annotation_carrying_a_tab_is_refused_by_tags_add() {
let temp = TempDir::new().unwrap();
setup_worklane(&temp);
let out = run(&temp, &["tags", "add", "bug", "-a", "Something\twrong."]);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success(), "{stderr}");
assert!(
stderr.contains("tab") && stderr.contains("separates its fields"),
"{stderr}"
);
assert!(!temp.path().join(".worklane").join("tags.md").exists());
// No staged write survived either, so the directory holds only the status folders.
let left: Vec<_> = fs::read_dir(temp.path().join(".worklane"))
.unwrap()
.map(|e| e.unwrap().file_name())
.collect();
assert_eq!(left.len(), 4, "{left:?}");
}
/// The same value is refused by `tags set`, and the declaration that is already there is
/// untouched.
#[test]
fn an_annotation_carrying_a_tab_is_refused_by_tags_set() {
let temp = TempDir::new().unwrap();
setup_worklane(&temp);
run(&temp, &["tags", "add", "bug", "-a", "Something wrong."]);
let before = vocabulary(&temp);
let out = run(&temp, &["tags", "set", "bug", "-a", "Now\twith a tab."]);
assert!(!out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(vocabulary(&temp), before);
}
/// Ordinary prose is unaffected, paragraphs included: the refusal is for the tab alone,
/// which is what keeps it from standing in front of the command's whole purpose.
#[test]
fn an_annotation_without_a_tab_is_taken_whatever_its_shape() {
let temp = TempDir::new().unwrap();
setup_worklane(&temp);
run(
&temp,
&[
"tags",
"add",
"bug",
"-a",
"A defect.",
"-a",
"",
"-a",
"--plan is prose",
],
);
assert_eq!(declared(&temp, "bug").as_deref(), Some("A defect.\n\n--plan is prose"));
}
/// The file is made on demand, the way `campaign add` makes the campaigns directory: a board
/// that predates the vocabulary must not need `worklane init` run over it.
#[test]
@@ -332,7 +397,17 @@ fn the_file_is_created_on_a_board_that_predates_it() {
#[test]
fn init_writes_the_vocabulary_beside_the_status_directories() {
let temp = TempDir::new().unwrap();
let out = run(&temp, &["init"]);
// Isolated HOME and XDG so `init` cannot decide on a real machine's boards config:
// the board has to be local no matter whose machine runs the suite.
let mut out = Command::cargo_bin(BIN_NAME).unwrap();
let out = out
.current_dir(temp.path())
.env("HOME", temp.path())
.env("XDG_CONFIG_HOME", temp.path().join("config"))
.env("XDG_DATA_HOME", temp.path().join("data"))
.arg("init")
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
let file = vocabulary(&temp);
+163 -1
View File
@@ -72,6 +72,29 @@ fn run(temp: &TempDir, args: &[&str]) -> Output {
.clone()
}
/// Run as an agent acting for the person: the variable still names the agent, the git
/// config names the human, and the flag is what tells the two apart.
fn run_for_the_human(temp: &TempDir, args: &[&str]) -> Output {
Command::cargo_bin(BIN_NAME)
.unwrap()
.current_dir(temp.path())
.env("WORKLANE_ACTOR", "claude")
.env("GIT_CONFIG_GLOBAL", git_config_naming(temp, "Ansho Rei"))
.env("GIT_CONFIG_NOSYSTEM", "1")
.args(args)
.assert()
.get_output()
.clone()
}
/// A git config file holding nothing but a `user.name`, for the tests that need the
/// fallback to answer something known instead of whatever the machine is configured with.
fn git_config_naming(temp: &TempDir, name: &str) -> PathBuf {
let path = temp.path().join("gitconfig");
fs::write(&path, format!("[user]\n\tname = {}\n", name)).unwrap();
path
}
/// Every entry on the ticket, name and content, in the order the log sorts them.
fn entries(worklane: &Path) -> Vec<(String, String)> {
let dir = worklane.join("history").join(UUID);
@@ -252,6 +275,36 @@ fn clearing_the_tags_writes_a_tags_entry() {
assert!(entry.starts_with("**Tags**\nalpha → _None_\n"), "{entry:?}");
}
/// Tags are logged wherever they change, so the command that adds to them logs the same
/// entry the one that replaces them does. The values come off the field rather than off
/// the flag, so the entry records where the field went and not what the call added: an
/// append of `beta` onto `alpha` reads as the pair, not as `beta`.
#[test]
fn appending_a_tag_writes_a_tags_entry() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane, "backlog");
run(&temp, &["append", UUID, "--tags", "beta"]);
let entry = only_entry(&worklane, "tags");
assert!(entry.starts_with("**Tags**\nalpha → alpha, beta\n"), "{entry:?}");
}
/// The sections are not logged, and appending to one is not a tag change: an append that
/// touches no tag writes nothing, so the log does not fill with the edits it deliberately
/// leaves out.
#[test]
fn appending_to_a_section_writes_nothing() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane, "backlog");
run(&temp, &["append", UUID, "--acceptance", "One more criterion"]);
assert_eq!(entries(&worklane), vec![]);
}
/// The entry names the campaign the way a reader knows it, the codename, not the uuid
/// the field actually holds. A ticket never assigned starts from the sentinel an unset
/// field reads as everywhere else.
@@ -410,6 +463,7 @@ fn a_no_op_edit_writes_nothing() {
vec!["mv", UUID, "--status", "backlog"],
vec!["chown", "alice", UUID],
vec!["set", UUID, "--tags", "alpha"],
vec!["append", UUID, "--tags", "alpha"],
] {
let out = run(&temp, &args);
assert!(
@@ -554,11 +608,119 @@ fn the_actor_flag_names_the_writer_on_every_command_that_writes_one() {
run(&temp, &["mv", UUID, "--status", "committed", "--actor", "opencode"]);
run(&temp, &["chown", "bob", UUID, "--actor", "opencode"]);
run(&temp, &["set", UUID, "--tags", "beta", "--actor", "opencode"]);
run(&temp, &["append", UUID, "--tags", "gamma", "--actor", "opencode"]);
run(&temp, &["assign", "v1", UUID, "--actor", "opencode"]);
let found = entries(&worklane);
assert_eq!(found.len(), 5, "{found:?}");
assert_eq!(found.len(), 6, "{found:?}");
for (name, content) in found {
assert!(content.contains("**Author**: opencode"), "{name}: {content:?}");
}
}
/// The lift is spelled the same on every command that writes an entry, and it raises
/// the git user over the variable on each of them.
#[test]
fn actor_from_git_names_the_git_user_on_every_command_that_writes_one() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane, "backlog");
run(
&temp,
&[
"campaign",
"add",
"--title",
"First release",
"--codename",
"v1",
],
);
run_for_the_human(&temp, &["comment", UUID, "By hand.", "--actor-from-git"]);
run_for_the_human(&temp, &["mv", UUID, "--status", "committed", "--actor-from-git"]);
run_for_the_human(&temp, &["chown", "bob", UUID, "--actor-from-git"]);
run_for_the_human(&temp, &["set", UUID, "--tags", "beta", "--actor-from-git"]);
run_for_the_human(&temp, &["append", UUID, "--tags", "gamma", "--actor-from-git"]);
run_for_the_human(&temp, &["assign", "v1", UUID, "--actor-from-git"]);
let found = entries(&worklane);
assert_eq!(found.len(), 6, "{found:?}");
for (name, content) in found {
assert!(content.contains("**Author**: Ansho Rei"), "{name}: {content:?}");
}
}
/// Both flags answer the same question — who is the entry attributed to — so a call
/// carrying both is a usage error at parse time rather than a last-wins answer. Refused
/// before any ticket is resolved, so nothing reaches the log.
#[test]
fn actor_and_actor_from_git_are_refused_together() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane, "backlog");
let calls: [&[&str]; 6] = [
&[
"comment",
UUID,
"Body.",
"--actor",
"opencode",
"--actor-from-git",
],
&[
"mv",
UUID,
"--status",
"committed",
"--actor",
"opencode",
"--actor-from-git",
],
&[
"chown",
"bob",
UUID,
"--actor",
"opencode",
"--actor-from-git",
],
&[
"set",
UUID,
"--tags",
"beta",
"--actor",
"opencode",
"--actor-from-git",
],
&[
"append",
UUID,
"--tags",
"beta",
"--actor",
"opencode",
"--actor-from-git",
],
&[
"assign",
"v1",
UUID,
"--actor",
"opencode",
"--actor-from-git",
],
];
for call in calls {
let output = run(&temp, call);
assert_eq!(output.status.code(), Some(2), "{call:?} was not a usage error");
}
assert!(
!worklane.join("history").join(UUID).exists(),
"an entry was written despite the usage error"
);
}