jev-harness 0.1.7

Zero-overhead System One decision harness and token optimizer for AI coding agents.
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
use crate::{
    client::JevClient,
    gates::{
        modulate_reasoning_effort_with_tokens, route_model_tier, should_abort_trajectory,
        triage_test_failure, verify_step_completion,
    },
};
use clap::{Parser, Subcommand};
use std::fs;
use std::io::{self, IsTerminal, Read};
use std::path::Path;
use std::process;

#[derive(Parser)]
#[command(
    name = "jev",
    author = "ISMAEL HOSNI SOILET DE LIMA <soilet.ismael@gmail.com>",
    version = env!("CARGO_PKG_VERSION"),
    about = "Zero-overhead System One decision harness and token optimizer for AI coding agents",
    long_about = None
)]
pub struct Cli {
    #[arg(long, global = true, help = "Force offline heuristic simulation mode")]
    pub mock: bool,

    #[arg(long, global = true, help = "Output results in machine-readable JSON")]
    pub json: bool,

    #[arg(
        long,
        global = true,
        help = "Override backend provider (typesafe, opencode, openrouter)"
    )]
    pub provider: Option<String>,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    #[command(about = "Display active credentials, provider, and engine mode")]
    Status,

    #[command(
        alias = "triage",
        about = "Triage test traceback & determine if frontier LLM call can be skipped"
    )]
    TestGate {
        #[arg(help = "Direct error string or path to error log file")]
        log_pos: Option<String>,

        #[arg(short, long, help = "Path to error log or raw string")]
        log: Option<String>,

        #[arg(long, help = "Sample error string (alias for --log)")]
        sample: Option<String>,
    },

    #[command(
        alias = "abort",
        about = "Evaluate if current trajectory or refactor direction should be aborted"
    )]
    AbortCheck {
        #[arg(help = "Proposed next step plan")]
        plan_pos: Option<String>,

        #[arg(short, long, help = "Proposed next step plan")]
        plan: Option<String>,

        #[arg(
            short = 'H',
            long,
            default_value = "",
            help = "Recent attempts or error history"
        )]
        history: String,
    },

    #[command(about = "Select minimal sufficient model tier for a given task")]
    Route {
        #[arg(help = "Task description")]
        task_pos: Option<String>,

        #[arg(short, long, help = "Task description")]
        task: Option<String>,
    },

    #[command(about = "Verify if actual step output satisfies required criteria")]
    Verify {
        #[arg(short, long, help = "Acceptance criteria to satisfy")]
        criteria: String,

        #[arg(short, long, help = "Actual output to verify")]
        output: String,
    },

    #[command(
        alias = "astra-jev",
        alias = "effort",
        about = "Dynamically modulate reasoning effort per-generation (Astra-Jev)"
    )]
    ReasoningEffort {
        #[arg(help = "Immediate step context or prompt description")]
        context_pos: Option<String>,

        #[arg(short, long, help = "Immediate step context or prompt description")]
        context: Option<String>,

        #[arg(
            long = "target-provider",
            default_value = "openai",
            help = "Target model provider (openai, deepseek, qwen, anthropic, gemini)"
        )]
        target_provider: String,

        #[arg(
            short,
            long,
            help = "Target model name (e.g. gpt-5.6-luna, deepseek-v4.1-flash)"
        )]
        model: Option<String>,

        #[arg(
            long = "session-context-tokens",
            default_value = "0",
            help = "Active prompt tokens in session context"
        )]
        session_context_tokens: usize,
    },
}

fn read_input(arg_pos: Option<String>, arg_flag: Option<String>) -> io::Result<String> {
    if let Some(target) = arg_flag.or(arg_pos) {
        let p = Path::new(&target);
        if p.is_file() {
            return fs::read_to_string(p);
        }
        return Ok(target);
    }

    if !io::stdin().is_terminal() {
        let mut buffer = String::new();
        io::stdin().read_to_string(&mut buffer)?;
        return Ok(buffer);
    }

    Ok(String::new())
}

pub async fn run_cli() {
    let cli = Cli::parse();
    let mut client = JevClient::new(None, None, None, None, cli.mock);
    if let Some(ref p) = cli.provider {
        client.provider = p.clone();
        if p == "opencode" {
            client.base_url = "https://opencode.ai/zen/v1/systemone".to_string();
            client.model = "jev-1.13-free".to_string();
        }
    }

    match cli.command {
        Commands::Status => {
            println!("\n=== JEV HARNESS (RUST) STATUS ===");
            let is_live =
                !client.force_mock && (client.provider == "opencode" || client.api_key.is_some());
            if is_live {
                if client.provider == "opencode" {
                    println!("Provider:    OPENCODE ZEN (Free Tier)");
                    println!("Endpoint:    {}", client.base_url);
                    println!("Engine Mode: LIVE (OpenCode Zen Free Community Model)");
                } else {
                    let masked = if let Some(ref key) = client.api_key {
                        if key.len() > 10 {
                            format!("{}...{}", &key[..6], &key[key.len() - 4..])
                        } else {
                            "***".to_string()
                        }
                    } else {
                        "***".to_string()
                    };
                    println!("API Key:     Configured ({})", masked);
                    println!("Provider:    {}", client.provider.to_uppercase());
                    println!("Endpoint:    {}", client.base_url);
                    println!("Engine Mode: LIVE");
                }
            } else {
                println!("API Key:     NOT DETECTED");
                println!("Engine Mode: SIMULATION / MOCK (Heuristic offline mode active)");
            }
            println!("Model:       {}", client.model);
            println!("=================================\n");
            process::exit(0);
        }

        Commands::TestGate {
            log_pos,
            log,
            sample,
        } => {
            let text = match read_input(log_pos, log.or(sample)) {
                Ok(t) if !t.trim().is_empty() => t,
                _ => {
                    eprintln!("Error: No test failure log provided. Pass log via argument or pipe via stdin.");
                    process::exit(2);
                }
            };

            match triage_test_failure(&text, Some(&client)).await {
                Ok(res) => {
                    if cli.json {
                        println!("{}", serde_json::to_string_pretty(&res).unwrap());
                    } else {
                        println!("\n--- JEV TEST TRIAGE VERDICT (RUST) ---");
                        println!("Category:        {}", res.category.to_uppercase());
                        println!("Confidence:      {:.1}%", res.confidence * 100.0);
                        println!(
                            "Skip LLM Call:   {}",
                            if res.skip_llm {
                                "YES (Save Tokens!)"
                            } else {
                                "NO (Dispatch to System 2)"
                            }
                        );
                        println!("Severity Score:  {:.1} / 4.0", res.severity_score);
                        println!("Recommendation:  {}", res.action_recommendation);
                        if res.is_mock {
                            println!("Mode:            [SIMULATION/MOCK]");
                        }
                        println!("--------------------------------------\n");
                    }
                    process::exit(if res.skip_llm { 0 } else { 1 });
                }
                Err(e) => {
                    eprintln!("Error triaging test failure: {}", e);
                    process::exit(2);
                }
            }
        }

        Commands::AbortCheck {
            plan_pos,
            plan,
            history,
        } => {
            let plan_text = match read_input(plan_pos, plan) {
                Ok(p) if !p.trim().is_empty() => p,
                _ => {
                    eprintln!(
                        "Error: No plan provided. Pass --plan <text> or positional argument."
                    );
                    process::exit(2);
                }
            };

            match should_abort_trajectory(&plan_text, &history, Some(&client)).await {
                Ok(res) => {
                    if cli.json {
                        println!("{}", serde_json::to_string_pretty(&res).unwrap());
                    } else {
                        println!("\n--- JEV ABORT GATE VERDICT (RUST) ---");
                        println!(
                            "Should Abort:     {}",
                            if res.should_abort {
                                "YES - STOP & RECONSIDER"
                            } else {
                                "NO - PROCEED"
                            }
                        );
                        println!("Abort Probability: {:.1}%", res.abort_probability * 100.0);
                        println!("Viability Score:   {:.1} / 4.0", res.viability_score);
                        println!("Summary:           {}", res.reasoning_summary);
                        if res.is_mock {
                            println!("Mode:              [SIMULATION/MOCK]");
                        }
                        println!("-------------------------------------\n");
                    }
                    process::exit(if res.should_abort { 1 } else { 0 });
                }
                Err(e) => {
                    eprintln!("Error evaluating abort gate: {}", e);
                    process::exit(2);
                }
            }
        }

        Commands::Route { task_pos, task } => {
            let task_text = match read_input(task_pos, task) {
                Ok(t) if !t.trim().is_empty() => t,
                _ => {
                    eprintln!("Error: No task description provided. Pass --task <text>.");
                    process::exit(2);
                }
            };

            match route_model_tier(&task_text, Some(&client)).await {
                Ok(res) => {
                    if cli.json {
                        println!("{}", serde_json::to_string_pretty(&res).unwrap());
                    } else {
                        println!("\n--- JEV MODEL ROUTE VERDICT (RUST) ---");
                        println!("Selected Tier:     {}", res.selected_tier.to_uppercase());
                        println!("Confidence:        {:.1}%", res.confidence * 100.0);
                        println!("Recommended Model: {}", res.recommended_model);
                        println!("Rationale:         {}", res.rationale);
                        if res.is_mock {
                            println!("Mode:              [SIMULATION/MOCK]");
                        }
                        println!("--------------------------------------\n");
                    }
                    process::exit(0);
                }
                Err(e) => {
                    eprintln!("Error routing model tier: {}", e);
                    process::exit(2);
                }
            }
        }

        Commands::Verify { criteria, output } => {
            match verify_step_completion(&criteria, &output, Some(&client)).await {
                Ok(res) => {
                    if cli.json {
                        println!("{}", serde_json::to_string_pretty(&res).unwrap());
                    } else {
                        println!("\n--- JEV VERIFICATION VERDICT (RUST) ---");
                        println!(
                            "Verified:          {}",
                            if res.is_verified {
                                "PASS"
                            } else {
                                "REWORK NEEDED"
                            }
                        );
                        println!(
                            "Satisfaction Prob: {:.1}%",
                            res.satisfaction_probability * 100.0
                        );
                        println!("Rigor Score:       {:.1} / 4.0", res.rigor_score);
                        if res.is_mock {
                            println!("Mode:              [SIMULATION/MOCK]");
                        }
                        println!("---------------------------------------\n");
                    }
                    process::exit(if res.is_verified { 0 } else { 1 });
                }
                Err(e) => {
                    eprintln!("Error verifying step completion: {}", e);
                    process::exit(2);
                }
            }
        }

        Commands::ReasoningEffort {
            context_pos,
            context,
            target_provider,
            model,
            session_context_tokens,
        } => {
            let ctx = match read_input(context_pos, context) {
                Ok(t) if !t.trim().is_empty() => t,
                _ => {
                    eprintln!(
                        "Error: Context/step description must be provided via argument or stdin."
                    );
                    process::exit(2);
                }
            };

            match modulate_reasoning_effort_with_tokens(
                &ctx,
                &target_provider,
                model.as_deref(),
                session_context_tokens,
                Some(&client),
            )
            .await
            {
                Ok(res) => {
                    if cli.json {
                        println!("{}", serde_json::to_string_pretty(&res).unwrap());
                    } else {
                        println!("\n--- JEV REASONING EFFORT VERDICT (RUST) ---");
                        println!("Effort:            {}", res.effort.to_uppercase());
                        println!("Confidence:        {:.1}%", res.confidence * 100.0);
                        println!("Complexity Score:  {:.1} / 4.0", res.complexity_score);
                        println!("Provider:          {}", res.provider);
                        println!(
                            "Supported:         {}",
                            if res.is_reasoning_supported {
                                "YES"
                            } else {
                                "NO (Direct model)"
                            }
                        );
                        println!("Rationale:         {}", res.rationale);
                        println!("Provider Params:   {}", res.provider_params);
                        if !res.cache_safe_recommendation.is_empty() {
                            println!("Cache Advisory:    {}", res.cache_safe_recommendation);
                        }
                        if res.is_mock {
                            println!("Mode:              [SIMULATION/MOCK]");
                        }
                        println!("------------------------------------------\n");
                    }
                    process::exit(0);
                }
                Err(e) => {
                    eprintln!("Error modulating reasoning effort: {}", e);
                    process::exit(2);
                }
            }
        }
    }
}