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
#[allow(clippy::wildcard_imports)]
use super::*;

/// `tix import`: pull open remote issues into local files.
///
/// Conflict resolution: a remote issue that already tracks a local one skips
/// the local file when the local `updated` is later or equal; when the remote
/// `updated_at` is newer the local file is overwritten (fields + body, keeping
/// `created`), with the previous file first copied into the centralized backup
/// directory (`.tix-backups/` beside the issues directory, #1581).
///
/// `policy` is the explicit triage-entry policy (WP07 T034). It decides **only
/// where a newly created file lands and what the report says about it**: the
/// conflict rules above, remote ids, and adapter behaviour are untouched, and
/// the overwrite path never consults it (T036).
///
/// Returns the number of local files created or overwritten.
pub fn import(
    store: &Store,
    tool: Tool,
    config: &Config,
    out: &mut dyn Write,
    policy: crate::triage::import_policy::ImportPolicy,
) -> Result<SyncReport> {
    let mut adapter = adapter_for(tool, config)?;
    import_with_adapter(store, tool, config, out, policy, adapter.as_mut())
}

/// [`import`] with the adapter injected — the [`CommandRunner`] pattern, so the
/// orchestration under test is the real one and the remote side is a fake that
/// returns canned [`RemoteIssue`]s without spawning a process (WP07 T037).
///
/// `command`s like `tix import` still go through [`import`]; this entry point
/// exists so a test can hold every input of the triage policy in one place —
/// config, policy, and the remote payloads — instead of installing a fake
/// binary on `PATH` and running the compiled CLI to reach it.
#[allow(clippy::too_many_lines)]
pub fn import_with_adapter(
    store: &Store,
    tool: Tool,
    config: &Config,
    out: &mut dyn Write,
    policy: crate::triage::import_policy::ImportPolicy,
    adapter: &mut dyn TrackerAdapter,
) -> Result<SyncReport> {
    // Resolved **before** the loop: a policy this project cannot represent
    // refuses the whole import, not the third item of it.
    let router = crate::triage::import_policy::resolve(config, policy)?;
    let remote_issues = adapter.list_open()?;
    let mut report = SyncReport::default().diagnostics_in_report();
    let mut handled = 0;
    // Remote ids imported this run, paired with the local number each one landed
    // on. A parent is named by a **remote** id in the payload, so the reference can
    // only be restored after the parent itself has been created — which is why
    // this is a second pass rather than something set while building each issue.
    let mut imported: Vec<(String, u32)> = Vec::new();
    // `(child remote id, parent remote id)` for every payload that named one.
    let mut claims: Vec<(String, String)> = Vec::new();
    // `(remote issue id, the project references that payload reported)` — WP08.
    // Collected for **every** payload, and applied after the issues exist, so a
    // payload's order cannot decide whether an association lands (T037 step 4).
    let mut project_payloads: Vec<(String, Vec<RemoteProject>)> = Vec::new();
    // `(remote issue id, the epic references that payload reported)` — WP08. Same
    // second-pass treatment as the project payloads, so the order a payload's issues
    // arrive in cannot decide whether a reference lands.
    let mut epic_payloads: Vec<(String, Vec<RemoteEpic>)> = Vec::new();
    // `(remote issue id, the local number it landed on)` for every payload this run
    // found a local counterpart for — created here or already tracked. Distinct from
    // `imported`, which is create-only and is what the parent pass resolves
    // references through.
    let mut located: Vec<(String, u32)> = Vec::new();
    for remote in remote_issues.clone() {
        if let Some(parent) = remote.parent.clone() {
            claims.push((remote.id.clone(), parent));
        }
        if !remote.projects.is_empty() {
            project_payloads.push((remote.id.clone(), remote.projects.clone()));
        }
        if !remote.epics.is_empty() {
            epic_payloads.push((remote.id.clone(), remote.epics.clone()));
        }
        let tracked = store
            .list()?
            .into_iter()
            .find(|i| remote_ref(tool, i) == Some(remote.id.as_str()));
        match tracked {
            None => {
                // WP07 T034/T035: the placement decision is made here, once, from
                // the remote state and the configured entry column — before any
                // byte of the file exists. `requested` comes from this module's
                // own mapper rather than being re-derived by the policy, so the
                // two answers can be compared in the report instead of guessed at.
                let requested = remote_to_local_status(tool, &remote.state, config);
                let mapping = router.place(&remote.state, &requested);
                let mut issue = Issue {
                    projects: None,
                    id: None,
                    number: 0,
                    title: remote.title.clone(),
                    status: Status::new(mapping.landed.clone()),
                    labels: remote.labels.clone(),
                    priority: crate::model::Priority::Medium,
                    assignee: remote.assignee.clone(),
                    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: crate::model::today(),
                    type_: None,
                    updated: crate::model::today(),
                    filename: String::new(),
                    body: String::new(),
                    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,
                };
                // T035: entry metadata through the same seam every other entry
                // uses. The queue's age is measured from `entered_at`, so an issue
                // that entered the board through an import has to record that it
                // did — and `import` is the origin data-model §2 documents for it.
                //
                // The **landing column** decides, not `mapping.routed`: `routed` is a
                // policy notion, so under `--triage-policy remote` (or a default whose
                // remote-mapped column happens to be the entry column) an imported
                // issue landed in the inbox with no stamp and the queue reported
                // `unknown` for an issue it was listing. On a project with no
                // `[triage]` section the shared rule stamps nothing, which is the
                // outcome the old guard was reaching for.
                crate::triage::record_entry_if_inbox(config, &mut issue, "import")?;
                match tool {
                    Tool::GitLab => issue.gitlab_id = Some(remote.id.clone()),
                    Tool::Linear => issue.linear_id = Some(remote.id.clone()),
                }
                // WP07 T031: a **column check** on the incoming status, and only
                // that. `remote_to_local_status` already lands on a column the board
                // configures — the service's completion column, or a name match, or
                // the first — so this is the belt to that braces, and it means an
                // import can never create a file in a column the board lacks. The
                // create path performs the same check (WP05), so this is belt *and*
                // braces for the remote-sourced case.
                //
                // Not a transition evaluation: a new issue is not leaving anywhere, so
                // the terminal lock has nothing to say. Importing an issue directly
                // into a terminal column is legitimate.
                let (_, resolution) = crate::workflow::active_resolution(config);
                if resolution.resolve(issue.status.display()).is_none() {
                    // Reported, not written. A skipped item is visible and the rest of
                    // the batch still lands.
                    writeln!(
                        out,
                        "skipped {tool} issue {} \"{}\": `{}` is not a column on board `{}`",
                        remote.id, remote.title, issue.status, resolution.board
                    )?;
                    report.skipped += 1;
                    continue;
                }
                // One transaction per imported issue (#1580), never one over the
                // whole import: each remote issue has its own outcome, and a
                // failure on one must not roll back the others. `create` claims a
                // number and writes the file, so the claim and the bytes are one
                // unit.
                let path =
                    store.transaction(|| store.create(&mut issue, &remote.description, None))?;
                imported.push((remote.id.clone(), issue.number));
                located.push((remote.id.clone(), issue.number));
                let name = path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default();
                // T035: the mapping is named in the same line that names the file,
                // and `report_clause` is empty exactly when the default policy
                // decided nothing — so a legacy project's report is byte-identical
                // to what it was, and a project that routed says where the remote
                // state asked for and where the issue landed.
                let clause = mapping.report_clause();
                writeln!(
                    out,
                    "imported {tool} issue {} \"{}\" as #{} ({}) [{name}]{clause}",
                    remote.id, remote.title, issue.number, issue.status
                )?;
                handled += 1;
            }
            Some(local) => {
                // The payload found its local issue. Recorded before the branches
                // below, because the association pass needs to attach a remote
                // payload's projects to it whether or not this run also overwrote
                // its fields — "kept" is a statement about title and body, not about
                // membership.
                located.push((remote.id.clone(), local.number));
                if is_remote_newer(remote.updated_at.as_deref().unwrap_or(""), &local.updated) {
                    let backup = crate::backup::save(&store.issues_dir, &local.filename);
                    // Captured before `local` is moved into `overwritten`: the
                    // skip path restores the local status, and reading it back off
                    // `overwritten` after the assignment would restore the status the
                    // *incoming* value was about to overwrite.
                    let local_status = local.status.clone();
                    let mut overwritten = local;
                    let keep_created = overwritten.created.clone();
                    overwritten.title = remote.title.clone();
                    overwritten.body = remote.description.clone();
                    overwritten.labels = remote.labels.clone();
                    let incoming = Status::new(remote_to_local_status(tool, &remote.state, config));
                    // WP07 T031: validate the incoming status as a **transition**,
                    // because this *is* one — an existing issue moving columns.
                    //
                    // **Skip-and-report**, which is the disposition the design settles
                    // (T031 step 3). The alternative, apply-and-report, would make a
                    // board's policy non-binding for the one path nobody watches, and
                    // a remote whose states the board forbids would quietly win.
                    // Skipping keeps the local file truthful and puts the conflict in
                    // the report where a human will see it. Recorded here rather than
                    // in `data-model.md` §8, which is a protected path for this lane.
                    let (_, resolution) = crate::workflow::active_resolution(config);
                    let transition = crate::workflow::validate_transition(
                        &overwritten,
                        incoming.display(),
                        &resolution,
                        config,
                        None,
                    );
                    if let crate::workflow::TransitionOutcome::Rejected(diagnostic) = transition {
                        // The status is left alone; the other fields still import,
                        // because they are not what the policy governs. The file is
                        // rewritten, so this is a **partial** import — reported as such
                        // rather than as a plain overwrite.
                        overwritten.status = local_status.clone();
                        overwritten.title = remote.title.clone();
                        overwritten.body = remote.description.clone();
                        overwritten.labels = remote.labels.clone();
                        if let Some(a) = &remote.assignee {
                            overwritten.assignee = Some(a.clone());
                        }
                        overwritten.created = keep_created;
                        overwritten.bump_updated();
                        let filename = overwritten.filename.clone();
                        // One transaction for the item's corpus write (#1580): the
                        // `update` writes the file and may then reconcile its
                        // location, so those two mutations are one unit. The
                        // backup copy above is deliberately out-of-corpus and is
                        // not part of the journaled set.
                        store.transaction(|| store.update(&filename, &overwritten))?;
                        writeln!(
                            out,
                            "overwrote {tool} issue {} \"{}\" without its status: {diagnostic} \
                             (kept {})",
                            remote.id, overwritten.title, overwritten.status
                        )?;
                        report.skipped += 1;
                        handled += 1;
                        continue;
                    }
                    overwritten.status = incoming;
                    if let Some(a) = &remote.assignee {
                        overwritten.assignee = Some(a.clone());
                    }
                    overwritten.created = keep_created;
                    overwritten.bump_updated();
                    let filename = overwritten.filename.clone();

                    // An import that moves a locally-blocked issue into the
                    // board's completion column goes through the same blocked-move
                    // policy as every other surface -- WP04 T016 step 6 names
                    // "any bulk or import path" explicitly, and an import that
                    // can end an issue in the completion column with open
                    // blockers is the sharpest form of that.
                    //
                    // It **records** the acknowledgement rather than refusing, and
                    // the asymmetry is deliberate. There is no interactive
                    // confirmation available mid-import, and refusing would make
                    // `tix import` unusable whenever one issue in a batch carries
                    // a stale blocker -- turning a stale local edge into a
                    // permanently un-syncable board. The user ran the import;
                    // that is the decision, and the event exists to preserve it.
                    // Where a human is present to answer, refusing is right
                    // (`tix move`, `tix edit --status`, `move_issue`); here the
                    // honest record is that the import did it.
                    let guard = crate::commands::mv::blocked_move_guard(
                        config,
                        store,
                        &overwritten,
                        overwritten.status.display(),
                    )?;
                    if let Some(warning) = guard.warning() {
                        overwritten.history.append_now(
                            &crate::storage::actor_identity(),
                            crate::model::HistoryEventKind::BlockedMoveAcknowledged,
                            &format!("imported to {}: {warning}", overwritten.status.display()),
                        );
                    }
                    store.transaction(|| store.update(&filename, &overwritten))?;
                    let backup_label = backup
                        .as_ref()
                        .map(|p| p.display().to_string())
                        .unwrap_or_else(|| "none".to_string());
                    writeln!(
                        out,
                        "overwrote {tool} issue {} \"{}\" (remote newer; backup at {backup_label})",
                        remote.id, overwritten.title
                    )?;
                    handled += 1;
                } else {
                    writeln!(
                        out,
                        "kept {tool} issue {} \"{}\" (local updated later or equal)",
                        remote.id, remote.title
                    )?;
                }
            }
        }
    }
    restore_imported_parents(store, tool, &claims, &imported, &mut report, out)?;
    apply_imported_projects(
        store,
        config,
        tool,
        &project_payloads,
        &located,
        &mut report,
        out,
    )?;
    apply_imported_epics(
        store,
        config,
        tool,
        &epic_payloads,
        &located,
        &mut report,
        out,
    )?;
    writeln!(out, "imported {handled} {tool} issue(s)")?;
    report.handled = handled;
    Ok(report)
}

/// Restore the parent references an import's payload reported.
///
/// A **second pass**, because a payload names a parent by *remote* id and the
/// parent may well be imported after its child. Setting the field while building
/// each issue would therefore succeed or fail depending on the order the remote
/// happened to return, which is the order-dependence NFR-003 forbids.
///
/// Every write goes through [`crate::hierarchy::set_parent`] rather than a field
/// assignment, so an imported reference obeys the same rules as a CLI write: it is
/// validated before anything is written, and a refusal leaves the file
/// byte-identical. T032's note is explicit — "an import that would create a cycle
/// is a defect, not a special case" — and the service is what decides that, not
/// this loop.
///
/// `claims` is `(child remote id, parent remote id)` and `imported` is
/// `(remote id, local number)`. A pair where either side does not resolve becomes a
/// diagnostic rather than a write: a reference to an issue this run did not import
/// is exactly the unresolved-parent state WP05 added a finding for, and
/// manufacturing it here would be this loop's own defect.
pub(super) fn restore_imported_parents(
    store: &Store,
    tool: Tool,
    claims: &[(String, String)],
    imported: &[(String, u32)],
    report: &mut SyncReport,
    out: &mut dyn Write,
) -> Result<()> {
    for (child_remote, parent_remote) in claims {
        let child = imported
            .iter()
            .find(|(id, _)| id == child_remote)
            .map(|(_, number)| *number);
        let parent = imported
            .iter()
            .find(|(id, _)| id == parent_remote)
            .map(|(_, number)| *number);
        let (Some(child), Some(parent)) = (child, parent) else {
            report.note_parent(
                MappedParent::Unsupported(RemoteMappingDiagnostic {
                    relation_id: format!("{child_remote}->{parent_remote}"),
                    field: parent_field(tool).to_string(),
                    tool,
                    message: format!(
                        "remote issue {child_remote} reports parent {parent_remote}, \
                         which this import did not create — it may be closed, \
                         filtered out, or in another project; no local reference is \
                         written, so the issue stays parentless rather than \
                         unresolved"
                    ),
                }),
                out,
            )?;
            continue;
        };
        // Through `Store::set_parent`, which resolves, validates with the
        // hierarchy service, writes, and records the one History entry — the
        // same path `tix edit --parent` takes, so an imported reference is
        // indistinguishable from a typed one. A refusal is reported and nothing is
        // written.
        let (child_sel, parent_sel) = (child.to_string(), parent.to_string());
        match store.set_parent(&child_sel, &parent_sel) {
            Ok(_) => writeln!(out, "restored parent of {tool} issue #{child} to #{parent}")?,
            Err(e) => {
                writeln!(
                    out,
                    "could not restore the parent of {tool} issue #{child}: {e}; the \
                     reference was not written"
                )?;
                report.diagnostics.push(RemoteMappingDiagnostic {
                    relation_id: format!("{child}->{parent}"),
                    field: parent_field(tool).to_string(),
                    tool,
                    message: format!(
                        "the remote reports #{child} under #{parent}, but the hierarchy \
                         service refused it: {e}"
                    ),
                });
            }
        }
    }
    Ok(())
}

/// Apply the project associations an import's payloads reported (WP08 T037).
///
/// A **second pass**, like [`restore_imported_parents`], because the association
/// belongs to an issue that must exist locally first and because the order a
/// remote happened to list its issues in must not decide the outcome (T037 step
/// 4). Every payload that found a local issue is in `located`, so an issue created
/// *after* its sibling still gets its memberships.
///
/// ## Every write goes through the project service
///
/// [`Store::associate`] is the same path `tix project add` will take, so
/// uniqueness, reference validation and the one History entry per accepted change
/// are the service's decisions rather than a second membership rule here. An
/// already-present association is the service's idempotent no-op: it writes
/// nothing, appends nothing, and leaves the canonical file byte-stable — which is
/// what makes a repeated import a true no-op (T037 step 3).
///
/// ## Matching is by id, and only by id
///
/// `resolve_project_id` also accepts a project *name*, because a human selects
/// projects by name. An import must not: a name is a display label (C-002), so a
/// remote that renames a project — or a local registry whose name happens to
/// equal the remote's id — would resolve to the wrong project, or to a second
/// association for a membership that is already there. The registry is therefore
/// consulted by **key** before the service is called, which both enforces
/// id-only matching and makes the refusal diagnosable instead of an
/// `unknown_project` error string.
///
/// ## An unknown id is diagnosed, never written
///
/// Writing the association would manufacture a dangling reference — one per
/// issue, per run, for a project the registry has never heard of: the "missing
/// reference storm" T037 step 4 names. The remote keeps the association, the
/// local file is untouched, and the diagnostic names the field, the tool and the
/// id (C-005). The registry itself is **never** written: the local
/// `[projects.<id>]` section is this repository's configuration (C-001) and not
/// the remote's to rewrite, which is also why there is no window in which a
/// partially written registry could exist.
///
/// A payload the import skipped — an issue whose remote state is not a column on
/// the board — was already reported on its own line and has no local issue to
/// attach a membership to, so it is passed over here rather than diagnosed twice.
pub(super) fn apply_imported_projects(
    store: &Store,
    config: &Config,
    tool: Tool,
    payloads: &[(String, Vec<RemoteProject>)],
    located: &[(String, u32)],
    report: &mut SyncReport,
    out: &mut dyn Write,
) -> Result<()> {
    if payloads.is_empty() {
        return Ok(());
    }
    // Resolved once, with a **no-op** warning sink: this is the same resolution the
    // adapters use, and quoting the project name the remote reported is the one
    // place remote output reaches a diagnostic, so it has to be scrubbed. The sink
    // is silent because `token::resolve` already warned on the adapter's behalf for
    // this run — warning twice per import would be noise, not extra safety.
    let secret = token::resolve(tool, config, &token::RealEnv, &mut |_| {})
        .secret()
        .map(str::to_string);
    for (remote_id, projects) in payloads {
        let Some(local_number) = located
            .iter()
            .find(|(id, _)| id == remote_id)
            .map(|(_, number)| *number)
        else {
            continue;
        };
        for project in projects {
            let project_id = match map_project_from_remote(tool, project) {
                MappedProject::Remote { value, .. } => value,
                MappedProject::Unsupported(mut diagnostic) => {
                    scrub_diagnostic(&mut diagnostic, secret.as_deref());
                    report.note_project(MappedProject::Unsupported(diagnostic), out)?;
                    continue;
                }
            };
            if !config.projects.contains_key(project_id.as_str()) {
                let mut diagnostic = RemoteMappingDiagnostic {
                    relation_id: format!("{local_number}->{project_id}"),
                    field: project_field(tool).to_string(),
                    tool,
                    message: format!(
                        "the remote reports #{local_number} in project `{project_id}`{}, \
                         which this repository's registry does not declare; nothing was \
                         written — the association stays on the remote and no missing \
                         reference was created locally",
                        project
                            .name
                            .as_deref()
                            .map(|name| format!(" (`{name}`)"))
                            .unwrap_or_default()
                    ),
                };
                scrub_diagnostic(&mut diagnostic, secret.as_deref());
                report.note_project(MappedProject::Unsupported(diagnostic), out)?;
                continue;
            }
            match store.associate(&local_number.to_string(), &project_id) {
                Ok(applied) if applied.changed => {
                    writeln!(
                        out,
                        "associated {tool} issue #{local_number} with {}",
                        crate::projects::association_detail(&project_id, true)
                    )?;
                }
                // Already associated: the service's no-op, so nothing was written and
                // no History entry was appended. Silent on purpose — a report line per
                // unchanged association would make every re-import look like work.
                Ok(_) => {}
                Err(error) => {
                    let mut diagnostic = RemoteMappingDiagnostic {
                        relation_id: format!("{local_number}->{project_id}"),
                        field: project_field(tool).to_string(),
                        tool,
                        message: format!(
                            "the remote reports #{local_number} in project `{project_id}`, \
                             but the project service refused the association: {error}; the \
                             local association list is unchanged"
                        ),
                    };
                    scrub_diagnostic(&mut diagnostic, secret.as_deref());
                    report.note_project(MappedProject::Unsupported(diagnostic), out)?;
                }
            }
        }
    }
    Ok(())
}

/// Apply the epic references an import's payloads reported (WP08, mission
/// `epics-work-items-01M3BYW4`).
///
/// A **second pass**, like [`apply_imported_projects`], because the reference
/// belongs to an issue that must exist locally first and because the order a remote
/// happened to list its issues in must not decide the outcome. Every payload that
/// found a local issue is in `located`, so an issue created *after* its sibling
/// still gets its references.
///
/// ## Every write goes through the epic service
///
/// [`Store::reference_epic`] is the same path `tix edit --add-epic` takes, so
/// uniqueness, reference validation and the one History entry per accepted change
/// are the service's decisions rather than a second reference rule here. An
/// already-present reference is the service's idempotent no-op: it writes nothing,
/// appends nothing, and leaves the canonical file byte-stable — which is what makes
/// a repeated import a true no-op (T039 step 3).
///
/// ## Matching is by id, and only by id
///
/// `resolve_epic_id` also accepts an epic *name*, because a human selects epics by
/// name. An import must not: a name is a display label (C-003), so a remote that
/// renames an epic — or a local registry whose name happens to equal the remote's id
/// — would resolve to the wrong epic, or to a second reference for a reference that
/// is already there. The registry is therefore consulted by **key** before the
/// service is called, which both enforces id-only matching and makes the refusal
/// diagnosable instead of an `unknown_epic` error string.
///
/// ## An unknown id is diagnosed, never written
///
/// Writing the reference would manufacture a dangling reference — one per issue, per
/// run, for an epic the registry has never heard of: the "missing reference storm"
/// T039 step 4 names. The remote keeps the reference, the local file is untouched,
/// and the diagnostic names the field, the tool and the id (C-007). The registry
/// itself is **never** written: the local `[epics.<id>]` section is this repository's
/// configuration (C-004) and not the remote's to rewrite, which is also why there is
/// no window in which a partially written registry could exist.
///
/// A payload the import skipped — an issue whose remote state is not a column on the
/// board — was already reported on its own line and has no local issue to attach a
/// reference to, so it is passed over here rather than diagnosed twice.
pub(super) fn apply_imported_epics(
    store: &Store,
    config: &Config,
    tool: Tool,
    payloads: &[(String, Vec<RemoteEpic>)],
    located: &[(String, u32)],
    report: &mut SyncReport,
    out: &mut dyn Write,
) -> Result<()> {
    if payloads.is_empty() {
        return Ok(());
    }
    // Resolved once, with a **no-op** warning sink: the same resolution the adapters
    // use, and quoting the epic name the remote reported is the one place remote
    // output reaches a diagnostic, so it has to be scrubbed. The sink is silent
    // because `token::resolve` already warned on the adapter's behalf for this run.
    let secret = token::resolve(tool, config, &token::RealEnv, &mut |_| {})
        .secret()
        .map(str::to_string);
    for (remote_id, epics) in payloads {
        let Some(local_number) = located
            .iter()
            .find(|(id, _)| id == remote_id)
            .map(|(_, number)| *number)
        else {
            continue;
        };
        for epic in epics {
            let epic_id = match map_epic_from_remote(tool, epic) {
                MappedEpic::Remote { value, .. } => value,
                MappedEpic::Unsupported(mut diagnostic) => {
                    scrub_diagnostic(&mut diagnostic, secret.as_deref());
                    report.note_epic(MappedEpic::Unsupported(diagnostic), out)?;
                    continue;
                }
            };
            if !config.epics.contains_key(epic_id.as_str()) {
                let mut diagnostic = RemoteMappingDiagnostic {
                    relation_id: format!("{local_number}->{epic_id}"),
                    field: EPIC_FIELD.to_string(),
                    tool,
                    message: format!(
                        "the remote reports #{local_number} in epic `{epic_id}`{}, which \
                         this repository's registry does not declare; nothing was written \
                         — the reference stays on the remote and no missing reference \
                         was created locally",
                        epic.name
                            .as_deref()
                            .map(|name| format!(" (`{name}`)"))
                            .unwrap_or_default()
                    ),
                };
                scrub_diagnostic(&mut diagnostic, secret.as_deref());
                report.note_epic(MappedEpic::Unsupported(diagnostic), out)?;
                continue;
            }
            match store.reference_epic(&local_number.to_string(), &epic_id) {
                Ok(applied) if applied.changed => {
                    writeln!(
                        out,
                        "referenced {tool} issue #{local_number} with {}",
                        crate::epics::reference_detail(&epic_id, true)
                    )?;
                }
                // Already referenced: the service's no-op, so nothing was written and
                // no History entry was appended. Silent on purpose — a report line per
                // unchanged reference would make every re-import look like work.
                Ok(_) => {}
                Err(error) => {
                    let mut diagnostic = RemoteMappingDiagnostic {
                        relation_id: format!("{local_number}->{epic_id}"),
                        field: EPIC_FIELD.to_string(),
                        tool,
                        message: format!(
                            "the remote reports #{local_number} in epic `{epic_id}`, but \
                             the epic service refused the reference: {error}; the local \
                             reference list is unchanged"
                        ),
                    };
                    scrub_diagnostic(&mut diagnostic, secret.as_deref());
                    report.note_epic(MappedEpic::Unsupported(diagnostic), out)?;
                }
            }
        }
    }
    Ok(())
}

/// Whether a computed **remote** status conveys "done" in that tracker's own
/// vocabulary.
///
/// Deliberately **not** the completion decision. `closed` is GitLab's word and
/// `Done` is Linear's; neither is a local column name, so this cannot be a
/// category question, and routing it through the service would mean asking the
/// service about a string from a different vocabulary.
///
/// It used to decide *local* completion at the export call sites, by mapping the
/// local status out to a remote string and testing that — a round trip that can
/// disagree with the category rule on any board with a category_map. Those call
/// sites now ask \`workflow::is_completed\` about the local issue (C-004), and this
/// function keeps only the narrower job it can actually do: telling an adapter
/// whether its own status update already closed the remote issue.
pub(super) fn remote_ref(tool: Tool, issue: &Issue) -> Option<&str> {
    match tool {
        Tool::GitLab => issue.gitlab_id.as_deref(),
        Tool::Linear => issue.linear_id.as_deref(),
    }
}