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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Pre-push: the person's Retry or Override approves the one push it lets go; newer cards supersede older ones (0.9.7) (#571)
Oleksandr Ivanchenko380f66be295c
diff --git a/src/db/approval_modes.rs b/src/db/approval_modes.rsindex a97d23bc..623d0aee 100644--- a/src/db/approval_modes.rs+++ b/src/db/approval_modes.rs@@ -383,6 +383,21 @@ impl Database {/// Records a call that ran without a card because approvals were off (or it was safe under/// "Ask only when risky").+ /// Records a call the person approved before it was asked (0.9.7: a push their Retry or+ /// Override on a pre-push card covers) as `allowed_once`, with no card. Its id.+ pub async fn save_granted(&self, input: &super::models::NewApproval) -> Result<String, DbError> {+ let id = uuid::Uuid::new_v4().to_string();+ sqlx::query("INSERT INTO approvals (id, turn_id, kwant_id, tool_name, parameters, status) VALUES (?, ?, ?, ?, ?, 'allowed_once')")+ .bind(&id)+ .bind(&input.turn_id)+ .bind(&input.kwant_id)+ .bind(&input.tool_name)+ .bind(serde_json::to_string(&input.parameters)?)+ .execute(&self.pool)+ .await?;+ Ok(id)+ }+pub async fn save_auto_allowed(&self, input: &super::models::NewApproval) -> Result<String, DbError> {let id = uuid::Uuid::new_v4().to_string();sqlx::query(diff --git a/src/db/dev_prepush.rs b/src/db/dev_prepush.rsindex 3937464a..cf1b7d3b 100644--- a/src/db/dev_prepush.rs+++ b/src/db/dev_prepush.rs@@ -25,10 +25,33 @@ const TABLES: &[&str] = &[UNIQUE (space_id, folder, branch, head_sha))","CREATE INDEX IF NOT EXISTS dev_prepush_cards_space ON dev_prepush_cards (space_id, created_at)",+ // 0.9.7: the person's one-time approval of a bot's push, from Retry or Override on a card+ "CREATE TABLE IF NOT EXISTS dev_prepush_grants (+ id TEXT PRIMARY KEY,+ space_id TEXT NOT NULL,+ kwant_id TEXT NOT NULL,+ folder TEXT NOT NULL,+ branch TEXT NOT NULL,+ kind TEXT NOT NULL,+ card_id TEXT NOT NULL,+ granted_at INTEGER NOT NULL,+ expires_at INTEGER NOT NULL,+ used_at INTEGER,+ next_card_id TEXT+ )",+ "CREATE INDEX IF NOT EXISTS dev_prepush_grants_branch ON dev_prepush_grants (space_id, folder, branch, granted_at)",+];++/// Columns added after the first release, as `(name, type)`: added when missing (add-only).+const ADDED_COLUMNS: [(&str, &str); 2] = [+ // 0.9.7: the newer card of the branch that replaced a `superseded` one+ ("superseded_by", "TEXT"),+ // 0.9.7: what a `superseded` card was before (`blocked` or `failed`), for a push of its commit again+ ("superseded_status", "TEXT"),];/// The tables [`Database::delete_dev_mode_of_space`] clears with the rest of Dev mode.-pub const PREPUSH_TABLES: [&str; 1] = ["dev_prepush_cards"];+pub const PREPUSH_TABLES: [&str; 2] = ["dev_prepush_cards", "dev_prepush_grants"];/// kwant is still checking: the push waits.pub const CHECKING: &str = "checking";@@ -46,6 +69,15 @@ pub const PREPUSH_FAILED: &str = "failed";/// The person asked for the checks to run again: the next push of this commit makes a new card,/// back at try 1.pub const RETRIED: &str = "retried";+/// A `blocked` or `failed` card of a branch that a newer card (another commit) replaced: it no+/// longer waits for the person (0.9.7). Pushing its commit again makes it what it was.+pub const SUPERSEDED: &str = "superseded";+/// How long a grant from Retry or Override waits for the push it covers (0.9.7).+pub const GRANT_MS: i64 = 2 * 60 * 60 * 1000;+/// A grant from Retry: the bot's next push of the branch whose card comes back `clear`.+pub const GRANT_RETRY: &str = "retry";+/// A grant from Override: the one push of the overridden commit.+pub const GRANT_OVERRIDE: &str = "override";/// From this many blocked or failed tries in a row, the card needs the person (Mira's P4).pub const NEEDS_YOU_TRIES: i64 = 2;@@ -69,20 +101,240 @@ pub struct PrepushRow {pub tries: i64,pub created_at: i64,pub updated_at: i64,+ /// The newer card that replaced it, when `superseded`.+ pub superseded_by: Option<String>,+ /// What it was before it was `superseded` (`blocked` or `failed`).+ pub superseded_status: Option<String>,+}++/// The person's one-time approval of a bot's push (0.9.7): Retry covers the next push of the+/// branch whose card is `clear`, Override the one push of its commit. Used at most once, and only+/// until `expires_at`.+#[derive(Debug, Clone, FromRow, PartialEq)]+pub struct PrepushGrantRow {+ pub id: String,+ pub space_id: String,+ pub kwant_id: String,+ pub folder: String,+ pub branch: String,+ /// [`GRANT_RETRY`] or [`GRANT_OVERRIDE`].+ pub kind: String,+ /// The card the person pressed.+ pub card_id: String,+ pub granted_at: i64,+ pub expires_at: i64,+ pub used_at: Option<i64>,+ /// The newest card a push of the branch made while the grant waited, then the card of the+ /// push it let go.+ pub next_card_id: Option<String>,}fn now_ms() -> i64 {chrono::Utc::now().timestamp_millis()}-const COLS: &str =- "id, space_id, kwant_id, folder, branch, head_sha, status, card, overridden_by, overridden_at, override_reason, tries, created_at, updated_at";+const COLS: &str = "id, space_id, kwant_id, folder, branch, head_sha, status, card, overridden_by, overridden_at, override_reason, tries, created_at, \+ updated_at, superseded_by, superseded_status";++const GRANT_COLS: &str = "id, space_id, kwant_id, folder, branch, kind, card_id, granted_at, expires_at, used_at, next_card_id";impl Database {pub(super) async fn migrate_prepush(&self) -> Result<(), DbError> {for sql in TABLES {sqlx::query(sql).execute(&self.pool).await?;}+ for (name, kind) in ADDED_COLUMNS {+ let has: Option<(String,)> =+ sqlx::query_as("SELECT name FROM pragma_table_info('dev_prepush_cards') WHERE name = ?").bind(name).fetch_optional(&self.pool).await?;+ if has.is_none() {+ sqlx::query(&format!("ALTER TABLE dev_prepush_cards ADD COLUMN {name} {kind}")).execute(&self.pool).await?;+ }+ }+ // Cards from before 0.9.7: only the newest waiting card of each branch can need the person+ self.collapse_prepush_cards().await?;+ Ok(())+ }++ /// Supersedes every `blocked` or `failed` card that isn't the newest waiting card of its+ /// `(space, folder, branch)`, pointing it at that one (0.9.7). Runs on every start, so cards+ /// saved before superseding existed collapse too; doing it again changes nothing. The number+ /// of cards it superseded.+ pub async fn collapse_prepush_cards(&self) -> Result<u64, DbError> {+ let r = sqlx::query(+ "WITH ranked AS (+ SELECT id, FIRST_VALUE(id) OVER w AS newest, ROW_NUMBER() OVER w AS n+ FROM dev_prepush_cards WHERE status IN ('blocked', 'failed')+ WINDOW w AS (PARTITION BY space_id, folder, branch ORDER BY created_at DESC, rowid DESC)+ )+ UPDATE dev_prepush_cards+ SET superseded_status = status, status = 'superseded',+ superseded_by = (SELECT newest FROM ranked WHERE ranked.id = dev_prepush_cards.id), updated_at = ?+ WHERE id IN (SELECT id FROM ranked WHERE n > 1)",+ )+ .bind(now_ms())+ .execute(&self.pool)+ .await?;+ Ok(r.rows_affected())+ }++ /// Card `newer` was made (or made waiting again) for its branch: every other `blocked` or+ /// `failed` card of the same `(space, folder, branch)` with another commit becomes+ /// `superseded` by it (0.9.7). The cards it changed, to notify.+ pub async fn supersede_prepush_cards_beside(&self, newer: &PrepushRow) -> Result<Vec<PrepushRow>, DbError> {+ let ids: Vec<(String,)> = sqlx::query_as(+ "SELECT id FROM dev_prepush_cards WHERE space_id = ? AND folder = ? AND branch = ? AND head_sha != ? AND id != ? AND status IN ('blocked', 'failed')",+ )+ .bind(&newer.space_id)+ .bind(&newer.folder)+ .bind(&newer.branch)+ .bind(&newer.head_sha)+ .bind(&newer.id)+ .fetch_all(&self.pool)+ .await?;+ let mut out = Vec::new();+ for (id,) in ids {+ let r = sqlx::query(+ "UPDATE dev_prepush_cards SET superseded_status = status, status = 'superseded', superseded_by = ?, updated_at = ?+ WHERE id = ? AND status IN ('blocked', 'failed')",+ )+ .bind(&newer.id)+ .bind(now_ms())+ .bind(&id)+ .execute(&self.pool)+ .await?;+ if r.rows_affected() > 0 {+ if let Some(row) = self.prepush_card(&id).await? {+ out.push(row);+ }+ }+ }+ Ok(out)+ }++ /// A bot pushes the commit of a `superseded` card again: it is what it was before (`blocked`+ /// or `failed`) and waits for the person again. The card, or `None` when it wasn't superseded.+ pub async fn revive_superseded_prepush_card(&self, id: &str) -> Result<Option<PrepushRow>, DbError> {+ let r = sqlx::query(+ "UPDATE dev_prepush_cards SET status = COALESCE(superseded_status, 'blocked'), superseded_by = NULL, superseded_status = NULL, updated_at = ?+ WHERE id = ? AND status = 'superseded'",+ )+ .bind(now_ms())+ .bind(id)+ .execute(&self.pool)+ .await?;+ if r.rows_affected() == 0 {+ return Ok(None);+ }+ self.prepush_card(id).await+ }++ /// Records the person's grant on `card` (Retry or Override, see [`PrepushGrantRow`]), for+ /// the card's bot, folder and branch, waiting [`GRANT_MS`]. Any grant of theirs on that branch+ /// still waiting ends now, so only one push is ever covered.+ pub async fn add_prepush_grant(&self, card: &PrepushRow, kind: &str) -> Result<PrepushGrantRow, DbError> {+ let now = now_ms();+ let id = format!("pg_{}", uuid::Uuid::new_v4().simple());+ let mut tx = self.pool.begin().await?;+ sqlx::query(+ "UPDATE dev_prepush_grants SET expires_at = ? WHERE space_id = ? AND kwant_id = ? AND folder = ? AND branch = ? AND used_at IS NULL AND expires_at > ?",+ )+ .bind(now)+ .bind(&card.space_id)+ .bind(&card.kwant_id)+ .bind(&card.folder)+ .bind(&card.branch)+ .bind(now)+ .execute(&mut *tx)+ .await?;+ sqlx::query(+ "INSERT INTO dev_prepush_grants (id, space_id, kwant_id, folder, branch, kind, card_id, granted_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",+ )+ .bind(&id)+ .bind(&card.space_id)+ .bind(&card.kwant_id)+ .bind(&card.folder)+ .bind(&card.branch)+ .bind(kind)+ .bind(&card.id)+ .bind(now)+ .bind(now + GRANT_MS)+ .execute(&mut *tx)+ .await?;+ tx.commit().await?;+ self.prepush_grant(&id).await?.ok_or_else(|| DbError::Sqlx(sqlx::Error::RowNotFound))+ }++ pub async fn prepush_grant(&self, id: &str) -> Result<Option<PrepushGrantRow>, DbError> {+ Ok(sqlx::query_as(&format!("SELECT {GRANT_COLS} FROM dev_prepush_grants WHERE id = ?")).bind(id).fetch_optional(&self.pool).await?)+ }++ /// The grant of `kind` still waiting (unused, not expired) on a bot's branch, newest first.+ pub async fn live_prepush_grant(&self, space_id: &str, kwant_id: &str, folder: &str, branch: &str, kind: &str) -> Result<Option<PrepushGrantRow>, DbError> {+ Ok(sqlx::query_as(&format!(+ "SELECT {GRANT_COLS} FROM dev_prepush_grants+ WHERE space_id = ? AND kwant_id = ? AND folder = ? AND branch = ? AND kind = ? AND used_at IS NULL AND expires_at > ?+ ORDER BY granted_at DESC, rowid DESC LIMIT 1"+ ))+ .bind(space_id)+ .bind(kwant_id)+ .bind(folder)+ .bind(branch)+ .bind(kind)+ .bind(now_ms())+ .fetch_optional(&self.pool)+ .await?)+ }++ /// Points a waiting grant at `card_id`, the newest card a push of its branch made.+ pub async fn point_prepush_grant(&self, id: &str, card_id: &str) -> Result<(), DbError> {+ sqlx::query("UPDATE dev_prepush_grants SET next_card_id = ? WHERE id = ? AND used_at IS NULL").bind(card_id).bind(id).execute(&self.pool).await?;+ Ok(())+ }++ /// Uses grant `id` for the push of card `card_id`: at most once, and only before it expires.+ /// False when another push used it first or it expired (the push then asks as usual).+ pub async fn use_prepush_grant(&self, id: &str, card_id: &str) -> Result<bool, DbError> {+ let now = now_ms();+ let r = sqlx::query("UPDATE dev_prepush_grants SET used_at = ?, next_card_id = ? WHERE id = ? AND used_at IS NULL AND expires_at > ?")+ .bind(now)+ .bind(card_id)+ .bind(id)+ .bind(now)+ .execute(&self.pool)+ .await?;+ Ok(r.rows_affected() > 0)+ }++ /// The newest grant of a card: the one the person pressed on it, or the one that followed the+ /// bot's push to it.+ pub async fn prepush_grant_of_card(&self, card_id: &str) -> Result<Option<PrepushGrantRow>, DbError> {+ Ok(sqlx::query_as(&format!(+ "SELECT {GRANT_COLS} FROM dev_prepush_grants WHERE card_id = ? OR next_card_id = ? ORDER BY granted_at DESC, rowid DESC LIMIT 1"+ ))+ .bind(card_id)+ .bind(card_id)+ .fetch_optional(&self.pool)+ .await?)+ }++ /// A space's grants, newest first, at most `limit`.+ pub async fn prepush_grants(&self, space_id: &str, limit: i64) -> Result<Vec<PrepushGrantRow>, DbError> {+ Ok(sqlx::query_as(&format!("SELECT {GRANT_COLS} FROM dev_prepush_grants WHERE space_id = ? ORDER BY granted_at DESC, rowid DESC LIMIT ?"))+ .bind(space_id)+ .bind(limit)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Moves grant `id`'s clock back by `ms`, for tests of a grant that expired.+ #[doc(hidden)]+ pub async fn age_prepush_grant(&self, id: &str, ms: i64) -> Result<(), DbError> {+ sqlx::query("UPDATE dev_prepush_grants SET granted_at = granted_at - ?, expires_at = expires_at - ? WHERE id = ?")+ .bind(ms)+ .bind(ms)+ .bind(id)+ .execute(&self.pool)+ .await?;Ok(())}diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex bc1525a9..707a83e0 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -396,11 +396,12 @@ pub trait ToolApprover: Send + Sync {}/// The pre-push card (B2) for an MCP call that writes to a GitHub branch: `Ok` with the- /// overridden cards it goes on (empty: not such a write, or nothing to use up), else the+ /// overridden cards it goes on and the person's grant that covers it (empty: not such a+ /// write, or nothing to use up), else the/// text the bot gets back instead of the call running. Asked before [`decide`](Self::decide)./// Default: no gate.- async fn prepush_gate(&self, _request: &ToolApprovalRequest) -> Result<Vec<String>, String> {- Ok(Vec::new())+ async fn prepush_gate(&self, _request: &ToolApprovalRequest) -> Result<PrepushPass, String> {+ Ok(PrepushPass::default())}/// Uses up the overrides [`prepush_gate`](Self::prepush_gate) found, once the call is@@ -408,6 +409,36 @@ pub trait ToolApprover: Send + Sync {async fn prepush_use(&self, _overrides: &[String]) -> Option<String> {None}++ /// [`decide`](Self::decide) for a push the person's Retry or Override on a pre-push card+ /// already approved (`grant`, 0.9.7): the ordinary approval card is skipped and the grant used+ /// up, but the payment floor, the production floor and Flight School still ask as in+ /// [`decide`](Self::decide). Default: `grant` changes nothing.+ async fn decide_granted(&self, request: ToolApprovalRequest, _grant: &PrepushGrant) -> ApprovalOutcome {+ self.decide(request).await+ }+}++/// The person's one-time approval of a bot's push, from Retry or Override on a pre-push card+/// (0.9.7, `dev_prepush_grants`).+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct PrepushGrant {+ pub id: String,+ /// `retry` or `override`.+ pub kind: String,+ /// The card the person pressed.+ pub pressed_card_id: String,+ /// The card of the push it covers (clear, or the overridden card itself).+ pub card_id: String,+}++/// What [`ToolApprover::prepush_gate`] found for a call that may run.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct PrepushPass {+ /// The `overridden` cards it goes on, for [`ToolApprover::prepush_use`].+ pub overrides: Vec<String>,+ /// The person's grant that covers it, for [`ToolApprover::decide_granted`].+ pub grant: Option<PrepushGrant>,}/// What became of a call that may have needed a card.diff --git a/src/mcp/session.rs b/src/mcp/session.rsindex eb28f1ee..95601981 100644--- a/src/mcp/session.rs+++ b/src/mcp/session.rs@@ -252,11 +252,15 @@ impl McpToolSession {// B2: a write to a GitHub branch waits for its pre-push card before any card or rulematch self.ctx.approver.prepush_gate(&req).await {Err(why) => ("denied", why),- Ok(overrides) => {- let outcome = self.ctx.approver.decide(req).await;+ Ok(pass) => {+ // A push the person's Retry or Override covers skips the ordinary card (0.9.7)+ let outcome = match &pass.grant {+ Some(g) => self.ctx.approver.decide_granted(req, g).await,+ None => self.ctx.approver.decide(req).await,+ };if !outcome.allowed() {(outcome.record_status(), outcome.refusal_text().to_string())- } else if let Some(why) = self.ctx.approver.prepush_use(&overrides).await {+ } else if let Some(why) = self.ctx.approver.prepush_use(&pass.overrides).await {("denied", why)} else {match client.call_tool(&t.tool.name, arguments.clone()).await {diff --git a/src/server/computer.rs b/src/server/computer.rsindex c661b6df..f47e82a8 100644--- a/src/server/computer.rs+++ b/src/server/computer.rs@@ -276,19 +276,32 @@ async fn local_shell_approvals(state: &AppState, target_id: &str) -> String {/// Asks the person before a shell command runs on their own computer, with no conversation to/// remember "always allow" in (see [`approve_local_shell_in`]).pub async fn approve_local_shell(state: &AppState, target_id: &str, command: &str, cwd: &Path) -> bool {- approve_local_shell_in(state, target_id, command, cwd, None).await+ approve_local_shell_with(state, target_id, command, cwd, None, None).await+}++/// [`approve_local_shell`] for a push the person's Retry or Override on a pre-push card may+/// already have approved (0.9.7): with `grant`, no card unless a floor asks.+pub async fn approve_local_shell_granted(state: &AppState, target_id: &str, command: &str, cwd: &Path, grant: Option<&crate::mcp::PrepushGrant>) -> bool {+ approve_local_shell_with(state, target_id, command, cwd, None, grant).await}/// Asks the person before a shell command runs on their own computer. Approvals `off` run it;/// "Ask only when risky" runs it when [`crate::mcp::shell_risk`] finds it safe in `cwd`, and/// remembers "Always this session" for `execute_shell` in `conversation`. Under `ask` every/// command asks and "always allow" counts for this one command only.-pub async fn approve_local_shell_in(+pub async fn approve_local_shell_in(state: &AppState, target_id: &str, command: &str, cwd: &Path, conversation: Option<&str>) -> bool {+ approve_local_shell_with(state, target_id, command, cwd, conversation, None).await+}++/// [`approve_local_shell_in`]; a `grant` (0.9.7) runs the command with no card when the payment+/// floor, Flight School and the production floor don't ask, and is used up.+async fn approve_local_shell_with(state: &AppState,target_id: &str,command: &str,cwd: &Path,conversation: Option<&str>,+ grant: Option<&crate::mcp::PrepushGrant>,) -> bool {use crate::db::approval_modes::{OFF, SMART};let mode = local_shell_approvals(state, target_id).await;@@ -339,6 +352,18 @@ pub async fn approve_local_shell_in(}return false;}+ // The person's Retry or Override approved this push already: no card, and the grant is used up+ if let Some(g) = grant.filter(|_| payment.is_none() && tier.is_none() && floor.is_none()) {+ if super::dev::prepush::use_grant(&state.db, &state.event_sender, g).await {+ tracing::info!(target = %target_id, grant = %g.id, card = %g.pressed_card_id, "ran a local push the person's {} approved", g.kind);+ details["prepush_grant"] = super::mcp_runtime::grant_details(g);+ let record = NewApproval { turn_id: String::new(), kwant_id: target_id.to_string(), tool_name: "execute_shell".into(), parameters: details };+ if let Err(e) = state.db.save_granted(&record).await {+ tracing::warn!(error = %e, "could not record a local push the person's grant approved");+ }+ return true;+ }+ }if let Some(conversation) = remembered {if state.broker.is_allowed_for_session(target_id, conversation, "execute_shell").await {return true;diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 67fa66b5..772b2eba 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -530,6 +530,14 @@ impl ToolApprover for SelfToolsApprover {async fn tier_gate(&self, req: &ToolApprovalRequest) -> Option<String> {self.inner.tier_gate(req).await}++ /// A push the person's grant covers is never one of kwant's own tools (0.9.7)+ async fn decide_granted(&self, req: ToolApprovalRequest, grant: &crate::mcp::PrepushGrant) -> crate::mcp::ApprovalOutcome {+ if req.server == SELF_SERVER_NAME {+ return self.decide(req).await;+ }+ self.inner.decide_granted(req, grant).await+ }}/// The turn's id when it read outside text: its notes land `outside`/`proposed` in the Truth Ledger.diff --git a/src/server/dev/prepush.rs b/src/server/dev/prepush.rsindex 1f74fd7b..0d57d406 100644--- a/src/server/dev/prepush.rs+++ b/src/server/dev/prepush.rs@@ -26,9 +26,11 @@use super::facts::{Author, CiState, DevFacts, FileDiff, Kind, KwantRef, Links};use super::git::{GitError, Repo};use super::scan::{self, Finding, State, Tile};-use crate::db::dev_prepush::{PrepushRow, BLOCKED, CHECKING, CLEAR, NEEDS_YOU_TRIES, OVERRIDDEN, PREPUSH_FAILED, PUSHED, RETRIED};+use crate::db::dev_prepush::{+ PrepushGrantRow, PrepushRow, BLOCKED, CHECKING, CLEAR, GRANT_OVERRIDE, GRANT_RETRY, NEEDS_YOU_TRIES, OVERRIDDEN, PREPUSH_FAILED, PUSHED, RETRIED, SUPERSEDED,+};use crate::drivers::events::RuntimeEvent;-use crate::mcp::prod_floor;+use crate::mcp::{prod_floor, PrepushGrant};use crate::server::AppState;use serde_json::{json, Value};use std::collections::BTreeMap;@@ -303,6 +305,7 @@ fn deny_text_for(row: &PrepushRow) -> String {)}RETRIED => format!("The person asked kwant to check this push of {branch} again (card {id}). Nothing was pushed. Run the same push again."),+ SUPERSEDED => format!("Pre-push card {id} for {branch} was replaced by a newer push of the branch. Nothing was pushed. Push your newest commit."),_ => format!("kwant's pre-push card {id} for {branch} doesn't let this push go. Nothing was pushed."),}}@@ -320,6 +323,12 @@ pub struct Pass {/// <sha>:refs/heads/<branch>`), so a commit made by a parallel call in the same turn isn't/// what goes. `None` for a shape kwant doesn't rewrite ([`pin`]).pub pinned: Option<String>,+ /// The person's Retry or Override that approved this push already (0.9.7): the approver skips+ /// the ordinary card and uses it up ([`ToolApprover::decide_granted`]). Only for a command or+ /// call that makes one push.+ ///+ /// [`ToolApprover::decide_granted`]: crate::mcp::ToolApprover::decide_granted+ pub grant: Option<PrepushGrant>,}/// Whether `command` may run now (`Ok`: no push, Dev mode off, the production floor asks@@ -361,6 +370,7 @@ pub async fn check_command(state: &AppState, kwant_id: &str, command: &str, fold}if one {pass.pinned = pin(command, &checked.head_sha, &checked.branch, local_src);+ pass.grant = checked.grant;}}Ok(pass)@@ -458,6 +468,8 @@ struct Checked {status: String,branch: String,head_sha: String,+ /// The person's grant that covers this push, if one does ([`grant_for`]).+ grant: Option<PrepushGrant>,}/// The card a push goes on, and whether its source is `HEAD` or a local branch (see [`pin`]).@@ -520,6 +532,15 @@ async fn gate_card(// The person asked for the checks again: a new card, back at try 1row = None;fresh_start = true;+ } else if r.status == SUPERSEDED {+ // The bot pushes an older commit again: its card waits for the person again, and is+ // now the branch's one waiting card+ if let Some(again) = state.db.revive_superseded_prepush_card(&r.id).await.ok().flatten() {+ notify(state, &again);+ supersede_beside(state, &again).await;+ return Err(deny_text(&again));+ }+ return Err(deny_text(r));} else if r.status == PUSHED {// The override let one push go: this one waits for the person againlet again = state.db.reblock_pushed_prepush_card(&r.id).await.ok().flatten();@@ -544,6 +565,11 @@ async fn gate_card(match made {Some(r) => {notify(state, &r);+ supersede_beside(state, &r).await;+ // The person's Retry follows the bot's push to its new card, for the card's story+ if let Ok(Some(g)) = state.db.live_prepush_grant(space_id, kwant_id, &key, &branch, GRANT_RETRY).await {+ let _ = state.db.point_prepush_grant(&g.id, &r.id).await;+ }tokio::spawn(check(state.clone(), r.clone(), src(), base.to_string()));r}@@ -553,11 +579,58 @@ async fn gate_card(}};match row.status.as_str() {- CLEAR | OVERRIDDEN => Ok(Checked { id: row.id, status: row.status, branch, head_sha: sha }),+ CLEAR | OVERRIDDEN => {+ let grant = grant_for(state, kwant_id, &row).await;+ Ok(Checked { id: row.id, status: row.status, branch, head_sha: sha, grant })+ }_ => Err(deny_text(&row)),}}+/// The person's grant that covers a push going on `card` (0.9.7), if one does: for a `clear`+/// card, the bot's Retry grant on the branch, made before the card was; for an `overridden` card,+/// the Override grant the person made on that card. Unused and not expired in both cases.+async fn grant_for(state: &AppState, kwant_id: &str, card: &PrepushRow) -> Option<PrepushGrant> {+ let (kind, row) = match card.status.as_str() {+ CLEAR => (GRANT_RETRY, state.db.live_prepush_grant(&card.space_id, kwant_id, &card.folder, &card.branch, GRANT_RETRY).await.ok().flatten()?),+ OVERRIDDEN => (GRANT_OVERRIDE, state.db.live_prepush_grant(&card.space_id, kwant_id, &card.folder, &card.branch, GRANT_OVERRIDE).await.ok().flatten()?),+ _ => return None,+ };+ let covers = match kind {+ GRANT_RETRY => row.granted_at <= card.created_at,+ _ => row.card_id == card.id,+ };+ covers.then(|| PrepushGrant { id: row.id, kind: row.kind, pressed_card_id: row.card_id, card_id: card.id.clone() })+}++/// Makes the other waiting cards of `newer`'s branch `superseded` and tells open pages (0.9.7).+async fn supersede_beside(state: &AppState, newer: &PrepushRow) {+ match state.db.supersede_prepush_cards_beside(newer).await {+ Ok(rows) => rows.iter().for_each(|r| notify(state, r)),+ Err(e) => tracing::warn!(card = %newer.id, "dev: could not supersede older pre-push cards: {e}"),+ }+}++/// Uses the person's grant for the push it covers (0.9.7): true when this push may go without+/// the ordinary card; false when another push used it first or it expired (the push asks as+/// usual). Tells open pages about the cards it shows on.+pub async fn use_grant(db: &crate::db::Database, events: &tokio::sync::broadcast::Sender<RuntimeEvent>, grant: &PrepushGrant) -> bool {+ if !db.use_prepush_grant(&grant.id, &grant.card_id).await.unwrap_or(false) {+ return false;+ }+ for id in [&grant.pressed_card_id, &grant.card_id] {+ if let Ok(Some(row)) = db.prepush_card(id).await {+ let _ = events.send(RuntimeEvent::DevPrepush { space_id: row.space_id.clone(), id: row.id.clone(), kwant_id: row.kwant_id.clone(), status: row.status.clone() });+ }+ }+ true+}++/// The line the side-effect ledger and the approval record keep for a push a grant let go.+pub fn grant_note(grant: &PrepushGrant) -> String {+ format!("approved by the person's {} on pre-push card {}", grant.kind, grant.pressed_card_id)+}+async fn resolve(repo: &Repo, src: &str) -> Result<String, GitError> {if src == "HEAD" {repo.head().await@@ -920,6 +993,7 @@ pub async fn check_mcp(state: &AppState, kwant_id: &str, server: &str, tool: &stif checked.status == OVERRIDDEN {pass.overrides.push(checked.id);}+ pass.grant = checked.grant;Ok(pass)}@@ -1100,8 +1174,22 @@ pub fn parse_semgrep(json_text: &str, prefix: &str) -> Option<Vec<Finding>> {// ---------------------------------------------------------------------------------------------// Routes (person only: `/api/spaces/:id/dev/…` and `/api/dev/…` are in `auth::person_only`)-/// A card as the API returns it (fresh-eyes-audit.md §4.2).-pub fn card_json(row: &PrepushRow) -> Value {+/// A grant as a card shows it (0.9.7): `{kind, at, expires_at, used_at, card_id, next_card_id}`,+/// all times ms epoch. `card_id` is the card the person pressed, `next_card_id` the newest card+/// the bot's push made after it (then the one it let go).+pub fn grant_json(g: &PrepushGrantRow) -> Value {+ json!({"kind": g.kind, "at": g.granted_at, "expires_at": g.expires_at, "used_at": g.used_at, "card_id": g.card_id, "next_card_id": g.next_card_id})+}++/// [`card_json`] with the card's grant read from the database.+pub async fn card_json_of(state: &AppState, row: &PrepushRow) -> Value {+ let grant = state.db.prepush_grant_of_card(&row.id).await.ok().flatten();+ card_json(row, grant.as_ref())+}++/// A card as the API returns it (fresh-eyes-audit.md §4.2), with `grant`: the person's grant+/// pressed on this card or followed to it (0.9.7), else null.+pub fn card_json(row: &PrepushRow, grant: Option<&PrepushGrantRow>) -> Value {let card = row.card.as_deref().and_then(|c| serde_json::from_str::<Value>(c).ok());let waiting = row.status == BLOCKED || row.status == PREPUSH_FAILED;let no_change = card.as_ref().is_some_and(|c| c["no_change"] == json!(true));@@ -1109,6 +1197,8 @@ pub fn card_json(row: &PrepushRow) -> Value {"id": row.id,"space_id": row.space_id,"kwant_id": row.kwant_id,+ // Needs-you dedupe is per (bot, folder, branch), as in the DB row+ "folder": row.folder,"branch": row.branch,"head_sha": row.head_sha,"base_sha": card.as_ref().map(|c| c["base_sha"].clone()),@@ -1127,6 +1217,10 @@ pub fn card_json(row: &PrepushRow) -> Value {"auto_retried": card.as_ref().is_some_and(|c| c["auto_retried"] == json!(true)),"last_override": row.overridden_by.as_ref().filter(|_| row.status != OVERRIDDEN && row.status != PUSHED).map(|by| json!({"by": by, "reason": row.override_reason, "at": row.overridden_at})),"card": card,+ // 0.9.7: the person's Retry or Override grant on this card, and the card that replaced a+ // `superseded` one+ "grant": grant.map(grant_json),+ "superseded_by": row.superseded_by,"overridden_by": row.overridden_by,"overridden_at": row.overridden_at,"created_at": row.created_at,@@ -1224,10 +1318,14 @@ pub async fn list(Ok(s) => s,Err(r) => return r,};- match state.db.prepush_cards(space.as_str(), 50).await {- Ok(rows) => axum::Json(json!({"cards": rows.iter().map(card_json).collect::<Vec<_>>()})).into_response(),- Err(e) => super::routes::internal(e),- }+ let rows = match state.db.prepush_cards(space.as_str(), 50).await {+ Ok(rows) => rows,+ Err(e) => return super::routes::internal(e),+ };+ // Newest first: a card shows the newest grant pressed on it or followed to it+ let grants = state.db.prepush_grants(space.as_str(), 200).await.unwrap_or_default();+ let of = |row: &PrepushRow| grants.iter().find(|g| g.card_id == row.id || g.next_card_id.as_deref() == Some(row.id.as_str()));+ axum::Json(json!({"cards": rows.iter().map(|r| card_json(r, of(r))).collect::<Vec<_>>()})).into_response()}#[allow(clippy::result_large_err)]@@ -1250,7 +1348,7 @@ pub async fn get_one() -> axum::response::Response {use axum::response::IntoResponse;match row_for(&state, &headers, &id).await {- Ok(row) => axum::Json(card_json(&row)).into_response(),+ Ok(row) => axum::Json(card_json_of(&state, &row).await).into_response(),Err(r) => r,}}@@ -1282,8 +1380,12 @@ pub async fn override_card(let reason: String = reason.chars().take(MAX_REASON_CHARS).collect();match state.db.override_prepush_card(&row.id, "person", &reason).await {Ok(Some(r)) => {+ // 0.9.7: the one push the override lets go doesn't ask the person again+ if let Err(e) = state.db.add_prepush_grant(&r, GRANT_OVERRIDE).await {+ tracing::warn!(card = %r.id, "dev: could not save the override's grant: {e}");+ }notify(&state, &r);- axum::Json(card_json(&r)).into_response()+ axum::Json(card_json_of(&state, &r).await).into_response()}Ok(None) => route_error(axum::http::StatusCode::CONFLICT, "conflict", "only a blocked or failed card can be overridden"),Err(e) => super::routes::internal(e),@@ -1305,8 +1407,13 @@ pub async fn retry_card(};match state.db.retry_prepush_card(&row.id).await {Ok(Some(r)) => {+ // 0.9.7: the bot's next push of the branch goes without asking again, once its card+ // comes back clear (within GRANT_MS)+ if let Err(e) = state.db.add_prepush_grant(&r, GRANT_RETRY).await {+ tracing::warn!(card = %r.id, "dev: could not save the retry's grant: {e}");+ }notify(&state, &r);- axum::Json(card_json(&r)).into_response()+ axum::Json(card_json_of(&state, &r).await).into_response()}Ok(None) => route_error(axum::http::StatusCode::CONFLICT, "conflict", "only a blocked or failed card can be checked again"),Err(e) => super::routes::internal(e),@@ -1382,6 +1489,8 @@ mod tests {tries: 1,created_at: 0,updated_at: 0,+ superseded_by: None,+ superseded_status: None,};let failed = failed_card(&row, "no main here");let rows = checks(PREPUSH_FAILED, Some(&failed));@@ -1446,6 +1555,7 @@ mod tests {let row = PrepushRow {id: "pp".into(), space_id: "s".into(), kwant_id: "k".into(), folder: "/f".into(), branch: "juno-x".into(), head_sha: "a".repeat(40),status: CHECKING.into(), card: None, overridden_by: None, overridden_at: None, override_reason: None, tries: 1, created_at: 0, updated_at: 0,+ superseded_by: None, superseded_status: None,};assert!(errored(PREPUSH_FAILED, &failed_card(&row, "the repo's git couldn't be read")));let mut slow = failed_card(&row, "the checks took longer than 12 minutes");@@ -1711,9 +1821,17 @@ mod tests {tries: 1,created_at: 0,updated_at: 0,+ superseded_by: None,+ superseded_status: None,}}+ #[test]+ fn card_json_names_the_folder_for_needs_you_dedupe() {+ let v = card_json(&row(BLOCKED, None), None);+ assert_eq!((v["kwant_id"].as_str(), v["folder"].as_str(), v["branch"].as_str()), (Some("k"), Some("/f"), Some("juno-x")));+ }+#[test]fn the_bot_is_told_why_and_how_to_clear_it() {assert!(deny_text(&row(CHECKING, None)).contains("Run the same push again"));diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 6aa22505..dbf0d2fc 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -186,9 +186,59 @@ impl ToolApprover for BrokerApprover {// Boxed: keeps this future (and every caller's) smallBox::pin(super::missions::flight_school::tier_gate(&self.db, &self.data_dir, req)).await}++ async fn decide_granted(&self, req: ToolApprovalRequest, grant: &mcp::PrepushGrant) -> ApprovalOutcome {+ match Box::pin(self.granted(&req, grant)).await {+ Some(approval_id) => {+ if super::missions::truth_ledger::request_reads_outside(&req) {+ super::missions::truth_ledger::taint(&req.turn_id);+ }+ let note = super::dev::prepush::grant_note(grant);+ super::missions::checkpoints::log_call_noted(&self.db, &self.data_dir, &req, "approved", approval_id.as_deref(), Some(¬e)).await;+ ApprovalOutcome::Allowed+ }+ None => self.decide(req).await,+ }+ }}impl BrokerApprover {+ /// A push the person's Retry or Override covers (0.9.7): uses the grant up and records the call+ /// as approved by it (`Some(approval id)`), with no card. `None` when it must ask as usual: the+ /// payment floor, Flight School or the production floor wants a card (exactly as in+ /// [`Self::classified`]), it names kwnt's secrets, or the grant was used or expired.+ async fn granted(&self, req: &ToolApprovalRequest, grant: &mcp::PrepushGrant) -> Option<Option<String>> {+ if req.payment.is_some() || mcp::payment_floor::reason(req, None).is_some() {+ return None;+ }+ if self.tier_gate(req).await.is_some() || super::dev::floor::for_call(&self.db, req).await.is_some() {+ return None;+ }+ let cwd = req.builtin.as_ref().and_then(|b| b.cwd.as_deref()).map(std::path::Path::new);+ if crate::sandbox::credentials::call_touches_kwnt_secrets(&req.arguments, cwd) {+ return None;+ }+ if !super::dev::prepush::use_grant(&self.db, &self.events, grant).await {+ return None;+ }+ tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, grant = %grant.id, card = %grant.pressed_card_id, "ran a push the person's {} approved", grant.kind);+ let mut details = match &req.builtin {+ Some(b) => json!({"source": "claude_builtin", "tool": req.tool, "arguments": req.arguments, "cwd": b.cwd, "outside_folder": b.outside_folder}),+ None => json!({"source": "mcp", "server": req.server, "tool": req.tool, "arguments": req.arguments}),+ };+ details["kwant_id"] = json!(req.kwant_id);+ details["kwant_name"] = json!(req.kwant_name);+ details["prepush_grant"] = grant_details(grant);+ let record = NewApproval { turn_id: req.turn_id.clone(), kwant_id: req.kwant_id.clone(), tool_name: req.tool_name.clone(), parameters: details };+ match self.db.save_granted(&record).await {+ Ok(id) => Some(Some(id)),+ Err(e) => {+ tracing::warn!(error = %e, "could not record a push the person's grant approved");+ Some(None)+ }+ }+ }+/// [`ToolApprover::decide`], with the ledger's decision class and the card's id.async fn classified(&self, req: ToolApprovalRequest) -> (ApprovalOutcome, &'static str, Option<String>) {// Approvals the person switched off: run, and keep a record of what ran. A setting that@@ -743,15 +793,32 @@ impl ToolApprover for PrepushApprover {self.inner.tier_gate(req).await}- async fn prepush_gate(&self, req: &ToolApprovalRequest) -> Result<Vec<String>, String> {- Box::pin(super::dev::prepush::check_mcp(&self.state, &req.kwant_id, &req.server, &req.tool, &req.arguments)).await.map(|p| p.overrides)+ async fn prepush_gate(&self, req: &ToolApprovalRequest) -> Result<mcp::PrepushPass, String> {+ Box::pin(super::dev::prepush::check_mcp(&self.state, &req.kwant_id, &req.server, &req.tool, &req.arguments))+ .await+ .map(|p| mcp::PrepushPass { overrides: p.overrides, grant: p.grant })}async fn prepush_use(&self, overrides: &[String]) -> Option<String> {- super::dev::prepush::use_up(&self.state, &super::dev::prepush::Pass { overrides: overrides.to_vec(), pinned: None }).await+ super::dev::prepush::use_up(&self.state, &super::dev::prepush::Pass { overrides: overrides.to_vec(), ..Default::default() }).await+ }++ async fn decide_granted(&self, req: ToolApprovalRequest, grant: &mcp::PrepushGrant) -> ApprovalOutcome {+ self.inner.decide_granted(req, grant).await}}+/// What an approval record keeps about the grant that approved its call (0.9.7).+pub fn grant_details(grant: &mcp::PrepushGrant) -> Value {+ json!({+ "id": grant.id,+ "kind": grant.kind,+ "card_id": grant.pressed_card_id,+ "push_card_id": grant.card_id,+ "note": super::dev::prepush::grant_note(grant),+ })+}+/// [`prepare_turn_with_self`] with [`TurnApprovalOpts`].pub async fn prepare_turn_with_opts(state: &AppState,@@ -949,7 +1016,7 @@ fn noted_request(session: &PermissionSession, tool_name: &str, server: &str, too/// Answers one claude permission prompt. MCP tools from the kwant's own servers get their/// approval card; claude's own tools follow [`mcp::builtin_tools`]; tools from servers the/// kwant doesn't have are denied.-async fn decide(session: &PermissionSession, args: &Value, smart: bool) -> Value {+async fn decide(session: &PermissionSession, args: &Value, smart: bool, grant: Option<&mcp::PrepushGrant>) -> Value {let tool_name = args["tool_name"].as_str().unwrap_or("");let input = args.get("input").cloned().unwrap_or_else(|| json!({}));let tool_use_id = args["tool_use_id"].as_str().unwrap_or("").to_string();@@ -1016,7 +1083,7 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool) -> Value}}};- let approval = session.ctx.approver.decide(ToolApprovalRequest {+ let req = ToolApprovalRequest {kwant_id: session.kwant_id.clone(),kwant_name: session.kwant_name.clone(),turn_id: session.turn_id.clone(),@@ -1027,7 +1094,14 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool) -> Valuebuiltin,smart: verdict,payment: None,- });+ };+ // A push the person's Retry or Override covers skips the ordinary card (0.9.7)+ let approval = async {+ match grant {+ Some(g) => session.ctx.approver.decide_granted(req, g).await,+ None => session.ctx.approver.decide(req).await,+ }+ };// Dropping the approval withdraws its card when the turn ends firstlet outcome = tokio::select! {outcome = approval => outcome,@@ -1107,7 +1181,7 @@ pub async fn permission_endpoint(let decision = match prepush {Err(why) => json!({"behavior": "deny", "message": why}),Ok(pass) => {- let mut decision = decide(&session, args, smart).await;+ let mut decision = decide(&session, args, smart, pass.grant.as_ref()).await;if decision["behavior"] == "allow" {// The override goes with the push that runs, never one the person declinedif let Some(why) = super::dev::prepush::use_up(&state, &pass).await {diff --git a/src/server/missions/checkpoints.rs b/src/server/missions/checkpoints.rsindex 4f1ff61c..f4189676 100644--- a/src/server/missions/checkpoints.rs+++ b/src/server/missions/checkpoints.rs@@ -1078,6 +1078,19 @@ pub fn summary(tool_name: &str, args: &Value) -> String {/// Records one permission decision of a task turn (D9: a turn without a task records nothing).pub async fn log_call(db: &crate::db::Database, data_dir: &FsPath, req: &crate::mcp::ToolApprovalRequest, decision: &'static str, approval_id: Option<&str>) {+ log_call_noted(db, data_dir, req, decision, approval_id, None).await+}++/// [`log_call`] with a note after the call's summary: who approved it, when it wasn't a card+/// (0.9.7: "approved by the person's retry on pre-push card X").+pub async fn log_call_noted(+ db: &crate::db::Database,+ data_dir: &FsPath,+ req: &crate::mcp::ToolApprovalRequest,+ decision: &'static str,+ approval_id: Option<&str>,+ note: Option<&str>,+) {let Ok(Some(task_id)) = db.task_of_turn(&req.kwant_id, &req.turn_id).await else { return };let folder = match db.get_task(&task_id).await {Ok(Some(t)) => super::task_folder_in(db, data_dir, &t).await,@@ -1085,7 +1098,10 @@ pub async fn log_call(db: &crate::db::Database, data_dir: &FsPath, req: &crate::};let effect = effect(req, folder.as_deref());let path = if effect == "workspace" { workspace_path(req, folder.as_deref()) } else { None };- let summary = summary(&req.tool_name, &req.arguments);+ let mut summary = summary(&req.tool_name, &req.arguments);+ if let Some(note) = note {+ summary = format!("{summary} ({note})");+ }if let Err(e) = db.log_tool_call(&req.turn_id, &req.kwant_id, &task_id, &req.tool_name, effect, &summary, decision, approval_id, path.as_deref()).await {tracing::warn!(error = %e, "could not log a tool call");}diff --git a/src/server/routes.rs b/src/server/routes.rsindex 2565727f..9c25a95f 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -6911,7 +6911,7 @@ pub async fn execute_tool(.map_err(crate::tools::ToolError::Execution)?;// What runs (and what the person approves) is the push pinned to the checked commitlet command = pass.pinned.clone().unwrap_or_else(|| command.to_string());- if !super::computer::approve_local_shell(state, team_id.unwrap_or("default"), &command, &workspace).await {+ if !super::computer::approve_local_shell_granted(state, team_id.unwrap_or("default"), &command, &workspace, pass.grant.as_ref()).await {return Err(crate::tools::ToolError::Execution("The person did not approve this command, so it was not run.".into(),));diff --git a/tests/prepush_test.rs b/tests/prepush_test.rsindex 5b2a9364..19fda3c3 100644--- a/tests/prepush_test.rs+++ b/tests/prepush_test.rs@@ -10,7 +10,9 @@ mod common;use base64::Engine;use common::*;-use kwnt::db::dev_prepush::{BLOCKED, CHECKING, CLEAR, OVERRIDDEN, PUSHED};+use kwnt::db::dev_prepush::{BLOCKED, CHECKING, CLEAR, GRANT_MS, OVERRIDDEN, PREPUSH_FAILED, PUSHED, SUPERSEDED};+use kwnt::mcp::{ApprovalOutcome, ToolApprovalRequest, ToolApprover};+use kwnt::server::mcp_runtime::BrokerApprover;use kwnt::drivers::events::RuntimeEvent;use kwnt::server::dev::prepush;use serde_json::{json, Value};@@ -558,9 +560,13 @@ async fn kwants_own_github_tools_go_through_the_pre_push_card() {smart: None,payment: None,};- let overrides = approver.prepush_gate(&req).await.expect("the override lets it go");- assert_eq!(overrides, std::slice::from_ref(&row.id));- assert_eq!(approver.prepush_use(&overrides).await, None);+ let pass = approver.prepush_gate(&req).await.expect("the override lets it go");+ assert_eq!(pass.overrides, std::slice::from_ref(&row.id));+ // 0.9.7: the override is also the person's approval of that one write+ let grant = pass.grant.clone().expect("the override's grant");+ assert_eq!((grant.kind.as_str(), grant.pressed_card_id.as_str(), grant.card_id.as_str()), ("override", row.id.as_str(), row.id.as_str()));+ assert_eq!(approver.decide_granted(req.clone(), &grant).await, kwnt::mcp::ApprovalOutcome::Allowed);+ assert_eq!(approver.prepush_use(&pass.overrides).await, None);assert_eq!(env.state.db.prepush_card(&row.id).await.unwrap().unwrap().status, PUSHED);// The same write again waits for the person again, on the permission prompt toolet d = decision(&call(&env.app, "POST", "/api/mcp/permission/gh-tok", Some(ask(&args))).await.1);@@ -632,3 +638,296 @@ async fn a_real_review_finding_is_never_run_again_on_its_own() {assert_eq!(invocations_with("FOUNDMARK").len(), 1, "one reviewer turn, no second roll");assert!(prepush::gate(&env.state, &env.a, "git push origin juno-found", &folder).await.unwrap().contains("blocked this push"));}++// 0.9.7, prepush-retry brief: the person's Retry or Override is their approval of the one push it+// lets go. The approver below is the real one (cards, floors, Flight School); a card nobody+// answers comes back `Unanswered` after 200 ms.++fn broker(env: &Env) -> BrokerApprover {+ BrokerApprover {+ db: env.state.db.clone(),+ data_dir: env.state.config.data_dir.clone(),+ broker: env.state.broker.clone(),+ events: env.state.event_sender.clone(),+ timeout: std::time::Duration::from_millis(200),+ conversation: env.a.clone(),+ chat: Some(json!({"direct_kwant_id": env.a})),+ always_ask: false,+ }+}++fn bash(env: &Env, turn: &str, command: &str, folder: &Path) -> ToolApprovalRequest {+ ToolApprovalRequest {+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ turn_id: turn.into(),+ tool_name: "Bash".into(),+ server: String::new(),+ tool: "Bash".into(),+ arguments: json!({"command": command, "description": "push", "cwd": folder}),+ builtin: None,+ smart: None,+ payment: None,+ }+}++/// The bot's turn `turn` works on a task, so its calls land in the checkpoints log.+async fn on_a_task(env: &Env, space: &str, turn: &str) -> String {+ let task = format!("tsk_{}", uuid::Uuid::new_v4().simple());+ let now = chrono::Utc::now();+ let at = now.to_rfc3339();+ env.state+ .db+ .exec_raw_for_test(&format!(+ "INSERT INTO tasks (id, space_id, title, state, budget_tokens, source_kind, created_by, created_at, updated_at) \+ VALUES ('{task}', '{space}', 'Fix the widgets', 'ready', 0, 'person', 'person', '{at}', '{at}')"+ ))+ .await+ .unwrap();+ let ms = now.timestamp_millis();+ env.state+ .db+ .exec_raw_for_test(&format!(+ "INSERT INTO agent_claims (id, task_id, kwant_id, turn_id, claimed_at, expires_at) VALUES ('clm_{task}', '{task}', '{}', '{turn}', {ms}, {})",+ env.a,+ ms + 3_600_000+ ))+ .await+ .unwrap();+ // A new task can't start as working; it moves there under the live lease above.+ env.state+ .db+ .exec_raw_for_test(&format!("UPDATE tasks SET state = 'working' WHERE id = '{task}'"))+ .await+ .unwrap();+ task+}++/// The approval cards still waiting on `command`.+async fn waiting_on(env: &Env, command: &str) -> usize {+ let rows = env.state.db.list_approvals(&kwnt::db::spaces::SpaceId::default_space(), Some("waiting"), Some(&env.a)).await.unwrap();+ rows.iter().filter(|r| r.parameters.contains(command)).count()+}++/// A blocked card on `branch`: a commit that switches the test off.+async fn blocked_card(env: &Env, space: &str, folder: &Path, branch: &str, marker: &str) -> kwnt::db::dev_prepush::PrepushRow {+ git(folder, &["checkout", "-q", "-b", branch]);+ commit(folder, "src/widgets.rs", &format!("{}pub fn count() -> u32 {{ 4 }}\n", clean_review(marker)), "Count widgets");+ commit(folder, TEST_FILE, &TEST_BODY.replace("#[test]\n", "#[test]\n#[ignore]\n"), "Skip the slow test");+ let push = format!("git push origin {branch}");+ assert!(prepush::gate(&env.state, &env.a, &push, folder).await.is_some(), "the first push waits for its card");+ let row = settled(env, space, branch).await;+ assert_eq!(row.status, BLOCKED, "{row:?}");+ row+}++#[tokio::test]+async fn a_retry_lets_the_next_clear_push_go_once_with_no_approval_card() {+ let env = setup().await;+ let space = space_of_a(&env).await;+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();+ let folder = repo(&env, "granted");+ let blocked = blocked_card(&env, &space, &folder, "juno-grant", "GRANTMARK").await;+ let push = "git push origin juno-grant";+ let task = on_a_task(&env, &space, "t-grant").await;+ let approver = broker(&env);++ // Without a grant, a clear push still gets the ordinary approval card (approvals ask)+ // The person presses Retry: a grant on the card, unused, for 2 hours+ let (s, v) = call(&env.app, "POST", &format!("/api/dev/prepush/{}/retry", blocked.id), None).await;+ assert_eq!((s.as_u16(), v["status"].as_str()), (200, Some("retried")), "{v}");+ let g = &v["grant"];+ assert_eq!((g["kind"].as_str(), g["card_id"].as_str(), g["used_at"].clone()), (Some("retry"), Some(blocked.id.as_str()), Value::Null), "{v}");+ assert_eq!(g["expires_at"].as_i64().unwrap() - g["at"].as_i64().unwrap(), GRANT_MS, "{v}");++ // The bot fixes the test and pushes: checked first, and a push still checking uses nothing+ let fixed = commit(&folder, TEST_FILE, TEST_BODY, "Bring the test back");+ let why = prepush::check_command(&env.state, &env.a, push, &folder).await.unwrap_err();+ assert!(why.contains("is checking"), "{why}");+ let card = settled_sha(&env, &space, &fixed).await;+ assert_eq!(card.status, CLEAR, "{card:?}");+ let grant_id = env.state.db.prepush_grant_of_card(&blocked.id).await.unwrap().unwrap().id;+ assert_eq!(env.state.db.prepush_grant(&grant_id).await.unwrap().unwrap().used_at, None);++ // Clear: the push goes with no approval card, once+ let pass = prepush::check_command(&env.state, &env.a, push, &folder).await.unwrap();+ let grant = pass.grant.clone().expect("the retry covers the next clear push");+ assert_eq!((grant.kind.as_str(), grant.pressed_card_id.as_str(), grant.card_id.as_str()), ("retry", blocked.id.as_str(), card.id.as_str()));+ let mut rx = env.state.event_sender.subscribe();+ assert_eq!(approver.decide_granted(bash(&env, "t-grant", push, &folder), &grant).await, ApprovalOutcome::Allowed);+ assert_eq!(waiting_on(&env, push).await, 0, "no approval card");+ let mut seen = Vec::new();+ while let Ok(e) = rx.try_recv() {+ if let RuntimeEvent::DevPrepush { id, .. } = e {+ seen.push(id);+ }+ }+ assert!(seen.contains(&blocked.id) && seen.contains(&card.id), "both cards show the grant was used: {seen:?}");+ // The approval record and the checkpoints log say who approved it+ let rows = env.state.db.list_approvals(&kwnt::db::spaces::SpaceId::default_space(), Some("allowed_once"), Some(&env.a)).await.unwrap();+ let rec = rows.iter().find(|r| r.parameters.contains("prepush_grant")).expect("an approval record");+ let details: Value = serde_json::from_str(&rec.parameters).unwrap();+ assert_eq!(details["prepush_grant"]["card_id"], json!(blocked.id), "{details}");+ assert_eq!(details["prepush_grant"]["push_card_id"], json!(card.id), "{details}");+ let note = format!("approved by the person's retry on pre-push card {}", blocked.id);+ assert_eq!(details["prepush_grant"]["note"], json!(note));+ let calls = env.state.db.tool_calls_of(&task).await.unwrap();+ let logged = calls.iter().find(|c| c.summary.contains(¬e)).expect("the checkpoints log names the grant");+ assert_eq!((logged.decision.as_str(), logged.approval_id.as_deref()), ("approved", Some(rec.id.as_str())));++ // Both cards show it: the pressed one and the push's own+ for id in [&blocked.id, &card.id] {+ let (_, v) = call(&env.app, "GET", &format!("/api/dev/prepush/{id}"), None).await;+ assert_eq!(v["grant"]["kind"], "retry", "{v}");+ assert!(v["grant"]["used_at"].is_i64(), "{v}");+ assert_eq!(v["grant"]["next_card_id"], json!(card.id), "{v}");+ }+ let (_, list) = call(&env.app, "GET", &format!("/api/spaces/{space}/dev/prepush"), None).await;+ assert!(list["cards"].as_array().unwrap().iter().all(|c| c["grant"]["kind"] == "retry"), "{list}");++ // A second push in the window gets the ordinary card: the grant is used up+ assert_eq!(prepush::check_command(&env.state, &env.a, push, &folder).await.unwrap().grant, None);+ assert_eq!(approver.decide_granted(bash(&env, "t-grant", push, &folder), &grant).await, ApprovalOutcome::Unanswered, "a used grant asks as usual");+ assert_eq!(waiting_on(&env, push).await, 1);+}++#[tokio::test]+async fn a_grant_never_skips_a_blocked_push_a_floor_or_an_expired_window() {+ let env = setup().await;+ let space = space_of_a(&env).await;+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();+ let folder = repo(&env, "ungranted");+ let blocked = blocked_card(&env, &space, &folder, "juno-nogrant", "NOGRANTMARK").await;+ let push = "git push origin juno-nogrant";+ let approver = broker(&env);+ let (s, _) = call(&env.app, "POST", &format!("/api/dev/prepush/{}/retry", blocked.id), None).await;+ assert_eq!(s.as_u16(), 200);+ let live = env.state.db.prepush_grant_of_card(&blocked.id).await.unwrap().unwrap();++ // The bot pushes again without fixing it: blocked, and the grant stays unused+ let still = commit(&folder, "src/more.rs", "pub fn more() {}\n", "More");+ assert!(prepush::check_command(&env.state, &env.a, push, &folder).await.is_err());+ let again = settled_sha(&env, &space, &still).await;+ assert_eq!(again.status, BLOCKED, "{again:?}");+ let err = prepush::check_command(&env.state, &env.a, push, &folder).await.unwrap_err();+ assert!(err.contains("blocked this push"), "{err}");+ assert_eq!(env.state.db.prepush_grant(&live.id).await.unwrap().unwrap().used_at, None, "a blocked push uses no grant");++ // A push to the protected branch is the production floor's: no grant, and one handed in+ // anyway still gets the floor's card and stays unused+ assert_eq!(prepush::check_command(&env.state, &env.a, "git push origin HEAD:main", &folder).await.unwrap().grant, None);+ let forged = kwnt::mcp::PrepushGrant { id: live.id.clone(), kind: "retry".into(), pressed_card_id: blocked.id.clone(), card_id: again.id.clone() };+ let floor = "git push origin HEAD:main";+ assert_eq!(approver.decide_granted(bash(&env, "t-nogrant", floor, &folder), &forged).await, ApprovalOutcome::Unanswered);+ assert_eq!(waiting_on(&env, floor).await, 1, "the floor asks");+ assert_eq!(env.state.db.prepush_grant(&live.id).await.unwrap().unwrap().used_at, None);++ // The window passes: the fixed, clear push asks as usual+ env.state.db.age_prepush_grant(&live.id, GRANT_MS + 1).await.unwrap();+ let fixed = commit(&folder, TEST_FILE, TEST_BODY, "Bring the test back");+ assert!(prepush::check_command(&env.state, &env.a, push, &folder).await.is_err());+ assert_eq!(settled_sha(&env, &space, &fixed).await.status, CLEAR);+ let pass = prepush::check_command(&env.state, &env.a, push, &folder).await.unwrap();+ assert_eq!(pass.grant, None, "an expired grant covers nothing");+ assert_eq!(approver.decide_granted(bash(&env, "t-nogrant", push, &folder), &forged).await, ApprovalOutcome::Unanswered);+ assert_eq!(env.state.db.prepush_grant(&live.id).await.unwrap().unwrap().used_at, None, "nor is it used");+}++#[tokio::test]+async fn an_override_lets_its_one_push_go_with_no_second_card() {+ let env = setup().await;+ let space = space_of_a(&env).await;+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();+ let folder = repo(&env, "overgrant");+ let row = blocked_card(&env, &space, &folder, "juno-over", "OVERGRANTMARK").await;+ let push = "git push origin juno-over";+ let approver = broker(&env);++ let (s, v) = call(&env.app, "POST", &format!("/api/dev/prepush/{}/override", row.id), Some(json!({"reason": "the slow test is flaky, tracked in #12"}))).await;+ assert_eq!((s.as_u16(), v["status"].as_str()), (200, Some(OVERRIDDEN)), "{v}");+ assert_eq!((v["grant"]["kind"].as_str(), v["grant"]["card_id"].as_str()), (Some("override"), Some(row.id.as_str())), "{v}");++ let pass = prepush::check_command(&env.state, &env.a, push, &folder).await.unwrap();+ let grant = pass.grant.clone().expect("the override covers its push");+ assert_eq!((grant.kind.as_str(), grant.pressed_card_id.as_str(), grant.card_id.as_str()), ("override", row.id.as_str(), row.id.as_str()));+ assert_eq!(approver.decide_granted(bash(&env, "t-over", push, &folder), &grant).await, ApprovalOutcome::Allowed);+ assert_eq!(waiting_on(&env, push).await, 0, "no second card");+ assert_eq!(prepush::use_up(&env.state, &pass).await, None);+ let (_, v) = call(&env.app, "GET", &format!("/api/dev/prepush/{}", row.id), None).await;+ assert_eq!(v["status"], PUSHED, "{v}");+ assert!(v["grant"]["used_at"].is_i64(), "{v}");++ // The same commit again: blocked again, the card asks the person again, and no grant+ assert!(prepush::check_command(&env.state, &env.a, push, &folder).await.is_err());+ assert_eq!(approver.decide_granted(bash(&env, "t-over", push, &folder), &grant).await, ApprovalOutcome::Unanswered);+}++#[tokio::test]+async fn a_newer_commit_supersedes_the_older_cards_and_only_the_newest_needs_you() {+ let env = setup().await;+ let space = space_of_a(&env).await;+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();+ let folder = repo(&env, "superseded");+ let first = blocked_card(&env, &space, &folder, "juno-sup", "SUPMARK").await;+ let push = "git push origin juno-sup";++ let mut rx = env.state.event_sender.subscribe();+ let next_sha = commit(&folder, "src/more.rs", "pub fn more() {}\n", "More");+ assert!(prepush::gate(&env.state, &env.a, push, &folder).await.is_some());+ let older = env.state.db.prepush_card(&first.id).await.unwrap().unwrap();+ assert_eq!(older.status, SUPERSEDED, "{older:?}");+ let next = settled_sha(&env, &space, &next_sha).await;+ assert_eq!((next.status.as_str(), next.tries), (BLOCKED, 2), "{next:?}");+ assert_eq!(older.superseded_by.as_deref(), Some(next.id.as_str()));+ let mut seen = Vec::new();+ while let Ok(e) = rx.try_recv() {+ if let RuntimeEvent::DevPrepush { id, status, .. } = e {+ seen.push((id, status));+ }+ }+ assert!(seen.contains(&(first.id.clone(), SUPERSEDED.to_string())), "{seen:?}");+ let (_, v) = call(&env.app, "GET", &format!("/api/dev/prepush/{}", first.id), None).await;+ assert_eq!((v["status"].as_str(), v["needs_you"].as_bool(), v["superseded_by"].as_str()), (Some(SUPERSEDED), Some(false), Some(next.id.as_str())), "{v}");+ // Nothing to do on a superseded card+ let (s, _) = call(&env.app, "POST", &format!("/api/dev/prepush/{}/retry", first.id), None).await;+ assert_eq!(s.as_u16(), 409);+ let (_, list) = call(&env.app, "GET", &format!("/api/spaces/{space}/dev/prepush"), None).await;+ let needs: Vec<&str> = list["cards"].as_array().unwrap().iter().filter(|c| c["needs_you"] == true).map(|c| c["id"].as_str().unwrap()).collect();+ assert_eq!(needs, [next.id.as_str()], "{list}");++ // The bot goes back to the older commit: its card comes back and the newer one steps aside+ git(&folder, &["reset", "-q", "--hard", &first.head_sha]);+ let why = prepush::gate(&env.state, &env.a, push, &folder).await.expect("still blocked");+ assert!(why.contains("blocked this push"), "{why}");+ assert_eq!(env.state.db.prepush_card(&first.id).await.unwrap().unwrap().status, BLOCKED);+ assert_eq!(env.state.db.prepush_card(&next.id).await.unwrap().unwrap().status, SUPERSEDED);+}++/// Cards from before 0.9.7: the migration leaves only the newest of each branch waiting.+#[tokio::test]+async fn the_migration_collapses_old_cards_to_the_newest_per_branch() {+ let env = setup().await;+ let db = &env.state.db;+ let mut ids = Vec::new();+ for (i, status) in [BLOCKED, PREPUSH_FAILED, BLOCKED].into_iter().enumerate() {+ let r = db.insert_prepush_card("spc_c", &env.a, "/f", "juno-c", &format!("{i}").repeat(40), CHECKING, None, false).await.unwrap().unwrap();+ db.finish_prepush_card(&r.id, status, "{}").await.unwrap().unwrap();+ ids.push(r.id);+ }+ let other = db.insert_prepush_card("spc_c", &env.a, "/f", "juno-d", &"9".repeat(40), CHECKING, None, false).await.unwrap().unwrap();+ db.finish_prepush_card(&other.id, BLOCKED, "{}").await.unwrap().unwrap();+ let clear = db.insert_prepush_card("spc_c", &env.a, "/g", "juno-c", &"8".repeat(40), CHECKING, None, false).await.unwrap().unwrap();+ db.finish_prepush_card(&clear.id, CLEAR, "{}").await.unwrap().unwrap();++ assert_eq!(db.collapse_prepush_cards().await.unwrap(), 2);+ let newest = ids.last().unwrap();+ for id in &ids[..2] {+ let r = db.prepush_card(id).await.unwrap().unwrap();+ assert_eq!((r.status.as_str(), r.superseded_by.as_deref()), (SUPERSEDED, Some(newest.as_str())), "{r:?}");+ }+ assert_eq!(db.prepush_card(&ids[1]).await.unwrap().unwrap().superseded_status.as_deref(), Some(PREPUSH_FAILED));+ assert_eq!(db.prepush_card(newest).await.unwrap().unwrap().status, BLOCKED);+ assert_eq!(db.prepush_card(&other.id).await.unwrap().unwrap().status, BLOCKED, "another branch keeps its card");+ assert_eq!(db.prepush_card(&clear.id).await.unwrap().unwrap().status, CLEAR, "another folder too");+ assert_eq!(db.collapse_prepush_cards().await.unwrap(), 0, "once");+}