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