Skip to main content

apm_core/ticket/
ticket_util.rs

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
37/// Build a reverse dependency index: for each ticket ID, collect the tickets
38/// that directly depend on it.  Pass only non-terminal, non-satisfies_deps
39/// tickets so that closed work does not inflate effective priority.
40pub 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
52/// Return the effective priority of a ticket: the max of its own priority and
53/// the priority of all direct and transitive dependents reachable via the
54/// reverse index.  Uses a visited set to handle cycles safely.
55pub 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
78/// Return all agent-actionable tickets sorted by descending score.
79pub 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
106/// Returns true if a ticket in `dep_state` satisfies the dependency gate
107/// required by the dependent ticket.  `required_gate` is `Some("tag")` when
108/// the dependent's state has `dep_requires = "tag"`, or `None` for the
109/// default (requires `satisfies_deps = true` or `terminal = true`).
110pub 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/// Return the highest-scoring ticket from `tickets` whose state is in
126/// `actionable` and (if `startable` is non-empty) also in `startable`,
127/// and whose `depends_on` deps are all satisfied.
128#[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
163/// Load all tickets by reading directly from their git branches.
164/// No filesystem cache is involved.
165pub 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        // Skip bare short-ID refs (e.g. ticket/268f5694) created by fetch operations.
171        // A real ticket branch always has a slug after the ID: ticket/<id>-<slug>.
172        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
188/// Read a ticket's state from a specific branch by relative path.
189pub fn state_from_branch(root: &Path, branch: &str, rel_path: &str) -> Option<String> {
190    let content = crate::git::read_from_branch(root, branch, rel_path).ok()?;
191    let dummy = root.join(rel_path);
192    Ticket::parse(&dummy, &content).ok().map(|t| t.frontmatter.state)
193}
194
195/// Close a ticket from any state.  Commits the change to the ticket branch,
196/// pushes it (non-fatal if no remote), then merges into the default branch
197/// so that `apm clean` can detect and remove the worktree.
198pub fn close(
199    root: &Path,
200    config: &crate::config::Config,
201    id_arg: &str,
202    reason: Option<&str>,
203    agent: &str,
204    aggressive: bool,
205) -> Result<Vec<String>> {
206    let mut output: Vec<String> = Vec::new();
207    let mut tickets = load_all_from_git(root, &config.tickets.dir)?;
208    let prefixes = id_arg_prefixes(id_arg)?;
209
210    // Search ticket branches first, then fall back to the default branch.
211    // This handles stale "implemented" tickets whose branch was deleted.
212    let branch_matches: Vec<usize> = tickets.iter()
213        .enumerate()
214        .filter(|(_, t)| prefixes.iter().any(|p| t.frontmatter.id.starts_with(p.as_str())))
215        .map(|(i, _)| i)
216        .collect();
217    // Deduplicate in case both prefixes matched the same ticket.
218    let branch_matches: Vec<usize> = {
219        let mut seen = std::collections::HashSet::new();
220        branch_matches.into_iter().filter(|&i| seen.insert(tickets[i].frontmatter.id.clone())).collect()
221    };
222
223    let mut from_default: Option<Ticket> = None;
224    let id: String = match branch_matches.len() {
225        1 => tickets[branch_matches[0]].frontmatter.id.clone(),
226        0 => {
227            let default_branch = &config.project.default_branch;
228            let mut found: Option<Ticket> = None;
229            if let Ok(files) = crate::git::list_files_on_branch(root, default_branch, &config.tickets.dir.to_string_lossy()) {
230                for rel_path in files {
231                    if !rel_path.ends_with(".md") { continue; }
232                    if let Ok(content) = crate::git::read_from_branch(root, default_branch, &rel_path) {
233                        let dummy = root.join(&rel_path);
234                        if let Ok(t) = Ticket::parse(&dummy, &content) {
235                            if prefixes.iter().any(|p| t.frontmatter.id.starts_with(p.as_str())) {
236                                found = Some(t);
237                                break;
238                            }
239                        }
240                    }
241                }
242            }
243            match found {
244                Some(t) => { let id = t.frontmatter.id.clone(); from_default = Some(t); id }
245                None => bail!("no ticket matches '{id_arg}'"),
246            }
247        }
248        _ => {
249            let names: Vec<String> = branch_matches.iter()
250                .map(|&i| tickets[i].frontmatter.id.clone())
251                .collect();
252            bail!("ambiguous prefix '{}', matches: {}", id_arg, names.join(", "));
253        }
254    };
255
256    let ticket_pos = tickets.iter().position(|t| t.frontmatter.id == id);
257    let t: &mut Ticket = match ticket_pos {
258        Some(pos) => &mut tickets[pos],
259        None => from_default.as_mut().ok_or_else(|| anyhow::anyhow!("ticket {id:?} not found"))?,
260    };
261
262    if t.frontmatter.state == "closed" {
263        anyhow::bail!("ticket {id:?} is already closed");
264    }
265
266    let now = chrono::Utc::now();
267    let prev = t.frontmatter.state.clone();
268    let when = now.format("%Y-%m-%dT%H:%MZ").to_string();
269    let by = match reason {
270        Some(r) => format!("{agent} (reason: {r})"),
271        None => agent.to_string(),
272    };
273
274    t.frontmatter.state = "closed".into();
275    t.frontmatter.updated_at = Some(now);
276
277    crate::state::append_history(&mut t.body, &prev, "closed", &when, &by);
278
279    let content = t.serialize()?;
280    let rel_path = format!(
281        "{}/{}",
282        config.tickets.dir.to_string_lossy(),
283        t.path.file_name().unwrap().to_string_lossy()
284    );
285    let branch = t.frontmatter.branch.clone()
286        .or_else(|| crate::ticket_fmt::branch_name_from_path(&t.path))
287        .unwrap_or_else(|| format!("ticket/{id}"));
288
289    crate::git::commit_to_branch(root, &branch, &rel_path, &content, &format!("ticket({id}): close"))?;
290    crate::logger::log("state_transition", &format!("{id:?} {prev} -> closed"));
291
292    let mut merge_warnings: Vec<String> = Vec::new();
293    if let Err(e) = crate::git::merge_branch_into_default(root, &branch, &config.project.default_branch, &mut merge_warnings) {
294        output.push(format!("warning: merge into {} failed: {e:#}", config.project.default_branch));
295    }
296    output.extend(merge_warnings);
297
298    if aggressive {
299        if let Err(e) = crate::git::push_branch(root, &branch) {
300            output.push(format!("warning: push failed for {branch}: {e:#}"));
301        }
302    }
303
304    output.push(format!("{id}: {prev} → closed"));
305    Ok(output)
306}
307
308#[allow(clippy::too_many_arguments)]
309pub fn create(
310    root: &std::path::Path,
311    config: &crate::config::Config,
312    title: String,
313    author: String,
314    context: Option<String>,
315    context_section: Option<String>,
316    aggressive: bool,
317    section_sets: Vec<(String, String)>,
318    epic: Option<String>,
319    target_branch: Option<String>,
320    depends_on: Option<Vec<String>>,
321    base_branch: Option<String>,
322    warnings: &mut Vec<String>,
323) -> Result<Ticket> {
324    let tickets_dir = root.join(&config.tickets.dir);
325    std::fs::create_dir_all(&tickets_dir)?;
326
327    let id = crate::ticket_fmt::gen_hex_id();
328    let slug = slugify(&title);
329    let filename = format!("{id}-{slug}.md");
330    let rel_path = format!("{}/{}", config.tickets.dir.to_string_lossy(), filename);
331    let branch = format!("ticket/{id}-{slug}");
332    let now = chrono::Utc::now();
333    let fm = Frontmatter {
334        id: id.clone(),
335        title: title.clone(),
336        state: "new".into(),
337        priority: 0,
338        effort: 0,
339        risk: 0,
340        author: Some(author.clone()),
341        owner: Some(author.clone()),
342        branch: Some(branch.clone()),
343        created_at: Some(now),
344        updated_at: Some(now),
345        focus_section: None,
346        epic,
347        target_branch,
348        depends_on,
349    };
350    let when = now.format("%Y-%m-%dT%H:%MZ");
351    let history_footer = format!("## History\n\n| When | From | To | By |\n|------|------|----|----|\n| {when} | — | new | {author} |\n");
352    let body_template = {
353        let mut s = String::from("## Spec\n\n");
354        for sec in &config.ticket.sections {
355            let placeholder = sec.placeholder.as_deref().unwrap_or("");
356            s.push_str(&format!("### {}\n\n{}\n\n", sec.name, placeholder));
357        }
358        s.push_str(&history_footer);
359        s
360    };
361    let body = if let Some(ctx) = &context {
362        let transition_section = config.workflow.states.iter()
363            .find(|s| s.id == "new")
364            .and_then(|s| s.transitions.iter().find(|tr| tr.to == "in_design"))
365            .and_then(|tr| tr.context_section.clone());
366        let section = context_section
367            .clone()
368            .or(transition_section)
369            .unwrap_or_else(|| "Problem".to_string());
370        if !config.ticket.sections.is_empty()
371            && !config.has_section(&section)
372        {
373            anyhow::bail!("section '### {section}' not found in ticket body template");
374        }
375        let mut doc = TicketDocument::parse(&body_template)?;
376        crate::spec::set_section(&mut doc, &section, ctx.clone());
377        doc.serialize()
378    } else {
379        body_template
380    };
381    let path = tickets_dir.join(&filename);
382    let mut t = Ticket { frontmatter: fm, body, path };
383
384    if !section_sets.is_empty() {
385        let mut doc = t.document()?;
386        for (name, value) in &section_sets {
387            let trimmed = value.trim().to_string();
388            let formatted = if !config.ticket.sections.is_empty() {
389                let section_config = config.find_section(name)
390                    .ok_or_else(|| anyhow::anyhow!("unknown section {:?}", name))?;
391                crate::spec::apply_section_type(&section_config.type_, trimmed)
392            } else {
393                trimmed
394            };
395            crate::spec::set_section(&mut doc, name, formatted);
396        }
397        t.body = doc.serialize();
398    }
399
400    let content = t.serialize()?;
401
402    if let Some(base) = base_branch {
403        let sha = crate::git::resolve_branch_sha(root, &base)?;
404        crate::git::create_branch_at(root, &branch, &sha)?;
405    }
406
407    crate::git::commit_to_branch(
408        root,
409        &branch,
410        &rel_path,
411        &content,
412        &format!("ticket({id}): create {title}"),
413    )?;
414
415    if aggressive {
416        if let Err(e) = crate::git::push_branch_tracking(root, &branch) {
417            warnings.push(format!("warning: push failed: {e:#}"));
418        }
419    }
420
421    Ok(t)
422}
423
424#[allow(clippy::too_many_arguments)]
425pub fn list_filtered<'a>(
426    tickets: &'a [Ticket],
427    config: &crate::config::Config,
428    state_filter: Option<&str>,
429    unassigned: bool,
430    all: bool,
431    actionable_filter: Option<&str>,
432    author_filter: Option<&str>,
433    owner_filter: Option<&str>,
434    mine_user: Option<&str>,
435) -> Vec<&'a Ticket> {
436    let terminal = config.terminal_state_ids();
437    let actionable_map: std::collections::HashMap<&str, &Vec<String>> = config.workflow.states.iter()
438        .map(|s| (s.id.as_str(), &s.actionable))
439        .collect();
440
441    tickets.iter().filter(|t| {
442        let fm = &t.frontmatter;
443        let state_ok = state_filter.is_none_or(|s| fm.state == s);
444        let agent_ok = !unassigned || fm.author.as_deref() == Some("unassigned");
445        let state_is_terminal = state_filter.is_some_and(|s| terminal.contains(s));
446        let terminal_ok = all || state_is_terminal || !terminal.contains(fm.state.as_str());
447        let actionable_ok = actionable_filter.is_none_or(|actor| {
448            actionable_map.get(fm.state.as_str())
449                .is_some_and(|actors| actors.iter().any(|a| a == actor || a == "any"))
450        });
451        let author_ok = author_filter.is_none_or(|a| fm.author.as_deref() == Some(a));
452        let owner_ok = owner_filter.is_none_or(|o| fm.owner.as_deref() == Some(o));
453        let mine_ok = mine_user.is_none_or(|me| {
454            fm.author.as_deref() == Some(me) || fm.owner.as_deref() == Some(me)
455        });
456        state_ok && agent_ok && terminal_ok && actionable_ok && author_ok && owner_ok && mine_ok
457    }).collect()
458}
459
460pub fn check_owner(root: &Path, ticket: &Ticket) -> anyhow::Result<()> {
461    let cfg = crate::config::Config::load(root)?;
462    let is_terminal = cfg.workflow.states.iter()
463        .find(|s| s.id == ticket.frontmatter.state)
464        .map(|s| s.terminal)
465        .unwrap_or(false);
466    if is_terminal {
467        anyhow::bail!("cannot change owner of a closed ticket");
468    }
469    let Some(o) = &ticket.frontmatter.owner else {
470        return Ok(());
471    };
472    let identity = crate::config::resolve_identity(root);
473    if identity == "unassigned" {
474        anyhow::bail!(
475            "cannot reassign: identity not configured (set local.user in .apm/local.toml or configure a GitHub token)"
476        );
477    }
478    if &identity != o {
479        anyhow::bail!("only the current owner ({o}) can reassign this ticket");
480    }
481    Ok(())
482}
483
484pub fn set_field(fm: &mut Frontmatter, field: &str, value: &str) -> anyhow::Result<()> {
485    match field {
486        "priority" => fm.priority = value.parse().map_err(|_| anyhow::anyhow!("priority must be 0–255"))?,
487        "effort"   => fm.effort   = value.parse().map_err(|_| anyhow::anyhow!("effort must be 0–255"))?,
488        "risk"     => fm.risk     = value.parse().map_err(|_| anyhow::anyhow!("risk must be 0–255"))?,
489        "author"   => anyhow::bail!("author is immutable"),
490        "owner"    => fm.owner    = if value == "-" { None } else { Some(value.to_string()) },
491        "branch"   => fm.branch   = if value == "-" { None } else { Some(value.to_string()) },
492        "title"    => fm.title    = value.to_string(),
493        "depends_on" => {
494            if value == "-" {
495                fm.depends_on = None;
496            } else {
497                let ids: Vec<String> = value
498                    .split(',')
499                    .map(|s| s.trim().to_string())
500                    .filter(|s| !s.is_empty())
501                    .collect();
502                fm.depends_on = if ids.is_empty() { None } else { Some(ids) };
503            }
504        }
505        other => anyhow::bail!("unknown field: {other}"),
506    }
507    Ok(())
508}
509
510#[derive(serde::Serialize, Clone, Debug)]
511pub struct BlockingDep {
512    pub id: String,
513    pub state: String,
514}
515
516pub fn compute_blocking_deps(
517    ticket: &Ticket,
518    all_tickets: &[Ticket],
519    config: &crate::config::Config,
520) -> Vec<BlockingDep> {
521    let deps = match &ticket.frontmatter.depends_on {
522        Some(d) if !d.is_empty() => d,
523        _ => return vec![],
524    };
525    let state_map: std::collections::HashMap<&str, &str> = all_tickets
526        .iter()
527        .map(|t| (t.frontmatter.id.as_str(), t.frontmatter.state.as_str()))
528        .collect();
529    deps.iter()
530        .filter_map(|dep_id| {
531            state_map.get(dep_id.as_str()).and_then(|&s| {
532                if dep_satisfied(s, None, config) {
533                    None
534                } else {
535                    Some(BlockingDep { id: dep_id.clone(), state: s.to_string() })
536                }
537            })
538        })
539        .collect()
540}
541
542/// Move a ticket into (or out of) an epic by rebasing its branch onto the new base.
543///
544/// `target` values:
545/// - `Some(epic_id_prefix)` — move into the named epic; resolves by prefix match
546/// - `None` or `Some("-")` — remove from any epic, rebase onto main
547///
548/// Returns an informational message on success (including no-op cases).
549pub fn move_to_epic(
550    root: &Path,
551    config: &crate::config::Config,
552    ticket_id_arg: &str,
553    target: Option<&str>,
554) -> Result<String> {
555    // 1. Load tickets and resolve the ticket by prefix.
556    let tickets = load_all_from_git(root, &config.tickets.dir)?;
557    let id = super::ticket_fmt::resolve_id_in_slice(&tickets, ticket_id_arg)?;
558    let ticket = tickets.iter().find(|t| t.frontmatter.id == id).unwrap();
559
560    // 2. Reject terminal tickets.
561    let terminal = config.terminal_state_ids();
562    if terminal.contains(&ticket.frontmatter.state) {
563        bail!(
564            "cannot move ticket {}: it is in a terminal state ({})",
565            id,
566            ticket.frontmatter.state
567        );
568    }
569
570    // 3. Resolve the ticket's git branch name.
571    let ticket_branch = ticket
572        .frontmatter
573        .branch
574        .clone()
575        .or_else(|| super::ticket_fmt::branch_name_from_path(&ticket.path))
576        .unwrap_or_else(|| format!("ticket/{id}"));
577
578    // 4. Determine the old base ref (where the ticket currently branches from).
579    let old_base_ref = ticket
580        .frontmatter
581        .target_branch
582        .as_deref()
583        .unwrap_or("main")
584        .to_string();
585
586    // 5. Determine new base ref and updated frontmatter fields.
587    let target_is_clear = target.is_none() || target == Some("-");
588
589    let (new_base_ref, new_epic, new_target_branch) = if target_is_clear {
590        if ticket.frontmatter.epic.is_none() {
591            return Ok(format!("ticket {id} is not in any epic; nothing to do"));
592        }
593        ("main".to_string(), None::<String>, None::<String>)
594    } else {
595        let epic_id_arg = target.unwrap();
596        let matches = crate::epic::find_epic_branches(root, epic_id_arg);
597        let epic_branch = match matches.len() {
598            0 => bail!("no epic found matching '{epic_id_arg}'"),
599            1 => matches.into_iter().next().unwrap(),
600            _ => bail!(
601                "ambiguous epic prefix '{}': matches {}",
602                epic_id_arg,
603                matches.join(", ")
604            ),
605        };
606        let epic_id = crate::epic::epic_id_from_branch(&epic_branch).to_string();
607
608        if ticket.frontmatter.epic.as_deref() == Some(&epic_id) {
609            return Ok(format!(
610                "ticket {id} is already in epic {epic_id}; nothing to do"
611            ));
612        }
613
614        (epic_branch.clone(), Some(epic_id), Some(epic_branch))
615    };
616
617    // 6. Reject if branch is checked out in a worktree.
618    if crate::worktree::find_worktree_for_branch(root, &ticket_branch).is_some() {
619        bail!(
620            "branch {} is checked out in a worktree; close the worktree first",
621            ticket_branch
622        );
623    }
624
625    // 7. Find old divergence point: git merge-base <ticket_branch> <old_base_ref>.
626    let old_base_sha = crate::git_util::resolve_branch_sha(root, &old_base_ref)
627        .with_context(|| format!("cannot resolve old base '{old_base_ref}'"))?;
628    let old_upstream_sha =
629        crate::git_util::merge_base(root, &ticket_branch, &old_base_sha)
630            .with_context(|| {
631                format!(
632                    "cannot find merge-base of {ticket_branch} and {old_base_ref}"
633                )
634            })?;
635
636    // 8. Resolve the new base to a SHA.
637    let new_base_sha = crate::git_util::resolve_branch_sha(root, &new_base_ref)
638        .with_context(|| format!("cannot resolve new base '{new_base_ref}'"))?;
639
640    // 9. Rebase: replay (old_upstream..ticket_branch] onto new_base.
641    let rebase_result = crate::git_util::run(
642        root,
643        &[
644            "rebase",
645            "--onto",
646            &new_base_sha,
647            &old_upstream_sha,
648            &ticket_branch,
649        ],
650    );
651
652    if let Err(e) = rebase_result {
653        let _ = crate::git_util::run(root, &["rebase", "--abort"]);
654        let err_str = e.to_string();
655        if err_str.contains("checked out") || err_str.contains("worktree") {
656            bail!(
657                "branch {} is checked out in a worktree; close the worktree first",
658                ticket_branch
659            );
660        }
661        bail!(
662            "rebase onto {new_base_ref} failed (conflicts or other error); \
663             resolve manually or create a new ticket with `apm new --epic`\n{e:#}"
664        );
665    }
666
667    // 10. Read the ticket file from the rebased branch tip, update frontmatter, commit.
668    let rel_path = format!(
669        "{}/{}",
670        config.tickets.dir.to_string_lossy(),
671        ticket.path.file_name().unwrap().to_string_lossy()
672    );
673
674    let updated_content =
675        crate::git_util::read_from_branch(root, &ticket_branch, &rel_path)
676            .with_context(|| {
677                format!("cannot read ticket file from {ticket_branch} after rebase")
678            })?;
679    let mut updated_ticket = Ticket::parse(&ticket.path, &updated_content)?;
680
681    let now = chrono::Utc::now();
682    updated_ticket.frontmatter.epic = new_epic.clone();
683    updated_ticket.frontmatter.target_branch = new_target_branch;
684    updated_ticket.frontmatter.updated_at = Some(now);
685
686    let when = now.format("%Y-%m-%dT%H:%MZ").to_string();
687    let history_note = format!("move: {old_base_ref} \u{2192} {new_base_ref}");
688    crate::state::append_history(
689        &mut updated_ticket.body,
690        "\u{2014}",
691        "\u{2014}",
692        &when,
693        &history_note,
694    );
695
696    let content = updated_ticket.serialize()?;
697    crate::git_util::commit_to_branch(
698        root,
699        &ticket_branch,
700        &rel_path,
701        &content,
702        &format!("ticket({id}): move to {new_base_ref}"),
703    )?;
704
705    let msg = if target_is_clear {
706        format!("{id}: moved out of epic, rebased onto main")
707    } else {
708        format!(
709            "{id}: moved into epic {}",
710            new_epic.as_deref().unwrap_or("")
711        )
712    };
713
714    Ok(msg)
715}
716
717#[cfg(test)]
718mod tests {
719    use super::*;
720    use std::path::Path;
721
722    fn dummy_path() -> &'static Path {
723        Path::new("test.md")
724    }
725
726    fn full_body(ac: &str) -> String {
727        format!(
728            "## 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|------|------|----|----|"
729        )
730    }
731
732    // ── compute_blocking_deps ─────────────────────────────────────────────
733
734    fn make_simple_ticket(id: &str, state: &str, depends_on: Option<Vec<&str>>) -> Ticket {
735        let deps_line = match &depends_on {
736            None => String::new(),
737            Some(ids) => {
738                let items: Vec<String> = ids.iter().map(|i| format!("\"{}\"", i)).collect();
739                format!("depends_on = [{}]\n", items.join(", "))
740            }
741        };
742        let raw = format!(
743            "+++\nid = \"{id}\"\ntitle = \"T\"\nstate = \"{state}\"\n{deps_line}+++\n\nbody\n"
744        );
745        Ticket::parse(Path::new("test.md"), &raw).unwrap()
746    }
747
748    #[test]
749    fn compute_blocking_deps_no_depends_on_returns_empty() {
750        let config = test_config_with_states(&["closed"]);
751        let ticket = make_simple_ticket("aaaa0001", "new", None);
752        let all = vec![ticket.clone()];
753        let result = compute_blocking_deps(&ticket, &all, &config);
754        assert!(result.is_empty());
755    }
756
757    #[test]
758    fn compute_blocking_deps_dep_in_non_terminal_state_returns_it() {
759        let config = test_config_with_states(&["closed"]);
760        let dep = make_simple_ticket("bbbb0001", "new", None);
761        let ticket = make_simple_ticket("aaaa0001", "new", Some(vec!["bbbb0001"]));
762        let all = vec![dep.clone(), ticket.clone()];
763        let result = compute_blocking_deps(&ticket, &all, &config);
764        assert_eq!(result.len(), 1);
765        assert_eq!(result[0].id, "bbbb0001");
766        assert_eq!(result[0].state, "new");
767    }
768
769    #[test]
770    fn compute_blocking_deps_all_deps_satisfied_returns_empty() {
771        let config = test_config_with_states(&["closed"]);
772        let dep = make_simple_ticket("bbbb0001", "closed", None);
773        let ticket = make_simple_ticket("aaaa0001", "new", Some(vec!["bbbb0001"]));
774        let all = vec![dep.clone(), ticket.clone()];
775        let result = compute_blocking_deps(&ticket, &all, &config);
776        assert!(result.is_empty());
777    }
778
779    #[test]
780    fn document_toggle_criterion() {
781        let body = full_body("- [ ] item one\n- [ ] item two");
782        let mut doc = TicketDocument::parse(&body).unwrap();
783        let ac = doc.sections.get("Acceptance criteria").unwrap();
784        assert!(ac.contains("- [ ] item one"));
785        doc.toggle_criterion(0, true).unwrap();
786        let ac = doc.sections.get("Acceptance criteria").unwrap();
787        assert!(ac.contains("- [x] item one"));
788    }
789
790    #[test]
791    fn document_unchecked_tasks() {
792        let body = full_body("- [ ] one\n- [x] two\n- [ ] three");
793        let doc = TicketDocument::parse(&body).unwrap();
794        assert_eq!(doc.unchecked_tasks("Acceptance criteria"), vec![0, 2]);
795    }
796
797    // ── list_filtered ─────────────────────────────────────────────────────
798
799    fn test_config_with_states(terminal_states: &[&str]) -> crate::config::Config {
800        let mut states_toml = String::new();
801        for s in ["new", "ready", "in_progress"] {
802            states_toml.push_str(&format!(
803                "[[workflow.states]]\nid = \"{s}\"\nlabel = \"{s}\"\nterminal = false\nactionable = [\"agent\"]\n\n"
804            ));
805        }
806        for s in terminal_states {
807            states_toml.push_str(&format!(
808                "[[workflow.states]]\nid = \"{s}\"\nlabel = \"{s}\"\nterminal = true\n\n"
809            ));
810        }
811        let full = format!(
812            "[project]\nname = \"test\"\n\n[tickets]\ndir = \"tickets\"\n\n{states_toml}"
813        );
814        toml::from_str(&full).unwrap()
815    }
816
817    fn make_ticket(id: &str, state: &str, agent: Option<&str>) -> Ticket {
818        let agent_line = agent.map(|a| format!("agent = \"{a}\"\n")).unwrap_or_default();
819        let raw = format!(
820            "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{agent_line}+++\n\n"
821        );
822        Ticket::parse(dummy_path(), &raw).unwrap()
823    }
824
825    #[test]
826    fn list_filtered_by_state() {
827        let config = test_config_with_states(&["closed"]);
828        let tickets = vec![
829            make_ticket("0001", "new", None),
830            make_ticket("0002", "ready", None),
831            make_ticket("0003", "new", None),
832        ];
833        let result = list_filtered(&tickets, &config, Some("new"), false, false, None, None, None, None);
834        assert_eq!(result.len(), 2);
835        assert!(result.iter().all(|t| t.frontmatter.state == "new"));
836    }
837
838    #[test]
839    fn list_filtered_terminal_hidden_by_default() {
840        let config = test_config_with_states(&["closed"]);
841        let tickets = vec![
842            make_ticket("0001", "new", None),
843            make_ticket("0002", "closed", None),
844        ];
845        // By default, terminal states are hidden.
846        let result = list_filtered(&tickets, &config, None, false, false, None, None, None, None);
847        assert_eq!(result.len(), 1);
848        assert_eq!(result[0].frontmatter.state, "new");
849
850        // With all=true, terminal states are shown.
851        let result_all = list_filtered(&tickets, &config, None, false, true, None, None, None, None);
852        assert_eq!(result_all.len(), 2);
853
854        // With state_filter matching the terminal state, it's shown.
855        let result_filtered = list_filtered(&tickets, &config, Some("closed"), false, false, None, None, None, None);
856        assert_eq!(result_filtered.len(), 1);
857        assert_eq!(result_filtered[0].frontmatter.state, "closed");
858    }
859
860    #[test]
861    fn list_filtered_unassigned() {
862        let config = test_config_with_states(&[]);
863        let make_with_author = |id: &str, author: Option<&str>| {
864            let author_line = author.map(|a| format!("author = \"{a}\"\n")).unwrap_or_default();
865            let raw = format!(
866                "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"new\"\n{author_line}+++\n\n"
867            );
868            Ticket::parse(Path::new("test.md"), &raw).unwrap()
869        };
870        let tickets = vec![
871            make_with_author("0001", Some("unassigned")),
872            make_with_author("0002", Some("alice")),
873            make_with_author("0003", Some("unassigned")),
874            make_with_author("0004", None),
875        ];
876        let result = list_filtered(&tickets, &config, None, true, false, None, None, None, None);
877        assert_eq!(result.len(), 2);
878        assert!(result.iter().all(|t| t.frontmatter.author.as_deref() == Some("unassigned")));
879    }
880
881    fn make_ticket_with_author(id: &str, state: &str, author: Option<&str>) -> Ticket {
882        let author_line = author.map(|a| format!("author = \"{a}\"\n")).unwrap_or_default();
883        let raw = format!(
884            "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{author_line}+++\n\n"
885        );
886        Ticket::parse(dummy_path(), &raw).unwrap()
887    }
888
889    #[test]
890    fn list_filtered_by_author() {
891        let config = test_config_with_states(&[]);
892        let tickets = vec![
893            make_ticket_with_author("0001", "new", Some("alice")),
894            make_ticket_with_author("0002", "new", Some("bob")),
895            make_ticket_with_author("0003", "ready", Some("alice")),
896        ];
897        let result = list_filtered(&tickets, &config, None, false, false, None, Some("alice"), None, None);
898        assert_eq!(result.len(), 2);
899        assert!(result.iter().all(|t| t.frontmatter.author.as_deref() == Some("alice")));
900    }
901
902    #[test]
903    fn list_filtered_author_none() {
904        let config = test_config_with_states(&[]);
905        let tickets = vec![
906            make_ticket_with_author("0001", "new", Some("alice")),
907            make_ticket_with_author("0002", "new", Some("bob")),
908        ];
909        let result = list_filtered(&tickets, &config, None, false, false, None, None, None, None);
910        assert_eq!(result.len(), 2);
911    }
912
913    fn make_ticket_with_owner(id: &str, state: &str, author: Option<&str>, owner: Option<&str>) -> Ticket {
914        let author_line = author.map(|a| format!("author = \"{a}\"\n")).unwrap_or_default();
915        let owner_line = owner.map(|o| format!("owner = \"{o}\"\n")).unwrap_or_default();
916        let raw = format!(
917            "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{author_line}{owner_line}+++\n\n"
918        );
919        Ticket::parse(dummy_path(), &raw).unwrap()
920    }
921
922    #[test]
923    fn list_filtered_by_owner() {
924        let config = test_config_with_states(&[]);
925        let tickets = vec![
926            make_ticket_with_owner("0001", "new", Some("alice"), Some("alice")),
927            make_ticket_with_owner("0002", "new", Some("bob"), Some("bob")),
928            make_ticket_with_owner("0003", "new", Some("carol"), None),
929        ];
930        let result = list_filtered(&tickets, &config, None, false, false, None, None, Some("alice"), None);
931        assert_eq!(result.len(), 1);
932        assert_eq!(result[0].frontmatter.id, "0001");
933    }
934
935    #[test]
936    fn list_filtered_mine_matches_author() {
937        let config = test_config_with_states(&[]);
938        let tickets = vec![
939            make_ticket_with_owner("0001", "new", Some("alice"), Some("bob")),
940            make_ticket_with_owner("0002", "new", Some("bob"), Some("carol")),
941        ];
942        let result = list_filtered(&tickets, &config, None, false, false, None, None, None, Some("alice"));
943        assert_eq!(result.len(), 1);
944        assert_eq!(result[0].frontmatter.id, "0001");
945    }
946
947    #[test]
948    fn list_filtered_mine_matches_owner() {
949        let config = test_config_with_states(&[]);
950        let tickets = vec![
951            make_ticket_with_owner("0001", "new", Some("bob"), Some("alice")),
952            make_ticket_with_owner("0002", "new", Some("carol"), Some("bob")),
953        ];
954        let result = list_filtered(&tickets, &config, None, false, false, None, None, None, Some("alice"));
955        assert_eq!(result.len(), 1);
956        assert_eq!(result[0].frontmatter.id, "0001");
957    }
958
959    #[test]
960    fn list_filtered_mine_or_semantics() {
961        let config = test_config_with_states(&[]);
962        let tickets = vec![
963            make_ticket_with_owner("0001", "new", Some("alice"), None),
964            make_ticket_with_owner("0002", "new", Some("bob"), Some("alice")),
965            make_ticket_with_owner("0003", "new", Some("carol"), Some("carol")),
966        ];
967        let result = list_filtered(&tickets, &config, None, false, false, None, None, None, Some("alice"));
968        assert_eq!(result.len(), 2);
969        let ids: Vec<&str> = result.iter().map(|t| t.frontmatter.id.as_str()).collect();
970        assert!(ids.contains(&"0001"));
971        assert!(ids.contains(&"0002"));
972    }
973
974    // ── set_field ─────────────────────────────────────────────────────────
975
976    fn make_frontmatter() -> Frontmatter {
977        Frontmatter {
978            id: "0001".to_string(),
979            title: "Test".to_string(),
980            state: "new".to_string(),
981            priority: 0,
982            effort: 0,
983            risk: 0,
984            author: None,
985            owner: None,
986            branch: None,
987            created_at: None,
988            updated_at: None,
989            focus_section: None,
990            epic: None,
991            target_branch: None,
992            depends_on: None,
993        }
994    }
995
996    #[test]
997    fn set_field_priority_valid() {
998        let mut fm = make_frontmatter();
999        set_field(&mut fm, "priority", "5").unwrap();
1000        assert_eq!(fm.priority, 5);
1001    }
1002
1003    #[test]
1004    fn set_field_priority_overflow() {
1005        let mut fm = make_frontmatter();
1006        let err = set_field(&mut fm, "priority", "256").unwrap_err();
1007        assert!(err.to_string().contains("priority must be 0"));
1008    }
1009
1010    #[test]
1011    fn set_field_author_immutable() {
1012        let mut fm = make_frontmatter();
1013        let err = set_field(&mut fm, "author", "alice").unwrap_err();
1014        assert!(err.to_string().contains("author is immutable"));
1015    }
1016
1017    #[test]
1018    fn set_field_unknown_field() {
1019        let mut fm = make_frontmatter();
1020        let err = set_field(&mut fm, "foo", "bar").unwrap_err();
1021        assert!(err.to_string().contains("unknown field: foo"));
1022    }
1023
1024    #[test]
1025    fn owner_round_trips_through_toml() {
1026        let toml_src = r#"id = "0001"
1027title = "T"
1028state = "new"
1029owner = "alice"
1030"#;
1031        let fm: Frontmatter = toml::from_str(toml_src).unwrap();
1032        assert_eq!(fm.owner, Some("alice".to_string()));
1033        let serialized = toml::to_string(&fm).unwrap();
1034        assert!(serialized.contains("owner = \"alice\""));
1035    }
1036
1037    #[test]
1038    fn owner_absent_deserializes_as_none() {
1039        let toml_src = r#"id = "0001"
1040title = "T"
1041state = "new"
1042"#;
1043        let fm: Frontmatter = toml::from_str(toml_src).unwrap();
1044        assert_eq!(fm.owner, None);
1045    }
1046
1047    #[test]
1048    fn set_field_owner_set() {
1049        let mut fm = make_frontmatter();
1050        set_field(&mut fm, "owner", "alice").unwrap();
1051        assert_eq!(fm.owner, Some("alice".to_string()));
1052    }
1053
1054    #[test]
1055    fn set_field_owner_clear() {
1056        let mut fm = make_frontmatter();
1057        fm.owner = Some("alice".to_string());
1058        set_field(&mut fm, "owner", "-").unwrap();
1059        assert_eq!(fm.owner, None);
1060    }
1061
1062    // ── dep_satisfied ─────────────────────────────────────────────────────
1063
1064    fn config_with_dep_states() -> crate::config::Config {
1065        let toml = r#"
1066[project]
1067name = "test"
1068
1069[tickets]
1070dir = "tickets"
1071
1072[[workflow.states]]
1073id = "ready"
1074label = "Ready"
1075actionable = ["agent"]
1076
1077[[workflow.states]]
1078id = "done"
1079label = "Done"
1080satisfies_deps = true
1081
1082[[workflow.states]]
1083id = "closed"
1084label = "Closed"
1085terminal = true
1086
1087[[workflow.states]]
1088id = "blocked"
1089label = "Blocked"
1090"#;
1091        toml::from_str(toml).unwrap()
1092    }
1093
1094    #[test]
1095    fn dep_satisfied_satisfies_deps_true() {
1096        let config = config_with_dep_states();
1097        assert!(dep_satisfied("done", None, &config));
1098    }
1099
1100    #[test]
1101    fn dep_satisfied_terminal_true() {
1102        let config = config_with_dep_states();
1103        assert!(dep_satisfied("closed", None, &config));
1104    }
1105
1106    #[test]
1107    fn dep_satisfied_both_false() {
1108        let config = config_with_dep_states();
1109        assert!(!dep_satisfied("blocked", None, &config));
1110    }
1111
1112    #[test]
1113    fn dep_satisfied_unknown_state() {
1114        let config = config_with_dep_states();
1115        assert!(!dep_satisfied("nonexistent", None, &config));
1116    }
1117
1118    fn config_with_spec_gate() -> crate::config::Config {
1119        let toml = r#"
1120[project]
1121name = "test"
1122
1123[tickets]
1124dir = "tickets"
1125
1126[[workflow.states]]
1127id = "groomed"
1128label = "Groomed"
1129actionable = ["agent"]
1130dep_requires = "spec"
1131
1132[[workflow.states]]
1133id = "ready"
1134label = "Ready"
1135actionable = ["agent"]
1136
1137[[workflow.states]]
1138id = "specd"
1139label = "Specd"
1140satisfies_deps = "spec"
1141
1142[[workflow.states]]
1143id = "in_progress"
1144label = "In Progress"
1145satisfies_deps = "spec"
1146
1147[[workflow.states]]
1148id = "implemented"
1149label = "Implemented"
1150satisfies_deps = true
1151
1152[[workflow.states]]
1153id = "closed"
1154label = "Closed"
1155terminal = true
1156"#;
1157        toml::from_str(toml).unwrap()
1158    }
1159
1160    #[test]
1161    fn dep_satisfied_tag_matches_required_gate() {
1162        let config = config_with_spec_gate();
1163        assert!(dep_satisfied("specd", Some("spec"), &config));
1164    }
1165
1166    #[test]
1167    fn dep_satisfied_tag_no_required_gate_is_false() {
1168        let config = config_with_spec_gate();
1169        assert!(!dep_satisfied("specd", None, &config));
1170    }
1171
1172    #[test]
1173    fn dep_satisfied_bool_true_with_no_gate() {
1174        let config = config_with_spec_gate();
1175        assert!(dep_satisfied("implemented", None, &config));
1176    }
1177
1178    #[test]
1179    fn pick_next_groomed_unblocked_when_dep_specd() {
1180        let config = config_with_spec_gate();
1181        let tickets = vec![
1182            make_ticket_with_deps("aaaa0001", "groomed", Some(vec!["bbbb0001"])),
1183            make_ticket_with_deps("bbbb0001", "specd", None),
1184        ];
1185        let result = pick_next(&tickets, &["groomed"], &[], 10.0, -2.0, -1.0, &config, None, None);
1186        assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1187    }
1188
1189    #[test]
1190    fn pick_next_groomed_unblocked_when_dep_in_progress() {
1191        let config = config_with_spec_gate();
1192        let tickets = vec![
1193            make_ticket_with_deps("aaaa0001", "groomed", Some(vec!["bbbb0001"])),
1194            make_ticket_with_deps("bbbb0001", "in_progress", None),
1195        ];
1196        let result = pick_next(&tickets, &["groomed"], &[], 10.0, -2.0, -1.0, &config, None, None);
1197        assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1198    }
1199
1200    #[test]
1201    fn pick_next_ready_blocked_when_dep_only_specd() {
1202        let config = config_with_spec_gate();
1203        let tickets = vec![
1204            make_ticket_with_deps("aaaa0001", "ready", Some(vec!["bbbb0001"])),
1205            make_ticket_with_deps("bbbb0001", "specd", None),
1206        ];
1207        let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1208        assert!(result.is_none());
1209    }
1210
1211    // ── pick_next dep filtering ────────────────────────────────────────────
1212
1213    fn make_ticket_with_deps(id: &str, state: &str, deps: Option<Vec<&str>>) -> Ticket {
1214        let deps_line = match &deps {
1215            None => String::new(),
1216            Some(v) => {
1217                let list: Vec<String> = v.iter().map(|d| format!("\"{d}\"")).collect();
1218                format!("depends_on = [{}]\n", list.join(", "))
1219            }
1220        };
1221        let raw = format!(
1222            "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{deps_line}+++\n\n"
1223        );
1224        Ticket::parse(dummy_path(), &raw).unwrap()
1225    }
1226
1227    #[test]
1228    fn pick_next_skips_dep_blocked_ticket() {
1229        let config = config_with_dep_states();
1230        let tickets = vec![
1231            make_ticket_with_deps("aaaa0001", "ready", Some(vec!["bbbb0001"])),
1232            make_ticket_with_deps("bbbb0001", "ready", None),
1233            make_ticket_with_deps("cccc0001", "ready", None),
1234        ];
1235        // aaaa0001 depends on bbbb0001 which is in "ready" (not satisfies_deps)
1236        // should skip aaaa0001 and return bbbb0001 (next by score, no deps)
1237        let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1238        assert!(result.is_some());
1239        let id = &result.unwrap().frontmatter.id;
1240        assert_ne!(id, "aaaa0001", "dep-blocked ticket should be skipped");
1241    }
1242
1243    #[test]
1244    fn pick_next_returns_ticket_when_dep_satisfied() {
1245        let config = config_with_dep_states();
1246        let tickets = vec![
1247            make_ticket_with_deps("aaaa0001", "ready", Some(vec!["bbbb0001"])),
1248            make_ticket_with_deps("bbbb0001", "done", None),
1249        ];
1250        let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1251        assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1252    }
1253
1254    #[test]
1255    fn pick_next_unknown_dep_id_not_blocking() {
1256        let config = config_with_dep_states();
1257        let tickets = vec![
1258            make_ticket_with_deps("aaaa0001", "ready", Some(vec!["unknown1"])),
1259        ];
1260        let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1261        assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1262    }
1263
1264    #[test]
1265    fn pick_next_empty_depends_on_not_blocking() {
1266        let config = config_with_dep_states();
1267        let raw = "+++\nid = \"aaaa0001\"\ntitle = \"T\"\nstate = \"ready\"\ndepends_on = []\n+++\n\n";
1268        let t = Ticket::parse(dummy_path(), raw).unwrap();
1269        let tickets = vec![t];
1270        let result = pick_next(&tickets, &["ready"], &[], 10.0, -2.0, -1.0, &config, None, None);
1271        assert_eq!(result.unwrap().frontmatter.id, "aaaa0001");
1272    }
1273
1274    // --- build_reverse_index / effective_priority / sorted_actionable ---
1275
1276    fn make_ticket_with_priority(id: &str, state: &str, priority: u8, deps: Option<Vec<&str>>) -> Ticket {
1277        let dep_line = match &deps {
1278            Some(d) => {
1279                let list: Vec<String> = d.iter().map(|s| format!("\"{s}\"")).collect();
1280                format!("depends_on = [{}]\n", list.join(", "))
1281            }
1282            None => String::new(),
1283        };
1284        let raw = format!(
1285            "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\npriority = {priority}\n{dep_line}+++\n\n"
1286        );
1287        Ticket::parse(Path::new("test.md"), &raw).unwrap()
1288    }
1289
1290    #[test]
1291    fn effective_priority_no_dependents_returns_own() {
1292        let a = make_ticket_with_priority("aaaa", "ready", 5, None);
1293        let tickets = vec![&a];
1294        let rev_idx = build_reverse_index(&tickets);
1295        assert_eq!(effective_priority(&a, &rev_idx), 5);
1296    }
1297
1298    #[test]
1299    fn effective_priority_single_hop_elevation() {
1300        // A (priority 2) is depended on by B (priority 9)
1301        let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1302        let b = make_ticket_with_priority("bbbb", "ready", 9, Some(vec!["aaaa"]));
1303        let tickets = vec![&a, &b];
1304        let rev_idx = build_reverse_index(&tickets);
1305        assert_eq!(effective_priority(&a, &rev_idx), 9);
1306        assert_eq!(effective_priority(&b, &rev_idx), 9);
1307    }
1308
1309    #[test]
1310    fn effective_priority_transitive_elevation() {
1311        // A (2) blocks B (5) blocks C (9); A's effective priority should be 9
1312        let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1313        let b = make_ticket_with_priority("bbbb", "ready", 5, Some(vec!["aaaa"]));
1314        let c = make_ticket_with_priority("cccc", "ready", 9, Some(vec!["bbbb"]));
1315        let tickets = vec![&a, &b, &c];
1316        let rev_idx = build_reverse_index(&tickets);
1317        assert_eq!(effective_priority(&a, &rev_idx), 9);
1318        assert_eq!(effective_priority(&b, &rev_idx), 9);
1319        assert_eq!(effective_priority(&c, &rev_idx), 9);
1320    }
1321
1322    #[test]
1323    fn effective_priority_cycle_does_not_panic() {
1324        // A depends on B, B depends on A
1325        let a = make_ticket_with_priority("aaaa", "ready", 3, Some(vec!["bbbb"]));
1326        let b = make_ticket_with_priority("bbbb", "ready", 7, Some(vec!["aaaa"]));
1327        let tickets = vec![&a, &b];
1328        let rev_idx = build_reverse_index(&tickets);
1329        // Should not panic; both see each other's priority
1330        let ep_a = effective_priority(&a, &rev_idx);
1331        let ep_b = effective_priority(&b, &rev_idx);
1332        assert_eq!(ep_a, 7);
1333        assert_eq!(ep_b, 7);
1334    }
1335
1336    #[test]
1337    fn effective_priority_closed_dependent_excluded() {
1338        // A (2) is in the active set; B (9, closed) is NOT passed to build_reverse_index
1339        let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1340        // B is "closed" — caller filters it out before building the index
1341        let tickets_active = vec![&a];
1342        let rev_idx = build_reverse_index(&tickets_active);
1343        assert_eq!(effective_priority(&a, &rev_idx), 2);
1344    }
1345
1346    #[test]
1347    fn sorted_actionable_low_priority_blocker_elevated() {
1348        // A (priority 2, ready) is depended on by B (priority 9, ready)
1349        // A's effective priority becomes 9 — it should not sort last
1350        let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1351        let b = make_ticket_with_priority("bbbb", "ready", 9, Some(vec!["aaaa"]));
1352        let tickets = vec![a, b];
1353        let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, None);
1354        assert_eq!(result.len(), 2);
1355        let ids: Vec<&str> = result.iter().map(|t| t.frontmatter.id.as_str()).collect();
1356        assert!(ids.contains(&"aaaa"), "A must appear in results");
1357        assert!(ids.contains(&"bbbb"), "B must appear in results");
1358        // A (ep=9) and B (ep=9) are tied; A must not be sorted below B due to raw priority
1359        // The last entry must not be A simply because raw priority 2 < 9
1360        // Both ep=9 so the sort is stable-ish; just verify A is present
1361    }
1362
1363    #[test]
1364    fn sorted_actionable_blocker_before_independent_higher_raw() {
1365        // A (priority 2, ready, blocks C which has priority 9)
1366        // B (priority 7, ready, no deps)
1367        // A's effective priority = 9, B's = 7 → A should sort before B
1368        let a = make_ticket_with_priority("aaaa", "ready", 2, None);
1369        let b = make_ticket_with_priority("bbbb", "ready", 7, None);
1370        let c = make_ticket_with_priority("cccc", "ready", 9, Some(vec!["aaaa"]));
1371        let tickets = vec![a, b, c];
1372        let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, None);
1373        assert_eq!(result.len(), 3);
1374        let ids: Vec<&str> = result.iter().map(|t| t.frontmatter.id.as_str()).collect();
1375        let a_pos = ids.iter().position(|&id| id == "aaaa").unwrap();
1376        let b_pos = ids.iter().position(|&id| id == "bbbb").unwrap();
1377        assert!(a_pos < b_pos, "A (ep=9) should sort before B (ep=7)");
1378    }
1379
1380    #[test]
1381    fn sorted_actionable_no_deps_unchanged() {
1382        let a = make_ticket_with_priority("aaaa", "ready", 3, None);
1383        let b = make_ticket_with_priority("bbbb", "ready", 7, None);
1384        let tickets = vec![a, b];
1385        let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, None);
1386        assert_eq!(result[0].frontmatter.id, "bbbb");
1387        assert_eq!(result[1].frontmatter.id, "aaaa");
1388    }
1389
1390    fn make_ticket_with_owner_field(id: &str, state: &str, owner: Option<&str>) -> Ticket {
1391        let owner_line = owner.map(|o| format!("owner = \"{o}\"\n")).unwrap_or_default();
1392        let raw = format!(
1393            "+++\nid = \"{id}\"\ntitle = \"T{id}\"\nstate = \"{state}\"\n{owner_line}+++\n\n"
1394        );
1395        Ticket::parse(Path::new("test.md"), &raw).unwrap()
1396    }
1397
1398    #[test]
1399    fn sorted_actionable_excludes_ticket_owned_by_other() {
1400        let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1401        let tickets = vec![t];
1402        let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, Some("bob"));
1403        assert!(result.is_empty(), "ticket owned by alice should not appear for bob");
1404    }
1405
1406    #[test]
1407    fn sorted_actionable_includes_ticket_owned_by_caller() {
1408        let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1409        let tickets = vec![t];
1410        let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, Some("alice"));
1411        assert_eq!(result.len(), 1);
1412        assert_eq!(result[0].frontmatter.id, "aaaa");
1413    }
1414
1415    #[test]
1416    fn sorted_actionable_includes_unowned_ticket() {
1417        let t = make_ticket_with_owner_field("aaaa", "ready", None);
1418        let tickets = vec![t];
1419        let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, Some("bob"));
1420        assert!(result.is_empty(), "unowned ticket should be excluded when owner_filter is set");
1421    }
1422
1423    #[test]
1424    fn sorted_actionable_no_owner_filter_shows_all() {
1425        let t1 = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1426        let t2 = make_ticket_with_owner_field("bbbb", "ready", Some("bob"));
1427        let tickets = vec![t1, t2];
1428        let result = sorted_actionable(&tickets, &["ready"], 1.0, 0.0, 0.0, None, None);
1429        assert_eq!(result.len(), 2);
1430    }
1431
1432    #[test]
1433    fn pick_next_skips_unowned_ticket_when_owner_filter_set() {
1434        let config = config_with_dep_states();
1435        let t = make_ticket_with_owner_field("aaaa", "ready", None);
1436        let tickets = vec![t];
1437        let result = pick_next(&tickets, &["ready"], &[], 1.0, 0.0, 0.0, &config, None, Some("alice"));
1438        assert!(result.is_none(), "unowned ticket should be skipped when owner_filter is set");
1439    }
1440
1441    #[test]
1442    fn pick_next_skips_ticket_owned_by_other() {
1443        let config = config_with_dep_states();
1444        let t = make_ticket_with_owner_field("aaaa", "ready", Some("bob"));
1445        let tickets = vec![t];
1446        let result = pick_next(&tickets, &["ready"], &[], 1.0, 0.0, 0.0, &config, None, Some("alice"));
1447        assert!(result.is_none(), "ticket owned by bob should be skipped for alice");
1448    }
1449
1450    #[test]
1451    fn pick_next_picks_ticket_owned_by_current_user() {
1452        let config = config_with_dep_states();
1453        let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1454        let tickets = vec![t];
1455        let result = pick_next(&tickets, &["ready"], &[], 1.0, 0.0, 0.0, &config, None, Some("alice"));
1456        assert!(result.is_some(), "ticket owned by alice should be picked");
1457        assert_eq!(result.unwrap().frontmatter.id, "aaaa");
1458    }
1459
1460    #[test]
1461    fn check_owner_passes_when_identity_matches_owner() {
1462        let tmp = tempfile::tempdir().unwrap();
1463        let apm_dir = tmp.path().join(".apm");
1464        std::fs::create_dir_all(&apm_dir).unwrap();
1465        std::fs::write(tmp.path().join("apm.toml"), "[project]\nname = \"test\"\n").unwrap();
1466        std::fs::write(apm_dir.join("local.toml"), "username = \"alice\"\n").unwrap();
1467        let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1468        assert!(check_owner(tmp.path(), &t).is_ok());
1469    }
1470
1471    #[test]
1472    fn check_owner_fails_when_identity_does_not_match_owner() {
1473        let tmp = tempfile::tempdir().unwrap();
1474        let apm_dir = tmp.path().join(".apm");
1475        std::fs::create_dir_all(&apm_dir).unwrap();
1476        std::fs::write(tmp.path().join("apm.toml"), "[project]\nname = \"test\"\n").unwrap();
1477        std::fs::write(apm_dir.join("local.toml"), "username = \"bob\"\n").unwrap();
1478        let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1479        let err = check_owner(tmp.path(), &t).unwrap_err();
1480        assert!(err.to_string().contains("alice"), "error should mention the owner");
1481    }
1482
1483    #[test]
1484    fn check_owner_fails_when_identity_is_unassigned() {
1485        let tmp = tempfile::tempdir().unwrap();
1486        std::fs::write(tmp.path().join("apm.toml"), "[project]\nname = \"test\"\n").unwrap();
1487        let t = make_ticket_with_owner_field("aaaa", "ready", Some("alice"));
1488        let err = check_owner(tmp.path(), &t).unwrap_err();
1489        assert!(err.to_string().contains("identity not configured"));
1490    }
1491
1492    #[test]
1493    fn check_owner_passes_when_ticket_has_no_owner() {
1494        let tmp = tempfile::tempdir().unwrap();
1495        std::fs::write(tmp.path().join("apm.toml"), "[project]\nname = \"test\"\n").unwrap();
1496        let t = make_ticket_with_owner_field("aaaa", "ready", None);
1497        assert!(check_owner(tmp.path(), &t).is_ok());
1498    }
1499
1500    #[test]
1501    fn check_owner_rejects_owner_change_on_terminal_state() {
1502        let tmp = tempfile::tempdir().unwrap();
1503        let cfg_toml = concat!(
1504            "[project]\nname = \"test\"\n\n",
1505            "[[workflow.states]]\nid = \"open\"\nlabel = \"Open\"\nterminal = false\n\n",
1506            "[[workflow.states]]\nid = \"closed\"\nlabel = \"Closed\"\nterminal = true\n",
1507        );
1508        std::fs::write(tmp.path().join("apm.toml"), cfg_toml).unwrap();
1509        let t = make_ticket_with_owner_field("aaaa", "closed", Some("alice"));
1510        let err = check_owner(tmp.path(), &t).unwrap_err();
1511        assert!(
1512            err.to_string().contains("cannot change owner of a closed ticket"),
1513            "unexpected error: {err}"
1514        );
1515    }
1516
1517    #[test]
1518    fn check_owner_allows_owner_change_on_non_terminal_state() {
1519        let tmp = tempfile::tempdir().unwrap();
1520        let apm_dir = tmp.path().join(".apm");
1521        std::fs::create_dir_all(&apm_dir).unwrap();
1522        let cfg_toml = concat!(
1523            "[project]\nname = \"test\"\n\n",
1524            "[[workflow.states]]\nid = \"open\"\nlabel = \"Open\"\nterminal = false\n\n",
1525            "[[workflow.states]]\nid = \"closed\"\nlabel = \"Closed\"\nterminal = true\n",
1526        );
1527        std::fs::write(tmp.path().join("apm.toml"), cfg_toml).unwrap();
1528        std::fs::write(apm_dir.join("local.toml"), "username = \"alice\"\n").unwrap();
1529        let t = make_ticket_with_owner_field("aaaa", "open", Some("alice"));
1530        assert!(check_owner(tmp.path(), &t).is_ok());
1531    }
1532}