1use anyhow::{bail, Context, Result};
2use std::collections::{HashMap, HashSet, VecDeque};
3use std::path::Path;
4
5use super::ticket_fmt::{parse_checklist, serialize_checklist, id_arg_prefixes, slugify, Frontmatter, Ticket, TicketDocument};
6
7impl Ticket {
8 pub fn score(&self, priority_weight: f64, effort_weight: f64, risk_weight: f64) -> f64 {
9 let fm = &self.frontmatter;
10 fm.priority as f64 * priority_weight
11 + fm.effort as f64 * effort_weight
12 + fm.risk as f64 * risk_weight
13 }
14}
15
16impl TicketDocument {
17 pub fn unchecked_tasks(&self, section_name: &str) -> Vec<usize> {
18 let val = self.sections.get(section_name).map(|s| s.as_str()).unwrap_or("");
19 parse_checklist(val).into_iter().enumerate()
20 .filter(|(_, c)| !c.checked)
21 .map(|(i, _)| i)
22 .collect()
23 }
24
25 pub fn toggle_criterion(&mut self, index: usize, checked: bool) -> Result<()> {
26 let val = self.sections.get("Acceptance criteria").cloned().unwrap_or_default();
27 let mut items = parse_checklist(&val);
28 if index >= items.len() {
29 anyhow::bail!("criterion index {index} out of range (have {})", items.len());
30 }
31 items[index].checked = checked;
32 self.sections.insert("Acceptance criteria".to_string(), serialize_checklist(&items));
33 Ok(())
34 }
35}
36
37pub fn build_reverse_index<'a>(tickets: &[&'a Ticket]) -> HashMap<&'a str, Vec<&'a Ticket>> {
41 let mut map: HashMap<&'a str, Vec<&'a Ticket>> = HashMap::new();
42 for &ticket in tickets {
43 if let Some(deps) = &ticket.frontmatter.depends_on {
44 for dep_id in deps {
45 map.entry(dep_id.as_str()).or_default().push(ticket);
46 }
47 }
48 }
49 map
50}
51
52pub fn effective_priority(ticket: &Ticket, reverse_index: &HashMap<&str, Vec<&Ticket>>) -> u8 {
56 let mut max_priority = ticket.frontmatter.priority;
57 let mut visited: HashSet<&str> = HashSet::new();
58 let mut queue: VecDeque<&str> = VecDeque::new();
59 let id = ticket.frontmatter.id.as_str();
60 queue.push_back(id);
61 visited.insert(id);
62 while let Some(cur_id) = queue.pop_front() {
63 if let Some(dependents) = reverse_index.get(cur_id) {
64 for &dep in dependents {
65 let dep_id = dep.frontmatter.id.as_str();
66 if visited.insert(dep_id) {
67 if dep.frontmatter.priority > max_priority {
68 max_priority = dep.frontmatter.priority;
69 }
70 queue.push_back(dep_id);
71 }
72 }
73 }
74 }
75 max_priority
76}
77
78pub fn sorted_actionable<'a>(
80 tickets: &'a [Ticket],
81 actionable: &[&str],
82 pw: f64,
83 ew: f64,
84 rw: f64,
85 _caller: Option<&str>,
86 owner_filter: Option<&str>,
87) -> Vec<&'a Ticket> {
88 let mut candidates: Vec<&Ticket> = tickets
89 .iter()
90 .filter(|t| actionable.contains(&t.frontmatter.state.as_str()))
91 .filter(|t| owner_filter.is_none_or(|f| t.frontmatter.owner.as_deref() == Some(f)))
92 .collect();
93 let rev_idx = build_reverse_index(&candidates);
94 candidates.sort_by(|a, b| {
95 let score_a = effective_priority(a, &rev_idx) as f64 * pw
96 + a.frontmatter.effort as f64 * ew
97 + a.frontmatter.risk as f64 * rw;
98 let score_b = effective_priority(b, &rev_idx) as f64 * pw
99 + b.frontmatter.effort as f64 * ew
100 + b.frontmatter.risk as f64 * rw;
101 score_b.partial_cmp(&score_a).unwrap_or(std::cmp::Ordering::Equal)
102 });
103 candidates
104}
105
106pub fn dep_satisfied(dep_state: &str, required_gate: Option<&str>, config: &crate::config::Config) -> bool {
111 use crate::config::SatisfiesDeps;
112 config.workflow.states.iter()
113 .find(|s| s.id == dep_state)
114 .map(|s| {
115 if s.terminal { return true; }
116 match &s.satisfies_deps {
117 SatisfiesDeps::Bool(true) => true,
118 SatisfiesDeps::Tag(tag) => required_gate == Some(tag.as_str()),
119 SatisfiesDeps::Bool(false) => false,
120 }
121 })
122 .unwrap_or(false)
123}
124
125#[allow(clippy::too_many_arguments)]
129pub fn pick_next<'a>(
130 tickets: &'a [Ticket],
131 actionable: &[&str],
132 startable: &[&str],
133 pw: f64,
134 ew: f64,
135 rw: f64,
136 config: &crate::config::Config,
137 caller: Option<&str>,
138 owner_filter: Option<&str>,
139) -> Option<&'a Ticket> {
140 sorted_actionable(tickets, actionable, pw, ew, rw, caller, owner_filter)
141 .into_iter()
142 .find(|t| {
143 let state = t.frontmatter.state.as_str();
144 if !startable.is_empty() && !startable.contains(&state) {
145 return false;
146 }
147 let required_gate = config.workflow.states.iter()
148 .find(|s| s.id == state)
149 .and_then(|s| s.dep_requires.as_deref());
150 if let Some(deps) = &t.frontmatter.depends_on {
151 for dep_id in deps {
152 if let Some(dep) = tickets.iter().find(|d| d.frontmatter.id == *dep_id) {
153 if !dep_satisfied(&dep.frontmatter.state, required_gate, config) {
154 return false;
155 }
156 }
157 }
158 }
159 true
160 })
161}
162
163pub fn load_all_from_git(root: &Path, tickets_dir_rel: &std::path::Path) -> Result<Vec<Ticket>> {
166 let branches = crate::git::ticket_branches(root)?;
167 let mut tickets = Vec::new();
168 for branch in &branches {
169 let suffix = branch.trim_start_matches("ticket/");
170 if suffix.len() == 8 && suffix.chars().all(|c| c.is_ascii_hexdigit()) {
173 continue;
174 }
175 let filename = format!("{suffix}.md");
176 let rel_path = format!("{}/{}", tickets_dir_rel.to_string_lossy(), filename);
177 let dummy_path = root.join(&rel_path);
178 if let Ok(content) = crate::git::read_from_branch(root, branch, &rel_path) {
179 if let Ok(t) = Ticket::parse(&dummy_path, &content) {
180 tickets.push(t);
181 }
182 }
183 }
184 tickets.sort_by_key(|t| t.frontmatter.created_at);
185 Ok(tickets)
186}
187
188pub fn load_all_from_git_classified(root: &Path, tickets_dir_rel: &std::path::Path) -> Result<Vec<Ticket>> {
203 let branches = crate::git::ticket_branches(root)?;
204 let mut tickets = Vec::new();
205 for branch in &branches {
206 let suffix = branch.trim_start_matches("ticket/");
207 if suffix.len() == 8 && suffix.chars().all(|c| c.is_ascii_hexdigit()) {
208 continue;
209 }
210 let filename = format!("{suffix}.md");
211 let rel_path = format!("{}/{}", tickets_dir_rel.to_string_lossy(), filename);
212 let dummy_path = root.join(&rel_path);
213 if let Ok((content, class)) = crate::git::read_from_branch_with_class(root, branch, &rel_path) {
214 if let Ok(mut t) = Ticket::parse(&dummy_path, &content) {
215 t.local_stale = matches!(class, crate::git::BranchClass::Behind);
216 t.local_diverged = matches!(class, crate::git::BranchClass::Diverged);
217 tickets.push(t);
218 }
219 }
220 }
221 tickets.sort_by_key(|t| t.frontmatter.created_at);
222 Ok(tickets)
223}
224
225pub fn state_from_branch(root: &Path, branch: &str, rel_path: &str) -> Option<String> {
227 let content = crate::git::read_from_branch(root, branch, rel_path).ok()?;
228 let dummy = root.join(rel_path);
229 Ticket::parse(&dummy, &content).ok().map(|t| t.frontmatter.state)
230}
231
232pub fn close(
236 root: &Path,
237 config: &crate::config::Config,
238 id_arg: &str,
239 reason: Option<&str>,
240 agent: &str,
241 aggressive: bool,
242) -> Result<Vec<String>> {
243 let mut output: Vec<String> = Vec::new();
244 let mut tickets = load_all_from_git(root, &config.tickets.dir)?;
245 let prefixes = id_arg_prefixes(id_arg)?;
246
247 let branch_matches: Vec<usize> = tickets.iter()
250 .enumerate()
251 .filter(|(_, t)| prefixes.iter().any(|p| t.frontmatter.id.starts_with(p.as_str())))
252 .map(|(i, _)| i)
253 .collect();
254 let branch_matches: Vec<usize> = {
256 let mut seen = std::collections::HashSet::new();
257 branch_matches.into_iter().filter(|&i| seen.insert(tickets[i].frontmatter.id.clone())).collect()
258 };
259
260 let mut from_default: Option<Ticket> = None;
261 let id: String = match branch_matches.len() {
262 1 => tickets[branch_matches[0]].frontmatter.id.clone(),
263 0 => {
264 let default_branch = &config.project.default_branch;
265 let mut found: Option<Ticket> = None;
266 if let Ok(files) = crate::git::list_files_on_branch(root, default_branch, &config.tickets.dir.to_string_lossy()) {
267 for rel_path in files {
268 if !rel_path.ends_with(".md") { continue; }
269 if let Ok(content) = crate::git::read_from_branch(root, default_branch, &rel_path) {
270 let dummy = root.join(&rel_path);
271 if let Ok(t) = Ticket::parse(&dummy, &content) {
272 if prefixes.iter().any(|p| t.frontmatter.id.starts_with(p.as_str())) {
273 found = Some(t);
274 break;
275 }
276 }
277 }
278 }
279 }
280 match found {
281 Some(t) => { let id = t.frontmatter.id.clone(); from_default = Some(t); id }
282 None => bail!("no ticket matches '{id_arg}'"),
283 }
284 }
285 _ => {
286 let names: Vec<String> = branch_matches.iter()
287 .map(|&i| tickets[i].frontmatter.id.clone())
288 .collect();
289 bail!("ambiguous prefix '{}', matches: {}", id_arg, names.join(", "));
290 }
291 };
292
293 let ticket_pos = tickets.iter().position(|t| t.frontmatter.id == id);
294 let t: &mut Ticket = match ticket_pos {
295 Some(pos) => &mut tickets[pos],
296 None => from_default.as_mut().ok_or_else(|| anyhow::anyhow!("ticket {id:?} not found"))?,
297 };
298
299 if t.frontmatter.state == "closed" {
300 anyhow::bail!("ticket {id:?} is already closed");
301 }
302
303 let now = chrono::Utc::now();
304 let prev = t.frontmatter.state.clone();
305 let when = now.format("%Y-%m-%dT%H:%MZ").to_string();
306 let by = match reason {
307 Some(r) => format!("{agent} (reason: {r})"),
308 None => agent.to_string(),
309 };
310
311 t.frontmatter.state = "closed".into();
312 t.frontmatter.updated_at = Some(now);
313
314 crate::state::append_history(&mut t.body, &prev, "closed", &when, &by);
315
316 let content = t.serialize()?;
317 let rel_path = format!(
318 "{}/{}",
319 config.tickets.dir.to_string_lossy(),
320 t.path.file_name().unwrap().to_string_lossy()
321 );
322 let branch = t.frontmatter.branch.clone()
323 .or_else(|| crate::ticket_fmt::branch_name_from_path(&t.path))
324 .unwrap_or_else(|| format!("ticket/{id}"));
325
326 crate::git::commit_to_branch(root, &branch, &rel_path, &content, &format!("ticket({id}): close"))?;
327 crate::logger::log("state_transition", &format!("{id:?} {prev} -> closed"));
328
329 let target = t.frontmatter.target_branch.as_deref()
330 .unwrap_or(config.project.default_branch.as_str());
331 if let Err(e) = crate::git::commit_to_branch(root, target, &rel_path, &content, &format!("ticket({id}): close")) {
332 output.push(format!("warning: commit closed state to {target} failed: {e:#}"));
333 }
334
335 if aggressive {
336 if let Err(e) = crate::git::push_branch(root, &branch) {
337 output.push(format!("warning: push failed for {branch}: {e:#}"));
338 }
339 }
340
341 output.push(format!("{id}: {prev} → closed"));
342 Ok(output)
343}
344
345#[allow(clippy::too_many_arguments)]
346pub fn create(
347 root: &std::path::Path,
348 config: &crate::config::Config,
349 title: String,
350 author: String,
351 actor: String,
352 context: Option<String>,
353 context_section: Option<String>,
354 aggressive: bool,
355 section_sets: Vec<(String, String)>,
356 epic: Option<String>,
357 target_branch: Option<String>,
358 depends_on: Option<Vec<String>>,
359 base_branch: Option<String>,
360 warnings: &mut Vec<String>,
361) -> Result<Ticket> {
362 let tickets_dir = root.join(&config.tickets.dir);
363 std::fs::create_dir_all(&tickets_dir)?;
364
365 let id = crate::ticket_fmt::gen_hex_id();
366 let slug = slugify(&title);
367 let filename = format!("{id}-{slug}.md");
368 let rel_path = format!("{}/{}", config.tickets.dir.to_string_lossy(), filename);
369 let branch = format!("ticket/{id}-{slug}");
370 let now = chrono::Utc::now();
371 let fm = Frontmatter {
372 id: id.clone(),
373 title: title.clone(),
374 state: "new".into(),
375 priority: 0,
376 effort: 0,
377 risk: 0,
378 author: Some(author.clone()),
379 owner: Some(author.clone()),
380 branch: Some(branch.clone()),
381 created_at: Some(now),
382 updated_at: Some(now),
383 focus_section: None,
384 epic,
385 target_branch,
386 depends_on,
387 agent: None,
388 agent_overrides: std::collections::HashMap::new(),
389 };
390 let when = now.format("%Y-%m-%dT%H:%MZ");
391 let by = if actor != author { format!("{actor}|{author}") } else { actor.clone() };
392 let history_footer = format!("## History\n\n| When | From | To | By |\n|------|------|----|----|\n| {when} | — | new | {by} |\n");
393 let body_template = {
394 let mut s = String::from("## Spec\n\n");
395 for sec in &config.ticket.sections {
396 let placeholder = sec.placeholder.as_deref().unwrap_or("");
397 s.push_str(&format!("### {}\n\n{}\n\n", sec.name, placeholder));
398 }
399 s.push_str(&history_footer);
400 s
401 };
402 let body = if let Some(ctx) = &context {
403 let transition_section = config.workflow.states.iter()
404 .find(|s| s.id == "new")
405 .and_then(|s| s.transitions.iter().find(|tr| tr.to == "in_design"))
406 .and_then(|tr| tr.context_section.clone());
407 let section = context_section
408 .clone()
409 .or(transition_section)
410 .unwrap_or_else(|| "Problem".to_string());
411 if !config.ticket.sections.is_empty()
412 && !config.has_section(§ion)
413 {
414 anyhow::bail!("section '### {section}' not found in ticket body template");
415 }
416 let mut doc = TicketDocument::parse(&body_template)?;
417 crate::spec::set_section(&mut doc, §ion, ctx.clone());
418 doc.serialize()
419 } else {
420 body_template
421 };
422 let path = tickets_dir.join(&filename);
423 let mut t = Ticket { frontmatter: fm, body, path, local_stale: false, local_diverged: false };
424
425 if !section_sets.is_empty() {
426 let mut doc = t.document()?;
427 for (name, value) in §ion_sets {
428 let trimmed = value.trim().to_string();
429 let formatted = if !config.ticket.sections.is_empty() {
430 let section_config = config.find_section(name)
431 .ok_or_else(|| anyhow::anyhow!("unknown section {:?}", name))?;
432 crate::spec::apply_section_type(§ion_config.type_, trimmed)
433 } else {
434 trimmed
435 };
436 crate::spec::set_section(&mut doc, name, formatted);
437 }
438 t.body = doc.serialize();
439 }
440
441 let content = t.serialize()?;
442
443 if let Some(base) = base_branch {
444 let sha = crate::git::resolve_branch_sha(root, &base)?;
445 crate::git::create_branch_at(root, &branch, &sha)?;
446 }
447
448 crate::git::commit_to_branch(
449 root,
450 &branch,
451 &rel_path,
452 &content,
453 &format!("ticket({id}): create {title}"),
454 )?;
455
456 if aggressive {
457 if let Err(e) = crate::git::push_branch_tracking(root, &branch) {
458 warnings.push(format!("warning: push failed: {e:#}"));
459 }
460 }
461
462 Ok(t)
463}
464
465#[allow(clippy::too_many_arguments)]
466pub fn list_filtered<'a>(
467 tickets: &'a [Ticket],
468 config: &crate::config::Config,
469 state_filter: Option<&str>,
470 unassigned: bool,
471 all: bool,
472 actionable_filter: Option<&str>,
473 author_filter: Option<&str>,
474 owner_filter: Option<&str>,
475 mine_user: Option<&str>,
476) -> Vec<&'a Ticket> {
477 let terminal = config.terminal_state_ids();
478
479 tickets.iter().filter(|t| {
480 let fm = &t.frontmatter;
481 let state_ok = state_filter.is_none_or(|s| fm.state == s);
482 let agent_ok = !unassigned || fm.author.as_deref() == Some("unassigned");
483 let state_is_terminal = state_filter.is_some_and(|s| terminal.contains(s));
484 let terminal_ok = all || state_is_terminal || !terminal.contains(fm.state.as_str());
485 let actionable_ok = actionable_filter.is_none_or(|actor| {
486 let state = config.workflow.states.iter().find(|s| s.id == fm.state);
487 match (actor, state) {
488 ("agent", Some(s)) => s.transitions.iter().any(|t| t.trigger == "command:start"),
489 ("supervisor", Some(s)) => !s.terminal
490 && !s.transitions.iter().any(|t| t.trigger == "command:start"),
491 _ => false,
492 }
493 });
494 let author_ok = author_filter.is_none_or(|a| fm.author.as_deref() == Some(a));
495 let owner_ok = owner_filter.is_none_or(|o| fm.owner.as_deref() == Some(o));
496 let mine_ok = mine_user.is_none_or(|me| {
497 fm.author.as_deref() == Some(me) || fm.owner.as_deref() == Some(me)
498 });
499 state_ok && agent_ok && terminal_ok && actionable_ok && author_ok && owner_ok && mine_ok
500 }).collect()
501}
502
503pub fn check_owner(root: &Path, ticket: &Ticket) -> anyhow::Result<()> {
504 let cfg = crate::config::Config::load(root)?;
505 let is_terminal = cfg.workflow.states.iter()
506 .find(|s| s.id == ticket.frontmatter.state)
507 .map(|s| s.terminal)
508 .unwrap_or(false);
509 if is_terminal {
510 anyhow::bail!("cannot change owner of a closed ticket");
511 }
512 let Some(o) = &ticket.frontmatter.owner else {
513 return Ok(());
514 };
515 let identity = crate::config::resolve_identity(root);
516 if identity == "unassigned" {
517 anyhow::bail!(
518 "cannot reassign: identity not configured (set local.user in .apm/local.toml or configure a GitHub token)"
519 );
520 }
521 if &identity != o {
522 anyhow::bail!("only the current owner ({o}) can reassign this ticket");
523 }
524 Ok(())
525}
526
527pub fn set_field(fm: &mut Frontmatter, field: &str, value: &str) -> anyhow::Result<()> {
528 match field {
529 "priority" => fm.priority = value.parse().map_err(|_| anyhow::anyhow!("priority must be 0–255"))?,
530 "effort" => fm.effort = value.parse().map_err(|_| anyhow::anyhow!("effort must be 0–255"))?,
531 "risk" => fm.risk = value.parse().map_err(|_| anyhow::anyhow!("risk must be 0–255"))?,
532 "author" => anyhow::bail!("author is immutable"),
533 "owner" => fm.owner = if value == "-" { None } else { Some(value.to_string()) },
534 "agent" => fm.agent = if value == "-" { None } else { Some(value.to_string()) },
535 "branch" => fm.branch = if value == "-" { None } else { Some(value.to_string()) },
536 "title" => fm.title = value.to_string(),
537 "depends_on" => {
538 if value == "-" {
539 fm.depends_on = None;
540 } else {
541 let ids: Vec<String> = value
542 .split(',')
543 .map(|s| s.trim().to_string())
544 .filter(|s| !s.is_empty())
545 .collect();
546 fm.depends_on = if ids.is_empty() { None } else { Some(ids) };
547 }
548 }
549 other => anyhow::bail!("unknown field: {other}"),
550 }
551 Ok(())
552}
553
554#[derive(serde::Serialize, Clone, Debug)]
555pub struct BlockingDep {
556 pub id: String,
557 pub state: String,
558}
559
560pub fn compute_blocking_deps(
561 ticket: &Ticket,
562 all_tickets: &[Ticket],
563 config: &crate::config::Config,
564) -> Vec<BlockingDep> {
565 let deps = match &ticket.frontmatter.depends_on {
566 Some(d) if !d.is_empty() => d,
567 _ => return vec![],
568 };
569 let state_map: std::collections::HashMap<&str, &str> = all_tickets
570 .iter()
571 .map(|t| (t.frontmatter.id.as_str(), t.frontmatter.state.as_str()))
572 .collect();
573 deps.iter()
574 .filter_map(|dep_id| {
575 state_map.get(dep_id.as_str()).and_then(|&s| {
576 if dep_satisfied(s, None, config) {
577 None
578 } else {
579 Some(BlockingDep { id: dep_id.clone(), state: s.to_string() })
580 }
581 })
582 })
583 .collect()
584}
585
586pub fn move_to_epic(
594 root: &Path,
595 config: &crate::config::Config,
596 ticket_id_arg: &str,
597 target: Option<&str>,
598) -> Result<String> {
599 let tickets = load_all_from_git(root, &config.tickets.dir)?;
601 let id = super::ticket_fmt::resolve_id_in_slice(&tickets, ticket_id_arg)?;
602 let ticket = tickets.iter().find(|t| t.frontmatter.id == id).unwrap();
603
604 let terminal = config.terminal_state_ids();
606 if terminal.contains(&ticket.frontmatter.state) {
607 bail!(
608 "cannot move ticket {}: it is in a terminal state ({})",
609 id,
610 ticket.frontmatter.state
611 );
612 }
613
614 let ticket_branch = ticket
616 .frontmatter
617 .branch
618 .clone()
619 .or_else(|| super::ticket_fmt::branch_name_from_path(&ticket.path))
620 .unwrap_or_else(|| format!("ticket/{id}"));
621
622 let old_base_ref = ticket
624 .frontmatter
625 .target_branch
626 .as_deref()
627 .unwrap_or("main")
628 .to_string();
629
630 let target_is_clear = target.is_none() || target == Some("-");
632
633 let (new_base_ref, new_epic, new_target_branch) = if target_is_clear {
634 if ticket.frontmatter.epic.is_none() {
635 return Ok(format!("ticket {id} is not in any epic; nothing to do"));
636 }
637 ("main".to_string(), None::<String>, None::<String>)
638 } else {
639 let epic_id_arg = target.unwrap();
640 let matches = crate::epic::find_epic_branches(root, epic_id_arg);
641 let epic_branch = match matches.len() {
642 0 => bail!("no epic found matching '{epic_id_arg}'"),
643 1 => matches.into_iter().next().unwrap(),
644 _ => bail!(
645 "ambiguous epic prefix '{}': matches {}",
646 epic_id_arg,
647 matches.join(", ")
648 ),
649 };
650 let epic_id = crate::epic::epic_id_from_branch(&epic_branch).to_string();
651
652 if ticket.frontmatter.epic.as_deref() == Some(&epic_id) {
653 return Ok(format!(
654 "ticket {id} is already in epic {epic_id}; nothing to do"
655 ));
656 }
657
658 (epic_branch.clone(), Some(epic_id), Some(epic_branch))
659 };
660
661 if crate::worktree::find_worktree_for_branch(root, &ticket_branch).is_some() {
663 bail!(
664 "branch {} is checked out in a worktree; close the worktree first",
665 ticket_branch
666 );
667 }
668
669 let old_base_sha = crate::git_util::resolve_branch_sha(root, &old_base_ref)
671 .with_context(|| format!("cannot resolve old base '{old_base_ref}'"))?;
672 let old_upstream_sha =
673 crate::git_util::merge_base(root, &ticket_branch, &old_base_sha)
674 .with_context(|| {
675 format!(
676 "cannot find merge-base of {ticket_branch} and {old_base_ref}"
677 )
678 })?;
679
680 let new_base_sha = crate::git_util::resolve_branch_sha(root, &new_base_ref)
682 .with_context(|| format!("cannot resolve new base '{new_base_ref}'"))?;
683
684 let rebase_result = crate::git_util::run(
686 root,
687 &[
688 "rebase",
689 "--onto",
690 &new_base_sha,
691 &old_upstream_sha,
692 &ticket_branch,
693 ],
694 );
695
696 if let Err(e) = rebase_result {
697 let _ = crate::git_util::run(root, &["rebase", "--abort"]);
698 let err_str = e.to_string();
699 if err_str.contains("checked out") || err_str.contains("worktree") {
700 bail!(
701 "branch {} is checked out in a worktree; close the worktree first",
702 ticket_branch
703 );
704 }
705 bail!(
706 "rebase onto {new_base_ref} failed (conflicts or other error); \
707 resolve manually or create a new ticket with `apm new --epic`\n{e:#}"
708 );
709 }
710
711 let rel_path = format!(
713 "{}/{}",
714 config.tickets.dir.to_string_lossy(),
715 ticket.path.file_name().unwrap().to_string_lossy()
716 );
717
718 let updated_content =
719 crate::git_util::read_from_branch(root, &ticket_branch, &rel_path)
720 .with_context(|| {
721 format!("cannot read ticket file from {ticket_branch} after rebase")
722 })?;
723 let mut updated_ticket = Ticket::parse(&ticket.path, &updated_content)?;
724
725 let now = chrono::Utc::now();
726 updated_ticket.frontmatter.epic = new_epic.clone();
727 updated_ticket.frontmatter.target_branch = new_target_branch;
728 updated_ticket.frontmatter.updated_at = Some(now);
729
730 let when = now.format("%Y-%m-%dT%H:%MZ").to_string();
731 let history_note = format!("move: {old_base_ref} \u{2192} {new_base_ref}");
732 crate::state::append_history(
733 &mut updated_ticket.body,
734 "\u{2014}",
735 "\u{2014}",
736 &when,
737 &history_note,
738 );
739
740 let content = updated_ticket.serialize()?;
741 crate::git_util::commit_to_branch(
742 root,
743 &ticket_branch,
744 &rel_path,
745 &content,
746 &format!("ticket({id}): move to {new_base_ref}"),
747 )?;
748
749 let msg = if target_is_clear {
750 format!("{id}: moved out of epic, rebased onto main")
751 } else {
752 format!(
753 "{id}: moved into epic {}",
754 new_epic.as_deref().unwrap_or("")
755 )
756 };
757
758 Ok(msg)
759}
760
761#[cfg(test)]
762mod tests {
763 use super::*;
764 use std::path::Path;
765
766 fn dummy_path() -> &'static Path {
767 Path::new("test.md")
768 }
769
770 fn full_body(ac: &str) -> String {
771 format!(
772 "## Spec\n\n### Problem\n\nSome problem.\n\n### Acceptance criteria\n\n{ac}\n\n### Out of scope\n\nNothing.\n\n### Approach\n\nDo it.\n\n## History\n\n| When | From | To | By |\n|------|------|----|----|"
773 )
774 }
775
776 fn make_simple_ticket(id: &str, state: &str, depends_on: Option<Vec<&str>>) -> Ticket {
779 let deps_line = match &depends_on {
780 None => String::new(),
781 Some(ids) => {
782 let items: Vec<String> = ids.iter().map(|i| format!("\"{}\"", i)).collect();
783 format!("depends_on = [{}]\n", items.join(", "))
784 }
785 };
786 let raw = format!(
787 "+++\nid = \"{id}\"\ntitle = \"T\"\nstate = \"{state}\"\n{deps_line}+++\n\nbody\n"
788 );
789 Ticket::parse(Path::new("test.md"), &raw).unwrap()
790 }
791
792 #[test]
793 fn compute_blocking_deps_no_depends_on_returns_empty() {
794 let config = test_config_with_states(&["closed"]);
795 let ticket = make_simple_ticket("aaaa0001", "new", None);
796 let all = vec![ticket.clone()];
797 let result = compute_blocking_deps(&ticket, &all, &config);
798 assert!(result.is_empty());
799 }
800
801 #[test]
802 fn compute_blocking_deps_dep_in_non_terminal_state_returns_it() {
803 let config = test_config_with_states(&["closed"]);
804 let dep = make_simple_ticket("bbbb0001", "new", None);
805 let ticket = make_simple_ticket("aaaa0001", "new", Some(vec!["bbbb0001"]));
806 let all = vec![dep.clone(), ticket.clone()];
807 let result = compute_blocking_deps(&ticket, &all, &config);
808 assert_eq!(result.len(), 1);
809 assert_eq!(result[0].id, "bbbb0001");
810 assert_eq!(result[0].state, "new");
811 }
812
813 #[test]
814 fn compute_blocking_deps_all_deps_satisfied_returns_empty() {
815 let config = test_config_with_states(&["closed"]);
816 let dep = make_simple_ticket("bbbb0001", "closed", None);
817 let ticket = make_simple_ticket("aaaa0001", "new", Some(vec!["bbbb0001"]));
818 let all = vec![dep.clone(), ticket.clone()];
819 let result = compute_blocking_deps(&ticket, &all, &config);
820 assert!(result.is_empty());
821 }
822
823 #[test]
824 fn document_toggle_criterion() {
825 let body = full_body("- [ ] item one\n- [ ] item two");
826 let mut doc = TicketDocument::parse(&body).unwrap();
827 let ac = doc.sections.get("Acceptance criteria").unwrap();
828 assert!(ac.contains("- [ ] item one"));
829 doc.toggle_criterion(0, true).unwrap();
830 let ac = doc.sections.get("Acceptance criteria").unwrap();
831 assert!(ac.contains("- [x] item one"));
832 }
833
834 #[test]
835 fn document_unchecked_tasks() {
836 let body = full_body("- [ ] one\n- [x] two\n- [ ] three");
837 let doc = TicketDocument::parse(&body).unwrap();
838 assert_eq!(doc.unchecked_tasks("Acceptance criteria"), vec![0, 2]);
839 }
840
841 fn test_config_with_states(terminal_states: &[&str]) -> crate::config::Config {
844 let mut states_toml = String::new();
845 for s in ["new", "ready", "in_progress"] {
846 states_toml.push_str(&format!(
847 "[[workflow.states]]\nid = \"{s}\"\nlabel = \"{s}\"\nterminal = false\n\n"
848 ));
849 }
850 for s in terminal_states {
851 states_toml.push_str(&format!(
852 "[[workflow.states]]\nid = \"{s}\"\nlabel = \"{s}\"\nterminal = true\n\n"
853 ));
854 }
855 let full = format!(
856 "[project]\nname = \"test\"\n\n[tickets]\ndir = \"tickets\"\n\n{states_toml}"
857 );
858 toml::from_str(&full).unwrap()
859 }
860
861 fn make_ticket(id: &str, state: &str, agent: Option<&str>) -> Ticket {
862 let agent_line = agent.map(|a| format!("agent = \"{a}\"\n")).unwrap_or_default();
863 let raw = format!(
864 "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{agent_line}+++\n\n"
865 );
866 Ticket::parse(dummy_path(), &raw).unwrap()
867 }
868
869 #[test]
870 fn list_filtered_by_state() {
871 let config = test_config_with_states(&["closed"]);
872 let tickets = vec![
873 make_ticket("0001", "new", None),
874 make_ticket("0002", "ready", None),
875 make_ticket("0003", "new", None),
876 ];
877 let result = list_filtered(&tickets, &config, Some("new"), false, false, None, None, None, None);
878 assert_eq!(result.len(), 2);
879 assert!(result.iter().all(|t| t.frontmatter.state == "new"));
880 }
881
882 #[test]
883 fn list_filtered_terminal_hidden_by_default() {
884 let config = test_config_with_states(&["closed"]);
885 let tickets = vec![
886 make_ticket("0001", "new", None),
887 make_ticket("0002", "closed", None),
888 ];
889 let result = list_filtered(&tickets, &config, None, false, false, None, None, None, None);
891 assert_eq!(result.len(), 1);
892 assert_eq!(result[0].frontmatter.state, "new");
893
894 let result_all = list_filtered(&tickets, &config, None, false, true, None, None, None, None);
896 assert_eq!(result_all.len(), 2);
897
898 let result_filtered = list_filtered(&tickets, &config, Some("closed"), false, false, None, None, None, None);
900 assert_eq!(result_filtered.len(), 1);
901 assert_eq!(result_filtered[0].frontmatter.state, "closed");
902 }
903
904 #[test]
905 fn list_filtered_unassigned() {
906 let config = test_config_with_states(&[]);
907 let make_with_author = |id: &str, author: Option<&str>| {
908 let author_line = author.map(|a| format!("author = \"{a}\"\n")).unwrap_or_default();
909 let raw = format!(
910 "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"new\"\n{author_line}+++\n\n"
911 );
912 Ticket::parse(Path::new("test.md"), &raw).unwrap()
913 };
914 let tickets = vec![
915 make_with_author("0001", Some("unassigned")),
916 make_with_author("0002", Some("alice")),
917 make_with_author("0003", Some("unassigned")),
918 make_with_author("0004", None),
919 ];
920 let result = list_filtered(&tickets, &config, None, true, false, None, None, None, None);
921 assert_eq!(result.len(), 2);
922 assert!(result.iter().all(|t| t.frontmatter.author.as_deref() == Some("unassigned")));
923 }
924
925 fn make_ticket_with_author(id: &str, state: &str, author: Option<&str>) -> Ticket {
926 let author_line = author.map(|a| format!("author = \"{a}\"\n")).unwrap_or_default();
927 let raw = format!(
928 "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{author_line}+++\n\n"
929 );
930 Ticket::parse(dummy_path(), &raw).unwrap()
931 }
932
933 #[test]
934 fn list_filtered_by_author() {
935 let config = test_config_with_states(&[]);
936 let tickets = vec![
937 make_ticket_with_author("0001", "new", Some("alice")),
938 make_ticket_with_author("0002", "new", Some("bob")),
939 make_ticket_with_author("0003", "ready", Some("alice")),
940 ];
941 let result = list_filtered(&tickets, &config, None, false, false, None, Some("alice"), None, None);
942 assert_eq!(result.len(), 2);
943 assert!(result.iter().all(|t| t.frontmatter.author.as_deref() == Some("alice")));
944 }
945
946 #[test]
947 fn list_filtered_author_none() {
948 let config = test_config_with_states(&[]);
949 let tickets = vec![
950 make_ticket_with_author("0001", "new", Some("alice")),
951 make_ticket_with_author("0002", "new", Some("bob")),
952 ];
953 let result = list_filtered(&tickets, &config, None, false, false, None, None, None, None);
954 assert_eq!(result.len(), 2);
955 }
956
957 fn make_ticket_with_owner(id: &str, state: &str, author: Option<&str>, owner: Option<&str>) -> Ticket {
958 let author_line = author.map(|a| format!("author = \"{a}\"\n")).unwrap_or_default();
959 let owner_line = owner.map(|o| format!("owner = \"{o}\"\n")).unwrap_or_default();
960 let raw = format!(
961 "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{author_line}{owner_line}+++\n\n"
962 );
963 Ticket::parse(dummy_path(), &raw).unwrap()
964 }
965
966 #[test]
967 fn list_filtered_by_owner() {
968 let config = test_config_with_states(&[]);
969 let tickets = vec![
970 make_ticket_with_owner("0001", "new", Some("alice"), Some("alice")),
971 make_ticket_with_owner("0002", "new", Some("bob"), Some("bob")),
972 make_ticket_with_owner("0003", "new", Some("carol"), None),
973 ];
974 let result = list_filtered(&tickets, &config, None, false, false, None, None, Some("alice"), None);
975 assert_eq!(result.len(), 1);
976 assert_eq!(result[0].frontmatter.id, "0001");
977 }
978
979 #[test]
980 fn list_filtered_mine_matches_author() {
981 let config = test_config_with_states(&[]);
982 let tickets = vec![
983 make_ticket_with_owner("0001", "new", Some("alice"), Some("bob")),
984 make_ticket_with_owner("0002", "new", Some("bob"), Some("carol")),
985 ];
986 let result = list_filtered(&tickets, &config, None, false, false, None, None, None, Some("alice"));
987 assert_eq!(result.len(), 1);
988 assert_eq!(result[0].frontmatter.id, "0001");
989 }
990
991 #[test]
992 fn list_filtered_mine_matches_owner() {
993 let config = test_config_with_states(&[]);
994 let tickets = vec![
995 make_ticket_with_owner("0001", "new", Some("bob"), Some("alice")),
996 make_ticket_with_owner("0002", "new", Some("carol"), Some("bob")),
997 ];
998 let result = list_filtered(&tickets, &config, None, false, false, None, None, None, Some("alice"));
999 assert_eq!(result.len(), 1);
1000 assert_eq!(result[0].frontmatter.id, "0001");
1001 }
1002
1003 #[test]
1004 fn list_filtered_mine_or_semantics() {
1005 let config = test_config_with_states(&[]);
1006 let tickets = vec![
1007 make_ticket_with_owner("0001", "new", Some("alice"), None),
1008 make_ticket_with_owner("0002", "new", Some("bob"), Some("alice")),
1009 make_ticket_with_owner("0003", "new", Some("carol"), Some("carol")),
1010 ];
1011 let result = list_filtered(&tickets, &config, None, false, false, None, None, None, Some("alice"));
1012 assert_eq!(result.len(), 2);
1013 let ids: Vec<&str> = result.iter().map(|t| t.frontmatter.id.as_str()).collect();
1014 assert!(ids.contains(&"0001"));
1015 assert!(ids.contains(&"0002"));
1016 }
1017
1018 fn make_frontmatter() -> Frontmatter {
1021 Frontmatter {
1022 id: "0001".to_string(),
1023 title: "Test".to_string(),
1024 state: "new".to_string(),
1025 priority: 0,
1026 effort: 0,
1027 risk: 0,
1028 author: None,
1029 owner: None,
1030 branch: None,
1031 created_at: None,
1032 updated_at: None,
1033 focus_section: None,
1034 epic: None,
1035 target_branch: None,
1036 depends_on: None,
1037 agent: None,
1038 agent_overrides: std::collections::HashMap::new(),
1039 }
1040 }
1041
1042 #[test]
1043 fn set_field_priority_valid() {
1044 let mut fm = make_frontmatter();
1045 set_field(&mut fm, "priority", "5").unwrap();
1046 assert_eq!(fm.priority, 5);
1047 }
1048
1049 #[test]
1050 fn set_field_priority_overflow() {
1051 let mut fm = make_frontmatter();
1052 let err = set_field(&mut fm, "priority", "256").unwrap_err();
1053 assert!(err.to_string().contains("priority must be 0"));
1054 }
1055
1056 #[test]
1057 fn set_field_author_immutable() {
1058 let mut fm = make_frontmatter();
1059 let err = set_field(&mut fm, "author", "alice").unwrap_err();
1060 assert!(err.to_string().contains("author is immutable"));
1061 }
1062
1063 #[test]
1064 fn set_field_unknown_field() {
1065 let mut fm = make_frontmatter();
1066 let err = set_field(&mut fm, "foo", "bar").unwrap_err();
1067 assert!(err.to_string().contains("unknown field: foo"));
1068 }
1069
1070 #[test]
1071 fn owner_round_trips_through_toml() {
1072 let toml_src = r#"id = "0001"
1073title = "T"
1074state = "new"
1075owner = "alice"
1076"#;
1077 let fm: Frontmatter = toml::from_str(toml_src).unwrap();
1078 assert_eq!(fm.owner, Some("alice".to_string()));
1079 let serialized = toml::to_string(&fm).unwrap();
1080 assert!(serialized.contains("owner = \"alice\""));
1081 }
1082
1083 #[test]
1084 fn owner_absent_deserializes_as_none() {
1085 let toml_src = r#"id = "0001"
1086title = "T"
1087state = "new"
1088"#;
1089 let fm: Frontmatter = toml::from_str(toml_src).unwrap();
1090 assert_eq!(fm.owner, None);
1091 }
1092
1093 #[test]
1094 fn set_field_owner_set() {
1095 let mut fm = make_frontmatter();
1096 set_field(&mut fm, "owner", "alice").unwrap();
1097 assert_eq!(fm.owner, Some("alice".to_string()));
1098 }
1099
1100 #[test]
1101 fn set_field_owner_clear() {
1102 let mut fm = make_frontmatter();
1103 fm.owner = Some("alice".to_string());
1104 set_field(&mut fm, "owner", "-").unwrap();
1105 assert_eq!(fm.owner, None);
1106 }
1107
1108 #[test]
1109 fn set_field_agent_set() {
1110 let mut fm = make_frontmatter();
1111 set_field(&mut fm, "agent", "pi").unwrap();
1112 assert_eq!(fm.agent, Some("pi".to_string()));
1113 }
1114
1115 #[test]
1116 fn set_field_agent_clear() {
1117 let mut fm = make_frontmatter();
1118 fm.agent = Some("pi".to_string());
1119 set_field(&mut fm, "agent", "-").unwrap();
1120 assert_eq!(fm.agent, None);
1121 }
1122
1123 fn config_with_dep_states() -> crate::config::Config {
1126 let toml = r#"
1127[project]
1128name = "test"
1129
1130[tickets]
1131dir = "tickets"
1132
1133[[workflow.states]]
1134id = "ready"
1135label = "Ready"
1136
1137[[workflow.states]]
1138id = "done"
1139label = "Done"
1140satisfies_deps = true
1141
1142[[workflow.states]]
1143id = "closed"
1144label = "Closed"
1145terminal = true
1146
1147[[workflow.states]]
1148id = "blocked"
1149label = "Blocked"
1150"#;
1151 toml::from_str(toml).unwrap()
1152 }
1153
1154 #[test]
1155 fn dep_satisfied_satisfies_deps_true() {
1156 let config = config_with_dep_states();
1157 assert!(dep_satisfied("done", None, &config));
1158 }
1159
1160 #[test]
1161 fn dep_satisfied_terminal_true() {
1162 let config = config_with_dep_states();
1163 assert!(dep_satisfied("closed", None, &config));
1164 }
1165
1166 #[test]
1167 fn dep_satisfied_both_false() {
1168 let config = config_with_dep_states();
1169 assert!(!dep_satisfied("blocked", None, &config));
1170 }
1171
1172 #[test]
1173 fn dep_satisfied_unknown_state() {
1174 let config = config_with_dep_states();
1175 assert!(!dep_satisfied("nonexistent", None, &config));
1176 }
1177
1178 fn config_with_spec_gate() -> crate::config::Config {
1179 let toml = r#"
1180[project]
1181name = "test"
1182
1183[tickets]
1184dir = "tickets"
1185
1186[[workflow.states]]
1187id = "groomed"
1188label = "Groomed"
1189dep_requires = "spec"
1190
1191[[workflow.states]]
1192id = "ready"
1193label = "Ready"
1194
1195[[workflow.states]]
1196id = "specd"
1197label = "Specd"
1198satisfies_deps = "spec"
1199
1200[[workflow.states]]
1201id = "in_progress"
1202label = "In Progress"
1203satisfies_deps = "spec"
1204
1205[[workflow.states]]
1206id = "implemented"
1207label = "Implemented"
1208satisfies_deps = true
1209
1210[[workflow.states]]
1211id = "closed"
1212label = "Closed"
1213terminal = true
1214"#;
1215 toml::from_str(toml).unwrap()
1216 }
1217
1218 #[test]
1219 fn dep_satisfied_tag_matches_required_gate() {
1220 let config = config_with_spec_gate();
1221 assert!(dep_satisfied("specd", Some("spec"), &config));
1222 }
1223
1224 #[test]
1225 fn dep_satisfied_tag_no_required_gate_is_false() {
1226 let config = config_with_spec_gate();
1227 assert!(!dep_satisfied("specd", None, &config));
1228 }
1229
1230 #[test]
1231 fn dep_satisfied_bool_true_with_no_gate() {
1232 let config = config_with_spec_gate();
1233 assert!(dep_satisfied("implemented", None, &config));
1234 }
1235
1236 #[test]
1237 fn pick_next_groomed_unblocked_when_dep_specd() {
1238 let config = config_with_spec_gate();
1239 let tickets = vec![
1240 make_ticket_with_deps("aaaa0001", "groomed", Some(vec!["bbbb0001"])),
1241 make_ticket_with_deps("bbbb0001", "specd", None),
1242 ];
1243 let result = pick_next(&tickets, &["groomed"], &[], 10.0, -2.0, -1.0, &config, None, None);
1244 assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1245 }
1246
1247 #[test]
1248 fn pick_next_groomed_unblocked_when_dep_in_progress() {
1249 let config = config_with_spec_gate();
1250 let tickets = vec![
1251 make_ticket_with_deps("aaaa0001", "groomed", Some(vec!["bbbb0001"])),
1252 make_ticket_with_deps("bbbb0001", "in_progress", None),
1253 ];
1254 let result = pick_next(&tickets, &["groomed"], &[], 10.0, -2.0, -1.0, &config, None, None);
1255 assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1256 }
1257
1258 #[test]
1259 fn pick_next_ready_blocked_when_dep_only_specd() {
1260 let config = config_with_spec_gate();
1261 let tickets = vec![
1262 make_ticket_with_deps("aaaa0001", "ready", Some(vec!["bbbb0001"])),
1263 make_ticket_with_deps("bbbb0001", "specd", None),
1264 ];
1265 let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1266 assert!(result.is_none());
1267 }
1268
1269 fn make_ticket_with_deps(id: &str, state: &str, deps: Option<Vec<&str>>) -> Ticket {
1272 let deps_line = match &deps {
1273 None => String::new(),
1274 Some(v) => {
1275 let list: Vec<String> = v.iter().map(|d| format!("\"{d}\"")).collect();
1276 format!("depends_on = [{}]\n", list.join(", "))
1277 }
1278 };
1279 let raw = format!(
1280 "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{deps_line}+++\n\n"
1281 );
1282 Ticket::parse(dummy_path(), &raw).unwrap()
1283 }
1284
1285 #[test]
1286 fn pick_next_skips_dep_blocked_ticket() {
1287 let config = config_with_dep_states();
1288 let tickets = vec![
1289 make_ticket_with_deps("aaaa0001", "ready", Some(vec!["bbbb0001"])),
1290 make_ticket_with_deps("bbbb0001", "ready", None),
1291 make_ticket_with_deps("cccc0001", "ready", None),
1292 ];
1293 let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1296 assert!(result.is_some());
1297 let id = &result.unwrap().frontmatter.id;
1298 assert_ne!(id, "aaaa0001", "dep-blocked ticket should be skipped");
1299 }
1300
1301 #[test]
1302 fn pick_next_returns_ticket_when_dep_satisfied() {
1303 let config = config_with_dep_states();
1304 let tickets = vec![
1305 make_ticket_with_deps("aaaa0001", "ready", Some(vec!["bbbb0001"])),
1306 make_ticket_with_deps("bbbb0001", "done", None),
1307 ];
1308 let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1309 assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1310 }
1311
1312 #[test]
1313 fn pick_next_unknown_dep_id_not_blocking() {
1314 let config = config_with_dep_states();
1315 let tickets = vec![
1316 make_ticket_with_deps("aaaa0001", "ready", Some(vec!["unknown1"])),
1317 ];
1318 let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1319 assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1320 }
1321
1322 #[test]
1323 fn pick_next_empty_depends_on_not_blocking() {
1324 let config = config_with_dep_states();
1325 let raw = "+++\nid = \"aaaa0001\"\ntitle = \"T\"\nstate = \"ready\"\ndepends_on = []\n+++\n\n";
1326 let t = Ticket::parse(dummy_path(), raw).unwrap();
1327 let tickets = vec![t];
1328 let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1329 assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1330 }
1331
1332 fn make_ticket_with_priority(id: &str, state: &str, priority: u8, deps: Option<Vec<&str>>) -> Ticket {
1335 let dep_line = match &deps {
1336 Some(d) => {
1337 let list: Vec<String> = d.iter().map(|s| format!("\"{s}\"")).collect();
1338 format!("depends_on = [{}]\n", list.join(", "))
1339 }
1340 None => String::new(),
1341 };
1342 let raw = format!(
1343 "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\npriority = {priority}\n{dep_line}+++\n\n"
1344 );
1345 Ticket::parse(Path::new("test.md"), &raw).unwrap()
1346 }
1347
1348 #[test]
1349 fn effective_priority_no_dependents_returns_own() {
1350 let a = make_ticket_with_priority("aaaa", "ready", 5, None);
1351 let tickets = vec![&a];
1352 let rev_idx = build_reverse_index(&tickets);
1353 assert_eq!(effective_priority(&a, &rev_idx), 5);
1354 }
1355
1356 #[test]
1357 fn effective_priority_single_hop_elevation() {
1358 let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1360 let b = make_ticket_with_priority("bbbb", "ready", 9, Some(vec!["aaaa"]));
1361 let tickets = vec![&a, &b];
1362 let rev_idx = build_reverse_index(&tickets);
1363 assert_eq!(effective_priority(&a, &rev_idx), 9);
1364 assert_eq!(effective_priority(&b, &rev_idx), 9);
1365 }
1366
1367 #[test]
1368 fn effective_priority_transitive_elevation() {
1369 let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1371 let b = make_ticket_with_priority("bbbb", "ready", 5, Some(vec!["aaaa"]));
1372 let c = make_ticket_with_priority("cccc", "ready", 9, Some(vec!["bbbb"]));
1373 let tickets = vec![&a, &b, &c];
1374 let rev_idx = build_reverse_index(&tickets);
1375 assert_eq!(effective_priority(&a, &rev_idx), 9);
1376 assert_eq!(effective_priority(&b, &rev_idx), 9);
1377 assert_eq!(effective_priority(&c, &rev_idx), 9);
1378 }
1379
1380 #[test]
1381 fn effective_priority_cycle_does_not_panic() {
1382 let a = make_ticket_with_priority("aaaa", "ready", 3, Some(vec!["bbbb"]));
1384 let b = make_ticket_with_priority("bbbb", "ready", 7, Some(vec!["aaaa"]));
1385 let tickets = vec![&a, &b];
1386 let rev_idx = build_reverse_index(&tickets);
1387 let ep_a = effective_priority(&a, &rev_idx);
1389 let ep_b = effective_priority(&b, &rev_idx);
1390 assert_eq!(ep_a, 7);
1391 assert_eq!(ep_b, 7);
1392 }
1393
1394 #[test]
1395 fn effective_priority_closed_dependent_excluded() {
1396 let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1398 let tickets_active = vec![&a];
1400 let rev_idx = build_reverse_index(&tickets_active);
1401 assert_eq!(effective_priority(&a, &rev_idx), 2);
1402 }
1403
1404 #[test]
1405 fn sorted_actionable_low_priority_blocker_elevated() {
1406 let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1409 let b = make_ticket_with_priority("bbbb", "ready", 9, Some(vec!["aaaa"]));
1410 let tickets = vec![a, b];
1411 let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, None);
1412 assert_eq!(result.len(), 2);
1413 let ids: Vec<&str> = result.iter().map(|t| t.frontmatter.id.as_str()).collect();
1414 assert!(ids.contains(&"aaaa"), "A must appear in results");
1415 assert!(ids.contains(&"bbbb"), "B must appear in results");
1416 }
1420
1421 #[test]
1422 fn sorted_actionable_blocker_before_independent_higher_raw() {
1423 let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1427 let b = make_ticket_with_priority("bbbb", "ready", 7, None);
1428 let c = make_ticket_with_priority("cccc", "ready", 9, Some(vec!["aaaa"]));
1429 let tickets = vec![a, b, c];
1430 let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, None);
1431 assert_eq!(result.len(), 3);
1432 let ids: Vec<&str> = result.iter().map(|t| t.frontmatter.id.as_str()).collect();
1433 let a_pos = ids.iter().position(|&id| id == "aaaa").unwrap();
1434 let b_pos = ids.iter().position(|&id| id == "bbbb").unwrap();
1435 assert!(a_pos < b_pos, "A (ep=9) should sort before B (ep=7)");
1436 }
1437
1438 #[test]
1439 fn sorted_actionable_no_deps_unchanged() {
1440 let a = make_ticket_with_priority("aaaa", "ready", 3, None);
1441 let b = make_ticket_with_priority("bbbb", "ready", 7, None);
1442 let tickets = vec![a, b];
1443 let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, None);
1444 assert_eq!(result[0].frontmatter.id, "bbbb");
1445 assert_eq!(result[1].frontmatter.id, "aaaa");
1446 }
1447
1448 fn make_ticket_with_owner_field(id: &str, state: &str, owner: Option<&str>) -> Ticket {
1449 let owner_line = owner.map(|o| format!("owner = \"{o}\"\n")).unwrap_or_default();
1450 let raw = format!(
1451 "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{owner_line}+++\n\n"
1452 );
1453 Ticket::parse(Path::new("test.md"), &raw).unwrap()
1454 }
1455
1456 #[test]
1457 fn sorted_actionable_excludes_ticket_owned_by_other() {
1458 let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1459 let tickets = vec![t];
1460 let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, Some("bob"));
1461 assert!(result.is_empty(), "ticket owned by alice should not appear for bob");
1462 }
1463
1464 #[test]
1465 fn sorted_actionable_includes_ticket_owned_by_caller() {
1466 let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1467 let tickets = vec![t];
1468 let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, Some("alice"));
1469 assert_eq!(result.len(), 1);
1470 assert_eq!(result[0].frontmatter.id, "aaaa");
1471 }
1472
1473 #[test]
1474 fn sorted_actionable_includes_unowned_ticket() {
1475 let t = make_ticket_with_owner_field("aaaa", "ready", None);
1476 let tickets = vec![t];
1477 let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, Some("bob"));
1478 assert!(result.is_empty(), "unowned ticket should be excluded when owner_filter is set");
1479 }
1480
1481 #[test]
1482 fn sorted_actionable_no_owner_filter_shows_all() {
1483 let t1 = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1484 let t2 = make_ticket_with_owner_field("bbbb", "ready", Some("bob"));
1485 let tickets = vec![t1, t2];
1486 let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, None);
1487 assert_eq!(result.len(), 2);
1488 }
1489
1490 #[test]
1491 fn pick_next_skips_unowned_ticket_when_owner_filter_set() {
1492 let config = config_with_dep_states();
1493 let t = make_ticket_with_owner_field("aaaa", "ready", None);
1494 let tickets = vec![t];
1495 let result = pick_next(&tickets, &["ready"], &[], 1.0, 0.0, 0.0, &config, None, Some("alice"));
1496 assert!(result.is_none(), "unowned ticket should be skipped when owner_filter is set");
1497 }
1498
1499 #[test]
1500 fn pick_next_skips_ticket_owned_by_other() {
1501 let config = config_with_dep_states();
1502 let t = make_ticket_with_owner_field("aaaa", "ready", Some("bob"));
1503 let tickets = vec![t];
1504 let result = pick_next(&tickets, &["ready"], &[], 1.0, 0.0, 0.0, &config, None, Some("alice"));
1505 assert!(result.is_none(), "ticket owned by bob should be skipped for alice");
1506 }
1507
1508 #[test]
1509 fn pick_next_picks_ticket_owned_by_current_user() {
1510 let config = config_with_dep_states();
1511 let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1512 let tickets = vec![t];
1513 let result = pick_next(&tickets, &["ready"], &[], 1.0, 0.0, 0.0, &config, None, Some("alice"));
1514 assert!(result.is_some(), "ticket owned by alice should be picked");
1515 assert_eq!(result.unwrap().frontmatter.id, "aaaa");
1516 }
1517
1518 #[test]
1519 fn check_owner_passes_when_identity_matches_owner() {
1520 let tmp = tempfile::tempdir().unwrap();
1521 let apm_dir = tmp.path().join(".apm");
1522 std::fs::create_dir_all(&apm_dir).unwrap();
1523 std::fs::write(apm_dir.join("config.toml"), "[project]\nname = \"test\"\n").unwrap();
1524 std::fs::write(apm_dir.join("local.toml"), "username = \"alice\"\n").unwrap();
1525 let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1526 assert!(check_owner(tmp.path(), &t).is_ok());
1527 }
1528
1529 #[test]
1530 fn check_owner_fails_when_identity_does_not_match_owner() {
1531 let tmp = tempfile::tempdir().unwrap();
1532 let apm_dir = tmp.path().join(".apm");
1533 std::fs::create_dir_all(&apm_dir).unwrap();
1534 std::fs::write(apm_dir.join("config.toml"), "[project]\nname = \"test\"\n").unwrap();
1535 std::fs::write(apm_dir.join("local.toml"), "username = \"bob\"\n").unwrap();
1536 let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1537 let err = check_owner(tmp.path(), &t).unwrap_err();
1538 assert!(err.to_string().contains("alice"), "error should mention the owner");
1539 }
1540
1541 #[test]
1542 fn check_owner_fails_when_identity_is_unassigned() {
1543 let tmp = tempfile::tempdir().unwrap();
1544 std::fs::create_dir_all(tmp.path().join(".apm")).unwrap();
1545 std::fs::write(tmp.path().join(".apm/config.toml"), "[project]\nname = \"test\"\n").unwrap();
1546 let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1547 let err = check_owner(tmp.path(), &t).unwrap_err();
1548 assert!(err.to_string().contains("identity not configured"));
1549 }
1550
1551 #[test]
1552 fn check_owner_passes_when_ticket_has_no_owner() {
1553 let tmp = tempfile::tempdir().unwrap();
1554 std::fs::create_dir_all(tmp.path().join(".apm")).unwrap();
1555 std::fs::write(tmp.path().join(".apm/config.toml"), "[project]\nname = \"test\"\n").unwrap();
1556 let t = make_ticket_with_owner_field("aaaa", "ready", None);
1557 assert!(check_owner(tmp.path(), &t).is_ok());
1558 }
1559
1560 #[test]
1561 fn check_owner_rejects_owner_change_on_terminal_state() {
1562 let tmp = tempfile::tempdir().unwrap();
1563 let cfg_toml = concat!(
1564 "[project]\nname = \"test\"\n\n",
1565 "[[workflow.states]]\nid = \"open\"\nlabel = \"Open\"\nterminal = false\n\n",
1566 "[[workflow.states]]\nid = \"closed\"\nlabel = \"Closed\"\nterminal = true\n",
1567 );
1568 std::fs::create_dir_all(tmp.path().join(".apm")).unwrap();
1569 std::fs::write(tmp.path().join(".apm/config.toml"), cfg_toml).unwrap();
1570 let t = make_ticket_with_owner_field("aaaa", "closed", Some("alice"));
1571 let err = check_owner(tmp.path(), &t).unwrap_err();
1572 assert!(
1573 err.to_string().contains("cannot change owner of a closed ticket"),
1574 "unexpected error: {err}"
1575 );
1576 }
1577
1578 #[test]
1579 fn check_owner_allows_owner_change_on_non_terminal_state() {
1580 let tmp = tempfile::tempdir().unwrap();
1581 let apm_dir = tmp.path().join(".apm");
1582 std::fs::create_dir_all(&apm_dir).unwrap();
1583 let cfg_toml = concat!(
1584 "[project]\nname = \"test\"\n\n",
1585 "[[workflow.states]]\nid = \"open\"\nlabel = \"Open\"\nterminal = false\n\n",
1586 "[[workflow.states]]\nid = \"closed\"\nlabel = \"Closed\"\nterminal = true\n",
1587 );
1588 std::fs::write(apm_dir.join("config.toml"), cfg_toml).unwrap();
1589 std::fs::write(apm_dir.join("local.toml"), "username = \"alice\"\n").unwrap();
1590 let t = make_ticket_with_owner_field("aaaa", "open", Some("alice"));
1591 assert!(check_owner(tmp.path(), &t).is_ok());
1592 }
1593}