Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Dev mode: review only fresh branches and PRs (0.7.7) (#447)

Oleksandr Ivanchenkoa2ca9b76bb7b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index de146685..809a4a2f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
+### Changed
+- **Dev mode reviews only fresh work.** A branch or PR gets a review card only if it moved in the last 7 days, so old branches no longer fill the desk or spend model calls. Cards on branches that went quiet go stale, and a new push brings a branch back. The newest branches are reviewed first, and Dev mode's status says how many old ones it skipped. A card that couldn't read a big file now says "Couldn't read N files (too large to diff)" instead of "(no diff from GitHub)".
+
### Fixed
- **A checkpoint's git commit only comes from the task's own git files.** When a mission takes a checkpoint, kwant notes the commit the task's folder is on. It now never follows a symlink inside `.git`, ignores a `ref:` that points outside it, skips FIFOs and oversized files, and keeps the value only when it's a real 40- or 64-character commit id. Before, a bot that could write its task folder could make a checkpoint show the first 64 characters of another file kwant can read. (#443)
- **Dev mode reads the checked-out branch safely too.** The production safeguard reads which branch a bot's folder is on. A planted FIFO could stall that check, and a symlink, a hard link or a `.git` file could point it at another file. It now reads `.git` the same careful way checkpoints do, and only follows a worktree's pointer into a real `.git/worktrees/` folder. Checkpoints also now skip a hard-linked git file. (#444)
diff --git a/docs/dev-mode.md b/docs/dev-mode.md
index 5711e118..40541ef1 100644
--- a/docs/dev-mode.md
+++ b/docs/dev-mode.md
@@ -298,6 +298,22 @@ deleted goes stale. A branch level with or behind the watched one gets none. At
are read (sorted), and 10 branches per poll; a mirror reads them with `git ls-remote`
and fetches a branch only to diff it, then drops the ref. A team folder is read in place.
+### Only fresh branches and PRs are reviewed (0.7.7)
+
+A review card is made only for a branch or PR that moved in the last 7 days
+(`poller::REVIEW_FRESH_DAYS`). For a branch, that's the head commit's committer date; for a forge PR,
+it's the PR's `updated_at`, or the head commit's date when the forge gives none. A ref whose date
+can't be read counts as fresh. An old branch or PR gets no card and no model call, and a card already
+on it goes stale the same way a merged branch's does. A new push makes the branch fresh again, so it
+gets a new card. Candidates are taken newest first, before the cap of 10 per poll, so a fresh branch
+is never pushed out by old ones. A mirror still reads branch heads with `git ls-remote`; when a head's
+date isn't already in the mirror, kwant fetches that one branch once to read it, then drops the ref.
+That's the same fetch the review would make, so a poll never fetches more than before.
+
+`GET /api/spaces/:id/dev_mode` shows the rule: each `repos[]` entry and the top level have `fresh_days` (the
+window in days) and `old_reviews_skipped` (how many branches or PRs the last poll left out for being
+old). The count is kept in memory and resets when kwnt restarts.
+
## Reading GitHub
Reads go through the GitHub connection only. kwnt never pushes, merges, approves or edits anything
@@ -532,7 +548,8 @@ prompts, other files under the data folder).
Test seams, for the test server only: `KWANT_DEV_POLL_SECS` (5–86400, default 300) and
`KWANT_DEV_CALL_CAP` (0–1000, default 30) and `KWANT_DEV_MIRROR_CAP_BYTES` (1 B to 1 TB, default
-1 GB, so QA can make a small repo too big), read once at the first use. The daily cap counts per UTC
+1 GB, so QA can make a small repo too big) and `KWANT_DEV_REVIEW_DAYS` (1–90, default 7; anything
+else is 7), read once at the first use. The daily cap counts per UTC
day. Tests move Dev mode's clock in-process with `server::dev::set_clock_skew`
(`tests/dev_seams_test.rs`). There are table tests for each
floor kind in `src/mcp/prod_floor.rs`. The backup checks and the Allow refusal are tested in
diff --git a/src/server/dev/git.rs b/src/server/dev/git.rs
index 6b7599cd..04d75491 100644
--- a/src/server/dev/git.rs
+++ b/src/server/dev/git.rs
@@ -1158,6 +1158,30 @@ impl Repo {
Ok(heads)
}
+ /// The committer dates of those of `shas` this repo has, by sha, in one `git log --no-walk`.
+ /// A sha it doesn't have (a mirror that never fetched it) is left out, as is one whose date
+ /// doesn't read; a name that isn't a sha is refused.
+ pub async fn commit_dates(&self, shas: &[&str]) -> Result<std::collections::HashMap<String, DateTime<Utc>>, GitError> {
+ if shas.iter().any(|s| !is_sha(s)) {
+ return Err(GitError::Refused);
+ }
+ let mut dates = std::collections::HashMap::new();
+ for chunk in shas.chunks(MAX_HEADS) {
+ let mut args = vec!["log", "--no-walk=unsorted", "--ignore-missing", "--format=%H %ct", "--end-of-options"];
+ args.extend_from_slice(chunk);
+ args.push("--");
+ let out = self.text(&args).await?;
+ for line in out.lines() {
+ let Some((sha, at)) = line.trim().split_once(' ') else { continue };
+ let Some(at) = at.parse::<i64>().ok().and_then(|t| DateTime::from_timestamp(t, 0)) else { continue };
+ if is_sha(sha) {
+ dates.insert(sha.to_string(), at);
+ }
+ }
+ }
+ Ok(dates)
+ }
+
/// Whether `a` is `b` or an ancestor of it.
pub async fn is_ancestor(&self, a: &str, b: &str) -> Result<bool, GitError> {
if !(is_sha(a) || ok_ref(a)) || !(is_sha(b) || ok_ref(b)) {
@@ -1569,6 +1593,26 @@ mod tests {
(w, vec![c0, c1, f1, m, c3])
}
+ /// 0.7.7 fresh reviews: every head git has gets its committer date in one call; a head it
+ /// doesn't have (a mirror that never fetched it) is left out, not an error.
+ #[tokio::test]
+ async fn commit_dates_read_what_git_has_and_leave_out_the_rest() {
+ let tmp = tempfile::tempdir().unwrap();
+ let (w, c) = upstream(tmp.path());
+ let repo = Repo::local(&w, &tmp.path().join("data")).await.unwrap();
+ let missing = "e".repeat(40);
+ let dates = repo.commit_dates(&[c[0].as_str(), missing.as_str(), c[2].as_str()]).await.unwrap();
+ assert_eq!(dates.len(), 2, "{dates:?}");
+ for sha in [&c[0], &c[2]] {
+ let want: i64 = sh(&w, &["log", "-1", "--format=%ct", sha]).parse().unwrap();
+ assert_eq!(dates[sha.as_str()].timestamp(), want);
+ }
+ assert!(repo.commit_dates(&[]).await.unwrap().is_empty());
+ // Only shas reach git
+ assert_eq!(repo.commit_dates(&["main"]).await, Err(GitError::Refused));
+ assert_eq!(repo.commit_dates(&["--all"]).await, Err(GitError::Refused));
+ }
+
#[tokio::test]
async fn a_mirror_reads_first_parent_history_files_tags_and_text() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/src/server/dev/mod.rs b/src/server/dev/mod.rs
index a72cebfd..a89fab78 100644
--- a/src/server/dev/mod.rs
+++ b/src/server/dev/mod.rs
@@ -66,6 +66,25 @@ pub fn call_cap() -> i64 {
*CAP.get_or_init(|| env_num("KWANT_DEV_CALL_CAP", 0, 1000).map_or(CALLS_CAP, |v| v as i64))
}
+/// How many days a pushed branch or open PR counts as fresh, so it gets a review card:
+/// `KWANT_DEV_REVIEW_DAYS` (1–90), else [`poller::REVIEW_FRESH_DAYS`] (7).
+pub fn review_days() -> u32 {
+ static DAYS: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
+ *DAYS.get_or_init(|| {
+ let raw = std::env::var("KWANT_DEV_REVIEW_DAYS").ok();
+ let days = review_days_from(raw.as_deref());
+ if raw.is_some() {
+ tracing::info!("dev: KWANT_DEV_REVIEW_DAYS read as {days} (whole days from 1 to 90; anything else is {})", poller::REVIEW_FRESH_DAYS);
+ }
+ days
+ })
+}
+
+/// [`review_days`] from the variable's text: a whole number from 1 to 90, else the default.
+pub fn review_days_from(raw: Option<&str>) -> u32 {
+ raw.and_then(|r| r.trim().parse::<u32>().ok()).filter(|d| (1..=90).contains(d)).unwrap_or(poller::REVIEW_FRESH_DAYS)
+}
+
/// The most disk one repo's git mirror may use: `KWANT_DEV_MIRROR_CAP_BYTES` (1 B–1 TB, so a test
/// can use a tiny cap), else [`git::MIRROR_CAP`] (1 GB).
pub fn mirror_cap() -> u64 {
@@ -152,9 +171,23 @@ mod tests {
// CI sets neither variable
assert_eq!(poll_every(), std::time::Duration::from_secs(300));
assert_eq!(call_cap(), 30);
+ assert_eq!(review_days(), 7);
assert!((now() - Utc::now()).num_seconds().abs() <= 1);
}
+ #[test]
+ fn the_review_days_variable_is_held_to_1_to_90() {
+ assert_eq!(review_days_from(None), 7);
+ for (raw, days) in [("1", 1), ("14", 14), (" 30 ", 30), ("90", 90)] {
+ assert_eq!(review_days_from(Some(raw)), days, "{raw:?}");
+ }
+ // Out of range or not a whole number of days: the default, never 0 (which would skip
+ // every review) and never more than 90
+ for raw in ["0", "91", "365", "-3", "7.5", "", "seven", "4294967296"] {
+ assert_eq!(review_days_from(Some(raw)), 7, "{raw:?}");
+ }
+ }
+
#[tokio::test]
async fn the_daily_cap_resets_at_midnight_utc() {
let tmp = tempfile::tempdir().unwrap();
diff --git a/src/server/dev/poller.rs b/src/server/dev/poller.rs
index bf789419..66e85e94 100644
--- a/src/server/dev/poller.rs
+++ b/src/server/dev/poller.rs
@@ -30,6 +30,10 @@ pub const BACKFILL: usize = 5;
pub const MAX_NEW: usize = 20;
/// Most new review heads one poll reads (each costs a few requests).
pub const MAX_REVIEWS: usize = 10;
+/// Pushed branches and open PRs get a review card only while their last commit (a PR's last
+/// update) is at most this many days old, unless `KWANT_DEV_REVIEW_DAYS` says otherwise
+/// ([`super::review_days`]). Older work gets no card and no model call; a new push makes it fresh.
+pub const REVIEW_FRESH_DAYS: u32 = 7;
/// Files whose history is read for `first_edit_files`.
pub const FIRST_EDIT_FILES: usize = 20;
/// "First edit" means no commit to the file in this many days.
@@ -47,6 +51,9 @@ struct Shared {
resume_at: HashMap<String, DateTime<Utc>>,
/// The newest tag of each watched repo (by [`tag_key`]), and when its commit was made.
tags: HashMap<String, (String, Option<DateTime<Utc>>)>,
+ /// Branches or PRs of each watched repo (by [`tag_key`]) the last poll gave no review card
+ /// because they weren't fresh ([`is_fresh`]). In memory only: 0 after a restart until a poll.
+ old_skipped: HashMap<String, u32>,
}
fn shared() -> &'static Mutex<Shared> {
@@ -95,6 +102,21 @@ pub fn last_tag_at(space_id: &str, repo_key: &str) -> Option<DateTime<Utc>> {
shared().lock().unwrap().tags.get(&tag_key(space_id, repo_key)).and_then(|(_, at)| *at)
}
+/// How many branches or PRs of one watched repo the last poll skipped as too old for a review.
+pub fn old_reviews_skipped(space_id: &str, repo_key: &str) -> u32 {
+ shared().lock().unwrap().old_skipped.get(&tag_key(space_id, repo_key)).copied().unwrap_or(0)
+}
+
+fn set_old_skipped(space_id: &str, repo_key: &str, n: u32) {
+ shared().lock().unwrap().old_skipped.insert(tag_key(space_id, repo_key), n);
+}
+
+/// Whether work last touched at `at` is fresh enough for a review card: within `days` of `now`.
+/// An unknown date is fresh, so real work is never dropped because git or the forge didn't say.
+pub fn is_fresh(at: Option<DateTime<Utc>>, now: DateTime<Utc>, days: u32) -> bool {
+ at.is_none_or(|t| t >= now - Duration::days(i64::from(days)))
+}
+
/// Starts the poller, after picking up what a restart left: pending cards go to `generate`
/// again, and a Fix it whose task never went out is sent.
pub fn spawn(state: AppState, shutdown: CancellationToken) {
@@ -383,17 +405,33 @@ async fn landed(state: &AppState, h: &History<'_>, forge: Option<&dyn Forge>, mo
Ok(true)
}
+/// Review cards for the open PRs: each fresh, non-draft PR gets one per head (see [`is_fresh`]:
+/// its last update, else its head commit's date), newest first, at most [`MAX_REVIEWS`] read per
+/// poll. A PR that isn't fresh gets no card and no model call, and its old card goes stale; a new
+/// push updates it, so it's fresh again.
async fn reviews(state: &AppState, h: &History<'_>, forge: &dyn Forge, mode: &DevRepoRow, kwants: &[Kwant], pulls: &[Change]) -> Result<(), GhError> {
let mut open = HashSet::new();
let mut read = 0;
- for p in pulls {
+ let mut old = 0;
+ let (now, days) = (Utc::now(), super::review_days());
+ let undated: Vec<&str> = pulls.iter().filter(|p| p.updated_at.is_none() && !p.draft).map(|p| p.head_sha.as_str()).filter(|s| git::is_sha(s)).collect();
+ let dates = h.commit_dates(&undated).await;
+ let mut pulls: Vec<(&Change, Option<DateTime<Utc>>)> = pulls.iter().map(|p| (p, p.updated_at.or_else(|| dates.get(&p.head_sha).copied()))).collect();
+ newest_first(&mut pulls);
+ for (p, at) in pulls {
let ref_ = format!("pr:{}", p.number);
- open.insert(ref_.clone());
if p.draft {
// Drafts are skipped (D8); a PR that went back to draft loses its card
+ open.insert(ref_.clone());
stale(state, mode, &ref_, None).await;
continue;
}
+ if !is_fresh(at, now, days) {
+ // Not touched in `days`: no card, and its old one goes stale below
+ old += 1;
+ continue;
+ }
+ open.insert(ref_.clone());
let have = state.db.dev_cards_of_ref_in(&mode.space_id, &mode.key, REVIEW, &ref_).await.unwrap_or_default();
if have.iter().any(|c| c.head_sha == p.head_sha) {
stale(state, mode, &ref_, Some(&p.head_sha)).await;
@@ -421,32 +459,61 @@ async fn reviews(state: &AppState, h: &History<'_>, forge: &dyn Forge, mode: &De
insert(state, mode, REVIEW, &ref_, &p.head_sha, &facts).await;
stale(state, mode, &ref_, Some(&p.head_sha)).await;
}
- // A PR of this repo that closed or merged: its review cards go stale
+ // A PR of this repo that closed, merged or went quiet: its review cards go stale
if let Ok(cards) = state.db.dev_cards_in(&mode.space_id, Some(&mode.key), REVIEW, None, 200).await {
let gone: HashSet<String> = cards.into_iter().filter(|c| c.status != STALE && !open.contains(&c.ref_)).map(|c| c.ref_).collect();
for r in gone {
stale(state, mode, &r, None).await;
}
}
+ set_old_skipped(&mode.space_id, &mode.key, old);
Ok(())
}
+/// Sorts candidates for review newest first; an unknown date counts as newest (it's fresh, and on
+/// a mirror it's a head kwant hasn't fetched yet: a new push). Ties keep their order.
+fn newest_first<T>(list: &mut [(T, Option<DateTime<Utc>>)]) {
+ list.sort_by_key(|(_, at)| std::cmp::Reverse(at.unwrap_or(DateTime::<Utc>::MAX_UTC)));
+}
+
/// Review cards for pushed branches when the repo has no forge, or no token for it (any-git.md
-/// G5): each branch other than the watched one with commits the watched branch doesn't have gets a
-/// card (ref `branch:<name>`), compared against the watched branch, with no PR, no CI and no Post
-/// (`no_forge`). A branch whose head already has a card keeps it; a new push makes a new card and
-/// the old one goes stale, as a PR's does. A branch that merged or was deleted goes stale. At most
-/// [`MAX_REVIEWS`] are read per poll; the rest wait for the next.
+/// G5): each fresh branch other than the watched one with commits the watched branch doesn't have
+/// gets a card (ref `branch:<name>`), compared against the watched branch, with no PR, no CI and no
+/// Post (`no_forge`). A branch whose head already has a card keeps it; a new push makes a new card
+/// and the old one goes stale, as a PR's does. A branch that merged or was deleted goes stale.
+///
+/// Fresh means its head commit's committer date is at most [`super::review_days`] old
+/// ([`is_fresh`]); an older branch gets no card and no model call, and its old card goes stale. A
+/// new push makes it fresh again. Branches are read newest first, at most [`MAX_REVIEWS`] per poll;
+/// the rest wait for the next. A team folder has every date; a mirror has the dates of heads it
+/// fetched before, and fetches a new head once to learn its date. That fetch is the one
+/// [`History::branch_files`] made before, and counts toward [`MAX_REVIEWS`] the same way, so a
+/// poll never fetches more than it did, and an old branch costs one fetch and never a model call.
pub async fn branches(state: &AppState, mode: &DevRepoRow, h: &History<'_>) -> Result<(), GhError> {
let space = SpaceId::new(&mode.space_id);
let kwants = state.db.list_kwants(&space).await.unwrap_or_default();
let heads = h.branches().await?;
+ let mut ahead = Vec::new();
+ for (name, sha) in heads.iter().filter(|(n, _)| *n != mode.branch) {
+ // Merged (or level with the watched branch): no card, and its old one goes stale below
+ if !h.in_branch(sha, &mode.branch).await {
+ ahead.push((name, sha));
+ }
+ }
+ let shas: Vec<&str> = ahead.iter().map(|(_, s)| s.as_str()).collect();
+ let dates = h.commit_dates(&shas).await;
+ let mirror = h.fetches_branches();
+ let mut ahead: Vec<_> = ahead.into_iter().map(|b| (b, dates.get(b.1.as_str()).copied())).collect();
+ newest_first(&mut ahead);
+ let (now, days) = (Utc::now(), super::review_days());
let mut open = HashSet::new();
let mut read = 0;
- for (name, sha) in heads.iter().filter(|(n, _)| *n != mode.branch) {
+ let mut old = 0;
+ for ((name, sha), at) in ahead {
let ref_ = format!("branch:{name}");
- // Merged (or level with the watched branch): no card, and its old one goes stale below
- if h.in_branch(sha, &mode.branch).await {
+ if !is_fresh(at, now, days) {
+ // No new commit in `days`: no card, and its old one goes stale below
+ old += 1;
continue;
}
let have = state.db.dev_cards_of_ref_in(&mode.space_id, &mode.key, REVIEW, &ref_).await.unwrap_or_default();
@@ -461,6 +528,17 @@ pub async fn branches(state: &AppState, mode: &DevRepoRow, h: &History<'_>) -> R
continue;
}
read += 1;
+ if mirror && at.is_none() {
+ // A head the mirror hasn't fetched: fetch it once for its date (and its files)
+ match h.fetch_branch_date(name, sha).await {
+ None => continue,
+ Some(t) if !is_fresh(Some(t), now, days) => {
+ old += 1;
+ continue;
+ }
+ Some(_) => {}
+ }
+ }
let Some(mut files) = h.branch_files(name, sha, &mode.branch).await else { continue };
if files.is_empty() {
continue;
@@ -480,13 +558,14 @@ pub async fn branches(state: &AppState, mode: &DevRepoRow, h: &History<'_>) -> R
insert(state, mode, REVIEW, &ref_, sha, &facts).await;
stale(state, mode, &ref_, Some(sha)).await;
}
- // A branch that merged, was deleted or has nothing new any more: its cards go stale
+ // A branch that merged, was deleted, went quiet or has nothing new any more: its cards go stale
if let Ok(cards) = state.db.dev_cards_in(&mode.space_id, Some(&mode.key), REVIEW, None, 200).await {
let gone: HashSet<String> = cards.into_iter().filter(|c| c.status != STALE && !open.contains(&c.ref_)).map(|c| c.ref_).collect();
for r in gone {
stale(state, mode, &r, None).await;
}
}
+ set_old_skipped(&mode.space_id, &mode.key, old);
Ok(())
}
@@ -716,6 +795,36 @@ mod tests {
.unwrap()
}
+ #[test]
+ fn fresh_means_within_the_window_and_an_unknown_date_is_fresh() {
+ let now = Utc::now();
+ assert!(is_fresh(None, now, 7), "unknown: fresh, never silently dropped");
+ assert!(is_fresh(Some(now - Duration::days(7)), now, 7));
+ assert!(!is_fresh(Some(now - Duration::days(7) - Duration::seconds(1)), now, 7));
+ assert!(!is_fresh(Some(now - Duration::days(30)), now, 7));
+ assert!(is_fresh(Some(now + Duration::hours(1)), now, 7), "a clock ahead of ours");
+ assert!(is_fresh(Some(now - Duration::days(30)), now, 30));
+ }
+
+ #[test]
+ fn candidates_go_newest_first_with_unknown_dates_first() {
+ let now = Utc::now();
+ let mut list = vec![("a", Some(now - Duration::days(3))), ("b", None), ("c", Some(now)), ("d", Some(now - Duration::days(9))), ("e", None)];
+ newest_first(&mut list);
+ assert_eq!(list.iter().map(|(n, _)| *n).collect::<Vec<_>>(), ["b", "e", "c", "a", "d"]);
+ }
+
+ #[test]
+ fn the_skipped_count_is_per_repo_and_set_by_each_poll() {
+ assert_eq!(old_reviews_skipped("skip-space", "a"), 0, "0 until a poll");
+ set_old_skipped("skip-space", "a", 24);
+ set_old_skipped("skip-space", "b", 1);
+ assert_eq!((old_reviews_skipped("skip-space", "a"), old_reviews_skipped("skip-space", "b")), (24, 1));
+ set_old_skipped("skip-space", "a", 0);
+ assert_eq!(old_reviews_skipped("skip-space", "a"), 0);
+ assert_eq!(old_reviews_skipped("other-space", "b"), 0);
+ }
+
/// Built from GitHub's JSON, so the conversion is under test too.
fn pull(n: u64, merge: Option<&str>, merged: bool, base: &str) -> Change {
serde_json::from_value::<crate::zombie::github::GhPull>(json!({
diff --git a/src/server/dev/review.rs b/src/server/dev/review.rs
index fa7b6ff6..92a5cb1a 100644
--- a/src/server/dev/review.rs
+++ b/src/server/dev/review.rs
@@ -701,7 +701,7 @@ mod tests {
f.files.push(FileDiff { path: "tests/big_test.rs".into(), status: "modified".into(), additions: 0, deletions: 300, patch: None, previous_path: None });
let (_, c) = card::<Stub>(&f, None, None).await;
assert_eq!(c["tamper"]["unread"], json!(["tests/big_test.rs"]));
- assert!(c["risk"]["reasons"].as_array().unwrap().contains(&json!("Couldn't read 1 file (no diff from GitHub)")), "{}", c["risk"]);
+ assert!(c["risk"]["reasons"].as_array().unwrap().contains(&json!("Couldn't read 1 file (too large to diff)")), "{}", c["risk"]);
assert_ne!(c["risk"]["level"], "low");
}
diff --git a/src/server/dev/risk.rs b/src/server/dev/risk.rs
index e9d9d573..c8cbca2e 100644
--- a/src/server/dev/risk.rs
+++ b/src/server/dev/risk.rs
@@ -147,15 +147,16 @@ pub fn assess(i: &Inputs) -> Risk {
Risk { level, reasons }
}
-/// Files with changed lines but no patch from GitHub (too large to diff). Binary files (no lines)
-/// aren't counted: there's no text to read.
+/// Files with changed lines but no patch (too large to diff, from git or the forge alike). Binary
+/// files (no lines) aren't counted: there's no text to read.
pub fn unread_files(files: &[FileDiff]) -> Vec<&str> {
files.iter().filter(|f| f.patch.is_none() && f.additions + f.deletions > 0).map(|f| f.path.as_str()).collect()
}
-/// "Couldn't read 2 files (no diff from GitHub)".
+/// "Couldn't read 2 files (too large to diff)". It names no host: the files may have come from
+/// git, GitHub, GitLab, Gitea or Forgejo.
pub fn unread_reason(n: usize) -> String {
- format!("Couldn't read {n} file{} (no diff from GitHub)", if n == 1 { "" } else { "s" })
+ format!("Couldn't read {n} file{} (too large to diff)", if n == 1 { "" } else { "s" })
}
/// "+27 −9 in 2 files" (a real minus sign, as the design writes it).
@@ -662,6 +663,20 @@ mod tests {
assert!(has_ddl("ALTER TABLE x") && has_ddl("alter table x") && has_ddl("ALTER TABLE") && !has_ddl("alter table"));
}
+ /// 0.7.7: the reason names no host. A GitLab repo read with plain git said "no diff from
+ /// GitHub"; git and every forge leave the patch out for the same reason, its size.
+ #[test]
+ fn the_unread_reason_says_why_and_names_no_host() {
+ assert_eq!(unread_reason(1), "Couldn't read 1 file (too large to diff)");
+ assert_eq!(unread_reason(3), "Couldn't read 3 files (too large to diff)");
+ for n in [1, 2] {
+ let r = unread_reason(n);
+ for host in ["GitHub", "GitLab", "Gitea", "Forgejo", "git"] {
+ assert!(!r.contains(host), "{r}");
+ }
+ }
+ }
+
/// Round 3 (V-T5): GitHub sends no patch for very large files. The card says it couldn't read
/// them and never calls the change small or code-free.
#[test]
@@ -670,14 +685,14 @@ mod tests {
// A test file losing 300 lines, unread: at least Medium, and said
let r = risk(&[unread("tests/a_test.rs", 0, 300)]);
assert_eq!(r.level, Level::Medium);
- assert_eq!(r.reasons, vec!["Couldn't read 1 file (no diff from GitHub)".to_string(), "+0 \u{2212}300 in 1 file".into()]);
+ assert_eq!(r.reasons, vec!["Couldn't read 1 file (too large to diff)".to_string(), "+0 \u{2212}300 in 1 file".into()]);
// A big source file, unread: large plus unread
let r = risk(&[unread("src/a.rs", 900, 0)]);
assert!(r.level >= Level::Medium);
- assert!(r.reasons.contains(&"Couldn't read 1 file (no diff from GitHub)".into()));
+ assert!(r.reasons.contains(&"Couldn't read 1 file (too large to diff)".into()));
// Next to a small read change: still no "Small change"
let r = risk(&[code("src/runner.rs", 2), test_edit("tests/runner_test.rs"), unread("src/big.rs", 4, 0), unread("tests/big_test.rs", 1, 9)]);
- assert!(r.reasons.contains(&"Couldn't read 2 files (no diff from GitHub)".into()), "{:?}", r.reasons);
+ assert!(r.reasons.contains(&"Couldn't read 2 files (too large to diff)".into()), "{:?}", r.reasons);
assert!(r.reasons.iter().all(|x| !x.starts_with("Small change") && !x.contains("no code changed")), "{:?}", r.reasons);
// A binary file (no lines) has no text to read: not counted
let png = FileDiff { path: "site/a.png".into(), status: "modified".into(), additions: 0, deletions: 0, patch: None, previous_path: None };
diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rs
index 4982cfcb..70dcfb17 100644
--- a/src/server/dev/routes.rs
+++ b/src/server/dev/routes.rs
@@ -171,6 +171,10 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
// A code for the one error the desk words differently; null for the rest
"poll_code": e.row.and_then(|r| r.poll_error.as_deref()).and_then(super::git::GitError::poll_code),
"polled_at": e.row.and_then(|r| r.polled_at),
+ // Branches and PRs get review cards only while fresh: this many days, and how many
+ // the last poll skipped as older (0 until the first poll after a restart)
+ "fresh_days": super::review_days(),
+ "old_reviews_skipped": e.row.map_or(0, |r| poller::old_reviews_skipped(space.as_str(), &r.key)),
"last_tag": e.row.and_then(|r| poller::last_tag(space.as_str(), &r.key)),
"added_by": e.row.map(|r| r.added_by_shown()),
}));
@@ -186,6 +190,8 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
"deploy_hint": first.and_then(|r| r.deploy_hint.clone()),
"last_seen_sha": first.and_then(|r| r.last_seen_sha.clone()),
"polled_at": first.and_then(|r| r.polled_at),
+ "fresh_days": super::review_days(),
+ "old_reviews_skipped": first.map_or(0, |r| poller::old_reviews_skipped(space.as_str(), &r.key)),
"poll_error": first.and_then(|r| r.poll_error.clone()),
"backup_command": row.as_ref().and_then(|r| r.backup_command.clone()),
"calls_today": calls,
diff --git a/src/server/dev/source.rs b/src/server/dev/source.rs
index 230ed775..0ac8210b 100644
--- a/src/server/dev/source.rs
+++ b/src/server/dev/source.rs
@@ -9,6 +9,7 @@ use super::git::{Auth, GitError, Repo};
use super::forge::ForgeKind;
use crate::zombie::github::{EtagCache, GhCheck, GhCommit, GhError, GhFile, GhGitPerson, GhPull, GhReview, GithubSource, PostError, ReviewPost};
use chrono::{DateTime, Utc};
+use std::collections::HashMap;
/// A git author or committer.
#[derive(Debug, Clone, PartialEq, Default)]
@@ -282,6 +283,42 @@ impl<'a> History<'a> {
got
}
+ /// The committer dates of those of `shas` git already has (see [`Repo::commit_dates`]): every
+ /// branch head of a team folder, and those a mirror fetched before (their objects stay after
+ /// [`Self::branch_files`] drops its ref). Empty with no git, or when git can't read them.
+ pub async fn commit_dates(&self, shas: &[&str]) -> HashMap<String, DateTime<Utc>> {
+ match &self.git {
+ Some(g) if !shas.is_empty() => g.commit_dates(shas).await.unwrap_or_default(),
+ _ => HashMap::new(),
+ }
+ }
+
+ /// Whether branch heads are fetched before they can be read (a mirror), rather than read in
+ /// place (a team folder).
+ pub fn fetches_branches(&self) -> bool {
+ self.git.as_ref().is_some_and(|g| !g.is_local())
+ }
+
+ /// When branch `name`'s head `sha`, which the mirror doesn't have yet, was committed: fetches
+ /// the branch the way [`Self::branch_files`] does, reads the date and drops the ref. The
+ /// objects stay, so a fresh branch's [`Self::branch_files`] right after fetches nothing more,
+ /// and later polls read the date with no fetch. `None` when the fetch failed or didn't bring
+ /// `sha` (the branch moved since it was listed): the branch waits for the next poll, as when
+ /// [`Self::branch_files`] can't read it.
+ pub async fn fetch_branch_date(&self, name: &str, sha: &str) -> Option<DateTime<Utc>> {
+ let g = self.git.as_ref()?;
+ if g.resolve(sha).await.is_ok() {
+ return g.commit_dates(&[sha]).await.ok().and_then(|d| d.get(sha).copied());
+ }
+ let local = format!("refs/kwant/branch/{name}");
+ let at = match g.fetch_ref(&self.url, &format!("refs/heads/{name}"), &local, self.auth.as_ref()).await {
+ Ok(_) => g.commit_dates(&[sha]).await.ok().and_then(|d| d.get(sha).copied()),
+ Err(_) => None,
+ };
+ g.drop_ref(&local).await;
+ at
+ }
+
/// Whether `sha` is already in `base_branch` (a pushed branch that merged, or never moved
/// ahead). `false` when git can't tell (the mirror doesn't have `sha` yet).
pub async fn in_branch(&self, sha: &str, base_branch: &str) -> bool {
diff --git a/tests/dev_fresh_reviews_test.rs b/tests/dev_fresh_reviews_test.rs
new file mode 100644
index 00000000..718c5efc
--- /dev/null
+++ b/tests/dev_fresh_reviews_test.rs
@@ -0,0 +1,296 @@
+//! Dev mode reviews only fresh work (0.7.7, dev-fresh-reviews/brief.md): a pushed branch or open
+//! PR gets a review card only while its last commit (a PR's last update) is at most
+//! `KWANT_DEV_REVIEW_DAYS` (default 7) days old. Older work gets no card and no model call, its
+//! old card goes stale, and a new push makes it fresh again. Candidates are read newest first under
+//! the per-poll cap, and the status says how many were skipped.
+//!
+//! Git repos are throwaway `git init`s in a temp dir with back-dated commits; nothing touches the
+//! network or any remote. CI sets no `KWANT_DEV_REVIEW_DAYS`, so the window is 7 days.
+
+mod common;
+
+use chrono::{DateTime, Duration, Utc};
+use common::*;
+use kwnt::db::dev_mode::{DevCardRow, DevRepoRow, BY_HAND, REVIEW, STALE};
+use kwnt::db::models::NewTeam;
+use kwnt::db::spaces::SpaceId;
+use kwnt::server::dev::facts::{Check, DevFacts, FileDiff};
+use kwnt::server::dev::forge::ForgeKind;
+use kwnt::server::dev::git::Repo;
+use kwnt::server::dev::poller;
+use kwnt::server::dev::source::{Change, Forge, History};
+use kwnt::zombie::github::{EtagCache, GhError, GhReview, PostError, ReviewPost};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+
+/// git in `dir`, with author and committer dates set to `at` when given.
+fn git_at(dir: &Path, args: &[&str], at: Option<DateTime<Utc>>) -> String {
+ let mut cmd = std::process::Command::new("git");
+ cmd.arg("-C")
+ .arg(dir)
+ .args(["-c", "user.name=Vega (kwant bot)", "-c", "[email protected]", "-c", "commit.gpgsign=false"])
+ .args(args)
+ .env("GIT_TERMINAL_PROMPT", "0")
+ .env("GIT_CONFIG_NOSYSTEM", "1");
+ if let Some(at) = at {
+ let at = format!("{} +0000", at.timestamp());
+ cmd.env("GIT_AUTHOR_DATE", &at).env("GIT_COMMITTER_DATE", &at);
+ }
+ let out = cmd.output().unwrap();
+ assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).trim().to_string()
+}
+
+fn days_ago(d: i64) -> DateTime<Utc> {
+ Utc::now() - Duration::days(d)
+}
+
+fn git(dir: &Path, args: &[&str]) -> String {
+ git_at(dir, args, None)
+}
+
+/// A commit of `file` dated `days` days back (now when `None`).
+fn commit_at(dir: &Path, file: &str, text: &str, message: &str, days: Option<i64>) -> String {
+ std::fs::write(dir.join(file), text).unwrap();
+ git(dir, &["add", "--", file]);
+ git_at(dir, &["commit", "-q", "-m", message], days.map(days_ago));
+ git(dir, &["rev-parse", "HEAD"])
+}
+
+/// Branch `name` off main with one commit dated `days` days back; returns its head.
+fn branch(dir: &Path, name: &str, days: Option<i64>) -> String {
+ git(dir, &["checkout", "-q", "-b", name, "main"]);
+ let sha = commit_at(dir, &format!("{name}.txt"), &format!("{name}\n"), &format!("Work on {name}"), days);
+ git(dir, &["checkout", "-q", "main"]);
+ sha
+}
+
+/// A team whose folder is a repo on `main` (its first commit 60 days old), watched by Dev mode
+/// with no forge: branches get the no-forge review cards.
+async fn watched(env: &Env, name: &str) -> (PathBuf, DevRepoRow) {
+ let space = SpaceId::default_space();
+ let folder = env.tmp.path().join("folders").join(name);
+ std::fs::create_dir_all(&folder).unwrap();
+ git(&folder, &["init", "-q", "-b", "main"]);
+ commit_at(&folder, "README.md", "# App\n", "Start the repo", Some(60));
+ let t = NewTeam {
+ name: name.into(),
+ description: None,
+ icon: None,
+ lead_kwant_id: env.a.clone(),
+ member_kwants: vec![env.a.clone()],
+ workspace_path: Some(folder.to_string_lossy().to_string()),
+ repo_url: None,
+ };
+ env.state.db.create_team(&space, &t).await.unwrap();
+ let (s, v) = call(&env.app, "PUT", &format!("/api/spaces/{}/dev_mode", space.as_str()), Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let row = env.state.db.dev_repo(space.as_str(), &format!("local:{name}")).await.unwrap().unwrap();
+ (folder, row)
+}
+
+/// Every review card of the repo, oldest first.
+async fn cards(env: &Env, key: &str) -> Vec<DevCardRow> {
+ let mut rows = env.state.db.dev_cards_in(SpaceId::default_space().as_str(), Some(key), REVIEW, None, 50).await.unwrap();
+ rows.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
+ rows
+}
+
+/// The refs of the repo's live (not stale) review cards, sorted.
+async fn live(env: &Env, key: &str) -> Vec<String> {
+ let mut refs: Vec<String> = cards(env, key).await.into_iter().filter(|c| c.status != STALE).map(|c| c.ref_).collect();
+ refs.sort();
+ refs
+}
+
+async fn status(env: &Env) -> Value {
+ let (s, v) = call(&env.app, "GET", &format!("/api/spaces/{}/dev_mode", SpaceId::default_space().as_str()), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ v
+}
+
+async fn poll(env: &Env) {
+ poller::poll_space(&env.state, SpaceId::default_space().as_str()).await;
+}
+
+/// Oleks's desk, 2026-11-08: every unmerged branch of a GitLab repo watched with plain git got a
+/// review, however old, until the day's 30 model calls were gone. Now a 30-day-old branch gets no
+/// card (so no model call), a 1-day-old one does, the status says one was skipped, and a new push
+/// to the old branch makes it fresh.
+#[tokio::test]
+async fn an_old_branch_gets_no_review_until_someone_pushes_to_it() {
+ let env = setup().await;
+ let (folder, row) = watched(&env, "fresh-a").await;
+ let old = branch(&folder, "kc-8125", Some(30));
+ let new = branch(&folder, "kc-9001", Some(1));
+ // Six days and a bit is still inside the window
+ branch(&folder, "kc-9000", Some(6));
+
+ poll(&env).await;
+ let all = cards(&env, &row.key).await;
+ assert!(all.iter().all(|c| c.ref_ != "branch:kc-8125" && c.head_sha != old), "no card at all for the old branch, so no generate: {all:?}");
+ assert_eq!(live(&env, &row.key).await, ["branch:kc-9000", "branch:kc-9001"]);
+ assert!(all.iter().any(|c| c.head_sha == new));
+
+ // The status says the window and how many it skipped, per repo and at the top
+ let v = status(&env).await;
+ assert_eq!((v["repos"][0]["fresh_days"].clone(), v["repos"][0]["old_reviews_skipped"].clone()), (json!(7), json!(1)), "{v}");
+ assert_eq!((v["fresh_days"].clone(), v["old_reviews_skipped"].clone()), (json!(7), json!(1)), "{v}");
+
+ // Still old on the next poll: still nothing
+ poll(&env).await;
+ assert!(cards(&env, &row.key).await.iter().all(|c| c.ref_ != "branch:kc-8125"));
+
+ // Someone pushes to the old branch: it's fresh, so it gets its card, and nothing is skipped
+ git(&folder, &["checkout", "-q", "kc-8125"]);
+ let pushed = commit_at(&folder, "kc-8125.txt", "kc-8125\nmore\n", "Pick KC-8125 up again", None);
+ git(&folder, &["checkout", "-q", "main"]);
+ poll(&env).await;
+ let all = cards(&env, &row.key).await;
+ let c = all.iter().find(|c| c.ref_ == "branch:kc-8125").expect("a card after the push");
+ assert_eq!(c.head_sha, pushed);
+ let f: DevFacts = serde_json::from_str(&c.facts).unwrap();
+ assert_eq!(f.files.iter().map(|x| x.path.as_str()).collect::<Vec<_>>(), ["kc-8125.txt"], "the whole branch against main, old commit included");
+ assert_eq!(live(&env, &row.key).await, ["branch:kc-8125", "branch:kc-9000", "branch:kc-9001"]);
+ assert_eq!(status(&env).await["repos"][0]["old_reviews_skipped"], 0);
+}
+
+/// The 27 cards on the desk drop by themselves after the upgrade: a review card made before, on a
+/// branch with no commit in 7 days, goes stale on the next poll, with no new card and no migration.
+#[tokio::test]
+async fn a_card_on_a_branch_that_went_quiet_goes_stale() {
+ let env = setup().await;
+ let (folder, row) = watched(&env, "fresh-b").await;
+ let old = branch(&folder, "kc-7000", Some(30));
+ let fresh = branch(&folder, "kc-7001", Some(2));
+ // Cards as 0.7.6 left them, for both heads
+ let space = SpaceId::default_space();
+ for (r, sha) in [("branch:kc-7000", &old), ("branch:kc-7001", &fresh)] {
+ env.state.db.insert_dev_card_in(space.as_str(), &row.key, REVIEW, r, sha, "{}").await.unwrap().unwrap();
+ }
+ assert_eq!(live(&env, &row.key).await, ["branch:kc-7000", "branch:kc-7001"]);
+
+ poll(&env).await;
+ assert_eq!(live(&env, &row.key).await, ["branch:kc-7001"], "the old branch's card is stale; the fresh one keeps its card");
+ let all = cards(&env, &row.key).await;
+ assert_eq!(all.len(), 2, "no new card for either: {all:?}");
+ assert_eq!(all.iter().find(|c| c.ref_ == "branch:kc-7000").unwrap().status, STALE);
+ assert_eq!(status(&env).await["repos"][0]["old_reviews_skipped"], 1);
+}
+
+/// At most MAX_REVIEWS branches are read per poll, and the freshest go first: name order would
+/// have read b00..b09, the oldest ten.
+#[tokio::test]
+async fn branches_are_read_newest_first_under_the_cap() {
+ assert_eq!(poller::MAX_REVIEWS, 10);
+ let env = setup().await;
+ let (folder, row) = watched(&env, "fresh-c").await;
+ // b00 is the oldest (5 days and 11 hours), b11 the newest (5 days)
+ for i in 0..12i64 {
+ let name = format!("b{i:02}");
+ git(&folder, &["checkout", "-q", "-b", &name, "main"]);
+ std::fs::write(folder.join(format!("{name}.txt")), "x\n").unwrap();
+ git(&folder, &["add", "--", &format!("{name}.txt")]);
+ git_at(&folder, &["commit", "-q", "-m", &name], Some(days_ago(5) - Duration::hours(11 - i)));
+ git(&folder, &["checkout", "-q", "main"]);
+ }
+ poll(&env).await;
+ let want: Vec<String> = (2..12).map(|i| format!("branch:b{i:02}")).collect();
+ assert_eq!(live(&env, &row.key).await, want, "the ten newest");
+ // The two oldest wait for the next poll, and none was skipped as old
+ assert_eq!(status(&env).await["repos"][0]["old_reviews_skipped"], 0);
+ poll(&env).await;
+ assert_eq!(live(&env, &row.key).await.len(), 12);
+}
+
+struct Fake {
+ open: Vec<Change>,
+}
+
+#[async_trait::async_trait]
+impl Forge for Fake {
+ async fn changes_for_commit(&self, _sha: &str) -> Result<Vec<Change>, GhError> {
+ Ok(vec![])
+ }
+ async fn open_changes(&self, _base: &str, _cache: &EtagCache) -> Result<Vec<Change>, GhError> {
+ Ok(self.open.clone())
+ }
+ async fn checks(&self, _sha: &str, _cache: &EtagCache) -> Result<Vec<Check>, GhError> {
+ Ok(vec![])
+ }
+ async fn change_files(&self, _number: u64) -> Result<Vec<FileDiff>, GhError> {
+ Ok(vec![])
+ }
+ fn change_head_ref(&self, number: u64) -> Option<String> {
+ Some(format!("refs/pull/{number}/head"))
+ }
+ async fn commit_login(&self, _sha: &str) -> Option<String> {
+ None
+ }
+ fn kind(&self) -> ForgeKind {
+ ForgeKind::Gitlab
+ }
+ async fn change(&self, number: u64) -> Result<Option<Change>, GhError> {
+ Ok(self.open.iter().find(|c| c.number == number).cloned())
+ }
+ async fn login(&self) -> Result<String, GhError> {
+ Ok("demo-bot".into())
+ }
+ async fn post_review(&self, _number: u64, _post: &ReviewPost) -> Result<GhReview, PostError> {
+ unreachable!("nothing posts in this test")
+ }
+}
+
+/// With a forge, a PR is fresh by its `updated_at`, else by its head commit's date; an unknown
+/// date counts as fresh. Old PRs get no card and their old cards go stale.
+#[tokio::test]
+async fn forge_prs_are_reviewed_only_while_updated_in_the_window() {
+ let env = setup().await;
+ let space = SpaceId::default_space();
+ let dir = env.tmp.path().join("mr");
+ std::fs::create_dir_all(&dir).unwrap();
+ git(&dir, &["init", "-q", "-b", "main"]);
+ commit_at(&dir, "README.md", "# App\n", "Start", Some(60));
+ let h20 = branch(&dir, "quiet", None);
+ let h21 = branch(&dir, "busy", Some(40));
+ let h22 = branch(&dir, "old-head", Some(30));
+ let h23 = branch(&dir, "new-head", Some(1));
+ let h24 = branch(&dir, "nothing-known", None);
+ let change = |n: u64, head_branch: &str, head_sha: &str, days: Option<i64>| Change {
+ number: n,
+ title: format!("MR {n}"),
+ url: Some(format!("https://gitlab.example.com/webc/app/-/merge_requests/{n}")),
+ head_branch: head_branch.into(),
+ head_sha: head_sha.into(),
+ base_branch: "main".into(),
+ updated_at: days.map(days_ago),
+ ..Default::default()
+ };
+ let fake = Fake {
+ open: vec![
+ // Updated 30 days ago, though its head commit is new: old
+ change(20, "quiet", &h20, Some(30)),
+ // A comment yesterday on an old commit: fresh
+ change(21, "busy", &h21, Some(1)),
+ // No updated_at: its head commit decides, 30 days old
+ change(22, "old-head", &h22, None),
+ // No updated_at, head commit a day old: fresh
+ change(23, "new-head", &h23, None),
+ // No updated_at and a head git doesn't have: unknown, so fresh (git can't diff it, so the forge's list is asked)
+ change(24, "nothing-known", &"e".repeat(40), None),
+ ],
+ };
+ let _ = h24;
+ env.state.db.add_dev_repo(space.as_str(), "gitlab.example.com/webc/app", None, "webc/app", Some("gitlab.example.com"), "main", None, BY_HAND).await.unwrap();
+ let row = env.state.db.dev_repo(space.as_str(), "gitlab.example.com/webc/app").await.unwrap().unwrap();
+ // A card 0.7.6 made for the old MR 20
+ env.state.db.insert_dev_card_in(space.as_str(), &row.key, REVIEW, "pr:20", &h20, "{}").await.unwrap().unwrap();
+ let h = History::new(Some(Repo::local(&dir, &env.state.config.data_dir).await.unwrap()), dir.to_string_lossy().to_string(), None, None, "main", None);
+ poller::read(&env.state, &row, &h, Some(&fake)).await.unwrap();
+
+ assert_eq!(live(&env, &row.key).await, ["pr:21", "pr:23", "pr:24"]);
+ let all = cards(&env, &row.key).await;
+ assert!(all.iter().all(|c| c.ref_ != "pr:22"), "no card for the MR whose head is 30 days old: {all:?}");
+ assert_eq!(all.iter().filter(|c| c.ref_ == "pr:20").map(|c| c.status.as_str()).collect::<Vec<_>>(), [STALE], "the old MR's card went stale and got no new one");
+ assert_eq!(poller::old_reviews_skipped(space.as_str(), &row.key), 2);
+}