tedi 0.17.8

Personal productivity CLI for task tracking, time management, and GitHub issue integration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
use clap::Args;
use color_eyre::eyre::{Report, Result, bail, eyre};
use jiff::Timestamp;
use tedi_adapters::github::GithubMilestone;
use tedi_core::RepoInfo;
use tedi_task_operations::{
	IssueLink, MilestoneLink, TaskView,
	clockify_tracking::{HaltArgs, ResumeArgs},
	mv::move_issues,
	open_interactions::SyncMode,
	search::SearchArgs,
	sprints::{expand_and_refresh, materialize_new_tasks, sync_embedded_issue_changes, sync_milestone_changes},
};
use tedi_utils::search::SearchKind;
use v_utils::{Timeframe, TimeframeDesignator};

use crate::config::LiveSettings;

#[derive(clap::Subcommand)]
pub enum SprintsCommands {
	Get {
		sprint: SprintRef,
	},
	/// Edit a sprint (milestone description, or the local urgent list) in your $EDITOR
	Edit {
		sprint: SprintRef,
	},
	/// Ensures all milestones up to date, if yes - writes "OK" to $XDG_DATA_HOME/todo/healthcheck.status
	/// Can get outdated easily, so printed output of the command is prepended with the filename
	Healthcheck,
	/// Change the active sprint's selected issue (circular with --up/--down, tree descent
	/// with --in/--out, history with --prev/--next, else search over the whole reachable tree)
	Select {
		pattern: Option<String>,
		#[command(flatten)]
		search: SearchArgs,
		/// Forward in the selection history
		#[arg(long, short)]
		next: bool,
		/// Back in the selection history
		#[arg(long, short)]
		prev: bool,
		#[arg(long, short)]
		/// Go to issue above currently selected in the main Sprint
		up: bool,
		#[arg(long, short)]
		/// Go to issue below currently selected in the main Sprint
		down: bool,
		/// Descend into the selected milestone (its top workable issue) or issue (its top open child)
		#[arg(long = "in", short = 'i')]
		enter: bool,
		/// Ascend one level in the selection path
		#[arg(long, short)]
		out: bool,
		/// Reset to the top item of the sprint
		#[arg(long, short)]
		top: bool,
	},
	/// Operate on the selected issue in the active sprint
	Selected {
		#[command(subcommand)]
		op: SelectedOp,
	},
	/// Build a task view of the open local issues matching a query, best first
	Search {
		query: String,
		#[command(flatten)]
		search: SearchArgs,
	},
}
#[derive(clap::Subcommand)]
pub enum SelectedOp {
	/// Open the selected issue file in $EDITOR
	Open,
	/// Print the sprint's `# Must` strip and day completion, then the selected issue's blockers
	List {
		/// Emit Pango markup (for eww labels) instead of ANSI color.
		#[arg(long)]
		markup: bool,
	},
	/// Compactly show the current blocker
	Current {
		/// Emit Pango markup (for eww labels), suffixed with a Clockify-tracking dot:
		/// blue active, white paused, red tracking-elsewhere.
		#[arg(long)]
		markup: bool,
	},
	/// Append a blocker to the selected issue
	Add {
		text: String,
		/// Nest as a child of the current deepest blocker
		#[arg(short = 'n', long)]
		nest: bool,
	},
	/// Pop the current blocker (repeat `-p` to also pop ancestors)
	Pop {
		#[arg(short = 'p', long = "parent", action = clap::ArgAction::Count)]
		parents: u8,
	},
	/// Replace the current blocker in-place
	Set { text: String },
	/// Start a Clockify timer on the selected issue
	Resume(ResumeArgs),
	/// Stop the Clockify timer
	Halt(HaltArgs),
}
#[derive(Args)]
pub struct SprintsArgs {
	#[command(subcommand)]
	command: SprintsCommands,
}
/// A sprint designator: a milestone timeframe, or the local urgent list.
#[derive(Clone)]
pub enum SprintRef {
	Urgent,
	Tf(Timeframe),
}
impl std::str::FromStr for SprintRef {
	type Err = Report;

	fn from_str(s: &str) -> Result<Self> {
		match s {
			"urgent" => Ok(Self::Urgent),
			_ => s.parse().map(Self::Tf),
		}
	}
}

pub static HEALTHCHECK_REL_PATH: &str = "healthcheck.status";
pub static SPRINT_HEADER_REL_PATH: &str = "sprint_header.md";

pub async fn sprints_command(settings: &LiveSettings, args: SprintsArgs, mock: Option<tedi_task_operations::MockType>, mode: SyncMode) -> Result<()> {
	use tedi_task_operations::sprints as ops;

	let yes = || settings.config().map(|c| c.yes).unwrap_or(false);
	match args.command {
		SprintsCommands::Get { sprint } => {
			let raw = match sprint {
				SprintRef::Urgent => match std::fs::read_to_string(tedi_task_operations::selection::urgent_path()) {
					Ok(c) => c,
					Err(e) if e.kind() == std::io::ErrorKind::NotFound => bail!("No urgent sprint. Create one with `sprints edit urgent`."),
					Err(e) => return Err(e.into()),
				},
				SprintRef::Tf(tf) => {
					let retrieved_milestones = request_milestones(settings).await?;
					let raw = get_milestone(tf, &retrieved_milestones)?;
					refresh_sprint_milestones(&raw).await;
					raw
				}
			};
			// read-only print: not worth a round-trip per referenced issue
			let expanded = expand_and_refresh(&raw, false).await?;
			println!("{expanded}");
			Ok(())
		}
		SprintsCommands::Edit { sprint } => match sprint {
			SprintRef::Urgent => edit_urgent(mode).await,
			SprintRef::Tf(tf) => edit_milestone(settings, tf, mode, mock.is_some()).await,
		},
		SprintsCommands::Healthcheck => healthcheck(settings).await,
		SprintsCommands::Select {
			pattern,
			search,
			next,
			prev,
			up,
			down,
			enter,
			out,
			top,
		} => {
			// A bare timeframe (`sprints select 1d`) focuses that sprint precision; anything else
			// is an issue pattern within the currently-active sprint. The alpha-designator guard
			// keeps numeric issue patterns (`select 2`) from parsing as a timeframe.
			if mode != SyncMode::Offline
				&& !next && !prev
				&& !up && !down
				&& !enter && !out
				&& !top && let Some(p) = pattern.as_deref()
				&& p.chars().any(|c| c.is_ascii_alphabetic())
				&& let Ok(tf) = p.parse::<Timeframe>()
			{
				focus_sprint(settings, tf, yes()).await
			} else {
				ensure_selection_cache(settings, mode).await?;
				ops::select(pattern, SearchKind::try_from(search)?, next, prev, up, down, enter, out, top, yes()).await
			}
		}
		SprintsCommands::Selected { op } => {
			ensure_selection_cache(settings, mode).await?;
			match op {
				SelectedOp::Open => ops::selected_open(mode, yes()).await,
				SelectedOp::List { markup } => ops::selected_list(markup),
				SelectedOp::Current { markup } => ops::selected_current(markup),
				SelectedOp::Add { text, nest } => ops::selected_add(text, nest, mode, yes()).await,
				SelectedOp::Pop { parents } => ops::selected_pop(parents as usize, mode, yes()).await,
				SelectedOp::Set { text } => ops::selected_set(text, mode, yes()).await,
				SelectedOp::Resume(resume_args) => ops::selected_resume(resume_args, yes()).await,
				SelectedOp::Halt(halt_args) => ops::selected_halt(halt_args).await,
			}
		}
		SprintsCommands::Search { query, search } => ops::search(&query, SearchKind::try_from(search)?).await,
	}
}

/// Refresh the milestone-content cache for every milestone ref in `content` (best-effort:
/// select ops serve stale cache; freshness is bounded by the fetching commands).
async fn refresh_sprint_milestones(content: &str) {
	let links = TaskView::parse(content).milestone_links();
	if links.is_empty() {
		return;
	}
	if let Err(e) = tedi_task_operations::sprints::refresh_milestone_cache(&links).await {
		tracing::warn!("failed to refresh milestone cache: {e}");
		eprintln!("warning: failed to refresh milestone cache: {e}");
	}
}

/// Ensure an active sprint is resolvable for selection. Urgent (a local file) needs nothing;
/// otherwise, when cold and online, fetch the lowest normal sprint (`blocker_tf`) into the cache.
/// When online, also fetch any milestone in the active view missing from the milestone cache.
/// Only what is missing locally is fetched, so `--sync-on-exit` reaches it too.
async fn ensure_selection_cache(settings: &LiveSettings, mode: SyncMode) -> Result<()> {
	let offline = mode == SyncMode::Offline;
	if !offline {
		let missing = tedi_task_operations::selection::Selected::uncached_active_milestones();
		if !missing.is_empty()
			&& let Err(e) = tedi_task_operations::sprints::refresh_milestone_cache(&missing).await
		{
			tracing::warn!("failed to refresh milestone cache: {e}");
			eprintln!("warning: failed to refresh milestone cache: {e}");
		}
	}
	if offline || tedi_task_operations::selection::Selected::active_ready() {
		return Ok(());
	}
	let config = settings.config()?;
	let blocker_tf = config.milestones.as_ref().map(|m| m.blocker_tf()).unwrap_or("1d").to_string();
	let milestones = request_milestones(settings).await?;
	let desc = milestones
		.iter()
		.find(|m| m.title == blocker_tf)
		.and_then(|m| m.description.clone())
		.ok_or_else(|| eyre!("No `{blocker_tf}` sprint on GitHub yet. Add issues to the '{blocker_tf}' milestone (or create an urgent list)."))?;
	tedi_task_operations::sprints::refresh_selection_cache(&blocker_tf, &desc);
	refresh_sprint_milestones(&desc).await;
	Ok(())
}

/// `sprints select <tf>` — focus a sprint precision: cache its content and show its selection
/// (persisted, or auto-set to the top open issue).
async fn focus_sprint(settings: &LiveSettings, tf: Timeframe, yes: bool) -> Result<()> {
	let milestones = request_milestones(settings).await?;
	let desc = milestones
		.iter()
		.find(|m| m.title == tf.to_string())
		.and_then(|m| m.description.clone())
		.ok_or_else(|| eyre!("Sprint '{tf}' not found on GitHub (or it has no description)."))?;
	tedi_task_operations::sprints::refresh_selection_cache(&tf.to_string(), &desc);
	refresh_sprint_milestones(&desc).await;
	tedi_task_operations::sprints::selected_show(yes).await
}
async fn request_milestones(settings: &LiveSettings) -> Result<Vec<GithubMilestone>> {
	let config = settings.config()?;
	let milestones_config = config
		.milestones
		.as_ref()
		.ok_or_else(|| eyre!("milestones config section is required. Add [milestones] section with url to your config"))?;
	let (owner, repo) = parse_github_repo(&milestones_config.url)?;
	let client = tedi_adapters::github::client::get()?;
	Ok(client.list_milestones(RepoInfo::new(&owner, &repo)).await?)
}

/// Parse owner and repo from various Github URL formats
/// Supports: "owner/repo", "https://github.com/owner/repo", "git@github.com:owner/repo.git", etc.
fn parse_github_repo(url: &str) -> Result<(String, String)> {
	let url = url.trim();

	// Handle "owner/repo" format directly
	if !url.contains(':') && !url.contains("//") {
		let parts: Vec<&str> = url.split('/').collect();
		if parts.len() == 2 {
			return Ok((parts[0].to_string(), parts[1].trim_end_matches(".git").to_string()));
		}
	}

	// Handle URL formats
	let sections: Vec<&str> = url.split('/').collect();
	if sections.len() >= 2 {
		let owner = sections[sections.len() - 2];
		let repo = sections[sections.len() - 1].trim_end_matches(".git");

		// For SSH format (git@github.com:owner/repo), owner might contain ':'
		let owner = if owner.contains(':') { owner.split(':').next_back().unwrap_or(owner) } else { owner };

		return Ok((owner.to_string(), repo.to_string()));
	}

	Err(eyre!("Could not parse Github repo from URL: {url}"))
}

#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("Error on `{requested_tf}` milestone: {source}")]
struct GetMilestoneError {
	requested_tf: Timeframe,
	#[source]
	source: MilestoneError,
}

#[derive(Clone, Debug, PartialEq, thiserror::Error)]
enum MilestoneError {
	#[error("Milestone is missing due_on date")]
	MissingDueOn,

	#[error("Milestone is outdated (due_on: {due_on}). Try moving it to a later date.")]
	MilestoneOutdated { due_on: Timestamp },

	#[error("Requested milestone on minute-designated timeframe (`m`). You likely meant to request Monthly (`M`).")]
	MinuteMilestone,

	#[error("Milestone not found. Here are all the existing milestones:\n{existing_milestones:?}")]
	MilestoneNotFound { existing_milestones: Vec<String> },

	#[error("Missing description")]
	MissingDescription,
}

fn get_milestone(tf: Timeframe, retrieved_milestones: &[GithubMilestone]) -> Result<String, GetMilestoneError> {
	if tf.designator() == TimeframeDesignator::Minutes {
		return Err(GetMilestoneError {
			requested_tf: tf,
			source: MilestoneError::MinuteMilestone,
		});
	}

	match retrieved_milestones.iter().find(|m| m.title == tf.to_string()) {
		Some(milestone) => {
			let due_on = milestone.due_on.as_ref().ok_or(GetMilestoneError {
				requested_tf: tf,
				source: MilestoneError::MissingDueOn,
			})?;

			if *due_on + tedi_eval::same_day_buffer() < Timestamp::now() {
				return Err(GetMilestoneError {
					requested_tf: tf,
					source: MilestoneError::MilestoneOutdated { due_on: *due_on },
				});
			}

			match milestone.description.clone() {
				Some(description) => Ok(description),
				None => Err(GetMilestoneError {
					requested_tf: tf,
					source: MilestoneError::MissingDescription,
				}),
			}
		}
		None => {
			let milestone_titles = retrieved_milestones.iter().map(|m| m.title.clone()).collect::<Vec<String>>();
			Err(GetMilestoneError {
				requested_tf: tf,
				source: MilestoneError::MilestoneNotFound {
					existing_milestones: milestone_titles,
				},
			})
		}
	}
}

static KEY_MILESTONES: [Timeframe; 6] = [
	Timeframe::from_naive(1, TimeframeDesignator::Days),
	Timeframe::from_naive(2, TimeframeDesignator::Weeks),
	Timeframe::from_naive(1, TimeframeDesignator::Quarters),
	Timeframe::from_naive(1, TimeframeDesignator::Years),
	Timeframe::from_naive(3, TimeframeDesignator::Years),
	Timeframe::from_naive(7, TimeframeDesignator::Years),
];

async fn healthcheck(settings: &LiveSettings) -> Result<()> {
	use std::fs;

	let healthcheck_path = v_utils::xdg_data_file!(HEALTHCHECK_REL_PATH);

	let retrieved_milestones = request_milestones(settings).await?;
	let results = KEY_MILESTONES
		.iter()
		.map(|tf| get_milestone(*tf, &retrieved_milestones))
		.collect::<Vec<Result<String, GetMilestoneError>>>();
	{
		let mut health = String::new();
		for result in &results {
			match result {
				Ok(_) => {}
				Err(e) => {
					if !health.is_empty() {
						health.push('\n');
					}
					health.push_str(&e.to_string());
				}
			}
		}

		if health.is_empty() {
			health = "OK".to_string();
		}
		println!("{}\n{health}", healthcheck_path.display());

		fs::write(healthcheck_path, health).unwrap();
	}

	{
		let sprint_ms =
			&<std::result::Result<std::string::String, GetMilestoneError> as Clone>::clone(&results[1]).map_err(|e| eyre!("Couldn't parse 2w milestone which MUST be defined: {e}"))?;
		let sprint_header = sprint_ms
			.lines()
			.next()
			.ok_or_else(|| eyre!("2w milestone does not have a description. MUST have a description."))?;
		if !sprint_header.starts_with("# ") {
			eprintln!("2w milestone description does not start with a header. It SHOULD start with '# '.");
		}
		fs::write(v_utils::xdg_data_file!(SPRINT_HEADER_REL_PATH), sprint_header).unwrap();
	}

	// Cache the blocker timeframe milestone for blocker commands
	cache_blocker_milestone(settings, &retrieved_milestones).await;

	Ok(())
}

/// Cache the blocker timeframe milestone description for synchronous blocker commands,
/// plus the contents of any milestone it references.
async fn cache_blocker_milestone(settings: &LiveSettings, milestones: &[GithubMilestone]) {
	let config = match settings.config() {
		Ok(c) => c,
		Err(_) => return,
	};
	let blocker_tf = config.milestones.as_ref().map(|m| m.blocker_tf()).unwrap_or("1d");

	if let Some(ms) = milestones.iter().find(|m| m.title == blocker_tf)
		&& let Some(ref desc) = ms.description
	{
		tedi_task_operations::sprints::refresh_selection_cache(blocker_tf, desc);
		refresh_sprint_milestones(desc).await;
	}
}

/// Edit the local urgent list (creating it if absent). Same expand/sync/collapse cycle as
/// milestones, but the storage is `urgent_path()` — no GitHub involved.
async fn edit_urgent(mode: SyncMode) -> Result<()> {
	use std::fs;

	let _lock = tedi_task_operations::selection::lock_sprint(tedi_task_operations::selection::URGENT_KEY)?;

	let path = tedi_task_operations::selection::urgent_path();
	let original = match fs::read_to_string(&path) {
		Ok(c) => c,
		Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
		Err(e) => return Err(e.into()),
	};
	let expanded = expand_and_refresh(&original, mode == SyncMode::Full).await?;

	let tmp_path = tempfile::tempdir()?.keep().join("milestone_urgent.md");
	fs::write(&tmp_path, &expanded)?;
	eprintln!("[milestone] tmp_path: {}", tmp_path.display());

	tedi_task_operations::utils::open_file(&tmp_path, None).await?;
	let _syncing = v_utils::io::Spinner::start(); // until the edit is synced

	let raw = fs::read_to_string(&tmp_path)?;
	if raw == expanded {
		sync_embedded_issue_changes(&raw, mode).await?; // an issue a killed run left unsynced has nothing else to carry it
		println!("No changes made to urgent sprint");
		return Ok(());
	}
	let (edited_content, moves) = match take_moves(&raw, mode) {
		Ok(taken) => taken,
		Err(e) => return dump_rejected(&raw, e),
	};

	let mut edited_doc = TaskView::parse(&edited_content);
	// urgent is local-only: milestone refs live on GitHub and have no meaning here
	let milestone_links = edited_doc.milestone_links();
	if !milestone_links.is_empty() {
		return dump_rejected(
			&raw,
			eyre!(
				"urgent sprint cannot contain milestone refs: {}",
				milestone_links.iter().map(|l| l.as_str()).collect::<Vec<_>>().join(", ")
			),
		);
	}

	if let Err(e) = sync_embedded_issue_changes(&edited_content, mode).await {
		return dump_rejected(&raw, e);
	}
	if !moves.is_empty() {
		match move_issues(&moves, None, mode).await {
			Ok(moved) => edited_doc.relink(&moved),
			Err(e) => return dump_rejected(&raw, e),
		}
	}

	if let Err(e) = materialize_new_tasks(&mut edited_doc, None, mode).await {
		return dump_rejected(&raw, e);
	}

	edited_doc.collapse_to_links();
	edited_doc.remove_issue_links(&tedi_task_operations::selection::closed_links(&edited_doc)); // an issue closed in the buffer leaves urgent with the same save
	let stored = edited_doc.serialize();
	// urgent is section-less by design (ARCHITECTURE.md); a header here is inert, not an error
	let headers: Vec<&str> = stored.lines().filter(|l| l.starts_with('#')).collect();
	if !headers.is_empty() {
		eprintln!("warning: urgent is a flat list — these headers carry no meaning in it: {}", headers.join(", "));
	}

	if stored.trim().is_empty() {
		if path.exists() {
			fs::remove_file(&path)?;
		}
		println!("Urgent sprint is empty; removed");
		return Ok(());
	}
	fs::create_dir_all(path.parent().expect("urgent_path is always nested under data dir"))?;
	fs::write(&path, stored)?;
	println!("Updated urgent sprint");
	Ok(())
}

async fn edit_milestone(settings: &LiveSettings, tf: Timeframe, mode: SyncMode, mock: bool) -> Result<()> {
	use std::fs;

	use tedi_task_operations::{
		MilestoneBody,
		local::{FsReader, Local},
		open_interactions::{MergeMode, MilestoneModifier, SyncOptions, modify_and_sync_milestone, pull_milestone},
		remote::load_remote_milestone,
	};

	let _lock = tedi_task_operations::selection::lock_sprint(&tf.to_string())?;

	// GitHub unreachable → degrade the whole run to offline: every edit persists to LocalFs as a
	// divergence from Consensus, reconciled by the next online sync of it.
	let mode = match mode == SyncMode::Full && !mock && !tedi_adapters::github::reachable().await {
		true => SyncMode::Offline,
		false => mode,
	};

	// The {app}_MOCK_MILESTONE file shortcut (existing mock tests) bypasses the client + three-way model.
	if let Ok(mock_milestone_path) = std::env::var(concat!(env!("CARGO_PKG_NAME"), "_MOCK_MILESTONE")) {
		return edit_milestone_mock_file(&mock_milestone_path, tf, mode).await;
	}

	let (owner, repo) = milestone_repo(settings)?;
	let repo_info = RepoInfo::new(&owner, &repo);
	let cached_number = || {
		Local::load_milestone_project_meta(repo_info, &FsReader)
			.milestones
			.iter()
			.find(|(_, m)| m.title == tf.to_string())
			.map(|(n, _)| *n)
	};
	let number = match (mode, cached_number()) {
		(SyncMode::OnExit | SyncMode::Offline, Some(n)) => n,
		(SyncMode::Offline, None) => bail!("Cannot edit '{tf}' offline — it was never fetched while online (no local milestone cache)."),
		(SyncMode::Full, _) | (SyncMode::OnExit, None) => {
			let retrieved = request_milestones(settings).await?;
			retrieved.iter().find(|m| m.title == tf.to_string()).map(|m| m.number).ok_or_else(|| {
				let existing = retrieved.iter().map(|m| m.title.clone()).collect::<Vec<_>>();
				eyre!("Milestone '{tf}' not found. Existing milestones: {existing:?}")
			})?
		}
	};
	let link = MilestoneLink::parse(&format!("https://github.com/{owner}/{repo}/milestone/{number}")).expect("well-formed milestone url");

	// Local-first load (mirrors `sync_milestone_changes`): a diverged local body seeds the editor so a
	// prior deferred edit stays visible and is preserved in the new body. Remote only when never cached.
	let mut milestone = match Local::load_milestone(&link, &FsReader)? {
		Some(m) => m,
		None if mode == SyncMode::Offline => bail!("Cannot edit '{tf}' offline — it was never fetched while online (no local milestone cache)."),
		None => load_remote_milestone(&link).await?,
	};
	// The buffer is what the edit is reasoned against, so reconcile before rendering it — not on the
	// way out, where whatever Github gained since would already have been typed over.
	match mode {
		SyncMode::Full => {
			pull_milestone(&mut milestone, MergeMode::Normal).await?;
			refresh_sprint_milestones(&milestone.to_string()).await;
		}
		SyncMode::OnExit =>
			if let Some(conflict_file) = tedi_task_operations::conflict_resolve::check_for_existing_milestone_conflict(&link).await? {
				bail!("Unresolved milestone conflict in {}. Resolve with git tools, then re-run.", conflict_file.display());
			},
		SyncMode::Offline => {}
	}
	let milestone_number = milestone.number();
	let original_description = milestone.to_string();

	let expanded_description = expand_and_refresh(&original_description, mode == SyncMode::Full).await?;

	// Use keep() so the temp file survives panics/errors.
	let tmp_path = tempfile::tempdir()?.keep().join(format!("milestone_{tf}.md"));
	fs::write(&tmp_path, &expanded_description)?;
	eprintln!("[milestone] tmp_path: {}", tmp_path.display());

	tedi_task_operations::utils::open_file(&tmp_path, None).await?;
	let _syncing = v_utils::io::Spinner::start(); // until the edit is synced

	let mode = match mode == SyncMode::OnExit && !mock && !tedi_adapters::github::reachable().await {
		true => SyncMode::Offline,
		false => mode,
	};

	let raw = fs::read_to_string(&tmp_path)?;
	// Compare against expanded (not original) — expansion itself is not a user edit.
	let changed = raw != expanded_description;
	let (edited_content, moves) = match take_moves(&raw, mode) {
		Ok(taken) => taken,
		Err(e) => return dump_rejected(&raw, e),
	};

	let mut edited_doc = TaskView::parse(&edited_content);
	// Unchanged too: an issue a killed run left unsynced has nothing else to carry it.
	if let Err(e) = sync_embedded_issue_changes(&edited_content, mode).await {
		// Transient GitHub errors are retried, probed to offline, or deferred at the sync boundary,
		// so a bail reaching here is a genuine non-transient parse/logic failure.
		return dump_rejected(&raw, e);
	}
	let moved = match moves.is_empty() {
		true => Default::default(),
		false => match move_issues(&moves, Some(&link), mode).await {
			Ok(moved) => moved,
			Err(e) => return dump_rejected(&raw, e),
		},
	};
	edited_doc.relink(&moved);
	if changed {
		// Top-level new tasks belong to this milestone → materialize as real issues in the milestones repo.
		if let Err(e) = materialize_new_tasks(&mut edited_doc, Some(link.clone()), mode).await {
			return dump_rejected(&raw, e);
		}
		// Persist edits inside inlined milestone blocks (incl. materialized tasks) to their own nodes.
		if let Err(e) = sync_milestone_changes(&edited_doc, mode).await {
			return dump_rejected(&raw, e);
		}
		edited_doc.collapse_to_links();
	}

	// No editor change → reuse the loaded body verbatim (so `collapse(expand(x)) != x` formatting jitter
	// can't spuriously push); the sync below still reflushes any prior divergence.
	let new_body = if changed {
		MilestoneBody::parse(&edited_doc.serialize(), milestone.identity.link.repo_info())
	} else {
		milestone.body.clone()
	};

	// Sync issue↔milestone assignments (incl. unassignments, which the set-union merge can't express).
	// Best-effort: a failure is reconciled on the next online edit rather than throwing hands.
	if mode != SyncMode::Offline && changed {
		let mut orig_doc = TaskView::parse(&original_description);
		orig_doc.resolve_bare_refs(None);
		orig_doc.relink(&moved); // a moved issue left for another repo, not this milestone
		let old_links = orig_doc.issue_links();
		let new_links = new_body.0.issue_links();
		if let Err(e) = sync_milestone_assignments(settings, milestone_number, &old_links, &new_links).await {
			tracing::warn!("failed to sync milestone assignments (will reconcile next online edit): {e}");
			eprintln!("warning: failed to sync milestone assignments: {e}");
		}
	}

	// Route the top-level body through the three-way model: apply the new body, then sink to
	// LocalFs + Consensus (+ Remote when online).
	let mut milestone = modify_and_sync_milestone(milestone, mode, MilestoneModifier::BodyWrite { body: new_body }, SyncOptions::default()).await?;

	// Outdated milestones get a due-date bump + an archived snapshot. Direct API, online only, best-effort.
	// Read off the synced due date: another machine may have bumped it already.
	let is_outdated = milestone.identity.due_on.map(|d| d + tedi_eval::same_day_buffer() < Timestamp::now()).unwrap_or(true);
	if mode != SyncMode::Offline && is_outdated {
		let new_date = Timestamp::now() + tf.duration();
		println!("Milestone was outdated, updating due date to {}", new_date.strftime("%Y-%m-%d"));
		let archive_title = format!("{}_{tf}", Timestamp::now().strftime("%Y/%m/%d"));
		let description = milestone.to_string();
		let (update_result, archive_result) = tokio::join!(
			update_milestone(settings, milestone_number, &description, Some(new_date)),
			create_closed_milestone(settings, &archive_title, &original_description)
		);
		if let Err(e) = update_result {
			tracing::warn!("failed to bump milestone due date (will reconcile next online edit): {e}");
		}
		match archive_result {
			Err(e) => tracing::warn!("Failed to archive old milestone contents (its closed issues stay until the next rollover): {e}"),
			Ok(()) => {
				// an issue closed within this edit is in no archive yet
				let archived = MilestoneBody::parse(&original_description, link.repo_info()).hosted();
				let pruned: Vec<IssueLink> = tedi_task_operations::selection::closed_links(&milestone.body.0)
					.into_iter()
					.filter(|l| archived.contains(l))
					.collect();
				if !pruned.is_empty() {
					let mut body = milestone.body.clone();
					body.0.remove_issue_links(&pruned);
					milestone = modify_and_sync_milestone(milestone, mode, MilestoneModifier::BodyWrite { body }, SyncOptions::default()).await?;
				}
			}
		}
	}

	let blocker_tf = settings.config()?.milestones.as_ref().map(|m| m.blocker_tf().to_string()).unwrap_or_else(|| "1d".to_string());
	if tf.to_string() == blocker_tf {
		tedi_task_operations::sprints::refresh_selection_cache(&blocker_tf, &milestone.to_string());
	}

	println!("Updated milestone '{tf}'");

	// The edit is already saved above; the trailing healthcheck is informational. It hard-requires the
	// `2w` sprint, so never let its absence abort a completed edit and make it read as discarded.
	if mode != SyncMode::Offline
		&& let Err(e) = healthcheck(settings).await
	{
		tracing::warn!("post-edit healthcheck failed (your edit was already saved): {e}");
		eprintln!("warning: post-edit healthcheck failed (your edit was already saved): {e}");
	}

	Ok(())
}

/// Cut the `!mv` requests out of an edited buffer; GitHub must be reachable to carry any of them.
fn take_moves(buffer: &str, mode: SyncMode) -> Result<(String, Vec<(IssueLink, RepoInfo)>)> {
	let (rest, moves) = tedi_core::take_moves(buffer)?;
	if mode == SyncMode::Offline && !moves.is_empty() {
		bail!("`!mv` needs GitHub, and this edit runs offline");
	}
	Ok((rest, moves))
}

/// Persist an editor buffer that failed a genuine (non-transient) sync/parse, and surface the path.
fn dump_rejected(edited_content: &str, e: Report) -> Result<()> {
	tedi_task_operations::utils::persist_rejected_changes(edited_content)?;
	eprintln!("Your changes were saved to /tmp/tedi/rejected-changes.md — you can recover them from there.");
	Err(e)
}

/// The {app}_MOCK_MILESTONE file shortcut: read/edit/write the milestone body from a plain file,
/// bypassing the client and the three-way model. Used by the simplest mock integration tests.
async fn edit_milestone_mock_file(mock_milestone_path: &str, tf: Timeframe, mode: SyncMode) -> Result<()> {
	use std::fs;

	let original_description = fs::read_to_string(mock_milestone_path)?;
	let expanded_description = expand_and_refresh(&original_description, false).await?;

	let tmp_path = tempfile::tempdir()?.keep().join(format!("milestone_{tf}.md"));
	fs::write(&tmp_path, &expanded_description)?;
	eprintln!("[milestone] tmp_path: {}", tmp_path.display());

	tedi_task_operations::utils::open_file(&tmp_path, None).await?;

	let edited_content = fs::read_to_string(&tmp_path)?;
	if edited_content == expanded_description {
		println!("No changes made to milestone '{tf}'");
		return Ok(());
	}

	if let Err(e) = sync_embedded_issue_changes(&edited_content, mode).await {
		return dump_rejected(&edited_content, e);
	}
	let mut edited_doc = TaskView::parse(&edited_content);
	if let Err(e) = materialize_new_tasks(&mut edited_doc, None, mode).await {
		return dump_rejected(&edited_content, e);
	}
	// Mock file mode never reaches the network.
	if let Err(e) = sync_milestone_changes(&edited_doc, SyncMode::Offline).await {
		return dump_rejected(&edited_content, e);
	}

	edited_doc.collapse_to_links();
	fs::write(mock_milestone_path, edited_doc.serialize())?;
	println!("Updated milestone '{tf}'");
	Ok(())
}

async fn update_milestone(settings: &LiveSettings, milestone_number: u64, description: &str, due_on: Option<Timestamp>) -> Result<()> {
	let (owner, repo) = milestone_repo(settings)?;
	let client = tedi_adapters::github::client::get()?;
	client.update_milestone(RepoInfo::new(&owner, &repo), milestone_number, description, due_on).await?;
	Ok(())
}

/// Creates a new milestone with the given title, description, and immediately closes it
async fn create_closed_milestone(settings: &LiveSettings, title: &str, description: &str) -> Result<()> {
	let (owner, repo) = milestone_repo(settings)?;
	let client = tedi_adapters::github::client::get()?;
	client.create_milestone(RepoInfo::new(&owner, &repo), title, description, true).await?;
	Ok(())
}

/// Resolve the (owner, repo) of the milestones repository from config.
fn milestone_repo(settings: &LiveSettings) -> Result<(String, String)> {
	let config = settings.config()?;
	let milestones_config = config.milestones.as_ref().ok_or_else(|| eyre!("milestones config section is required"))?;
	parse_github_repo(&milestones_config.url)
}

/// Sync milestone assignments on GitHub.
///
/// Compares issue links in old vs new description, then:
/// - Assigns newly added issues to the milestone
/// - Unassigns removed issues from the milestone
/// Only operates on issues in the same repo as the milestone.
async fn sync_milestone_assignments(settings: &LiveSettings, milestone_number: u64, old_links: &[IssueLink], new_links: &[IssueLink]) -> Result<()> {
	use std::collections::HashSet;

	let config = settings.config()?;
	let milestones_config = config.milestones.as_ref().ok_or_else(|| eyre!("milestones config section is required"))?;
	let (ms_owner, ms_repo) = parse_github_repo(&milestones_config.url)?;

	let ms_repo_info: tedi_core::RepoInfo = (ms_owner.as_str(), ms_repo.as_str()).into();
	let old_numbers: HashSet<u64> = old_links.iter().filter(|l| l.project() == ms_repo_info).map(|l| l.number()).collect();
	let new_numbers: HashSet<u64> = new_links.iter().filter(|l| l.project() == ms_repo_info).map(|l| l.number()).collect();

	let to_assign: Vec<u64> = new_numbers.difference(&old_numbers).copied().collect();
	let to_unassign: Vec<u64> = old_numbers.difference(&new_numbers).copied().collect();

	if to_assign.is_empty() && to_unassign.is_empty() {
		return Ok(());
	}

	let client = tedi_adapters::github::client::get()?;
	let repo = tedi_core::RepoInfo::new(&ms_owner, &ms_repo);

	let mut futs = Vec::new();
	for num in &to_assign {
		println!("Assigning #{num} to milestone");
		futs.push(client.set_issue_milestone(repo, *num, Some(milestone_number)));
	}
	for num in &to_unassign {
		println!("Unassigning #{num} from milestone");
		futs.push(client.set_issue_milestone(repo, *num, None));
	}
	for fut in futs {
		fut.await?;
	}

	Ok(())
}