spikes 0.4.0

Drop-in feedback collection for static HTML mockups
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
use std::collections::HashMap;
use std::io::{self, Write};

use crate::error::Result;
use crate::spike::{Rating, SpikeType};
use crate::storage::load_spikes;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ExportFormat {
    Json,
    Csv,
    Jsonl,
    CursorContext,
    ClaudeContext,
}

impl std::str::FromStr for ExportFormat {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "json" => Ok(ExportFormat::Json),
            "csv" => Ok(ExportFormat::Csv),
            "jsonl" => Ok(ExportFormat::Jsonl),
            "cursor-context" => Ok(ExportFormat::CursorContext),
            "claude-context" => Ok(ExportFormat::ClaudeContext),
            _ => Err(format!(
                "Invalid format: {}. Use json, csv, jsonl, cursor-context, or claude-context",
                s
            )),
        }
    }
}

pub fn run(format: ExportFormat) -> Result<()> {
    let spikes = load_spikes()?;
    let stdout = io::stdout();
    let mut handle = stdout.lock();

    match format {
        ExportFormat::Json => {
            let json = serde_json::to_string_pretty(&spikes)?;
            writeln!(handle, "{}", json)?;
        }
        ExportFormat::Jsonl => {
            for spike in &spikes {
                let json = serde_json::to_string(spike)?;
                writeln!(handle, "{}", json)?;
            }
        }
        ExportFormat::Csv => {
            let mut wtr = csv::Writer::from_writer(handle);
            wtr.write_record([
                "id",
                "type",
                "project_key",
                "page",
                "url",
                "reviewer_id",
                "reviewer_name",
                "selector",
                "element_text",
                "rating",
                "comments",
                "timestamp",
                "viewport_width",
                "viewport_height",
            ])?;

            for spike in &spikes {
                wtr.write_record([
                    &spike.id,
                    spike.type_str(),
                    &spike.project_key,
                    &spike.page,
                    &spike.url,
                    &spike.reviewer.id,
                    &spike.reviewer.name,
                    spike.selector.as_deref().unwrap_or(""),
                    spike.element_text.as_deref().unwrap_or(""),
                    spike.rating_str(),
                    &spike.comments,
                    &spike.timestamp,
                    &spike.viewport.as_ref().map(|v| v.width.to_string()).unwrap_or_default(),
                    &spike.viewport.as_ref().map(|v| v.height.to_string()).unwrap_or_default(),
                ])?;
            }
            wtr.flush()?;
        }
        ExportFormat::CursorContext => {
            let markdown = generate_cursor_context(&spikes);
            write!(handle, "{}", markdown)?;
        }
        ExportFormat::ClaudeContext => {
            let markdown = generate_claude_context(&spikes);
            write!(handle, "{}", markdown)?;
        }
    }

    Ok(())
}

// ============================================================================
// Cursor Context Format
// ============================================================================

/// Generate Cursor-compatible context markdown.
///
/// Sections: blocking issues, hotspots, element-specific notes.
/// Punk/zine energy in headers and taglines.
fn generate_cursor_context(spikes: &[crate::spike::Spike]) -> String {
    let mut output = String::new();

    // Metadata header
    let timestamp = chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC");
    let project = spikes
        .first()
        .map(|s| s.project_key.as_str())
        .unwrap_or("unknown");

    output.push_str("# 🎯 FEEDBACK INTEL\n\n");
    output.push_str("_Your roadmap to glory or ruin._\n\n");
    output.push_str(&format!("**Project:** {}\n", project));
    output.push_str(&format!("**Total Spikes:** {}\n", spikes.len()));
    output.push_str(&format!("**Generated:** {}\n\n", timestamp));
    output.push_str("---\n\n");

    // Blocking issues section
    output.push_str("## 🚫 BLOCKING ISSUES\n\n");
    output.push_str("_The vibes are off. Fix these before shipping._\n\n");

    let blocking: Vec<&crate::spike::Spike> = spikes
        .iter()
        .filter(|s| is_blocking(s))
        .collect();

    if blocking.is_empty() {
        output.push_str("✨ **Clean slate!** No blocking issues found.\n\n");
    } else {
        for spike in &blocking {
            output.push_str(&format!("### [{}] {} on `{}`\n", 
                &spike.id.chars().take(8).collect::<String>(),
                spike.type_str(),
                spike.page
            ));
            output.push_str(&format!("- **Rating:** {}\n", spike.rating_str()));
            if spike.spike_type == SpikeType::Element {
                if let Some(selector) = &spike.selector {
                    output.push_str(&format!("- **Selector:** `{}`\n", selector));
                }
            }
            if !spike.comments.is_empty() {
                output.push_str(&format!("- **Comment:** \"{}\"\n", spike.comments));
            }
            output.push_str(&format!("- **Reviewer:** {}\n", spike.reviewer.name));
            output.push('\n');
        }
    }

    output.push_str("---\n\n");

    // Hotspots section
    output.push_str("## 🔥 FEEDBACK HOTSPOTS\n\n");
    output.push_str("_Where the action is. Elements with the most heat._\n\n");

    let hotspots = compute_hotspots(spikes);
    if hotspots.is_empty() {
        output.push_str("📊 **No element feedback.** Nothing's hot yet.\n\n");
    } else {
        for (i, (selector, count)) in hotspots.iter().enumerate() {
            output.push_str(&format!(
                "{}. `{}` — **{} spike{}**\n",
                i + 1,
                selector,
                count,
                if *count == 1 { "" } else { "s" }
            ));
        }
        output.push('\n');
    }

    output.push_str("---\n\n");

    // Element-specific notes section
    output.push_str("## 📝 ELEMENT-SPECIFIC NOTES\n\n");
    output.push_str("_Deep cuts on specific elements. Grouped by selector._\n\n");

    let element_spikes: Vec<&crate::spike::Spike> = spikes
        .iter()
        .filter(|s| s.spike_type == SpikeType::Element)
        .collect();

    if element_spikes.is_empty() {
        output.push_str("🔍 **No element feedback recorded.**\n\n");
    } else {
        // Group by selector
        let mut by_selector: HashMap<String, Vec<&crate::spike::Spike>> = HashMap::new();
        for spike in &element_spikes {
            let selector = spike.selector.clone().unwrap_or_default();
            by_selector.entry(selector).or_default().push(*spike);
        }

        // Sort selectors alphabetically for consistent output
        let mut selectors: Vec<String> = by_selector.keys().cloned().collect();
        selectors.sort();

        for selector in &selectors {
            let spikes_for_selector = &by_selector[selector];
            output.push_str(&format!("### `{}`\n\n", selector));

            for spike in spikes_for_selector {
                let status = if spike.is_resolved() { "" } else { "" };
                output.push_str(&format!(
                    "- {} **{}** — \"{}\" _({})_\n",
                    status,
                    spike.rating_str(),
                    spike.comments,
                    spike.reviewer.name
                ));
            }
            output.push('\n');
        }
    }

    output.push_str("---\n\n");
    output.push_str("_Generated by [spikes](https://spikes.sh) — feedback that talks back._\n");

    output
}

// ============================================================================
// Claude Context Format
// ============================================================================

/// Generate Claude-compatible context markdown.
///
/// Sections: critical issues, feedback hotspots, element feedback.
/// Distinct punk/zine tone from cursor-context.
fn generate_claude_context(spikes: &[crate::spike::Spike]) -> String {
    let mut output = String::new();

    // Metadata header
    let timestamp = chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC");
    let project = spikes
        .first()
        .map(|s| s.project_key.as_str())
        .unwrap_or("unknown");

    output.push_str("# ⚡ SPIKES FEEDBACK REPORT\n\n");
    output.push_str("_The raw truth, served fresh._\n\n");
    output.push_str(&format!("**Project:** {}\n", project));
    output.push_str(&format!("**Total Feedback Items:** {}\n", spikes.len()));
    output.push_str(&format!("**Generated:** {}\n\n", timestamp));
    output.push_str("---\n\n");

    // Critical issues section
    output.push_str("## ⚠️ CRITICAL ISSUES\n\n");
    output.push_str("_Unresolved problems demanding attention. The must-fix list._\n\n");

    let blocking: Vec<&crate::spike::Spike> = spikes
        .iter()
        .filter(|s| is_blocking(s))
        .collect();

    if blocking.is_empty() {
        output.push_str("**✅ All clear.** No critical issues blocking progress.\n\n");
    } else {
        output.push_str(&format!("**{} critical issue{} found:**\n\n", 
            blocking.len(),
            if blocking.len() == 1 { "" } else { "s" }
        ));

        for spike in &blocking {
            output.push_str(&format!("### ID: `{}`\n\n", 
                &spike.id.chars().take(8).collect::<String>()
            ));
            output.push_str(&format!("- **Type:** {} on page `{}`\n", 
                spike.type_str(),
                spike.page
            ));
            output.push_str(&format!("- **Rating:** {} (negative)\n", spike.rating_str()));
            if spike.spike_type == SpikeType::Element {
                if let Some(selector) = &spike.selector {
                    output.push_str(&format!("- **Target:** `{}`\n", selector));
                }
            }
            if !spike.comments.is_empty() {
                output.push_str(&format!("- **Feedback:** \"{}\"\n", spike.comments));
            }
            output.push_str(&format!("- **From:** {}\n", spike.reviewer.name));
            output.push('\n');
        }
    }

    output.push_str("---\n\n");

    // Hotspots section
    output.push_str("## 📊 FEEDBACK HOTSPOTS\n\n");
    output.push_str("_Where reviewers clustered. The conversation starters._\n\n");

    let hotspots = compute_hotspots(spikes);
    if hotspots.is_empty() {
        output.push_str("**No element hotspots.** Reviewers haven't targeted specific elements yet.\n\n");
    } else {
        output.push_str("**Top feedback targets:**\n\n");
        for (i, (selector, count)) in hotspots.iter().enumerate() {
            output.push_str(&format!(
                "{}. `{}` — {} feedback item{}\n",
                i + 1,
                selector,
                count,
                if *count == 1 { "" } else { "s" }
            ));
        }
        output.push('\n');
    }

    output.push_str("---\n\n");

    // Element feedback section
    output.push_str("## 🔍 ELEMENT FEEDBACK\n\n");
    output.push_str("_Granular feedback on specific components. Organized by selector._\n\n");

    let element_spikes: Vec<&crate::spike::Spike> = spikes
        .iter()
        .filter(|s| s.spike_type == SpikeType::Element)
        .collect();

    if element_spikes.is_empty() {
        output.push_str("**No element-level feedback recorded.**\n\n");
    } else {
        // Group by selector
        let mut by_selector: HashMap<String, Vec<&crate::spike::Spike>> = HashMap::new();
        for spike in &element_spikes {
            let selector = spike.selector.clone().unwrap_or_default();
            by_selector.entry(selector).or_default().push(*spike);
        }

        // Sort selectors alphabetically
        let mut selectors: Vec<String> = by_selector.keys().cloned().collect();
        selectors.sort();

        for selector in &selectors {
            let spikes_for_selector = &by_selector[selector];
            output.push_str(&format!("### Selector: `{}`\n\n", selector));

            for spike in spikes_for_selector {
                let resolved_marker = if spike.is_resolved() { "[RESOLVED] " } else { "" };
                output.push_str(&format!(
                    "- {}**{}** from {}: \"{}\"\n",
                    resolved_marker,
                    spike.rating_str(),
                    spike.reviewer.name,
                    spike.comments
                ));
            }
            output.push('\n');
        }
    }

    output.push_str("---\n\n");
    output.push_str("_Spikes — structured feedback for the modern builder._\n");

    output
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Check if a spike is blocking (unresolved with meh/no rating)
fn is_blocking(spike: &crate::spike::Spike) -> bool {
    !spike.is_resolved()
        && matches!(
            spike.rating,
            Some(Rating::Meh) | Some(Rating::No)
        )
}

/// Compute hotspots: element-type spikes counted by selector, sorted descending
fn compute_hotspots(spikes: &[crate::spike::Spike]) -> Vec<(String, usize)> {
    let mut counts: HashMap<String, usize> = HashMap::new();

    for spike in spikes {
        if spike.spike_type == SpikeType::Element {
            if let Some(selector) = &spike.selector {
                *counts.entry(selector.clone()).or_insert(0) += 1;
            }
        }
    }

    let mut hotspots: Vec<(String, usize)> = counts.into_iter().collect();
    hotspots.sort_by_key(|item| std::cmp::Reverse(item.1));
    hotspots
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::spike::{Rating, Reviewer, Spike, SpikeType, Viewport};

    // Helper to create a test spike
    fn create_spike(
        id: &str,
        spike_type: SpikeType,
        page: &str,
        rating: Option<Rating>,
        selector: Option<&str>,
        resolved: bool,
        comments: &str,
    ) -> Spike {
        Spike {
            id: id.to_string(),
            spike_type,
            project_key: "test-project".to_string(),
            page: page.to_string(),
            url: format!("http://test/{}", page),
            reviewer: Reviewer {
                id: "r1".to_string(),
                name: "TestReviewer".to_string(),
            },
            selector: selector.map(|s| s.to_string()),
            element_text: None,
            bounding_box: None,
            rating,
            comments: comments.to_string(),
            timestamp: "2024-01-15T10:00:00Z".to_string(),
            viewport: Some(Viewport {
                width: 1920,
                height: 1080,
            }),
            resolved: if resolved { Some(true) } else { None },
            resolved_at: if resolved {
                Some("2024-01-16T10:00:00Z".to_string())
            } else {
                None
            },
        }
    }

    // ========================================
    // ExportFormat parsing tests
    // ========================================

    #[test]
    fn test_parse_json_format() {
        assert_eq!("json".parse::<ExportFormat>().unwrap(), ExportFormat::Json);
        assert_eq!("JSON".parse::<ExportFormat>().unwrap(), ExportFormat::Json);
    }

    #[test]
    fn test_parse_csv_format() {
        assert_eq!("csv".parse::<ExportFormat>().unwrap(), ExportFormat::Csv);
    }

    #[test]
    fn test_parse_jsonl_format() {
        assert_eq!("jsonl".parse::<ExportFormat>().unwrap(), ExportFormat::Jsonl);
    }

    #[test]
    fn test_parse_cursor_context_format() {
        assert_eq!(
            "cursor-context".parse::<ExportFormat>().unwrap(),
            ExportFormat::CursorContext
        );
        assert_eq!(
            "CURSOR-CONTEXT".parse::<ExportFormat>().unwrap(),
            ExportFormat::CursorContext
        );
    }

    #[test]
    fn test_parse_claude_context_format() {
        assert_eq!(
            "claude-context".parse::<ExportFormat>().unwrap(),
            ExportFormat::ClaudeContext
        );
        assert_eq!(
            "CLAUDE-CONTEXT".parse::<ExportFormat>().unwrap(),
            ExportFormat::ClaudeContext
        );
    }

    #[test]
    fn test_invalid_format_lists_all_five() {
        let result = "invalid".parse::<ExportFormat>();
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("json"), "Error should list json format");
        assert!(err.contains("csv"), "Error should list csv format");
        assert!(err.contains("jsonl"), "Error should list jsonl format");
        assert!(err.contains("cursor-context"), "Error should list cursor-context format");
        assert!(err.contains("claude-context"), "Error should list claude-context format");
    }

    // ========================================
    // is_blocking tests
    // ========================================

    #[test]
    fn test_is_blocking_meh_unresolved() {
        let spike = create_spike("s1", SpikeType::Page, "index.html", Some(Rating::Meh), None, false, "Not great");
        assert!(is_blocking(&spike), "Unresolved meh should be blocking");
    }

    #[test]
    fn test_is_blocking_no_unresolved() {
        let spike = create_spike("s2", SpikeType::Page, "index.html", Some(Rating::No), None, false, "Bad");
        assert!(is_blocking(&spike), "Unresolved no should be blocking");
    }

    #[test]
    fn test_is_not_blocking_love() {
        let spike = create_spike("s3", SpikeType::Page, "index.html", Some(Rating::Love), None, false, "Great");
        assert!(!is_blocking(&spike), "Love should not be blocking");
    }

    #[test]
    fn test_is_not_blocking_like() {
        let spike = create_spike("s4", SpikeType::Page, "index.html", Some(Rating::Like), None, false, "Good");
        assert!(!is_blocking(&spike), "Like should not be blocking");
    }

    #[test]
    fn test_is_not_blocking_resolved_meh() {
        let spike = create_spike("s5", SpikeType::Page, "index.html", Some(Rating::Meh), None, true, "Fixed");
        assert!(!is_blocking(&spike), "Resolved meh should not be blocking");
    }

    #[test]
    fn test_is_not_blocking_resolved_no() {
        let spike = create_spike("s6", SpikeType::Page, "index.html", Some(Rating::No), None, true, "Fixed");
        assert!(!is_blocking(&spike), "Resolved no should not be blocking");
    }

    #[test]
    fn test_is_not_blocking_no_rating() {
        let spike = create_spike("s7", SpikeType::Page, "index.html", None, None, false, "Comment only");
        assert!(!is_blocking(&spike), "No rating should not be blocking");
    }

    // ========================================
    // compute_hotspots tests
    // ========================================

    #[test]
    fn test_hotspots_empty() {
        let spikes = vec![];
        let hotspots = compute_hotspots(&spikes);
        assert!(hotspots.is_empty());
    }

    #[test]
    fn test_hotspots_page_only() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::Love), None, false, "Good"),
        ];
        let hotspots = compute_hotspots(&spikes);
        assert!(hotspots.is_empty(), "Page spikes should not create hotspots");
    }

    #[test]
    fn test_hotspots_single_element() {
        let spikes = vec![
            create_spike("s1", SpikeType::Element, "index.html", Some(Rating::Love), Some(".hero"), false, "Nice"),
        ];
        let hotspots = compute_hotspots(&spikes);
        assert_eq!(hotspots.len(), 1);
        assert_eq!(hotspots[0], (".hero".to_string(), 1));
    }

    #[test]
    fn test_hotspots_sorted_descending() {
        let spikes = vec![
            create_spike("s1", SpikeType::Element, "index.html", Some(Rating::Love), Some(".hero"), false, "1"),
            create_spike("s2", SpikeType::Element, "index.html", Some(Rating::Like), Some(".hero"), false, "2"),
            create_spike("s3", SpikeType::Element, "index.html", Some(Rating::Meh), Some(".hero"), false, "3"),
            create_spike("s4", SpikeType::Element, "index.html", Some(Rating::No), Some(".footer"), false, "4"),
        ];
        let hotspots = compute_hotspots(&spikes);
        assert_eq!(hotspots.len(), 2);
        assert_eq!(hotspots[0], (".hero".to_string(), 3), "Most feedback should be first");
        assert_eq!(hotspots[1], (".footer".to_string(), 1));
    }

    // ========================================
    // cursor-context format tests
    // ========================================

    #[test]
    fn test_cursor_context_empty_state() {
        let spikes = vec![];
        let markdown = generate_cursor_context(&spikes);

        assert!(markdown.contains("# 🎯 FEEDBACK INTEL"));
        assert!(markdown.contains("No blocking issues"));
        assert!(markdown.contains("No element feedback"));
        assert!(markdown.contains("Total Spikes:** 0"));
    }

    #[test]
    fn test_cursor_context_positive_only() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::Love), None, false, "Amazing"),
            create_spike("s2", SpikeType::Page, "about.html", Some(Rating::Like), None, false, "Good"),
        ];
        let markdown = generate_cursor_context(&spikes);

        assert!(markdown.contains("Clean slate!"));
        assert!(markdown.contains("No blocking issues"));
    }

    #[test]
    fn test_cursor_context_mixed_ratings() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::Love), None, false, "Great"),
            create_spike("s2", SpikeType::Page, "about.html", Some(Rating::Meh), None, false, "Needs work"),
            create_spike("s3", SpikeType::Element, "index.html", Some(Rating::No), Some(".button"), false, "Broken"),
        ];
        let markdown = generate_cursor_context(&spikes);

        // Blocking section should have meh and no ratings
        assert!(markdown.contains("BLOCKING ISSUES"));
        assert!(markdown.contains("about.html"));
        assert!(markdown.contains(".button"));
        assert!(markdown.contains("meh"));
        assert!(markdown.contains("no"));

        // Love should NOT appear in blocking
        assert!(!markdown.contains("Great"));
    }

    #[test]
    fn test_cursor_context_resolved_negative_not_blocking() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::No), None, true, "Fixed now"),
            create_spike("s2", SpikeType::Page, "about.html", Some(Rating::Meh), None, true, "Resolved"),
        ];
        let markdown = generate_cursor_context(&spikes);

        assert!(markdown.contains("Clean slate!"));
        assert!(markdown.contains("No blocking issues"));
    }

    #[test]
    fn test_cursor_context_element_grouping() {
        let spikes = vec![
            create_spike("s1", SpikeType::Element, "index.html", Some(Rating::Love), Some(".hero"), false, "Nice hero"),
            create_spike("s2", SpikeType::Element, "index.html", Some(Rating::No), Some(".hero"), false, "Hero broken"),
            create_spike("s3", SpikeType::Element, "about.html", Some(Rating::Like), Some(".footer"), false, "Nice footer"),
        ];
        let markdown = generate_cursor_context(&spikes);

        assert!(markdown.contains("ELEMENT-SPECIFIC NOTES"));
        assert!(markdown.contains("### `.hero`"));
        assert!(markdown.contains("### `.footer`"));
        // Check that both spikes for .hero appear
        assert!(markdown.contains("Nice hero"));
        assert!(markdown.contains("Hero broken"));
    }

    #[test]
    fn test_cursor_context_hotspots() {
        let spikes = vec![
            create_spike("s1", SpikeType::Element, "index.html", Some(Rating::Love), Some(".hero"), false, "1"),
            create_spike("s2", SpikeType::Element, "index.html", Some(Rating::Like), Some(".hero"), false, "2"),
            create_spike("s3", SpikeType::Element, "index.html", Some(Rating::No), Some(".footer"), false, "3"),
        ];
        let markdown = generate_cursor_context(&spikes);

        assert!(markdown.contains("FEEDBACK HOTSPOTS"));
        assert!(markdown.contains("`.hero` — **2 spikes**"));
        assert!(markdown.contains("`.footer` — **1 spike**"));
    }

    #[test]
    fn test_cursor_context_punk_zine_tone() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::No), None, false, "Bad"),
        ];
        let markdown = generate_cursor_context(&spikes);

        assert!(markdown.contains("vibes are off"));
        assert!(markdown.contains("Where the action is"));
        assert!(markdown.contains("Deep cuts"));
    }

    // ========================================
    // claude-context format tests
    // ========================================

    #[test]
    fn test_claude_context_empty_state() {
        let spikes = vec![];
        let markdown = generate_claude_context(&spikes);

        assert!(markdown.contains("# ⚡ SPIKES FEEDBACK REPORT"));
        assert!(markdown.contains("No critical issues"));
        assert!(markdown.contains("No element hotspots"));
        assert!(markdown.contains("Total Feedback Items:** 0"));
    }

    #[test]
    fn test_claude_context_positive_only() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::Love), None, false, "Amazing"),
            create_spike("s2", SpikeType::Page, "about.html", Some(Rating::Like), None, false, "Good"),
        ];
        let markdown = generate_claude_context(&spikes);

        assert!(markdown.contains("All clear"));
        assert!(markdown.contains("No critical issues"));
    }

    #[test]
    fn test_claude_context_mixed_ratings() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::Love), None, false, "Great"),
            create_spike("s2", SpikeType::Page, "about.html", Some(Rating::Meh), None, false, "Needs work"),
            create_spike("s3", SpikeType::Element, "index.html", Some(Rating::No), Some(".button"), false, "Broken"),
        ];
        let markdown = generate_claude_context(&spikes);

        assert!(markdown.contains("CRITICAL ISSUES"));
        assert!(markdown.contains("about.html"));
        assert!(markdown.contains(".button"));
        assert!(markdown.contains("negative"));
    }

    #[test]
    fn test_claude_context_distinct_from_cursor() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::No), None, false, "Bad"),
        ];
        let cursor_md = generate_cursor_context(&spikes);
        let claude_md = generate_claude_context(&spikes);

        // Different main headers
        assert!(cursor_md.contains("# 🎯 FEEDBACK INTEL"));
        assert!(claude_md.contains("# ⚡ SPIKES FEEDBACK REPORT"));

        // Different section headers
        assert!(cursor_md.contains("BLOCKING ISSUES"));
        assert!(claude_md.contains("CRITICAL ISSUES"));
    }

    #[test]
    fn test_claude_context_element_feedback_resolved_marker() {
        let spikes = vec![
            create_spike("s1", SpikeType::Element, "index.html", Some(Rating::Love), Some(".hero"), true, "Fixed"),
            create_spike("s2", SpikeType::Element, "index.html", Some(Rating::No), Some(".hero"), false, "Broken"),
        ];
        let markdown = generate_claude_context(&spikes);

        assert!(markdown.contains("[RESOLVED]"));
        assert!(markdown.contains("Fixed"));
        assert!(markdown.contains("Broken"));
    }

    #[test]
    fn test_claude_context_punk_zine_tone() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::No), None, false, "Bad"),
        ];
        let markdown = generate_claude_context(&spikes);

        assert!(markdown.contains("raw truth"));
        assert!(markdown.contains("demanding attention"));
        assert!(markdown.contains("Where reviewers clustered"));
    }

    // ========================================
    // Metadata tests
    // ========================================

    #[test]
    fn test_context_export_includes_metadata() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::Love), None, false, "Good"),
        ];

        let cursor_md = generate_cursor_context(&spikes);
        let claude_md = generate_claude_context(&spikes);

        // Both should have project, count, timestamp
        assert!(cursor_md.contains("**Project:**"));
        assert!(cursor_md.contains("**Total Spikes:**"));
        assert!(cursor_md.contains("**Generated:**"));

        assert!(claude_md.contains("**Project:**"));
        assert!(claude_md.contains("**Total Feedback Items:**"));
        assert!(claude_md.contains("**Generated:**"));
    }

    #[test]
    fn test_context_export_project_from_spikes() {
        let spikes = vec![
            create_spike("s1", SpikeType::Page, "index.html", Some(Rating::Love), None, false, "Good"),
        ];

        let cursor_md = generate_cursor_context(&spikes);
        assert!(cursor_md.contains("test-project"));
    }
}