Compare commits

..
16 Commits
Author SHA1 Message Date
Ansho ReiandClaude Opus 5 5a7cfeb849 (b8aa66b) Evaluate ticket resolution in tiers, from four characters up, and bump to 0.4.0
resolve_ticket ORed the uuid prefix, title and filename predicates into one flat
list, so an exact prefix match was reported as ambiguous against any title that
merely mentioned that id. Reproduced: `show 641e3d5` on a board where another
ticket's title quoted it failed with "Multiple tickets found", and told the user
to use the displayed id, which was the id they had just used.

The three tiers are now evaluated in order and the first non-empty one wins
outright, which is what AGENTS.md always claimed.

The ticket also asked for prefix matching to require eight characters, and that
is not implemented. The guard it replaced read short_id.len() >= 8 where
short_id was always the full uuid, so it was always true and any length already
worked. Eight would have regressed that: ls prints seven characters, so the id
the tool displays would drop out of the uuid tier and lose to any title quoting
it, which is the very bug above. MIN_ID_SEARCH is four, so a short search is
still text and `show 641` remains a title search.

Docs corrected in four places that all stated the eight character rule: README,
AGENTS.md, the opencode tool descriptions and the kanban skill.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 23:38:29 +02:00
Ansho ReiandClaude Opus 5 e20396ce6b (322150c) Make mv crash-safe by writing before renaming, and bump to 0.3.3
cmd_mv renamed the ticket into its new directory and only then wrote the updated
content, so a write that failed left the ticket in the target directory still
claiming the old status. Reproduced with a read-only ticket file: the move
reported a bare "Permission denied" and left the file in committed/ carrying
"Status: backlog".

move_ticket_file now stages the content in a temp file, renames it over the
source, and only then renames the file into the target directory. Two atomic
steps, so a partial write is discarded and the original is untouched. The other
obvious order, writing to the target and deleting the source afterwards, was
rejected because it has the ticket in two directories at once.

The worst case left is a ticket still in its old directory with a Status one
move ahead, which the next mv corrects since the directory is what decides the
current status. Tested, including the retry.

The temp file is staged under .worklane/ rather than beside the ticket, so a
leftover from a hard kill is invisible to ticket lookup and to the listing
instead of appearing as a stray untitled ticket. IO errors now name the ticket
and the path rather than propagating bare.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 23:12:17 +02:00
Ansho ReiandClaude Opus 5 f5204f6d8b (866a4eb) Accept prose values that begin with a hyphen, and bump to 0.3.2
clap read any value starting with a hyphen as a flag, so a criterion quoting
--print was refused with "unexpected argument found" and no ticket was written
at all. Ticket text quotes flag names constantly, and the space form is what
both a person and the opencode wrapper produce, so the failure was routine.

allow_hyphen_values on the five arguments that carry prose: add --title,
--description, --acceptance, --plan, and the comment body. The trade is that a
genuinely mistyped flag there now lands as content instead of raising a usage
error, which is the right way round for prose and the wrong way round for
anything else, so due, priority, tags, owner and status are left alone and still
fail with exit 2. Written down in AGENTS.md.

The bare double hyphen is the one shape this does not reach: as an option value
it is stored as text, but in a positional it is clap's end-of-options marker and
is consumed before assignment. A comment body of exactly -- therefore needs its
own separator. Without it the body is reported missing and nothing is written,
so it is a clear failure rather than a silent drop. Tested, along with the
ordering that lets mv reach a hyphen-leading title.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 18:00:52 +02:00
Ansho ReiandClaude Opus 5 b28ddb9210 (eed7309) Die quietly on a truncated pipe, and bump to 0.3.1
Rust sets SIGPIPE to SIG_IGN at startup, so a write to a closed pipe returned
EPIPE and println panicked on it. `worklane ls | head -3` printed a panic and a
backtrace on stderr instead of three lines, which reads as a real fault and is
not what any other tool in a pipeline does.

main now restores the default disposition before any output, the same six lines
frig carries for the same reason. The cost is that a truncated pipe kills the
process with signal 13, so a shell reports 141 rather than 101. That is what
head and sort do, and it is now in the README next to the other exit codes.

The tests drop the read end rather than racing head for it, over a listing large
enough to exceed the 64 KiB a pipe holds, since a smaller one lands entirely in
the buffer and proves nothing. A shell pipeline into head is covered too, and
the exit codes for a real error and a usage mistake are pinned so the reset
cannot quietly change them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 17:34:45 +02:00
Ansho ReiandClaude Opus 5 f557437f62 (277a527) Render the metadata section as an aligned table, and bump to 0.3.0
show printed the Metadata block as the markdown list the file stores, so with
seven fields the values did not line up and the block read as file contents
rather than as a summary. It now renders as two aligned columns: field names
left, values right. The file is untouched, this is display only.

content_trim_colored streamed one line at a time, so nothing ever saw the whole
section. The Metadata lines are now taken as a block, since the field column
cannot be sized until every name has been seen.

Column width is measured on the raw names, in characters, and padding is applied
before anything is styled. Measuring a coloured name counts its escape sequences
towards its width, which tilts the table with colour on and not with it off.
paint() is color_text() with the decision passed in, which is what lets a test
render both ways in one process and compare.

colorize_metadata is folded into the renderer, its only caller. A line in the
section that is not a field is carried through rather than dropped, so a hand
written note survives, and an unrecognised field still gets a row.

Plain columns, no border characters: nothing to degrade on a font that lacks
them, and the section rules already carry the only box drawing here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 17:12:57 +02:00
Ansho ReiandClaude Opus 5 75fb2b3a6d (4b1e7e8) Print the ticket title once in show
cmd_show printed the resolved title with its rule, then content_trim_colored
printed the "# " heading again out of the file content, so every show output
carried the title twice.

The body now skips the heading, along with the blank line the template puts
under it so nothing is left where it was. cmd_show keeps the surviving copy and
colours it green, which is where the colour guideline puts a title.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 17:12:22 +02:00
Ansho ReiandClaude Opus 5 8b440593e2 (594c741) Measure heading rules on the displayed name
Section rules repeated the character for the byte length of the whole heading
line, so every rule ran three past its heading for the "## " prefix. The title
rule in cmd_show used byte length, which over-draws for a non-ASCII title.

Both now count characters of the text as displayed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 17:11:43 +02:00
Ansho ReiandClaude Opus 5 ab1dae098c (641e3d5) Scope metadata field lookup to the Metadata section, and bump to 0.2.1
parse_ticket_field searched every line of the file with contains, and
set_status_field rewrote the first line starting with the Status marker
wherever it sat. Tickets in this repo quote field markers in their
descriptions, so a description list shaped like metadata was read in place
of the real value and rewritten by mv, leaving the metadata stale.

Both now scan only the lines under the Metadata heading and match on a line
prefix rather than a substring. A file with no Metadata heading has no
fields, so mv reports the missing Status field instead of editing prose.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 16:38:35 +02:00
Ansho ReiandClaude Opus 5 2503f9aee9 (3b7edd7) Show priority as a glyph, and bump to 0.2.0
A bare digit in a listing is easy to skip over. Levels render as a
two-segment meter that empties as the level rises: ●● 1, ●◐ 2, ●○ 3,
◐○ 4, ○○ 5, with ·· for unset and ?? for a value outside the range.

Only ●, ◐, ○ and · are used, because they are what frig draws for its
status indicators and so are known to be in the terminal font. The first
cut of this used the quadrant circles ◕ and ◔, which are in a quarter as
many fonts, so terminals substituted them from a fallback that drew them
oversized and the column came out ragged. Two cells of a three-level ramp
gives five steps of ink, 2, 1.5, 1, 0.5, 0, without leaving that safe set.
Tests pin the safe set, the equal width and the monotonic emptying.

The mark carries the level on its own, because colour cannot. Output is
colourless whenever it is piped, which is how the opencode tools and every
script read it, and NO_COLOR turns it off in a terminal too. Colour only
accentuates: brightred, red, orange, cyan, grey, skipping green because
green means title.

The number counts up while the meter empties, since 1 is the most urgent.
That is the convention, but it reads as a bug unless written down, so it
is in AGENTS.md and in the legend.

Both the ramp and the legend come from priority_mark, and `ls --help`
prints the legend, since nothing in a listing explains a mark. brightred
is indexed like grey, for the same reason: it is the spelling that
renders.

Minor bump: two new flags, a new metadata field and a changed ls row,
covering dca0b61 and this ticket.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 15:50:09 +02:00
Ansho ReiandClaude Opus 5 ddbd45e332 (dca0b61) Add priority as a ticket field
Priority lived in tags, as p1 to p3, which ls could neither sort nor
filter on, nothing validated, and a typo like P1 passed silently. ls
sorted by title only, so a backlog of any size gave no ordering signal.

Levels are 1 to 5 with 1 most urgent, matching what the tags meant.
Omitting the flag leaves the field _Not set_, like Due and Owner: there is
no implicit middle level, because a priority nobody chose is worse than
none. clap rejects anything outside the range before a ticket is written.

Priority parses to three states rather than two. A stored value outside
the range is Invalid, kept distinct from Unset, so a typo cannot read as
"no priority": it shows as ? and sorts just ahead of the unset tail.

ls sorts on priority and falls back to the old title sort, and --priority
filters, composing with the status filter in both the grouped and the
filtered listing. TicketItem becomes a struct, since a sixth tuple field
was past reading.

Migrated the 31 tickets already carrying p1 to p3 tags: the level moves to
the field and the tag is dropped.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 15:36:19 +02:00
Ansho ReiandClaude Opus 5 b7781a830c (482ff01) Grey unset Due and Owner in ls, and bump to 0.1.2
display_ticket_items printed both fields raw, so a ticket with no due date
showed _Not set_ in the default foreground. show already honoured the
guideline through colorize_metadata, leaving the listing as the one place
that ignored it. Reuses is_unknown_value rather than matching the markers
a second time.

Grey is indexed colour 8 in the 256-colour form. Two SGR spellings were
tried against a real terminal and both read as white: 90 leans on the
palette's bright-black slot, and 37 can sit right on top of the default
foreground. \x1b[38;5;8m is byte for byte what crossterm emits for
ratatui's Color::DarkGray, which is the grey frig and pantop already use
for dimmed rows, so this is the spelling known to render here. Pinned by a
test and written down in AGENTS.md, since only an eye in a real terminal
would catch it drifting back.

Patch bump covering the three colour tickets, 9991698, 934bf1a and this
one, as one body of work: nothing new, three places where output did not
do what the guideline said.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 15:24:42 +02:00
Ansho ReiandClaude Opus 5 3abe8755c8 (934bf1a) Define magenta and keep bold markers when colour is off
colorize_line asked color_text for magenta, which get_color never
defined, so it returned an empty prefix: in a terminal the bold text got
a reset with no colour, and piped it lost the ** markers with nothing put
in their place. Every piped show and everything the opencode tools read
saw plain text where the ticket had emphasis.

Define magenta as the bold escape the guideline names, and leave the line
untouched when colour is off, because there the markers are the emphasis.
The scan is rewritten to hand back an unterminated run verbatim rather
than walking off the end, which used to drop the final character.

The scan now takes the enabled flag instead of asking for it, so both
paths are tested rather than only the one a test process happens to get.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 15:05:32 +02:00
Ansho ReiandClaude Opus 5 b6d0b55d4b (9991698) Respect NO_COLOR and non-capable terminals
should_use_colors only asked whether stdout was a terminal, so there was
no way to turn colour off in one, and it was re-evaluated on every
color_text call.

Honour NO_COLOR by the no-color.org rule, set and non-empty disables
whatever the value, with an empty value treated as unset so an inherited
one can be cleared. Treat TERM=dumb and an empty TERM as no colour.
Decide once in a OnceLock, since none of the three inputs change mid-run.

The decision itself is a pure function of its three inputs, so it is
tested without a pty. Verified under a real one as well: colour on by
default, absent with NO_COLOR=1, absent with TERM=dumb, present again
with NO_COLOR set to empty.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 15:04:41 +02:00
Ansho ReiandClaude Opus 5 3fcb0ddc0a Require a local tag alongside every version bump
Records the rule in the Version Bumps section: a bump carries a matching
annotated v<version> tag on the bump commit, kept local unless a push is
asked for. Tagged v0.1.1 on 8563218 retroactively, which was bumped
before the rule existed.

Docs only, so no bump and no tag for this one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 15:01:56 +02:00
Ansho ReiandClaude Opus 5 8563218ab5 (06f15bf) Stop comments overwriting each other, and bump to 0.1.1
Comment filenames were stamped to the second, so two comments added in
the same second produced the same name and fs::write truncated the first.
Agents post in bursts, so this was routine data loss: five comments added
back to back left one file.

Stamp microseconds instead, and create the file with create_new rather
than fs::write, so a name that already exists is taken as a collision and
the next zero-padded suffix is used instead of overwriting. The suffix
sorts after the bare stem, so read_comments still orders comments the way
they were written.

The collision branch cannot be reached from the CLI, since two processes
will not share a microsecond, so it has a unit test of its own.

Patch bump: existing second-resolution comment files still read and still
sort ahead of new ones written in the same second, so no migration.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 15:00:23 +02:00
Ansho ReiandClaude Opus 5 54569b2c85 Require a version bump decision before every commit
Records the rule in the Git Workflow section: decide whether a change
warrants a bump, ask before making one, no bump for docs, tests or
fixups, and bump once on the final commit when work spans several.

Docs only, so no bump for this one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 14:54:43 +02:00
16 changed files with 2275 additions and 158 deletions
+10 -5
View File
@@ -37,6 +37,7 @@ Add a new ticket to the backlog.
- `--tags` (or `-g`): Tags (comma-separated)
- `--due` (or `--due`): Due date in YYYY-MM-DD format
- `--owner` (or `-o`): Owner name
- `--priority`: Priority level, 1 (most urgent) to 5 (least). Unset if omitted
```bash
worklane add -t "Implement login" -d "Add user login page" -t login,auth -p "Design UI" "Build backend" "Write tests" --due 2026-06-01 --owner "ilya"
@@ -56,11 +57,15 @@ List tickets, optionally filtered by status.
**Valid statuses:** `backlog`, `committed`, `reviewing`, `done`
```
worklane ls # List all tickets
worklane ls backlog # List tickets in backlog
worklane ls done # List completed tickets
worklane ls # List all tickets
worklane ls backlog # List tickets in backlog
worklane ls done # List completed tickets
worklane ls --priority 1 # Only the most urgent, any status
worklane ls backlog --priority 2 # Composes with the status filter
```
Tickets are listed priority first, then by title. Tickets with no priority sort last.
### `worklane show`
Show the full details of a single ticket by UUID or title.
@@ -74,7 +79,7 @@ worklane show "ticket title or uuid"
Move a ticket between statuses.
**Positional arguments:**
- `<id>`: Ticket UUID (8+ characters) or title
- `<id>`: Ticket UUID prefix (4+ characters) or title
**Required options:**
- `--status <target>`: Target status (`backlog`, `committed`, `reviewing`, `done`)
@@ -98,7 +103,7 @@ worklane mv "My Ticket" --status done -f # Move by title with force
Add a comment to a ticket.
**Positional arguments:**
- `<ticket>`: Ticket UUID (8+ characters) or title
- `<ticket>`: Ticket UUID prefix (4+ characters) or title
- `<body>`: Comment text
Comments are stored as timestamped markdown files in `.worklane/comments/<ticket-uuid>/` and include the git author and timestamp.
+14 -4
View File
@@ -76,6 +76,10 @@ export const add = tool({
owner: tool.schema
.string()
.describe("Ticket owner name. If omitted, defaults to the git user."),
priority: tool.schema
.string()
.describe("Priority level, 1 (most urgent) to 5 (least). Left unset if omitted.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.title) {
@@ -109,6 +113,7 @@ export const add = tool({
if (args.tags) cmd.push("--tags", args.tags);
if (args.due) cmd.push("--due", args.due);
if (args.owner) cmd.push("--owner", args.owner);
if (args.priority) cmd.push("--priority", String(args.priority));
try {
return await run(cmd, context);
@@ -120,15 +125,20 @@ export const add = tool({
export const ls = tool({
description:
"List all worklane tickets. Optionally filter by status (backlog, committed, reviewing, done).",
"List all worklane tickets, sorted by priority then title. Optionally filter by status and by priority.",
args: {
status: tool.schema
.enum(["backlog", "committed", "reviewing", "done"])
.describe("Filter by status")
.optional(),
priority: tool.schema
.string()
.describe("Only show tickets at this priority, 1 (most urgent) to 5 (least)")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
const cmd = args.status ? ["ls", args.status] : ["ls"];
if (args.priority) cmd.push("--priority", String(args.priority));
try {
return await run(cmd, context);
} catch (err: any) {
@@ -145,7 +155,7 @@ export const show = tool({
args: {
id: tool.schema
.string()
.describe("Ticket UUID (8+ chars) or title substring (required)"),
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.id) {
@@ -165,7 +175,7 @@ export const mv = tool({
args: {
ticket: tool.schema
.string()
.describe("Ticket UUID (8+ chars) or title substring (required)"),
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
status: tool.schema
.enum(["backlog", "committed", "reviewing", "done"])
.describe("Target status (required)"),
@@ -197,7 +207,7 @@ export const comment = tool({
args: {
ticket: tool.schema
.string()
.describe("Ticket UUID (8+ chars) or title substring (required)"),
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
body: tool.schema
.string()
.describe("Comment body text (required). Supports markdown formatting and multiple paragraphs separated by newlines."),
+33 -5
View File
@@ -8,7 +8,7 @@
## Ticket File Format
- Filenames: `<uuid_v4>_<slug>.md`
- Metadata fields parsed by `parse_ticket_field()`: `ID`, `Tags`, `Due`, `Owner`, `Created At`, `Status`
- Metadata fields parsed by `parse_ticket_field()`: `ID`, `Priority`, `Tags`, `Due`, `Owner`, `Created At`, `Status`
- Format: `**Field Name**: value`
- Ticket structure: `# Title` → `## Description` → `## Acceptance Criteria` → `## Implementation Plan` → `## Metadata`
- Comments stored in `.worklane/comments/<ticket_uuid>/<timestamp>.md` with `**Comment**`, `**Author**`, `**Time**` fields
@@ -31,28 +31,45 @@
- 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
### 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
- 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
### Color and Output
- Use `color_text()` helper for colored output — it respects `should_use_colors()` (terminal detection)
- Color codes are defined in `get_color()`: red (31), cyan (36), orange (33), green (32), grey (90)
- Color codes are defined in `get_color()`: red (31), cyan (36), orange (33), green (32), grey (38;5;8), magenta (1;35), brightred (38;5;9)
- 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 (90)
- 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
- 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
- Colorization functions (`colorize_line`, `colorize_metadata`, `colorize_ordered`, `content_trim_colored`) handle markdown formatting
- Colorization functions (`colorize_line`, `colorize_ordered`, `content_trim_colored`) handle markdown formatting
- `show` renders the Metadata section as a two column table via `render_metadata_table`, not line by line. Column width is measured on the raw field names in characters and padding is applied before anything is styled: measuring a coloured 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
- Priority: exact UUID prefix (8+ chars) > title substring > filename substring
- Three tiers, evaluated in order: UUID prefix > title substring > filename substring. The first non-empty tier wins outright and later tiers are not consulted. This is not cosmetic: ticket titles reference other tickets by id, so a flat OR of the three reported an exact prefix match as ambiguous against whichever title mentioned it
- 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 `_Not set_` or `_None_` as defaults
@@ -60,3 +77,14 @@
- 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
- 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
- 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
- Bump `Cargo.toml` and the `worklane` entry in `Cargo.lock` together, in the commit that carries the bump
- 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
Generated
+2 -1
View File
@@ -1029,13 +1029,14 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.1.0"
version = "0.4.0"
dependencies = [
"anyhow",
"assert_cmd",
"assert_fs",
"chrono",
"clap",
"libc",
"tempfile",
"uuid",
]
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "worklane"
version = "0.1.0"
version = "0.4.0"
edition = "2024"
[dependencies]
@@ -8,6 +8,7 @@ clap = { version = "4", features = ["derive"] }
anyhow = "1"
uuid = { version = "1", features = ["v4"] }
chrono = { version = "0.4", features = ["serde"] }
libc = "0.2"
[dev-dependencies]
assert_cmd = "2"
+16 -3
View File
@@ -6,8 +6,21 @@ Worklane is a local Kanban flow for agentic software development.
| Command | Description |
|---------|-------------|
| `worklane init` | Creates `.worklane/` with backlog, committed, reviewing, done directories |
| `worklane add` | Creates a ticket in backlog with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--owner` flags |
| `worklane ls` | Lists tickets, optionally filtered by `--status` |
| `worklane show <id>` | Shows ticket by UUID prefix (8+ chars) or title substring |
| `worklane add` | Creates a ticket in backlog with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--owner`, `--priority` flags |
| `worklane ls [status]` | Lists tickets, sorted by priority then title. Optional positional status, and `--priority <1-5>` |
| `worklane show <id>` | Shows ticket by UUID prefix (4+ chars), title substring, or filename substring |
| `worklane mv <id> --status <target> [-f]` | Moves ticket between statuses. Default: forward only, one stage at a time. `-f` bypasses both restrictions |
| `worklane comment <ticket> <body>` | Adds a comment to a ticket by UUID or title |
## Exit codes
| Code | Meaning |
|------|---------|
| 0 | Success |
| 1 | An error, such as no matching ticket or an ambiguous search |
| 2 | A usage mistake, such as an unknown flag |
| 141 | Output was piped to a reader that stopped early, for example `worklane ls \| head -3` |
141 is 128 + 13, the shell's way of reporting death by `SIGPIPE`. Worklane restores
the default signal disposition so a truncated pipe is quiet, the way `head` and
`sort` are, rather than printing a panic. A script using `set -o pipefail` will see
141 for a case that is not a failure, so guard for it there.
+45 -4
View File
@@ -1,5 +1,25 @@
use clap::Parser;
use std::sync::LazyLock;
use crate::util::{PRIORITY_RANGE, priority_legend};
/// clap wants a `&str` with a long enough lifetime, and the legend is built from
/// the same ramp the listing uses rather than spelled out a second time.
static PRIORITY_LEGEND: LazyLock<String> = LazyLock::new(priority_legend);
/// Reject a level outside the range at parse time, so no command has to.
fn priority_level(raw: &str) -> Result<u8, String> {
match raw.parse::<u8>() {
Ok(level) if PRIORITY_RANGE.contains(&level) => Ok(level),
_ => Err(format!(
"priority must be a whole number from {} to {}",
PRIORITY_RANGE.start(),
PRIORITY_RANGE.end()
)),
}
}
/// What `--version` prints: the crate version and the commit it was built from.
///
/// The sha is the part that matters. Two binaries built weeks apart both call
@@ -17,6 +37,17 @@ pub struct Cli {
pub command: Command,
}
/// 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
/// 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.
const PROSE: bool = true;
#[derive(clap::Subcommand)]
pub enum Command {
/// Initialize worklane in the current project
@@ -25,19 +56,19 @@ pub enum Command {
/// Add a new ticket to the backlog
Add {
/// Ticket title
#[arg(short, long)]
#[arg(short, long, allow_hyphen_values = PROSE)]
title: String,
/// Ticket description. Use multiple flags to create multiline descriptions.
#[arg(short, long)]
#[arg(short, long, allow_hyphen_values = PROSE)]
description: Vec<String>,
/// Acceptance criteria. Accepts multiple flags, each will be interpreted as a single criterium
#[arg(short, long)]
#[arg(short, long, allow_hyphen_values = PROSE)]
acceptance: Vec<String>,
/// Implementation plan. Accepts multiple flags, each will be interpreted as a single step
#[arg(short, long)]
#[arg(short, long, allow_hyphen_values = PROSE)]
plan: Vec<String>,
/// Tags (comma-separated)
@@ -51,12 +82,21 @@ pub enum Command {
/// Owner
#[arg(short, long)]
owner: Option<String>,
/// Priority, 1 (most urgent) to 5 (least). Left unset if omitted.
#[arg(long, value_parser = priority_level)]
priority: Option<u8>,
},
/// List tickets, optionally filtered by status
#[command(after_help = PRIORITY_LEGEND.as_str())]
Ls {
/// Filter by status (backlog, committed, reviewing, done)
status: Option<String>,
/// Only show tickets at this priority, 1 (most urgent) to 5 (least)
#[arg(long, value_parser = priority_level)]
priority: Option<u8>,
},
/// Show a ticket by UUID or title
@@ -85,6 +125,7 @@ pub enum Command {
ticket: String,
/// Comment body (required)
#[arg(allow_hyphen_values = PROSE)]
body: String,
/// Owner
+178 -18
View File
@@ -1,6 +1,7 @@
use anyhow::{Result, anyhow};
use chrono::Local;
use std::fs;
use std::io::Write;
use std::path::Path;
use crate::util::*;
@@ -28,7 +29,11 @@ pub fn cmd_init(start: &Path) -> Result<()> {
Ok(())
}
pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()> {
pub fn cmd_ls(
status_filter: &Option<String>,
priority_filter: Option<u8>,
worklane_dir: &Path,
) -> Result<()> {
if let Some(status) = status_filter {
let status_path = worklane_dir.join(status);
if !status_path.exists() {
@@ -38,7 +43,7 @@ pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()>
));
}
let items = collect_ticket_items(&status_path)?;
let items = filter_by_priority(collect_ticket_items(&status_path)?, priority_filter);
if items.is_empty() {
println!("No tickets in '{}' status.", status);
@@ -56,8 +61,8 @@ pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()>
if !status_path.exists() {
continue;
}
let entries: Vec<_> = fs::read_dir(&status_path)?.filter_map(|e| e.ok()).collect();
let count = entries.len();
let items = filter_by_priority(collect_ticket_items(&status_path)?, priority_filter);
let count = items.len();
let label = if count == 1 { "ticket" } else { "tickets" };
println!(" [{}] {} {}", status.to_uppercase(), count, label);
}
@@ -72,7 +77,7 @@ pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()>
continue;
}
let items = match collect_ticket_items(&status_path) {
Ok(items) => items,
Ok(items) => filter_by_priority(items, priority_filter),
Err(_) => continue,
};
if items.is_empty() {
@@ -87,6 +92,17 @@ pub fn cmd_ls(status_filter: &Option<String>, worklane_dir: &Path) -> Result<()>
Ok(())
}
/// Keep only the tickets at `level`, or everything when no level was asked for.
fn filter_by_priority(items: Vec<TicketItem>, level: Option<u8>) -> Vec<TicketItem> {
match level {
Some(level) => items
.into_iter()
.filter(|item| item.priority == Priority::Level(level))
.collect(),
None => items,
}
}
pub fn cmd_add(
title: &str,
description: &[String],
@@ -95,6 +111,7 @@ pub fn cmd_add(
tags: &[String],
due: &Option<String>,
owner: &Option<String>,
priority: Option<u8>,
start: &Path,
) -> Result<()> {
let owner = match owner {
@@ -140,6 +157,7 @@ pub fn cmd_add(
## Metadata\n\
\n\
- **ID**: {}\n\
- **Priority**: {}\n\
- **Tags**: {}\n\
- **Due**: {}\n\
- **Owner**: {}\n\
@@ -167,6 +185,10 @@ pub fn cmd_add(
.join("\n")
},
id,
match priority {
Some(level) => level.to_string(),
None => "_Not set_".to_string(),
},
if tags.is_empty() {
"_None_".to_string()
} else {
@@ -234,12 +256,49 @@ fn read_comments(comments_dir: &Path) -> Result<Vec<(String, String, String, Str
Ok(comments)
}
/// Write a comment under the first free name derived from `stem`.
///
/// `create_new` rather than `fs::write`: a name that already exists means another
/// comment landed in the same microsecond, and truncating it is exactly the data
/// loss this guards against. The suffix is zero padded so the names keep sorting
/// in the order they were written.
fn write_new_comment(comments_dir: &Path, stem: &str, content: &str) -> Result<String> {
for attempt in 0..100 {
let filename = match attempt {
0 => format!("{}.md", stem),
n => format!("{}_{:02}.md", stem, n),
};
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(comments_dir.join(&filename))
{
Ok(mut file) => {
file.write_all(content.as_bytes())?;
return Ok(filename);
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e.into()),
}
}
Err(anyhow!(
"No free comment filename for '{}' in {}",
stem,
comments_dir.display()
))
}
pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
let (_status, title, content) = resolve_ticket(search, worklane_dir)?;
let ticket_uuid = parse_ticket_field(&content, "ID");
println!("{}", title);
println!("{}", "─".repeat(title.len()));
// The only title in the output: content_trim_colored used to print it a second
// time from the file content. Green per the colour guideline, and the rule is
// measured in characters so a non-ASCII title is not over-drawn.
println!("{}", color_text(&title, "green"));
println!("{}", "─".repeat(title.chars().count()));
println!("\n{}", content_trim_colored(&content));
if ticket_uuid != "_Not set_" {
@@ -252,6 +311,67 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
Ok(())
}
/// Put `content` in `filename` and move it from `from` to `to`, without ever
/// leaving the ticket in two status directories or with half a file in it.
///
/// Two atomic steps, in this order. The content is staged in a temp file and
/// renamed over the source, so a partial write is thrown away and the original is
/// untouched. Only then is the file renamed into the target directory.
///
/// The old order renamed first and wrote second, so a failure in between left the
/// ticket sitting in its new directory still claiming the old status. Writing
/// straight to the target and deleting the source afterwards would instead have it
/// in both directories at once. Neither happens here. The worst case is a ticket
/// still in its old directory carrying a Status field one move ahead, which the
/// next `mv` corrects, since the directory is what decides the current status.
fn move_ticket_file(
worklane_dir: &Path,
from: &Path,
to: &Path,
filename: &str,
content: &str,
title: &str,
) -> Result<()> {
let source = from.join(filename);
let dest = to.join(filename);
// Staged outside the status directories on purpose: a temp file left behind by a
// hard kill is then invisible to ticket lookup and to the listing, rather than
// showing up as a stray untitled ticket.
let temp = worklane_dir.join(format!(".mv-{}.tmp", filename));
if let Err(e) = fs::write(&temp, content) {
let _ = fs::remove_file(&temp);
return Err(anyhow!(
"Could not stage the update for ticket '{}' at {}: {}",
title,
temp.display(),
e
));
}
if let Err(e) = fs::rename(&temp, &source) {
let _ = fs::remove_file(&temp);
return Err(anyhow!(
"Could not update the status of ticket '{}' at {}: {}",
title,
source.display(),
e
));
}
// The content is correct and in one place by now, so a failure here leaves the
// ticket where it started rather than half moved.
fs::rename(&source, &dest).map_err(|e| {
anyhow!(
"Could not move ticket '{}' to {}: {}",
title,
dest.display(),
e
)
})
}
pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -> Result<()> {
let valid_statuses = ["backlog", "committed", "reviewing", "done"];
let forward_order = ["backlog", "committed", "reviewing", "done"];
@@ -331,15 +451,24 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -
// Read and update the ticket content before touching the filesystem, so a ticket
// without a Status field is never half-moved.
let source_path = current_path.join(&found_filename);
let content = fs::read_to_string(&source_path)?;
let content = fs::read_to_string(&source_path).map_err(|e| {
anyhow!(
"Could not read ticket '{}' at {}: {}",
title,
source_path.display(),
e
)
})?;
let content = set_status_field(&content, target_status, &title)?;
// Move the file
let dest_path = target_path.join(&found_filename);
fs::rename(&source_path, &dest_path)?;
// Write back updated content
fs::write(&dest_path, content)?;
move_ticket_file(
&worklane_dir,
&current_path,
&target_path,
&found_filename,
&content,
&title,
)?;
println!(
"Moved ticket '{}' from {} to {}",
@@ -351,6 +480,39 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// The collision path cannot be provoked from the CLI, since two processes
/// will not share a microsecond, but it is the whole point of the guard.
#[test]
fn a_colliding_stem_takes_the_next_name_and_keeps_the_first() {
let dir = std::env::temp_dir().join(format!("worklane-test-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&dir).unwrap();
let first = write_new_comment(&dir, "20260820_143012_123456", "first").unwrap();
let second = write_new_comment(&dir, "20260820_143012_123456", "second").unwrap();
let third = write_new_comment(&dir, "20260820_143012_123456", "third").unwrap();
assert_eq!(first, "20260820_143012_123456.md");
assert_eq!(second, "20260820_143012_123456_01.md");
assert_eq!(third, "20260820_143012_123456_02.md");
// Nothing was truncated on the way through
assert_eq!(fs::read_to_string(dir.join(&first)).unwrap(), "first");
assert_eq!(fs::read_to_string(dir.join(&second)).unwrap(), "second");
assert_eq!(fs::read_to_string(dir.join(&third)).unwrap(), "third");
// read_comments sorts on the stem, so the names must sort in write order
let mut names = vec![second.clone(), third.clone(), first.clone()];
names.sort();
assert_eq!(names, vec![first, second, third]);
fs::remove_dir_all(&dir).unwrap();
}
}
pub fn cmd_comment(
ticket_id: &str,
body: &str,
@@ -372,9 +534,7 @@ pub fn cmd_comment(
let comments_dir = worklane_dir.join("comments").join(&ticket_uuid);
fs::create_dir_all(&comments_dir)?;
let timestamp = Local::now().format("%Y%m%d_%H%M%S");
let filename = format!("{}.md", timestamp);
let filepath = comments_dir.join(&filename);
let stem = Local::now().format(COMMENT_FILE_FORMAT).to_string();
let author = match owner {
Some(o) => o.clone(),
@@ -393,7 +553,7 @@ pub fn cmd_comment(
Local::now().format(TIMESTAMP_FORMAT)
);
fs::write(&filepath, comment_content)?;
let filename = write_new_comment(&comments_dir, &stem, &comment_content)?;
println!("Comment added to '{}' ({})", title, filename);
Ok(())
+25 -2
View File
@@ -9,7 +9,28 @@ use command::*;
use handlers::*;
use util::*;
/// Die quietly when stdout is closed early, the way every other Unix tool does.
///
/// Rust sets `SIGPIPE` to `SIG_IGN` at startup, which turns a closed pipe into an
/// io error that `println!` panics on. So `worklane ls | head -3` printed a panic
/// and a backtrace instead of three lines, which is both alarming and easy to
/// mistake for a real fault. Restoring the default handler makes `| head` behave.
///
/// The cost is that a truncated pipe now kills the process with signal 13 rather
/// than returning a code, so `pipefail` sees 141 instead of 101. That is what
/// `head` and `sort` do, and it is recorded in the README.
fn quiet_broken_pipe() {
// SAFETY: setting a signal disposition to the default is always valid, and
// this runs before any thread is spawned.
unsafe {
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
}
}
fn main() -> Result<()> {
// Before any output, so no write can beat it to a closed pipe.
quiet_broken_pipe();
let cli = Cli::parse();
let start = std::env::current_dir()?;
@@ -24,6 +45,7 @@ fn main() -> Result<()> {
tags,
due,
owner,
priority,
} => cmd_add(
&title,
&description,
@@ -32,11 +54,12 @@ fn main() -> Result<()> {
&tags,
&due,
&owner,
priority,
&start,
),
Command::Ls { status } => {
Command::Ls { status, priority } => {
let worklane_dir = find_worklane_dir(&start)?;
cmd_ls(&status, &worklane_dir)
cmd_ls(&status, priority, &worklane_dir)
}
Command::Show { id } => {
let worklane_dir = find_worklane_dir(&start)?;
+936 -115
View File
File diff suppressed because it is too large Load Diff
+173
View File
@@ -0,0 +1,173 @@
use assert_fs::TempDir;
use assert_fs::fixture::{PathChild, PathCreateDir};
use std::fs;
use std::os::unix::process::ExitStatusExt;
use std::process::{Command, Stdio};
const BIN_NAME: &str = env!("CARGO_BIN_EXE_worklane");
/// What a truncated pipe costs: the process dies by signal rather than returning a
/// code, so a shell reports 128 + 13. Asserted here so the README and the code stay
/// honest about what `pipefail` sees.
const SIGPIPE: i32 = 13;
/// A pipe holds 64 KiB on Linux before a write blocks. Below that the whole listing
/// lands in the buffer, the writer never notices the reader is gone, and a test
/// proves nothing. Every ticket here is one `ls` row of roughly a hundred bytes.
const TICKETS: usize = 1200;
fn setup_crowded_board(temp: &TempDir) -> std::path::PathBuf {
let worklane = temp.child(".worklane");
worklane.create_dir_all().unwrap();
for dir in ["backlog", "committed", "reviewing", "done"] {
worklane.child(dir).create_dir_all().unwrap();
}
let backlog = worklane.path().join("backlog");
for i in 0..TICKETS {
let id = format!("{:08x}-0000-4000-8000-000000000000", i);
let title = format!("A ticket with a title long enough to fill a row {}", i);
fs::write(
backlog.join(format!("{}_ticket-{}.md", id, i)),
format!(
"# {}\n\n## Metadata\n\n\
- **ID**: {}\n\
- **Owner**: someone with a name\n\
- **Status**: backlog\n",
title, id
),
)
.unwrap();
}
temp.path().to_path_buf()
}
fn panic_text(stderr: &str) -> bool {
stderr.contains("panicked")
|| stderr.contains("failed printing to stdout")
|| stderr.contains("Broken pipe")
}
/// The reader closed before the writer finished: dropping the read end here is the
/// same thing `head` does when it has seen enough, without the timing luck.
fn run_with_stdout_dropped(dir: &std::path::Path, args: &[&str]) -> std::process::Output {
let mut child = Command::new(BIN_NAME)
.args(args)
.current_dir(dir)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
drop(child.stdout.take().unwrap());
child.wait_with_output().unwrap()
}
#[test]
fn ls_says_nothing_when_the_reader_goes_away() {
let temp = TempDir::new().unwrap();
let dir = setup_crowded_board(&temp);
let output = run_with_stdout_dropped(&dir, &["ls", "backlog"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!panic_text(&stderr), "stderr was {stderr:?}");
assert_ne!(output.status.code(), Some(101), "panicked instead of dying");
assert_eq!(
output.status.signal(),
Some(SIGPIPE),
"expected death by SIGPIPE, got {:?}",
output.status
);
}
#[test]
fn show_says_nothing_when_the_reader_goes_away() {
let temp = TempDir::new().unwrap();
let dir = setup_crowded_board(&temp);
// A ticket carrying more comments than a pipe will hold, since the comment list
// is the longest thing show prints and the last thing it reaches.
let comments = temp
.path()
.join(".worklane")
.join("comments")
.join("00000000-0000-4000-8000-000000000000");
fs::create_dir_all(&comments).unwrap();
for i in 0..800 {
fs::write(
comments.join(format!("2026082{}_120000_{:06}.md", i % 10, i)),
format!(
"**Comment**\nA comment body long enough to be worth buffering, number {}.\n\n\
**Author**: someone\n**Time**: 2026-08-20 12:00:00\n",
i
),
)
.unwrap();
}
let output = run_with_stdout_dropped(&dir, &["show", "00000000-0000-4000"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(!panic_text(&stderr), "stderr was {stderr:?}");
assert_ne!(output.status.code(), Some(101), "panicked instead of dying");
assert_eq!(
output.status.signal(),
Some(SIGPIPE),
"expected death by SIGPIPE, got {:?}",
output.status
);
}
/// The real invocation, through a shell into `head`, which is how this was found.
/// Whether the writer gets far enough to notice is up to the scheduler, so this
/// asserts only what must hold either way: `head` gets its lines and nothing
/// alarming reaches stderr.
#[test]
fn a_shell_pipeline_into_head_prints_lines_and_not_a_panic() {
let temp = TempDir::new().unwrap();
let dir = setup_crowded_board(&temp);
let output = Command::new("sh")
.arg("-c")
.arg(format!("{} ls backlog | head -3", BIN_NAME))
.current_dir(&dir)
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(stdout.lines().count(), 3, "stdout was {stdout:?}");
assert!(!panic_text(&stderr), "stderr was {stderr:?}");
}
/// The reset must not touch anything else: a real failure still returns its code.
#[test]
fn real_exit_codes_are_unchanged() {
let temp = TempDir::new().unwrap();
let dir = setup_crowded_board(&temp);
let ok = Command::new(BIN_NAME)
.args(["ls", "backlog"])
.current_dir(&dir)
.output()
.unwrap();
assert_eq!(ok.status.code(), Some(0));
let missing = Command::new(BIN_NAME)
.args(["show", "no-such-ticket-anywhere"])
.current_dir(&dir)
.output()
.unwrap();
assert_eq!(missing.status.code(), Some(1));
let misuse = Command::new(BIN_NAME)
.arg("--bogus")
.current_dir(&dir)
.output()
.unwrap();
assert_eq!(misuse.status.code(), Some(2));
}
+181
View File
@@ -199,3 +199,184 @@ fn add_file_has_uuid_prefix() {
assert_eq!(parts[0].len(), 36);
assert_eq!(parts[0].chars().filter(|c| c.is_ascii_hexdigit()).count(), 32);
}
#[test]
fn add_writes_the_priority_field() {
let temp = TempDir::new().unwrap();
setup_worklane(&temp);
Command::cargo_bin(BIN_NAME)
.unwrap()
.current_dir(&temp.path())
.args(["add", "--title", "Urgent thing", "--priority", "1"])
.assert()
.success();
let files: Vec<_> = fs::read_dir(temp.child(".worklane").join("backlog"))
.unwrap()
.filter_map(|e| e.ok())
.collect();
let content = fs::read_to_string(files[0].path()).unwrap();
assert!(content.contains("- **Priority**: 1"), "was {content:?}");
}
#[test]
fn add_leaves_priority_unset_when_omitted() {
let temp = TempDir::new().unwrap();
setup_worklane(&temp);
Command::cargo_bin(BIN_NAME)
.unwrap()
.current_dir(&temp.path())
.args(["add", "--title", "Whenever"])
.assert()
.success();
let files: Vec<_> = fs::read_dir(temp.child(".worklane").join("backlog"))
.unwrap()
.filter_map(|e| e.ok())
.collect();
let content = fs::read_to_string(files[0].path()).unwrap();
assert!(content.contains("- **Priority**: _Not set_"), "was {content:?}");
}
/// Rejected at parse time, so no ticket is written at all.
#[test]
fn add_rejects_a_level_outside_the_range() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
// The `=` form, so a negative value reaches the validator instead of being
// read as a flag.
for bad in ["0", "6", "high", "-1"] {
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["add", "--title", "Bad level", &format!("--priority={bad}")])
.assert()
.failure();
let stderr = String::from_utf8(cmd.assert().get_output().stderr.clone()).unwrap();
assert!(stderr.contains("priority must be"), "for {bad}: {stderr}");
}
let count = fs::read_dir(worklane.join("backlog")).unwrap().count();
assert_eq!(count, 0, "a ticket was written despite a bad level");
}
/// Ticket text quotes flag names constantly, and the space form is what both a
/// person and the opencode wrapper produce. Every one of these used to be refused
/// with "unexpected argument found", writing no ticket at all.
#[test]
fn add_accepts_prose_values_that_begin_with_a_hyphen() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["add", "--title", "-t is a flag name"])
.args(["--description", "-x does nothing"])
.args(["--acceptance", "--print should be supported"])
.args(["--plan", "-f skips the check"])
.assert()
.success();
let content = only_ticket(&worklane);
// Stored verbatim, hyphens and all
assert!(content.contains("# -t is a flag name"), "was {content:?}");
assert!(content.contains("-x does nothing"), "was {content:?}");
assert!(
content.contains("- [ ] --print should be supported"),
"was {content:?}"
);
assert!(content.contains("1. -f skips the check"), "was {content:?}");
}
/// The docs and the habit both use it, and it reaches the parser as one token, so
/// it has to keep working alongside the space form.
#[test]
fn add_still_accepts_the_equals_form() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["add", "--title=-x equals form"])
.args(["--acceptance=--print via equals"])
.assert()
.success();
let content = only_ticket(&worklane);
assert!(content.contains("# -x equals form"), "was {content:?}");
assert!(
content.contains("- [ ] --print via equals"),
"was {content:?}"
);
}
/// Never silently dropped: a value that is nothing but hyphens is content.
#[test]
fn add_stores_a_title_that_is_only_hyphens() {
for bare in ["-", "--", "---"] {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["add", "--title", bare])
.assert()
.success();
let content = only_ticket(&worklane);
assert!(
content.starts_with(&format!("# {}\n", bare)),
"for {bare:?}: {content:?}"
);
}
}
/// The other half of the trade. These arguments were deliberately left alone, so a
/// mistyped flag there is still a usage error rather than stored text.
#[test]
fn add_still_rejects_a_mistyped_flag_on_a_non_prose_argument() {
for flag in ["--due", "--priority", "--tags", "--owner"] {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["add", "--title", "Mistyped", flag, "--bogus"])
.assert()
.failure();
let count = fs::read_dir(worklane.join("backlog")).unwrap().count();
assert_eq!(count, 0, "{flag} wrote a ticket anyway");
}
}
/// `add` has no positionals, so a bare `--` ends the options and whatever follows
/// has nowhere to go. Recorded because clap's separator and a hyphen-leading value
/// are easy to confuse.
#[test]
fn add_rejects_arguments_after_a_bare_separator() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["add", "--title", "Sep", "--", "--title", "second"])
.assert()
.failure();
let count = fs::read_dir(worklane.join("backlog")).unwrap().count();
assert_eq!(count, 0);
}
fn only_ticket(worklane: &PathBuf) -> String {
let files: Vec<_> = fs::read_dir(worklane.join("backlog"))
.unwrap()
.filter_map(|e| e.ok())
.collect();
assert_eq!(files.len(), 1, "expected exactly one ticket");
fs::read_to_string(files[0].path()).unwrap()
}
+127
View File
@@ -212,3 +212,130 @@ fn comment_falls_back_to_git_user_when_owner_omitted() {
let content = fs::read_to_string(files[0].path()).unwrap();
assert!(content.contains("**Author**"));
}
/// Second-resolution filenames meant the second of two quick comments
/// truncated the first.
#[test]
fn comments_added_back_to_back_are_both_kept() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let uuid = create_ticket(&worklane, "backlog", "Rapid Fire");
for body in ["first comment", "second comment", "third comment"] {
Command::cargo_bin(BIN_NAME)
.unwrap()
.current_dir(&temp.path())
.arg("comment")
.args([&uuid, body])
.assert()
.success();
}
let comments_dir = worklane.join("comments").join(&uuid);
let files: Vec<_> = fs::read_dir(&comments_dir)
.unwrap()
.filter_map(|e| e.ok())
.collect();
assert_eq!(files.len(), 3, "a comment was overwritten");
// And show has to render them in the order they were added
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("show").arg(&uuid);
let assert = cmd.assert().success();
let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
let first = stdout.find("first comment").expect("first comment missing");
let second = stdout.find("second comment").expect("second comment missing");
let third = stdout.find("third comment").expect("third comment missing");
assert!(first < second && second < third, "comments out of order");
}
/// The body is a positional, and the case that motivated this: a review comment
/// quoting a flag name used to be refused outright.
#[test]
fn comment_accepts_a_body_that_begins_with_a_hyphen() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let uuid = create_ticket(&worklane, "backlog", "Hyphen body");
for body in ["--print is the flag I mean", "-f skips the check", "-"] {
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["comment", &uuid, body])
.assert()
.success();
}
let bodies: String = fs::read_dir(worklane.join("comments").join(&uuid))
.unwrap()
.filter_map(|e| e.ok())
.map(|e| fs::read_to_string(e.path()).unwrap())
.collect();
for body in ["--print is the flag I mean", "-f skips the check"] {
assert!(bodies.contains(body), "{body:?} missing from {bodies:?}");
}
}
/// The ticket positional was deliberately left alone, so a hyphen-leading search
/// term is still a usage error. A bare separator is the way through, and it is the
/// only way through for `comment` since the body follows in the same position.
#[test]
fn comment_needs_a_separator_for_a_hyphen_leading_ticket() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(&worklane, "backlog", "-leading");
let mut without = Command::cargo_bin(BIN_NAME).unwrap();
without
.current_dir(&temp.path())
.args(["comment", "-leading", "a body"])
.assert()
.failure();
let mut with = Command::cargo_bin(BIN_NAME).unwrap();
with.current_dir(&temp.path())
.args(["comment", "--", "-leading", "a body"])
.assert()
.success();
}
/// The one shape `allow_hyphen_values` does not reach: a lone `--` in a positional
/// is clap's end-of-options marker, consumed before any value is assigned. So a
/// comment body of exactly `--` needs its own separator in front of it.
///
/// Not a silent drop either way, which is what matters: without the separator the
/// body is reported missing and nothing is written.
#[test]
fn a_bare_double_hyphen_body_needs_a_separator() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let uuid = create_ticket(&worklane, "backlog", "Bare separator");
let mut without = Command::cargo_bin(BIN_NAME).unwrap();
let assert = without
.current_dir(&temp.path())
.args(["comment", &uuid, "--"])
.assert()
.failure();
let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
assert!(stderr.contains("<BODY>"), "unclear error: {stderr}");
assert!(
!worklane.join("comments").join(&uuid).exists(),
"a comment was written despite the error"
);
let mut with = Command::cargo_bin(BIN_NAME).unwrap();
with.current_dir(&temp.path())
.args(["comment", &uuid, "--", "--"])
.assert()
.success();
let stored: String = fs::read_dir(worklane.join("comments").join(&uuid))
.unwrap()
.filter_map(|e| e.ok())
.map(|e| fs::read_to_string(e.path()).unwrap())
.collect();
assert!(stored.contains("**Comment**\n--\n"), "was {stored:?}");
}
+80
View File
@@ -216,3 +216,83 @@ fn ls_survives_a_malformed_created_at() {
// Unparseable, so the timestamp column is dropped rather than printed raw
assert!(!stdout.contains("日本語"));
}
fn create_ticket_with_priority(worklane_dir: &std::path::PathBuf, title: &str, priority: &str) {
let slug: String = title.to_lowercase().replace(' ', "-");
let body = format!(
"# {}\n\n## Metadata\n\n- **ID**: 00000000-0000-0000-0000-00000000000{}\n\
- **Priority**: {}\n- **Tags**: test\n- **Due**: _Not set_\n\
- **Owner**: alice\n- **Status**: backlog\n",
title,
slug.len() % 10,
priority
);
let filename = format!("0000000{}-0000-0000-0000-000000000001_{}.md", slug.len() % 10, slug);
fs::write(worklane_dir.join("backlog").join(filename), body).unwrap();
}
#[test]
fn ls_sorts_by_priority_then_title() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket_with_priority(&worklane, "Zebra urgent", "1");
create_ticket_with_priority(&worklane, "Apple later", "4");
create_ticket_with_priority(&worklane, "Middle one", "2");
create_ticket(&worklane, "backlog", "No priority at all", "alice", "_Not set_");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("ls").arg("backlog");
let stdout = get_stdout(&mut cmd);
let at = |needle: &str| stdout.find(needle).unwrap_or_else(|| panic!("{needle} missing"));
assert!(at("Zebra urgent") < at("Middle one"), "priority 1 must lead");
assert!(at("Middle one") < at("Apple later"), "2 before 4");
// Unset sorts last even though its title would come first alphabetically
assert!(at("Apple later") < at("No priority at all"), "unset must trail");
}
#[test]
fn ls_filters_by_priority_and_composes_with_status() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket_with_priority(&worklane, "Urgent one", "1");
create_ticket_with_priority(&worklane, "Lower one", "3");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["ls", "backlog", "--priority", "1"]);
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Urgent one"));
assert!(!stdout.contains("Lower one"), "filter let a level 3 through");
// Same filter without a status, through the grouped listing
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).args(["ls", "--priority", "3"]);
let stdout = get_stdout(&mut cmd);
assert!(stdout.contains("Lower one"));
assert!(!stdout.contains("Urgent one"));
}
#[test]
fn ls_shows_a_mark_for_the_level() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket_with_priority(&worklane, "Top level", "1");
create_ticket_with_priority(&worklane, "Bottom level", "5");
create_ticket(&worklane, "backlog", "Nothing set", "alice", "_Not set_");
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("ls").arg("backlog");
let stdout = get_stdout(&mut cmd);
// Piped, so no escapes: the glyph is carrying the level by itself
assert!(!stdout.contains('\u{1b}'));
assert!(stdout.contains("\u{25cf}\u{25cf} "), "no full meter for level 1 in {stdout:?}");
assert!(stdout.contains("\u{25cb}\u{25cb} "), "no empty meter for level 5");
assert!(stdout.contains("\u{b7}\u{b7} "), "no unset mark");
// The raw number is not what the listing shows
assert!(!stdout.contains(" 1 "), "the digit leaked into the row");
}
+171
View File
@@ -431,3 +431,174 @@ fn mv_fails_when_status_field_is_missing() {
assert!(worklane.join("backlog").join(filename).exists());
assert!(!worklane.join("committed").join(filename).exists());
}
use std::os::unix::fs::PermissionsExt;
fn chmod(path: &std::path::Path, mode: u32) {
let mut perms = fs::metadata(path).unwrap().permissions();
perms.set_mode(mode);
fs::set_permissions(path, perms).unwrap();
}
fn md_files(dir: &std::path::Path) -> Vec<String> {
match fs::read_dir(dir) {
Ok(entries) => entries
.filter_map(|e| e.ok())
.map(|e| e.file_name().into_string().unwrap())
.filter(|name| name.ends_with(".md"))
.collect(),
Err(_) => vec![],
}
}
/// Nothing is staged in a status directory, so nothing can be left behind that the
/// listing would read as a ticket.
fn stray_files(worklane: &std::path::Path) -> Vec<String> {
let mut stray: Vec<String> = fs::read_dir(worklane)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name().into_string().unwrap())
.filter(|name| !["backlog", "committed", "reviewing", "done", "comments"].contains(&name.as_str()))
.collect();
for dir in ["backlog", "committed", "reviewing", "done"] {
stray.extend(
fs::read_dir(worklane.join(dir))
.into_iter()
.flatten()
.filter_map(|e| e.ok())
.map(|e| e.file_name().into_string().unwrap())
.filter(|name| !name.ends_with(".md")),
);
}
stray
}
/// The bug this fixes. The old order renamed first and wrote second, so a write
/// that failed left the ticket in its new directory still claiming the old status.
/// A read-only ticket file is the cheapest way to make the write fail.
#[test]
fn mv_never_leaves_stale_content_in_the_target_directory() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = create_ticket(
&worklane,
"backlog",
"Read Only",
"A description.",
"abc123def456789012345678901234567890",
"alice",
"2026-12-31",
"test",
);
let source = worklane.join("backlog").join(&filename);
chmod(&source, 0o444);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["mv", "abc123def4567", "--status", "committed"])
.assert()
.success();
// Wherever it ended up, its Status must agree with the directory it is in
let moved = worklane.join("committed").join(&filename);
assert!(moved.exists(), "ticket did not move");
let content = fs::read_to_string(&moved).unwrap();
assert!(
content.contains("- **Status**: committed"),
"stale status: {content:?}"
);
assert!(!content.contains("- **Status**: backlog"), "{content:?}");
assert_eq!(md_files(&worklane.join("backlog")).len(), 0);
assert_eq!(stray_files(&worklane), Vec::<String>::new());
}
/// The other criterion: one directory or the other, never both. An unwritable
/// target directory fails the move at the last step, which is the step that would
/// have to be reordered to break this.
#[test]
fn mv_leaves_the_ticket_in_one_place_when_the_move_fails() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = create_ticket(
&worklane,
"backlog",
"Blocked Move",
"A description.",
"abc123def456789012345678901234567890",
"alice",
"2026-12-31",
"test",
);
let target = worklane.join("committed");
chmod(&target, 0o555);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
let assert = cmd
.current_dir(&temp.path())
.args(["mv", "abc123def4567", "--status", "committed"])
.assert()
.failure();
let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
// Named, not a bare io error
assert!(stderr.contains("Blocked Move"), "{stderr}");
assert_eq!(
md_files(&worklane.join("backlog")),
vec![filename.clone()],
"the ticket left its own directory"
);
assert_eq!(md_files(&target).len(), 0, "the ticket is in both places");
assert_eq!(stray_files(&worklane), Vec::<String>::new());
// The documented worst case: still in its old directory, carrying a Status one
// move ahead because the content was written before the move was attempted.
let left = fs::read_to_string(worklane.join("backlog").join(&filename)).unwrap();
assert!(left.contains("- **Status**: committed"), "{left:?}");
// And the state is recoverable, because the directory is what decides the
// current status, so a retry moves it rather than refusing.
chmod(&target, 0o755);
let mut retry = Command::cargo_bin(BIN_NAME).unwrap();
retry
.current_dir(&temp.path())
.args(["mv", "abc123def4567", "--status", "committed"])
.assert()
.success();
assert_eq!(md_files(&target), vec![filename]);
assert_eq!(md_files(&worklane.join("backlog")).len(), 0);
}
#[test]
fn mv_leaves_nothing_behind_on_success() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(
&worklane,
"backlog",
"Clean Move",
"A description.",
"abc123def456789012345678901234567890",
"alice",
"2026-12-31",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path())
.args(["mv", "abc123def4567", "--status", "committed"])
.assert()
.success();
assert_eq!(stray_files(&worklane), Vec::<String>::new());
}
+282
View File
@@ -393,3 +393,285 @@ fn show_searches_across_all_statuses() {
assert!(stdout.contains("Committed Task"));
assert!(stdout.contains("This is in committed."));
}
#[test]
fn show_renders_the_priority_mark_beside_the_number() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = "abc123def456789012345678901234567890_prio.md";
fs::write(
worklane.join("backlog").join(filename),
"# Prio Ticket\n\n## Metadata\n\n- **ID**: abc123def456789012345678901234567890\n\
- **Priority**: 2\n- **Status**: backlog\n",
)
.unwrap();
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("show").arg("Prio");
let stdout = get_stdout(&mut cmd);
// Mark for the eye, number still there for the file's sake
assert!(stdout.contains("\u{25cf}\u{25d0}"), "no mark in {stdout:?}");
assert!(stdout.contains("Priority"));
assert!(stdout.contains('2'));
// And the file itself is untouched
let content = fs::read_to_string(worklane.join("backlog").join(filename)).unwrap();
assert!(content.contains("- **Priority**: 2"));
}
#[test]
fn show_prints_the_title_once() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(
&worklane,
"backlog",
"Once Only",
"A description that does not name the title.",
"abc123def456789012345678901234567890",
"alice",
"2026-12-31",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("show").arg("Once Only");
let stdout = get_stdout(&mut cmd);
assert_eq!(
stdout.matches("Once Only").count(),
1,
"title repeated in {stdout:?}"
);
// The rule under it is still the width of the title
assert!(stdout.contains("Once Only\n─────────\n"), "{stdout:?}");
}
#[test]
fn show_renders_the_metadata_as_an_aligned_table() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = "abc123def456789012345678901234567890_table.md";
fs::write(
worklane.join("backlog").join(filename),
"# Table Ticket\n\n## Metadata\n\n\
- **ID**: abc123def456789012345678901234567890\n\
- **Created At**: 2026-08-20 15:51:01\n\
- **Owner**: alice\n\
- **Status**: backlog\n",
)
.unwrap();
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("show").arg("Table");
let stdout = get_stdout(&mut cmd);
// Every value starts in the same column, sized by the longest field name
assert!(
stdout.contains(
"ID abc123def456789012345678901234567890\n\
Created At 2026-08-20 15:51:01\n\
Owner alice\n\
Status backlog\n"
),
"{stdout:?}"
);
// Display only: the file is still the markdown list it was
let content = fs::read_to_string(worklane.join("backlog").join(filename)).unwrap();
assert!(content.contains("- **Owner**: alice"));
}
/// Write a ticket with an exact uuid and title, since both matter to resolution.
fn ticket_with(worklane: &std::path::Path, status: &str, uuid: &str, title: &str, slug: &str) {
fs::write(
worklane.join(status).join(format!("{}_{}.md", uuid, slug)),
format!(
"# {}\n\n## Metadata\n\n- **ID**: {}\n- **Status**: {}\n",
title, uuid, status
),
)
.unwrap();
}
fn show(temp: &TempDir, search: &str) -> std::process::Output {
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("show").arg(search);
cmd.assert().get_output().clone()
}
/// The bug. A flat OR of the three predicates put an exact uuid prefix and a title
/// that merely mentions it in the same list, so the search reported as ambiguous
/// the very id the listing had just printed.
#[test]
fn show_prefers_a_uuid_prefix_over_a_title_that_mentions_it() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
ticket_with(
&worklane,
"backlog",
"641e3d5d-ef23-4213-8346-e8b0114b84e9",
"Alpha",
"alpha",
);
ticket_with(
&worklane,
"backlog",
"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"Notes on 641e3d5 regression",
"notes",
);
let out = show(&temp, "641e3d5");
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr));
assert!(stdout.contains("Alpha"), "{stdout:?}");
assert!(!stdout.contains("Notes on"), "{stdout:?}");
}
/// `ls` prints SHORT_ID_WIDTH characters, so pasting that back has to resolve. This
/// is the guard against reinstating an eight character minimum.
#[test]
fn show_resolves_the_short_id_the_listing_prints() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let uuid = "641e3d5d-ef23-4213-8346-e8b0114b84e9";
ticket_with(&worklane, "backlog", uuid, "Alpha", "alpha");
let mut ls = Command::cargo_bin(BIN_NAME).unwrap();
ls.current_dir(&temp.path()).args(["ls", "backlog"]);
let listing = String::from_utf8(ls.assert().success().get_output().stdout.clone()).unwrap();
// Take the id exactly as printed, so this couples to the display width rather
// than to a hardcoded number
let printed = listing
.split('(')
.nth(1)
.and_then(|rest| rest.split(')').next())
.expect("no id in the listing")
.to_string();
assert!(printed.len() < 8, "the listing prints {} chars", printed.len());
// A decoy whose title quotes that id. Without it the search would still land on
// Alpha through the filename tier, since the filename contains the uuid, and the
// test would pass under a minimum longer than the printed id.
ticket_with(
&worklane,
"backlog",
"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
&format!("Notes on {} regression", printed),
"notes",
);
let out = show(&temp, &printed);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{printed} did not resolve");
assert!(stdout.contains("Alpha"), "{stdout:?}");
assert!(!stdout.contains("Notes on"), "{stdout:?}");
}
#[test]
fn show_resolves_a_four_character_uuid_prefix() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
ticket_with(
&worklane,
"backlog",
"641e3d5d-ef23-4213-8346-e8b0114b84e9",
"Alpha",
"alpha",
);
let out = show(&temp, "641e");
assert!(out.status.success());
assert!(String::from_utf8_lossy(&out.stdout).contains("Alpha"));
}
/// Below four characters the search is text, so it must not be read as a prefix
/// matching a large slice of the board.
#[test]
fn show_treats_a_search_below_four_characters_as_text() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
ticket_with(
&worklane,
"backlog",
"641e3d5d-ef23-4213-8346-e8b0114b84e9",
"Alpha",
"alpha",
);
ticket_with(
&worklane,
"backlog",
"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"Notes on 641 regression",
"notes",
);
// "641" prefixes Alpha's uuid, but it is too short to be read as one, so the
// title match is the only match
let out = show(&temp, "641");
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr));
assert!(stdout.contains("Notes on"), "{stdout:?}");
assert!(!stdout.contains("Alpha"), "{stdout:?}");
}
/// The last tier earns its place: it reaches the middle of a uuid, which the prefix
/// tier cannot.
#[test]
fn show_falls_back_to_the_filename_for_a_mid_uuid_substring() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
ticket_with(
&worklane,
"backlog",
"641e3d5d-ef23-4213-8346-e8b0114b84e9",
"Alpha",
"alpha",
);
let out = show(&temp, "ef23");
assert!(out.status.success());
assert!(String::from_utf8_lossy(&out.stdout).contains("Alpha"));
}
/// Tiering removes false ambiguity across tiers, not real ambiguity inside one.
#[test]
fn show_still_reports_ambiguity_within_the_uuid_tier() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
ticket_with(
&worklane,
"backlog",
"5eeddeed-1111-2222-3333-444444444444",
"Beta",
"beta",
);
ticket_with(
&worklane,
"backlog",
"5eedbeef-9999-8888-7777-666666666666",
"Gamma",
"gamma",
);
let out = show(&temp, "5eed");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success());
assert!(stderr.contains("Multiple tickets found"), "{stderr:?}");
assert!(stderr.contains("Beta") && stderr.contains("Gamma"), "{stderr:?}");
}