nornir 0.5.1

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! **YouTrack / JIRA-style cards over funnel items** — a pure, additive
//! projection layer that turns the funnel's [`HistoryItem`]s (the Jira half of
//! "JIRA + Maven = nornir") into issue **cards**, groups them into a kanban
//! **board**, and filters them with a YouTrack-style **smart query**
//! (`type:bug is:open for:rickard sort:newest`).
//!
//! This module is deliberately **read-only and event-free**: it never touches the
//! `funnel_events` table, the proto, or the Iceberg schema. It projects whatever
//! [`history`](super::history::history) already returns, so it works today against
//! the live funnel and stays migration-safe. A future `facett-board` viz / the
//! `Funnel.Board` RPC / the `funnel cards` CLI all bind to these pure types; the
//! richer persisted card fields (assignee, comments, workflow state) land later as
//! new optional `funnel_events` columns (see `.nornir/funnel-cards.md`).
//!
//! Everything here is deterministic (FC-7): given the same items + query string the
//! output is bit-identical, so the board is golden-testable with no warehouse, no
//! GPU, and no clock.

use serde::{Deserialize, Serialize};

use super::event::ItemKind;
use super::history::{HistoryItem, HistoryStatus};

/// The issue **type** badge on a card — the JIRA/YouTrack vocabulary for the
/// funnel's [`ItemKind`]: a feature request, a bug, or a test-idea.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CardType {
    /// A feature / krav / prompt (funnel [`ItemKind::Idea`]).
    Feature,
    /// A bug / pasted error report (funnel [`ItemKind::Error`]).
    Bug,
    /// A desired/missing test (funnel [`ItemKind::Test`]).
    Test,
}

impl CardType {
    /// From the funnel item kind.
    #[must_use]
    pub fn from_item_kind(k: ItemKind) -> Self {
        match k {
            ItemKind::Idea => CardType::Feature,
            ItemKind::Error => CardType::Bug,
            ItemKind::Test => CardType::Test,
        }
    }
    /// The lower-case query/wire token (`feature` | `bug` | `test`).
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            CardType::Feature => "feature",
            CardType::Bug => "bug",
            CardType::Test => "test",
        }
    }
    /// Parse a query token, accepting both the JIRA/YouTrack word and the funnel
    /// `ItemKind` word (`idea`→feature, `error`→bug). Unknown → `None`.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "feature" | "idea" | "story" => Some(CardType::Feature),
            "bug" | "error" | "defect" => Some(CardType::Bug),
            "test" => Some(CardType::Test),
            _ => None,
        }
    }
}

/// A kanban **lane** (board column) — the workflow state, derived from the
/// funnel's [`HistoryStatus`]. The fixed left→right order is the board layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Lane {
    /// Submitted, not yet triaged (`Untriaged`).
    Inbox,
    /// Triaged `accept`, awaiting a plan (`Accepted`).
    Accepted,
    /// At least one plan refines it — work is tracked (`Planned`).
    Planned,
    /// Triaged `drop` — won't be worked (`Dropped`).
    Dropped,
}

impl Lane {
    /// From the funnel-derived history status.
    #[must_use]
    pub fn from_status(s: HistoryStatus) -> Self {
        match s {
            HistoryStatus::Untriaged => Lane::Inbox,
            HistoryStatus::Accepted => Lane::Accepted,
            HistoryStatus::Planned => Lane::Planned,
            HistoryStatus::Dropped => Lane::Dropped,
        }
    }
    /// The lower-case query/wire token.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Lane::Inbox => "inbox",
            Lane::Accepted => "accepted",
            Lane::Planned => "planned",
            Lane::Dropped => "dropped",
        }
    }
    /// The human column title.
    #[must_use]
    pub fn title(&self) -> &'static str {
        match self {
            Lane::Inbox => "Inbox",
            Lane::Accepted => "Accepted",
            Lane::Planned => "Planned",
            Lane::Dropped => "Dropped",
        }
    }
    /// Parse a query token, accepting the lane word and the `HistoryStatus` word
    /// (`untriaged`→inbox). Unknown → `None`.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "inbox" | "untriaged" | "open" => Some(Lane::Inbox),
            "accepted" => Some(Lane::Accepted),
            "planned" | "done" => Some(Lane::Planned),
            "dropped" => Some(Lane::Dropped),
            _ => None,
        }
    }
    /// The fixed board order (left→right).
    #[must_use]
    pub fn board_order() -> [Lane; 4] {
        [Lane::Inbox, Lane::Accepted, Lane::Planned, Lane::Dropped]
    }
    /// "Open" lanes = actionable, not yet closed (not Planned/Dropped). Used by the
    /// `is:open` smart-query operator.
    #[must_use]
    pub fn is_open(&self) -> bool {
        matches!(self, Lane::Inbox | Lane::Accepted)
    }
}

/// A YouTrack/JIRA-style issue **card** projected from a funnel [`HistoryItem`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Card {
    /// Stable id (`i-NNN`), the card identity (FC-5).
    pub id: String,
    /// One-line summary (the first line of the item text, trimmed).
    pub title: String,
    /// Full item text (the description body).
    pub body: String,
    /// Issue type badge.
    pub card_type: CardType,
    /// Workflow lane / board column.
    pub lane: Lane,
    /// Who reported it (the funnel `source`, e.g. `human:rickard`).
    pub reporter: String,
    /// RFC3339 creation time.
    pub created: String,
    /// Plan ids that refine this card (its lineage / linked work).
    pub plan_ids: Vec<String>,
    /// Labels: the type token, the lane token, and any `#hashtags` mined from the
    /// body — all deterministic, sorted, deduped (chip row on the card).
    pub labels: Vec<String>,
}

/// Extract `#hashtag` labels from free text (lower-cased, deduped, sorted). A tag
/// is `#` followed by `[A-Za-z0-9_-]+`.
#[must_use]
pub fn mine_hashtags(text: &str) -> Vec<String> {
    let mut tags: Vec<String> = Vec::new();
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'#' {
            let start = i + 1;
            let mut j = start;
            while j < bytes.len() {
                let c = bytes[j];
                if c.is_ascii_alphanumeric() || c == b'_' || c == b'-' {
                    j += 1;
                } else {
                    break;
                }
            }
            if j > start {
                tags.push(text[start..j].to_ascii_lowercase());
            }
            i = j;
        } else {
            i += 1;
        }
    }
    tags.sort();
    tags.dedup();
    tags
}

/// Project one funnel history item into a card.
#[must_use]
pub fn card_from_history(it: &HistoryItem) -> Card {
    let card_type = CardType::from_item_kind(it.item_kind);
    let lane = Lane::from_status(it.status);
    let title = it.text.lines().next().unwrap_or("").trim().to_string();
    let mut labels = vec![card_type.as_str().to_string(), lane.as_str().to_string()];
    labels.extend(mine_hashtags(&it.text));
    labels.sort();
    labels.dedup();
    Card {
        id: it.id.clone(),
        title,
        body: it.text.clone(),
        card_type,
        lane,
        reporter: it.source.clone(),
        created: it.submitted_at.clone(),
        plan_ids: it.plan_ids.clone(),
        labels,
    }
}

/// Project a whole history list into cards (order preserved from `history`,
/// which is newest-first).
#[must_use]
pub fn cards_from_history(items: &[HistoryItem]) -> Vec<Card> {
    items.iter().map(card_from_history).collect()
}

// ───────────────────────────── smart query ─────────────────────────────────

/// How a [`query_cards`] result is ordered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Sort {
    /// Newest created first (the default).
    #[default]
    Newest,
    /// Oldest created first.
    Oldest,
    /// By id ascending (stable, content-independent).
    Id,
}

impl Sort {
    fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "newest" | "updated" | "created" => Some(Sort::Newest),
            "oldest" => Some(Sort::Oldest),
            "id" => Some(Sort::Id),
            _ => None,
        }
    }
}

/// A parsed YouTrack-style smart query. Build it with [`parse_query`]; test a card
/// with [`Query::matches`]. Unknown operators degrade to free-text terms, so a
/// query is never an error — it just narrows.
///
/// Supported operators (case-insensitive keys):
/// - `type:` / `kind:` → feature | bug | test (also idea/error)
/// - `lane:` / `status:` → inbox | accepted | planned | dropped (also untriaged)
/// - `is:` → open | inbox | accepted | planned | dropped | done
/// - `reporter:` / `for:` → substring of the reporter (`for:me` → contains "rickard")
/// - `label:` → an exact label chip
/// - `has:plan` / `no:plan` → linked-plan presence
/// - `sort:` → newest | oldest | id
/// - any bare word → case-insensitive substring of title+body+id+reporter
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Query {
    pub types: Vec<CardType>,
    pub lanes: Vec<Lane>,
    pub open_only: bool,
    pub reporter_terms: Vec<String>,
    pub labels: Vec<String>,
    pub has_plan: Option<bool>,
    pub text_terms: Vec<String>,
    pub sort: Sort,
}

/// Parse a smart-query string into a [`Query`]. Quoting is not needed — operators
/// are whitespace-delimited `key:value` pairs; everything else is free text.
#[must_use]
pub fn parse_query(q: &str) -> Query {
    let mut out = Query::default();
    for tok in q.split_whitespace() {
        if let Some((key, val)) = tok.split_once(':') {
            let val = val.trim();
            if val.is_empty() {
                continue;
            }
            match key.to_ascii_lowercase().as_str() {
                "type" | "kind" => {
                    if let Some(t) = CardType::parse(val) {
                        out.types.push(t);
                    }
                }
                "lane" | "status" => {
                    if let Some(l) = Lane::parse(val) {
                        out.lanes.push(l);
                    }
                }
                "is" => match val.to_ascii_lowercase().as_str() {
                    "open" => out.open_only = true,
                    other => {
                        if let Some(l) = Lane::parse(other) {
                            out.lanes.push(l);
                        }
                    }
                },
                "reporter" | "for" | "assignee" => {
                    let v = if val.eq_ignore_ascii_case("me") { "rickard".to_string() } else { val.to_ascii_lowercase() };
                    out.reporter_terms.push(v);
                }
                "label" | "tag" => out.labels.push(val.to_ascii_lowercase()),
                "has" => {
                    if val.eq_ignore_ascii_case("plan") {
                        out.has_plan = Some(true);
                    }
                }
                "no" => {
                    if val.eq_ignore_ascii_case("plan") {
                        out.has_plan = Some(false);
                    }
                }
                "sort" => {
                    if let Some(s) = Sort::parse(val) {
                        out.sort = s;
                    }
                }
                // Unknown operator → treat the whole token as a free-text term.
                _ => out.text_terms.push(tok.to_ascii_lowercase()),
            }
        } else {
            out.text_terms.push(tok.to_ascii_lowercase());
        }
    }
    out
}

impl Query {
    /// Does `card` satisfy every constraint in this query? Multiple values of the
    /// same facet are OR'd (any type matches); across facets they are AND'd; free
    /// text terms must all appear somewhere.
    #[must_use]
    pub fn matches(&self, card: &Card) -> bool {
        if !self.types.is_empty() && !self.types.contains(&card.card_type) {
            return false;
        }
        if !self.lanes.is_empty() && !self.lanes.contains(&card.lane) {
            return false;
        }
        if self.open_only && !card.lane.is_open() {
            return false;
        }
        if let Some(want) = self.has_plan {
            if card.plan_ids.is_empty() == want {
                return false;
            }
        }
        let reporter_lc = card.reporter.to_ascii_lowercase();
        for r in &self.reporter_terms {
            if !reporter_lc.contains(r) {
                return false;
            }
        }
        for l in &self.labels {
            if !card.labels.iter().any(|c| c == l) {
                return false;
            }
        }
        if !self.text_terms.is_empty() {
            let hay = format!("{} {} {} {}", card.id, card.title, card.body, card.reporter).to_ascii_lowercase();
            for t in &self.text_terms {
                if !hay.contains(t) {
                    return false;
                }
            }
        }
        true
    }
}

/// Filter `cards` by the smart query `q` and order by its `sort` (deterministic;
/// ties always break on id so the result is stable).
#[must_use]
pub fn query_cards(cards: &[Card], q: &str) -> Vec<Card> {
    let query = parse_query(q);
    let mut out: Vec<Card> = cards.iter().filter(|c| query.matches(c)).cloned().collect();
    match query.sort {
        Sort::Newest => out.sort_by(|a, b| b.created.cmp(&a.created).then(a.id.cmp(&b.id))),
        Sort::Oldest => out.sort_by(|a, b| a.created.cmp(&b.created).then(a.id.cmp(&b.id))),
        Sort::Id => out.sort_by(|a, b| a.id.cmp(&b.id)),
    }
    out
}

// ───────────────────────────── board ───────────────────────────────────────

/// One board column: a lane + the cards in it (newest-first, id-stable).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Column {
    pub lane: Lane,
    pub title: String,
    pub cards: Vec<Card>,
}

/// A kanban **board**: the four lanes in fixed left→right order, each with its
/// cards. The `facett-board` viz binds directly to this.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Board {
    pub columns: Vec<Column>,
    /// Total cards across all columns.
    pub total: usize,
}

/// Group `cards` into the fixed-order kanban board. Within a column cards are
/// newest-first with an id tie-break (deterministic).
#[must_use]
pub fn board(cards: &[Card]) -> Board {
    let mut columns = Vec::with_capacity(4);
    for lane in Lane::board_order() {
        let mut col: Vec<Card> = cards.iter().filter(|c| c.lane == lane).cloned().collect();
        col.sort_by(|a, b| b.created.cmp(&a.created).then(a.id.cmp(&b.id)));
        columns.push(Column { lane, title: lane.title().to_string(), cards: col });
    }
    Board { total: cards.len(), columns }
}

/// The board as `state_json` (the headless robot-test + viz surface, LAW 6):
/// `{ total, columns: [{ lane, title, count, cards: [{id,title,type,reporter,labels,plans}] }] }`.
#[must_use]
pub fn board_to_json(b: &Board) -> serde_json::Value {
    serde_json::json!({
        "total": b.total,
        "columns": b.columns.iter().map(|c| serde_json::json!({
            "lane": c.lane.as_str(),
            "title": c.title,
            "count": c.cards.len(),
            "cards": c.cards.iter().map(|card| serde_json::json!({
                "id": card.id,
                "title": card.title,
                "type": card.card_type.as_str(),
                "reporter": card.reporter,
                "labels": card.labels,
                "plans": card.plan_ids.len(),
            })).collect::<Vec<_>>(),
        })).collect::<Vec<_>>(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn item(id: &str, kind: ItemKind, status: HistoryStatus, text: &str, source: &str, ts: &str, plans: &[&str]) -> HistoryItem {
        HistoryItem {
            id: id.to_string(),
            item_kind: kind,
            text: text.to_string(),
            source: source.to_string(),
            submitted_at: ts.to_string(),
            status,
            plan_ids: plans.iter().map(|s| s.to_string()).collect(),
        }
    }

    fn sample() -> Vec<HistoryItem> {
        vec![
            item("i-1", ItemKind::Idea, HistoryStatus::Untriaged, "Add #board view\nmulti-line body", "human:rickard", "2026-06-30T10:00:00+00:00", &[]),
            item("i-2", ItemKind::Error, HistoryStatus::Planned, "panic on empty #funnel", "human:ada", "2026-06-30T11:00:00+00:00", &["p-1"]),
            item("i-3", ItemKind::Test, HistoryStatus::Accepted, "cover topo_ready", "agent:autonom", "2026-06-30T09:00:00+00:00", &[]),
            item("i-4", ItemKind::Idea, HistoryStatus::Dropped, "rewrite in COBOL", "human:rickard", "2026-06-29T08:00:00+00:00", &[]),
        ]
    }

    /// The projection maps every funnel facet into card vocabulary, and labels are
    /// deterministic (type + lane + mined hashtags, sorted/deduped).
    #[test]
    fn card_projection_maps_facets_and_labels() {
        let c = card_from_history(&sample()[0]);
        assert_eq!(c.id, "i-1");
        assert_eq!(c.card_type, CardType::Feature);
        assert_eq!(c.lane, Lane::Inbox);
        assert_eq!(c.title, "Add #board view", "title is the first line, trimmed");
        assert_eq!(c.reporter, "human:rickard");
        assert!(c.labels.contains(&"feature".to_string()) && c.labels.contains(&"inbox".to_string()));
        assert!(c.labels.contains(&"board".to_string()), "mined the #board hashtag");
        // sorted + deduped
        let mut sorted = c.labels.clone();
        sorted.sort();
        sorted.dedup();
        assert_eq!(c.labels, sorted);

        let bug = card_from_history(&sample()[1]);
        assert_eq!(bug.card_type, CardType::Bug);
        assert_eq!(bug.lane, Lane::Planned);
        assert!(bug.labels.contains(&"funnel".to_string()));
    }

    /// Hashtag mining handles boundaries, case, dedupe.
    #[test]
    fn hashtag_mining() {
        assert_eq!(mine_hashtags("a #Foo, #foo and #bar-baz! #"), vec!["bar-baz", "foo"]);
        assert!(mine_hashtags("no tags here").is_empty());
    }

    /// Each smart-query operator parses and filters as specified.
    #[test]
    fn smart_query_operators() {
        let cards = cards_from_history(&sample());

        // type:bug → only the error card
        let r = query_cards(&cards, "type:bug");
        assert_eq!(r.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), ["i-2"]);
        // kind:idea alias + lane filter
        assert_eq!(query_cards(&cards, "kind:feature lane:dropped").iter().map(|c| c.id.clone()).collect::<Vec<_>>(), ["i-4"]);
        // is:open = inbox|accepted (i-1, i-3)
        let open: Vec<String> = query_cards(&cards, "is:open").iter().map(|c| c.id.clone()).collect();
        assert_eq!(open, ["i-1", "i-3"], "open = inbox+accepted, newest first");
        // for:me → reporter contains rickard (i-1, i-4)
        let mine: Vec<String> = query_cards(&cards, "for:me").iter().map(|c| c.id.clone()).collect();
        assert_eq!(mine, ["i-1", "i-4"]);
        // has:plan / no:plan
        assert_eq!(query_cards(&cards, "has:plan").iter().map(|c| c.id.clone()).collect::<Vec<_>>(), ["i-2"]);
        assert_eq!(query_cards(&cards, "no:plan").len(), 3);
        // label chip
        assert_eq!(query_cards(&cards, "label:funnel").iter().map(|c| c.id.clone()).collect::<Vec<_>>(), ["i-2"]);
        // free text (case-insensitive, across title/body/id/reporter)
        assert_eq!(query_cards(&cards, "cobol").iter().map(|c| c.id.clone()).collect::<Vec<_>>(), ["i-4"]);
        // combined AND across facets
        assert_eq!(query_cards(&cards, "type:feature for:rickard is:open").iter().map(|c| c.id.clone()).collect::<Vec<_>>(), ["i-1"]);
    }

    /// Sort operators order deterministically with an id tie-break.
    #[test]
    fn smart_query_sort() {
        let cards = cards_from_history(&sample());
        let newest: Vec<String> = query_cards(&cards, "sort:newest").iter().map(|c| c.id.clone()).collect();
        assert_eq!(newest, ["i-2", "i-1", "i-3", "i-4"]);
        let oldest: Vec<String> = query_cards(&cards, "sort:oldest").iter().map(|c| c.id.clone()).collect();
        assert_eq!(oldest, ["i-4", "i-3", "i-1", "i-2"]);
        let byid: Vec<String> = query_cards(&cards, "sort:id").iter().map(|c| c.id.clone()).collect();
        assert_eq!(byid, ["i-1", "i-2", "i-3", "i-4"]);
    }

    /// The board groups into the four fixed lanes with correct counts + order, and
    /// its json is deterministic.
    #[test]
    fn board_groups_into_fixed_lanes() {
        let cards = cards_from_history(&sample());
        let b = board(&cards);
        assert_eq!(b.total, 4);
        assert_eq!(b.columns.len(), 4);
        let lanes: Vec<&str> = b.columns.iter().map(|c| c.lane.as_str()).collect();
        assert_eq!(lanes, ["inbox", "accepted", "planned", "dropped"], "fixed left→right order");
        let counts: Vec<usize> = b.columns.iter().map(|c| c.cards.len()).collect();
        assert_eq!(counts, [1, 1, 1, 1]);
        assert_eq!(b.columns[0].cards[0].id, "i-1");

        // Deterministic json (bit-identical on a re-projection).
        let j1 = board_to_json(&board(&cards_from_history(&sample())));
        let j2 = board_to_json(&board(&cards_from_history(&sample())));
        assert_eq!(j1.to_string(), j2.to_string());
        assert_eq!(j1["columns"][2]["cards"][0]["plans"], 1, "the planned bug shows 1 linked plan");

        // ── functional-status row (the test matrix sees this surface ran) ──────
        #[cfg(feature = "testmatrix")]
        {
            let ok = b.total == 4 && lanes == ["inbox", "accepted", "planned", "dropped"];
            crate::selftest::emit(
                "nornir::funnel::card",
                "board_projection_groups_lanes",
                ok,
                &format!("total={} lanes={:?} counts={:?}", b.total, lanes, counts),
            );
        }
    }

    /// An empty funnel projects to an empty-but-shaped board (RAGNARÖK: zero cards
    /// is honest empty, the four columns still exist).
    #[test]
    fn empty_funnel_is_honest_empty_board() {
        let b = board(&cards_from_history(&[]));
        assert_eq!(b.total, 0);
        assert_eq!(b.columns.len(), 4);
        assert!(b.columns.iter().all(|c| c.cards.is_empty()));
    }
}