tix-tracker 0.8.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
//! `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::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};
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 captured report to stdout
/// (the CLI keeps stdout clean and machine-parseable; warnings go to stderr
/// via `sync::token::resolve`).
pub fn run(
    config: &Config,
    store: &Store,
    target: &str,
    dry_run: bool,
    project_override: Option<&str>,
    cycle: Option<&str>,
    output: Option<&str>,
) -> Result<()> {
    if target == "ics" {
        return run_ics(config, store, cycle, output);
    }
    if target == "views" {
        return run_views(config, output);
    }
    if target == "health" {
        return run_health(config, output);
    }
    if target == "roadmap" {
        return run_roadmap(config, output);
    }
    if target == "capacity" {
        return run_capacity(config, store, cycle, output);
    }
    if target == "time" {
        return run_time(config, store, output);
    }
    if target == "chart" {
        return run_chart(config, store, cycle, output);
    }
    let report = run_core(config, store, Some(target), dry_run, project_override)?;
    print!("{report}");
    Ok(())
}

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
}

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())
    })?;
    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(String::from_utf8(report).expect("sync reports contain only UTF-8 text"))
}

/// 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 {
    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 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}"
        );
    }
}