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
//! Selection resolution: which issues a bulk operation acts on (WP01 T001, T002,
//! T005).
//!
//! The seam other work packages import, and the module that **owns** these types —
//! `crate::bulk` re-exports from here rather than the other way round. An earlier
//! arrangement had both modules re-exporting each other, which does not compile
//! and which is a sign the ownership was not decided.

use serde::{Deserialize, Serialize};

use crate::error::{Result, TixError};
use crate::model::Issue;
use crate::storage::{IssueSelector, Store};

// ---------------------------------------------------------------------------
// T001–T002 — selection
// ---------------------------------------------------------------------------

/// Where a selection came from.
///
/// Recorded rather than inferred, because the three sources have genuinely
/// different failure modes and a caller that has to report "what did you mean?"
/// needs to know whether the user typed a fragment or ran a filter (C-003).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SelectionSource {
    /// One or more explicit selectors: numbers, filename fragments, title
    /// fragments.
    Explicit,
    /// A `tix list --filter` query.
    Filter,
    /// A `tix search` query.
    Search,
}

impl SelectionSource {
    /// The word the diagnostics use, so a message names the grammar the user
    /// actually typed.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Explicit => "selector",
            Self::Filter => "filter",
            Self::Search => "search",
        }
    }
}

/// Which issues are in play, active or archived.
///
/// The archive mission (#190) owns archived-view policy. This enum does not
/// implement it: it carries the **request** so the later work packages can
/// delegate, and the default is the one the contract names — operational
/// selection follows the active view (data-model §1, contract §6).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum SelectionScope {
    /// Active issues only. The default, and the only scope that writes.
    #[default]
    Active,
    /// Active **and** archived.
    ActiveAndArchived,
    /// Archived only.
    ArchivedOnly,
}

impl SelectionScope {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Active => "active",
            Self::ActiveAndArchived => "active+archived",
            Self::ArchivedOnly => "archived",
        }
    }

    /// Parse the CLI spelling. Case-insensitive, because it is a user-typed word
    /// and the vocabulary is three items.
    pub fn parse(raw: &str) -> Result<Self> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "active" => Ok(Self::Active),
            "active+archived" | "all" => Ok(Self::ActiveAndArchived),
            "archived" | "archived-only" => Ok(Self::ArchivedOnly),
            other => Err(TixError::InvalidInput(format!(
                "unknown scope '{other}' — expected one of: active, active+archived, archived"
            ))),
        }
    }
}

/// A resolved, ordered, immutable snapshot of the issues a bulk operation acts on.
///
/// Built by [`Selection::resolve`]. The store is read; **nothing is written**, and
/// there is no method on this type that can write — that is the property
/// contract §3 needs, and it is structural rather than a promise.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Selection {
    source: SelectionSource,
    /// The selectors as the user typed them, in the order they typed them, with
    /// duplicates removed. Kept because a diagnostic that says "3 issues selected"
    /// when the user typed 4 selectors is a bug report waiting to happen.
    selectors: Vec<String>,
    /// The query, when the source was Filter or Search.
    query: Option<String>,
    issues: Vec<Issue>,
    scope: SelectionScope,
    /// Selectors that named the same issue as an earlier one.
    duplicates: Vec<String>,
}

impl Selection {
    /// Resolve a selection from explicit selectors and/or a query.
    ///
    /// Resolution order, and why: **explicit selectors first**, then the query's
    /// issues, then de-duplication. A user who typed both means the union, and
    /// taking the union in that order means the explicit ones lead — which is what
    /// a dry run should show first.
    ///
    /// Ambiguity and not-found are the **existing** diagnostics, propagated
    /// unwrapped (contract §2). The first version wrapped the selector failure in
    /// a fresh `NotFound`, and the user saw `not found: not found: issue matching
    /// …` — the same doubled prefix a relationship message had. One message, from
    /// one place.
    pub fn resolve(
        store: &Store,
        selectors: &[String],
        query: Option<&str>,
        source: SelectionSource,
        scope: SelectionScope,
    ) -> Result<Self> {
        let mut issues: Vec<Issue> = Vec::new();
        let mut seen_numbers: Vec<u32> = Vec::new();
        let mut seen_selectors: Vec<String> = Vec::new();
        let mut duplicates: Vec<String> = Vec::new();

        for raw in selectors {
            let selector = crate::commands::parse_selector(store, raw)?;
            let issue = store.get(selector).map_err(|_| {
                TixError::NotFound(format!(
                    "issue matching '{raw}' by number, filename or title"
                ))
            })?;
            // De-duplicated by **number**, not by the text typed: `12` and
            // `2026-01-12-alpha` name the same issue, and de-duplicating on the
            // text would apply the patch to it twice.
            if seen_numbers.contains(&issue.number) {
                duplicates.push(raw.clone());
                continue;
            }
            seen_numbers.push(issue.number);
            seen_selectors.push(raw.clone());
            issues.push(issue);
        }

        if let Some(query) = query {
            for issue in selection_query(store, query, source, scope)? {
                if seen_numbers.contains(&issue.number) {
                    continue;
                }
                seen_numbers.push(issue.number);
                issues.push(issue);
            }
        }

        if issues.is_empty() {
            // Not an error. An empty board is a valid selection — the plan then
            // proposes zero changes, which is the honest answer to a filter that
            // matched nothing. Conflating it with an error would make
            // `--dry-run` on an empty result look like a failure.
            return Ok(Self {
                source,
                selectors: seen_selectors,
                query: query.map(str::to_string),
                issues,
                scope,
                duplicates,
            });
        }

        Ok(Self {
            source,
            selectors: seen_selectors,
            query: query.map(str::to_string),
            issues,
            scope,
            duplicates,
        })
    }

    /// A snapshot from issues the caller **already has**, with no store involved.
    ///
    /// Two callers need this and neither is a test: the TUI multi-select (WP07)
    /// resolves a selection from the board's cards rather than from typed
    /// selectors, and a caller previewing a large in-memory set has no store to
    /// resolve against. Both want the same guarantee — a **value** that cannot grow
    /// — which is what makes this a constructor on the type rather than a `pub`
    /// field.
    ///
    /// The order is preserved rather than sorted: a board's column order is what a
    /// user sees, and a selection's order is presentation (the *fingerprint* is the
    /// order-insensitive part, and is the thing an apply is authorized for).
    ///
    /// Numbers are de-duplicated, because a board can list the same issue twice and
    /// a plan that writes it twice is the failure the data-model calls "the plan
    /// never double-writes an issue unintentionally".
    pub fn from_issues(
        issues: impl IntoIterator<Item = Issue>,
        source: SelectionSource,
        scope: SelectionScope,
    ) -> Self {
        let mut seen: Vec<u32> = Vec::new();
        let mut kept = Vec::new();
        for issue in issues {
            if seen.contains(&issue.number) {
                continue;
            }
            seen.push(issue.number);
            kept.push(issue);
        }
        Self {
            source,
            selectors: Vec::new(),
            query: None,
            issues: kept,
            scope,
            duplicates: Vec::new(),
        }
    }

    /// The issues, in the snapshot's order.
    pub fn issues(&self) -> &[Issue] {
        &self.issues
    }

    /// Take the snapshot, so a later stage owns it rather than borrowing.
    pub fn into_issues(self) -> Vec<Issue> {
        self.issues
    }

    pub fn source(&self) -> SelectionSource {
        self.source
    }

    pub fn query(&self) -> Option<&str> {
        self.query.as_deref()
    }

    pub fn scope(&self) -> SelectionScope {
        self.scope
    }

    /// The selectors after de-duplication, in the order they resolved.
    pub fn selectors(&self) -> &[String] {
        &self.selectors
    }

    /// Selectors that named an issue an earlier selector had already named.
    ///
    /// Reported rather than silently dropped: a user who typed `12 12 alpha` and
    /// sees "3 issues" would otherwise have no way to know the third selector was
    /// ignored. The plan renders this (WP02 T009).
    pub fn duplicates(&self) -> &[String] {
        &self.duplicates
    }

    pub fn len(&self) -> usize {
        self.issues.len()
    }

    pub fn is_empty(&self) -> bool {
        self.issues.is_empty()
    }

    /// The issue numbers, for a confirmation echo.
    pub fn numbers(&self) -> Vec<u32> {
        self.issues.iter().map(|i| i.number).collect()
    }

    /// A stable identity for this selection, so an apply can refuse a plan that
    /// was confirmed against a different snapshot (contract §4: "apply requires
    /// the exact confirmed plan").
    ///
    /// Built from the **numbers**, not from a hash of the issue contents: a user
    /// may edit a selected issue between preview and apply, and the plan still
    /// applies to *those issues* — the values were validated at preview time and
    /// re-validated at apply time, so a content hash would refuse a legitimate
    /// apply for the wrong reason. Membership is what has to match.
    pub fn fingerprint(&self) -> Vec<u32> {
        self.numbers()
    }

    /// Whether this selection matches a fingerprint, ignoring order.
    ///
    /// Order-insensitive on purpose. A selection's order is presentation; its
    /// **membership** is what an apply is authorized for, and rejecting an apply
    /// because the board came back in a different order would be a refusal with
    /// no user-visible cause.
    pub fn matches_fingerprint(&self, fingerprint: &[u32]) -> bool {
        let mut mine = self.numbers();
        let mut theirs = fingerprint.to_vec();
        mine.sort_unstable();
        theirs.sort_unstable();
        mine == theirs
    }
}

/// The issues a filter or search query names, through the **existing** matcher.
///
/// There is deliberately no bulk-specific filter language (contract §7). The only
/// reason this is a function rather than an inline call is that `Filter` and
/// `Search` resolve differently — a `Search` is pure substring, while a `Filter`
/// also interprets `key:value` tokens — and the difference has to be the existing
/// one. A bare term is a case-insensitive substring for **both** (tix #1498).
///
/// A `--filter` goes through the **same pair the list path uses**
/// ([`crate::search::resolve_filter_criteria`] then
/// [`crate::search::matches_issue`]) rather than straight to the token matcher.
/// The store-level tokens (`category:`, `scope:`, `parent:`) are *lifted out* of
/// the query by the resolver and answered from the store and the board's
/// resolution, so a matcher called on the raw string had no arm for them and fell
/// through to "matched nothing": `tix triage batch --filter scope:triage` reported
/// `0 of 0 would change` and exited 0, which is indistinguishable from a filter
/// that legitimately selected nothing (found by tix's post-merge mission review,
/// RISK-2).
fn selection_query(
    store: &Store,
    query: &str,
    source: SelectionSource,
    scope: SelectionScope,
) -> Result<Vec<Issue>> {
    let issues = store.list()?;
    // `from_issues` defers serialization until a matcher asks for it (tix #1520).
    let corpus = crate::search::Corpus::from_issues(issues.clone());
    // A bare term is a case-insensitive substring over the corpus for both
    // sources; a filter additionally interprets `key:value` tokens.
    // `query_matches` is the grammar matcher and `search_substring` is the
    // plain-substring one, so the two sources get the two **existing** matchers
    // rather than one approximation of both.
    //
    // The dispatch is on `source`, not `scope`: an archived-scope *search* is
    // still a search. The first version matched on `scope`, which does not carry
    // that distinction and so could not name a matcher at all.
    let _ = scope;
    let out: Vec<Issue> = match source {
        SelectionSource::Search => crate::search::search_substring(&corpus, query)
            .into_iter()
            .map(|hit| hit.issue)
            .collect(),
        _ => {
            // `matches_issue(query, filter, …)`: the resolver returns the query with
            // its store-level tokens lifted out, plus the structured filter that now
            // carries them.
            let (query_text, criteria) = crate::search::resolve_filter_criteria(store, query)?;
            let (_, resolution) = crate::workflow::active_resolution(&store.config);
            corpus
                .issues
                .iter()
                .zip(corpus.texts().iter())
                .filter(|(issue, text)| {
                    crate::search::matches_issue(&query_text, &criteria, issue, text, &resolution)
                })
                .map(|(issue, _)| issue.clone())
                .collect()
        }
    };
    Ok(out)
}

// ---------------------------------------------------------------------------
// T005 — scope metadata
// ---------------------------------------------------------------------------

/// The scope metadata an enumeration exposes, so a caller can say what it did.
///
/// A separate function from [`Selection::resolve`] because the **archive
/// enumeration seam** does not exist yet (#190 owns it). Rather than guess at its
/// shape and have WP05 rewrite the guess, this returns the request and says so —
/// and `can_write` is the one thing that genuinely depends on the scope, because
/// a bulk write to an archived issue is not a thing this mission does.
pub fn scope_metadata(scope: SelectionScope, selected: usize) -> ScopeMetadata {
    ScopeMetadata {
        scope,
        selected,
        // Archived issues are read-only in this mission. #190 owns the archive
        // service; until it lands there is nothing to delegate a write to, and
        // claiming otherwise would be a promise with no implementation behind it.
        can_write: scope == SelectionScope::Active,
        delegation_pending: scope != SelectionScope::Active,
    }
}

/// What a scope selection means, for the plan's header.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScopeMetadata {
    pub scope: SelectionScope,
    pub selected: usize,
    /// Whether this scope permits writes at all.
    pub can_write: bool,
    /// Whether a request for this scope needs the archive service before it can be
    /// honoured. Reported so a caller can say "not yet" instead of silently
    /// behaving as though archived issues were active ones.
    pub delegation_pending: bool,
}

impl std::fmt::Display for ScopeMetadata {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} ({} selected)", self.scope.as_str(), self.selected)?;
        if self.delegation_pending {
            write!(f, " — read-only, the archive service is not wired yet")?;
        }
        Ok(())
    }
}

/// Resolve a selector for a caller that only wants the number.
///
/// Exists so a test or a later surface can assert "this selector names that
/// issue" without building a whole `Selection`, and so the de-duplication
/// key — the number — is computed in exactly one place.
pub fn selector_number(store: &Store, raw: &str) -> Result<u32> {
    let selector: IssueSelector = crate::commands::parse_selector(store, raw)?;
    Ok(store.get(selector)?.number)
}