resolve_ticket printed the candidate list to stdout and called process::exit(1) from inside a helper. That combination is the one thing the opencode wrapper cannot relay: it throws on the non-zero exit and keeps stderr, so the list was thrown away and the agent saw a bare exit code with nothing to choose from. Return an error carrying the rendered list instead. It reaches stderr the way every other error does, the exit code stays non-zero so `show x && ...` still fails, and no process::exit remains in util.rs. The wrapper half, which was dropping stderr on the floor regardless, follows in 3e8b6fa. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
523 lines
16 KiB
Rust
523 lines
16 KiB
Rust
use anyhow::{Result, anyhow};
|
|
use chrono::NaiveDateTime;
|
|
use std::fs;
|
|
use std::io::IsTerminal;
|
|
use std::path::Path;
|
|
|
|
/// How timestamps are written into tickets and comments, and therefore how they
|
|
/// are read back. Shared so the writer and the reader cannot drift apart.
|
|
pub const TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M:%S";
|
|
|
|
pub fn should_use_colors() -> bool {
|
|
std::io::stdout().is_terminal()
|
|
}
|
|
|
|
pub fn get_color(color: &str) -> &'static str {
|
|
match color {
|
|
"red" => "\x1b[31m",
|
|
"cyan" => "\x1b[36m",
|
|
"orange" => "\x1b[33m",
|
|
"green" => "\x1b[32m",
|
|
"grey" => "\x1b[90m",
|
|
_ => "",
|
|
}
|
|
}
|
|
|
|
pub fn color_text(text: &str, color: &str) -> String {
|
|
if should_use_colors() {
|
|
format!("{}{}{}", get_color(color), text, "\x1b[0m")
|
|
} else {
|
|
text.to_string()
|
|
}
|
|
}
|
|
|
|
pub fn find_worklane_dir(start: &Path) -> Result<std::path::PathBuf> {
|
|
let mut current = start.canonicalize()?;
|
|
|
|
loop {
|
|
let worklane_dir = current.join(".worklane");
|
|
if worklane_dir.exists() {
|
|
return Ok(worklane_dir);
|
|
}
|
|
|
|
if !current.pop() {
|
|
break;
|
|
}
|
|
}
|
|
|
|
Err(anyhow!(
|
|
"No .worklane directory found. Run `worklane init` first."
|
|
))
|
|
}
|
|
|
|
/// Width of the abbreviated id shown by `ls` and by the disambiguation list.
|
|
pub const SHORT_ID_WIDTH: usize = 7;
|
|
|
|
/// The leading characters of `text`, counted in characters rather than bytes.
|
|
///
|
|
/// Byte slicing panics twice over here: on text shorter than the width, and on a
|
|
/// multibyte character straddling the cut. Both reach this code from a filename,
|
|
/// which nothing validates.
|
|
pub fn truncate_chars(text: &str, width: usize) -> &str {
|
|
match text.char_indices().nth(width) {
|
|
Some((byte, _)) => &text[..byte],
|
|
None => text,
|
|
}
|
|
}
|
|
|
|
/// A ticket id abbreviated for display.
|
|
pub fn short_id(id: &str) -> &str {
|
|
truncate_chars(id, SHORT_ID_WIDTH)
|
|
}
|
|
|
|
pub fn slug(title: &str) -> String {
|
|
title
|
|
.to_lowercase()
|
|
.chars()
|
|
.filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_')
|
|
.map(|c| if c == ' ' { '-' } else { c })
|
|
.collect()
|
|
}
|
|
|
|
pub fn get_git_user() -> Option<String> {
|
|
std::process::Command::new("git")
|
|
.args(&["config", "user.name"])
|
|
.output()
|
|
.ok()
|
|
.and_then(|out| {
|
|
if out.status.success() {
|
|
String::from_utf8(out.stdout)
|
|
.ok()
|
|
.map(|s| s.trim().to_string())
|
|
.filter(|s| !s.is_empty())
|
|
} else {
|
|
None
|
|
}
|
|
})
|
|
}
|
|
/// The candidate list for an ambiguous search, as an error rather than a print
|
|
/// followed by `exit(1)`.
|
|
///
|
|
/// An error reaches the user on stderr and leaves the exit code non-zero, which
|
|
/// is the only combination the opencode wrapper can relay: it throws on the exit
|
|
/// code and keeps stderr, so the list printed to stdout was thrown away and the
|
|
/// agent saw nothing but a bare exit code.
|
|
fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyhow::Error {
|
|
let mut message = format!("Multiple tickets found matching '{}':\n", search);
|
|
|
|
for (i, (status, title, _, id)) in matches.iter().enumerate() {
|
|
message.push_str(&format!(
|
|
" {}. ({}) {} [{}]\n",
|
|
i + 1,
|
|
color_text(short_id(id), "red"),
|
|
title,
|
|
color_text(status, "orange"),
|
|
));
|
|
}
|
|
|
|
message.push_str("\nUse the displayed ID or a more specific search term to select.");
|
|
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();
|
|
|
|
for status in &statuses {
|
|
let status_path = worklane_dir.join(status);
|
|
if !status_path.exists() {
|
|
continue;
|
|
}
|
|
let entries = fs::read_dir(&status_path)?;
|
|
for entry in entries.filter_map(|e| e.ok()) {
|
|
let path = entry.path();
|
|
if !path.extension().map_or(false, |e| e == "md") {
|
|
continue;
|
|
}
|
|
let content = match fs::read_to_string(&path) {
|
|
Ok(c) => c,
|
|
Err(_) => continue,
|
|
};
|
|
let title = content
|
|
.lines()
|
|
.find(|l| l.starts_with("# "))
|
|
.map(|l| l[2..].trim())
|
|
.unwrap_or("")
|
|
.to_string();
|
|
let filename = path
|
|
.file_stem()
|
|
.map(|s| s.to_string_lossy().to_string())
|
|
.unwrap_or_default();
|
|
let short_id = filename.split('_').next().unwrap_or("");
|
|
|
|
let search_lower = search.to_lowercase();
|
|
let title_lower = title.to_lowercase();
|
|
let filename_lower = filename.to_lowercase();
|
|
|
|
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 id_match || title_match || filename_match {
|
|
matches.push((status.to_string(), title, content, short_id.to_string()));
|
|
}
|
|
}
|
|
}
|
|
|
|
if matches.is_empty() {
|
|
return Err(anyhow!("No ticket found matching '{}'", search));
|
|
}
|
|
|
|
if matches.len() > 1 {
|
|
return Err(ambiguous(search, &matches));
|
|
}
|
|
|
|
let (status, title, content, _short_id) = matches.remove(0);
|
|
Ok((status, title, content))
|
|
}
|
|
pub fn format_comments(comments: &[(String, String, String, String)]) -> String {
|
|
if comments.is_empty() {
|
|
return color_text("No comments yet.", "grey");
|
|
}
|
|
|
|
let mut result = String::new();
|
|
result.push_str("\n");
|
|
result.push_str(&color_text("COMMENTS", "orange"));
|
|
result.push_str(&format!("\n{}\n", "─".repeat(20)));
|
|
|
|
for (_filename, author, time, body) in comments {
|
|
result.push_str("\n");
|
|
result.push_str(&color_text(&format!("From {} ({})", author, time), "cyan"));
|
|
result.push_str("\n");
|
|
if !body.is_empty() {
|
|
result.push_str(&" ".to_string());
|
|
result.push_str(body);
|
|
}
|
|
result.push('\n');
|
|
}
|
|
|
|
result
|
|
}
|
|
pub fn content_trim_colored(content: &str) -> String {
|
|
let lines: Vec<&str> = content.trim().lines().collect();
|
|
let mut result = String::new();
|
|
let mut current_section = "";
|
|
|
|
for line in &lines {
|
|
// Track current section
|
|
if line.starts_with("## ") {
|
|
current_section = line;
|
|
let section_name = &line[3..];
|
|
result.push_str(&color_text(section_name, "orange"));
|
|
result.push('\n');
|
|
result.push_str(&"─".repeat(line.len()));
|
|
result.push('\n');
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
|
|
// First line is the title header - color it in green
|
|
if line.starts_with("# ") && current_section.is_empty() {
|
|
let header = &line[2..]; // Remove "# "
|
|
result.push_str(&color_text(header, "green"));
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
|
|
// Implementation Plan - color numbers in cyan
|
|
if current_section == "## Implementation Plan" {
|
|
result.push_str(&colorize_ordered(line));
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
|
|
// Metadata - color field names in RED
|
|
if current_section == "## Metadata" {
|
|
result.push_str(&colorize_metadata(line));
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
|
|
// Acceptance Criteria checkboxes
|
|
if line.starts_with("- [ ]") {
|
|
result.push_str(&color_text("- [ ]", "grey"));
|
|
result.push_str(&line[5..]);
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
|
|
// Standard markdown link colorization in cyan
|
|
if line.contains("[") && line.contains("(") && line.contains("]") {
|
|
if let Some(start) = line.find("[") {
|
|
let bracket_text = &line[start..];
|
|
if let Some(end_bracket) = bracket_text.find("](") {
|
|
let link_start = start + end_bracket + 1;
|
|
if let Some(end) = line[link_start..].find(']') {
|
|
let absolute_end = link_start + end + 1;
|
|
result.push_str(&color_text(&line[start..absolute_end], "cyan"));
|
|
result.push('\n');
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Regular content - colorize **bold** in magenta
|
|
result.push_str(&colorize_line(line));
|
|
result.push('\n');
|
|
}
|
|
|
|
result
|
|
}
|
|
|
|
pub fn colorize_ordered(line: &str) -> String {
|
|
if line.chars().next().map_or(true, |c| !c.is_ascii_digit()) {
|
|
return line.to_string();
|
|
}
|
|
|
|
// Match "1. " pattern and color the number in cyan
|
|
let mut result = String::new();
|
|
let chars: Vec<char> = line.chars().collect();
|
|
|
|
for (i, c) in chars.iter().enumerate() {
|
|
if c.is_ascii_digit() {
|
|
// still scanning digits
|
|
} else if *c == '.' && i + 1 < chars.len() && chars[i + 1] == ' ' {
|
|
let number = &line[..i + 1];
|
|
result.push_str(&color_text(number, "cyan"));
|
|
result.push_str(&line[i + 1..]);
|
|
return result;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
line.to_string()
|
|
}
|
|
|
|
pub fn colorize_metadata(line: &str) -> String {
|
|
if !line.contains("**") {
|
|
return line.to_string();
|
|
}
|
|
|
|
let content = line;
|
|
let open_pos = match content.find("**") {
|
|
Some(p) => p,
|
|
None => return content.to_string(),
|
|
};
|
|
|
|
let after_open = open_pos + 2;
|
|
let remaining = &content[after_open..];
|
|
let close_pos = match remaining.find("**") {
|
|
Some(p) => p,
|
|
None => return content.to_string(),
|
|
};
|
|
|
|
let field_name = &content[after_open..after_open + close_pos];
|
|
let after_field = &content[after_open + close_pos + 2..];
|
|
|
|
let colored_field = color_text(field_name, "red");
|
|
let value_text = after_field.strip_prefix(": ").map(|s| s.trim()).unwrap_or(after_field);
|
|
let after_field_colored = if is_unknown_value(value_text) {
|
|
color_text(after_field, "grey")
|
|
} else {
|
|
after_field.to_string()
|
|
};
|
|
|
|
format!(
|
|
"{}{}{}",
|
|
&content[..open_pos],
|
|
colored_field,
|
|
after_field_colored
|
|
)
|
|
}
|
|
|
|
pub fn is_unknown_value(value: &str) -> bool {
|
|
let trimmed = value.trim();
|
|
trimmed == "_None_" || trimmed == "_Not set_" || trimmed == "-None-" || trimmed == "-Not set-"
|
|
}
|
|
|
|
pub fn colorize_line(line: &str) -> String {
|
|
let mut result = String::new();
|
|
let chars: Vec<char> = line.chars().collect();
|
|
let len = chars.len();
|
|
let mut i = 0;
|
|
|
|
while i < len {
|
|
// Check for **bold** markdown
|
|
if i + 1 < len && chars[i] == '*' && chars[i + 1] == '*' {
|
|
// Find closing **
|
|
let start = i + 2;
|
|
let mut end = start;
|
|
while end + 1 < len && !(chars[end] == '*' && chars[end + 1] == '*') {
|
|
if chars[end] == '\n' {
|
|
break;
|
|
}
|
|
end += 1;
|
|
}
|
|
|
|
let bold_text: String = chars[start..end].iter().collect();
|
|
result.push_str(&color_text(&bold_text, "magenta"));
|
|
i = end + 2;
|
|
continue;
|
|
}
|
|
|
|
result.push(chars[i]);
|
|
i += 1;
|
|
}
|
|
|
|
result
|
|
}
|
|
|
|
pub fn parse_ticket_field(content: &str, field: &str) -> String {
|
|
let pattern = format!("**{}**:", field);
|
|
content
|
|
.lines()
|
|
.find(|line| line.contains(&pattern))
|
|
.map(|line| {
|
|
line.splitn(2, &pattern)
|
|
.nth(1)
|
|
.unwrap_or("_Not set_")
|
|
.trim()
|
|
.to_string()
|
|
})
|
|
.unwrap_or("_Not set_".to_string())
|
|
}
|
|
|
|
fn is_status_line(line: &str) -> bool {
|
|
// The second spelling is what earlier versions wrote, repair it on the way through.
|
|
line.starts_with("- **Status**:") || line.starts_with("- **-Status**:")
|
|
}
|
|
|
|
// Rewrite the Status field in the Metadata section, leaving every other line untouched.
|
|
pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Result<String> {
|
|
let mut updated = String::with_capacity(content.len());
|
|
let mut found = false;
|
|
|
|
for line in content.lines() {
|
|
if !found && is_status_line(line) {
|
|
updated.push_str("- **Status**: ");
|
|
updated.push_str(target_status);
|
|
found = true;
|
|
} else {
|
|
updated.push_str(line);
|
|
}
|
|
updated.push('\n');
|
|
}
|
|
|
|
if !found {
|
|
return Err(anyhow!(
|
|
"Ticket '{}' has no Status field in its Metadata section",
|
|
title
|
|
));
|
|
}
|
|
|
|
Ok(updated)
|
|
}
|
|
|
|
// Format created_at for display: "YYYY-MM-DD HH:MM:SS" becomes "YY-MM-DD:HH".
|
|
//
|
|
// Parsed rather than sliced by byte offset: the value comes from a file nothing
|
|
// validates, and the old offsets panicked on any multibyte character before them.
|
|
// Anything unparseable yields an empty string, which drops the column.
|
|
pub fn format_created_at(created_at: &str) -> String {
|
|
match NaiveDateTime::parse_from_str(created_at, TIMESTAMP_FORMAT) {
|
|
Ok(created_at) => created_at.format("%y-%m-%d:%H").to_string(),
|
|
Err(_) => String::new(),
|
|
}
|
|
}
|
|
|
|
pub fn status_dirs() -> Vec<&'static str> {
|
|
vec!["backlog", "committed", "reviewing", "done"]
|
|
}
|
|
|
|
pub type TicketItem = (String, String, String, String, String);
|
|
|
|
pub fn display_ticket_items(items: &Vec<TicketItem>) {
|
|
for (title, owner, due, uuid, ts) in items {
|
|
let uuid_colored = color_text(uuid, "red");
|
|
if ts.is_empty() {
|
|
println!(
|
|
" ({}) {} | Owner: {} | Due: {}",
|
|
uuid_colored, title, owner, due
|
|
);
|
|
} else {
|
|
let ts_colored = color_text(ts, "cyan");
|
|
println!(
|
|
" {} ({}) {} | Owner: {} | Due: {}",
|
|
ts_colored, uuid_colored, title, owner, due
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketItem>> {
|
|
let entries: Vec<_> = fs::read_dir(status_path)?.filter_map(|e| e.ok()).collect();
|
|
|
|
let mut items: Vec<TicketItem> = entries
|
|
.iter()
|
|
.filter_map(|e| {
|
|
let content = fs::read_to_string(e.path()).ok()?;
|
|
let title = content
|
|
.lines()
|
|
.find(|l| l.starts_with("# "))
|
|
.map(|l| l[2..].trim().to_string())
|
|
.unwrap_or_else(|| "_No title_".to_string());
|
|
let owner = parse_ticket_field(&content, "Owner");
|
|
let due = parse_ticket_field(&content, "Due");
|
|
let filename = e.path().file_stem()?.to_string_lossy().to_string();
|
|
let created_at = parse_ticket_field(&content, "Created At");
|
|
let short_date = format_created_at(&created_at);
|
|
|
|
Some((
|
|
title,
|
|
owner,
|
|
due,
|
|
short_id(&filename).to_string(),
|
|
short_date,
|
|
))
|
|
})
|
|
.collect();
|
|
|
|
items.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()));
|
|
Ok(items)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn short_id_shortens_a_full_uuid() {
|
|
assert_eq!(short_id("c230d2c6-d78a-44a5-8f5f-88fb28f84493"), "c230d2c");
|
|
}
|
|
|
|
#[test]
|
|
fn short_id_leaves_anything_shorter_alone() {
|
|
assert_eq!(short_id("abc"), "abc");
|
|
assert_eq!(short_id(""), "");
|
|
assert_eq!(short_id("abcdefg"), "abcdefg");
|
|
}
|
|
|
|
/// The cut used to land inside a character and panic.
|
|
#[test]
|
|
fn short_id_counts_characters_not_bytes() {
|
|
assert_eq!(short_id("émigré-ticket"), "émigré-");
|
|
assert_eq!(short_id("日本語"), "日本語");
|
|
}
|
|
|
|
#[test]
|
|
fn created_at_is_shortened_for_display() {
|
|
assert_eq!(format_created_at("2026-08-20 13:06:34"), "26-08-20:13");
|
|
}
|
|
|
|
/// Every one of these reached the old byte offsets from an unvalidated file.
|
|
#[test]
|
|
fn unparseable_created_at_drops_the_column() {
|
|
for value in ["_Not set_", "", "2026-08-20", "日本語日本語日本語", "not a date at all"] {
|
|
assert_eq!(format_created_at(value), "", "for {value:?}");
|
|
}
|
|
}
|
|
}
|