Compare commits

..
2 Commits
Author SHA1 Message Date
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
8 changed files with 481 additions and 13 deletions
+8
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,6 +62,7 @@
- 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
Generated
+1 -1
View File
@@ -1029,7 +1029,7 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.3.1"
version = "0.3.3"
dependencies = [
"anyhow",
"assert_cmd",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "worklane"
version = "0.3.1"
version = "0.3.3"
edition = "2024"
[dependencies]
+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 {}",
+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());
}