tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
//! `tix export --target <gitlab|linear|ics|views|health|roadmap|capacity|time|chart>
//! [--dry-run] [--project <p>]`: mirror local issues to an external tracker, recording
//! the remote id back into `gitlab_id`/`linear_id` so a re-run updates instead of
//! duplicating (`contracts/external-tools.md`).
//!
//! Seven of the nine targets are **local** and never reach an external tool:
//! `ics` writes a calendar for a cycle, `views` (WP07, mission
//! `saved-issue-views-01M3C926`, T037) writes the portable saved-view document,
//! `health` (WP05, mission `project-issue-health-status-01M3C8HX`) writes the
//! portable health document, `roadmap` (WP07, mission
//! `roadmap-initiatives-01M3C8SX`) writes the portable roadmap document,
//! `capacity` (WP08, mission `cycle-capacity-planning-01M3C85C`, T043) writes the
//! portable local capacity document, `time` (WP07, mission
//! `per-issue-time-tracking-01M3C9A4`, T036/T037) writes the portable local time
//! document, and `chart` (WP04, mission `burndown-scope-analytics-01M3C9J1`,
//! T019–T023) writes the versioned local chart document.
//! They are dispatched by name in [`run`] *before* `Tool::from_target` is
//! consulted, which is what keeps the remote `gitlab`/`linear` namespaces
//! separate from local view/health/initiative/capacity/time/chart data.

use std::collections::BTreeSet;

use crate::analytics::chart::ChartExport;
use crate::analytics::events::{AnalyticsScope, Period};
use crate::analytics::series::{Mode, ScopeSnapshot};
use crate::analytics::units::estimate_series;
use crate::capacity::portable::PortableCapacityDocument;
use crate::cli::ExitCode;
use crate::config::Config;
use crate::cycle_schedule::identity::CycleReference;
use crate::error::{Result, TixError};
use crate::health::diagnostics::{HealthDiagnostic, HealthDiagnosticKind, RemoteTarget};
use crate::health::events::{HealthScope, project};
use crate::health::policy::HealthPolicy;
use crate::health::portable::{PortableHealth, PortableHealthDiagnostic};
use crate::ics::{self, Event};
use crate::planning::Planner;
use crate::roadmap::RoadmapFilter;
use crate::roadmap::portable::PortableRoadmap;
use crate::storage::Store;
use crate::sync::{self, MappedHealth, Tool, beads};
use crate::time_tracking::aggregate::TimeSnapshot;
use crate::time_tracking::filters::TimeFilter;
use crate::time_tracking::portable::PortableTimeDocument;
use crate::views::portable::{PortableDocument, PortableRemoteTargets};

/// Run the export orchestration, printing the report to stdout and every
/// unsupported-field or token warning to stderr. A remote export with any
/// unsupported local data returns `UsageConfig` after printing both streams, so
/// exit `0` means the complete model travelled.
// The signature mirrors the CLI's `Export` flags one for one — that is a
// dispatcher's whole job — and bundling them into a struct would only move the
// same destructuring to the caller. `commands::list::run` carries this allow for
// the same reason.
#[allow(clippy::too_many_arguments)]
pub fn run(
    config: &Config,
    store: &Store,
    target: &str,
    dry_run: bool,
    project_override: Option<&str>,
    cycle: Option<&str>,
    output: Option<&str>,
    verbose: bool,
) -> Result<ExitCode> {
    if target == "ics" {
        run_ics(config, store, cycle, output)?;
        return Ok(ExitCode::Success);
    }
    if target == "views" {
        run_views(config, output)?;
        return Ok(ExitCode::Success);
    }
    if target == "health" {
        run_health(config, output)?;
        return Ok(ExitCode::Success);
    }
    if target == "roadmap" {
        run_roadmap(config, output)?;
        return Ok(ExitCode::Success);
    }
    if target == "capacity" {
        run_capacity(config, store, cycle, output)?;
        return Ok(ExitCode::Success);
    }
    if target == "time" {
        run_time(config, store, output)?;
        return Ok(ExitCode::Success);
    }
    if target == "chart" {
        run_chart(config, store, cycle, output)?;
        return Ok(ExitCode::Success);
    }
    if target == "beads" {
        run_beads(config, store, dry_run, output, verbose)?;
        return Ok(ExitCode::Success);
    }
    let outcome = run_remote_core(config, store, target, dry_run, project_override)?;
    print!("{}", outcome.report);
    for diagnostic in &outcome.diagnostics {
        eprintln!("{diagnostic}");
    }
    Ok(if outcome.diagnostics.is_empty() {
        ExitCode::Success
    } else {
        ExitCode::UsageConfig
    })
}

#[derive(Debug)]
struct RemoteExportOutcome {
    report: String,
    diagnostics: Vec<String>,
}

fn run_ics(
    config: &Config,
    store: &Store,
    cycle: Option<&str>,
    output: Option<&str>,
) -> Result<()> {
    let cycle_name = cycle.ok_or_else(|| TixError::InvalidInput("missing --cycle".into()))?;
    let root =
        Config::project_root(&store.issues_dir).unwrap_or_else(|| std::path::PathBuf::from("."));
    let planner = Planner::from_config(config.clone(), root);
    let cycle = planner
        .cycle(cycle_name)
        .ok_or_else(|| TixError::NotFound(format!("cycle `{cycle_name}`")))?;

    let cycle_start = cycle.start_date.clone().unwrap_or_else(crate::model::today);
    if cycle.start_date.is_none() || cycle.due_date.is_none() {
        eprintln!(
            "{}",
            crate::diagnostics::Diagnostic::note(
                "N-tix-export",
                format!("cycle `{cycle_name}` has incomplete dates; DTSTART fallback was applied")
            )
            .render_auto()
        );
    }
    let cycle_end = cycle
        .due_date
        .as_deref()
        .and_then(ics::plus_one_day)
        .and_then(|s| ics::ymd_to_ics(&s));

    let mut matching_issues: Vec<_> = store
        .list()?
        .into_iter()
        .filter(|issue| {
            issue
                .cycles
                .as_ref()
                .is_some_and(|cycles| cycles.iter().any(|c| c == cycle_name))
        })
        .collect();
    matching_issues.sort_by_key(|i| i.number);

    let cycle_start_ics = ics::ymd_to_ics(&cycle_start).ok_or_else(|| {
        TixError::InvalidInput(format!("invalid cycle start date `{cycle_start}`"))
    })?;

    let mut events = vec![Event {
        uid: format!(
            "cycle-{}-{}-{}@tix",
            crate::slug::slugify(cycle_name),
            cycle.start_date.as_deref().unwrap_or("none"),
            cycle.due_date.as_deref().unwrap_or("none")
        ),
        summary: cycle_name.to_string(),
        description: Some(format!(
            "{} / {} issue(s)",
            cycle.description.clone().unwrap_or_default(),
            matching_issues.len()
        )),
        dtstart: Some(cycle_start_ics),
        dtend: cycle_end,
    }];
    for issue in matching_issues {
        let start = issue
            .start_date
            .clone()
            .or_else(|| cycle.start_date.clone())
            .unwrap_or_else(crate::model::today);
        let end = issue
            .due_date
            .as_deref()
            .or(cycle.due_date.as_deref())
            .and_then(ics::plus_one_day)
            .and_then(|s| ics::ymd_to_ics(&s));
        events.push(Event {
            uid: format!("issue-{}-{}@tix", issue.number, cycle_name),
            summary: format!("[{}] {}", issue.status.display(), issue.title),
            description: (!issue.body.trim().is_empty()).then_some(issue.body.clone()),
            dtstart: ics::ymd_to_ics(&start),
            dtend: end,
        });
    }
    let calendar = ics::write_vcalendar(&events)?;
    if let Some(path) = output {
        ics::write_to_path(std::path::Path::new(path), &calendar)?;
        println!("{path}");
    } else {
        print!("{calendar}");
    }
    Ok(())
}

/// `tix export --target views [--output <path>]` — the local portable saved-view
/// document (WP07; T037).
///
/// A **local** target, like `ics`: it shells out to nothing, touches no issue
/// file, and is dispatched by name before `Tool::from_target`, so the remote
/// `gitlab`/`linear` namespaces are never consulted, never written, and cannot
/// collide with a view. The document is the shared portable DTO
/// ([`crate::views::portable`]) built by the one mapping every surface uses.
///
/// Side-effect policy: the document goes to stdout, or to `--output` through the
/// existing atomic export writer (temp file + rename), which is the same helper
/// `ics` uses. Diagnostics — an unknown field, a remote-target-shaped key, an
/// executable-shaped key, a foreign format/version marker — go to **stderr**, so
/// they are reported without corrupting the machine-readable stdout. They are
/// informational, never a refusal and never a drop: the value they are about is
/// retained in the document (NFR-002).
/// `tix export --target health`: the portable health document, as the machine-readable
/// form of everything `tix health` prints (WP05 T025's "parseable output", C-007).
///
/// Pretty JSON to a file or to stdout, exactly as `--target views` does; diagnostics
/// go to stderr so they are reported without corrupting the document on stdout.
pub fn run_health(config: &Config, output: Option<&str>) -> Result<()> {
    let document = run_health_core(config)?;
    for diagnostic in &document.diagnostics {
        eprintln!("diagnostic: {}", diagnostic.to_diagnostic().render());
    }
    let json = document.to_json_pretty()?;
    match output {
        Some(path) => {
            ics::write_to_path(std::path::Path::new(path), &json)?;
            println!("{path}");
        }
        None => print!("{json}"),
    }
    Ok(())
}

/// `tix export --target roadmap [--output <path>]` — the local portable roadmap
/// document (WP07; T032/T033).
///
/// A **local** target, like `ics`, `views` and `health`: it shells out to nothing,
/// touches no initiative record and no issue file, and is dispatched by name before
/// `Tool::from_target`, so the remote `gitlab`/`linear` namespaces are never
/// consulted and cannot collide with an initiative. The document is the shared DTO
/// ([`crate::roadmap::portable`]) built from the one projection every surface reads,
/// so `tix roadmap list`, the TUI, MCP and this file cannot disagree.
///
/// Pretty JSON to a file or to stdout; diagnostics — a missing reference, an empty
/// summary, an unsupported remote field — go to **stderr**, so they are reported
/// without corrupting the document on stdout. They are informational, never a
/// refusal and never a drop: every value they are about is retained in the
/// document (C-005/C-009).
pub fn run_roadmap(config: &Config, output: Option<&str>) -> Result<()> {
    let document = run_roadmap_core(config)?;
    for diagnostic in &document.diagnostics {
        eprintln!("diagnostic: {}", diagnostic.render());
    }
    let json = document.to_json_pretty()?;
    match output {
        Some(path) => {
            ics::write_to_path(std::path::Path::new(path), &json)?;
            println!("{path}");
        }
        None => print!("{json}"),
    }
    Ok(())
}

/// The roadmap export core: the versioned document, with no printing and no writing.
///
/// Split out of [`run_roadmap`] so an MCP/portable parity check or a test can read
/// exactly the document the CLI emits without capturing stdout (the same split
/// [`run_core`], [`run_health_core`] and [`run_views_core`] offer).
///
/// It reads the **same** source snapshot the CLI roadmap reads, through
/// [`crate::commands::roadmap::build_sources`] — the one gathering of the consumed
/// planning/relationship facts — so the document cannot become a second definition
/// of what an initiative's summary is. Read-only: nothing is written, and the only
/// side effects are the reads the projection already makes.
pub fn run_roadmap_core(config: &Config) -> Result<PortableRoadmap> {
    let store = Store::open(config)?;
    let issues = store.list_all()?;
    let sources = crate::commands::roadmap::build_sources(config, &store, &issues)?;
    // The empty filter is the documented "no filter" default: `tix export` takes no
    // roadmap filter flags, so the export is the whole ordered roadmap, and the
    // document carries that normalized filter so a reader can see it was empty.
    let document = PortableRoadmap::build(config, &sources, &RoadmapFilter::default())?
        .with_remote_mappings(config);
    Ok(document)
}

/// `tix export --target capacity [--cycle <REFERENCE>] [--output <path>]` — the local
/// portable capacity document (WP08; T043).
///
/// A **local** target, like `ics`, `views`, `health` and `roadmap`: it shells out to
/// nothing, touches no issue file and no remote tracker, and is dispatched by name before
/// [`Tool::from_target`] is consulted, so the remote `gitlab`/`linear` namespaces are
/// never consulted, never written, and cannot collide with a capacity value. The document
/// is the shared DTO ([`PortableCapacityDocument`]) whose every number is the shared
/// calculation's.
///
/// Side-effect policy: the document goes to stdout, or to `--output` through the existing
/// atomic export writer (temp file + rename) the other local targets use. Diagnostics — an
/// unknown preserved key, a version mismatch, and the [`UNSUPPORTED_REMOTE_FIELD`] finding
/// that says a configured remote tracker cannot carry capacity — go to **stderr**, so they
/// are reported without corrupting the machine-readable stdout. They are informational,
/// never a refusal and never a drop: every value they are about stays in the document.
///
/// [`UNSUPPORTED_REMOTE_FIELD`]: crate::capacity::portable::UNSUPPORTED_REMOTE_FIELD
pub fn run_capacity(
    config: &Config,
    store: &Store,
    cycle: Option<&str>,
    output: Option<&str>,
) -> Result<()> {
    let document = run_capacity_core(config, store, cycle)?;
    for diagnostic in &document.diagnostics {
        eprintln!("diagnostic: {}", diagnostic.render());
    }
    let json = document.to_json_pretty()?;
    match output {
        Some(path) => {
            ics::write_to_path(std::path::Path::new(path), &json)?;
            println!("{path}");
        }
        None => print!("{json}"),
    }
    Ok(())
}

/// The portable-capacity export core: the document, with no printing and no writing.
///
/// Split out of [`run_capacity`] so an MCP/portable parity check or a test can read exactly
/// the document the CLI emits without capturing stdout (the same split [`run_core`],
/// [`run_health_core`], [`run_views_core`] and [`run_roadmap_core`] offer).
///
/// It reads the **same** snapshot/index pair `tix capacity calculate` reads, through
/// [`crate::commands::capacity::snapshot_for`] — the one builder of the pair — so a
/// document's numbers cannot become a second reading of the same repository. `cycle` is
/// the CLI's `--cycle`; when it names one, the document is narrowed to that cycle (the
/// reference is folded by the library, so a generated cycle's name and its stable id
/// select the same document). Read-only: nothing is written, and the only side effects are
/// the reads the calculation and the snapshot store already make.
pub fn run_capacity_core(
    config: &Config,
    store: &Store,
    cycle: Option<&str>,
) -> Result<PortableCapacityDocument> {
    let root =
        Config::project_root(&store.issues_dir).unwrap_or_else(|| std::path::PathBuf::from("."));
    let (index, snapshot) = crate::commands::capacity::snapshot_for(config, &root, store)?;
    match cycle {
        Some(reference) => {
            PortableCapacityDocument::build_for_cycle(config, &root, &index, &snapshot, reference)
        }
        None => PortableCapacityDocument::build(config, &root, &index, &snapshot),
    }
}

/// `tix export --target time [--output <path>]` — the local portable time document
/// (WP07; T036/T037).
///
/// A **local** target, like `ics`, `views`, `health`, `roadmap` and `capacity`: it
/// shells out to nothing, touches no issue file and no remote tracker, and is dispatched
/// by name before [`Tool::from_target`] is consulted, so the remote `gitlab`/`linear`
/// namespaces are never consulted, never written, and cannot collide with a time entry.
/// The document is the shared DTO ([`PortableTimeDocument`]): every number is the shared
/// calculation's and every entry is the issue's own current value, so `tix time total`
/// and this file cannot disagree.
///
/// Side-effect policy: the document goes to stdout, or to `--output` through the existing
/// atomic export writer (temp file + rename) the other local targets use. Diagnostics — an
/// entry's field problem, a preserved metadata key, and the
/// [`UNSUPPORTED_REMOTE_FIELD`] finding that says a configured remote tracker cannot
/// carry time — go to **stderr**, so they are reported without corrupting the
/// machine-readable stdout. They are informational, never a refusal and never a drop:
/// every value they are about stays in the document. A refused scope is the exception and
/// exits non-zero with the shared findings and their remedies, exactly as `tix time total`
/// refuses it.
///
/// [`UNSUPPORTED_REMOTE_FIELD`]: crate::time_tracking::portable::UNSUPPORTED_REMOTE_FIELD
pub fn run_time(config: &Config, store: &Store, output: Option<&str>) -> Result<()> {
    let document = run_time_core(config, store)?;
    for diagnostic in &document.diagnostics {
        eprintln!("diagnostic: {}", diagnostic.render());
    }
    let json = document.to_json_pretty()?;
    match output {
        Some(path) => {
            ics::write_to_path(std::path::Path::new(path), &json)?;
            println!("{path}");
        }
        None => print!("{json}"),
    }
    Ok(())
}

/// The portable-time export core: the versioned document, with no printing and no
/// writing.
///
/// Split out of [`run_time`] so an MCP/portable parity check or a test can read exactly
/// the document the CLI emits without capturing stdout (the same split [`run_core`],
/// [`run_health_core`], [`run_views_core`], [`run_roadmap_core`] and
/// [`run_capacity_core`] offer).
///
/// It reads the **same** snapshot `tix time total` reads — every active issue, as
/// `tix list` enumerates them, indexed once by [`TimeSnapshot::of`] — under the
/// documented "no filter" default ([`TimeFilter::new`], which the export takes no flags
/// to narrow), so a document's numbers cannot become a second reading of the repository.
/// Read-only: nothing is written, and the only side effects are the reads the store
/// already makes.
pub fn run_time_core(config: &Config, store: &Store) -> Result<PortableTimeDocument> {
    let snapshot = TimeSnapshot::of(&store.list()?);
    PortableTimeDocument::build(config, &snapshot, &TimeFilter::new())
}

/// `tix export --target chart --cycle <REFERENCE> [--output <path>]` — the versioned
/// local chart document (WP04, mission `burndown-scope-analytics-01M3C9J1`,
/// T019–T023).
///
/// A **local** target, like `ics`, `views`, `health`, `roadmap`, `capacity` and `time`:
/// it shells out to nothing, touches no issue file and no remote tracker, and is
/// dispatched by name before [`Tool::from_target`] is consulted, so the remote
/// `gitlab`/`linear` namespaces are never consulted, never written, and cannot collide
/// with a chart document. The document is WP04's [`ChartExport`] — its scope, period,
/// mode, unit, points, optional projection, coverage and diagnostics all come from the
/// one shared fold, so this file cannot disagree with `tix analytics burndown`.
///
/// The export flags carry **one** scope reference (`--cycle`) and no mode/unit flag: the
/// local target therefore documents the cycle's **count**-mode series. The reference is
/// folded through [`cycle_scope_for`] — the crate's one cycle identity adapter — so a
/// generated cycle's **name** and its stable `<schedule-id>:<sequence>` id select the
/// same document. A caller selecting estimate mode, a milestone scope or an end-date
/// forecast goes through WP05's `tix analytics export` verb, which builds the same
/// document through [`chart_document`] — the target owns the document, the verb owns the
/// flags (analysis-report H9). A missing `--cycle` is the same `InvalidInput` `ics`
/// reports; a reference nothing resolves to is a `not_found`.
///
/// Side-effect policy: the document goes to stdout, or to `--output` through the existing
/// atomic export writer (temp file + rename) the other local targets use. Diagnostics —
/// the remote-tracker and version findings — go to **stderr**, so they are reported
/// without corrupting the machine-readable stdout. They are informational, never a
/// refusal and never a drop: every value they are about stays in the document (NFR-002).
pub fn run_chart(
    config: &Config,
    store: &Store,
    cycle: Option<&str>,
    output: Option<&str>,
) -> Result<()> {
    let document = run_chart_core(config, store, cycle)?;
    for diagnostic in &document.diagnostics {
        eprintln!("diagnostic: {}", diagnostic.render());
    }
    let json = document.to_json_pretty()?;
    match output {
        Some(path) => {
            ics::write_to_path(std::path::Path::new(path), &json)?;
            println!("{path}");
        }
        None => print!("{json}"),
    }
    Ok(())
}

/// The local chart export core: the referenced cycle's count-mode document, with no
/// printing and no writing.
///
/// Split out of [`run_chart`] so a test or an MCP/portable parity check can read exactly
/// the document the CLI emits without capturing stdout (the same split [`run_core`],
/// [`run_views_core`], [`run_health_core`], [`run_roadmap_core`], [`run_capacity_core`]
/// and [`run_time_core`] offer). It resolves the reference through [`cycle_scope_for`] and
/// delegates to [`chart_document`].
pub fn run_chart_core(config: &Config, store: &Store, cycle: Option<&str>) -> Result<ChartExport> {
    let reference = cycle.ok_or_else(|| TixError::InvalidInput("missing --cycle".into()))?;
    let scope = cycle_scope_for(config, store, reference)?;
    chart_document(config, store, &scope, Mode::Count, None, None)
}

/// The cycle scope a chart export names, from the caller's reference (T019/T022).
///
/// The reference is folded through the crate's one cycle identity adapter
/// ([`crate::capacity::resolve_cycle`]) over the project's own schedule index, so a
/// generated cycle's **name** and its stable `<schedule-id>:<sequence>` id select the
/// same scope — and therefore the same document — exactly as `tix capacity` resolves a
/// scope. The scope's id is the resolved cycle's canonical **name** rather than the
/// spelling the caller wrote, which is what makes the two spellings one document rather
/// than two that merely agree on their members.
///
/// The period is the resolved cycle's own declared `start_date`/`due_date`: the store
/// record's when the project has one (a generated cycle's dates live there and nowhere in
/// `tix.toml`), the legacy `[cycles.<name>]` table's otherwise — the two provenances
/// [`crate::capacity::schedule_index`] builds its index from. A cycle that declares
/// neither bound stays unbounded on that side, which the series reports as coverage
/// rather than guessing.
///
/// A reference nothing resolves to is a `not_found`, not an empty document — the same
/// answer `tix export --target ics` gives, with the stable-id spelling added.
pub fn cycle_scope_for(config: &Config, store: &Store, reference: &str) -> Result<AnalyticsScope> {
    let root =
        Config::project_root(&store.issues_dir).unwrap_or_else(|| std::path::PathBuf::from("."));
    let index = crate::capacity::schedule_index(config, &root)?;
    let name = match crate::capacity::resolve_cycle(&index, reference) {
        CycleReference::Generated { name, .. } | CycleReference::Legacy { name } => name,
        CycleReference::Unknown { name } => {
            return Err(TixError::NotFound(format!("cycle `{name}`")));
        }
    };
    let period = cycle_period(config, &root, &name)?;
    AnalyticsScope::cycle(name, period)
}

/// The declared period of the cycle `name` resolves to.
///
/// The store's record first — a generated cycle's dates are the record's, and a
/// store-less project's store list is the implicit `Default` cycle — then the legacy
/// `[cycles.<name>]` table, which is the whole registry of a project with no
/// `docs/cycles/`. Neither is a guess: a bound the cycle does not declare stays absent,
/// and the series reports that as coverage.
///
/// A name the index answered for but that neither registry declares is left unbounded
/// rather than invented; the series then refuses to enumerate the period, which is the
/// visible answer this module gives when a reference resolves to nothing it can date.
fn cycle_period(config: &Config, root: &std::path::Path, name: &str) -> Result<Period> {
    if let Some(record) = crate::cycle_store::CycleStore::new(root)
        .list()?
        .into_iter()
        .find(|record| record.name == name)
    {
        return Period::new(record.start_date, record.due_date);
    }
    match config.cycles.get(name) {
        Some(cycle) => Period::new(cycle.start_date.clone(), cycle.due_date.clone()),
        None => Ok(Period::default()),
    }
}

/// The one chart-document core every surface reads (T019–T023).
///
/// `scope` is the **already-resolved** scope: the caller folds its `--cycle` reference
/// through [`cycle_scope_for`] and its `--milestone` reference through
/// [`milestone_scope`](crate::analytics::events::milestone_scope). Either way the fold
/// keys membership on the identity the scope's `id` resolves to rather than on the
/// spelling, so a scope built from a cycle's name and one built from its stable id select
/// the same members; [`cycle_scope_for`] canonicalizes to the name, so they are also the
/// same document. `mode`/`unit` are the caller's choice; `unit` is required in estimate
/// mode (an issue count is unitless, so count mode ignores it) and is resolved by WP03's
/// [`estimate_series`], which is the crate's one estimate entry point. `projection` is
/// the caller's `(as_of, end_date)` pair, both dates required together and both the
/// caller's own, never a clock: when it is absent the document carries no forecast.
///
/// It reads the store's issues **once** and folds them through WP02's [`ScopeSnapshot`],
/// so a document's numbers are the shared fold's and this file recomputes nothing; the
/// configured remote targets add their own findings. Read-only: nothing is written, and
/// the only side effects are the reads the fold already makes.
pub fn chart_document(
    config: &Config,
    store: &Store,
    scope: &AnalyticsScope,
    mode: Mode,
    unit: Option<&str>,
    projection: Option<(&str, &str)>,
) -> Result<ChartExport> {
    let root =
        Config::project_root(&store.issues_dir).unwrap_or_else(|| std::path::PathBuf::from("."));
    let index = crate::capacity::schedule_index(config, &root)?;
    let issues = store.list_all()?;
    let snapshot = ScopeSnapshot::build(config, &index, &issues, scope);
    let series = match mode {
        Mode::Count => snapshot.series(Mode::Count),
        Mode::Estimate => {
            let unit = unit.ok_or_else(|| {
                TixError::InvalidInput("estimate mode needs a unit (--unit)".into())
            })?;
            estimate_series(&snapshot, &issues, config, unit)
        }
    };
    let projection = match projection {
        Some((as_of, end_date)) => Some(crate::analytics::projection::project(
            &series, as_of, end_date,
        )?),
        None => None,
    };
    let targets = configured_remote_targets(config);
    Ok(ChartExport::build(&series, projection.as_ref(), &targets))
}

/// The configured remote trackers that cannot carry a chart document, in a stable order.
///
/// The names are the `[export.*]` sections' own (`gitlab`, then `linear`), so the
/// finding names the target the same way `tix export` does. Nothing is resolved beyond
/// the presence of the section: this is the export's *diagnostic* half, not a mapping.
fn configured_remote_targets(config: &Config) -> Vec<&'static str> {
    let mut targets = Vec::new();
    if config.export.gitlab.is_some() {
        targets.push("gitlab");
    }
    if config.export.linear.is_some() {
        targets.push("linear");
    }
    targets
}

/// `tix export --target beads` — the CLI face of [`run_beads_core`].
///
/// **Writes through `bd`**, never the Dolt database: the rows are staged as JSONL
/// and handed to `bd import`, which upserts by their deterministic id
/// (`tix-<number>`), so a re-run updates instead of duplicating.
///
/// The one thing the CLI adds over the core is `--output <path>`, which writes the
/// JSONL document instead of pushing it — the same rows `bd import` would receive,
/// so a caller can inspect or pipe them.
fn run_beads(
    config: &Config,
    store: &Store,
    dry_run: bool,
    output: Option<&str>,
    verbose: bool,
) -> Result<()> {
    if let Some(path) = output {
        // `--output` writes the **whole** document, never the incremental diff: the
        // reason to name a file is to inspect or pipe a complete interchange, and a
        // caller piping it into another workspace has no state file to be
        // incremental against. `tix beads push` is the incremental face.
        let plan = beads_plan(config, store)?;
        if verbose {
            for diagnostic in &plan.diagnostics {
                eprintln!("{diagnostic}");
            }
        }
        ics::write_to_path(std::path::Path::new(path), &beads::to_jsonl(&plan.rows)?)?;
        println!("{path}");
        return Ok(());
    }
    let report = run_beads_core(
        config,
        store,
        ExportOptions {
            dry_run,
            all: false,
            verbose,
        },
    )?;
    if dry_run && report.trim().is_empty() {
        // An empty dry run is the *good* case, and silence would read as a failure.
        eprintln!("nothing changed since the last export (pass --all to send everything)");
    }
    print!("{report}");
    Ok(())
}

/// The beads rows for this store, built in **one** place.
///
/// The export target, the `--output` document, and the `beads` command group's
/// `push` all come through here, so they cannot disagree about the mapping or the
/// id prefix.
fn beads_plan(config: &Config, store: &Store) -> Result<beads::BeadsPlan> {
    let resolution = crate::workflow::resolution(config, config.default_config(), "default");
    let issues = store.list()?;
    // **One** pass over the whole graph. A `relationships_for(issue.number)` loop
    // would read every issue file and rebuild the graph once per issue — millions
    // of file reads at this repository's size — where this reads once.
    let relationships = store.all_relationships()?;
    Ok(beads::plan(
        &config.beads.id_prefix,
        &resolution,
        &issues,
        &relationships,
    ))
}

/// How one beads export should behave.
///
/// A struct rather than four positional booleans: `run_beads_core` is reached from
/// three surfaces (the `export` target, `tix beads push`, and the MCP tool), and
/// a call site that says `ExportOptions { all: true, .. }` cannot silently pass
/// `all` where `verbose` was meant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExportOptions {
    /// Print the JSONL a real run would send, and write nothing at all.
    pub dry_run: bool,
    /// Ignore the export watermark and send every issue.
    pub all: bool,
    /// List the per-issue diagnostics. Off by default: a board of this size
    /// produces hundreds, and a run that sends three issues should not print the
    /// local-field notes for the other 1700.
    pub verbose: bool,
}

/// Above this many rows an import is long enough that a reader starts to wonder
/// whether it is stuck.
const SLOW_EXPORT_THRESHOLD: usize = 100;

/// The pre-flight line: what is going, and a word when that is a lot.
///
/// A function rather than an `eprintln!` written inline so the threshold is
/// testable at its own boundary — a hundred rows say nothing, a hundred and one
/// say so.
fn preflight_line(sending: usize, total: usize, unchanged: usize) -> String {
    let caveat = if sending > SLOW_EXPORT_THRESHOLD {
        " — this may take a while..."
    } else {
        ""
    };
    format!("exporting {sending} of {total} issue(s) to beads ({unchanged} unchanged){caveat}")
}

/// The shared beads export.
///
/// **Incremental by default.** Each row is fingerprinted ([`beads::fingerprint`])
/// and compared with the fingerprint recorded for its beads id in the state file;
/// a row that matches has not changed since it was last sent, so it is not sent
/// again. A second run with nothing changed therefore does **no** `bd import` at
/// all — which is the difference between one pass over the tree and a full
/// 1700-row upsert every time.
///
/// `options.all` forces every row through, which is what a lost state file (or a
/// workspace rebuilt from scratch) needs; `tix beads push --all`.
///
/// `options.dry_run` returns the JSONL of the rows a real run would send — the
/// changed ones — and, like every dry run, writes nothing: not to beads, and not
/// to the state file either, so previewing does not advance the watermark.
///
/// ## Which stream says what
///
/// **stdout carries the report** (and, on a dry run, the JSONL itself, so it can
/// be piped into `bd import`), and **stderr carries the progress and the
/// per-issue diagnostics**. The pre-flight count goes out *before* `bd import`
/// starts, because a run over thousands of issues is otherwise silent for the
/// part a reader is waiting on.
pub fn run_beads_core(config: &Config, store: &Store, options: ExportOptions) -> Result<String> {
    let ExportOptions {
        dry_run,
        all,
        verbose,
    } = options;
    let root =
        Config::project_root(&store.issues_dir).unwrap_or_else(|| std::path::PathBuf::from("."));
    let beads::BeadsPlan { rows, diagnostics } = beads_plan(config, store)?;

    let workspace = beads::workspace_identity(config);
    let mut state = beads::load_state(&root);
    // A watermark is only meaningful for the workspace it was written against.
    // Without this, pointing tix at a different workspace would look like "every
    // issue was already exported" and send *nothing* — silently.
    let workspace_changed = !state.exported.is_empty() && state.workspace != workspace;
    if workspace_changed {
        state.exported.clear();
    }
    let beads::BeadsPayload {
        rows: payload,
        fingerprints,
        unchanged,
    } = beads::select_payload(rows, &state.exported, all)?;

    // Only the diagnostics belonging to the rows being **sent** are worth a word: a
    // repeat run that sends nothing must not replay three hundred "cannot
    // represent" lines about issues it did not touch.
    let sent: BTreeSet<u32> = payload
        .iter()
        .filter_map(|row| beads::number_from_id(&row.id, &config.beads.id_prefix))
        .collect();
    let reported: Vec<&beads::BeadsDiagnostic> = diagnostics
        .iter()
        .filter(|diagnostic| {
            diagnostic
                .number
                .is_none_or(|number| sent.contains(&number))
        })
        .collect();

    if workspace_changed {
        // Before anything else, because it explains why everything is going again.
        eprintln!(
            "the beads workspace changed since the last export; the export watermark was reset"
        );
    }
    if verbose {
        for diagnostic in &reported {
            eprintln!("{diagnostic}");
        }
    }

    if dry_run {
        return beads::to_jsonl(&payload);
    }
    let total = payload.len() + unchanged;
    if payload.is_empty() {
        return Ok(format!(
            "nothing to export: all {unchanged} issue(s) are unchanged since the last export\n"
        ));
    }

    // The one line worth printing *before* an import that can take a while.
    eprintln!("{}", preflight_line(payload.len(), total, unchanged));
    let mut report = beads::push(&crate::sync::ProcessRunner, &config.beads.binary, &payload)?;
    // The watermark advances only after `bd import` succeeded, so a failed export
    // is retried whole rather than being silently recorded as done.
    for (id, fingerprint) in fingerprints {
        state.exported.insert(id, fingerprint);
    }
    state.workspace = workspace;
    beads::save_state(&root, &state)?;

    let hidden = if verbose || reported.is_empty() {
        String::new()
    } else {
        "; pass --verbose to list them".to_string()
    };
    report.push_str(&format!(
        "exported {} of {} issue(s) to beads ({} unchanged, {} diagnostic(s) — local data beads \
         cannot hold{hidden})\n",
        payload.len(),
        total,
        unchanged,
        reported.len()
    ));
    Ok(report)
}

pub fn run_views(config: &Config, output: Option<&str>) -> Result<()> {
    let document = run_views_core(config)?;
    for diagnostic in document.all_diagnostics() {
        eprintln!("diagnostic: {}", diagnostic.render());
    }
    let json = document.to_json_pretty()?;
    match output {
        Some(path) => {
            ics::write_to_path(std::path::Path::new(path), &json)?;
            println!("{path}");
        }
        None => print!("{json}"),
    }
    Ok(())
}

/// The portable-view export core: the document, with no printing and no writing.
///
/// Split out of [`run_views`] so an MCP/portable parity check or a test can read
/// exactly the document the CLI emits without capturing stdout (the same split
/// [`run_core`] offers the remote targets).
pub fn run_views_core(config: &Config) -> Result<PortableDocument> {
    let mut document =
        PortableDocument::from_registry(&config.views, &project_directory(), None, None);
    document.remote = PortableRemoteTargets::from_config(config);
    Ok(document)
}

/// The health export core (WP04): every health fact in the repository, as the one
/// portable DTO the CLI, the TUI, and MCP all render (C-007).
///
/// It reads and derives — issues, the memberships the planning services declare, the
/// index, the rollups — and never writes. Health is read-only on every surface
/// (C-007), so there is no `--apply` for it to honour.
///
/// When a remote target is configured, the document also carries what that target
/// cannot represent, as `unsupported_remote_field` diagnostics naming the field and
/// the target (T023): the export proves the value stays local instead of asking a
/// reader to trust that it did.
pub fn run_health_core(config: &Config) -> Result<PortableHealth> {
    let store = Store::open(config)?;
    let issues = store.list_all()?;
    // The planner reads the *project's* cycles and milestones, not the process's
    // working directory's: a test fixture gets its own, and a command run from
    // elsewhere does not pick up an unrelated repository's configuration.
    let root =
        Config::project_root(&store.issues_dir).unwrap_or_else(|| std::path::PathBuf::from("."));
    let planner = Planner::from_config(config.clone(), root);
    let cycles = planner.cycle_names();
    let milestones: Vec<String> = planner
        .list_milestones()?
        .into_iter()
        .map(|milestone| milestone.name)
        .collect();
    let policy = HealthPolicy::v1();
    let mut document = PortableHealth::build(&issues, &cycles, &milestones, &policy);

    // The remote half: one diagnostic per configured target, per issue-scoped value.
    let targets: Vec<(Tool, RemoteTarget)> = [
        (
            config.export.gitlab.is_some(),
            Tool::GitLab,
            RemoteTarget::GitLab,
        ),
        (
            config.export.linear.is_some(),
            Tool::Linear,
            RemoteTarget::Linear,
        ),
    ]
    .into_iter()
    .filter_map(|(configured, tool, target)| configured.then_some((tool, target)))
    .collect();
    if targets.is_empty() {
        return Ok(document);
    }
    for issue in &issues {
        let view = project(issue, &policy);
        let scope = HealthScope::of_issue(issue.number);
        for (tool, target) in &targets {
            let MappedHealth::Unsupported(diagnostic) =
                sync::map_health_to_remote(*tool, &scope, view.state)
            else {
                continue;
            };
            let wire = HealthDiagnostic::new(
                HealthDiagnosticKind::UnsupportedRemoteField,
                scope.clone(),
                diagnostic.message.clone(),
            )
            .referencing(diagnostic.relation_id.clone())
            .at_field(diagnostic.field.clone())
            .for_target(*target)
            .carrying(view.state.as_str());
            document
                .diagnostics
                .push(PortableHealthDiagnostic::from_diagnostic(&wire));
        }
    }
    document.diagnostics.sort_by(|left, right| {
        (&left.kind, &left.scope, &left.message).cmp(&(&right.kind, &right.scope, &right.message))
    });
    document
        .diagnostics
        .dedup_by(|left, right| left.same_as(right));
    Ok(document)
}

/// The project ids a project-scoped view can resolve against.
///
/// Empty for the same reason `commands::views::project_directory` is: `tix` has no
/// first-class project registry in this build. A project-scoped view therefore
/// exports with `resolution = "missing"` and the registry's own diagnostic rather
/// than being silently re-scoped to the repository.
fn project_directory() -> BTreeSet<String> {
    BTreeSet::new()
}

/// The export core (WP03): run the export orchestration and return the full
/// stdout report as a `String` — including the `nothing to export` line on an
/// empty store, so the MCP `export_issues` tool (WP04) can mirror CLI stdout
/// byte-for-byte (NFR-005).
///
/// The BAIL-early config gates (`no [export.gitlab] section`, missing
/// `project`) and their exact messages live in `sync`, and are surfaced here
/// untouched (C-006). Side-effect policy (C-005): the report is captured into
/// a buffer, never printed; the CLI renders it in [`run`] (which also keeps
/// `token::resolve` warnings on stderr as today).
///
/// `target` is `None` for a missing required arg — caught by the tool layer
/// before it reaches here per the MCP schema — and surfaces as the same
/// `unknown --target`-style `InvalidInput` error class (C-006).
pub fn run_core(
    config: &Config,
    store: &Store,
    target: Option<&str>,
    dry_run: bool,
    project_override: Option<&str>,
) -> Result<String> {
    let target = target.ok_or_else(|| {
        TixError::InvalidInput("missing --target — use gitlab or linear".to_string())
    })?;
    // `beads` is a local target reached through the `bd` CLI, not a tracker with a
    // `Tool` adapter, so it branches **before** the tracker validation — the same
    // reason the import path does. Both the CLI and the MCP `export_issues` tool
    // arrive here, so both get it.
    if target == "beads" {
        return run_beads_core(
            config,
            store,
            ExportOptions {
                dry_run,
                // The MCP tool takes neither `--all` nor `--verbose`: it is an
                // incremental export that reports its summary, and a tool result is
                // not a place for hundreds of per-issue lines.
                all: false,
                verbose: false,
            },
        );
    }
    let outcome = run_remote_core(config, store, target, dry_run, project_override)?;
    let mut text = outcome.report;
    for diagnostic in outcome.diagnostics {
        text.push_str(&diagnostic);
        text.push('\n');
    }
    Ok(text)
}

/// Run one remote export without choosing a presentation stream or exit status.
fn run_remote_core(
    config: &Config,
    store: &Store,
    target: &str,
    dry_run: bool,
    project_override: Option<&str>,
) -> Result<RemoteExportOutcome> {
    let tool = Tool::from_target(target)?;
    let config = apply_project_override(config, tool, project_override);
    let mut report: Vec<u8> = Vec::new();
    let outcome = sync::export(store, tool, &config, dry_run, &mut report)?;
    let handled = outcome.handled;
    if handled == 0 {
        report.extend_from_slice(b"nothing to export\n");
    }
    Ok(RemoteExportOutcome {
        report: String::from_utf8(report).expect("sync reports contain only UTF-8 text"),
        diagnostics: outcome
            .diagnostics
            .iter()
            .map(ToString::to_string)
            .collect(),
    })
}

/// Honor a `--project`/`--team` CLI override on a cloned config so the
/// on-disk `tix.toml` stays untouched.
fn apply_project_override(config: &Config, tool: Tool, project: Option<&str>) -> Config {
    let Some(project) = project else {
        return config.clone();
    };
    let mut config = config.clone();
    match tool {
        Tool::GitLab => {
            let remote = config.export.gitlab.get_or_insert_with(Default::default);
            remote.project = Some(project.to_string());
        }
        Tool::Linear => {
            let remote = config.export.linear.get_or_insert_with(Default::default);
            remote.team = Some(project.to_string());
        }
    }
    config
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::model::{Issue, Priority, Status};
    use std::fs;
    use tempfile::TempDir;

    fn make_store() -> (TempDir, Store) {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(&dir).unwrap();
        let config_path = tmp.path().join("tix.toml");
        let mut config = crate::config::Config {
            issues_dir: dir.clone(),
            ..crate::config::Config::default()
        };
        config.export.gitlab = Some(crate::config::RemoteConfig {
            project: Some("acme/tix".to_string()),
            ..Default::default()
        });
        config.save(&config_path).unwrap();
        let config = crate::config::Config::load_with_warning(&config_path, |_| {}).unwrap();
        (
            tmp,
            Store {
                issues_dir: dir,
                config,
            },
        )
    }

    #[test]
    fn the_preflight_line_warns_only_past_a_hundred_issues() {
        // The boundary itself: a hundred rows are quiet, a hundred and one are not.
        assert_eq!(
            preflight_line(100, 200, 100),
            "exporting 100 of 200 issue(s) to beads (100 unchanged)"
        );
        assert_eq!(
            preflight_line(101, 200, 99),
            "exporting 101 of 200 issue(s) to beads (99 unchanged) — this may take a while..."
        );
        // The incremental case that matters in practice: one issue going out of a
        // board of thousands says nothing about taking a while.
        assert_eq!(
            preflight_line(1, 1707, 1706),
            "exporting 1 of 1707 issue(s) to beads (1706 unchanged)"
        );
    }

    #[test]
    fn dry_run_captures_the_report_without_invoking_the_tool() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let mut issue = Issue {
            projects: None,
            id: None,
            number: 1,
            type_: None,
            title: "Replicate".to_string(),
            status: Status::new("todo"),
            labels: vec!["bug".to_string()],
            priority: Priority::High,
            assignee: Some("alice".to_string()),
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            related_issues: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".to_string(),
            updated: "2026-01-01".to_string(),
            filename: String::new(),
            body: "body".to_string(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            time_entries: vec![],
            parent: None,
            series: None,
            health: None,
            epics: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        issue.filename = "alice/2026-01-01-replicate.md".to_string();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        fs::write(
            store.issues_dir.join(&issue.filename),
            issue.to_file_contents(),
        )
        .unwrap();

        let report = run_core(&store.config, &store, Some("gitlab"), true, None).unwrap();
        assert!(
            report.contains("would create gitlab issue \"Replicate\""),
            "dry-run report must describe the planned create, got:\n{report}"
        );
        assert!(
            report.contains("dry run — gitlab CLI was not invoked"),
            "dry-run never invokes the binary, got:\n{report}"
        );
    }

    #[test]
    fn run_core_missing_export_section_is_the_frozen_config_error() {
        let (tmp, store) = make_store();
        let _ = tmp;
        // Drop the gitlab config the helper seeded: no binary is needed for
        // the BAIL gate to fire before any capture.
        let mut bare = store.config.clone();
        bare.export.gitlab = None;
        let err = run_core(&bare, &store, Some("gitlab"), false, None).unwrap_err();
        assert_eq!(
            err.to_string(),
            "config error: no `[export.gitlab]` section in tix.toml — run `tix init --with gitlab` or edit tix.toml"
        );
    }

    #[test]
    fn run_core_missing_target_is_an_invalid_input_error() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let err = run_core(&store.config, &store, None, true, None).unwrap_err();
        assert!(
            matches!(err, TixError::InvalidInput(_)),
            "missing target must be a structured InvalidInput error, got {err}"
        );
    }
}