Files
worklane/src/handlers.rs
T
Ansho ReiandClaude Opus 5 d5fb22cfd8 (16c2bed) Add a worklane-review skill, and bump to 0.13.0
install-skill now writes every document the binary carries, with an optional
name to narrow it. Requiring a name per document would mean a skill added
later never reaches anyone who already knows the invocation, which is the
drift the command exists to prevent. --print is the exception and requires
the name: a diff is against one document.

The review skill is its own document rather than a section of SKILL.md,
because the frontmatter description is the whole of what decides loading and
one description cannot name both "anything touching a ticket" and "only when
a review is asked for".

The reviewer never ticks a criterion and never moves the ticket. A tick is
the implementer's claim and unticking is the review disagreeing; one mark for
both loses the disagreement. mv belongs to whoever does the work.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 02:40:37 +02:00

1284 lines
43 KiB
Rust

use anyhow::{Result, anyhow};
use chrono::Local;
use std::fs;
use std::io::{BufRead, IsTerminal, Write};
use std::path::Path;
use crate::campaign::*;
use crate::command::{AddArgs, AppendArgs, CampaignAddArgs, CheckArgs, RelateArgs, SetArgs};
use crate::install;
use crate::util::*;
pub fn cmd_init(start: &Path) -> Result<()> {
let dir = start.canonicalize().unwrap_or_else(|_| start.to_path_buf());
let worklane_dir = dir.join(".worklane");
if worklane_dir.exists() {
println!(
"worklane already initialized in: {}",
worklane_dir.display()
);
return Ok(());
}
fs::create_dir_all(&worklane_dir)?;
let folders = ["backlog", "committed", "reviewing", "done"];
for folder in &folders {
fs::create_dir_all(worklane_dir.join(folder))?;
}
// Beside the status directories, not among them: a campaign has no status. Created
// here for a new board, and on demand by `campaign add` for a board that predates
// campaigns, which is why `status_dirs()` is untouched.
fs::create_dir_all(campaigns_dir(&worklane_dir))?;
println!("Initialized worklane in: {}", worklane_dir.display());
Ok(())
}
pub fn cmd_ls(
status_filter: &Option<String>,
priority_filter: Option<u8>,
campaign_filter: &Option<String>,
worklane_dir: &Path,
) -> Result<()> {
// Resolved before anything is read, so an unknown campaign is refused rather than
// silently listing nothing, and the name is available for the heading.
let campaign = match campaign_filter {
Some(search) => Some(resolve_campaign(search, worklane_dir)?),
None => None,
};
let uuid = campaign.as_ref().map(|campaign| campaign.uuid.as_str());
if let Some(campaign) = &campaign {
println!(
"Members of campaign ({}) {}\n",
color_text(short_id(&campaign.uuid), Color::Red),
color_text(&campaign.title, Color::Green),
);
}
if let Some(status) = status_filter {
let status_path = worklane_dir.join(status);
if !status_path.exists() {
return Err(anyhow!(
"Status '{}' not found. Valid statuses: backlog, committed, reviewing, done",
status
));
}
let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid);
if items.is_empty() {
println!("No tickets in '{}' status.", status);
return Ok(());
}
println!("Tickets in '{}' status:\n", status);
display_ticket_items(&items);
} else {
// List all statuses with their ticket counts
let statuses = status_dirs();
println!("Tickets by status:\n");
for status in &statuses {
let status_path = worklane_dir.join(status);
if !status_path.exists() {
continue;
}
let items = filtered(collect_ticket_items(&status_path)?, priority_filter, uuid);
let count = items.len();
let label = if count == 1 { "ticket" } else { "tickets" };
println!(" [{}] {} {}", status.to_uppercase(), count, label);
}
// Show all tickets except done grouped by status
for status in &statuses {
if *status == DONE {
continue;
}
let status_path = worklane_dir.join(status);
if !status_path.exists() || !fs::metadata(&status_path)?.is_dir() {
continue;
}
let items = match collect_ticket_items(&status_path) {
Ok(items) => filtered(items, priority_filter, uuid),
Err(_) => continue,
};
if items.is_empty() {
continue;
}
let status_header = color_text(&format!("[{}]", status.to_uppercase()), Color::Orange);
println!("\n{}", status_header);
display_ticket_items(&items);
}
}
Ok(())
}
/// The listing filters in one call, so the three places `ls` collects a column cannot
/// end up applying a different set of them.
fn filtered(items: Vec<TicketItem>, level: Option<u8>, campaign: Option<&str>) -> Vec<TicketItem> {
filter_by_campaign(filter_by_priority(items, level), campaign)
}
/// Keep only the members of `campaign`, or everything when none was asked for.
fn filter_by_campaign(items: Vec<TicketItem>, campaign: Option<&str>) -> Vec<TicketItem> {
match campaign {
Some(uuid) => items
.into_iter()
.filter(|item| item.campaign.as_deref() == Some(uuid))
.collect(),
None => items,
}
}
/// 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(args: &AddArgs, start: &Path) -> Result<()> {
let AddArgs {
title,
description,
acceptance,
plan,
tags,
due,
owner,
priority,
} = args;
let owner = match owner {
Some(o) => Some(o.clone()),
None => get_git_user(),
};
let worklane_dir = find_worklane_dir(start)?;
let backlog_dir = worklane_dir.join("backlog");
if !backlog_dir.exists() {
return Err(anyhow!(
"Backlog directory not found. Run `worklane init` first."
));
}
let id = uuid::Uuid::new_v4();
let slug = slug(title);
let filename = format!("{}_{}.md", id, slug);
let filepath = backlog_dir.join(&filename);
if filepath.exists() {
return Err(anyhow!("A ticket with this title already exists."));
}
// Joined with a single newline, so an empty value is how a caller spells a
// paragraph break and an all-blank description is no description at all.
let description = trim_blank_ends(description);
let description_text = if description.is_empty() {
"_No description provided._".to_string()
} else {
description.join("\n")
};
let mut body = format!(
"# {}\n\
\n\
## Description\n\
{}\n\
\n\
## Acceptance Criteria\n\
{}\n\
\n\
## Implementation Plan\n\
{}\n\
\n\
## Metadata\n\
\n\
- **ID**: {}\n\
- **Priority**: {}\n\
- **Tags**: {}\n\
- **Due**: {}\n\
- **Owner**: {}\n\
- **Created At**: {}\n\
- **Status**: backlog\n\
",
title,
description_text,
if acceptance.is_empty() {
"_No acceptance criteria provided._".to_string()
} else {
acceptance
.iter()
.map(|c| format!("- [ ] {}", c))
.collect::<Vec<_>>()
.join("\n")
},
if plan.is_empty() {
"_No implementation plan provided._".to_string()
} else {
plan.iter()
.enumerate()
.map(|(i, s)| format!("{}. {}", i + 1, s))
.collect::<Vec<_>>()
.join("\n")
},
id,
match priority {
Some(level) => level.to_string(),
None => "_Not set_".to_string(),
},
if tags.is_empty() {
"_None_".to_string()
} else {
tags.join(", ")
},
due.as_deref().unwrap_or("_Not set_"),
owner.as_deref().unwrap_or("_Not set_"),
Local::now().format(TIMESTAMP_FORMAT),
);
body.push('\n');
fs::write(&filepath, body)?;
println!("Created ticket: {}", filename);
Ok(())
}
/// Public for the TUI's detail view, which shows the same comments `show` does.
pub fn read_comments(comments_dir: &Path) -> Result<Vec<(String, String, String, String)>> {
if !comments_dir.exists() {
return Ok(vec![]);
}
let mut comments: Vec<(String, String, String, String)> = Vec::new();
for entry in fs::read_dir(comments_dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().is_some_and(|e| e == "md") {
let content = fs::read_to_string(&path)?;
let filename = path
.file_stem()
.map(|s| s.to_string_lossy().to_string())
.unwrap_or_default();
let author = content
.lines()
.find(|l| l.starts_with("**Author**"))
.and_then(|l| l.split_once("**Author**:"))
.map(|(_, value)| value)
.map(|s| s.trim().to_string())
.unwrap_or_else(|| "unknown".to_string());
let time = content
.lines()
.find(|l| l.starts_with("**Time**"))
.and_then(|l| l.split_once("**Time**:"))
.map(|(_, value)| value)
.map(|s| s.trim().to_string())
.unwrap_or_else(|| "unknown".to_string());
let body = if let Some(after_comment) = content.strip_prefix("**Comment**\n") {
if let Some(end) = after_comment.find("\n\n**Author**") {
after_comment[..end].trim()
} else {
after_comment.trim()
}
} else {
""
};
comments.push((filename, author, time, body.to_string()));
}
}
comments.sort_by(|a, b| a.0.cmp(&b.0));
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");
// Read before anything is printed, so a board that cannot be read fails instead of
// half printing a ticket.
let resolved = resolved_for(&content, worklane_dir, should_use_colors())?;
// 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, Color::Green));
println!("{}", "─".repeat(title.chars().count()));
println!("\n{}", content_trim_colored(&content, &resolved));
if ticket_uuid != "_Not set_" {
let comments_dir = worklane_dir.join("comments").join(&ticket_uuid);
let comments = read_comments(&comments_dir)?;
let formatted = format_comments(&comments);
println!("{}", formatted);
}
Ok(())
}
/// Write `content` over `path`, without ever leaving half a file behind.
///
/// Staged in a temp file and renamed into place, because `fs::write` truncates before
/// it writes and a partial write would corrupt the ticket. The temp sits 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 showing up as a stray
/// untitled ticket.
fn write_then_replace(
worklane_dir: &Path,
path: &Path,
filename: &str,
content: &str,
title: &str,
) -> Result<()> {
let temp = worklane_dir.join(format!(".wl-{}.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, path) {
let _ = fs::remove_file(&temp);
return Err(anyhow!(
"Could not write ticket '{}' at {}: {}",
title,
path.display(),
e
));
}
Ok(())
}
/// The ticket file in `dir` carrying `uuid`.
///
/// Matched on the uuid, not the title. Titles are not unique, `add` allows duplicates
/// on purpose, so a title scan could land on a different ticket than the one that was
/// resolved: `mv <uuid-of-second>` moved the first ticket sharing its title.
fn find_ticket_file(dir: &Path, uuid: &str, title: &str) -> Result<String> {
if uuid.trim().is_empty() || is_unknown_value(uuid) {
return Err(anyhow!(
"Ticket '{}' has no ID field, so its file cannot be located",
title
));
}
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if !path.extension().is_some_and(|e| e == "md") {
continue;
}
let name = match path.file_name() {
Some(name) => name.to_string_lossy().to_string(),
None => continue,
};
if name.starts_with(uuid) {
return Ok(name);
}
}
Err(anyhow!(
"Could not find the file for ticket '{}' in {}",
title,
dir.display()
))
}
/// 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);
write_then_replace(worklane_dir, &source, filename, content, title)?;
// 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
)
})
}
/// Refuse a move while a ticket it is `blocked by` is not done.
///
/// Every move, not only the one into committed: an open blocker is a reason not to
/// start and a reason not to finish, and one rule is easier to hold than a table of
/// which transitions care. Called before anything is written, so a refusal leaves no
/// rename, no rewritten field and no half moved ticket.
///
/// A target the board does not have warns and allows the move. Refusing there would
/// wedge the ticket behind a bookkeeping fault with no way out but `--force`, and a
/// dangling uuid is not a dependency.
fn check_blockers(worklane_dir: &Path, content: &str, title: &str) -> Result<()> {
let blockers: Vec<Relation> = parse_relations(content, title)?
.into_iter()
.filter(|relation| relation.kind == RelationKind::BlockedBy)
.collect();
if blockers.is_empty() {
return Ok(());
}
let index = RelationIndex::load(worklane_dir)?;
let mut open: Vec<String> = Vec::new();
for blocker in &blockers {
match index.get(&blocker.target) {
Some(target) if target.status == DONE => {}
Some(target) => open.push(format!(
" ({}) {} [{}]",
color_text(short_id(&target.uuid), Color::Red),
target.title,
color_text(&target.status, Color::Orange),
)),
None => eprintln!(
"Warning: ticket '{}' is blocked by {}, which is not on the board.",
title,
short_id(&blocker.target),
),
}
}
if open.is_empty() {
return Ok(());
}
// Every open blocker, not the first: a ticket waiting on three of them is not
// unblocked by clearing the one the message happened to name.
Err(anyhow!(
"Cannot move '{}' while it is blocked by:\n{}\nUse --force (-f) to move it anyway.",
color_text(title, Color::Green),
open.join("\n"),
))
}
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"];
if !valid_statuses.contains(&target_status) {
return Err(anyhow!(
"Invalid target status '{}'. Valid statuses: {}",
target_status,
valid_statuses.join(", ")
));
}
let worklane_dir = find_worklane_dir(start)?;
let (current_status, title, resolved) = resolve_ticket(ticket_id, &worklane_dir)?;
let current_idx = forward_order
.iter()
.position(|&s| s == current_status)
.unwrap();
let target_idx = forward_order
.iter()
.position(|&s| s == target_status)
.unwrap();
if !force && target_idx < current_idx {
return Err(anyhow!(
"Cannot move backward from {} to {}. Use --force (-f) to allow.",
color_text(&current_status, Color::Orange),
color_text(target_status, Color::Orange),
));
}
if !force && target_idx != current_idx + 1 && target_idx != current_idx {
return Err(anyhow!(
"Can only move one stage forward at a time. Use --force (-f) to skip stages."
));
}
if current_status == target_status {
println!(
"Ticket is already in '{}' status.",
color_text(target_status, Color::Orange)
);
return Ok(());
}
// After the no-op above, so a ticket is never refused for a move it is not making,
// and behind `force`, which is where the other two overrides of a rule the board
// keeps true already live.
if !force {
check_blockers(&worklane_dir, &resolved, &title)?;
}
let current_path = worklane_dir.join(&current_status);
let target_path = worklane_dir.join(target_status);
// Updated before the file is even located, so a ticket without a Status field is
// refused for that reason rather than for whatever the lookup notices first.
let content = set_status_field(&resolved, target_status, &title)?;
let found_filename =
find_ticket_file(&current_path, &parse_ticket_field(&resolved, "ID"), &title)?;
move_ticket_file(
&worklane_dir,
&current_path,
&target_path,
&found_filename,
&content,
&title,
)?;
println!(
"Moved ticket '{}' from {} to {}",
color_text(&title, Color::Green),
color_text(&current_status, Color::Orange),
color_text(target_status, Color::Orange),
);
Ok(())
}
pub fn cmd_comment(
ticket_id: &str,
body: &str,
owner: &Option<String>,
start: &Path,
) -> Result<()> {
if body.is_empty() {
return Err(anyhow!("Comment body is required."));
}
let worklane_dir = find_worklane_dir(start)?;
let (_status, title, content) = resolve_ticket(ticket_id, &worklane_dir)?;
let ticket_uuid = parse_ticket_field(&content, "ID");
if ticket_uuid == "_Not set_" {
return Err(anyhow!("Could not determine ticket ID."));
}
let comments_dir = worklane_dir.join("comments").join(&ticket_uuid);
fs::create_dir_all(&comments_dir)?;
let stem = Local::now().format(COMMENT_FILE_FORMAT).to_string();
let author = match owner {
Some(o) => o.clone(),
None => get_git_user().unwrap_or_else(|| "unknown".to_string()),
};
let comment_content = format!(
"**Comment**\n\
{}\n\
\n\
**Author**: {}\n\
**Time**: {}\n\
",
body,
author,
Local::now().format(TIMESTAMP_FORMAT)
);
let filename = write_new_comment(&comments_dir, &stem, &comment_content)?;
println!("Comment added to '{}' ({})", title, filename);
Ok(())
}
/// The sections `set` and `append` can rewrite, paired with the flag that carries them.
///
/// One list, so both commands walk the same table and a section added later needs no
/// change here.
fn section_args<'a>(
description: &'a [String],
acceptance: &'a [String],
plan: &'a [String],
) -> [(&'static Section, &'a [String]); 3] {
[
(&DESCRIPTION, description),
(&ACCEPTANCE, acceptance),
(&PLAN, plan),
]
}
/// Write the ticket back, renaming the file when a new title changes its slug.
///
/// The content goes down first and the rename second, the same order and for the same
/// reason as `mv`: a failure at the rename leaves a correct ticket under a stale name,
/// which lookup still finds by uuid or title, rather than a half-written one.
fn save_ticket(
worklane_dir: &Path,
status: &str,
uuid: &str,
title: &str,
new_title: Option<&String>,
content: &str,
) -> Result<()> {
let status_path = worklane_dir.join(status);
let filename = find_ticket_file(&status_path, uuid, title)?;
let path = status_path.join(&filename);
write_then_replace(worklane_dir, &path, &filename, content, title)?;
// The uuid is kept, so the new name cannot collide with another ticket, and an
// unchanged slug means there is nothing to rename.
if let Some(new_title) = new_title {
let renamed = format!("{}_{}.md", uuid, slug(new_title));
if renamed != filename {
let destination = status_path.join(&renamed);
fs::rename(&path, &destination).map_err(|e| {
anyhow!(
"Ticket '{}' was updated but could not be renamed to {}: {}",
title,
destination.display(),
e
)
})?;
}
}
Ok(())
}
fn report(fields: &[&str], title: &str, verb: &str) {
if fields.is_empty() {
println!("No changes to '{}'", color_text(title, Color::Green));
return;
}
println!(
"{} {} on '{}'",
verb,
fields.join(", "),
color_text(title, Color::Green)
);
}
pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
let uuid = parse_ticket_field(&original, "ID");
let mut content = original.clone();
let mut changed: Vec<&str> = Vec::new();
// Each edit is compared against the content going in, so a field set to the value
// it already holds is reported as unchanged rather than claimed as an update.
let mut apply = |content: &mut String, field: &'static str, next: String| {
if *content != next {
content.clone_from(&next);
changed.push(field);
}
};
if let Some(new_title) = &args.title {
let next = set_title(&content, new_title)?;
apply(&mut content, "title", next);
}
for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) {
if values.is_empty() {
continue;
}
let items = section.normalise(values);
if items.is_empty() {
return Err(anyhow!(
"An empty {} is not a way to clear the section, and clearing is not supported yet",
section.label
));
}
let next = set_section_body(&content, section, &items)?;
apply(&mut content, section.label, next);
}
if !args.tags.is_empty() {
let next = set_metadata_field(&content, "Tags", &args.tags.join(", "), &title)?;
apply(&mut content, "tags", next);
}
if let Some(due) = &args.due {
let next = set_metadata_field(&content, "Due", due, &title)?;
apply(&mut content, "due", next);
}
if let Some(priority) = args.priority {
let next = set_metadata_field(&content, "Priority", &priority.to_string(), &title)?;
apply(&mut content, "priority", next);
}
if changed.is_empty() {
report(&changed, &title, "Updated");
return Ok(());
}
let renamed = changed.contains(&"title").then_some(()).and(args.title.as_ref());
save_ticket(&worklane_dir, &status, &uuid, &title, renamed, &content)?;
let shown = args.title.clone().unwrap_or(title);
report(&changed, &shown, "Updated");
Ok(())
}
/// Rewrite the Owner field, the only writer of it.
///
/// The user comes first at the call site, after Unix `chown`, and the reasoning for
/// reversing the ticket-first order is on the `Chown` variant. A swapped call is left
/// to resolution: nothing here inspects `user` to see whether it also names a ticket,
/// since the check would only fire on the case resolution already refuses and would
/// stay silent on the one it cannot, a ticket whose title is the username.
///
/// No-op detection compares the whole file, the way `set` does, so an owner set to the
/// value it already holds is reported unchanged and nothing is written.
pub fn cmd_chown(user: &str, ticket_id: &str, start: &Path) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let (status, title, original) = resolve_ticket(ticket_id, &worklane_dir)?;
let uuid = parse_ticket_field(&original, "ID");
let content = set_metadata_field(&original, "Owner", user, &title)?;
if content == original {
report(&[], &title, "Updated");
return Ok(());
}
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
report(&["owner"], &title, "Updated");
Ok(())
}
pub fn cmd_append(args: &AppendArgs, start: &Path) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
let uuid = parse_ticket_field(&original, "ID");
let mut content = original.clone();
let mut changed: Vec<&str> = Vec::new();
for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) {
if values.is_empty() {
continue;
}
let items = section.normalise(values);
if items.is_empty() {
return Err(anyhow!(
"Nothing to append to the {}: every value given was blank",
section.label
));
}
content = append_section_body(&content, section, &items)?;
changed.push(section.label);
}
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
report(&changed, &title, "Appended to");
Ok(())
}
/// Record a relation from one ticket to another.
///
/// One side is written and the inverse is derived wherever it is shown. `blocked by`
/// goes on the gated ticket rather than `blocks` on the blocker: the gated ticket is the
/// one whose move is refused and whose author knows about the dependency. `relates to`
/// is symmetric, so it is written once, on whichever end the caller ran it from.
///
/// The kinds are a flag each rather than a `--kind` value, so an unknown kind is a
/// usage error at the door instead of a line written into the file and refused on the
/// way back out.
pub fn cmd_relate(args: &RelateArgs, start: &Path) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
let uuid = parse_ticket_field(&original, "ID");
let existing = parse_relations(&original, &title)?;
// Every target resolved and every refusal raised before a byte is written, so a
// call naming one good ticket and one bad one records neither.
let mut items: Vec<String> = Vec::new();
let mut changed: Vec<&str> = Vec::new();
for (kind, targets) in args.requested() {
for search in targets {
let (_target_status, target_title, target) = resolve_ticket(search, &worklane_dir)?;
let target_uuid = parse_ticket_field(&target, "ID");
if target_uuid.trim().is_empty() || is_unknown_value(&target_uuid) {
return Err(anyhow!(
"Ticket '{}' has no ID field, so nothing can point at it",
target_title
));
}
if target_uuid == uuid {
return Err(anyhow!(
"A ticket cannot relate to itself, and '{}' is the ticket being edited",
title
));
}
let relation = Relation {
kind,
target: target_uuid,
};
// Already held, either in the file or earlier in this call. Recording it
// twice would read as two dependencies on one ticket.
if existing.contains(&relation) || items.contains(&relation.item()) {
continue;
}
items.push(relation.item());
if !changed.contains(&kind.label()) {
changed.push(kind.label());
}
}
}
if items.is_empty() {
report(&[], &title, "Recorded");
return Ok(());
}
let content = append_section_body(&ensure_section(&original, &RELATIONS), &RELATIONS, &items)?;
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
report(&changed, &title, "Recorded");
Ok(())
}
// ------------------------------------------------------------------- campaigns --
/// File a new campaign.
///
/// Written through `write_then_replace` rather than `fs::write`, so a failure leaves no
/// half-written campaign behind. `cmd_add` predates that primitive and still uses the
/// plain write; the difference is noted on the ticket rather than fixed here.
pub fn cmd_campaign_add(args: &CampaignAddArgs, start: &Path) -> Result<()> {
let CampaignAddArgs {
title,
description,
owner,
} = args;
let worklane_dir = find_worklane_dir(start)?;
let dir = ensure_campaigns_dir(&worklane_dir)?;
let owner = match owner {
Some(owner) => Some(owner.clone()),
None => get_git_user(),
};
let id = uuid::Uuid::new_v4();
let filename = format!("{}_{}.md", id, slug(title));
let path = dir.join(&filename);
let body = campaign_body(
title,
description,
&id,
owner.as_deref(),
&Local::now().format(TIMESTAMP_FORMAT).to_string(),
);
write_then_replace(&worklane_dir, &path, &filename, &body, title)?;
println!("Created campaign: {}", filename);
Ok(())
}
/// List the campaigns with how far each has got.
///
/// The counts come from one pass over the status directories per campaign. That is a
/// scan per row rather than one scan reused, and it is deliberate: the alternative is a
/// map from campaign uuid to counts built in a single walk, which is worth writing when
/// a board has enough campaigns to notice and is premature now.
pub fn cmd_campaign_ls(worklane_dir: &Path) -> Result<()> {
let index = CampaignIndex::load(worklane_dir)?;
if index.is_empty() {
println!("No campaigns yet. `worklane campaign add --title` files one.");
return Ok(());
}
let colored = should_use_colors();
println!("Campaigns:\n");
for campaign in index.iter() {
let standing = Standing::of(&members(worklane_dir, &campaign.uuid)?);
let state = match standing.state() {
Some(state) => format!(" [{}]", paint(state, Color::Orange, colored)),
None => String::new(),
};
println!(
" ({}) {} | {}{}",
paint(short_id(&campaign.uuid), Color::Red, colored),
campaign.title,
standing.label(),
state,
);
}
Ok(())
}
/// Show a campaign, then its members grouped by status.
///
/// Every status is shown, done included, unlike `ls`, which leaves done out of its
/// listing. A campaign's whole point is what is finished against what is left, so
/// hiding the finished half would hide the answer.
pub fn cmd_campaign_show(search: &str, worklane_dir: &Path) -> Result<()> {
let campaign = resolve_campaign(search, worklane_dir)?;
println!("{}", color_text(&campaign.title, Color::Green));
println!("{}", "─".repeat(campaign.title.chars().count()));
// No relations and no campaign of its own: a campaign is not a ticket, and neither
// belongs to one.
println!(
"\n{}",
content_trim_colored(&campaign.content, &Resolved::default())
);
let grouped = members(worklane_dir, &campaign.uuid)?;
let standing = Standing::of(&grouped);
println!("{}", color_text("Members", Color::Orange));
println!("{}", "─".repeat("Members".chars().count()));
println!("\n{}", standing.label());
for (status, items) in &grouped {
if items.is_empty() {
continue;
}
println!(
"\n{}",
color_text(&format!("[{}]", status.to_uppercase()), Color::Orange)
);
display_ticket_items(items);
}
Ok(())
}
/// Put a ticket in a campaign, the only writer of the Campaign field.
///
/// The campaign is resolved first, so a call naming a good ticket and a bad campaign
/// writes nothing. A ticket names at most one campaign because the field is rewritten
/// rather than added to, so assigning a ticket that is already in one moves it.
///
/// No-op detection compares the whole file, the way `set` and `chown` do, so assigning
/// a ticket to the campaign it already names writes nothing.
pub fn cmd_assign(campaign_search: &str, ticket_id: &str, start: &Path) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let campaign = resolve_campaign(campaign_search, &worklane_dir)?;
let (status, title, original) = resolve_ticket(ticket_id, &worklane_dir)?;
let uuid = parse_ticket_field(&original, "ID");
let content =
set_or_insert_metadata_field(&original, CAMPAIGN_FIELD, &campaign.uuid, &title)?;
if content == original {
println!(
"Ticket '{}' is already in campaign '{}'",
color_text(&title, Color::Green),
campaign.title,
);
return Ok(());
}
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
println!(
"Assigned '{}' to campaign '{}'",
color_text(&title, Color::Green),
campaign.title,
);
Ok(())
}
/// Which criterion to act on, asked for when the caller did not say.
///
/// A terminal gets the list and a prompt. Anything else gets the same list as an
/// error, which is what `resolve_ticket` does for an ambiguous match and for the same
/// reason: the opencode wrapper throws on the exit code and keeps stderr, so a list
/// printed to stdout would be discarded and an agent would learn nothing. Prompting
/// regardless would leave it blocked on a stdin that never closes.
fn ask_which_criterion(criteria: &[Criterion], title: &str) -> Result<usize> {
let listing = criteria_list(criteria);
if !std::io::stdin().is_terminal() {
return Err(anyhow!(
"Which criterion of '{}'?\n{}\n\nRe-run with the number, or a substring of the text.",
title,
listing
));
}
println!("Acceptance criteria of '{}':", color_text(title, Color::Green));
println!("{}", listing);
// Either form, since find_criteria takes both.
print!("Number or text: ");
std::io::stdout().flush()?;
let mut answer = String::new();
std::io::stdin().lock().read_line(&mut answer)?;
// An empty needle matches every criterion, so it would otherwise be reported as
// ambiguous rather than as nothing having been chosen.
if answer.trim().is_empty() {
return Err(anyhow!("No criterion chosen"));
}
let chosen = find_criteria(criteria, &answer);
match chosen.len() {
1 => Ok(chosen[0]),
0 => Err(anyhow!(
"'{}' matches none of the {} criteria",
answer.trim(),
criteria.len()
)),
_ => Err(anyhow!(
"'{}' matches more than one criterion, use the number",
answer.trim()
)),
}
}
pub fn cmd_check(args: &CheckArgs, checked: bool, start: &Path) -> Result<()> {
let worklane_dir = find_worklane_dir(start)?;
let (status, title, content) = resolve_ticket(&args.ticket, &worklane_dir)?;
let criteria = criteria(&content);
if criteria.is_empty() {
return Err(anyhow!("Ticket '{}' has no acceptance criteria", title));
}
let chosen = match &args.criterion {
None => ask_which_criterion(&criteria, &title)?,
Some(search) => {
let found = find_criteria(&criteria, search);
match found.len() {
1 => found[0],
0 if is_index(search) => {
return Err(anyhow!(
"'{}' is not one of the {} criteria of '{}':\n{}",
search.trim(),
criteria.len(),
title,
criteria_list(&criteria)
));
}
0 => {
return Err(anyhow!(
"No criterion of '{}' matches '{}'. Its criteria are:\n{}",
title,
search,
criteria_list(&criteria)
));
}
_ => {
return Err(anyhow!(
"'{}' matches {} criteria of '{}':\n{}\n\nUse the number instead.",
search,
found.len(),
title,
numbered_criteria(&criteria, &found)
));
}
}
}
};
let criterion = &criteria[chosen];
let verb = if checked { "checked" } else { "unchecked" };
if criterion.checked == checked {
println!(
"Already {}: {}",
verb,
color_text(&criterion.text, Color::Green)
);
return Ok(());
}
let updated = set_criterion(&content, criterion.line, checked);
let uuid = parse_ticket_field(&content, "ID");
save_ticket(&worklane_dir, &status, &uuid, &title, None, &updated)?;
println!(
"{} {}: {}",
if checked { "Checked" } else { "Unchecked" },
chosen + 1,
color_text(&criterion.text, Color::Green)
);
Ok(())
}
/// Install the agent skills, or print one so a modified copy can be diffed.
///
/// No board is looked for. The documents are what teach an agent worklane, so needing
/// a `.worklane` to install them would put them out of reach exactly when they are
/// wanted.
///
/// With no name, every shipped document is installed. Narrowing to one is the
/// exception rather than the rule, so that a document added in a later version reaches
/// anyone who already knows the command.
pub fn cmd_install_skill(skill: Option<&str>, force: bool, print: bool) -> Result<()> {
if print {
// Printing every document would run them together into something that is not
// any of them, and the point of `--print` is to diff one against its copy.
let name = skill.ok_or_else(|| {
anyhow!(
"name the skill to print, as in `worklane install-skill worklane --print`. This binary ships {}",
install::skill_names()
)
})?;
print!("{}", install::skill_named(name)?.content);
return Ok(());
}
let chosen: Vec<&install::Asset> = match skill {
Some(name) => vec![install::skill_named(name)?],
None => install::SKILLS.iter().collect(),
};
let root = install::skills_root()?;
let mut written = false;
for asset in chosen {
match asset.install(&root, force)? {
install::Outcome::Written(path) => {
println!("Installed the {} {} to: {}", asset.name, asset.what, path.display());
written = true;
}
install::Outcome::Unchanged(path) => {
println!("Already up to date: {}", path.display());
}
install::Outcome::Refused(path) => {
println!("Differs from the version in this binary: {}", path.display());
println!(
"Compare with `worklane install-skill {} --print`, or overwrite with --force",
asset.name
);
}
}
}
// Once, and only when something arrived: repeating it per document would make the
// instruction look like part of each outcome rather than the one thing to do next.
if written {
println!("Claude Code and opencode pick it up on their next session");
}
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();
}
}