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
//! Integration tests for OpenCode CLI client
//!
//! These tests verify the CLI-based OpenCode integration for
//! RAG-powered validation enrichment.
//!
//! Prerequisites:
//! 1. OpenCode CLI installed: `curl -fsSL https://opencode.ai/install | bash`
//! 2. Authenticated: `opencode auth login` → Select Z.AI Coding Plan
//!
//! To run:
//! ```bash
//! cargo test -p gatekpr-opencode
//! ```
//!
//! Tests that require the CLI will skip gracefully if not installed.

use gatekpr_opencode::{FileContext, OpenCodeClient, OpenCodeConfig, RawFinding, Severity};
use std::path::PathBuf;

/// Check if OpenCode CLI is available
fn cli_available() -> bool {
    OpenCodeConfig::new().is_ok()
}

/// Skip test if OpenCode CLI is not available
macro_rules! skip_if_no_cli {
    () => {
        if !cli_available() {
            eprintln!("Skipping test: OpenCode CLI not installed");
            eprintln!("Install with: curl -fsSL https://opencode.ai/install | bash");
            return;
        }
    };
}

/// Get the path to test fixtures
fn fixtures_path() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent() // crates/
        .unwrap()
        .parent() // workspace root
        .unwrap()
        .join("tests")
        .join("fixtures")
        .join("apps")
}

// ===========================================================================
// CONFIGURATION TESTS
// ===========================================================================

#[test]
fn test_config_with_cli_path() {
    let config = OpenCodeConfig::with_cli_path(PathBuf::from("/usr/bin/opencode"));
    assert_eq!(config.cli_path, PathBuf::from("/usr/bin/opencode"));
}

#[test]
fn test_config_with_model() {
    let config = OpenCodeConfig::with_cli_path(PathBuf::from("/usr/bin/opencode"))
        .with_model("custom/model");
    assert_eq!(config.model, "custom/model");
}

#[test]
fn test_config_with_timeout() {
    use std::time::Duration;

    let config = OpenCodeConfig::with_cli_path(PathBuf::from("/usr/bin/opencode"))
        .with_timeout(Duration::from_secs(300));
    assert_eq!(config.timeout, Duration::from_secs(300));
}

#[test]
fn test_config_default_model() {
    let config = OpenCodeConfig::with_cli_path(PathBuf::from("/usr/bin/opencode"));
    assert!(config.model.contains("zai-coding-plan"));
}

#[test]
fn test_config_auto_detection() {
    // This may pass or fail depending on whether CLI is installed
    let result = OpenCodeConfig::new();
    if let Ok(config) = result {
        assert!(config.cli_path.exists());
    }
}

// ===========================================================================
// MODEL TESTS
// ===========================================================================

#[test]
fn test_raw_finding_creation() {
    let finding = RawFinding::new(
        "WH001",
        Severity::Critical,
        "webhooks",
        "src/webhooks.ts",
        "Missing GDPR webhook handler",
    )
    .with_line(42)
    .with_column(10)
    .with_match("// TODO: add webhook");

    assert_eq!(finding.rule_id, "WH001");
    assert_eq!(finding.severity, Severity::Critical);
    assert_eq!(finding.category, "webhooks");
    assert_eq!(finding.file_path, "src/webhooks.ts");
    assert_eq!(finding.line, Some(42));
    assert_eq!(finding.column, Some(10));
    assert_eq!(finding.raw_match, "// TODO: add webhook");
}

#[test]
fn test_raw_finding_location() {
    let finding = RawFinding::new(
        "WH001",
        Severity::Critical,
        "webhooks",
        "src/app.ts",
        "Test",
    )
    .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_severity_is_blocking() {
    assert!(Severity::Critical.is_blocking());
    assert!(!Severity::Warning.is_blocking());
    assert!(!Severity::Info.is_blocking());
}

#[test]
fn test_file_context_creation() {
    let content = "const app = express();\napp.listen(3000);";
    let context = FileContext::new("src/app.ts", content);

    assert_eq!(context.path, "src/app.ts");
    assert_eq!(context.language, "typescript");
    assert_eq!(context.line_count, 2);
}

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

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

#[test]
fn test_file_context_language_detection() {
    assert_eq!(FileContext::new("app.ts", "").language, "typescript");
    assert_eq!(FileContext::new("app.tsx", "").language, "typescript");
    assert_eq!(FileContext::new("app.js", "").language, "javascript");
    assert_eq!(FileContext::new("app.jsx", "").language, "javascript");
    assert_eq!(FileContext::new("app.rb", "").language, "ruby");
    assert_eq!(FileContext::new("app.py", "").language, "python");
    assert_eq!(FileContext::new("app.go", "").language, "go");
    assert_eq!(FileContext::new("app.rs", "").language, "rust");
}

// ===========================================================================
// CLIENT TESTS (require CLI)
// ===========================================================================

#[test]
fn test_client_creation_with_valid_path() {
    skip_if_no_cli!();

    let config = OpenCodeConfig::new().expect("CLI should be found");
    let client = OpenCodeClient::new(config);
    assert!(client.is_ok());
}

#[test]
fn test_client_auto_creation() {
    skip_if_no_cli!();

    let client = OpenCodeClient::auto();
    assert!(client.is_ok());

    let client = client.unwrap();
    assert!(client.cli_path().exists());
    assert!(client.model().contains("zai-coding-plan"));
}

#[test]
fn test_client_invalid_path() {
    let config = OpenCodeConfig::with_cli_path(PathBuf::from("/nonexistent/opencode"));
    let client = OpenCodeClient::new(config);
    assert!(client.is_err());
}

// ===========================================================================
// INTEGRATION TESTS (require authenticated CLI)
// ===========================================================================

#[tokio::test]
async fn test_enrich_single_finding() {
    skip_if_no_cli!();

    // Skip in CI environments
    if std::env::var("CI").is_ok() {
        eprintln!("Skipping: CI environment detected");
        return;
    }

    let client = match OpenCodeClient::auto() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Skipping: {}", e);
            return;
        }
    };

    let finding = RawFinding::new(
        "WH001",
        Severity::Critical,
        "webhooks",
        "src/webhooks.ts",
        "Missing GDPR customers/redact webhook handler",
    )
    .with_line(1);

    let context = FileContext::new(
        "src/webhooks.ts",
        r#"
import express from 'express';

const app = express();

// Webhook handlers
app.post('/webhooks/orders/create', (req, res) => {
    console.log('Order created');
    res.sendStatus(200);
});

// Missing: customers/redact
// Missing: customers/data_request
// Missing: shop/redact
"#,
    );

    match client.enrich_finding(&finding, &context).await {
        Ok(enriched) => {
            assert_eq!(enriched.rule_id, "WH001");
            assert_eq!(enriched.severity, Severity::Critical);
            assert!(!enriched.issue.title.is_empty());
            // Enriched findings should have more detail than raw
            println!("Enriched: {:#?}", enriched);
        }
        Err(e) => {
            // Auth errors are expected if not logged in
            let msg = e.to_string();
            if msg.contains("auth") || msg.contains("credential") {
                eprintln!("Skipping: Not authenticated");
            } else {
                eprintln!("Error: {}", e);
            }
        }
    }
}

#[tokio::test]
async fn test_enrich_findings_batch() {
    skip_if_no_cli!();

    if std::env::var("CI").is_ok() {
        eprintln!("Skipping: CI environment detected");
        return;
    }

    let app_path = fixtures_path().join("passing-app");
    if !app_path.exists() {
        eprintln!("Skipping: fixtures not found at {}", app_path.display());
        return;
    }

    let client = match OpenCodeClient::auto() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Skipping: {}", e);
            return;
        }
    };

    let findings = vec![
        RawFinding::new(
            "WH001",
            Severity::Critical,
            "webhooks",
            "src/webhooks/gdpr.ts",
            "Missing webhook",
        ),
        RawFinding::new(
            "API001",
            Severity::Warning,
            "api",
            "src/api/products.ts",
            "Using REST API",
        ),
    ];

    match client.enrich_findings(findings, &app_path).await {
        Ok(enriched) => {
            assert_eq!(enriched.len(), 2);
            for finding in &enriched {
                println!("{}: {}", finding.rule_id, finding.issue.title);
            }
        }
        Err(e) => {
            let msg = e.to_string();
            if msg.contains("auth") || msg.contains("credential") || msg.contains("Failed to read")
            {
                eprintln!("Skipping: {}", e);
            } else {
                eprintln!("Error: {}", e);
            }
        }
    }
}

#[tokio::test]
async fn test_analyze_file() {
    skip_if_no_cli!();

    if std::env::var("CI").is_ok() {
        eprintln!("Skipping: CI environment detected");
        return;
    }

    let app_path = fixtures_path().join("failing-app");
    if !app_path.exists() {
        eprintln!("Skipping: fixtures not found");
        return;
    }

    let client = match OpenCodeClient::auto() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Skipping: {}", e);
            return;
        }
    };

    // Find a TypeScript file to analyze
    let file_path = app_path.join("src").join("index.ts");
    if !file_path.exists() {
        // Try alternative paths
        eprintln!("Skipping: No TypeScript file found in fixtures");
        return;
    }

    match client
        .analyze_file(&file_path, &["webhooks", "security"])
        .await
    {
        Ok(findings) => {
            println!("Found {} issues", findings.len());
            for finding in &findings {
                println!("  {}: {}", finding.rule_id, finding.message);
            }
        }
        Err(e) => {
            let msg = e.to_string();
            if msg.contains("auth") || msg.contains("credential") {
                eprintln!("Skipping: Not authenticated");
            } else {
                eprintln!("Error: {}", e);
            }
        }
    }
}

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

#[test]
fn test_validation_result_summary() {
    use gatekpr_opencode::{EnrichedFinding, ValidationResult, ValidationStatus};

    let mut result = ValidationResult::new("/app");

    // Add findings
    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
        .findings
        .push(EnrichedFinding::from_raw(&RawFinding::new(
            "PERF001",
            Severity::Info,
            "performance",
            "src/api.ts",
            "Large bundle",
        )));

    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_eq!(result.summary.info_count, 1);
    assert!(result.summary.score < 100);
}

#[test]
fn test_validation_result_ready() {
    use gatekpr_opencode::{EnrichedFinding, ValidationResult, ValidationStatus};

    let mut result = ValidationResult::new("/app");

    // Only info findings = ready
    result
        .findings
        .push(EnrichedFinding::from_raw(&RawFinding::new(
            "PERF001",
            Severity::Info,
            "performance",
            "src/api.ts",
            "Consider caching",
        )));

    result.calculate_summary();

    assert_eq!(result.summary.status, ValidationStatus::Ready);
    assert_eq!(result.summary.score, 100);
}

#[test]
fn test_validation_result_needs_review() {
    use gatekpr_opencode::{EnrichedFinding, ValidationResult, ValidationStatus};

    let mut result = ValidationResult::new("/app");

    // Only warnings = needs review
    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::NeedsReview);
    assert!(result.summary.score < 100);
    assert!(result.summary.score > 0);
}