tix-tracker 0.10.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
//! The local portable saved-view document (WP07; mission
//! `saved-issue-views-01M3C926`; T034–T038, C-001, C-002, C-003, C-005, C-007,
//! C-009, FR-001–FR-005, NFR-002, NFR-003).
//!
//! [`PortableDocument`] is the **local, loss-aware interchange form** of the
//! saved-view registry: a versioned JSON document carrying stable ids, display
//! names, scope metadata, normalized plans, board visibility, the active marker,
//! divergence, preserved extensions, and diagnostics. It is a *projection* of the
//! shared types — [`SavedView`](crate::views::registry::SavedView),
//! [`ViewScope`], [`ViewPlan`], [`ActiveViewMarker`], [`ViewDivergence`] — never a
//! second model: every field is read through those type's own accessors, so a
//! rename, a new optional criterion, or a display change cannot make the portable
//! form mean something the registry does not.
//!
//! # Loss-aware, not lossy (NFR-002/C-009)
//!
//! Three bags of unknown data survive a round trip verbatim:
//!
//! - the record-level and scope-level `extensions` of every view, exactly as
//!   `tix.toml` stores them;
//! - every unknown key inside `[plan]`, `[plan.filter]`, and `[plan.visibility]`,
//!   both in `plan` (the table as written) and in `normalized_plan` (the same
//!   table after [`ViewPlan::to_toml`], which also re-emits its preserved keys);
//! - document-level keys a future build may add, captured by
//!   [`PortableDocument::extensions`].
//!
//! Unknown metadata is *diagnosed as well as kept*: [`PortableDocument::diagnostics`]
//! reports it with the same [`ViewDiagnosticKind::UnknownMetadata`] vocabulary the
//! registry and the plan already use, so no surface has to learn a second one. Two
//! key shapes get a specific report rather than the generic "preserved" one:
//!
//! - a key that **names a remote export target** (`gitlab`, `linear`) — remote
//!   namespaces are kept separate from local view data and are never read from a
//!   view (T037);
//! - a key that looks like **executable or query-payload content** (`query`,
//!   `script`, `command`, …) — such a value is never interpreted, because a view
//!   is data, not code (C-004/C-009).
//!
//! Either way the value is retained, never dropped: dropping it would be the
//! silent metadata loss the mission forbids, and refusing the whole document over
//! one unknown key would make an older `tix` unable to read a newer registry.
//!
//! # Remote namespaces are separate (T037)
//!
//! Remote export (`tix export --target gitlab|linear`, `[export.*]`,
//! `src/sync/`) is a different concern with different storage: it writes remote
//! ids back into issue files and shells out to `glab`/`linear-cli`. A portable
//! view document describes *views*. The only place the two meet is
//! [`PortableRemoteTargets`]: a read-only echo of the configured remote targets,
//! present so a consumer can see which namespaces are remote without confusing
//! them for view data. It is populated from
//! [`Config::export`](crate::config::Config) by the export surface, it is never
//! derived from a view, and the remote **token is deliberately never projected**.
//!
//! # Determinism
//!
//! `toml::Table`, `serde_json::Map`, and the `Vec`s here are all ordered
//! (declaration order for views, sorted keys for tables), and no field is skipped
//! when serializing, so `document → JSON → document → JSON` is **byte-identical**
//! after the first pass. Repeated round trips are idempotent, including the
//! diagnostics: derived document diagnostics are merged without duplication
//! ([`PortableDocument::refresh_diagnostics`]).
#![allow(clippy::module_name_repetitions)]

use serde::{Deserialize, Serialize};
use toml::{Table, Value};

use crate::config::{Config, RemoteConfig};
use crate::error::{Result, TixError};
use crate::views::divergence::{ActiveViewMarker, ViewDivergence};
use crate::views::plan::ViewPlan;
use crate::views::registry::{
    ProjectDirectory, SavedView, ViewDiagnostic, ViewDiagnosticKind, ViewId, ViewRegistry,
    ViewScope,
};

/// The portable document's format marker. A consumer reads this before treating
/// the payload as a saved-view document.
pub const FORMAT: &str = "tix.saved-views";

/// The portable document version this build writes and reads.
///
/// A document with a different version is still read: its own fields are
/// preserved and the mismatch is reported as a diagnostic rather than a refusal,
/// because a newer `tix` writing one extra field must not make the definitions
/// unreadable.
pub const VERSION: u32 = 1;

/// The key names reserved for **remote** export targets.
///
/// A view (or a scope, or a plan) carrying one of these keys cannot have it read
/// as a remote namespace: remote export lives in `[export.*]` and `src/sync/`,
/// and a portable view document only ever echoes it under
/// [`PortableDocument::remote`].
pub const REMOTE_TARGETS: &[&str] = &["gitlab", "linear"];

/// Key names that denote executable or query-payload content.
///
/// The mission forbids arbitrary executable queries and new query languages
/// (C-004/C-009). Nothing here is executed or parsed; the names exist only so a
/// value under one of them is **reported as uninterpreted** rather than passing
/// silently through a portable document.
pub const EXECUTABLE_KEYS: &[&str] = &[
    "code",
    "command",
    "dsl",
    "exec",
    "expr",
    "expression",
    "jq",
    "program",
    "query",
    "run",
    "script",
    "shell",
    "sql",
];

/// One view diagnostic, projected into the portable vocabulary.
///
/// The shape mirrors the surface DTO every `tix view` arm already returns
/// (`kind`/`field`/`message`/`remedy`/`view_id`, with `null` for the parts a
/// diagnostic does not have), so CLI, MCP, and portable output cannot drift
/// (C-007/NFR-003). `kind` is the stable contract name — a plain string, so a
/// kind a newer build adds survives a round trip instead of failing to parse.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortableDiagnostic {
    /// The stable contract name of the diagnostic (`unknown_metadata`, …).
    pub kind: String,
    /// The view this is about, when it is about a stored definition.
    #[serde(default)]
    pub view_id: Option<String>,
    /// The record-relative field the problem sits at (`extensions.colour`, …).
    #[serde(default)]
    pub field: Option<String>,
    /// The human-readable explanation.
    pub message: String,
    /// What the caller can do about it, when there is something.
    #[serde(default)]
    pub remedy: Option<String>,
}

impl PortableDiagnostic {
    /// Project a registry/plan diagnostic into the portable vocabulary.
    #[must_use]
    pub fn from_diagnostic(diagnostic: &ViewDiagnostic) -> Self {
        Self {
            kind: diagnostic.kind().as_str().to_string(),
            view_id: diagnostic.view_id().map(|id| id.as_str().to_string()),
            field: diagnostic.field().map(str::to_string),
            message: diagnostic.message().to_string(),
            remedy: diagnostic.remedy().map(str::to_string),
        }
    }

    /// The stable contract name.
    #[must_use]
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// The view this is about, when there is one.
    #[must_use]
    pub fn view_id(&self) -> Option<&str> {
        self.view_id.as_deref()
    }

    /// The record-relative field, when the problem is field-shaped.
    #[must_use]
    pub fn field(&self) -> Option<&str> {
        self.field.as_deref()
    }

    /// The human-readable explanation.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// The actionable part, when there is one.
    #[must_use]
    pub fn remedy(&self) -> Option<&str> {
        self.remedy.as_deref()
    }

    /// One line, `kind [field]: message` — what a surface prints.
    #[must_use]
    pub fn render(&self) -> String {
        match self.field() {
            Some(field) => format!("{} [{field}]: {}", self.kind, self.message),
            None => format!("{}: {}", self.kind, self.message),
        }
    }

    /// Whether two diagnostics describe the same problem, which is how a derived
    /// diagnostic is merged without being appended twice on a repeated round trip.
    #[must_use]
    fn same_as(&self, other: &Self) -> bool {
        self.kind == other.kind
            && self.view_id == other.view_id
            && self.field == other.field
            && self.message == other.message
    }
}

/// The scope metadata of one portable view (data-model §2).
///
/// `kind` is a plain string rather than [`ViewScopeKind`](crate::views::registry::ViewScopeKind)
/// on purpose: a scope family a newer build introduces must survive a round trip,
/// and an enum would refuse the whole document instead. The projection mirrors the
/// surface DTO's `scope` object exactly — the scope's preserved unknown fields
/// live under `extensions`, never mixed into the scope's own keys.
///
/// [`ViewScopeKind`]: crate::views::registry::ViewScopeKind
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortableScope {
    /// The scope family's contract name (`repository`, `project`, `user_share`).
    pub kind: String,
    /// The project a project scope belongs to.
    #[serde(default)]
    pub project_id: Option<String>,
    /// The identity a user/share scope belongs to. A label, not an account.
    #[serde(default)]
    pub owner: Option<String>,
    /// The identities a user/share scope is shared with. Labels, not grants.
    #[serde(default)]
    pub shared_with: Vec<String>,
    /// Scope keys this build does not interpret, preserved verbatim.
    #[serde(default)]
    pub extensions: Table,
    /// Scope keys a **newer** portable format adds, preserved verbatim.
    #[serde(flatten)]
    pub extra: Table,
}

impl PortableScope {
    /// Project a registry scope into the portable form.
    #[must_use]
    pub fn from_scope(scope: &ViewScope) -> Self {
        Self {
            kind: scope.kind.as_str().to_string(),
            project_id: scope.project_id.clone(),
            owner: scope.owner.clone(),
            shared_with: scope.shared_with.clone(),
            extensions: scope.extensions.clone(),
            extra: Table::new(),
        }
    }
}

/// One saved view in the portable form (data-model §1).
///
/// `plan` is the `[plan]` table **as written**, so a consumer can rebuild the
/// stored definition byte for byte; `normalized_plan` is the same plan after
/// [`ViewPlan::from_toml`]/[`ViewPlan::to_toml`], which is the one normalized plan
/// every surface consumes (C-007) and is `None` exactly when this build cannot
/// interpret the stored plan — in which case the refusal's diagnostics are carried
/// in `diagnostics` and the `plan` table is still retained.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortableView {
    /// The stable identity. Immutable across rename; never reused.
    pub id: String,
    /// The display label. Mutable — it is not the identity.
    pub name: String,
    /// The explicit scope metadata.
    pub scope: PortableScope,
    /// The scope's derived resolution (`resolved`, `missing`, `conflict`).
    pub resolution: String,
    /// The persisted `[plan]` table, verbatim.
    #[serde(default)]
    pub plan: Table,
    /// The normalized plan, when this build can interpret it.
    #[serde(default)]
    pub normalized_plan: Option<Table>,
    /// Record-level fields this build does not interpret, preserved verbatim.
    #[serde(default)]
    pub extensions: Table,
    /// Unknown-metadata, scope, namespace, and executable-content diagnostics.
    #[serde(default)]
    pub diagnostics: Vec<PortableDiagnostic>,
    /// View keys a **newer** portable format adds, preserved verbatim.
    #[serde(flatten)]
    pub extra: Table,
}

impl PortableView {
    /// Project one stored view, given the registry-level diagnostics the caller's
    /// registry pass produced for it.
    ///
    /// The registry's own diagnostics are reused rather than recomputed, so the
    /// scope/unknown-field vocabulary has exactly one author; the keys this module
    /// classifies (a remote target name, an executable name) replace the generic
    /// "unknown field" notice for the same field instead of duplicating it.
    #[must_use]
    pub fn from_saved<P: ProjectDirectory + ?Sized>(
        view: &SavedView,
        projects: &P,
        registry_diagnostics: &[ViewDiagnostic],
    ) -> Self {
        let (normalized_plan, plan_diagnostics) = match ViewPlan::from_toml(&view.plan) {
            Ok(plan) => (Some(plan.to_toml()), plan.diagnostics()),
            Err(refusal) => (None, refusal.diagnostics().to_vec()),
        };

        let mut classified: Vec<String> = Vec::new();
        let mut diagnostics: Vec<ViewDiagnostic> = Vec::new();
        let tables = [
            ("extensions", Some(&view.extensions)),
            ("scope.extensions", Some(&view.scope.extensions)),
            // These three spell the path the way `ViewPlan::diagnostics()` does
            // (`plan.extensions.<key>`), so a classified key replaces the plan's
            // own unknown-metadata diagnostic instead of being emitted twice.
            ("plan.extensions", Some(&view.plan)),
            (
                "plan.filter.extensions",
                view.plan.get("filter").and_then(Value::as_table),
            ),
            (
                "plan.visibility.extensions",
                view.plan.get("visibility").and_then(Value::as_table),
            ),
        ];
        for (path, table) in tables {
            let Some(table) = table else { continue };
            for key in table.keys() {
                let field = format!("{path}.{key}");
                if let Some(diagnostic) = classify_key(&field, key, Some(&view.id)) {
                    classified.push(field);
                    diagnostics.push(diagnostic);
                }
            }
        }
        for diagnostic in registry_diagnostics.iter().chain(plan_diagnostics.iter()) {
            let replaces_classified = diagnostic
                .field()
                .is_some_and(|field| classified.iter().any(|seen| seen.as_str() == field));
            if !replaces_classified {
                diagnostics.push(diagnostic.clone());
            }
        }

        Self {
            id: view.id.as_str().to_string(),
            name: view.name.clone(),
            scope: PortableScope::from_scope(&view.scope),
            resolution: view.scope.resolution(projects).as_str().to_string(),
            plan: view.plan.clone(),
            normalized_plan,
            extensions: view.extensions.clone(),
            diagnostics: diagnostics
                .iter()
                .map(PortableDiagnostic::from_diagnostic)
                .collect(),
            extra: Table::new(),
        }
    }

    /// The stable identity.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    /// The normalized plan, when this build can interpret it.
    #[must_use]
    pub fn normalized_plan(&self) -> Option<&Table> {
        self.normalized_plan.as_ref()
    }

    /// Every diagnostic about this view.
    #[must_use]
    pub fn diagnostics(&self) -> &[PortableDiagnostic] {
        &self.diagnostics
    }
}

/// The active-view marker in the portable form (data-model §4).
///
/// Derived, informational provenance: it records which saved definition the live
/// board was associated with, not what the live filters are. `applied_plan` is the
/// normalized plan that was applied.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortableMarker {
    /// The stable id of the selected definition.
    pub view_id: String,
    /// The surface the marker came from (`cli`, `tui`, `mcp`).
    #[serde(default)]
    pub source: Option<String>,
    /// The optional display timestamp.
    #[serde(default)]
    pub applied_at: Option<String>,
    /// The normalized plan that was applied.
    #[serde(default)]
    pub applied_plan: Table,
    /// Marker keys a **newer** portable format adds, preserved verbatim.
    #[serde(flatten)]
    pub extra: Table,
}

impl PortableMarker {
    /// Project a marker.
    #[must_use]
    pub fn from_marker(marker: &ActiveViewMarker) -> Self {
        Self {
            view_id: marker.view_id().as_str().to_string(),
            source: marker.source().map(|surface| surface.as_str().to_string()),
            applied_at: marker.applied_at().map(str::to_string),
            applied_plan: marker.applied_plan().to_toml(),
            extra: Table::new(),
        }
    }
}

/// One divergent field: its record-relative path and the saved/live values.
///
/// `saved`/`live` are `None` when the field is unset on that side, which is why
/// they are serialized as `null` rather than omitted — "unset" is information.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortableDifference {
    /// The record-relative field path (`plan.sort`, `plan.visibility.hidden_columns`).
    pub field: String,
    /// The saved definition's normalized value, or `null` when unset.
    #[serde(default)]
    pub saved: Option<String>,
    /// The live normalized value, or `null` when unset.
    #[serde(default)]
    pub live: Option<String>,
}

/// The read-only divergence report in the portable form (data-model §5).
///
/// A derived, per-operation value: it compares the saved plan with the live plan
/// and never reconciles them. `in_sync` is false both when there are differences
/// and when there are diagnostics ("nothing to compare" is not "in sync").
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortableDivergence {
    /// The view the comparison is about, when one was identified.
    #[serde(default)]
    pub view_id: Option<String>,
    /// The saved definition's normalized plan, when it could be read.
    #[serde(default)]
    pub saved_plan: Option<Table>,
    /// The live normalized plan that was compared.
    #[serde(default)]
    pub live_plan: Table,
    /// The divergent fields, in a fixed field order.
    #[serde(default)]
    pub differences: Vec<PortableDifference>,
    /// Whether the live plan matches the saved plan, with no diagnostics.
    pub in_sync: bool,
    /// Problems that prevented or qualified the comparison.
    #[serde(default)]
    pub diagnostics: Vec<PortableDiagnostic>,
    /// Divergence keys a **newer** portable format adds, preserved verbatim.
    #[serde(flatten)]
    pub extra: Table,
}

impl PortableDivergence {
    /// Project a divergence report.
    #[must_use]
    pub fn from_divergence(divergence: &ViewDivergence) -> Self {
        Self {
            view_id: divergence.view_id().map(|id| id.as_str().to_string()),
            saved_plan: divergence.saved_plan().map(ViewPlan::to_toml),
            live_plan: divergence.live_plan().to_toml(),
            differences: divergence
                .differences()
                .iter()
                .map(|difference| PortableDifference {
                    field: difference.field().to_string(),
                    saved: difference.saved().map(str::to_string),
                    live: difference.live().map(str::to_string),
                })
                .collect(),
            in_sync: divergence.in_sync(),
            diagnostics: divergence
                .diagnostics()
                .iter()
                .map(PortableDiagnostic::from_diagnostic)
                .collect(),
            extra: Table::new(),
        }
    }
}

/// One **remote** export target, echoed read-only (T037).
///
/// This is not view data and is never read as such: it carries the configured
/// remote namespace's own non-secret fields so a consumer can tell the two apart.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortableRemoteTarget {
    /// The target name (`gitlab`, `linear`).
    pub name: String,
    /// The target's configured fields, verbatim — **never** its token.
    #[serde(default)]
    pub fields: Table,
    /// Target keys a **newer** portable format adds, preserved verbatim.
    #[serde(flatten)]
    pub extra: Table,
}

impl PortableRemoteTarget {
    /// Project one remote target. The token is deliberately excluded: it is a
    /// credential, `tix.toml` never writes it back, and a portable document must
    /// not start doing so.
    #[must_use]
    pub fn new(name: &str, remote: &RemoteConfig) -> Self {
        let mut fields = Table::new();
        for (key, value) in [
            ("base_url", &remote.base_url),
            ("project", &remote.project),
            ("team", &remote.team),
        ] {
            if let Some(value) = value {
                fields.insert(key.to_string(), Value::String(value.clone()));
            }
        }
        Self {
            name: name.to_string(),
            fields,
            extra: Table::new(),
        }
    }

    /// The target name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// The remote-export namespace of a portable document (T037).
///
/// Always **separate** from [`PortableDocument::views`]: it is populated from
/// `[export.*]` by the export surface and is empty for a document built only from
/// a registry. A local view never contributes a target here, and a view key that
/// happens to name a target is diagnosed instead (see [`classify_key`]).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct PortableRemoteTargets {
    /// The configured remote targets, in `gitlab` then `linear` order.
    #[serde(default)]
    pub targets: Vec<PortableRemoteTarget>,
    /// Namespace keys a **newer** portable format adds, preserved verbatim.
    #[serde(flatten)]
    pub extra: Table,
}

impl PortableRemoteTargets {
    /// The configured targets, read out of `[export.*]` — never out of a view.
    #[must_use]
    pub fn from_config(config: &Config) -> Self {
        let mut targets = Vec::new();
        if let Some(gitlab) = &config.export.gitlab {
            targets.push(PortableRemoteTarget::new("gitlab", gitlab));
        }
        if let Some(linear) = &config.export.linear {
            targets.push(PortableRemoteTarget::new("linear", linear));
        }
        Self {
            targets,
            extra: Table::new(),
        }
    }

    /// Whether no remote target is configured.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.targets.is_empty()
    }

    /// The configured targets.
    #[must_use]
    pub fn targets(&self) -> &[PortableRemoteTarget] {
        &self.targets
    }

    /// Whether the namespace names `name` as a remote target.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.targets.iter().any(|target| target.name == name)
    }
}

/// The local portable saved-view document (T034).
///
/// Build one from a registry with [`PortableDocument::from_registry`], add the
/// remote namespace with [`PortableDocument::with_remote`], and serialize it with
/// [`PortableDocument::to_json`] / [`PortableDocument::from_json`]. All fields are
/// public and always serialized — nothing is skipped — so a round trip is
/// byte-stable by construction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortableDocument {
    /// The format marker: [`FORMAT`].
    pub format: String,
    /// The format version: [`VERSION`].
    pub version: u32,
    /// Every view, in registry declaration order.
    #[serde(default)]
    pub views: Vec<PortableView>,
    /// The active marker, when one was projected.
    #[serde(default)]
    pub active: Option<PortableMarker>,
    /// The divergence report, when one was projected.
    #[serde(default)]
    pub divergence: Option<PortableDivergence>,
    /// The remote export namespace — separate from [`Self::views`] (T037).
    #[serde(default)]
    pub remote: PortableRemoteTargets,
    /// Document-level keys this build does not interpret, preserved verbatim.
    #[serde(flatten)]
    pub extensions: Table,
    /// Document-level diagnostics (format/version markers, unknown top-level keys).
    #[serde(default)]
    pub diagnostics: Vec<PortableDiagnostic>,
}

impl Default for PortableDocument {
    fn default() -> Self {
        Self::empty()
    }
}

impl PortableDocument {
    /// An empty document for this build's format version.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            format: FORMAT.to_string(),
            version: VERSION,
            views: Vec::new(),
            active: None,
            divergence: None,
            remote: PortableRemoteTargets::default(),
            extensions: Table::new(),
            diagnostics: Vec::new(),
        }
    }

    /// Project a registry — and optionally an active marker and divergence report
    /// — into the portable form (T034/T036).
    ///
    /// `projects` is the same project directory the registry's own resolution and
    /// diagnostics use, so a project-scoped view is reported `missing` here exactly
    /// as it is everywhere else. The remote namespace is left empty; the export
    /// surface fills it from `[export.*]` (T037).
    #[must_use]
    pub fn from_registry<P: ProjectDirectory + ?Sized>(
        registry: &ViewRegistry,
        projects: &P,
        active: Option<&ActiveViewMarker>,
        divergence: Option<&ViewDivergence>,
    ) -> Self {
        let registry_diagnostics = registry.diagnostics(projects);
        let views = registry
            .iter()
            .map(|view| {
                let own: Vec<ViewDiagnostic> = registry_diagnostics
                    .iter()
                    .filter(|diagnostic| diagnostic.view_id() == Some(&view.id))
                    .cloned()
                    .collect();
                PortableView::from_saved(view, projects, &own)
            })
            .collect();
        let mut document = Self {
            views,
            active: active.map(PortableMarker::from_marker),
            divergence: divergence.map(PortableDivergence::from_divergence),
            ..Self::empty()
        };
        document.refresh_diagnostics();
        document
    }

    /// Attach the remote export namespace read from `[export.*]`.
    #[must_use]
    pub fn with_remote(mut self, remote: PortableRemoteTargets) -> Self {
        self.remote = remote;
        self
    }

    /// The format marker as written.
    #[must_use]
    pub fn format(&self) -> &str {
        &self.format
    }

    /// The format version as written.
    #[must_use]
    pub const fn version(&self) -> u32 {
        self.version
    }

    /// Every view, in declaration order.
    #[must_use]
    pub fn views(&self) -> &[PortableView] {
        &self.views
    }

    /// One view by stable id.
    #[must_use]
    pub fn view(&self, id: &str) -> Option<&PortableView> {
        self.views.iter().find(|view| view.id == id)
    }

    /// The active marker, when one was projected.
    #[must_use]
    pub fn active(&self) -> Option<&PortableMarker> {
        self.active.as_ref()
    }

    /// The divergence report, when one was projected.
    #[must_use]
    pub fn divergence(&self) -> Option<&PortableDivergence> {
        self.divergence.as_ref()
    }

    /// The remote export namespace.
    #[must_use]
    pub const fn remote(&self) -> &PortableRemoteTargets {
        &self.remote
    }

    /// Document-level unknown keys, preserved verbatim.
    #[must_use]
    pub const fn extensions(&self) -> &Table {
        &self.extensions
    }

    /// Document-level diagnostics.
    #[must_use]
    pub fn diagnostics(&self) -> &[PortableDiagnostic] {
        &self.diagnostics
    }

    /// Every diagnostic in the document: the document's own first, then each
    /// view's in declaration order.
    ///
    /// What a surface reports. Unknown metadata is diagnosed *and* retained, so
    /// this list is informational — it never changes what the document carries.
    #[must_use]
    pub fn all_diagnostics(&self) -> Vec<&PortableDiagnostic> {
        let mut all: Vec<&PortableDiagnostic> = self.diagnostics.iter().collect();
        for view in &self.views {
            all.extend(view.diagnostics.iter());
        }
        all
    }

    /// Serialize the document as compact, byte-stable JSON.
    pub fn to_json(&self) -> Result<String> {
        serde_json::to_string(self)
            .map_err(|error| TixError::Parse(format!("portable view document: {error}")))
    }

    /// Serialize the document as indented JSON — what `tix export --target views`
    /// emits for a human.
    pub fn to_json_pretty(&self) -> Result<String> {
        serde_json::to_string_pretty(self)
            .map_err(|error| TixError::Parse(format!("portable view document: {error}")))
    }

    /// Read a portable document, reporting (never dropping) anything it carries
    /// that this build does not interpret.
    pub fn from_json(text: &str) -> Result<Self> {
        let mut document: Self = serde_json::from_str(text)
            .map_err(|error| TixError::Parse(format!("portable view document: {error}")))?;
        document.refresh_diagnostics();
        Ok(document)
    }

    /// Merge the diagnostics this build derives from the document into the ones it
    /// carried, without duplicating.
    ///
    /// Idempotent by design: `document → JSON → document → JSON` must be stable,
    /// and a derived diagnostic that a previous round trip already stored is
    /// *recognized* by [`PortableDiagnostic::same_as`] instead of appended a second
    /// time. The document's own diagnostics keep their order; only genuinely new
    /// derived ones are appended.
    pub fn refresh_diagnostics(&mut self) {
        let derived = self.derived_diagnostics();
        let mut merged: Vec<PortableDiagnostic> =
            Vec::with_capacity(self.diagnostics.len() + derived.len());
        for diagnostic in self.diagnostics.iter().chain(derived.iter()) {
            if !merged.iter().any(|seen| seen.same_as(diagnostic)) {
                merged.push(diagnostic.clone());
            }
        }
        self.diagnostics = merged;
    }

    /// The diagnostics the document itself implies: a foreign format/version
    /// marker, and every unknown top-level key — including one that names a remote
    /// target or looks executable, which get their specific report.
    #[must_use]
    fn derived_diagnostics(&self) -> Vec<PortableDiagnostic> {
        let mut diagnostics: Vec<ViewDiagnostic> = Vec::new();
        if self.format != FORMAT {
            diagnostics.push(
                ViewDiagnostic::new(
                    ViewDiagnosticKind::UnknownMetadata,
                    format!(
                        "portable document declares format `{}`, but this build writes and reads \
                         `{FORMAT}`; the declared value is preserved verbatim",
                        self.format
                    ),
                )
                .with_field("format")
                .with_remedy(
                    "read the document with the tool that wrote it, or migrate the format",
                ),
            );
        }
        if self.version != VERSION {
            diagnostics.push(
                ViewDiagnostic::new(
                    ViewDiagnosticKind::UnknownMetadata,
                    format!(
                        "portable document declares version {}, but this build writes and reads \
                         version {VERSION}; fields this build does not interpret are preserved \
                         verbatim",
                        self.version
                    ),
                )
                .with_field("version"),
            );
        }
        for key in self.extensions.keys() {
            diagnostics.push(match classify_key(key, key, None) {
                Some(diagnostic) => diagnostic,
                None => unknown_metadata(key),
            });
        }
        diagnostics
            .iter()
            .map(PortableDiagnostic::from_diagnostic)
            .collect()
    }
}

/// Classify one key by the shape it names: a remote export target, executable
/// content, or nothing this module needs to say anything specific about.
///
/// `field` is the record-relative path the key sits at (`extensions.colour`,
/// `plan.filter.query`); for a document-level key it is the key itself, because
/// those keys are inline at the top level. `key` is the bare name being
/// classified. Returns `None` for an ordinary unknown key, which the caller
/// reports with the generic preserved-verbatim notice instead.
fn classify_key(field: &str, key: &str, view_id: Option<&ViewId>) -> Option<ViewDiagnostic> {
    let (message, remedy) = if REMOTE_TARGETS.contains(&key) {
        (
            format!(
                "`{field}` names the remote export target `{key}`; remote namespaces are kept \
                 separate from local view data and the value is preserved verbatim"
            ),
            "rename the key; remote export configuration lives under `[export.*]`, never on a view"
                .to_string(),
        )
    } else if EXECUTABLE_KEYS.contains(&key) {
        (
            format!(
                "`{field}` looks like executable or query-payload content; this build never \
                 interprets it and preserves the value verbatim"
            ),
            "views are data-only; remove the key, or express the intent with a supported plan field"
                .to_string(),
        )
    } else {
        return None;
    };
    let diagnostic = match view_id {
        Some(id) => ViewDiagnostic::for_view(ViewDiagnosticKind::UnknownMetadata, id, message),
        None => ViewDiagnostic::new(ViewDiagnosticKind::UnknownMetadata, message),
    };
    Some(diagnostic.with_field(field.to_string()).with_remedy(remedy))
}

/// The generic preserved-verbatim notice for an unknown document-level key.
fn unknown_metadata(field: &str) -> ViewDiagnostic {
    ViewDiagnostic::new(
        ViewDiagnosticKind::UnknownMetadata,
        format!("`{field}` is not interpreted by this build; the value is preserved verbatim"),
    )
    .with_field(field.to_string())
}