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: no daily model call cap by default; capped cards are written again (#550)

Oleksandr Ivanchenkoc3223bd86b10
diff --git a/site-src/docs-dev-mode.html b/site-src/docs-dev-mode.html
index 1d4165fb..918634fb 100644
--- a/site-src/docs-dev-mode.html
+++ b/site-src/docs-dev-mode.html
@@ -67,7 +67,7 @@ card_art: avatar:devops
<li><strong>Draft release notes</strong> writes notes from every landed card since the last tag.</li>
<li><strong>Verified</strong> goes on a merge only when another bot reviewed that exact head in kwant, every finding was fixed or dismissed, and CI on the merge is green. A pull request merged before its review was ready stays "not verified": the sticker says what was checked before the change landed, not after.</li>
</ul>
-<p>kwant checks the repo every 5 minutes. The first check writes up the last 5 merges. Card text is written by one of the space's bots, at most 30 model calls per space per day; the risk, the test checks and CI come from rules and need no model.</p>
+<p>kwant checks the repo every 5 minutes. The first check writes up the last 5 merges. Card text is written by one of the space's bots, and its model calls count toward the space's daily spending stop and the bot's monthly budget; the risk, the test checks and CI come from rules and need no model.</p>
<h2 id="reviews">Reviews</h2>
<p>The <strong>Reviews</strong> tab has one card per open pull request, written by a bot that didn't write the code, on a different engine when the space has one. A new push to the pull request gets a new review.</p>
diff --git a/site/docs/dev-mode.html b/site/docs/dev-mode.html
index 85c5a9b9..57ee3897 100644
--- a/site/docs/dev-mode.html
+++ b/site/docs/dev-mode.html
@@ -20,7 +20,7 @@
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="Dev mode: Plain-words cards for every merge, a second bot&#x27;s review on every pull request, and a floor under production.">
<meta property="article:published_time" content="2026-11-06">
-<meta property="article:modified_time" content="2026-11-11">
+<meta property="article:modified_time" content="2026-11-12">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@kwantbot">
<meta name="twitter:title" content="Dev mode: AI code review and a production safety floor · kwant">
@@ -118,7 +118,7 @@
<li><strong>Draft release notes</strong> writes notes from every landed card since the last tag.</li>
<li><strong>Verified</strong> goes on a merge only when another bot reviewed that exact head in kwant, every finding was fixed or dismissed, and CI on the merge is green. A pull request merged before its review was ready stays "not verified": the sticker says what was checked before the change landed, not after.</li>
</ul>
-<p>kwant checks the repo every 5 minutes. The first check writes up the last 5 merges. Card text is written by one of the space's bots, at most 30 model calls per space per day; the risk, the test checks and CI come from rules and need no model.</p>
+<p>kwant checks the repo every 5 minutes. The first check writes up the last 5 merges. Card text is written by one of the space's bots, and its model calls count toward the space's daily spending stop and the bot's monthly budget; the risk, the test checks and CI come from rules and need no model.</p>
<h2 id="reviews">Reviews</h2>
<p>The <strong>Reviews</strong> tab has one card per open pull request, written by a bot that didn't write the code, on a different engine when the space has one. A new push to the pull request gets a new review.</p>
@@ -277,7 +277,7 @@
</footer>
<script src="../assets/js/site.js?v=6d3de1ef56" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
-<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/dev-mode#article","headline":"Dev mode: AI code review and a production safety floor","description":"Point a kwant space at its git repos, on GitHub, GitLab, Gitea, Forgejo or any git server. Bots explain every merge in plain words, review each pull request with a second bot, and every push to main or deploy asks you first.","url":"https://kwant.si/docs/dev-mode","mainEntityOfPage":"https://kwant.si/docs/dev-mode","image":"https://kwant.si/assets/og/docs-dev-mode.png?v=4b20e5912f","inLanguage":"en","datePublished":"2026-11-06","dateModified":"2026-11-11","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Dev mode","item":"https://kwant.si/docs/dev-mode"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
+<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/dev-mode#article","headline":"Dev mode: AI code review and a production safety floor","description":"Point a kwant space at its git repos, on GitHub, GitLab, Gitea, Forgejo or any git server. Bots explain every merge in plain words, review each pull request with a second bot, and every push to main or deploy asks you first.","url":"https://kwant.si/docs/dev-mode","mainEntityOfPage":"https://kwant.si/docs/dev-mode","image":"https://kwant.si/assets/og/docs-dev-mode.png?v=4b20e5912f","inLanguage":"en","datePublished":"2026-11-06","dateModified":"2026-11-12","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Dev mode","item":"https://kwant.si/docs/dev-mode"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
</body>
</html>
diff --git a/site/sitemap.xml b/site/sitemap.xml
index 6c0d2249..4788a713 100644
--- a/site/sitemap.xml
+++ b/site/sitemap.xml
@@ -8,7 +8,7 @@
<url><loc>https://kwant.si/docs/approvals</loc><lastmod>2026-11-07</lastmod></url>
<url><loc>https://kwant.si/docs/bots-and-teams</loc><lastmod>2026-11-12</lastmod></url>
<url><loc>https://kwant.si/docs/browser</loc><lastmod>2026-11-12</lastmod></url>
- <url><loc>https://kwant.si/docs/dev-mode</loc><lastmod>2026-11-11</lastmod></url>
+ <url><loc>https://kwant.si/docs/dev-mode</loc><lastmod>2026-11-12</lastmod></url>
<url><loc>https://kwant.si/docs/flight-school</loc><lastmod>2026-11-06</lastmod></url>
<url><loc>https://kwant.si/docs/goals</loc><lastmod>2026-11-05</lastmod></url>
<url><loc>https://kwant.si/docs/idea-jar</loc><lastmod>2026-11-06</lastmod></url>
diff --git a/src/db/dev_mode.rs b/src/db/dev_mode.rs
index 52dbb81b..5fdd3180 100644
--- a/src/db/dev_mode.rs
+++ b/src/db/dev_mode.rs
@@ -9,8 +9,10 @@ use super::{Database, DbError};
use chrono::{DateTime, Utc};
use sqlx::FromRow;
-/// Most model calls Dev mode makes per space per day (plan D8).
-pub const CALLS_CAP: i64 = 30;
+/// No daily cap on Dev mode's model calls: the default since 0.9.5. Cost is held by the space's
+/// daily spending stop and each bot's monthly budget, which every card turn passes; a fixed 30
+/// calls a day (plan D8) failed cards on a busy repo with no way out.
+pub const NO_CALL_CAP: i64 = i64::MAX;
/// Most repos one space watches (team-repos.md T4).
pub const MAX_REPOS: usize = 10;
@@ -826,6 +828,23 @@ impl Database {
.await?)
}
+ /// Failed cards whose only fault was the old daily call cap (their `error` is
+ /// `generate::cap_reason`: "Today's N Dev mode model calls…"), last written at or after
+ /// `since`: back to pending, so a restart writes them again. A card that went stale stays as
+ /// it is. The number put back.
+ pub async fn requeue_capped_dev_cards(&self, since: DateTime<Utc>) -> Result<u64, DbError> {
+ let done = sqlx::query(
+ "UPDATE dev_cards SET status = 'pending', updated_at = ?2, rev = rev + 1
+ WHERE status = 'failed' AND updated_at >= ?1
+ AND card LIKE '%\"error\":\"Today''s % Dev mode model calls for this space are used up%'",
+ )
+ .bind(since)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected())
+ }
+
/// Cards still pending (a restart left them), oldest first.
pub async fn pending_dev_cards(&self) -> Result<Vec<DevCardRow>, DbError> {
Ok(sqlx::query_as(&format!("SELECT {CARD_COLS} FROM dev_cards WHERE status = 'pending' ORDER BY created_at")).fetch_all(&self.pool).await?)
@@ -872,8 +891,8 @@ impl Database {
Ok(row.map(|r| r.0).unwrap_or(0))
}
- /// Takes one model call from today's cap (`dev::call_cap()`, default [`CALLS_CAP`]): false (and
- /// nothing counted) once it's used up.
+ /// Counts one model call against today's cap (`dev::call_cap()`, none unless
+ /// `KWANT_DEV_CALL_CAP` sets one): false (and nothing counted) once it's used up.
pub async fn take_dev_call(&self, space_id: &str) -> Result<bool, DbError> {
self.take_dev_call_at(space_id, crate::server::dev::now(), crate::server::dev::call_cap()).await
}
diff --git a/src/server/dev/generate.rs b/src/server/dev/generate.rs
index 0ff4328a..ee61ef6e 100644
--- a/src/server/dev/generate.rs
+++ b/src/server/dev/generate.rs
@@ -6,7 +6,7 @@
//! person. The reply must be one JSON object; a reply that doesn't validate is asked for once more,
//! then the card is `failed` with the reason and keeps its rule-based parts. Each try takes a call
//! from the space's daily cap, which is a parameter of [`generate_with_cap`]; [`generate`] reads it
-//! from `KWANT_DEV_CALL_CAP` ([`super::call_cap`], 30 by default).
+//! from `KWANT_DEV_CALL_CAP` ([`super::call_cap`]; no cap when unset, since 0.9.5).
//!
//! Every card turn is asked with [`NO_TOOLS`]: the [`Model`] seam gets the tool list with each
//! call, [`TurnModel`] refuses any other list, and the tests check the list stays empty.
@@ -30,8 +30,8 @@ pub fn cap_reason(cap: i64) -> String {
format!("Today's {cap} Dev mode model calls for this space are used up; the card has only its rule-based parts.")
}
-/// Generates the card `card_id` under the space's daily cap ([`super::call_cap`]:
-/// `KWANT_DEV_CALL_CAP`, else 30); see [`generate_with_cap`].
+/// Generates the card `card_id` under the space's daily cap ([`super::call_cap`]: none unless
+/// `KWANT_DEV_CALL_CAP` sets one); see [`generate_with_cap`].
pub async fn generate(state: AppState, card_id: String) {
generate_with_cap(state, card_id, super::call_cap()).await
}
@@ -481,9 +481,8 @@ mod tests {
(m.cap, m.calls_left) = (5, 0);
let e = ask_json(&mut m, "P", parse).await.unwrap_err();
assert!(e.starts_with("Today's 5 Dev mode model calls"), "{e}");
- assert_eq!(cap_reason(crate::db::dev_mode::CALLS_CAP), cap_reason(30));
- // generate() reads the space's cap from Lin's KWANT_DEV_CALL_CAP seam (30 when unset)
- assert_eq!(super::super::call_cap(), crate::db::dev_mode::CALLS_CAP);
+ // generate() reads the space's cap from Lin's KWANT_DEV_CALL_CAP seam (no cap when unset)
+ assert_eq!(super::super::call_cap(), crate::db::dev_mode::NO_CALL_CAP);
}
#[test]
@@ -539,6 +538,35 @@ mod tests {
assert_eq!(db.dev_calls_on("sp_a", &super::super::utc_day(now)).await.unwrap(), 3);
}
+ /// 0.9.5: cards the old 30-call cap failed go back to pending (recent ones only); a card that
+ /// failed for another reason, a ready one and a stale one stay as they are.
+ #[tokio::test]
+ async fn cards_the_old_cap_failed_go_back_to_pending() {
+ use crate::db::dev_mode::{PENDING, STALE};
+ let tmp = tempfile::tempdir().unwrap();
+ let db = crate::db::Database::init(tmp.path()).await.unwrap();
+ let mut ids = Vec::new();
+ for (i, (status, error)) in [(FAILED, cap_reason(30)), (FAILED, "`intent` is missing".to_string()), (READY, String::new()), (STALE, cap_reason(30))].into_iter().enumerate() {
+ let row = db.insert_dev_card("sp_a", REVIEW, &format!("pr-{i}"), &format!("sha{i}"), "{}").await.unwrap().unwrap();
+ let card = serde_json::json!({"kind": REVIEW, "error": error, "risk": {"level": "low"}}).to_string();
+ db.set_dev_card(&row.id, status, Some(&card)).await.unwrap();
+ ids.push(row.id);
+ }
+ // A cap failure from before the window stays failed
+ assert_eq!(db.requeue_capped_dev_cards(chrono::Utc::now() + chrono::Duration::minutes(1)).await.unwrap(), 0);
+ assert_eq!(db.requeue_capped_dev_cards(chrono::Utc::now() - chrono::Duration::days(3)).await.unwrap(), 1);
+ let status = |i: usize| {
+ let (db, id) = (&db, ids[i].clone());
+ async move { db.dev_card(&id).await.unwrap().unwrap().status }
+ };
+ assert_eq!(status(0).await, PENDING);
+ assert_eq!(status(1).await, FAILED);
+ assert_eq!(status(2).await, READY);
+ assert_eq!(status(3).await, STALE);
+ let pending: Vec<String> = db.pending_dev_cards().await.unwrap().into_iter().map(|r| r.id).collect();
+ assert_eq!(pending, vec![ids[0].clone()]);
+ }
+
#[test]
fn the_prompt_diff_stops_at_60k() {
let big = "+x\n".repeat(DIFF_CHARS / 3 / 3);
diff --git a/src/server/dev/mod.rs b/src/server/dev/mod.rs
index beed9253..e5f35d99 100644
--- a/src/server/dev/mod.rs
+++ b/src/server/dev/mod.rs
@@ -35,7 +35,7 @@ pub mod worktrees;
pub use generate::generate;
-use crate::db::dev_mode::{DevCardRow, CALLS_CAP};
+use crate::db::dev_mode::{DevCardRow, NO_CALL_CAP};
use crate::drivers::events::RuntimeEvent;
use crate::server::AppState;
@@ -65,10 +65,16 @@ pub fn poll_every() -> std::time::Duration {
std::time::Duration::from_secs(*SECS.get_or_init(|| env_num("KWANT_DEV_POLL_SECS", 5, 86_400).unwrap_or(poller::EVERY.as_secs())))
}
-/// Most model calls Dev mode makes per space per UTC day: `KWANT_DEV_CALL_CAP` (0–1000), else 30.
+/// Most model calls Dev mode makes per space per UTC day: `KWANT_DEV_CALL_CAP` (0–1000) when set,
+/// else no cap ([`NO_CALL_CAP`]); the daily spending stop and each bot's budget hold the cost.
pub fn call_cap() -> i64 {
static CAP: std::sync::OnceLock<i64> = std::sync::OnceLock::new();
- *CAP.get_or_init(|| env_num("KWANT_DEV_CALL_CAP", 0, 1000).map_or(CALLS_CAP, |v| v as i64))
+ *CAP.get_or_init(|| env_num("KWANT_DEV_CALL_CAP", 0, 1000).map_or(NO_CALL_CAP, |v| v as i64))
+}
+
+/// The cap to show: `None` when there is none.
+pub fn shown_cap() -> Option<i64> {
+ Some(call_cap()).filter(|&c| c != NO_CALL_CAP)
}
/// How many days a pushed branch or open PR counts as fresh, so it gets a review card:
@@ -175,7 +181,8 @@ mod tests {
fn unset_seams_keep_the_defaults() {
// CI sets neither variable
assert_eq!(poll_every(), std::time::Duration::from_secs(300));
- assert_eq!(call_cap(), 30);
+ assert_eq!(call_cap(), NO_CALL_CAP, "no daily cap unless KWANT_DEV_CALL_CAP sets one");
+ assert_eq!(shown_cap(), None);
assert_eq!(review_days(), 7);
assert!((now() - Utc::now()).num_seconds().abs() <= 1);
}
diff --git a/src/server/dev/poller.rs b/src/server/dev/poller.rs
index 76caa18e..d0db7a81 100644
--- a/src/server/dev/poller.rs
+++ b/src/server/dev/poller.rs
@@ -118,7 +118,8 @@ pub fn is_fresh(at: Option<DateTime<Utc>>, now: DateTime<Utc>, days: u32) -> boo
}
/// 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.
+/// again (with the last [`CAPPED_REDO_DAYS`] days' cards that failed only on the old daily call
+/// cap, while there is no cap), and a Fix it whose task never went out is sent.
pub fn spawn(state: AppState, shutdown: CancellationToken) {
tokio::spawn(async move {
recover(&state).await;
@@ -151,7 +152,17 @@ pub fn spawn(state: AppState, shutdown: CancellationToken) {
});
}
+/// How far back a restart writes again the cards the old 30-call cap failed (0.9.5).
+pub const CAPPED_REDO_DAYS: i64 = 3;
+
async fn recover(state: &AppState) {
+ if super::shown_cap().is_none() {
+ match state.db.requeue_capped_dev_cards(Utc::now() - Duration::days(CAPPED_REDO_DAYS)).await {
+ Ok(0) => {}
+ Ok(n) => tracing::info!("dev: writing {n} card(s) again that the old daily call cap failed"),
+ Err(e) => tracing::warn!("dev: could not put capped cards back: {e}"),
+ }
+ }
match state.db.pending_dev_cards().await {
Ok(rows) => {
for r in rows {
diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rs
index 85147e7a..e9597639 100644
--- a/src/server/dev/routes.rs
+++ b/src/server/dev/routes.rs
@@ -195,7 +195,7 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
"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,
- "calls_cap": super::call_cap(),
+ "calls_cap": super::shown_cap(),
});
let any_watching = repos.iter().any(|r| matches!(r["status"].as_str(), Some("watching" | "error")));
let any_unread = repos.iter().any(|r| r["status"] == "not_connected");
diff --git a/tests/dev_seams_test.rs b/tests/dev_seams_test.rs
index 7738e733..3b0175c7 100644
--- a/tests/dev_seams_test.rs
+++ b/tests/dev_seams_test.rs
@@ -52,6 +52,7 @@ async fn the_env_seams_set_the_poll_and_the_cap() {
std::env::set_var("KWANT_DEV_MIRROR_CAP_BYTES", "4096");
assert_eq!(dev::poll_every(), std::time::Duration::from_secs(7));
assert_eq!(dev::call_cap(), 2);
+ assert_eq!(dev::shown_cap(), Some(2), "an opt-in cap is shown");
assert_eq!(dev::mirror_cap(), 4096, "a tiny git mirror cap, for QA (the default is 1 GB)");
let tmp = tempfile::tempdir().unwrap();
diff --git a/tests/dev_tickets_test.rs b/tests/dev_tickets_test.rs
index 14520c1a..5e3ced1d 100644
--- a/tests/dev_tickets_test.rs
+++ b/tests/dev_tickets_test.rs
@@ -463,17 +463,19 @@ async fn the_person_answers_on_the_card_and_edits_the_brief() {
assert_eq!(hooks::work_seam(st, sp, "TRAIL-999").await, hooks::WorkSeam::default(), "no brief, no work");
}
-/// J13: with the space's model calls used up, the brief fails and says why; no turn runs.
+/// J13 (0.9.5): Dev mode has no daily model call cap unless KWANT_DEV_CALL_CAP sets one, so a
+/// space that already made more than the old 30 calls today still gets its brief.
#[tokio::test]
-async fn the_call_cap_fails_the_brief() {
- let marker = call_tool_marker("submit_brief", brief_args("Capped goal", &["x"], json!({})));
- let w = world("Capped", fixture(&marker, "", ""), false).await;
- while w.env.state.db.take_dev_call(w.space.as_str()).await.unwrap() {}
+async fn a_busy_day_does_not_stop_the_brief() {
+ let marker = call_tool_marker("submit_brief", brief_args("Busy goal", &["x"], json!({})));
+ let w = world("Busy", fixture(&marker, "", ""), false).await;
+ for _ in 0..40 {
+ assert!(w.env.state.db.take_dev_call(w.space.as_str()).await.unwrap(), "no cap by default");
+ }
w.start("TRAIL-101").await;
let b = w.state_is("TRAIL-101", &["failed", "working"]).await;
- assert_eq!(b["state"], "failed", "{b}");
- assert!(b["note"].as_str().unwrap().contains("cap"), "{b}");
- assert!(invocations_with(&marker).is_empty(), "no turn ran");
+ assert_eq!(b["state"], "working", "{b}");
+ assert!(!invocations_with(&marker).is_empty(), "the brief's turn ran");
}
/// With Jira off (no site), nothing happens: no row, no turn, no brief route.