Compare commits

..
3 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
13 changed files with 722 additions and 34 deletions
@@ -79,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`)
@@ -103,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.
+3 -3
View File
@@ -155,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) {
@@ -175,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)"),
@@ -207,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."),
+11 -1
View File
@@ -31,6 +31,13 @@
- 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 (38;5;8), magenta (1;35), brightred (38;5;9)
@@ -55,11 +62,14 @@
- 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
Generated
+1 -1
View File
@@ -1029,7 +1029,7 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.3.1"
version = "0.4.0"
dependencies = [
"anyhow",
"assert_cmd",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "worklane"
version = "0.3.1"
version = "0.4.0"
edition = "2024"
[dependencies]
+1 -1
View File
@@ -8,7 +8,7 @@ Worklane is a local Kanban flow for agentic software development.
| `worklane init` | Creates `.worklane/` with backlog, committed, reviewing, done directories |
| `worklane add` | Creates a ticket in backlog with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--owner`, `--priority` flags |
| `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 (8+ chars) or title substring |
| `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 |
+16 -4
View File
@@ -37,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
@@ -45,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)
@@ -114,6 +125,7 @@ pub enum Command {
ticket: String,
/// Comment body (required)
#[arg(allow_hyphen_values = PROSE)]
body: String,
/// Owner
+77 -7
View File
@@ -311,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"];
@@ -390,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 {}",
+42 -14
View File
@@ -177,11 +177,28 @@ fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyh
anyhow!(message)
}
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
let statuses = status_dirs();
let mut matches: Vec<(String, String, String, String)> = Vec::new();
/// Shortest search tried as a UUID prefix. Below it the search is text, so a one or
/// two character term is a title search rather than a prefix matching half the board.
///
/// Four, not eight. The guard this replaces read `short_id.len() >= 8`, and `short_id`
/// there was always the full 36 character uuid, so it was always true and any length
/// already worked. Requiring eight would have broken the id the tool prints itself:
/// `ls` shows [`SHORT_ID_WIDTH`] characters, and pasting that back has to resolve.
pub const MIN_ID_SEARCH: usize = 4;
for status in &statuses {
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
let search_lower = search.to_lowercase();
let long_enough_for_an_id = search.chars().count() >= MIN_ID_SEARCH;
// Three tiers, filled in one pass and consulted in order. A uuid prefix has to win
// outright rather than join a flat list: ticket titles reference other tickets by
// id, so an exact prefix match was reported as ambiguous against whichever title
// happened to mention it.
let mut by_id: Vec<(String, String, String, String)> = Vec::new();
let mut by_title: Vec<(String, String, String, String)> = Vec::new();
let mut by_filename: Vec<(String, String, String, String)> = Vec::new();
for status in status_dirs() {
let status_path = worklane_dir.join(status);
if !status_path.exists() {
continue;
@@ -206,23 +223,34 @@ pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, Stri
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
let short_id = filename.split('_').next().unwrap_or("");
let uuid = filename.split('_').next().unwrap_or("");
let search_lower = search.to_lowercase();
let title_lower = title.to_lowercase();
let filename_lower = filename.to_lowercase();
let by_prefix = long_enough_for_an_id && uuid.to_lowercase().starts_with(&search_lower);
let in_title = title.to_lowercase().contains(&search_lower);
// Still reaches the middle of a uuid, which the prefix tier cannot.
let in_filename = filename.to_lowercase().contains(&search_lower);
let id_match =
short_id.to_lowercase().starts_with(&search_lower) && short_id.len() >= 8;
let title_match = title_lower.contains(&search_lower);
let filename_match = filename_lower.contains(&search_lower);
if !(by_prefix || in_title || in_filename) {
continue;
}
if id_match || title_match || filename_match {
matches.push((status.to_string(), title, content, short_id.to_string()));
let found = (status.to_string(), title, content, uuid.to_string());
if by_prefix {
by_id.push(found);
} else if in_title {
by_title.push(found);
} else {
by_filename.push(found);
}
}
}
let mut matches = match (by_id.is_empty(), by_title.is_empty()) {
(false, _) => by_id,
(true, false) => by_title,
(true, true) => by_filename,
};
if matches.is_empty() {
return Err(anyhow!("No ticket found matching '{}'", search));
}
+118
View File
@@ -262,3 +262,121 @@ fn add_rejects_a_level_outside_the_range() {
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()
}
+89
View File
@@ -250,3 +250,92 @@ fn comments_added_back_to_back_are_both_kept() {
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:?}");
}
+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());
}
+190
View File
@@ -485,3 +485,193 @@ fn show_renders_the_metadata_as_an_aligned_table() {
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:?}");
}