prview 0.4.0

PR Review & Artifact Generator - cross-language PR analysis tool
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
//! `run_review`: spawn the prview binary to produce a review pack.
//!
//! The MCP layer adds no review logic — it prepares a run directory, spawns
//! `prview` (its own binary) as a subprocess, and reads the resulting pack from
//! storage. quick waits synchronously within a hard 60s budget; deep detaches
//! and is polled later through `verdict`/`state`. A single active run per repo
//! branch is enforced via the `RUNNING.json` liveness marker (R2b).

use crate::mcp::read;
use crate::mcp::types::{ToolError, error_class};
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Review depth requested by the caller.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Profile {
    Quick,
    Deep,
}

impl Profile {
    /// Parse the tool argument; default quick, unknown value is fail-loud.
    pub fn parse(value: Option<&str>) -> Result<Self, ToolError> {
        match value {
            None | Some("quick") => Ok(Profile::Quick),
            Some("deep") => Ok(Profile::Deep),
            Some(other) => Err(ToolError::new(
                error_class::RUN_FAILED,
                format!("unknown profile '{other}'; expected 'quick' or 'deep'"),
            )),
        }
    }

    fn cli_flag(self) -> &'static str {
        match self {
            Profile::Quick => "--quick",
            Profile::Deep => "--deep",
        }
    }

    fn as_str(self) -> &'static str {
        match self {
            Profile::Quick => "quick",
            Profile::Deep => "deep",
        }
    }
}

const QUICK_BUDGET: Duration = Duration::from_secs(60);
const DEFAULT_BASES: &[&str] = &["develop", "main", "master"];

fn short_head(repo: &Path) -> String {
    crate::git::git_cmd()
        .args(["rev-parse", "--short", "HEAD"])
        .current_dir(repo)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_default()
}

/// Allocate a fresh, collision-free run directory under the standard storage
/// layout so a later `verdict(run_id)` scan can find an in-flight deep run.
fn allocate_run_dir(repo_name: &str, branch_key: &str) -> Result<(PathBuf, String), ToolError> {
    let repo_runs_root = crate::config::prview_home().join("runs").join(repo_name);
    let stamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string();
    allocate_run_dir_in(&repo_runs_root, branch_key, &stamp)
}

/// Exclusive, race-free allocation of a run directory (PR #12 review).
///
/// `create_dir` is atomic and fails with `AlreadyExists` when the leaf already
/// exists, unlike `create_dir_all`, which succeeds silently. That closes the
/// TOCTOU window where two concurrent `run_review` calls pick the same
/// timestamp directory and both write into it, corrupting a single pack — the
/// loser now bumps to a fresh suffixed id instead of clobbering the winner.
fn allocate_run_dir_in(
    repo_runs_root: &Path,
    branch_key: &str,
    stamp: &str,
) -> Result<(PathBuf, String), ToolError> {
    let base = repo_runs_root.join(branch_key);
    std::fs::create_dir_all(&base).map_err(|e| {
        ToolError::new(
            error_class::RUN_FAILED,
            format!("failed to create runs dir {}: {e}", base.display()),
        )
    })?;

    let mut suffix = 2u32;
    let mut run_id = stamp.to_string();
    loop {
        // Spec 4a: run_id must be globally unique within the repo storage, not
        // just within a branch (PR #12 review). Reject an id already taken under
        // ANY branch before claiming it, so verdict/read_artifact by explicit
        // run_id never resolve to a same-second run from a different branch.
        if !run_id_taken_in_repo(repo_runs_root, &run_id) {
            let run_dir = base.join(&run_id);
            match std::fs::create_dir(&run_dir) {
                Ok(()) => return Ok((run_dir, run_id)),
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
                Err(e) => {
                    return Err(ToolError::new(
                        error_class::RUN_FAILED,
                        format!("failed to create run dir {}: {e}", run_dir.display()),
                    ));
                }
            }
        }
        run_id = format!("{stamp}-{suffix}");
        suffix += 1;
        if suffix > 10_000 {
            return Err(ToolError::new(
                error_class::RUN_FAILED,
                "exhausted run-id suffixes allocating a run directory".to_string(),
            ));
        }
    }
}

/// True when `run_id` already names a directory under any `runs/<repo>/<branch>`
/// subtree — the repo-global uniqueness probe for `allocate_run_dir_in`.
fn run_id_taken_in_repo(repo_runs_root: &Path, run_id: &str) -> bool {
    let Ok(read) = std::fs::read_dir(repo_runs_root) else {
        return false;
    };
    for branch in read.flatten() {
        let bp = branch.path();
        if bp.is_dir() && bp.join(run_id).exists() {
            return true;
        }
    }
    false
}

/// Detect a currently active run on this repo branch (live RUNNING marker).
fn active_run(repo_name: &str, branch_key: &str) -> Option<String> {
    let base = crate::config::prview_home()
        .join("runs")
        .join(repo_name)
        .join(branch_key);
    let read = std::fs::read_dir(&base).ok()?;
    for entry in read.flatten() {
        let dir = entry.path();
        if dir.is_dir()
            && matches!(read::run_status(&dir), read::RunStatus::Running { .. })
            && let Some(id) = dir.file_name().and_then(|n| n.to_str())
        {
            return Some(id.to_string());
        }
    }
    None
}

fn write_marker(run_dir: &Path, marker: &read::RunningMarker) {
    if let Ok(text) = serde_json::to_string_pretty(marker) {
        let _ = std::fs::write(read::running_marker_path(run_dir), text);
    }
}

fn intended_bases(base: &Option<String>) -> Vec<String> {
    match base {
        Some(b) => vec![b.clone()],
        None => DEFAULT_BASES.iter().map(|s| s.to_string()).collect(),
    }
}

/// Positional args for the child prview: `[branch, base]` when a base is given
/// (base is positional in the CLI, so target must precede it), else none.
fn positional_args(repo: &Path, base: &Option<String>) -> Vec<String> {
    match base {
        Some(b) => {
            let branch =
                crate::config::current_branch_name(repo).unwrap_or_else(|| "HEAD".to_string());
            vec![branch, b.clone()]
        }
        None => Vec::new(),
    }
}

fn stdio_files(run_dir: &Path) -> Result<(File, File), ToolError> {
    let out = File::create(run_dir.join("run.log")).map_err(|e| {
        ToolError::new(
            error_class::RUN_FAILED,
            format!("cannot create run.log: {e}"),
        )
    })?;
    let err = File::create(run_dir.join("run.stderr.log")).map_err(|e| {
        ToolError::new(
            error_class::RUN_FAILED,
            format!("cannot create run.stderr.log: {e}"),
        )
    })?;
    Ok((out, err))
}

fn stderr_tail(run_dir: &Path) -> String {
    let text = std::fs::read_to_string(run_dir.join("run.stderr.log")).unwrap_or_default();
    let tail: Vec<&str> = text.lines().rev().take(20).collect();
    tail.into_iter().rev().collect::<Vec<_>>().join("\n")
}

/// Start a review. Returns the ready success body (without `schema_version`,
/// which the tool layer stamps).
pub async fn start(
    repo: &Path,
    base: Option<String>,
    profile: Profile,
) -> Result<serde_json::Value, ToolError> {
    let repo_name = crate::config::repo_name_from_root(repo);
    let branch_key = crate::config::storage_branch_key(repo);

    // R2b: one active run per repo branch.
    if let Some(active_run_id) = active_run(&repo_name, &branch_key) {
        return Err(ToolError::with_extra(
            error_class::STORAGE_LOCKED,
            "another review is already running for this repo branch",
            serde_json::json!({
                "active_run_id": active_run_id,
                "retry_after_ms": 5000,
            }),
        ));
    }

    let (run_dir, run_id) = allocate_run_dir(&repo_name, &branch_key)?;
    let commit = short_head(repo);
    let (out_file, err_file) = stdio_files(&run_dir)?;

    let mut args: Vec<String> = vec![
        "--output-dir".to_string(),
        run_dir.to_string_lossy().to_string(),
        profile.cli_flag().to_string(),
    ];
    args.extend(positional_args(repo, &base));

    match profile {
        Profile::Quick => {
            let mut cmd = tokio::process::Command::new(std::env::current_exe().map_err(|e| {
                ToolError::new(error_class::RUN_FAILED, format!("current_exe failed: {e}"))
            })?);
            cmd.current_dir(repo)
                .args(&args)
                .stdout(std::process::Stdio::from(out_file))
                .stderr(std::process::Stdio::from(err_file));
            // Shared rails: detached stdin, kill_on_drop, and (unix) own process
            // group so a timeout SIGKILLs the WHOLE tree (prview -> semgrep/cargo
            // grandchildren), not just the wrapper — kill_on_drop/start_kill reap
            // only the direct child (PR #12 review).
            crate::proc::harden(&mut cmd);

            let mut child = cmd.spawn().map_err(|e| {
                ToolError::new(error_class::RUN_FAILED, format!("spawn prview failed: {e}"))
            })?;
            // Capture the pid (also the pgid, since the child leads its group)
            // before the borrow in `child.wait()`; needed to signal the group.
            let child_pid = child.id();

            // Marker with the real child pid: on timeout it is left behind with a
            // now-dead pid, which reads as `stale` — fail-loud, not eternal running.
            write_marker(
                &run_dir,
                &read::RunningMarker {
                    pid: child_pid.unwrap_or(0),
                    started_at: chrono::Local::now().to_rfc3339(),
                    profile: profile.as_str().to_string(),
                    commit: commit.clone(),
                    base_used: intended_bases(&base),
                },
            );

            match tokio::time::timeout(QUICK_BUDGET, child.wait()).await {
                Err(_) => {
                    // Kill the whole group first so the check-tool grandchildren
                    // die, then reap the direct child.
                    #[cfg(unix)]
                    if let Some(pid) = child_pid {
                        crate::proc::sigkill_process_group(pid);
                    }
                    let _ = child.start_kill();
                    Err(ToolError::with_extra(
                        error_class::RUN_TIMEOUT,
                        "quick review exceeded the 60s budget",
                        serde_json::json!({ "run_id": run_id }),
                    ))
                }
                Ok(Err(e)) => Err(ToolError::new(
                    error_class::RUN_FAILED,
                    format!("failed to wait on prview: {e}"),
                )),
                Ok(Ok(_status)) => {
                    // Success is defined by a finalized pack (SANITY.json, the last
                    // guaranteed finalization artifact), NOT the exit code: prview
                    // exits non-zero on a BLOCK verdict yet the run is a valid
                    // completed review.
                    if read::run_status(&run_dir) != read::RunStatus::Completed {
                        return Err(ToolError::with_extra(
                            error_class::RUN_FAILED,
                            "prview produced no completed pack",
                            serde_json::json!({
                                "run_id": run_id,
                                "stderr_tail": stderr_tail(&run_dir),
                            }),
                        ));
                    }
                    // Completed: the child already registered the run; drop the
                    // marker so status readers see a clean completion.
                    let _ = std::fs::remove_file(read::running_marker_path(&run_dir));
                    Ok(completed_body(&run_dir, &run_id, &commit))
                }
            }
        }
        Profile::Deep => {
            let pid = spawn_detached(repo, &args, out_file, err_file)?;
            write_marker(
                &run_dir,
                &read::RunningMarker {
                    pid,
                    started_at: chrono::Local::now().to_rfc3339(),
                    profile: profile.as_str().to_string(),
                    commit: commit.clone(),
                    base_used: intended_bases(&base),
                },
            );
            Ok(serde_json::json!({
                "run_id": run_id,
                "status": "running",
                "commit": commit,
                "base_used": intended_bases(&base),
            }))
        }
    }
}

/// Spawn a fully detached deep run (own process group on unix) and return its
/// pid. The MCP server does not wait on it — the handle is dropped so the child
/// keeps running independently.
fn spawn_detached(
    repo: &Path,
    args: &[String],
    out_file: File,
    err_file: File,
) -> Result<u32, ToolError> {
    let mut cmd = std::process::Command::new(std::env::current_exe().map_err(|e| {
        ToolError::new(error_class::RUN_FAILED, format!("current_exe failed: {e}"))
    })?);
    cmd.current_dir(repo)
        .args(args)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::from(out_file))
        .stderr(std::process::Stdio::from(err_file));

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }

    let child = cmd.spawn().map_err(|e| {
        ToolError::new(
            error_class::RUN_FAILED,
            format!("spawn detached prview failed: {e}"),
        )
    })?;
    Ok(child.id())
}

/// Build the completed-run response body (quick sync path).
fn completed_body(run_dir: &Path, run_id: &str, commit: &str) -> serde_json::Value {
    let decision = read::read_decision(run_dir);
    let (verdict, merge_rec, allow_merge, base_used, blocking, caveats) = match &decision {
        Ok(d) => (
            d.verdict.clone(),
            d.merge_recommendation.clone(),
            d.allow_merge,
            d.base_used.clone(),
            d.blocking_issues.clone(),
            d.caveats.clone(),
        ),
        Err(_) => (
            "UNKNOWN".to_string(),
            "review_required".to_string(),
            false,
            read::read_bases(run_dir),
            Vec::new(),
            Vec::new(),
        ),
    };

    let (checks_passed, checks_failed, files_changed) = run_stats(run_id, run_dir);

    let mut artifact_paths = serde_json::json!({
        "pack": run_dir.to_string_lossy(),
        "merge_gate": "00_summary/MERGE_GATE.json",
    });
    if run_dir
        .join("30_context")
        .join("INLINE_FINDINGS.sarif")
        .exists()
    {
        artifact_paths["sarif"] = serde_json::json!("30_context/INLINE_FINDINGS.sarif");
    }
    // report.json is written at the pack ROOT (the sanity checker also expects
    // it there), not under 00_summary — so advertise the root path or MCP
    // clients cannot discover the machine-readable report (PR #12 review).
    if run_dir.join("report.json").exists() {
        artifact_paths["report"] = serde_json::json!("report.json");
    }

    serde_json::json!({
        "run_id": run_id,
        "status": "completed",
        "commit": commit,
        "base_used": base_used,
        "verdict": verdict,
        "merge_recommendation": merge_rec,
        "allow_merge": allow_merge,
        "blocking_issues": blocking,
        "caveats": caveats,
        "gates": read::read_gates(run_dir),
        "artifact_paths": artifact_paths,
        "stats": {
            "checks_passed": checks_passed,
            "checks_failed": checks_failed,
            "files_changed": files_changed,
        },
    })
}

/// Pull run stats from the freshly-registered index entry (falls back to zeros).
fn run_stats(run_id: &str, run_dir: &Path) -> (usize, usize, usize) {
    let index = crate::storage::RunIndex::load();
    if let Some(e) = index
        .entries()
        .iter()
        .find(|e| e.id == run_id && e.path == run_dir)
    {
        (e.checks_passed, e.checks_failed, e.files_changed)
    } else {
        (0, 0, 0)
    }
}

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

    #[test]
    fn profile_parse_defaults_quick_and_rejects_unknown() {
        assert_eq!(Profile::parse(None).unwrap(), Profile::Quick);
        assert_eq!(Profile::parse(Some("quick")).unwrap(), Profile::Quick);
        assert_eq!(Profile::parse(Some("deep")).unwrap(), Profile::Deep);
        let err = Profile::parse(Some("turbo")).unwrap_err();
        assert_eq!(err.class, error_class::RUN_FAILED);
    }

    #[test]
    fn intended_bases_uses_explicit_then_defaults() {
        assert_eq!(intended_bases(&Some("dev".to_string())), vec!["dev"]);
        assert_eq!(intended_bases(&None), vec!["develop", "main", "master"]);
    }

    /// PR #12 review: two allocations that collide on the same timestamp within
    /// one branch must not share a directory. Exclusive `create_dir` makes the
    /// second caller take a distinct suffixed id instead of clobbering the pack.
    #[test]
    fn allocate_run_dir_is_exclusive_within_branch() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let stamp = "20260701-120000";
        let (dir1, id1) = allocate_run_dir_in(root, "main", stamp).unwrap();
        let (dir2, id2) = allocate_run_dir_in(root, "main", stamp).unwrap();
        assert_eq!(id1, stamp);
        assert_eq!(id2, "20260701-120000-2");
        assert_ne!(dir1, dir2);
        assert!(dir1.is_dir() && dir2.is_dir());
    }

    /// PR #12 review (spec 4a): a run_id is unique across the whole repo, not
    /// per branch. An id already used on another branch forces a suffix so an
    /// explicit-id lookup never collides between branches.
    #[test]
    fn allocate_run_dir_is_globally_unique_across_branches() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let stamp = "20260701-120000";
        let (existing, existing_id) = allocate_run_dir_in(root, "feature", stamp).unwrap();
        let (fresh, fresh_id) = allocate_run_dir_in(root, "main", stamp).unwrap();
        assert_eq!(existing_id, stamp);
        assert_eq!(fresh_id, "20260701-120000-2");
        assert_ne!(existing_id, fresh_id);
        assert!(existing.is_dir() && fresh.is_dir());
    }

    /// PR #12 review: a completed pack writes report.json at the pack root, so
    /// the run_review response must advertise `report.json`, not the (never
    /// present) `00_summary/report.json`, or clients cannot find the report.
    #[test]
    fn completed_body_advertises_root_report_json() {
        let tmp = tempfile::tempdir().unwrap();
        let run_dir = tmp.path();
        let summary = run_dir.join("00_summary");
        std::fs::create_dir_all(&summary).unwrap();
        std::fs::write(
            summary.join("MERGE_GATE.json"),
            serde_json::to_string(&serde_json::json!({
                "bases": ["main"],
                "decision": {
                    "merge_recommendation": "approve",
                    "verdict": "APPROVE",
                    "allow_merge": true
                }
            }))
            .unwrap(),
        )
        .unwrap();
        // Root-level report.json — where the pack actually writes it.
        std::fs::write(run_dir.join("report.json"), "{}").unwrap();

        let body = completed_body(run_dir, "20260701-120000", "abc1234");
        assert_eq!(
            body["artifact_paths"]["report"],
            serde_json::json!("report.json")
        );
    }

    // The quick-timeout process-group kill uses crate::proc::sigkill_process_group,
    // proven canonically in crate::proc::tests (grandchild reap).
}