wvq-runtime 0.1.0-alpha.2

Bounded test-runner adapters and evidence normalization for Weavatrix Quality
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
//! Registered executors. The program argv is never taken from MCP/user fields.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use crate::normalize::RuntimeError;
use crate::process::{self, ProcessLimits, RawExecution};

/// Frozen identity of a runner (`vitest`, `go-test`, …).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ExecutorId(String);

impl ExecutorId {
    /// Parse a non-empty executor id. Whitespace is rejected.
    ///
    /// # Errors
    ///
    /// Returns [`RuntimeError::InvalidArg`] when empty or containing whitespace.
    pub fn new(raw: impl AsRef<str>) -> Result<Self, RuntimeError> {
        let raw = raw.as_ref();
        if raw.is_empty() || raw.chars().any(char::is_whitespace) {
            return Err(RuntimeError::InvalidArg(
                "executor id must be a non-empty token".into(),
            ));
        }
        Ok(Self(raw.to_owned()))
    }

    /// Borrow the id.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// What a registered executor can do.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExecutorCapabilities {
    /// Produces JUnit-like case lists.
    pub cases: bool,
    /// Can emit LCOV or equivalent coverage.
    pub coverage: bool,
}

/// How to invoke a registered program. `program` is never user-supplied.
#[derive(Debug, Clone)]
pub struct ExecutorSpec {
    /// Registry key.
    pub id: ExecutorId,
    /// PATH executable name. Must not contain a path separator.
    pub program: String,
    /// Frozen argv prefix after the program.
    pub prefix: Vec<String>,
    /// Optional flag inserted once before the typed filter argv slots.
    pub filter_flag: Option<String>,
    /// Capabilities.
    pub capabilities: ExecutorCapabilities,
}

/// Request to prepare a registered run. Unknown map keys fail closed.
#[derive(Debug, Clone)]
pub struct PrepareRequest {
    /// Must match a registered id.
    pub executor: ExecutorId,
    /// Working directory.
    pub cwd: PathBuf,
    /// Optional test filters (separate argv values, never a shell string).
    pub filters: Vec<String>,
    /// Optional exact normalized case name. Only runners with a frozen,
    /// reviewed case-filter flag accept it.
    pub exact_case: Option<String>,
    /// Extra MCP/user fields. Only empty is accepted.
    pub extra: BTreeMap<String, String>,
    /// Deadline / output caps.
    pub limits: ProcessLimits,
    /// Cooperative cancel flag.
    pub cancel: Arc<AtomicBool>,
}

/// Frozen argv ready to spawn.
#[derive(Debug, Clone)]
pub struct PreparedRun {
    /// Executor that produced this argv.
    pub executor: ExecutorId,
    /// Registered program name.
    pub program: String,
    /// Arguments after the program. Never a user executable.
    pub args: Vec<String>,
    /// Working directory.
    pub cwd: PathBuf,
    /// Limits copied from the request.
    pub limits: ProcessLimits,
    /// Cancel flag.
    pub cancel: Arc<AtomicBool>,
}

/// Outcome of a bounded spawn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExecutionResult {
    /// Process exit code, if it exited.
    pub status_code: Option<i32>,
    /// Capped stdout.
    pub stdout: Vec<u8>,
    /// Capped stderr.
    pub stderr: Vec<u8>,
}

/// Registry of allowed runners.
#[derive(Debug, Clone)]
pub struct ExecutorRegistry {
    specs: BTreeMap<ExecutorId, ExecutorSpec>,
}

impl ExecutorRegistry {
    /// Empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            specs: BTreeMap::new(),
        }
    }

    /// Vitest / Jest / Bun / Go / Playwright, frozen argv prefixes.
    ///
    /// # Errors
    ///
    /// Returns [`RuntimeError::InvalidArg`] if a built-in id is illegal.
    pub fn production() -> Result<Self, RuntimeError> {
        let mut registry = Self::new();
        let npm = if cfg!(windows) { "npm.cmd" } else { "npm" };
        registry.register(spec(
            "cargo-test",
            "cargo",
            &["test", "--color", "never", "--workspace", "--all-targets"],
            None,
        )?)?;
        registry.register(spec("npm-test", npm, &["test", "--"], None)?)?;
        registry.register(spec(
            "vitest",
            npm,
            &[
                "exec",
                "--offline",
                "--yes=false",
                "--",
                "vitest",
                "run",
                "--reporter=junit",
                "--outputFile=.weavatrix-quality/junit.xml",
            ],
            None,
        )?)?;
        registry.register(spec(
            "storybook-vitest",
            npm,
            &[
                "exec",
                "--offline",
                "--yes=false",
                "--",
                "vitest",
                "run",
                "--project=storybook",
                "--reporter=junit",
                "--outputFile=.weavatrix-quality/junit.xml",
            ],
            None,
        )?)?;
        registry.register(spec(
            "storybook-vitest-v8",
            npm,
            &[
                "exec",
                "--offline",
                "--yes=false",
                "--",
                "vitest",
                "run",
                "--project=storybook",
                "--coverage",
                "--coverage.reporter=lcov",
                "--reporter=junit",
                "--outputFile=.weavatrix-quality/junit.xml",
            ],
            None,
        )?)?;
        registry.register(spec(
            "jest",
            "jest",
            &["--runInBand"],
            Some("--runTestsByPath"),
        )?)?;
        registry.register(spec("bun-test", "bun", &["test"], None)?)?;
        registry.register(spec(
            "go-test",
            "go",
            &[
                "test",
                "-json",
                "-coverprofile=.weavatrix-quality/go-cover.out",
                "./...",
            ],
            Some("-run"),
        )?)?;
        registry.register(spec("playwright", "playwright", &["test"], None)?)?;
        Ok(registry)
    }

    /// Add a spec. `program` must be a bare filename.
    ///
    /// # Errors
    ///
    /// Returns [`RuntimeError::InvalidArg`] when `program` looks like a path.
    pub fn register(&mut self, spec: ExecutorSpec) -> Result<(), RuntimeError> {
        validate_program(&spec.program)?;
        self.specs.insert(spec.id.clone(), spec);
        Ok(())
    }

    /// Build argv from typed fields only.
    ///
    /// # Errors
    ///
    /// Unknown executor, extra MCP keys, or unsafe filter.
    pub fn prepare(&self, request: PrepareRequest) -> Result<PreparedRun, RuntimeError> {
        reject_injected_command(&request.extra)?;
        if !request.extra.is_empty() {
            let keys = request.extra.keys().cloned().collect::<Vec<_>>();
            return Err(RuntimeError::InvalidArg(format!(
                "unknown executor fields: {}",
                keys.join(", ")
            )));
        }
        let spec = self
            .specs
            .get(&request.executor)
            .ok_or_else(|| RuntimeError::UnknownExecutor(request.executor.as_str().to_owned()))?;
        let mut args = spec.prefix.clone();
        if !request.filters.is_empty() {
            if let Some(flag) = &spec.filter_flag {
                args.push(flag.clone());
            }
            for filter in &request.filters {
                args.push(sanitize_filter(filter)?);
            }
        }
        if let Some(case) = &request.exact_case {
            let pattern = exact_case_pattern(case)?;
            match spec.id.as_str() {
                "vitest" | "storybook-vitest" | "storybook-vitest-v8" => {
                    args.push("--testNamePattern".into());
                    args.push(pattern);
                }
                "go-test" if request.filters.is_empty() => {
                    args.push("-run".into());
                    args.push(pattern);
                }
                runner => {
                    return Err(RuntimeError::InvalidArg(format!(
                        "executor `{runner}` does not support an exact case filter"
                    )));
                }
            }
        }
        Ok(PreparedRun {
            executor: spec.id.clone(),
            program: spec.program.clone(),
            args,
            cwd: request.cwd,
            limits: request.limits,
            cancel: request.cancel,
        })
    }

    /// Spawn the prepared argv with deadline, output cap, and cancel.
    ///
    /// # Errors
    ///
    /// Spawn, deadline, output limit, or cancel.
    pub fn execute(&self, run: &PreparedRun) -> Result<ExecutionResult, RuntimeError> {
        if run.cancel.load(Ordering::SeqCst) {
            return Err(RuntimeError::Cancelled);
        }
        let raw: RawExecution =
            process::run_bounded(&run.program, &run.args, &run.cwd, &run.limits, &run.cancel)?;
        Ok(ExecutionResult {
            status_code: raw.status_code,
            stdout: raw.stdout,
            stderr: raw.stderr,
        })
    }
}

impl Default for ExecutorRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Trait from spec §15. Implemented by [`ExecutorRegistry`] via prepare/execute.
pub trait Executor {
    /// Declared capabilities of `id`, if registered.
    fn capabilities(&self, id: &ExecutorId) -> Option<ExecutorCapabilities>;
    /// Bind typed args to a frozen argv.
    ///
    /// # Errors
    ///
    /// Unknown id or illegal args.
    fn prepare(&self, request: PrepareRequest) -> Result<PreparedRun, RuntimeError>;
    /// Run a prepared argv.
    ///
    /// # Errors
    ///
    /// Process limit or spawn failure.
    fn execute(&self, run: &PreparedRun) -> Result<ExecutionResult, RuntimeError>;
}

impl Executor for ExecutorRegistry {
    fn capabilities(&self, id: &ExecutorId) -> Option<ExecutorCapabilities> {
        self.specs.get(id).map(|spec| spec.capabilities)
    }

    fn prepare(&self, request: PrepareRequest) -> Result<PreparedRun, RuntimeError> {
        Self::prepare(self, request)
    }

    fn execute(&self, run: &PreparedRun) -> Result<ExecutionResult, RuntimeError> {
        Self::execute(self, run)
    }
}

fn spec(
    id: &str,
    program: &str,
    prefix: &[&str],
    filter_flag: Option<&str>,
) -> Result<ExecutorSpec, RuntimeError> {
    Ok(ExecutorSpec {
        id: ExecutorId::new(id)?,
        program: program.to_owned(),
        prefix: prefix.iter().map(|item| (*item).to_owned()).collect(),
        filter_flag: filter_flag.map(ToOwned::to_owned),
        capabilities: ExecutorCapabilities {
            cases: true,
            coverage: matches!(
                id,
                "vitest" | "storybook-vitest-v8" | "jest" | "bun-test" | "go-test"
            ),
        },
    })
}

fn validate_program(program: &str) -> Result<(), RuntimeError> {
    if program.is_empty()
        || program.contains('/')
        || program.contains('\\')
        || program.contains("..")
    {
        return Err(RuntimeError::InvalidArg(
            "executor program must be a bare filename".into(),
        ));
    }
    Ok(())
}

fn reject_injected_command(extra: &BTreeMap<String, String>) -> Result<(), RuntimeError> {
    const FORBIDDEN: &[&str] = &[
        "command",
        "cmd",
        "shell",
        "argv",
        "executable",
        "program",
        "bin",
        "script",
    ];
    let forbidden = FORBIDDEN.iter().copied().collect::<BTreeSet<_>>();
    for key in extra.keys() {
        if forbidden.contains(key.as_str()) {
            return Err(RuntimeError::InvalidArg(format!(
                "field `{key}` cannot select an executable"
            )));
        }
    }
    Ok(())
}

fn sanitize_filter(filter: &str) -> Result<String, RuntimeError> {
    if filter.is_empty()
        || filter.contains('\0')
        || filter
            .chars()
            .any(|ch| matches!(ch, '\n' | '\r' | '|' | '&' | ';' | '`'))
    {
        return Err(RuntimeError::InvalidArg(
            "filter must be a single argv value without shell metacharacters".into(),
        ));
    }
    Ok(filter.to_owned())
}

fn exact_case_pattern(case: &str) -> Result<String, RuntimeError> {
    if case.is_empty()
        || case.len() > 1024
        || case.contains('\0')
        || case
            .chars()
            .any(|character| matches!(character, '\n' | '\r'))
    {
        return Err(RuntimeError::InvalidArg(
            "exact case must be one non-empty line of at most 1024 bytes".into(),
        ));
    }
    let mut escaped = String::with_capacity(case.len().saturating_add(2));
    escaped.push('^');
    for character in case.chars() {
        if matches!(
            character,
            '.' | '+' | '*' | '?' | '(' | ')' | '|' | '[' | ']' | '{' | '}' | '^' | '$' | '\\'
        ) {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    escaped.push('$');
    Ok(escaped)
}

/// Convenience constructor for tests and callers.
#[must_use]
pub fn default_limits() -> ProcessLimits {
    ProcessLimits {
        deadline: Duration::from_secs(900),
        max_output_bytes: 8 * 1024 * 1024,
    }
}