1use anyhow::{anyhow, bail, Result};
2use crate::{config::{CompletionStrategy, Config}, git, review, ticket, ticket_fmt};
3use chrono::Utc;
4use std::path::{Path, PathBuf};
5
6pub struct TransitionOutput {
7 pub id: String,
8 pub old_state: String,
9 pub new_state: String,
10 pub worktree_path: Option<PathBuf>,
11 pub warnings: Vec<String>,
12 pub messages: Vec<String>,
13}
14
15pub fn transition(root: &Path, id_arg: &str, new_state: String, no_aggressive: bool, force: bool) -> Result<TransitionOutput> {
16 let mut warnings: Vec<String> = Vec::new();
17 let mut messages: Vec<String> = Vec::new();
18
19 let config = Config::load(root)?;
20 let valid_states: std::collections::HashSet<&str> = config.workflow.states.iter()
21 .map(|s| s.id.as_str())
22 .collect();
23 if !valid_states.is_empty() && !valid_states.contains(new_state.as_str()) {
24 let list: Vec<&str> = config.workflow.states.iter().map(|s| s.id.as_str()).collect();
25 bail!("unknown state {:?} — valid states: {}", new_state, list.join(", "));
26 }
27 let aggressive = config.sync.aggressive && !no_aggressive;
28
29 let mut tickets = ticket::load_all_from_git(root, &config.tickets.dir)?;
30 let id = ticket::resolve_id_in_slice(&tickets, id_arg)?;
31
32 if aggressive {
33 let branches = git::ticket_branches(root).unwrap_or_default();
34 if let Some(b) = branches.iter().find(|b| {
35 b.strip_prefix("ticket/")
36 .and_then(|s| s.split('-').next())
37 .map(|bid| bid == id.as_str())
38 .unwrap_or(false)
39 }) {
40 if let Err(e) = git::fetch_branch(root, b) {
41 warnings.push(format!("warning: fetch failed: {e:#}"));
42 }
43 }
44 }
45
46 let Some(t) = tickets.iter_mut().find(|t| t.frontmatter.id == id) else {
47 bail!("ticket {id:?} not found");
48 };
49 let old_state = t.frontmatter.state.clone();
50
51 let target_is_terminal = config.workflow.states.iter()
52 .find(|s| s.id == new_state)
53 .map(|s| s.terminal)
54 .unwrap_or(false);
55 let (completion, on_failure): (CompletionStrategy, Option<String>) = if force {
56 (CompletionStrategy::None, None)
57 } else if !target_is_terminal {
58 if let Some(state_cfg) = config.workflow.states.iter().find(|s| s.id == old_state) {
59 if !state_cfg.transitions.is_empty() {
60 let tr = state_cfg.transitions.iter().find(|tr| tr.to == new_state);
61 if tr.is_none() {
62 let allowed: Vec<&str> = state_cfg.transitions.iter().map(|tr| tr.to.as_str()).collect();
63 bail!(
64 "no transition from {:?} to {:?} — valid transitions from {:?}: {}",
65 old_state, new_state, old_state,
66 allowed.join(", ")
67 );
68 }
69 let found = tr.unwrap();
70 if let Some(ref w) = found.warning {
71 warnings.push(format!("⚠ {w}"));
72 }
73 (found.completion.clone(), found.on_failure.clone())
74 } else {
75 (CompletionStrategy::None, None)
76 }
77 } else {
78 (CompletionStrategy::None, None)
79 }
80 } else {
81 (CompletionStrategy::None, None)
82 };
83
84 let branch = t
85 .frontmatter
86 .branch
87 .clone()
88 .or_else(|| ticket_fmt::branch_name_from_path(&t.path))
89 .unwrap_or_else(|| format!("ticket/{id}"));
90
91 match new_state.as_str() {
92 "specd" => {
93 if let Ok(doc) = t.document() {
94 let errors = doc.validate(&config.ticket.sections);
95 if !errors.is_empty() {
96 let msgs: Vec<String> = errors.iter().map(|e| format!(" - {e}")).collect();
97 bail!("spec validation failed:\n{}", msgs.join("\n"));
98 }
99 if old_state == "ammend" {
100 let unchecked = doc.unchecked_tasks("Amendment requests");
101 if !unchecked.is_empty() {
102 bail!("not all amendment requests are checked — mark them [x] before resubmitting");
103 }
104 }
105 }
106 }
107 "implemented" => {
108 if let Ok(doc) = t.document() {
109 let unchecked = doc.unchecked_tasks("Acceptance criteria");
110 if !unchecked.is_empty() {
111 bail!(
112 "not all acceptance criteria are checked — mark them [x] before transitioning to implemented"
113 );
114 }
115 }
116 let should_check = match &completion {
119 CompletionStrategy::Merge => true,
120 CompletionStrategy::PrOrEpicMerge => t.frontmatter.target_branch.is_some(),
121 _ => false,
122 };
123 if should_check {
124 let merge_target = t.frontmatter.target_branch.as_deref()
125 .unwrap_or(config.project.default_branch.as_str());
126 let leaked = git::check_leaked_files(root, &branch, merge_target)?;
127 if !leaked.is_empty() {
128 let file_list = leaked
129 .iter()
130 .map(|f| format!(" {f}"))
131 .collect::<Vec<_>>()
132 .join("\n");
133 let log_hint = crate::worktree::find_worktree_for_branch(root, &branch)
134 .map(|p| p.join(".apm-worker.log").to_string_lossy().into_owned())
135 .unwrap_or_else(|| "<ticket-worktree>/.apm-worker.log".to_string());
136 bail!(
137 "cannot complete {new_state}: the target worktree has uncommitted changes \
138 to files this ticket also modified:\n{file_list}\n\
139 This usually means a worker leaked edits outside its worktree.\n\
140 Inspect the worker's transcript: {log_hint}\n\
141 Then either commit/restore the leaked files and re-run \
142 `apm state {id} implemented`, or run `apm verify` to investigate."
143 );
144 }
145 }
146 }
147 _ => {}
148 }
149
150 let now = Utc::now();
151 let actor = crate::config::resolve_caller_name();
152 t.frontmatter.state = new_state.clone();
153 t.frontmatter.updated_at = Some(now);
154 if new_state == "ammend" {
155 review::ensure_amendment_section(&mut t.body);
156 }
157 append_history(&mut t.body, &old_state, &new_state, &now.format("%Y-%m-%dT%H:%MZ").to_string(), &actor);
158
159 let content = t.serialize()?;
160 let rel_path = format!(
161 "{}/{}",
162 config.tickets.dir.to_string_lossy(),
163 t.path.file_name().unwrap().to_string_lossy()
164 );
165
166 git::commit_to_branch(
167 root,
168 &branch,
169 &rel_path,
170 &content,
171 &format!("ticket({id}): {old_state} → {new_state}"),
172 )?;
173 crate::logger::log("state_transition", &format!("{id:?} {old_state} -> {new_state}"));
174
175 match completion {
176 CompletionStrategy::Pr => {
177 git::push_branch_tracking(root, &branch)?;
178 let pr_base = t.frontmatter.target_branch.as_deref()
179 .unwrap_or(&config.project.default_branch);
180 crate::github::gh_pr_create_or_update(root, &branch, pr_base, &id, &t.frontmatter.title, &format!("Closes #{id}"), &mut messages)?;
181 }
182 CompletionStrategy::Merge => {
183 let merge_result = {
184 let merge_target = t.frontmatter.target_branch.as_deref()
185 .unwrap_or(&config.project.default_branch);
186 let is_main = merge_target == config.project.default_branch;
187 if let Err(e) = git::push_branch_tracking(root, &branch) {
188 warnings.push(format!("warning: could not push {branch}: {e}"));
189 }
190 git::merge_into_default(root, &config, &branch, merge_target, is_main, &mut messages, &mut warnings)
191 };
192 if let Err(merge_err) = merge_result {
193 let merge_err_msg = format!("{merge_err:#}");
194 let failure_state = match &on_failure {
195 Some(s) => s.clone(),
196 None => {
197 return Err(anyhow!(
198 "{merge_err_msg}\n\nMerge failed and the transition to '{}' has \
199 no `on_failure` configured. Run `apm validate --fix` to add it.",
200 new_state
201 ));
202 }
203 };
204 let fail_now = Utc::now();
205 t.frontmatter.state = failure_state.clone();
206 t.frontmatter.updated_at = Some(fail_now);
207 set_merge_notes(&mut t.body, &merge_err_msg);
208 append_history(&mut t.body, &new_state, &failure_state, &fail_now.format("%Y-%m-%dT%H:%MZ").to_string(), &actor);
209 let fallback_content = match t.serialize() {
210 Ok(c) => c,
211 Err(_) => return Err(merge_err),
212 };
213 if git::commit_to_branch(root, &branch, &rel_path, &fallback_content, &format!("ticket({id}): {new_state} → {failure_state}")).is_err() {
214 return Err(merge_err);
215 }
216 crate::logger::log("state_transition", &format!("{id:?} {new_state} -> {failure_state}"));
217 return Ok(TransitionOutput {
218 id: id.clone(),
219 old_state: old_state.clone(),
220 new_state: failure_state,
221 worktree_path: None,
222 warnings,
223 messages,
224 });
225 }
226 }
227 CompletionStrategy::PrOrEpicMerge => {
228 git::push_branch_tracking(root, &branch)?;
229 if let Some(ref target) = t.frontmatter.target_branch {
230 let merge_result = git::merge_into_default(root, &config, &branch, target, false, &mut messages, &mut warnings);
231 if let Err(merge_err) = merge_result {
232 let merge_err_msg = format!("{merge_err:#}");
233 let failure_state = match &on_failure {
234 Some(s) => s.clone(),
235 None => {
236 return Err(anyhow!(
237 "{merge_err_msg}\n\nMerge failed and the transition to '{}' has \
238 no `on_failure` configured. Run `apm validate --fix` to add it.",
239 new_state
240 ));
241 }
242 };
243 let fail_now = Utc::now();
244 t.frontmatter.state = failure_state.clone();
245 t.frontmatter.updated_at = Some(fail_now);
246 set_merge_notes(&mut t.body, &merge_err_msg);
247 append_history(&mut t.body, &new_state, &failure_state, &fail_now.format("%Y-%m-%dT%H:%MZ").to_string(), &actor);
248 let fallback_content = match t.serialize() {
249 Ok(c) => c,
250 Err(_) => return Err(merge_err),
251 };
252 if git::commit_to_branch(root, &branch, &rel_path, &fallback_content, &format!("ticket({id}): {new_state} → {failure_state}")).is_err() {
253 return Err(merge_err);
254 }
255 crate::logger::log("state_transition", &format!("{id:?} {new_state} -> {failure_state}"));
256 return Ok(TransitionOutput {
257 id: id.clone(),
258 old_state: old_state.clone(),
259 new_state: failure_state,
260 worktree_path: None,
261 warnings,
262 messages,
263 });
264 }
265 } else {
266 crate::github::gh_pr_create_or_update(root, &branch, &config.project.default_branch, &id, &t.frontmatter.title, &format!("Closes #{id}"), &mut messages)?;
267 }
268 }
269 CompletionStrategy::Pull => {
270 git::pull_default(root, &config.project.default_branch, &mut warnings)?;
271 }
272 CompletionStrategy::None => {
273 if aggressive {
274 if let Err(e) = git::push_branch_tracking(root, &branch) {
275 warnings.push(format!("warning: push failed: {e:#}"));
276 }
277 }
278 }
279 }
280
281 let worktree_path = if new_state == "in_design" {
282 Some(crate::worktree::provision_worktree(root, &config, &branch, &mut warnings)?)
283 } else {
284 None
285 };
286
287 Ok(TransitionOutput {
288 id,
289 old_state,
290 new_state,
291 worktree_path,
292 warnings,
293 messages,
294 })
295}
296
297
298pub fn available_transitions(config: &crate::config::Config, current_state: &str) -> Vec<(String, String, String)> {
299 let terminal_ids: Vec<&str> = config.workflow.states.iter()
300 .filter(|s| s.terminal)
301 .map(|s| s.id.as_str())
302 .collect();
303
304 let state_cfg = config.workflow.states.iter().find(|s| s.id == current_state);
305
306 if let Some(sc) = state_cfg {
307 if !sc.transitions.is_empty() {
308 return sc.transitions.iter()
309 .filter(|tr| !tr.trigger.starts_with("event:"))
310 .map(|tr| (tr.to.clone(), tr.label.clone(), tr.hint.clone()))
311 .collect();
312 }
313 }
314
315 config.workflow.states.iter()
317 .filter(|s| s.id != current_state && !terminal_ids.contains(&s.id.as_str()))
318 .map(|s| (s.id.clone(), s.label.clone(), String::new()))
319 .collect()
320}
321
322#[derive(serde::Serialize, Clone, Debug)]
323pub struct TransitionOption {
324 pub to: String,
325 pub label: String,
326 #[serde(skip_serializing_if = "Option::is_none")]
327 pub warning: Option<String>,
328}
329
330pub fn compute_valid_transitions(state: &str, config: &crate::config::Config) -> Vec<TransitionOption> {
331 config
332 .workflow
333 .states
334 .iter()
335 .find(|s| s.id == state)
336 .map(|s| {
337 s.transitions
338 .iter()
339 .map(|tr| TransitionOption {
340 to: tr.to.clone(),
341 label: if tr.label.is_empty() {
342 format!("-> {}", tr.to)
343 } else {
344 tr.label.clone()
345 },
346 warning: tr.warning.clone(),
347 })
348 .collect()
349 })
350 .unwrap_or_default()
351}
352
353fn set_merge_notes(body: &mut String, notes: &str) {
354 const SECTION: &str = "### Merge notes";
355
356 if let Some(start) = body.find(SECTION) {
358 let actual_start = if start > 0 && body.as_bytes().get(start - 1) == Some(&b'\n') {
359 start - 1
360 } else {
361 start
362 };
363 let after_header = start + SECTION.len();
364 let end = body[after_header..]
365 .find("\n##")
366 .map(|i| after_header + i)
367 .unwrap_or(body.len());
368 body.replace_range(actual_start..end, "");
369 }
370
371 let block = format!("\n{SECTION}\n\n{notes}\n");
373 if let Some(pos) = body.find("\n## History") {
374 body.insert_str(pos, &block);
375 } else {
376 body.push_str(&block);
377 }
378}
379
380pub fn append_history(body: &mut String, from: &str, to: &str, when: &str, by: &str) {
381 let row = format!("| {when} | {from} | {to} | {by} |");
382 if body.contains("## History") {
383 if !body.ends_with('\n') {
384 body.push('\n');
385 }
386 body.push_str(&row);
387 body.push('\n');
388 } else {
389 body.push_str(&format!(
390 "\n## History\n\n| When | From | To | By |\n|------|------|----|----|\n{row}\n"
391 ));
392 }
393}
394
395#[cfg(test)]
396mod tests {
397 use super::*;
398
399 fn config_with_transitions() -> crate::config::Config {
400 let toml = concat!(
401 "[project]\nname = \"test\"\n",
402 "[tickets]\ndir = \"tickets\"\n",
403 "[[workflow.states]]\n",
404 "id = \"new\"\nlabel = \"New\"\n",
405 "[[workflow.states.transitions]]\n",
406 "to = \"ready\"\nlabel = \"Mark ready\"\n",
407 "[[workflow.states.transitions]]\n",
408 "to = \"closed\"\nlabel = \"\"\n",
409 "warning = \"This will close the ticket\"\n",
410 "[[workflow.states]]\n",
411 "id = \"ready\"\nlabel = \"Ready\"\n",
412 "[[workflow.states]]\n",
413 "id = \"closed\"\nlabel = \"Closed\"\nterminal = true\n",
414 );
415 toml::from_str(toml).unwrap()
416 }
417
418 #[test]
419 fn set_merge_notes_inserts_before_history() {
420 let mut body = "## Spec\n\ncontent\n\n## History\n\n| row |".to_string();
421 set_merge_notes(&mut body, "conflict error");
422 assert!(body.contains("### Merge notes\n\nconflict error\n"));
423 let notes_pos = body.find("### Merge notes").unwrap();
424 let hist_pos = body.find("## History").unwrap();
425 assert!(notes_pos < hist_pos);
426 }
427
428 #[test]
429 fn set_merge_notes_appends_when_no_history() {
430 let mut body = "## Spec\n\ncontent".to_string();
431 set_merge_notes(&mut body, "error msg");
432 assert!(body.contains("### Merge notes\n\nerror msg\n"));
433 }
434
435 #[test]
436 fn set_merge_notes_overwrites_existing_section() {
437 let mut body = "## Spec\n\n### Merge notes\n\nold error\n\n## History\n\n| row |".to_string();
438 set_merge_notes(&mut body, "new error");
439 assert!(body.contains("### Merge notes\n\nnew error\n"));
440 assert!(!body.contains("old error"));
441 let notes_pos = body.find("### Merge notes").unwrap();
442 let hist_pos = body.find("## History").unwrap();
443 assert!(notes_pos < hist_pos);
444 }
445
446 #[test]
447 fn compute_valid_transitions_returns_expected_options() {
448 let config = config_with_transitions();
449 let opts = compute_valid_transitions("new", &config);
450 assert_eq!(opts.len(), 2);
451 assert_eq!(opts[0].to, "ready");
452 assert_eq!(opts[0].label, "Mark ready");
453 assert!(opts[0].warning.is_none());
454 assert_eq!(opts[1].to, "closed");
455 assert_eq!(opts[1].label, "-> closed");
456 assert_eq!(opts[1].warning.as_deref(), Some("This will close the ticket"));
457 }
458
459 #[test]
460 fn compute_valid_transitions_unknown_state_returns_empty() {
461 let config = config_with_transitions();
462 let opts = compute_valid_transitions("nonexistent", &config);
463 assert!(opts.is_empty());
464 }
465}