tedi 0.16.3

Personal productivity CLI for task tracking, time management, and GitHub issue integration
Documentation
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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! Integration tests for sync conflict resolution.
//!
//! Tests the consensus-based sync logic where:
//! - Git commit state = last synced truth (consensus)
//! - Only conflict if BOTH local and remote changed since last sync
//! - Single-side changes auto-resolve
//!
//! Tests work with `VirtualIssue` for setup, converting to `Issue` through
//! the test context methods. The mock Github layer translates to API format at the boundary.
//!
//! ## Timestamp Seeds
//!
//! Each test uses unique seed values to ensure variety. Higher seed = newer timestamp = wins in merge.
//! Seeds are chosen to be either:
//! - Close together (e.g., 100 vs 105): tests edge cases where timestamps are similar
//! - Far apart (e.g., 50 vs 200): guarantees one side dominates
//!
//! ## Snapshot Testing
//!
//! Tests use insta snapshots to capture the resulting directory state.
//! The `.meta.json` file contains actual timestamps from seed-based generation,
//! so snapshots verify both file content and timestamp values.

use insta::assert_snapshot;
use rstest::rstest;
use v_fixtures::FixtureRenderer;

use crate::common::{
	FixtureIssuesExt, Seed, TestContext,
	are_you_sure::{UnsafePathExt, read_issue_file, write_to_path},
	parse_virtual, render_fixture,
};

/// Fixture for tests where consensus, local, and remote all have different bodies.
/// The key difference between these tests is the seed values, which determine timestamps
/// and therefore which side "wins" the merge.
struct DivergedBodiesFixture {
	ctx: TestContext,
	local: tedi::Issue,
}

impl DivergedBodiesFixture {
	async fn new(consensus_seed: i64, local_seed: i64, remote_seed: i64) -> Self {
		let ctx = TestContext::build_with_preexisting_state_unsafe("");

		let consensus_vi = parse_virtual(
			r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  consensus body
"#,
		);
		let local_vi = parse_virtual(
			r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  local body
"#,
		);
		let remote_vi = parse_virtual(
			r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  remote changed body
"#,
		);

		ctx.consensus(&consensus_vi, Some(Seed::new(consensus_seed))).await;
		let local = ctx.local(&local_vi, Some(Seed::new(local_seed))).await;
		ctx.remote(&remote_vi, Some(Seed::new(remote_seed)));

		Self { ctx, local }
	}
}

/// Tests that different timestamp seeds lead to different merge winners.
/// - remote_wins: seeds cause remote timestamps to win
/// - local_wins: seeds cause local timestamps to win
#[rstest]
#[case::remote_wins(-50, 40, 45, "remote changed body")]
#[case::local_wins(-70, 60, 65, "local body")]
#[tokio::test]
async fn test_both_diverged_merge_winner(#[case] consensus_seed: i64, #[case] local_seed: i64, #[case] remote_seed: i64, #[case] expected_body: &str) {
	let f = DivergedBodiesFixture::new(consensus_seed, local_seed, remote_seed).await;

	let out = f.ctx.open_issue(&f.local).run();

	// Verify the expected side won the merge
	let rendered = render_fixture(FixtureRenderer::try_new(&f.ctx).unwrap(), &out);
	assert!(rendered.contains(expected_body), "Expected body '{expected_body}' not found in:\n{rendered}");
}

/// When local matches consensus (no uncommitted changes) and remote has changed,
/// we only pull remote changes if --pull is specified.
#[tokio::test]
async fn test_only_remote_changed_takes_remote_with_pull() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let consensus_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  consensus body
"#,
	);
	let remote_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  remote changed body
"#,
	);

	// Local matches consensus (no uncommitted changes), remote changed
	// Seeds: consensus=-45, remote=90 (remote much newer, guarantees dominance)
	let consensus = ctx.consensus(&consensus_vi, Some(Seed::new(-45))).await;
	ctx.remote(&remote_vi, Some(Seed::new(90)));

	// Must use --pull to fetch remote changes when local is unchanged
	let out = ctx.open_issue(&consensus).args(&["--pull"]).run();

	assert!(
		out.status.success() && (out.stdout.contains("Syncing") || out.stdout.contains("pre-open sync")),
		"Should succeed with sync activity. stdout: {}, stderr: {}",
		out.stdout,
		out.stderr
	);
}

#[tokio::test]
async fn test_only_local_changed_pushes_local() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let consensus_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  consensus body
"#,
	);
	let local_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  local changed body
"#,
	);

	// Local changed, remote still matches consensus
	// Seeds: consensus=-25, local=85, remote=-25 (local much newer than unchanged remote)
	ctx.consensus(&consensus_vi, Some(Seed::new(-100))).await;
	let local = ctx.local(&local_vi, Some(Seed::new(100))).await;
	ctx.remote(&consensus_vi, Some(Seed::new(-100)));

	let out = ctx.open_issue(&local).run();

	assert!(out.status.success(), "Should succeed when only local changed. stderr: {}", out.stderr);

	// Capture the resulting directory state
	insta::assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap().redact_timestamps(&[10]), &out), @r#"
	//- /o/r/.meta.json
	{
	  "virtual_project": false,
	  "next_virtual_issue_number": 0,
	  "issues": {
	    "1": {
	      "user": "mock_user",
	      "timestamps": {
	        "title": "2001-09-12T11:20:39Z",
	        [REDACTED - non-deterministic timestamp]
	        "labels": "2001-09-12T01:55:52Z",
	        "state": "2001-09-12T00:39:25Z",
	        "comments": []
	      }
	    }
	  }
	}
	//- /o/r/1_-_Test_Issue.md
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  local changed body
	"#);
}

#[tokio::test]
async fn test_reset_with_local_source_skips_sync() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let consensus_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  consensus body
"#,
	);
	let local_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  local body
"#,
	);
	let remote_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  remote changed body
"#,
	);

	// --reset uses local as source, so timestamps don't affect result
	// Seeds: consensus=-30, local=20, remote=25
	ctx.consensus(&consensus_vi, Some(Seed::new(-30))).await;
	let local = ctx.local(&local_vi, Some(Seed::new(20))).await;
	ctx.remote(&remote_vi, Some(Seed::new(25)));

	// Run with --reset flag
	let out = ctx.open_issue(&local).args(&["--reset"]).run();

	eprintln!("stdout: {}", out.stdout);
	eprintln!("stderr: {}", out.stderr);
	eprintln!("status: {:?}", out.status);

	// With --reset, should reset to local state without sync
	assert!(out.status.success(), "Should succeed with --reset. stderr: {}", out.stderr);

	// Local file should still have local changes (not overwritten by remote)
	let issue_path = ctx.resolve_issue_path(&local);
	let content = read_issue_file(&issue_path);
	assert!(content.contains("local body"), "Local changes should be preserved with --reset");
}

/// Opening via URL when no local file exists should create the file from remote.
#[tokio::test]
async fn test_url_open_creates_local_file_from_remote() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let remote_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  remote body content
"#,
	);
	// Seed: 15 (arbitrary, no comparison needed)
	ctx.remote(&remote_vi, Some(Seed::new(15)));

	// No local file exists - URL open should create it
	let expected_path = ctx.flat_issue_path(("o", "r").into(), 1, "Test Issue");
	assert!(!expected_path.exists(), "Local file should not exist before open");

	let out = ctx.open_url(("o", "r").into(), 1).run();

	eprintln!("stdout: {}", out.stdout);
	eprintln!("stderr: {}", out.stderr);

	assert!(out.status.success(), "Should succeed creating from URL. stderr: {}", out.stderr);

	// File should now exist with remote content
	assert!(expected_path.exists(), "Local file should be created");
	let content = read_issue_file(&expected_path);
	assert!(content.contains("remote body content"), "Should have remote content. Got: {content}");
}

/// When opening via URL with --reset, local state should be completely replaced with remote.
/// No merge conflicts, no prompts - just nuke and replace.
#[tokio::test]
async fn test_reset_with_remote_url_nukes_local_state() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let local_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->

  local body that should be nuked
"#,
	);
	let remote_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->

  remote body wins
"#,
	);

	// --reset overrides everything, but remote is the source when opening via URL
	// Seeds: consensus=-40, remote=80 (remote much newer)
	let local = ctx.consensus(&local_vi, Some(Seed::new(-40))).await;
	ctx.remote(&remote_vi, Some(Seed::new(80)));

	// Open via URL with --reset should nuke local and use remote
	let out = ctx.open_url(("o", "r").into(), 1).args(&["--reset"]).run();

	eprintln!("stdout: {}", out.stdout);
	eprintln!("stderr: {}", out.stderr);

	assert!(out.status.success(), "Should succeed with --reset via URL. stderr: {}", out.stderr);

	// Local file should now have remote content
	let issue_path = ctx.resolve_issue_path(&local);
	let content = read_issue_file(&issue_path);
	assert!(content.contains("remote body wins"), "Local should be replaced with remote. Got: {content}");
	assert!(!content.contains("local body that should be nuked"), "Local content should be gone");
}

/// When opening via URL with --reset and there's divergence, should NOT trigger merge conflict.
#[tokio::test]
async fn test_reset_with_remote_url_skips_merge_on_divergence() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let consensus_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  consensus body
"#,
	);
	let local_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  local diverged body
"#,
	);
	let remote_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  remote diverged body
"#,
	);

	// Both diverged, but --reset via URL should skip merge and use remote
	// Seeds: consensus=-60, local=30, remote=35
	ctx.consensus(&consensus_vi, Some(Seed::new(-60))).await;
	let local = ctx.local(&local_vi, Some(Seed::new(30))).await;
	ctx.remote(&remote_vi, Some(Seed::new(35)));

	// Open via URL with --reset should NOT trigger merge conflict
	let out = ctx.open_url(("o", "r").into(), 1).args(&["--reset"]).run();

	eprintln!("stdout: {}", out.stdout);
	eprintln!("stderr: {}", out.stderr);

	// Should succeed without merge conflict
	assert!(out.status.success(), "Should succeed without merge conflict. stderr: {}", out.stderr);
	assert!(!out.stderr.contains("Conflict"), "Should not mention conflict with --reset");
	assert!(!out.stdout.contains("Merging"), "Should not attempt merge with --reset");

	// Local should have remote content
	let issue_path = ctx.resolve_issue_path(&local);
	let content = read_issue_file(&issue_path);
	assert!(content.contains("remote diverged body"), "Should have remote content. Got: {content}");
}

/// --pull flag should fetch and sync BEFORE opening editor.
/// This test verifies the fetch actually happens by checking stdout for fetch message.
#[tokio::test]
async fn test_pull_fetches_before_editor() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let local_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  local body
"#,
	);
	let remote_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  remote body from github
"#,
	);

	// Local unchanged from consensus, remote changed
	// Seeds: consensus=-20, remote=70
	let local = ctx.consensus(&local_vi, Some(Seed::new(-20))).await;
	ctx.remote(&remote_vi, Some(Seed::new(70)));

	// --pull should fetch from Github before opening editor
	let out = ctx.open_issue(&local).args(&["--pull"]).run();

	// Should show fetch activity
	assert!(out.stderr.contains("pre-open sync"), "Should show fetch/pull activity with --pull. stdout: {}", out.stderr);

	assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap().skip_meta(), &out), @"
	//- /o/r/1_-_Test_Issue.md
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  remote body from github
	");
}

/// --pull with diverged state should trigger conflict resolution (or auto-resolve).
#[tokio::test]
async fn test_pull_with_divergence_runs_sync_before_editor() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let consensus_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  consensus body
"#,
	);
	let local_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  local diverged body
"#,
	);
	let remote_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  remote diverged body
"#,
	);

	// Both local and remote changed since consensus
	ctx.consensus(&consensus_vi, Some(Seed::new(-100))).await;
	let local = ctx.local(&local_vi, Some(Seed::new(100))).await;
	ctx.remote(&remote_vi, Some(Seed::new(100)));

	// --pull should attempt to sync/merge even BEFORE editor opens
	let out = ctx.open_issue(&local).args(&["--pull"]).run();

	// Ensure we detect the conflict even before the editor is opened for the user
	assert!(
		out.stderr.contains("pre-open sync"), //Q: don't like reliance on impl-specific details
		"Should attempt sync/merge with --pull before editor; stderr:\n{}",
		out.stderr
	);

	// Ensure conflict is opened
	assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap(), &out), @r#"
	//- /o/__conflict.md
	<<<<<<< HEAD
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  local diverged body
	||||||| [hash]
	=======
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  remote diverged body
	>>>>>>> remote-state
	//- /o/r/.meta.json
	{
	  "virtual_project": false,
	  "next_virtual_issue_number": 0,
	  "issues": {
	    "1": {
	      "user": "mock_user",
	      "timestamps": {
	        "title": "2001-09-12T11:20:39Z",
	        "description": "2001-09-12T10:04:12Z",
	        "labels": "2001-09-12T01:55:52Z",
	        "state": "2001-09-12T00:39:25Z",
	        "comments": []
	      }
	    }
	  }
	}
	//- /o/r/1_-_Test_Issue.md
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  local diverged body
	"#)
}

#[tokio::test]
async fn test_closing_issue_syncs_state_change() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let open_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  body
"#,
	);
	// Local = consensus = remote initially
	// Seeds: consensus=5, remote=5 (same seed = same base time)
	let open_issue = ctx.consensus(&open_vi, Some(Seed::new(5))).await;
	ctx.remote(&open_vi, Some(Seed::new(5)));

	// Edit to close the issue
	let mut closed_issue = open_vi.clone();
	closed_issue.contents.state = tedi::CloseState::Closed;

	let out = ctx.open_issue(&open_issue).edit(&closed_issue).run();

	// Line 11 contains `state` timestamp set via Timestamp::now() when detecting state change
	let result_str = render_fixture(FixtureRenderer::try_new(&ctx).unwrap().redact_timestamps(&[12]), &out);

	insta::assert_snapshot!(result_str, @r#"
	//- /o/r/.meta.json
	{
	  "virtual_project": false,
	  "next_virtual_issue_number": 0,
	  "issues": {
	    "1": {
	      "user": "mock_user",
	      "timestamps": {
	        "title": "2001-09-11T09:15:20Z",
	        "description": "2001-09-11T04:30:34Z",
	        "labels": "2001-09-11T06:38:10Z",
	        [REDACTED - non-deterministic timestamp]
	        "comments": []
	      }
	    }
	  }
	}
	//- /o/r/1_-_Test_Issue.md.bak
	- [x] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  body
	"#);
}

/// Sub-issues closed as duplicates should NOT appear in the pulled remote state.
/// Github marks these with state_reason="duplicate" - they should be filtered out entirely.
#[tokio::test]
async fn test_duplicate_sub_issues_filtered_from_remote() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	// Create parent with children for remote - normal closed and duplicate sub-issues
	let parent_vi = parse_virtual(
		r#"- [ ] Parent Issue <!-- @mock_user https://github.com/o/r/issues/1 -->

  parent body

  - [x] Normal Closed Sub <!--sub @mock_user https://github.com/o/r/issues/2 -->

    sub body

  - [2] Duplicate Sub <!--sub @mock_user https://github.com/o/r/issues/3 -->

    duplicate body
"#,
	);

	// Seed: -10 (arbitrary)
	ctx.remote(&parent_vi, Some(Seed::new(-10)));

	// Open via URL to fetch from remote
	let out = ctx.open_url(("o", "r").into(), 1).run();

	eprintln!("stdout: {}", out.stdout);
	eprintln!("stderr: {}", out.stderr);

	assert!(out.status.success(), "Should succeed. stderr: {}", out.stderr);

	insta::assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap().skip_meta(), &out), @"
	//- /o/r/1_-_Parent_Issue/2_-_Normal_Closed_Sub.md.bak
	- [x] Normal Closed Sub <!-- @mock_user https://github.com/o/r/issues/2 -->
	  sub body
	//- /o/r/1_-_Parent_Issue/__main__.md
	- [ ] Parent Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  parent body
	");
}

/// Opening an issue twice when local matches remote should succeed (no-op).
/// This tests the case where you:
/// 1. Open an issue from URL (fetches remote)
/// 2. Open again without making changes
///
/// The second open should succeed, not fail with "Failed to commit remote state".
#[tokio::test]
async fn test_open_unchanged_succeeds() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->

  issue body
"#,
	);
	// Seed: 10 (arbitrary)
	let issue = ctx.remote(&vi, Some(Seed::new(10)));

	// First open via URL
	let out = ctx.open_url(("o", "r").into(), 1).run();
	assert!(out.status.success(), "First open should succeed. stderr: {}", out.stderr);

	// Second open - should also succeed (no-op since nothing changed)
	let out = ctx.open_issue(&issue).run();
	assert!(out.status.success(), "Second open (unchanged) should succeed. stderr: {}", out.stderr);
}

/// Opening an issue by number when remote state matches local should succeed.
/// Reproduces: https://github.com/valeratrades/todo/issues/83
/// The issue happens when:
/// 1. `todo open --reset <url>` fetches and stores remote state
/// 2. `todo open <number>` is called (by number, not path)
/// 3. Remote state hasn't changed, but the merge machinery still runs
/// 4. Git commit fails because there's nothing to commit
#[tokio::test]
async fn test_open_by_number_unchanged_succeeds() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->

  issue body
"#,
	);
	ctx.remote(&vi, None);

	// First open via URL with --reset
	let out = ctx.open_url(("o", "r").into(), 1).args(&["--reset"]).run();
	eprintln!("First open stdout: {}", out.stdout);
	eprintln!("First open stderr: {}", out.stderr);
	assert!(out.status.success(), "First open should succeed. stderr: {}", out.stderr);

	// Second open by number (simulating the failing case)
	// This uses the mock, so remote state is the same
	let out = ctx.open_url(("o", "r").into(), 1).run();
	eprintln!("Second open stdout: {}", out.stdout);
	eprintln!("Second open stderr: {}", out.stderr);
	assert!(out.status.success(), "Second open (unchanged) should succeed. stderr: {}", out.stderr);
}

/// --reset should only apply to the first sync (before editor).
/// After the user makes changes, normal sync should happen.
/// Reproduces the issue where changes made after --reset don't sync.
#[tokio::test]
async fn test_reset_syncs_changes_after_editor() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let remote_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->

  remote body
"#,
	);
	ctx.remote(&remote_vi, None);

	// emulate user closing the issue after
	let mut modified_issue = remote_vi.clone();
	modified_issue.contents.state = tedi::CloseState::Closed;
	let out = ctx.open_url(("o", "r").into(), 1).args(&["--reset"]).edit(&modified_issue).run();

	// want to see the issue closed here
	insta::assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap().redact_timestamps(&[12]), &out), @r#"
	//- /o/r/.meta.json
	{
	  "virtual_project": false,
	  "next_virtual_issue_number": 0,
	  "issues": {
	    "1": {
	      "user": "mock_user",
	      "timestamps": {
	        "title": null,
	        "description": null,
	        "labels": null,
	        [REDACTED - non-deterministic timestamp]
	        "comments": []
	      }
	    }
	  }
	}
	//- /o/r/1_-_Test_Issue.md.bak
	- [x] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  remote body
	"#);
}

/// `!c` shorthand should expand to `<!-- new comment -->` and trigger comment creation.
/// When the user types `!c` on its own line, it should:
/// 1. Be expanded to `<!-- new comment -->` in the file
/// 2. Result in a new comment being created on Github
#[tokio::test]
async fn test_comment_shorthand_creates_comment() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	// Start with an issue that has no comments
	let vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  issue body
"#,
	);
	let issue = ctx.consensus(&vi, None).await;
	ctx.remote(&vi, None);

	// Simulate user adding `!c` followed by comment content
	// After expansion, the file should have `<!-- new comment -->` marker
	let edited_content = r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  issue body

  !c
  My new comment content
"#;

	// Write the edited content (simulating what user typed in editor)
	let issue_path = ctx.resolve_issue_path(&issue);
	write_to_path(&issue_path, edited_content);

	// Run open to trigger sync (which should expand !c and create the comment)
	let out = ctx.open_issue(&issue).run();

	//eprintln!("stdout: {}", out.stdout);
	//eprintln!("stderr: {}", out.stderr);

	// Capture the resulting directory state
	insta::assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap().skip_meta(), &out), @"
	//- /o/__conflict.md
	<<<<<<< HEAD
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  issue body

	  <!-- new comment -->
	  My new comment content
	||||||| [hash]
	=======
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  issue body
	>>>>>>> remote-state
	//- /o/r/1_-_Test_Issue.md
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  issue body

	  !c
	  My new comment content
	");
}

/// When local and remote have different sub-issues, force merge should preserve both.
/// This tests the scenario where:
/// - Local has sub-issue A that remote doesn't have
/// - Remote has sub-issue B that local doesn't have
/// - Local has an extra line in the description
/// After merge with --force (either side), consensus should contain both sub-issues.
///
/// Flag semantics:
/// - `--force` alone: prefer local on conflicts
/// - `--pull --force`: prefer remote on conflicts
#[rstest]
#[case::prefer_local(&["--force"], true)]
#[case::prefer_remote(&["--pull", "--force"], false)]
#[tokio::test]
async fn test_force_merge_preserves_both_sub_issues(#[case] args: &[&str], #[case] expect_local_description: bool) {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	// Local: parent with local-only sub-issue and modified description
	let local_vi = parse_virtual(
		r#"- [ ] Parent Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  parent body
  extra line from local

  - [ ] Local Sub <!--sub @mock_user https://github.com/o/r/issues/2 -->
    local sub body
"#,
	);

	// Remote: parent with remote-only sub-issue (no extra description line)
	let remote_vi = parse_virtual(
		r#"- [ ] Parent Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  parent body

  - [ ] Remote Sub <!--sub @mock_user https://github.com/o/r/issues/3 -->
    remote sub body
"#,
	);

	// Consensus: original state (no sub-issues, original description)
	let consensus_vi = parse_virtual(
		r#"- [ ] Parent Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  parent body
"#,
	);

	ctx.consensus(&consensus_vi, Some(Seed::new(-100))).await;
	let local = ctx.local(&local_vi, Some(Seed::new(100))).await;
	ctx.remote(&remote_vi, Some(Seed::new(100)));

	let out = ctx.open_issue(&local).args(args).run();

	// Snapshot the result - different expectations based on which side wins conflicts
	//#[codestyle::skip]
	if expect_local_description {
		// --force: local wins conflicts, so "extra local line" should be present
		insta::assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap().skip_meta(), &out), @"
		//- /o/r/1_-_Parent_Issue/2_-_Local_Sub.md
		- [ ] Local Sub <!-- @mock_user https://github.com/o/r/issues/2 -->
		  local sub body
		//- /o/r/1_-_Parent_Issue/3_-_Remote_Sub.md
		- [ ] Remote Sub <!-- @mock_user https://github.com/o/r/issues/3 -->
		  remote sub body
		//- /o/r/1_-_Parent_Issue/__main__.md
		- [ ] Parent Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
		  parent body
		  extra line from local
		");
	} else {
		// --pull --force: remote wins conflicts, so "extra local line" should NOT be present
		insta::assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap().skip_meta(), &out), @"
		//- /o/r/1_-_Parent_Issue/2_-_Local_Sub.md
		- [ ] Local Sub <!-- @mock_user https://github.com/o/r/issues/2 -->
		  local sub body
		//- /o/r/1_-_Parent_Issue/3_-_Remote_Sub.md
		- [ ] Remote Sub <!-- @mock_user https://github.com/o/r/issues/3 -->
		  remote sub body
		//- /o/r/1_-_Parent_Issue/__main__.md
		- [ ] Parent Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
		  parent body
		");
	}
}

/// `!u` on the last line of the virtual file means "undo" - treat as if no changes were made.
/// User makes edits but then changes their mind, appends `!u` to abort sync.
/// The filesystem state should remain identical to the initial state.
#[tokio::test]
async fn test_undo_shorthand_aborts_sync() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  issue body
"#,
	);
	let issue = ctx.consensus(&vi, None).await;
	ctx.remote(&vi, None);

	let (vpath, paused) = ctx.open_issue(&issue).args(&["--offline"]).break_to_edit();

	// Simulate user making edits but then deciding to abort
	let content = std::fs::read_to_string(&vpath).unwrap();
	std::fs::write(&vpath, format!("{content}  some random edits\n  another line of changes\n!u\n")).unwrap();

	let out = paused.resume();
	assert!(out.status.success(), "Should succeed. stderr: {}", out.stderr);

	// Issue file should remain unchanged from initial state
	assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap().skip_meta(), &out), @"
	//- /o/r/1_-_Test_Issue.md
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  issue body
	");
}

/// Verify that .meta.json is written with timestamps when sinking to Consensus.
/// This is critical for the merge algorithm to work - timestamps determine which side wins.
#[tokio::test]
async fn test_consensus_sink_writes_meta_json_with_timestamps() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	// Set up a remote issue with a comment (will have timestamps from mock)
	let remote_vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  remote body

  ---
  <!-- comment 1001 @commenter -->
  A test comment
"#,
	);
	ctx.remote(&remote_vi, None);

	// Fetch the issue via URL - this should sink to Consensus and write .meta.json
	let out = ctx.open_url(("o", "r").into(), 1).run();

	eprintln!("stdout: {}", out.stdout);
	eprintln!("stderr: {}", out.stderr);

	assert!(out.status.success(), "Fetch should succeed. stderr: {}", out.stderr);

	// Capture the resulting directory state (includes .meta.json with timestamps)
	insta::assert_snapshot!(render_fixture(FixtureRenderer::try_new(&ctx).unwrap().redact_timestamps(&[10]), &out), @r#"
	//- /o/r/.meta.json
	{
	  "virtual_project": false,
	  "next_virtual_issue_number": 0,
	  "issues": {
	    "1": {
	      "user": "mock_user",
	      "timestamps": {
	        "title": null,
	        [REDACTED - non-deterministic timestamp]
	        "labels": null,
	        "state": null,
	        "comments": []
	      }
	    }
	  }
	}
	//- /o/r/1_-_Test_Issue.md
	- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
	  remote body
	  \---<!-- comment 1001 @commenter -->

	  A test comment
	"#);
}

/// Adding labels to an issue should sync them to remote.
/// Labels are specified as `[label1, label2] Title` in the file format.
#[tokio::test]
async fn test_adding_labels_syncs_to_remote() {
	let ctx = TestContext::build_with_preexisting_state_unsafe("");

	let vi = parse_virtual(
		r#"- [ ] Test Issue <!-- @mock_user https://github.com/o/r/issues/1 -->
  body
"#,
	);
	let issue = ctx.consensus(&vi, Some(Seed::new(5))).await;
	ctx.remote(&vi, Some(Seed::new(5)));

	// Edit to add labels
	let mut labeled_vi = vi.clone();
	labeled_vi.contents.labels = vec!["bug".to_string(), "urgent".to_string()];

	let out = ctx.open_issue(&issue).edit(&labeled_vi).run();

	assert!(out.status.success(), "Should succeed. stderr: {}", out.stderr);
	assert!(out.stdout.contains("Updating issue #1 labels"), "Should push labels to remote. stdout: {}", out.stdout);

	// Verify labels appear in the resulting file
	let issue_path = ctx.resolve_issue_path(&issue);
	let content = read_issue_file(&issue_path);
	assert!(content.contains("(bug, urgent)"), "Labels should be in file. Got: {content}");
}