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
//! Data models for OpenCode validation enrichment
//!
//! These models represent the two-stage validation flow:
//! - Stage 1: Local pipeline produces RawFinding
//! - Stage 2: OpenCode enriches to EnrichedFinding with RAG context

use serde::{Deserialize, Serialize};

// =============================================================================
// SEVERITY
// =============================================================================

/// Severity level for findings
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Critical,
    Warning,
    Info,
}

impl Severity {
    /// Get priority for sorting (lower = higher priority)
    pub fn priority(&self) -> u8 {
        match self {
            Self::Critical => 0,
            Self::Warning => 1,
            Self::Info => 2,
        }
    }

    /// Check if this is a blocking severity
    pub fn is_blocking(&self) -> bool {
        matches!(self, Self::Critical)
    }
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Critical => write!(f, "critical"),
            Self::Warning => write!(f, "warning"),
            Self::Info => write!(f, "info"),
        }
    }
}

// =============================================================================
// RAW FINDING (Stage 1 - from Local Pipeline)
// =============================================================================

/// Raw finding from local pipeline (Stage 1)
///
/// This is produced by the pattern matching and rule engine.
/// It contains the basic violation information without enrichment.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawFinding {
    /// Rule ID (e.g., "WH001", "SEC002")
    pub rule_id: String,

    /// Severity level
    pub severity: Severity,

    /// Category (e.g., "webhooks", "security", "billing")
    pub category: String,

    /// File path where the issue was found
    pub file_path: String,

    /// Line number (if available)
    pub line: Option<usize>,

    /// Column number (if available)
    pub column: Option<usize>,

    /// The matched pattern or code snippet
    pub raw_match: String,

    /// Brief message from the rule
    pub message: String,
}

impl RawFinding {
    /// Create a new raw finding
    pub fn new(
        rule_id: impl Into<String>,
        severity: Severity,
        category: impl Into<String>,
        file_path: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            rule_id: rule_id.into(),
            severity,
            category: category.into(),
            file_path: file_path.into(),
            line: None,
            column: None,
            raw_match: String::new(),
            message: message.into(),
        }
    }

    /// Set line number
    pub fn with_line(mut self, line: usize) -> Self {
        self.line = Some(line);
        self
    }

    /// Set column number
    pub fn with_column(mut self, column: usize) -> Self {
        self.column = Some(column);
        self
    }

    /// Set the raw match
    pub fn with_match(mut self, raw_match: impl Into<String>) -> Self {
        self.raw_match = raw_match.into();
        self
    }

    /// Get location as string
    pub fn location(&self) -> String {
        match (self.line, self.column) {
            (Some(l), Some(c)) => format!("{}:{}:{}", self.file_path, l, c),
            (Some(l), None) => format!("{}:{}", self.file_path, l),
            _ => self.file_path.clone(),
        }
    }
}

// =============================================================================
// ENRICHED FINDING (Stage 2 - from OpenCode + RAG)
// =============================================================================

/// Enriched finding after OpenCode + RAG processing (Stage 2)
///
/// This contains the full analysis with explanations, fix recommendations,
/// and documentation references from the RAG system.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnrichedFinding {
    // === From Stage 1 ===
    /// Rule ID (e.g., "WH001", "SEC002")
    pub rule_id: String,

    /// Severity level
    pub severity: Severity,

    /// Category (e.g., "webhooks", "security", "billing")
    pub category: String,

    /// File path where the issue was found
    pub file_path: String,

    /// Line number (if available)
    pub line: Option<usize>,

    // === From Stage 2 (OpenCode + RAG) ===
    /// Detailed issue information
    pub issue: IssueDetails,

    /// Analysis context from RAG
    pub analysis: AnalysisContext,

    /// Fix recommendation
    pub fix: FixRecommendation,

    /// Documentation references
    pub references: Vec<DocReference>,
}

impl EnrichedFinding {
    /// Create from a raw finding (without enrichment yet)
    pub fn from_raw(raw: &RawFinding) -> Self {
        Self {
            rule_id: raw.rule_id.clone(),
            severity: raw.severity,
            category: raw.category.clone(),
            file_path: raw.file_path.clone(),
            line: raw.line,
            issue: IssueDetails {
                title: raw.message.clone(),
                description: String::new(),
                impact: String::new(),
            },
            analysis: AnalysisContext::default(),
            fix: FixRecommendation::default(),
            references: Vec::new(),
        }
    }

    /// Get location as string
    pub fn location(&self) -> String {
        match self.line {
            Some(l) => format!("{}:{}", self.file_path, l),
            None => self.file_path.clone(),
        }
    }

    /// Check if this is a blocking issue
    pub fn is_blocking(&self) -> bool {
        self.severity.is_blocking()
    }
}

/// Detailed issue information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IssueDetails {
    /// Short title for the issue
    pub title: String,

    /// Detailed description of what's wrong
    pub description: String,

    /// Impact if not fixed (e.g., "App will be rejected")
    pub impact: String,
}

/// Analysis context from RAG
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AnalysisContext {
    /// RAG sources that were consulted (collection:doc_id)
    pub rag_sources: Vec<String>,

    /// Confidence score (0.0 - 1.0)
    pub confidence: f32,

    /// Reasoning for the analysis
    pub reasoning: String,

    /// Related rules that may also apply
    pub related_rules: Vec<String>,
}

/// Fix recommendation
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FixRecommendation {
    /// Type of fix action required
    pub action: FixAction,

    /// Target file for the fix
    pub target_file: String,

    /// Code snippet to add/modify (if applicable)
    pub code_snippet: Option<String>,

    /// Step-by-step instructions
    pub steps: Vec<String>,

    /// Estimated complexity
    pub complexity: FixComplexity,
}

/// Type of fix action
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FixAction {
    /// Add new code
    AddCode,
    /// Modify existing code
    ModifyCode,
    /// Remove code
    RemoveCode,
    /// Add a new file
    AddFile,
    /// Update configuration
    UpdateConfig,
    /// No action needed (informational)
    #[default]
    None,
}

/// Complexity of the fix
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FixComplexity {
    /// Simple fix (few lines)
    Simple,
    /// Medium complexity
    #[default]
    Medium,
    /// Complex fix (architectural changes)
    Complex,
}

/// Documentation reference
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocReference {
    /// Document title
    pub title: String,

    /// URL to the documentation
    pub url: String,

    /// Relevance score (0.0 - 1.0)
    pub relevance: f32,

    /// Brief excerpt from the doc
    pub excerpt: Option<String>,
}

impl DocReference {
    /// Create a new documentation reference
    pub fn new(title: impl Into<String>, url: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            url: url.into(),
            relevance: 1.0,
            excerpt: None,
        }
    }

    /// Set relevance score
    pub fn with_relevance(mut self, relevance: f32) -> Self {
        self.relevance = relevance;
        self
    }

    /// Set excerpt
    pub fn with_excerpt(mut self, excerpt: impl Into<String>) -> Self {
        self.excerpt = Some(excerpt.into());
        self
    }
}

// =============================================================================
// VALIDATION RESULT
// =============================================================================

/// Complete validation result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
    /// Unique validation ID
    pub id: String,

    /// Path to the validated codebase
    pub codebase_path: String,

    /// Duration of Stage 1 (local pipeline) in milliseconds
    pub stage1_duration_ms: u64,

    /// Duration of Stage 2 (OpenCode enrichment) in milliseconds
    pub stage2_duration_ms: u64,

    /// All enriched findings
    pub findings: Vec<EnrichedFinding>,

    /// Summary of the validation
    pub summary: ValidationSummary,
}

impl ValidationResult {
    /// Create a new validation result
    pub fn new(codebase_path: impl Into<String>) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            codebase_path: codebase_path.into(),
            stage1_duration_ms: 0,
            stage2_duration_ms: 0,
            findings: Vec::new(),
            summary: ValidationSummary::default(),
        }
    }

    /// Calculate summary from findings
    pub fn calculate_summary(&mut self) {
        let critical = self
            .findings
            .iter()
            .filter(|f| f.severity == Severity::Critical)
            .count();
        let warnings = self
            .findings
            .iter()
            .filter(|f| f.severity == Severity::Warning)
            .count();
        let info = self
            .findings
            .iter()
            .filter(|f| f.severity == Severity::Info)
            .count();

        let status = if critical > 0 {
            ValidationStatus::NotReady
        } else if warnings > 0 {
            ValidationStatus::NeedsReview
        } else {
            ValidationStatus::Ready
        };

        // Score: 100 - (critical * 20) - (warnings * 5)
        let score = (100i32 - (critical as i32 * 20) - (warnings as i32 * 5)).max(0) as u8;

        self.summary = ValidationSummary {
            status,
            score,
            critical_count: critical,
            warning_count: warnings,
            info_count: info,
            next_steps: self.generate_next_steps(),
        };
    }

    /// Generate next steps from critical findings
    fn generate_next_steps(&self) -> Vec<String> {
        self.findings
            .iter()
            .filter(|f| f.severity == Severity::Critical)
            .take(5)
            .map(|f| f.issue.title.clone())
            .collect()
    }
}

/// Validation summary
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ValidationSummary {
    /// Overall status
    pub status: ValidationStatus,

    /// Score out of 100
    pub score: u8,

    /// Count of critical issues
    pub critical_count: usize,

    /// Count of warnings
    pub warning_count: usize,

    /// Count of info items
    pub info_count: usize,

    /// Next steps to fix blocking issues
    pub next_steps: Vec<String>,
}

/// Validation status
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ValidationStatus {
    /// Ready for submission
    Ready,
    /// Needs review but may pass
    NeedsReview,
    /// Not ready, has blocking issues
    #[default]
    NotReady,
}

impl std::fmt::Display for ValidationStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Ready => write!(f, "ready"),
            Self::NeedsReview => write!(f, "needs_review"),
            Self::NotReady => write!(f, "not_ready"),
        }
    }
}

// =============================================================================
// FILE CONTEXT
// =============================================================================

/// File context for enrichment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileContext {
    /// File path
    pub path: String,

    /// File content
    pub content: String,

    /// Detected language
    pub language: String,

    /// Line count
    pub line_count: usize,
}

impl FileContext {
    /// Create from file path and content
    pub fn new(path: impl Into<String>, content: impl Into<String>) -> Self {
        let content = content.into();
        let line_count = content.lines().count();
        let path = path.into();
        let language = Self::detect_language(&path);

        Self {
            path,
            content,
            language,
            line_count,
        }
    }

    /// Detect language from file extension
    fn detect_language(path: &str) -> String {
        let ext = path.rsplit('.').next().unwrap_or("");
        match ext {
            "ts" | "tsx" => "typescript",
            "js" | "jsx" => "javascript",
            "rb" => "ruby",
            "py" => "python",
            "php" => "php",
            "go" => "go",
            "rs" => "rust",
            "toml" => "toml",
            "json" => "json",
            "yaml" | "yml" => "yaml",
            _ => "unknown",
        }
        .to_string()
    }

    /// Get a snippet around a line
    pub fn snippet(&self, line: usize, context_lines: usize) -> String {
        let lines: Vec<&str> = self.content.lines().collect();
        let start = line.saturating_sub(context_lines + 1);
        let end = (line + context_lines).min(lines.len());

        lines[start..end].join("\n")
    }
}

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

    #[test]
    fn test_raw_finding_location() {
        let finding = RawFinding::new(
            "WH001",
            Severity::Critical,
            "webhooks",
            "src/app.ts",
            "Missing webhook",
        )
        .with_line(42)
        .with_column(5);

        assert_eq!(finding.location(), "src/app.ts:42:5");
    }

    #[test]
    fn test_severity_priority() {
        assert!(Severity::Critical.priority() < Severity::Warning.priority());
        assert!(Severity::Warning.priority() < Severity::Info.priority());
    }

    #[test]
    fn test_validation_result_summary() {
        let mut result = ValidationResult::new("/app");
        result
            .findings
            .push(EnrichedFinding::from_raw(&RawFinding::new(
                "WH001",
                Severity::Critical,
                "webhooks",
                "src/app.ts",
                "Missing webhook",
            )));
        result
            .findings
            .push(EnrichedFinding::from_raw(&RawFinding::new(
                "SEC001",
                Severity::Warning,
                "security",
                "src/utils.ts",
                "Eval usage",
            )));

        result.calculate_summary();

        assert_eq!(result.summary.status, ValidationStatus::NotReady);
        assert_eq!(result.summary.critical_count, 1);
        assert_eq!(result.summary.warning_count, 1);
        assert!(result.summary.score < 100);
    }

    #[test]
    fn test_file_context_snippet() {
        let content = "line1\nline2\nline3\nline4\nline5\nline6\nline7";
        let ctx = FileContext::new("test.ts", content);

        let snippet = ctx.snippet(4, 1);
        assert!(snippet.contains("line3"));
        assert!(snippet.contains("line4"));
        assert!(snippet.contains("line5"));
    }
}