metsuke 0.1.1

metsuke 目付 — the typed review surface of a code forge: read what awaits your judgment (pull requests, diffs, review threads) and record the verdict. Mockable Forge/ForgeReview seams over a `gh` backend; no merge, no close, no push.
Documentation
//! The seam: what a forge can be asked, and a mock that answers.
//!
//! Split OBSERVE from RECORD deliberately, the way `banken_spec::env` splits
//! reads from the postigo write verbs. A surface that only ever reads takes
//! `&impl Forge` and gains no way to submit a verdict — not by convention,
//! but because the method is not on the trait it holds.

use crate::types::{
    FilePatch, Involvement, PrNumber, PrSummary, RepoId, Result, ReviewComment, Verdict,
};

/// Reading a code forge. Every method here is side-effect free.
pub trait Forge {
    /// Pull requests matching an involvement lane, newest first.
    ///
    /// `limit` is a ceiling, not a promise: a forge may return fewer.
    ///
    /// # Errors
    /// Any [`crate::ForgeError`]; see its variants for what a caller can do.
    fn search(&self, lane: Involvement, limit: usize) -> Result<Vec<PrSummary>>;

    /// One pull request in detail.
    ///
    /// # Errors
    /// [`crate::ForgeError::Backend`] when the PR does not exist or is not
    /// visible to the current credential — those are the same answer from the
    /// forge and this crate does not pretend to tell them apart.
    fn pull_request(&self, repo: &RepoId, number: PrNumber) -> Result<PrSummary>;

    /// The changed files, with their unified-diff text.
    ///
    /// # Errors
    /// Any [`crate::ForgeError`].
    fn files(&self, repo: &RepoId, number: PrNumber) -> Result<Vec<FilePatch>>;

    /// The review conversation, oldest first.
    ///
    /// # Errors
    /// Any [`crate::ForgeError`].
    fn comments(&self, repo: &RepoId, number: PrNumber) -> Result<Vec<ReviewComment>>;
}

/// Recording a verdict — the whole write surface, and it is one method.
///
/// A separate trait so a read-only consumer cannot reach it. Note what is
/// absent and stays absent: there is no `merge`, no `close`, no `push`. A
/// reviewer reviews. Merging is a decision made elsewhere, and the way to
/// keep this crate from growing into a general forge-mutation API is to give
/// it no place to put one.
pub trait ForgeReview {
    /// Submit a review.
    ///
    /// [`Verdict::is_binding`] says whether this changes the PR's
    /// mergeability; a UI is expected to confirm before submitting one that
    /// does. This crate does not confirm on the caller's behalf — a library
    /// that silently declines to do what it was asked is worse than one that
    /// does it.
    ///
    /// # Errors
    /// Any [`crate::ForgeError`].
    fn submit_review(&self, repo: &RepoId, number: PrNumber, verdict: &Verdict) -> Result<()>;
}

/// A scripted forge for tests: canned reads, recorded writes.
///
/// Interior mutability via `RefCell` (so it is not `Sync`) because a
/// recording double is single-threaded on purpose — the recording only means
/// anything if the test can read it back on the same thread that ran it.
#[derive(Debug, Default)]
pub struct MockForge {
    prs: Vec<PrSummary>,
    files: Vec<(PrNumber, FilePatch)>,
    comments: Vec<(PrNumber, ReviewComment)>,
    /// Every verdict submitted, in order. Public so a test asserts on what
    /// the seam was actually *called with* — "the app reported success" and
    /// "the review was submitted" are different claims, and only the second
    /// one is evidence.
    pub submitted: std::cell::RefCell<Vec<(RepoId, PrNumber, Verdict)>>,
    /// When set, every read fails with this. For exercising the error paths a
    /// happy-path mock can never reach.
    fail_reads_with: Option<crate::ForgeError>,
}

impl MockForge {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn with_pr(mut self, pr: PrSummary) -> Self {
        self.prs.push(pr);
        self
    }

    #[must_use]
    pub fn with_file(mut self, number: PrNumber, patch: FilePatch) -> Self {
        self.files.push((number, patch));
        self
    }

    #[must_use]
    pub fn with_comment(mut self, number: PrNumber, c: ReviewComment) -> Self {
        self.comments.push((number, c));
        self
    }

    /// Make every read fail, so a caller's error handling is exercised rather
    /// than assumed.
    #[must_use]
    pub fn failing(mut self, e: crate::ForgeError) -> Self {
        self.fail_reads_with = Some(e);
        self
    }

    /// How many verdicts have been submitted.
    #[must_use]
    pub fn submitted_count(&self) -> usize {
        self.submitted.borrow().len()
    }

    fn guard(&self) -> Result<()> {
        match &self.fail_reads_with {
            Some(e) => Err(e.clone()),
            None => Ok(()),
        }
    }
}

impl Forge for MockForge {
    fn search(&self, _lane: Involvement, limit: usize) -> Result<Vec<PrSummary>> {
        self.guard()?;
        Ok(self.prs.iter().take(limit).cloned().collect())
    }

    fn pull_request(&self, repo: &RepoId, number: PrNumber) -> Result<PrSummary> {
        self.guard()?;
        self.prs
            .iter()
            .find(|p| p.repo == *repo && p.number == number)
            .cloned()
            .ok_or_else(|| crate::ForgeError::Backend {
                operation: "pull_request",
                detail: format_missing(repo, number),
            })
    }

    fn files(&self, _repo: &RepoId, number: PrNumber) -> Result<Vec<FilePatch>> {
        self.guard()?;
        Ok(self
            .files
            .iter()
            .filter(|(n, _)| *n == number)
            .map(|(_, f)| f.clone())
            .collect())
    }

    fn comments(&self, _repo: &RepoId, number: PrNumber) -> Result<Vec<ReviewComment>> {
        self.guard()?;
        Ok(self
            .comments
            .iter()
            .filter(|(n, _)| *n == number)
            .map(|(_, c)| c.clone())
            .collect())
    }
}

impl ForgeReview for MockForge {
    fn submit_review(&self, repo: &RepoId, number: PrNumber, verdict: &Verdict) -> Result<()> {
        self.submitted
            .borrow_mut()
            .push((repo.clone(), number, verdict.clone()));
        Ok(())
    }
}

/// Built without `format!()` (★★ TYPED EMISSION): the crate emits no strings
/// through format machinery, and an error detail is no exception.
fn format_missing(repo: &RepoId, number: PrNumber) -> String {
    let mut s = String::from("no such pull request: ");
    s.push_str(&repo.owner);
    s.push('/');
    s.push_str(&repo.name);
    s.push('#');
    s.push_str(&number.0.to_string());
    s
}

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

    fn pr(n: u64) -> PrSummary {
        PrSummary {
            repo: RepoId::parse("pleme-io/metsuke").unwrap(),
            number: PrNumber(n),
            title: "a change".into(),
            author: "drzzln".into(),
            state: PrState::Open,
            draft: false,
            updated_at: "2026-08-03T00:00:00Z".into(),
            url: "https://example.invalid".into(),
        }
    }

    #[test]
    fn the_mock_returns_what_it_was_seeded_with() {
        let f = MockForge::new().with_pr(pr(1)).with_pr(pr(2));
        assert_eq!(f.search(Involvement::ReviewRequested, 10).unwrap().len(), 2);
        assert_eq!(f.search(Involvement::ReviewRequested, 1).unwrap().len(), 1);
    }

    #[test]
    fn a_missing_pr_is_an_error_not_an_empty_default() {
        let f = MockForge::new();
        let repo = RepoId::parse("pleme-io/metsuke").unwrap();
        let e = f.pull_request(&repo, PrNumber(9)).unwrap_err();
        assert!(
            e.to_string().contains("pleme-io/metsuke#9"),
            "the error must name what was missing; got: {e}"
        );
    }

    #[test]
    fn submitting_records_the_exact_verdict() {
        let f = MockForge::new();
        let repo = RepoId::parse("pleme-io/metsuke").unwrap();
        f.submit_review(&repo, PrNumber(3), &Verdict::Approve("lgtm".into()))
            .unwrap();
        let got = f.submitted.borrow();
        assert_eq!(got.len(), 1);
        assert_eq!(got[0].1, PrNumber(3));
        assert_eq!(got[0].2, Verdict::Approve("lgtm".into()));
    }

    #[test]
    fn a_failing_mock_fails_reads_and_the_error_survives() {
        let f = MockForge::new()
            .with_pr(pr(1))
            .failing(crate::ForgeError::NotAuthenticated {
                detail: "gh auth login".into(),
            });
        let e = f.search(Involvement::Authored, 10).unwrap_err();
        assert!(matches!(e, crate::ForgeError::NotAuthenticated { .. }));
    }
}