tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
//! The normalized view plan: the typed, validated query/board definition a saved
//! view applies (WP02; mission `saved-issue-views-01M3C926`).
//!
//! A [`ViewPlan`] is the answer to "what does this saved view ask for?" as a
//! *typed value* rather than a query string: the existing [`StructuredFilter`],
//! an optional text query, a supported sort key, a supported group key, and
//! board visibility settings. It is deliberately **not** a query engine.
//!
//! # No second query language (C-002/C-004)
//!
//! The plan adds no grammar and reimplements no matching. Filtering is the
//! existing [`StructuredFilter`] predicate; the text query is the existing
//! substring/fuzzy/control-token grammar; sorting is the existing `sort:` control
//! token; grouping is the existing `group:` control token; visibility is the
//! existing board `hidden_columns`/`show_mismatch` pair. [`ViewPlan::apply`]
//! reconstructs the *existing* query string and calls the *existing*
//! [`BoardState::build_filtered`] once — it never walks the corpus itself and
//! never mutates an issue (C-005/C-007).
//!
//! # Normalization, validation, diagnostics
//!
//! [`ViewPlan::normalize`] trims every textual value, drops the empty ones,
//! folds `overdue: false` to unset, and de-duplicates column lists.
//! [`ViewPlan::validate`] then reports *every* unsupported field as a
//! [`ViewDiagnostic`] the registry already defines — `invalid_filter`,
//! `invalid_sort`, `invalid_group`, `invalid_visibility` — with a
//! record-relative path (`plan.sort`, `plan.filter.category`, …), so a surface
//! renders the plan half of a record through the same vocabulary as its scope
//! half (T008/T009).
//!
//! Validation is a pure function of the plan, the active
//! [`BoardConfiguration`], and the project's configured category vocabulary
//! ([`Config::categories`]); it is called by [`ViewPlan::apply`] *before* the
//! board is built, and by the write path *before* persistence, so a rejected
//! plan produces no board and no `tix.toml` (T009/C-008).
//!
//! # Unknown metadata (T010/NFR-002)
//!
//! A plan round-trips through TOML — the shape `SavedView::plan` persists — and
//! every key this build does not interpret is preserved verbatim: at the plan
//! level, inside `[plan.filter]`, and inside `[plan.visibility]`. Those keys are
//! *never* fed to a matcher; they are reported as
//! [`ViewDiagnosticKind::UnknownMetadata`] diagnostics by [`ViewPlan::diagnostics`]
//! and carried back out on the next serialization. A newer `tix` that adds a
//! filter criterion writes it into `[plan.filter]`, and this build keeps it.

use crate::config::{BoardConfiguration, Config};
use crate::search::{Corpus, StructuredFilter};
use crate::ui::board::BoardState;
use crate::views::registry::{ViewDiagnostic, ViewDiagnosticKind, ViewId, ViewRefusal, ViewResult};
use crate::workflow::CategoryResolution;
use toml::{Table, Value};

/// The sort keys the existing `sort:` control token accepts
/// ([`crate::search::query_matches`]). The list is pinned here rather than
/// re-derived, because the token grammar is the authority and this is its
/// published spelling.
pub const SORT_KEYS: &[&str] = &[
    "created",
    "priority",
    "status",
    "cycle",
    "milestone",
    "due",
    "start",
    "reviewer",
];

/// The group keys the existing `group:` control token accepts.
pub const GROUP_KEYS: &[&str] = &["cycle", "milestone"];

/// Every key of the persisted `[plan.filter]` table that this build interprets.
const FILTER_KEYS: &[&str] = &[
    "assignee",
    "label",
    "status",
    "priority",
    "cycle",
    "milestone",
    "reviewer",
    "start_date",
    "due_date",
    "overdue",
    "parent",
    "category",
    "scope",
];

/// The board visibility part of a plan (data-model §3).
///
/// The two settings the board surface already has: the columns hidden from
/// render, and whether the computed "Mismatched" pseudo-column is shown. A
/// *present* [`ViewVisibility`] is an **absolute** snapshot — `hidden_columns`
/// replaces the live board's hidden set on apply — while the enclosing
/// [`ViewPlan::visibility`] being `None` means "do not constrain visibility,
/// inherit the live board". That distinction is what lets an acceptance run
/// restore "nothing hidden" rather than inherit someone else's hidden columns.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ViewVisibility {
    hidden_columns: Vec<String>,
    show_mismatch: Option<bool>,
}

impl ViewVisibility {
    /// A visibility setting, normalized: column names trimmed, blanks dropped,
    /// duplicates collapsed to their first position.
    #[must_use]
    pub fn new(hidden_columns: Vec<String>, show_mismatch: Option<bool>) -> Self {
        let mut visibility = Self {
            hidden_columns,
            show_mismatch,
        };
        visibility.normalize();
        visibility
    }

    /// The columns hidden from render, in declaration order.
    #[must_use]
    pub fn hidden_columns(&self) -> &[String] {
        &self.hidden_columns
    }

    /// Whether the mismatched pseudo-column is shown, when the plan says.
    ///
    /// `None` means "leave the board's own setting alone"; `Some(false)` is a
    /// real override that hides the column on a board configured to show it.
    #[must_use]
    pub const fn show_mismatch(&self) -> Option<bool> {
        self.show_mismatch
    }

    /// Trim, drop blanks and collapse duplicates in the hidden-column list.
    pub fn normalize(&mut self) {
        self.hidden_columns = normalize_columns(std::mem::take(&mut self.hidden_columns));
    }
}

/// The normalized query/board plan (data-model §3).
///
/// Construct one with [`ViewPlan::from_parts`] (the adapter from a filter modal's
/// [`StructuredFilter`] plus a raw query), [`ViewPlan::from_query`] (the raw
/// query alone), the `with_*` builders, or [`ViewPlan::from_toml`] (the persisted
/// shape). Whichever route, the value is normalized before it is returned.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ViewPlan {
    filter: StructuredFilter,
    text_query: Option<String>,
    sort: Option<String>,
    group: Option<String>,
    visibility: Option<ViewVisibility>,
    /// Plan-level keys this build does not interpret, preserved verbatim.
    extensions: Table,
    /// Unknown keys found inside `[plan.filter]`, preserved verbatim.
    filter_extensions: Table,
    /// Unknown keys found inside `[plan.visibility]`, preserved verbatim.
    visibility_extensions: Table,
}

impl ViewPlan {
    /// Adapt the two inputs every surface already has into one normalized plan
    /// (T007).
    ///
    /// `filter` is the typed modal state; `text_query` is the raw query string.
    /// Any `sort:`/`group:` control token in the query is **lifted** into the
    /// typed fields (first occurrence wins, matching
    /// [`crate::search::control_token`]) and removed from the text query, so the
    /// plan has exactly one place a sort or group lives. A typed field the caller
    /// already set wins over the token; the token is dropped either way.
    #[must_use]
    pub fn from_parts(filter: StructuredFilter, text_query: &str) -> Self {
        let mut plan = Self {
            filter,
            ..Self::default()
        };
        plan.absorb_control_tokens(text_query);
        plan.normalize();
        plan
    }

    /// A plan from a raw query string alone, with no structured criteria.
    #[must_use]
    pub fn from_query(text_query: &str) -> Self {
        Self::from_parts(StructuredFilter::default(), text_query)
    }

    /// The structured criteria.
    #[must_use]
    pub fn filter(&self) -> &StructuredFilter {
        &self.filter
    }

    /// The remaining text query, with control tokens lifted out. `None` when the
    /// plan carries no free text.
    #[must_use]
    pub fn text_query(&self) -> Option<&str> {
        self.text_query.as_deref()
    }

    /// The supported sort key, or `None` for the board's default ordering.
    #[must_use]
    pub fn sort(&self) -> Option<&str> {
        self.sort.as_deref()
    }

    /// The supported group key, or `None` for no grouping.
    #[must_use]
    pub fn group(&self) -> Option<&str> {
        self.group.as_deref()
    }

    /// The visibility snapshot, or `None` when the plan leaves visibility to the
    /// live board.
    #[must_use]
    pub fn visibility(&self) -> Option<&ViewVisibility> {
        self.visibility.as_ref()
    }

    /// Plan-level keys this build does not interpret, preserved verbatim.
    #[must_use]
    pub fn extensions(&self) -> &Table {
        &self.extensions
    }

    /// Whether the plan asks for nothing at all — no criteria, text, sort,
    /// group, visibility, or unknown metadata.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.filter == StructuredFilter::default()
            && self.text_query.is_none()
            && self.sort.is_none()
            && self.group.is_none()
            && self.visibility.is_none()
            && self.extensions.is_empty()
            && self.filter_extensions.is_empty()
            && self.visibility_extensions.is_empty()
    }

    /// Replace the structured criteria, normalizing the result.
    #[must_use]
    pub fn with_filter(mut self, filter: StructuredFilter) -> Self {
        self.filter = filter;
        self.normalize();
        self
    }

    /// Replace the text query, lifting any control tokens it carries.
    #[must_use]
    pub fn with_text_query(mut self, text_query: &str) -> Self {
        self.text_query = Some(text_query.to_string());
        self.absorb_control_tokens(&self.text_query.clone().unwrap_or_default());
        self.normalize();
        self
    }

    /// Set the sort key.
    #[must_use]
    pub fn with_sort(mut self, sort: &str) -> Self {
        self.sort = Some(sort.to_string());
        self.normalize();
        self
    }

    /// Set the group key.
    #[must_use]
    pub fn with_group(mut self, group: &str) -> Self {
        self.group = Some(group.to_string());
        self.normalize();
        self
    }

    /// Set the visibility snapshot.
    #[must_use]
    pub fn with_visibility(mut self, visibility: ViewVisibility) -> Self {
        self.visibility = Some(visibility);
        self.normalize();
        self
    }

    /// Attach plan-level unknown metadata (already normalized by the caller's
    /// round trip; kept verbatim here).
    #[must_use]
    pub fn with_extensions(mut self, extensions: Table) -> Self {
        self.extensions = extensions;
        self
    }

    /// Canonicalize every value (T008).
    ///
    /// Trims text, drops the empty ones, folds `overdue: false` to "unset", and
    /// normalizes column lists. Unsupported sort or group keys are **kept** —
    /// normalization is not validation, and [`Self::validate`] is what reports
    /// them. An explicit sort/group key is kept too: `sort:created` is a
    /// different plan from "no sort", because the board's own `order_by` is not
    /// the sorted path.
    pub fn normalize(&mut self) {
        self.filter.normalize();
        if self.filter.overdue == Some(false) {
            self.filter.overdue = None;
        }
        self.filter.scope = self
            .filter
            .scope
            .take()
            .map(normalize_columns)
            .filter(|columns| !columns.is_empty());
        self.text_query = self
            .text_query
            .take()
            .map(|query| query.trim().to_string())
            .filter(|query| !query.is_empty());
        self.sort = normalize_key(self.sort.take());
        self.group = normalize_key(self.group.take());
        if let Some(visibility) = &mut self.visibility {
            visibility.normalize();
        }
    }

    /// Report every unsupported field in the plan, against `board` and the
    /// project's category vocabulary (T009).
    ///
    /// Returns `Ok(())` only when every field is representable on this board.
    /// Otherwise the refusal carries one diagnostic per problem, in a stable
    /// order (filter, then sort, then group, then visibility), each with its
    /// record-relative field path. `config` is consulted for the **configured**
    /// category vocabulary — the same
    /// [`Config::categories`] the live `category:` token path validates against
    /// — so a plan cannot validate here and then match nothing on apply.
    pub fn validate(&self, board: &BoardConfiguration, config: &Config) -> ViewResult<()> {
        let mut diagnostics = Vec::new();
        self.validate_filter(board, config, &mut diagnostics);
        self.validate_sort(&mut diagnostics);
        self.validate_group(&mut diagnostics);
        self.validate_visibility(board, &mut diagnostics);
        if diagnostics.is_empty() {
            Ok(())
        } else {
            Err(ViewRefusal::from_diagnostics(diagnostics))
        }
    }

    /// Unknown-metadata notices for this plan (T010).
    ///
    /// Informational, never a refusal: the keys were preserved, and this is how a
    /// surface tells the user they exist. The fields are
    /// `plan.extensions.<key>`, `plan.filter.extensions.<key>`, and
    /// `plan.visibility.extensions.<key>`.
    #[must_use]
    pub fn diagnostics(&self) -> Vec<ViewDiagnostic> {
        let mut diagnostics = Vec::new();
        for (path, table) in [
            ("plan.extensions", &self.extensions),
            ("plan.filter.extensions", &self.filter_extensions),
            ("plan.visibility.extensions", &self.visibility_extensions),
        ] {
            for key in table.keys() {
                diagnostics.push(
                    ViewDiagnostic::new(
                        ViewDiagnosticKind::UnknownMetadata,
                        format!("plan carries an unknown field `{key}`, preserved as written"),
                    )
                    .with_field(format!("{path}.{key}")),
                );
            }
        }
        diagnostics
    }

    /// Serialize to the persisted `[plan]` table shape (T010).
    ///
    /// Only fields that are set are written, so an empty plan is an empty table.
    /// Unknown keys captured at any level are merged back into their original
    /// position, unchanged.
    #[must_use]
    pub fn to_toml(&self) -> Table {
        let mut table = Table::new();
        if let Some(query) = &self.text_query {
            table.insert("text_query".to_string(), Value::String(query.clone()));
        }
        if let Some(sort) = &self.sort {
            table.insert("sort".to_string(), Value::String(sort.clone()));
        }
        if let Some(group) = &self.group {
            table.insert("group".to_string(), Value::String(group.clone()));
        }

        let filter = self.filter_to_toml();
        if !filter.is_empty() {
            table.insert("filter".to_string(), Value::Table(filter));
        }

        if let Some(visibility) = &self.visibility {
            let mut visible = Table::new();
            // Always written, even empty: a present `[plan.visibility]` is an
            // absolute snapshot, and an empty one means "show every column". An
            // omitted `hidden_columns` would let the serializer drop an empty
            // table and turn an explicit setting into "inherit".
            visible.insert(
                "hidden_columns".to_string(),
                Value::Array(
                    visibility
                        .hidden_columns
                        .iter()
                        .cloned()
                        .map(Value::String)
                        .collect(),
                ),
            );
            if let Some(show_mismatch) = visibility.show_mismatch {
                visible.insert("show_mismatch".to_string(), Value::Boolean(show_mismatch));
            }
            for (key, value) in &self.visibility_extensions {
                visible.insert(key.clone(), value.clone());
            }
            table.insert("visibility".to_string(), Value::Table(visible));
        }

        // Last, so a captured key can never be shadowed by the writer above;
        // `from_toml` guarantees the two sets are disjoint.
        for (key, value) in &self.extensions {
            table.insert(key.clone(), value.clone());
        }
        table
    }

    /// Parse the persisted `[plan]` table shape (T010).
    ///
    /// Structural problems (a field of the wrong TOML type) are refusals; an
    /// unsupported *value* (`sort = "bogus"`) is not — that is
    /// [`Self::validate`]'s job, so a plan written by a newer build with a sort
    /// key this build does not know still loads and still round-trips.
    pub fn from_toml(table: &Table) -> ViewResult<Self> {
        let mut plan = Self::default();
        let mut diagnostics = Vec::new();
        for (key, value) in table {
            match key.as_str() {
                "text_query" => {
                    if let Some(text) = string_value(
                        value,
                        "plan.text_query",
                        ViewDiagnosticKind::InvalidFilter,
                        &mut diagnostics,
                    ) {
                        plan.text_query = Some(text);
                    }
                }
                "sort" => {
                    plan.sort = string_value(
                        value,
                        "plan.sort",
                        ViewDiagnosticKind::InvalidSort,
                        &mut diagnostics,
                    );
                }
                "group" => {
                    plan.group = string_value(
                        value,
                        "plan.group",
                        ViewDiagnosticKind::InvalidGroup,
                        &mut diagnostics,
                    );
                }
                "filter" => {
                    let Some(sub) = table_value(
                        value,
                        "plan.filter",
                        ViewDiagnosticKind::InvalidFilter,
                        &mut diagnostics,
                    ) else {
                        continue;
                    };
                    let (filter, unknown, error) = parse_filter(sub);
                    plan.filter = filter;
                    plan.filter_extensions = unknown;
                    diagnostics.extend(error);
                }
                "visibility" => {
                    let Some(sub) = table_value(
                        value,
                        "plan.visibility",
                        ViewDiagnosticKind::InvalidVisibility,
                        &mut diagnostics,
                    ) else {
                        continue;
                    };
                    let (visibility, unknown, errors) = parse_visibility(sub);
                    plan.visibility = Some(visibility);
                    plan.visibility_extensions = unknown;
                    diagnostics.extend(errors);
                }
                _ => {
                    plan.extensions.insert(key.clone(), value.clone());
                }
            }
        }
        if !diagnostics.is_empty() {
            return Err(ViewRefusal::from_diagnostics(diagnostics));
        }
        // A persisted `text_query` may itself carry `sort:`/`group:` tokens — a
        // plan written before the typed fields existed, or by a surface that
        // only had the raw query. Lift them exactly as `from_parts` does, so the
        // typed fields are authoritative and a token cannot be silently
        // overridden by the empty typed field on the next write.
        if let Some(text) = plan.text_query.take() {
            plan.absorb_control_tokens(&text);
        }
        plan.normalize();
        Ok(plan)
    }

    /// Apply the plan: build the board **once** through the existing filter path
    /// and return a read-only result (T011/C-005).
    ///
    /// Validates first, so an unsupported field returns a refusal and no board is
    /// built. The board's *visibility* comes from the plan when the plan sets it
    /// and from `board` otherwise; the *sort* and *group* are reconstructed as
    /// the existing control tokens, so the existing
    /// [`BoardState::build_filtered`] ordering and grouping apply unchanged.
    pub fn apply(
        &self,
        board: &BoardConfiguration,
        config: &Config,
        corpus: &Corpus,
        resolution: &CategoryResolution,
    ) -> ViewResult<ViewApplyResult> {
        self.validate(board, config)?;
        let effective = self.effective_board(board);
        let query = self.effective_query();
        let board_state = BoardState::build_filtered(
            &effective,
            config,
            corpus,
            &query,
            &self.filter,
            resolution,
        );
        let issue_numbers = collect_issue_numbers(&board_state);
        Ok(ViewApplyResult {
            view_id: None,
            plan: self.clone(),
            issue_numbers,
            board: board_state,
            diagnostics: self.diagnostics(),
        })
    }

    /// [`Self::apply`] for a plan reached through a stable view id, so the result
    /// carries the identity its surface selected.
    pub fn apply_as(
        &self,
        view_id: &ViewId,
        board: &BoardConfiguration,
        config: &Config,
        corpus: &Corpus,
        resolution: &CategoryResolution,
    ) -> ViewResult<ViewApplyResult> {
        let mut result = self.apply(board, config, corpus, resolution)?;
        result.view_id = Some(view_id.clone());
        Ok(result)
    }

    /// Lift `sort:`/`group:` control tokens out of `text_query` into the typed
    /// fields.
    ///
    /// The first occurrence wins, as [`crate::search::control_token`] does, and
    /// **every** occurrence is removed from the text query so the plan never
    /// carries two spellings of the same setting. A typed field the caller
    /// already set is left alone; the query's token is still dropped, because a
    /// plan has one sort and one group.
    fn absorb_control_tokens(&mut self, text_query: &str) {
        let mut kept: Vec<&str> = Vec::new();
        let mut sort = None;
        let mut group = None;
        for token in text_query.split_whitespace() {
            if let Some((key, value)) = token.split_once(':') {
                let value = value.trim().to_string();
                match key.to_ascii_lowercase().as_str() {
                    "sort" => {
                        if sort.is_none() {
                            sort = Some(value);
                        }
                        continue;
                    }
                    "group" => {
                        if group.is_none() {
                            group = Some(value);
                        }
                        continue;
                    }
                    _ => {}
                }
            }
            kept.push(token);
        }
        if self.sort.is_none() {
            self.sort = sort;
        }
        if self.group.is_none() {
            self.group = group;
        }
        self.text_query = Some(kept.join(" "));
    }

    /// The query string the existing matcher and board builder consume: the free
    /// text plus the typed sort/group re-spelled as their control tokens.
    ///
    /// Public because a surface that installs a plan into **live** filter state
    /// (the TUI, WP05) must hand the *same* query to the *same*
    /// [`BoardState::build_filtered`] path [`Self::apply`] uses. Re-spelling the
    /// tokens at the call site would be a second, drift-prone spelling of the
    /// control-token protocol (C-002/C-007/NFR-003).
    #[must_use]
    pub fn effective_query(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        if let Some(query) = &self.text_query {
            parts.push(query.clone());
        }
        if let Some(sort) = &self.sort {
            parts.push(format!("sort:{sort}"));
        }
        if let Some(group) = &self.group {
            parts.push(format!("group:{group}"));
        }
        parts.join(" ")
    }

    /// The board configuration a view is applied over: the live board, with its
    /// visibility replaced when the plan carries a snapshot.
    ///
    /// Public for the same reason as [`Self::effective_query`]: a surface that
    /// keeps the applied plan as live state (the TUI, WP05) rebuilds the board
    /// through the existing path, and the visibility it must use is exactly the
    /// one [`Self::apply`] used.
    #[must_use]
    pub fn effective_board(&self, board: &BoardConfiguration) -> BoardConfiguration {
        let mut effective = board.clone();
        if let Some(visibility) = &self.visibility {
            effective.hidden_columns = visibility.hidden_columns.clone();
            if let Some(show_mismatch) = visibility.show_mismatch {
                effective.show_mismatch = show_mismatch;
            }
        }
        effective
    }

    /// The `[plan.filter]` table for the typed criteria, plus preserved unknowns.
    fn filter_to_toml(&self) -> Table {
        let mut table = Table::new();
        let filter = &self.filter;
        let strings = [
            ("assignee", &filter.assignee),
            ("label", &filter.label),
            ("status", &filter.status),
            ("priority", &filter.priority),
            ("cycle", &filter.cycle),
            ("milestone", &filter.milestone),
            ("reviewer", &filter.reviewer),
            ("start_date", &filter.start_date),
            ("due_date", &filter.due_date),
            ("parent", &filter.parent),
            ("category", &filter.category),
        ];
        for (key, value) in strings {
            if let Some(value) = value {
                table.insert(key.to_string(), Value::String(value.clone()));
            }
        }
        if filter.overdue == Some(true) {
            table.insert("overdue".to_string(), Value::Boolean(true));
        }
        if let Some(scope) = &filter.scope {
            table.insert(
                "scope".to_string(),
                Value::Array(scope.iter().cloned().map(Value::String).collect()),
            );
        }
        for (key, value) in &self.filter_extensions {
            table.insert(key.clone(), value.clone());
        }
        table
    }

    fn validate_filter(
        &self,
        board: &BoardConfiguration,
        config: &Config,
        diagnostics: &mut Vec<ViewDiagnostic>,
    ) {
        if let Some(category) = &self.filter.category
            && !config.categories.contains(category)
        {
            diagnostics.push(
                ViewDiagnostic::new(
                    ViewDiagnosticKind::InvalidFilter,
                    format!("`category:{category}` is not a known workflow category"),
                )
                .with_field("plan.filter.category")
                .with_remedy(format!(
                    "this project's categories are: {}",
                    config.categories.order.join(", ")
                )),
            );
        }
        if let Some(parent) = &self.filter.parent
            && parent.parse::<u32>().is_err()
        {
            diagnostics.push(
                ViewDiagnostic::new(
                    ViewDiagnosticKind::InvalidFilter,
                    format!(
                        "`parent:{parent}` is not a resolved issue number; a saved plan \
                         stores the number, not the selector"
                    ),
                )
                .with_field("plan.filter.parent")
                .with_remedy("resolve the selector to its issue number before saving"),
            );
        }
        if let Some(scope) = &self.filter.scope {
            for column in scope {
                if !board.columns.contains(column) {
                    diagnostics.push(
                        ViewDiagnostic::new(
                            ViewDiagnosticKind::InvalidFilter,
                            format!("`scope` names column `{column}`, which this board does not configure"),
                        )
                        .with_field("plan.filter.scope")
                        .with_remedy(format!("configured columns: {}", board.columns.join(", "))),
                    );
                }
            }
        }
    }

    fn validate_sort(&self, diagnostics: &mut Vec<ViewDiagnostic>) {
        if let Some(sort) = &self.sort
            && !SORT_KEYS.contains(&sort.as_str())
        {
            diagnostics.push(
                ViewDiagnostic::new(
                    ViewDiagnosticKind::InvalidSort,
                    format!("`sort:{sort}` is not a supported sort key"),
                )
                .with_field("plan.sort")
                .with_remedy(format!("use one of: {}", SORT_KEYS.join(", "))),
            );
        }
    }

    fn validate_group(&self, diagnostics: &mut Vec<ViewDiagnostic>) {
        if let Some(group) = &self.group
            && !GROUP_KEYS.contains(&group.as_str())
        {
            diagnostics.push(
                ViewDiagnostic::new(
                    ViewDiagnosticKind::InvalidGroup,
                    format!("`group:{group}` is not a supported group key"),
                )
                .with_field("plan.group")
                .with_remedy(format!("use one of: {}", GROUP_KEYS.join(", "))),
            );
        }
    }

    fn validate_visibility(
        &self,
        board: &BoardConfiguration,
        diagnostics: &mut Vec<ViewDiagnostic>,
    ) {
        let Some(visibility) = &self.visibility else {
            return;
        };
        for column in &visibility.hidden_columns {
            if !board.columns.contains(column) {
                diagnostics.push(
                    ViewDiagnostic::new(
                        ViewDiagnosticKind::InvalidVisibility,
                        format!("visibility hides column `{column}`, which this board does not configure"),
                    )
                    .with_field("plan.visibility.hidden_columns")
                    .with_remedy(format!("configured columns: {}", board.columns.join(", "))),
                );
            }
        }
    }
}

/// The read-only result of applying a plan (data-model §6).
///
/// `issue_numbers` is the applied issue set in board order (visible columns, then
/// hidden columns, then the mismatched pseudo-column); `board` is the existing
/// board summary the filter path produced. Nothing here can write: the corpus and
/// config were borrowed, and the result owns copies only.
#[derive(Debug, Clone)]
pub struct ViewApplyResult {
    view_id: Option<ViewId>,
    plan: ViewPlan,
    issue_numbers: Vec<u32>,
    board: BoardState,
    diagnostics: Vec<ViewDiagnostic>,
}

impl ViewApplyResult {
    /// The stable view that was applied, when the caller selected one.
    #[must_use]
    pub fn view_id(&self) -> Option<&ViewId> {
        self.view_id.as_ref()
    }

    /// The normalized plan that produced this result.
    #[must_use]
    pub fn plan(&self) -> &ViewPlan {
        &self.plan
    }

    /// The applied issue set, in board order.
    #[must_use]
    pub fn issue_numbers(&self) -> &[u32] {
        &self.issue_numbers
    }

    /// The board the existing filter path built.
    #[must_use]
    pub const fn board(&self) -> &BoardState {
        &self.board
    }

    /// Unknown-metadata notices carried out of the plan.
    #[must_use]
    pub fn diagnostics(&self) -> &[ViewDiagnostic] {
        &self.diagnostics
    }
}

/// Normalize a list of column names: trimmed, blanks dropped, duplicates
/// collapsed to their first occurrence (declaration order preserved).
fn normalize_columns(columns: Vec<String>) -> Vec<String> {
    let mut out: Vec<String> = Vec::with_capacity(columns.len());
    for column in columns {
        let column = column.trim();
        if column.is_empty() || out.iter().any(|seen| seen == column) {
            continue;
        }
        out.push(column.to_string());
    }
    out
}

/// Trim and lower-case a control key; `None` for blank.
///
/// An explicit key is **never** folded to unset: an explicit `sort:created` is
/// not the same plan as no sort at all. With no sort token the board applies its
/// own `order_by` per column (default newest-first), while `sort:created` takes
/// the sorted path and orders by creation date **ascending**. Folding the two
/// would make applying a stored plan produce the opposite order from the query
/// that saved it.
fn normalize_key(key: Option<String>) -> Option<String> {
    let key = key?.trim().to_ascii_lowercase();
    if key.is_empty() { None } else { Some(key) }
}

/// Every issue number the board holds, in board order.
fn collect_issue_numbers(board: &BoardState) -> Vec<u32> {
    board
        .columns
        .iter()
        .chain(board.hidden.iter())
        .chain(std::iter::once(&board.mismatch))
        .flat_map(|column| column.cards.iter().map(|card| card.number))
        .collect()
}

/// A TOML value as a string, or a `field`-aware type diagnostic of `kind`.
fn string_value(
    value: &Value,
    field: &str,
    kind: ViewDiagnosticKind,
    diagnostics: &mut Vec<ViewDiagnostic>,
) -> Option<String> {
    match value.clone().try_into::<String>() {
        Ok(text) => Some(text),
        Err(error) => {
            diagnostics.push(
                ViewDiagnostic::new(kind, format!("`{field}` must be a string: {error}"))
                    .with_field(field.to_string()),
            );
            None
        }
    }
}

/// A TOML value as a table, or a `field`-aware type diagnostic.
fn table_value<'a>(
    value: &'a Value,
    field: &str,
    kind: ViewDiagnosticKind,
    diagnostics: &mut Vec<ViewDiagnostic>,
) -> Option<&'a Table> {
    match value {
        Value::Table(table) => Some(table),
        other => {
            diagnostics.push(
                ViewDiagnostic::new(
                    kind,
                    format!("`{field}` must be a table, found {}", other.type_str()),
                )
                .with_field(field.to_string()),
            );
            None
        }
    }
}

/// Split `[plan.filter]` into the typed criteria this build knows and the keys it
/// preserves.
fn parse_filter(table: &Table) -> (StructuredFilter, Table, Option<ViewDiagnostic>) {
    let mut known = Table::new();
    let mut unknown = Table::new();
    for (key, value) in table {
        if FILTER_KEYS.contains(&key.as_str()) {
            known.insert(key.clone(), value.clone());
        } else {
            unknown.insert(key.clone(), value.clone());
        }
    }
    match Value::Table(known).try_into::<StructuredFilter>() {
        Ok(filter) => (filter, unknown, None),
        Err(error) => (
            StructuredFilter::default(),
            unknown,
            Some(
                ViewDiagnostic::new(
                    ViewDiagnosticKind::InvalidFilter,
                    format!("`plan.filter` is malformed: {error}"),
                )
                .with_field("plan.filter"),
            ),
        ),
    }
}

/// Split `[plan.visibility]` into the typed settings this build knows and the
/// keys it preserves.
fn parse_visibility(table: &Table) -> (ViewVisibility, Table, Vec<ViewDiagnostic>) {
    let mut visibility = ViewVisibility::default();
    let mut unknown = Table::new();
    let mut errors = Vec::new();
    for (key, value) in table {
        match key.as_str() {
            "hidden_columns" => match value.clone().try_into::<Vec<String>>() {
                Ok(columns) => visibility.hidden_columns = columns,
                Err(found) => {
                    errors.push(
                        ViewDiagnostic::new(
                            ViewDiagnosticKind::InvalidVisibility,
                            format!(
                                "`plan.visibility.hidden_columns` must be a list of strings: {found}"
                            ),
                        )
                        .with_field("plan.visibility.hidden_columns"),
                    );
                }
            },
            "show_mismatch" => match value.clone().try_into::<bool>() {
                Ok(show) => visibility.show_mismatch = Some(show),
                Err(found) => {
                    errors.push(
                        ViewDiagnostic::new(
                            ViewDiagnosticKind::InvalidVisibility,
                            format!("`plan.visibility.show_mismatch` must be a boolean: {found}"),
                        )
                        .with_field("plan.visibility.show_mismatch"),
                    );
                }
            },
            _ => {
                unknown.insert(key.clone(), value.clone());
            }
        }
    }
    visibility.normalize();
    (visibility, unknown, errors)
}