gatekpr-opencode 0.2.3

OpenCode CLI integration for RAG-powered validation enrichment
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
//! OpenCode CLI client for RAG-powered validation enrichment
//!
//! This client invokes the OpenCode CLI to enrich validation findings
//! with context from the RAG system. Each finding is processed in a
//! fresh context to avoid context window explosion.

use crate::config::OpenCodeConfig;
use crate::error::{OpenCodeError, Result};
use crate::models::*;
use std::path::Path;
use std::process::Stdio;
use std::time::Instant;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tracing::{debug, info};

/// OpenCode CLI client for validation enrichment
///
/// This client invokes `opencode run` to process findings through
/// GLM 4.7 with access to the RAG-powered MCP server.
pub struct OpenCodeClient {
    config: OpenCodeConfig,
    platform: String,
}

impl OpenCodeClient {
    /// Create a new OpenCode client
    pub fn new(config: OpenCodeConfig) -> Result<Self> {
        config.validate()?;
        let platform = config
            .platform
            .clone()
            .unwrap_or_else(|| "Shopify".to_string());
        Ok(Self { config, platform })
    }

    /// Set platform for prompt customization
    pub fn with_platform(mut self, platform: &str) -> Self {
        self.platform = platform.to_string();
        self
    }

    /// Create client from environment variables
    pub fn from_env() -> Result<Self> {
        let config = OpenCodeConfig::from_env()?;
        Self::new(config)
    }

    /// Create client with auto-detected configuration
    pub fn auto() -> Result<Self> {
        let config = OpenCodeConfig::new()?;
        Self::new(config)
    }

    /// Get the CLI path
    pub fn cli_path(&self) -> &Path {
        &self.config.cli_path
    }

    /// Get the model being used
    pub fn model(&self) -> &str {
        &self.config.model
    }

    /// Check if MCP integration is available
    pub fn has_mcp(&self) -> bool {
        self.config.has_mcp()
    }

    // =========================================================================
    // ENRICHMENT OPERATIONS
    // =========================================================================

    /// Enrich a single finding with RAG context
    ///
    /// Invokes OpenCode with the finding details and file context.
    /// OpenCode will use MCP tools (search_docs_for_rule) to fetch
    /// relevant documentation and provide a detailed analysis.
    pub async fn enrich_finding(
        &self,
        finding: &RawFinding,
        file_context: &FileContext,
    ) -> Result<EnrichedFinding> {
        let prompt = self.build_enrichment_prompt(finding, file_context);

        debug!(
            "Enriching finding {} in {}",
            finding.rule_id, finding.file_path
        );

        let output = self.run_opencode(&prompt, Some(&file_context.path)).await?;
        self.parse_enriched_finding(finding, &output)
    }

    /// Enrich multiple findings in a SINGLE OpenCode call
    ///
    /// Batches all findings together and sends them to OpenCode once,
    /// which analyzes the codebase and returns enriched results for all.
    /// This is much faster than processing findings one-by-one.
    pub async fn enrich_findings(
        &self,
        findings: Vec<RawFinding>,
        codebase_path: &Path,
    ) -> Result<Vec<EnrichedFinding>> {
        if findings.is_empty() {
            return Ok(Vec::new());
        }

        info!(
            "Enriching {} findings with OpenCode (single batch call)",
            findings.len()
        );

        // Build a single prompt with ALL findings
        let prompt = self.build_batch_enrichment_prompt(&findings, codebase_path);

        // Run OpenCode ONCE with streaming output
        let output = self
            .run_opencode_streaming(&prompt, Some(codebase_path))
            .await?;

        // Parse the batch response
        self.parse_batch_enrichment(&findings, &output)
    }

    /// Analyze a file for potential issues
    ///
    /// Uses OpenCode to scan a file and identify any marketplace-related
    /// issues that the local pipeline might have missed.
    pub async fn analyze_file(
        &self,
        file_path: &Path,
        categories: &[&str],
    ) -> Result<Vec<RawFinding>> {
        let content = tokio::fs::read_to_string(file_path).await?;
        let relative_path = file_path
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| file_path.display().to_string());

        let file_context = FileContext::new(&relative_path, &content);
        let prompt = self.build_analysis_prompt(&file_context, categories);

        let output = self.run_opencode(&prompt, Some(&relative_path)).await?;
        self.parse_analysis_results(&output, &relative_path)
    }

    // =========================================================================
    // CLI EXECUTION
    // =========================================================================

    /// Run OpenCode CLI with streaming output (logs as it runs)
    async fn run_opencode_streaming(
        &self,
        prompt: &str,
        working_dir: Option<&Path>,
    ) -> Result<String> {
        use tokio::io::{AsyncBufReadExt, BufReader};

        let start = Instant::now();

        let mut cmd = Command::new(&self.config.cli_path);
        cmd.arg("run")
            .arg(prompt)
            .arg("--model")
            .arg(&self.config.model)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        // Set working directory to codebase path
        if let Some(dir) = working_dir {
            if dir.exists() && dir.is_dir() {
                cmd.current_dir(dir);
                info!("OpenCode working directory: {}", dir.display());
            }
        }

        // Add environment variables
        for (key, value) in &self.config.env_vars {
            cmd.env(key, value);
        }

        info!("Starting OpenCode CLI (streaming mode)...");

        let mut child = cmd.spawn().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                OpenCodeError::CliNotFound(self.config.cli_path.display().to_string())
            } else {
                OpenCodeError::CliExecution(e.to_string())
            }
        })?;

        // Stream stderr (OpenCode's progress output) in real-time
        let stderr = child.stderr.take();
        let stderr_handle = tokio::spawn(async move {
            let mut stderr_content = String::new();
            if let Some(stderr) = stderr {
                let mut reader = BufReader::new(stderr).lines();
                while let Ok(Some(line)) = reader.next_line().await {
                    // Log each line from OpenCode as it comes
                    info!("[OpenCode] {}", line);
                    stderr_content.push_str(&line);
                    stderr_content.push('\n');
                }
            }
            stderr_content
        });

        // Stream stdout (the actual response)
        let stdout = child.stdout.take();
        let stdout_handle = tokio::spawn(async move {
            let mut stdout_content = String::new();
            if let Some(stdout) = stdout {
                let mut reader = BufReader::new(stdout).lines();
                while let Ok(Some(line)) = reader.next_line().await {
                    debug!("[OpenCode stdout] {}", line);
                    stdout_content.push_str(&line);
                    stdout_content.push('\n');
                }
            }
            stdout_content
        });

        // Wait for completion with timeout
        let timeout = self.config.timeout;
        let result = tokio::time::timeout(timeout, async {
            let status = child.wait().await?;
            let stdout = stdout_handle.await.unwrap_or_default();
            let stderr = stderr_handle.await.unwrap_or_default();
            Ok::<_, std::io::Error>((stdout, stderr, status))
        })
        .await;

        let elapsed = start.elapsed();
        info!("OpenCode completed in {:?}", elapsed);

        match result {
            Ok(Ok((stdout, stderr, status))) => {
                if status.success() {
                    Ok(stdout)
                } else if stderr.contains("auth") || stderr.contains("credential") {
                    Err(OpenCodeError::AuthRequired)
                } else if stderr.contains("rate limit") {
                    Err(OpenCodeError::RateLimited)
                } else {
                    Err(OpenCodeError::exit_error(
                        status.code().unwrap_or(-1),
                        stderr,
                    ))
                }
            }
            Ok(Err(e)) => Err(OpenCodeError::CliExecution(e.to_string())),
            Err(_) => {
                let _ = child.kill().await;
                Err(OpenCodeError::timeout(timeout.as_secs()))
            }
        }
    }

    /// Run OpenCode CLI with a prompt (non-streaming, for single finding)
    async fn run_opencode(&self, prompt: &str, working_dir: Option<&str>) -> Result<String> {
        let start = Instant::now();

        let mut cmd = Command::new(&self.config.cli_path);
        cmd.arg("run")
            .arg(prompt)
            .arg("--model")
            .arg(&self.config.model)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        // Set working directory if specified
        if let Some(dir) = working_dir.or(self
            .config
            .working_dir
            .as_ref()
            .map(|p| p.to_str().unwrap_or(".")))
        {
            if let Some(parent) = Path::new(dir).parent() {
                if parent.exists() {
                    cmd.current_dir(parent);
                }
            }
        }

        // Add environment variables
        for (key, value) in &self.config.env_vars {
            cmd.env(key, value);
        }

        debug!("Running: {:?}", cmd);

        let mut child = cmd.spawn().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                OpenCodeError::CliNotFound(self.config.cli_path.display().to_string())
            } else {
                OpenCodeError::CliExecution(e.to_string())
            }
        })?;

        // Read stdout with timeout
        let timeout = self.config.timeout;
        let result = tokio::time::timeout(timeout, async {
            let mut stdout = String::new();
            let mut stderr = String::new();

            if let Some(ref mut out) = child.stdout {
                out.read_to_string(&mut stdout).await?;
            }
            if let Some(ref mut err) = child.stderr {
                err.read_to_string(&mut stderr).await?;
            }

            let status = child.wait().await?;
            Ok::<_, std::io::Error>((stdout, stderr, status))
        })
        .await;

        let elapsed = start.elapsed();
        debug!("OpenCode completed in {:?}", elapsed);

        match result {
            Ok(Ok((stdout, stderr, status))) => {
                if status.success() {
                    Ok(stdout)
                } else {
                    // Check for common error patterns
                    if stderr.contains("auth") || stderr.contains("credential") {
                        Err(OpenCodeError::AuthRequired)
                    } else if stderr.contains("rate limit") {
                        Err(OpenCodeError::RateLimited)
                    } else if stderr.contains("model") && stderr.contains("not") {
                        Err(OpenCodeError::ModelUnavailable(self.config.model.clone()))
                    } else {
                        Err(OpenCodeError::exit_error(
                            status.code().unwrap_or(-1),
                            stderr,
                        ))
                    }
                }
            }
            Ok(Err(e)) => Err(OpenCodeError::CliExecution(e.to_string())),
            Err(_) => {
                // Timeout - kill the process
                let _ = child.kill().await;
                Err(OpenCodeError::timeout(timeout.as_secs()))
            }
        }
    }

    // =========================================================================
    // PROMPT BUILDING
    // =========================================================================

    /// Build a single prompt with ALL findings for batch enrichment
    fn build_batch_enrichment_prompt(
        &self,
        findings: &[RawFinding],
        codebase_path: &Path,
    ) -> String {
        let findings_json: Vec<serde_json::Value> = findings
            .iter()
            .map(|f| {
                serde_json::json!({
                    "rule_id": f.rule_id,
                    "category": f.category,
                    "severity": format!("{:?}", f.severity).to_lowercase(),
                    "file_path": f.file_path,
                    "line": f.line,
                    "message": f.message,
                    "raw_match": f.raw_match
                })
            })
            .collect();

        format!(
            r#"You are a {platform} marketplace compliance expert. Analyze this codebase for the following validation findings.

CODEBASE: {codebase_path}

FINDINGS TO ANALYZE:
{findings_json}

INSTRUCTIONS:
1. For each finding, explore the codebase to understand the context
2. Determine if the finding is a true positive or false positive
3. Provide specific fix recommendations with code examples
4. Reference {platform} documentation where applicable

Respond with a JSON array containing enriched findings:

```json
{{
  "enriched_findings": [
    {{
      "rule_id": "RULE001",
      "is_valid": true,
      "issue": {{
        "title": "Brief title",
        "description": "Detailed explanation",
        "impact": "What happens if not fixed"
      }},
      "fix": {{
        "action": "add_code|modify_code|remove_code",
        "steps": ["Step 1", "Step 2"],
        "code_snippet": "// example fix"
      }},
      "confidence": 0.95
    }}
  ]
}}
```

Analyze ALL {count} findings and return enrichments for each."#,
            platform = self.platform,
            codebase_path = codebase_path.display(),
            findings_json = serde_json::to_string_pretty(&findings_json).unwrap_or_default(),
            count = findings.len()
        )
    }

    /// Build prompt for enriching a finding
    fn build_enrichment_prompt(&self, finding: &RawFinding, context: &FileContext) -> String {
        format!(
            r#"You are analyzing a {platform} app for compliance issues.

FINDING:
- Rule: {rule_id}
- Category: {category}
- Severity: {severity}
- File: {file_path}:{line}
- Message: {message}
- Match: {raw_match}

FILE CONTEXT ({language}):
```{language}
{content}
```

INSTRUCTIONS:
1. Use the search_docs_for_rule tool with rule_id="{rule_id}" to get relevant {platform} documentation
2. Analyze the code against {platform}'s requirements
3. Provide your response in this EXACT JSON format:

```json
{{
  "issue": {{
    "title": "Brief issue title",
    "description": "Detailed explanation of the problem",
    "impact": "What happens if not fixed"
  }},
  "analysis": {{
    "confidence": 0.95,
    "reasoning": "Why this is an issue based on docs",
    "related_rules": ["OTHER001"]
  }},
  "fix": {{
    "action": "add_code|modify_code|remove_code|add_file|update_config",
    "target_file": "path/to/file.ts",
    "code_snippet": "// code to add or modify",
    "steps": ["Step 1", "Step 2"],
    "complexity": "simple|medium|complex"
  }},
  "references": [
    {{"title": "Doc title", "url": "https://shopify.dev/...", "relevance": 0.9}}
  ]
}}
```

Respond ONLY with the JSON block, no other text."#,
            platform = self.platform,
            rule_id = finding.rule_id,
            category = finding.category,
            severity = finding.severity,
            file_path = finding.file_path,
            line = finding.line.unwrap_or(0),
            message = finding.message,
            raw_match = finding.raw_match,
            language = context.language,
            content = Self::truncate_content(&context.content, 2000),
        )
    }

    /// Build prompt for file analysis
    fn build_analysis_prompt(&self, context: &FileContext, categories: &[&str]) -> String {
        let categories_str = categories.join(", ");
        format!(
            r#"Analyze this {platform} app file for compliance issues in these categories: {categories}

FILE: {path} ({language})
```{language}
{content}
```

INSTRUCTIONS:
1. Check for issues related to: {categories}
2. Use search_docs tool to verify {platform} requirements
3. Return findings in this JSON format:

```json
{{
  "findings": [
    {{
      "rule_id": "CATEGORY###",
      "severity": "critical|warning|info",
      "category": "category_name",
      "line": 42,
      "message": "Brief description",
      "raw_match": "the problematic code"
    }}
  ]
}}
```

If no issues found, return: {{"findings": []}}
Respond ONLY with the JSON block."#,
            platform = self.platform,
            categories = categories_str,
            path = context.path,
            language = context.language,
            content = Self::truncate_content(&context.content, 3000),
        )
    }

    /// Truncate content to max length, preserving line boundaries
    fn truncate_content(content: &str, max_len: usize) -> String {
        if content.len() <= max_len {
            return content.to_string();
        }

        let mut result = String::with_capacity(max_len);
        for line in content.lines() {
            if result.len() + line.len() + 1 > max_len {
                result.push_str("\n... (truncated)");
                break;
            }
            if !result.is_empty() {
                result.push('\n');
            }
            result.push_str(line);
        }
        result
    }

    // =========================================================================
    // OUTPUT PARSING
    // =========================================================================

    /// Parse enriched finding from OpenCode output
    fn parse_enriched_finding(&self, raw: &RawFinding, output: &str) -> Result<EnrichedFinding> {
        // Extract JSON from output (may have markdown code blocks)
        let json_str = Self::extract_json(output)?;

        // Parse the JSON
        let parsed: serde_json::Value = serde_json::from_str(&json_str)?;

        let mut enriched = EnrichedFinding::from_raw(raw);

        // Parse issue details
        if let Some(issue) = parsed.get("issue") {
            enriched.issue = IssueDetails {
                title: issue
                    .get("title")
                    .and_then(|v| v.as_str())
                    .unwrap_or(&raw.message)
                    .to_string(),
                description: issue
                    .get("description")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string(),
                impact: issue
                    .get("impact")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string(),
            };
        }

        // Parse analysis
        if let Some(analysis) = parsed.get("analysis") {
            enriched.analysis = AnalysisContext {
                confidence: analysis
                    .get("confidence")
                    .and_then(|v| v.as_f64())
                    .unwrap_or(0.5) as f32,
                reasoning: analysis
                    .get("reasoning")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string(),
                rag_sources: Vec::new(), // Populated by MCP calls
                related_rules: analysis
                    .get("related_rules")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    })
                    .unwrap_or_default(),
            };
        }

        // Parse fix recommendation
        if let Some(fix) = parsed.get("fix") {
            enriched.fix = FixRecommendation {
                action: fix
                    .get("action")
                    .and_then(|v| v.as_str())
                    .map(|s| match s {
                        "add_code" => FixAction::AddCode,
                        "modify_code" => FixAction::ModifyCode,
                        "remove_code" => FixAction::RemoveCode,
                        "add_file" => FixAction::AddFile,
                        "update_config" => FixAction::UpdateConfig,
                        _ => FixAction::None,
                    })
                    .unwrap_or(FixAction::None),
                target_file: fix
                    .get("target_file")
                    .and_then(|v| v.as_str())
                    .unwrap_or(&raw.file_path)
                    .to_string(),
                code_snippet: fix
                    .get("code_snippet")
                    .and_then(|v| v.as_str())
                    .map(String::from),
                steps: fix
                    .get("steps")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(String::from))
                            .collect()
                    })
                    .unwrap_or_default(),
                complexity: fix
                    .get("complexity")
                    .and_then(|v| v.as_str())
                    .map(|s| match s {
                        "simple" => FixComplexity::Simple,
                        "complex" => FixComplexity::Complex,
                        _ => FixComplexity::Medium,
                    })
                    .unwrap_or(FixComplexity::Medium),
            };
        }

        // Parse references
        if let Some(refs) = parsed.get("references").and_then(|v| v.as_array()) {
            enriched.references = refs
                .iter()
                .filter_map(|r| {
                    let title = r.get("title").and_then(|v| v.as_str())?;
                    let url = r.get("url").and_then(|v| v.as_str())?;
                    let relevance =
                        r.get("relevance").and_then(|v| v.as_f64()).unwrap_or(1.0) as f32;
                    Some(DocReference::new(title, url).with_relevance(relevance))
                })
                .collect();
        }

        Ok(enriched)
    }

    /// Parse analysis results from OpenCode output
    fn parse_analysis_results(&self, output: &str, file_path: &str) -> Result<Vec<RawFinding>> {
        let json_str = Self::extract_json(output)?;
        let parsed: serde_json::Value = serde_json::from_str(&json_str)?;

        let findings = parsed
            .get("findings")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|f| {
                        let rule_id = f.get("rule_id").and_then(|v| v.as_str())?;
                        let severity = f
                            .get("severity")
                            .and_then(|v| v.as_str())
                            .map(|s| match s {
                                "critical" => Severity::Critical,
                                "warning" => Severity::Warning,
                                _ => Severity::Info,
                            })
                            .unwrap_or(Severity::Info);
                        let category = f
                            .get("category")
                            .and_then(|v| v.as_str())
                            .unwrap_or("unknown");
                        let message = f.get("message").and_then(|v| v.as_str()).unwrap_or("");

                        let mut finding =
                            RawFinding::new(rule_id, severity, category, file_path, message);

                        if let Some(line) = f.get("line").and_then(|v| v.as_u64()) {
                            finding = finding.with_line(line as usize);
                        }
                        if let Some(raw_match) = f.get("raw_match").and_then(|v| v.as_str()) {
                            finding = finding.with_match(raw_match);
                        }

                        Some(finding)
                    })
                    .collect()
            })
            .unwrap_or_default();

        Ok(findings)
    }

    /// Parse batch enrichment response from OpenCode
    fn parse_batch_enrichment(
        &self,
        original_findings: &[RawFinding],
        output: &str,
    ) -> Result<Vec<EnrichedFinding>> {
        let json_str = Self::extract_json(output)?;
        let parsed: serde_json::Value = serde_json::from_str(&json_str)?;

        let enriched_array = parsed
            .get("enriched_findings")
            .and_then(|v| v.as_array())
            .ok_or_else(|| OpenCodeError::parse_error("Missing enriched_findings array"))?;

        let mut results = Vec::with_capacity(original_findings.len());

        for original in original_findings {
            // Find matching enrichment by rule_id
            let enrichment = enriched_array.iter().find(|e| {
                e.get("rule_id")
                    .and_then(|v| v.as_str())
                    .map(|id| id == original.rule_id)
                    .unwrap_or(false)
            });

            let mut enriched = EnrichedFinding::from_raw(original);

            if let Some(e) = enrichment {
                // Parse issue details
                if let Some(issue) = e.get("issue") {
                    enriched.issue = IssueDetails {
                        title: issue
                            .get("title")
                            .and_then(|v| v.as_str())
                            .unwrap_or(&original.message)
                            .to_string(),
                        description: issue
                            .get("description")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string(),
                        impact: issue
                            .get("impact")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string(),
                    };
                }

                // Parse fix recommendation
                if let Some(fix) = e.get("fix") {
                    enriched.fix = FixRecommendation {
                        action: fix
                            .get("action")
                            .and_then(|v| v.as_str())
                            .map(|s| match s {
                                "add_code" => FixAction::AddCode,
                                "modify_code" => FixAction::ModifyCode,
                                "remove_code" => FixAction::RemoveCode,
                                "add_file" => FixAction::AddFile,
                                "update_config" => FixAction::UpdateConfig,
                                _ => FixAction::None,
                            })
                            .unwrap_or(FixAction::None),
                        target_file: original.file_path.clone(),
                        code_snippet: fix
                            .get("code_snippet")
                            .and_then(|v| v.as_str())
                            .map(String::from),
                        steps: fix
                            .get("steps")
                            .and_then(|v| v.as_array())
                            .map(|arr| {
                                arr.iter()
                                    .filter_map(|v| v.as_str().map(String::from))
                                    .collect()
                            })
                            .unwrap_or_default(),
                        complexity: FixComplexity::Medium,
                    };
                }

                // Parse confidence
                if let Some(conf) = e.get("confidence").and_then(|v| v.as_f64()) {
                    enriched.analysis.confidence = conf as f32;
                }

                // Mark as valid finding if is_valid is true or not specified
                let is_valid = e.get("is_valid").and_then(|v| v.as_bool()).unwrap_or(true);
                if !is_valid {
                    enriched.analysis.confidence = 0.1; // Low confidence for false positives
                }
            }

            results.push(enriched);
        }

        info!(
            "Parsed {} enriched findings from batch response",
            results.len()
        );
        Ok(results)
    }

    /// Extract JSON from OpenCode output (handles markdown code blocks)
    fn extract_json(output: &str) -> Result<String> {
        // Try to find JSON in markdown code block first
        if let Some(start) = output.find("```json") {
            let start = start + 7;
            if let Some(end) = output[start..].find("```") {
                return Ok(output[start..start + end].trim().to_string());
            }
        }

        // Try generic code block
        if let Some(start) = output.find("```") {
            let start = start + 3;
            // Skip language identifier if present
            let start = output[start..]
                .find('\n')
                .map(|n| start + n + 1)
                .unwrap_or(start);
            if let Some(end) = output[start..].find("```") {
                return Ok(output[start..start + end].trim().to_string());
            }
        }

        // Try to find raw JSON
        if let Some(start) = output.find('{') {
            if let Some(end) = output.rfind('}') {
                if end > start {
                    return Ok(output[start..=end].to_string());
                }
            }
        }

        Err(OpenCodeError::parse_error("No JSON found in output"))
    }

    // =========================================================================
    // HELPERS
    // =========================================================================

    /// Load file context for a finding (used by single-finding enrichment)
    #[allow(dead_code)]
    fn load_file_context(&self, abs_path: &Path, relative_path: &str) -> Result<FileContext> {
        let content = std::fs::read_to_string(abs_path).map_err(|e| {
            OpenCodeError::FileCollection(format!("Failed to read {}: {}", abs_path.display(), e))
        })?;

        Ok(FileContext::new(relative_path, content))
    }
}

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

    #[test]
    fn test_extract_json_from_markdown() {
        let output = r#"Here's the analysis:

```json
{"issue": {"title": "Test"}}
```

Done!"#;

        let json = OpenCodeClient::extract_json(output).unwrap();
        assert!(json.contains("issue"));
    }

    #[test]
    fn test_extract_json_raw() {
        let output = r#"{"findings": []}"#;
        let json = OpenCodeClient::extract_json(output).unwrap();
        assert_eq!(json, r#"{"findings": []}"#);
    }

    #[test]
    fn test_truncate_content() {
        let content = "line1\nline2\nline3\nline4\nline5";
        let truncated = OpenCodeClient::truncate_content(content, 20);
        // The truncated content includes "... (truncated)" suffix
        assert!(truncated.contains("truncated") || truncated.len() <= 20);
    }

    #[test]
    fn test_build_enrichment_prompt() {
        let config = OpenCodeConfig::with_cli_path(std::path::PathBuf::from("/usr/bin/opencode"));
        let client = OpenCodeClient {
            config,
            platform: "Shopify".to_string(),
        };

        let finding = RawFinding::new(
            "WH001",
            Severity::Critical,
            "webhooks",
            "src/app.ts",
            "Missing webhook",
        );
        let context = FileContext::new("src/app.ts", "const app = express();");

        let prompt = client.build_enrichment_prompt(&finding, &context);

        assert!(prompt.contains("WH001"));
        assert!(prompt.contains("webhooks"));
        assert!(prompt.contains("search_docs_for_rule"));
    }
}