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.

0.8.0 B1+B2 follow-ups: one-push override, pinned push, GitHub-write cards, fresh-eyes allowlist (#456 Later) (#472)

Oleksandr Ivanchenko7d379778472f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bb1b9f19..c4b321db 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
### Added
+- **Pre-push card follow-ups.** kwant's own GitHub tools that write files to a branch (`push_files`, `create_or_update_file`, `delete_file` and Composio's GitHub file tools) now wait for a pre-push card too, and must name their branch. An override now lets exactly one push go: the next push of the same commit waits for the person again. A plain `git push <remote> [<branch>]` of a branch runs pinned to the commit kwant checked; a tag or any other ref (`refs/notes/…`, `refs/pull/…`) runs as written, gated by its card. GitHub tools now meet the production floor like `git push`: a file write to a protected branch, every pull-request merge, moving a protected branch's ref (`GITHUB_UPDATE_A_REFERENCE`), creating or moving a tag ref (`GITHUB_CREATE_A_REFERENCE`, `GITHUB_UPDATE_A_REFERENCE`), and deleting a protected branch or a tag ask the person. A check that errored (not a reviewer's own finding) runs once more on its own. A lead's review of a hand-off is labelled "Checked with fresh eyes" when it ran in a fresh-eyes turn, and the review kwant posts for a PR says when the person pushed anyway, with their reason. Fresh-eyes turns now get only an allowlist of kwant's tools, so a new tool is off in them until it is added. **Known limits:** the card doesn't see shells kwant doesn't run (Codex's own shell, VM mode), git aliases, `gh`, `git.exe`, `"$(which git)"` or scripts that push, or a person's own Claude settings that allow `git push`; tokenless loopback calls to person-only routes need `KWNT_REQUIRE_TOKEN=always` to close; a command substitution runs before the push it sits in; and a bot's non-kwant MCP servers stay on in fresh-eyes turns. See docs/dev-mode.md. (#456 follow-up)
- **kwant's own browser on Windows and Linux ARM.** When no Chrome is found, kwant can now download Google's Chrome for Testing on 64-bit Windows and on Linux ARM (aarch64) too, as it already did on Mac and Linux x64. On Windows it's kept in `AppData\Local\kwant\chrome` in your user folder. (#457)
### Fixed
diff --git a/docs/dev-mode.md b/docs/dev-mode.md
index 40541ef1..34a7857d 100644
--- a/docs/dev-mode.md
+++ b/docs/dev-mode.md
@@ -500,11 +500,18 @@ deploy can cost a site.
code that uses its SDK, doesn't ask unless it goes through a connection marked production.
- **Tools and providers missing from the lists**, and MCP tools whose names don't say what they
do. Mark such a connection production to make every one of its tools ask.
-- **Git writes through a connection.** A GitHub MCP server or Composio app that isn't marked
- production can write to the repo with no card: `push_files`, `create_or_update_file` on `main`,
- `merge_pull_request`, `delete_branch` and the like reach the watched branch directly. The floor
- reads git commands and deploy tools, not these tool names. Mark that connection production
- (Connections → Production) to make every one of its tools ask.
+- **Git writes through a connection.** The floor reads GitHub's own tool names (GitHub's MCP
+ server and Composio's `GITHUB_*` tools, also inside a multi-execute) like `git push`: a file
+ write (`push_files`, `create_or_update_file`, `delete_file`, `GITHUB_COMMIT_MULTIPLE_FILES`, …)
+ to a protected branch asks, every merge tool asks (its base isn't in the call, so it counts as
+ protected), and deleting a protected branch, a tag or a ref the call doesn't name asks. Moving a
+ ref asks too: `GITHUB_UPDATE_A_REFERENCE` on a protected branch, or on a ref the call doesn't
+ name, asks as a push to it (a force-push when `force` is set), and `GITHUB_CREATE_A_REFERENCE` or
+ `GITHUB_UPDATE_A_REFERENCE` with a tag (`tags/…`, `refs/tags/…`) asks as a deploy, like a tag
+ push. A file write to any other branch gets a pre-push card (below). `create_branch` and
+ creating a branch ref (`GITHUB_CREATE_A_REFERENCE` with `refs/heads/…`) don't ask, and other
+ tools that change a repo (a GitLab server, or GitHub tools named otherwise) reach it directly:
+ mark that connection production (Connections → Production) to make every one of its tools ask.
- **Where a command runs.** The floor can't tell a production database from a local copy unless
the command says so (a remote URL, `--prod`, `RAILS_ENV=production`, …). So a plain
`sqlx migrate run` doesn't ask, but `DROP TABLE` does, wherever it runs.
@@ -517,6 +524,49 @@ deploy can cost a site.
the first repo's branch. A bare `git push` from a
detached head, or from a folder that isn't a repo, counts as a push to a protected branch.
+## The pre-push card (0.8.0)
+
+Before a bot pushes its own branch, kwant checks what the push sends: gitleaks, new packages, test
+tamper, the risk rules and one review by another bot that sees only the diff (fresh eyes). Semgrep
+runs only when it is installed and the repo has its own `.semgrep.yml`. The push waits until the
+card is clear, or until the person overrides it with a reason. A push the production floor already
+asks about (a protected branch, a force-push, a deploy remote) gets the floor card instead.
+
+- **Where it runs:** claude's `Bash` (through kwant's permission prompt), kwant's own
+ `execute_shell` in Local mode, and kwant's own GitHub tools that write files to a branch (above).
+ A GitHub write must name its branch, and one call makes one write; its card checks the files the
+ tool sends as added lines, so semgrep doesn't run on it.
+- **One override, one push.** An override lets exactly one push of that commit go. The next push of
+ the same commit finds the card blocked again (status `pushed` while it waits; the reason is kept),
+ until the person overrides it again or a new commit gets a new check. A push that fails after it
+ was allowed still uses the override.
+- **The pushed commit.** A plain `git push <remote> [<branch>]` (optionally after `cd <folder> &&`)
+ runs as `git push <remote> <checked sha>:refs/heads/<branch>`, so a commit made in the meantime
+ isn't what goes. Only a branch is pinned: the source must be `HEAD`, `@` or a local branch no tag
+ shares a name with, and the destination that branch. A tag (`git push origin checkpoint`), a
+ commit sha or another ref runs as written, gated by the card of the commit it sends. Other shapes
+ (`-u`, other flags, several pushes, no remote) run as written too.
+- **A check that errored** (kwant couldn't read the repo, or the reviewer's turn didn't answer:
+ `review_failed`) runs once more on its own; the card says `auto_retried`. A timeout isn't
+ retried, and neither is the reviewer's own critical or high finding: that is a verdict.
+- **Pushed anyway.** When the person overrode a card on a branch, the review kwant posts for that
+ branch's PR (when the person presses Post) says so, with the person's reason.
+
+### Known limits
+
+The card sees only what kwant runs or is asked about, so these pushes skip it:
+
+- Shells kwant doesn't see: Codex's own shell, and VM mode.
+- Git aliases (`git -c alias.p=push p`, aliases in a git config), `gh`, `git.exe`,
+ `"$(which git)"` and scripts that push.
+- A person's own Claude settings that already allow `git push`: claude doesn't ask kwant then.
+- Tokenless calls from the same computer to person-only routes (such as the override) are allowed,
+ as for every person-only route; set `KWNT_REQUIRE_TOKEN=always` to close that.
+- A command substitution (`$(…)`, backticks) runs before the push it sits in, so its side effects
+ happen even when the push is refused.
+- A bot's MCP servers other than kwant's stay on in fresh-eyes turns; only kwant's own tools are
+ limited to the review's allowlist.
+
## Tests
Run these focused tests:
diff --git a/src/db/dev_prepush.rs b/src/db/dev_prepush.rs
index 15161734..39241b96 100644
--- a/src/db/dev_prepush.rs
+++ b/src/db/dev_prepush.rs
@@ -1,7 +1,7 @@
//! B2 (0.8.0, fresh-eyes-audit.md §4): the pre-push card. Before a bot pushes its own branch in
//! Dev mode, kwant checks the commit it would push and keeps one card per
//! `(space, folder, branch, head_sha)`. The push is refused until the card is `clear`, or the
-//! person `overridden` it. Kept outside exports like the other Dev mode tables. Add-only.
+//! person `overridden` it (for one push: then it is `pushed`). Kept outside exports like the other Dev mode tables. Add-only.
use super::{Database, DbError};
use sqlx::FromRow;
@@ -36,8 +36,11 @@ pub const CHECKING: &str = "checking";
pub const BLOCKED: &str = "blocked";
/// Every check passed: the push goes.
pub const CLEAR: &str = "clear";
-/// The person let the push go anyway.
+/// The person let the push go anyway: one push, used up by the first push it lets go.
pub const OVERRIDDEN: &str = "overridden";
+/// An `overridden` card whose one push went. Pushing the same commit again makes it `blocked`
+/// again, so the person decides each push (Rigel's QA of #456, finding C).
+pub const PUSHED: &str = "pushed";
/// kwant couldn't check (no base, git failed): the push waits for the person, as blocked does.
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,
@@ -97,7 +100,8 @@ impl Database {
/// A new card for this push in `status` (`checking`, or `failed` with its card), or `None`
/// when one is already there (two pushes at once make one card). Its `tries` is 1, or one more
/// than the branch's newest card when that one is blocked or failed (the bot is still fixing);
- /// `fresh_start` (after the person asked for a re-check) makes it 1 again.
+ /// `fresh_start` (after the person asked for a re-check) makes it 1 again, and so does a card
+ /// the person overrode that is blocked again only because its one push was used.
#[allow(clippy::too_many_arguments)]
pub async fn insert_prepush_card(
&self,
@@ -113,7 +117,7 @@ impl Database {
let id = format!("pp_{}", uuid::Uuid::new_v4().simple());
let now = now_ms();
let tries = match self.prepush_newest_on(space_id, folder, branch).await? {
- Some(last) if !fresh_start && (last.status == BLOCKED || last.status == PREPUSH_FAILED) => last.tries + 1,
+ Some(last) if !fresh_start && last.overridden_by.is_none() && (last.status == BLOCKED || last.status == PREPUSH_FAILED) => last.tries + 1,
_ => 1,
};
let done = sqlx::query(
@@ -155,6 +159,19 @@ impl Database {
.await?)
}
+ /// The cards on `branch` in a space the person overrode (standing, used or blocked again),
+ /// newest first, at most `limit`: what a PR from that branch says was pushed anyway.
+ pub async fn prepush_overrides_on(&self, space_id: &str, branch: &str, limit: i64) -> Result<Vec<PrepushRow>, DbError> {
+ Ok(sqlx::query_as(&format!(
+ "SELECT {COLS} FROM dev_prepush_cards WHERE space_id = ? AND branch = ? AND overridden_by IS NOT NULL ORDER BY overridden_at DESC, rowid DESC LIMIT ?"
+ ))
+ .bind(space_id)
+ .bind(branch)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await?)
+ }
+
/// The newest cards of a space, at most `limit`.
pub async fn prepush_cards(&self, space_id: &str, limit: i64) -> Result<Vec<PrepushRow>, DbError> {
Ok(sqlx::query_as(&format!("SELECT {COLS} FROM dev_prepush_cards WHERE space_id = ? ORDER BY created_at DESC, id DESC LIMIT ?"))
@@ -201,6 +218,31 @@ impl Database {
self.prepush_card(id).await
}
+ /// Uses up the override of card `id` for the push it is letting go: `overridden` becomes
+ /// `pushed`, at most once. False when it wasn't `overridden` (another push used it first).
+ pub async fn use_prepush_override(&self, id: &str) -> Result<bool, DbError> {
+ let r = sqlx::query("UPDATE dev_prepush_cards SET status = 'pushed', updated_at = ? WHERE id = ? AND status = 'overridden'")
+ .bind(now_ms())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ Ok(r.rows_affected() > 0)
+ }
+
+ /// A bot pushes the commit of a `pushed` card again: the card is `blocked` again (its
+ /// override history stays). The card, or `None` when it wasn't `pushed`.
+ pub async fn reblock_pushed_prepush_card(&self, id: &str) -> Result<Option<PrepushRow>, DbError> {
+ let r = sqlx::query("UPDATE dev_prepush_cards SET status = 'blocked', updated_at = ? WHERE id = ? AND status = 'pushed'")
+ .bind(now_ms())
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+ if r.rows_affected() == 0 {
+ return Ok(None);
+ }
+ self.prepush_card(id).await
+ }
+
/// The person asks for the checks of a `blocked` or `failed` card to run again: it becomes
/// `retried`, and the next push of that commit makes a new card at try 1. `None` when it isn't
/// there or wasn't blocked or failed.
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index 617a82af..b64e5bba 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -385,6 +385,20 @@ pub trait ToolApprover: Send + Sync {
async fn tier_gate(&self, _request: &ToolApprovalRequest) -> Option<String> {
None
}
+
+ /// 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
+ /// 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())
+ }
+
+ /// Uses up the overrides [`prepush_gate`](Self::prepush_gate) found, once the call is
+ /// allowed: `None` lets it run, else the text the bot gets back. Default: nothing to use.
+ async fn prepush_use(&self, _overrides: &[String]) -> Option<String> {
+ None
+ }
}
/// What became of a call that may have needed a card.
diff --git a/src/mcp/prod_floor.rs b/src/mcp/prod_floor.rs
index bddd1b16..70d36fd4 100644
--- a/src/mcp/prod_floor.rs
+++ b/src/mcp/prod_floor.rs
@@ -183,7 +183,10 @@ pub fn reason(req: &ToolApprovalRequest, ctx: &DevCtx) -> Option<Floor> {
} else if req.server == super::SELF_SERVER_NAME {
None
} else {
- mcp_reason(&req.server, &req.tool, &req.arguments, ctx)
+ match (mcp_reason(&req.server, &req.tool, &req.arguments, ctx), github_reason(&req.server, &req.tool, &req.arguments, ctx, 0)) {
+ (Some(a), Some(b)) => Some(a.merge(b)),
+ (a, b) => a.or(b),
+ }
};
// A production connection is checked last: what the call does names the card first
match (found, prod_key(&req.server, &req.tool, &req.arguments, ctx)) {
@@ -279,6 +282,110 @@ fn mcp_reason(server: &str, tool: &str, args: &Value, ctx: &DevCtx) -> Option<Fl
best
}
+/// A GitHub tool (GitHub's own MCP server, or Composio's `GITHUB_*` tools, also inside
+/// `COMPOSIO_MULTI_EXECUTE_TOOL`) that writes to a protected branch, merges a pull request, or
+/// deletes a protected branch or a tag (Ada's review of #472, must-fix 2). It matches what
+/// [`git_reason`] asks for a `git push`:
+/// - a content write (`push_files`, `create_or_update_file`, `delete_file`, Composio's
+/// `COMMIT_MULTIPLE_FILES` and the like) to a protected branch: [`FloorKind::PushMain`]. One
+/// that names no branch is refused by the pre-push card instead;
+/// - every merge tool: the base it writes to isn't in its arguments, and unknown counts as
+/// protected, so [`FloorKind::PushMain`];
+/// - deleting a protected branch, a tag, or a ref kwant can't read: [`FloorKind::DeleteRef`].
+///
+/// - creating or updating a tag ref (`GITHUB_CREATE_A_REFERENCE`, `GITHUB_UPDATE_A_REFERENCE`
+/// with `tags/…` or `refs/tags/…`): a deploy, as a tag push is;
+/// - updating a protected branch's ref, or a ref the call doesn't name:
+/// [`FloorKind::ForcePush`] with `force`, else [`FloorKind::PushMain`]. Creating a ref the
+/// call doesn't name could make a tag, so it asks as a deploy.
+///
+/// `create_branch` and creating a branch ref add a ref and write no content, so they don't ask.
+fn github_reason(server: &str, tool: &str, args: &Value, ctx: &DevCtx, depth: usize) -> Option<Floor> {
+ if depth > 2 {
+ return None;
+ }
+ let mut best: Option<Floor> = None;
+ let mut add = |f: Floor| best = Some(match best.take() { Some(b) => b.merge(f), None => f });
+ if let Some(list) = args["tools"].as_array() {
+ for t in list.iter().take(20) {
+ if let Some(slug) = t["tool_slug"].as_str().or(t["slug"].as_str()) {
+ if let Some(f) = github_reason(server, slug, &t["arguments"], ctx, depth + 1) {
+ add(f);
+ }
+ }
+ }
+ }
+ let lower = tool.to_ascii_lowercase();
+ let github = lower.starts_with("github_") || server.to_ascii_lowercase().contains("github");
+ let name = lower.strip_prefix("github_").unwrap_or(&lower);
+ let has_repo = args["owner"].is_string() && args["repo"].is_string();
+ let branch_arg = |keys: &[&str]| keys.iter().find_map(|k| args[*k].as_str()).map(str::trim).filter(|b| !b.is_empty()).map(String::from);
+ let w = words(name);
+ let read = w.first().is_some_and(|f| READ_VERBS.contains(&f.as_str()));
+ match name {
+ "push_files" | "commit_multiple_files" | "create_or_update_file" | "create_or_update_file_contents" | "delete_file" | "delete_a_file" if has_repo => {
+ if let Some(b) = branch_arg(&["branch"]) {
+ if ctx.is_protected(&b) {
+ let b = b.trim_start_matches("refs/heads/").to_string();
+ add(Floor::new(FloorKind::PushMain, format!("{tool} writes commits straight to {b} on GitHub")).row("What changes", format!("New commits land on {b}.")));
+ }
+ }
+ }
+ _ if !read && (github || has_repo) && w.iter().any(|x| x == "merge") => {
+ add(Floor::new(FloorKind::PushMain, format!("{tool} writes a pull request's commits to its base branch, which the call doesn't name, so it counts as protected"))
+ .row("What changes", "The pull request's commits land on its base branch."));
+ }
+ _ if !read && (github || has_repo) && w.iter().any(|x| x == "delete") && w.iter().any(|x| matches!(x.as_str(), "branch" | "ref" | "reference")) => {
+ let r = branch_arg(&["branch", "ref", "branch_name", "name"]).unwrap_or_default();
+ let r = r.trim_start_matches("refs/");
+ let tag = r.starts_with("tags/");
+ let b = r.trim_start_matches("heads/");
+ if r.is_empty() || tag || ctx.is_protected(b) || looks_like_version(b) {
+ let shown = if r.is_empty() { "a ref kwant can't read from the call".to_string() } else { b.to_string() };
+ add(Floor::new(FloorKind::DeleteRef, format!("{tool} deletes {shown} on GitHub")).row("What changes", format!("{shown} is deleted on GitHub.")));
+ }
+ }
+ _ if !read
+ && (github || has_repo)
+ && w.iter().any(|x| matches!(x.as_str(), "update" | "create"))
+ && w.iter().any(|x| matches!(x.as_str(), "ref" | "reference")) =>
+ {
+ // Ada's review of #472, round 2, must-fix 2: moving a ref is a push. A tag can start a
+ // release; updating a protected branch (or one the call doesn't name) is a push to
+ // it, forced when `force` is set. Creating a branch ref writes no content.
+ let create = w.iter().any(|x| x == "create") && !w.iter().any(|x| x == "update");
+ let force = args["force"].as_bool().unwrap_or(false) || args["force"].as_str().is_some_and(|f| f.eq_ignore_ascii_case("true"));
+ let raw = branch_arg(&["ref", "branch", "name"]).unwrap_or_default();
+ let r = raw.trim_start_matches("refs/");
+ let named_branch = r.starts_with("heads/");
+ let b = r.strip_prefix("heads/").unwrap_or(r);
+ let tag = r.starts_with("tags/") || (!named_branch && looks_like_version(b));
+ if tag {
+ let t = r.trim_start_matches("tags/");
+ add(ctx.deploy(format!("{tool} sends the tag {t} to GitHub, which can start a release")));
+ } else if r.is_empty() {
+ let what = "a ref kwant can't read from the call";
+ if create {
+ // It could be a tag
+ add(ctx.deploy(format!("{tool} creates {what}, which could be a tag that starts a release")));
+ } else if force {
+ add(Floor::new(FloorKind::ForcePush, format!("{tool} force-moves {what}, so it counts as protected")).row("What changes", "The ref is rewritten; commits others have can be lost."));
+ } else {
+ add(Floor::new(FloorKind::PushMain, format!("{tool} moves {what}, so it counts as protected")).row("What changes", "The ref moves to a new commit."));
+ }
+ } else if !create && ctx.is_protected(b) {
+ if force {
+ add(Floor::new(FloorKind::ForcePush, format!("{tool} force-moves {b} on GitHub")).row("What changes", format!("{b} is rewritten; commits others have can be lost.")));
+ } else {
+ add(Floor::new(FloorKind::PushMain, format!("{tool} moves {b} to a new commit on GitHub")).row("What changes", format!("New commits land on {b}.")));
+ }
+ }
+ }
+ _ => {}
+ }
+ best
+}
+
fn collect_strings(v: &Value, out: &mut Vec<String>, depth: usize) {
if depth > 4 || out.len() > 50 {
return;
@@ -1326,6 +1433,87 @@ mod tests {
assert_eq!(k("notion", "publish_page", json!({})), None);
}
+ /// Ada's review of #472, must-fix 2: GitHub tools ask like `git push` does.
+ #[test]
+ fn github_tools_writing_merging_or_deleting_protected_branches_ask() {
+ use FloorKind::*;
+ let c = ctx();
+ let k = |server: &str, tool: &str, args: Value| reason(&req(server, tool, args), &c).map(|f| f.kind);
+ let write = |b: &str| json!({"owner": "o", "repo": "r", "branch": b, "message": "m", "files": [{"path": "a.rs", "content": "x"}]});
+ assert_eq!(k("github", "push_files", write("main")), Some(PushMain));
+ assert_eq!(k("github", "push_files", write("release/1.0")), Some(PushMain));
+ assert_eq!(k("github", "create_or_update_file", json!({"owner": "o", "repo": "r", "branch": "master", "path": "a", "content": "x"})), Some(PushMain));
+ assert_eq!(k("github", "delete_file", json!({"owner": "o", "repo": "r", "branch": "refs/heads/main", "path": "a"})), Some(PushMain));
+ assert_eq!(k("composio", "GITHUB_COMMIT_MULTIPLE_FILES", write("main")), Some(PushMain));
+ assert_eq!(k("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", json!({"tools": [{"tool_slug": "GITHUB_CREATE_OR_UPDATE_FILE_CONTENTS", "arguments": write("main")}]})), Some(PushMain));
+ let extra = DevCtx { protected: vec!["staging".into()], ..ctx() };
+ assert_eq!(reason(&req("github", "push_files", write("staging")), &extra).map(|f| f.kind), Some(PushMain));
+ // A bot's own branch gets the pre-push card only
+ assert_eq!(k("github", "push_files", write("juno-x")), None);
+ assert_eq!(k("composio", "GITHUB_COMMIT_MULTIPLE_FILES", write("juno-x")), None);
+ // Every merge: the base isn't in the call
+ assert_eq!(k("github", "merge_pull_request", json!({"owner": "o", "repo": "r", "pull_number": 7})), Some(PushMain));
+ assert_eq!(k("composio", "GITHUB_MERGE_A_PULL_REQUEST", json!({"owner": "o", "repo": "r", "pull_number": 7})), Some(PushMain));
+ assert_eq!(k("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", json!({"tools": [{"tool_slug": "GITHUB_MERGE_A_PULL_REQUEST", "arguments": {}}]})), Some(PushMain));
+ assert_eq!(k("composio", "GITHUB_MERGE_A_BRANCH", json!({"owner": "o", "repo": "r", "base": "juno-x", "head": "y"})), Some(PushMain));
+ // Deletes: a protected branch, a tag or an unreadable ref asks; a bot's own branch doesn't
+ assert_eq!(k("github", "delete_branch", json!({"owner": "o", "repo": "r", "branch": "main"})), Some(DeleteRef));
+ assert_eq!(k("composio", "GITHUB_DELETE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "heads/main"})), Some(DeleteRef));
+ assert_eq!(k("composio", "GITHUB_DELETE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "refs/heads/release/2.0"})), Some(DeleteRef));
+ assert_eq!(k("composio", "GITHUB_DELETE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "tags/checkpoint"})), Some(DeleteRef));
+ assert_eq!(k("github", "delete_branch", json!({"owner": "o", "repo": "r"})), Some(DeleteRef));
+ assert_eq!(k("github", "delete_branch", json!({"owner": "o", "repo": "r", "branch": "juno-x"})), None);
+ assert_eq!(k("composio", "GITHUB_DELETE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "heads/juno-x"})), None);
+ // Creating a branch, reads and a write that names no branch (refused by the card) don't
+ assert_eq!(k("github", "create_branch", json!({"owner": "o", "repo": "r", "branch": "main", "from_branch": "x"})), None);
+ assert_eq!(k("composio", "GITHUB_CREATE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "refs/heads/main", "sha": "abc"})), None);
+ assert_eq!(k("github", "get_pull_request", json!({"owner": "o", "repo": "r", "pull_number": 7})), None);
+ assert_eq!(k("composio", "GITHUB_CHECK_IF_A_PULL_REQUEST_HAS_BEEN_MERGED", json!({"owner": "o", "repo": "r", "pull_number": 7})), None);
+ assert_eq!(k("github", "push_files", json!({"owner": "o", "repo": "r", "files": []})), None);
+ // Other apps' merge or delete tools aren't GitHub's
+ assert_eq!(k("pdf", "merge_pdfs", json!({})), None);
+ assert_eq!(k("slack", "delete_message", json!({})), None);
+ }
+
+ /// Ada's review of #472, round 2, must-fix 2: moving a ref through GitHub's API asks like
+ /// the `git push` it stands for.
+ #[test]
+ fn github_ref_writes_ask_like_a_push() {
+ use FloorKind::*;
+ let c = ctx();
+ let k = |server: &str, tool: &str, args: Value| reason(&req(server, tool, args), &c).map(|f| f.kind);
+ let upd = |r: &str, force: bool| json!({"owner": "o", "repo": "r", "ref": r, "sha": "0123456789abcdef0123456789abcdef01234567", "force": force});
+ let deploy = |x: Option<FloorKind>| matches!(x, Some(Deploy | DeployMigration));
+ // Updating a protected branch: a force-push with force, else a push to it
+ assert_eq!(k("composio", "GITHUB_UPDATE_A_REFERENCE", upd("heads/main", true)), Some(ForcePush));
+ assert_eq!(k("composio", "GITHUB_UPDATE_A_REFERENCE", upd("heads/main", false)), Some(PushMain));
+ assert_eq!(k("composio", "GITHUB_UPDATE_A_REFERENCE", upd("refs/heads/release/1.0", false)), Some(PushMain));
+ assert_eq!(k("composio", "GITHUB_UPDATE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "heads/main", "sha": "abc", "force": "true"})), Some(ForcePush));
+ assert_eq!(k("github", "update_ref", json!({"owner": "o", "repo": "r", "ref": "heads/main", "sha": "abc"})), Some(PushMain));
+ // A bot's own branch doesn't ask
+ assert_eq!(k("composio", "GITHUB_UPDATE_A_REFERENCE", upd("heads/juno-x", true)), None);
+ assert_eq!(k("composio", "GITHUB_UPDATE_A_REFERENCE", upd("heads/juno-x", false)), None);
+ // No ref: it counts as protected
+ assert_eq!(k("composio", "GITHUB_UPDATE_A_REFERENCE", json!({"owner": "o", "repo": "r", "sha": "abc"})), Some(PushMain));
+ assert_eq!(k("composio", "GITHUB_UPDATE_A_REFERENCE", json!({"owner": "o", "repo": "r", "sha": "abc", "force": true})), Some(ForcePush));
+ assert!(deploy(k("composio", "GITHUB_CREATE_A_REFERENCE", json!({"owner": "o", "repo": "r", "sha": "abc"}))));
+ // A tag, created or updated, can start a release
+ assert!(deploy(k("composio", "GITHUB_CREATE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "refs/tags/v0.8.0", "sha": "abc"}))));
+ assert!(deploy(k("composio", "GITHUB_CREATE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "refs/tags/mac-v0.8.0", "sha": "abc"}))));
+ assert!(deploy(k("composio", "GITHUB_UPDATE_A_REFERENCE", upd("tags/checkpoint", true))));
+ // Creating a branch ref writes no content
+ assert_eq!(k("composio", "GITHUB_CREATE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "refs/heads/juno-y", "sha": "abc"})), None);
+ assert_eq!(k("composio", "GITHUB_CREATE_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "refs/heads/main", "sha": "abc"})), None);
+ // Inside COMPOSIO_MULTI_EXECUTE_TOOL
+ let multi = |slug: &str, args: Value| json!({"tools": [{"tool_slug": "GITHUB_LIST_BRANCHES", "arguments": {}}, {"tool_slug": slug, "arguments": args}]});
+ assert_eq!(k("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", multi("GITHUB_UPDATE_A_REFERENCE", upd("heads/main", true))), Some(ForcePush));
+ assert!(deploy(k("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", multi("GITHUB_CREATE_A_REFERENCE", json!({"ref": "refs/tags/v0.8.0", "sha": "abc"})))));
+ assert_eq!(k("composio", "COMPOSIO_MULTI_EXECUTE_TOOL", multi("GITHUB_CREATE_A_REFERENCE", json!({"ref": "refs/heads/juno-y", "sha": "abc"}))), None);
+ // Reads stay reads
+ assert_eq!(k("composio", "GITHUB_GET_A_REFERENCE", json!({"owner": "o", "repo": "r", "ref": "heads/main"})), None);
+ assert_eq!(k("composio", "GITHUB_LIST_MATCHING_REFERENCES", json!({"owner": "o", "repo": "r", "ref": "tags/v"})), None);
+ }
+
#[test]
fn production_connections_always_ask() {
let c = DevCtx { prod_connections: vec!["digitalocean-droplets".into(), "stripe".into()], ..ctx() };
@@ -1627,6 +1815,10 @@ mod tests {
("digitalocean-droplets", "droplet-delete", json!({}), &c),
("supabase", "execute_sql", json!({"query": "DROP TABLE users"}), &c),
("stripe", "create_refund", json!({}), &prod),
+ ("github", "push_files", json!({"owner": "o", "repo": "r", "branch": "main", "files": []}), &c),
+ ("github", "merge_pull_request", json!({"owner": "o", "repo": "r", "pull_number": 1}), &c),
+ ("github", "delete_branch", json!({"owner": "o", "repo": "r", "branch": "main"}), &c),
+ ("github", "delete_branch", json!({"owner": "o", "repo": "r"}), &c),
] {
check(&format!("{server} {tool}"), reason(&req(server, tool, args), c));
}
diff --git a/src/mcp/session.rs b/src/mcp/session.rs
index 87863508..eb28f1ee 100644
--- a/src/mcp/session.rs
+++ b/src/mcp/session.rs
@@ -237,29 +237,34 @@ impl McpToolSession {
Some(_) if !arguments.is_object() => ("error", "Tool arguments must be a JSON object.".to_string()),
Some(t) => {
let (server, client) = &self.clients[t.server_index];
- let outcome = self
- .ctx
- .approver
- .decide(ToolApprovalRequest {
- kwant_id: caller.kwant_id.clone(),
- kwant_name: caller.kwant_name.clone(),
- turn_id: caller.turn_id.clone(),
- tool_name: name.to_string(),
- server: server.clone(),
- tool: t.tool.name.clone(),
- arguments: arguments.clone(),
- builtin: None,
- smart: Some(read_only_verdict(t.tool.read_only)),
- payment: None,
- })
- .await;
- if !outcome.allowed() {
- (outcome.record_status(), outcome.refusal_text().to_string())
- } else {
- match client.call_tool(&t.tool.name, arguments.clone()).await {
- Ok(r) if r.is_error => ("error", r.text),
- Ok(r) => ("ok", r.text),
- Err(e) => ("error", format!("Tool call failed: {e}")),
+ let req = ToolApprovalRequest {
+ kwant_id: caller.kwant_id.clone(),
+ kwant_name: caller.kwant_name.clone(),
+ turn_id: caller.turn_id.clone(),
+ tool_name: name.to_string(),
+ server: server.clone(),
+ tool: t.tool.name.clone(),
+ arguments: arguments.clone(),
+ builtin: None,
+ smart: Some(read_only_verdict(t.tool.read_only)),
+ payment: None,
+ };
+ // B2: a write to a GitHub branch waits for its pre-push card before any card or rule
+ match self.ctx.approver.prepush_gate(&req).await {
+ Err(why) => ("denied", why),
+ Ok(overrides) => {
+ let outcome = 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 {
+ ("denied", why)
+ } else {
+ match client.call_tool(&t.tool.name, arguments.clone()).await {
+ Ok(r) if r.is_error => ("error", r.text),
+ Ok(r) => ("ok", r.text),
+ Err(e) => ("error", format!("Tool call failed: {e}")),
+ }
+ }
}
}
}
diff --git a/src/server/dev/generate.rs b/src/server/dev/generate.rs
index 42096a6c..5f73716d 100644
--- a/src/server/dev/generate.rs
+++ b/src/server/dev/generate.rs
@@ -72,7 +72,12 @@ async fn build(state: &AppState, row: &DevCardRow, cap: i64) -> (&'static str, V
let mut model = picked.as_ref().map(|p| model_on(p.bot.clone()));
// J12: a PR on a ticket with a brief is checked against its done-when lines
let ticket = super::tickets::brief::ticket_check(state, &row.space_id, &facts).await;
- let (status, card) = review::card_for(&facts, picked.as_ref(), model.as_mut(), ticket.as_ref()).await;
+ let (status, mut card) = review::card_for(&facts, picked.as_ref(), model.as_mut(), ticket.as_ref()).await;
+ // B2: a push from this branch the person let go past its pre-push card
+ let anyway = super::prepush::pushed_anyway(state, &row.space_id, facts.head_branch.as_deref()).await;
+ if anyway.as_array().is_some_and(|a| !a.is_empty()) {
+ card["pushed_anyway"] = anyway;
+ }
if let (Some(t), Some(v)) = (&ticket, review::matches_verdict(&card)) {
super::tickets::hooks::reviewed(state, &row.space_id, &t.key, v).await;
}
diff --git a/src/server/dev/post.rs b/src/server/dev/post.rs
index 4501f9d3..d079c684 100644
--- a/src/server/dev/post.rs
+++ b/src/server/dev/post.rs
@@ -249,6 +249,13 @@ pub fn build(card: &Value, facts: &DevFacts, inline: bool) -> Built {
b.push_str(&format!("- {r}\n"));
}
+ // B2: what the person let go past kwant's pre-push check, in their own words
+ for p in card["pushed_anyway"].as_array().into_iter().flatten() {
+ let sha: String = p["head_sha"].as_str().unwrap_or("").chars().take(7).collect();
+ let reason: String = p["reason"].as_str().unwrap_or("").split_whitespace().collect::<Vec<_>>().join(" ").chars().take(300).collect();
+ b.push_str(&format!("- Pushed anyway: the person overrode kwant's pre-push check on commit `{sha}`: \u{201c}{}\u{201d}\n", reason.replace('`', "'")));
+ }
+
b.push_str("\n**Intent check**");
let intent = &card["intent"];
match intent["source"].as_str() {
@@ -645,6 +652,22 @@ mod tests {
assert!(!build(&card(vec![]), &facts(), true).body.contains("Matches the ticket"));
}
+ /// Ada's review of #456, Later 6: a push the person let go past the pre-push card says so,
+ /// with their reason, in the review kwant posts.
+ #[test]
+ fn a_push_let_go_anyway_is_in_the_body_with_the_persons_reason() {
+ let mut c = card(vec![]);
+ c["pushed_anyway"] = json!([{"card_id": "pp1", "head_sha": "0123456789abcdef0123456789abcdef01234567", "by": "person",
+ "reason": "the slow test is flaky,\n tracked in `#12`", "at": 1}]);
+ let b = build(&c, &facts(), true);
+ assert!(
+ b.body.contains("- Pushed anyway: the person overrode kwant's pre-push check on commit `0123456`: \u{201c}the slow test is flaky, tracked in '#12'\u{201d}"),
+ "{}",
+ b.body
+ );
+ assert!(!build(&card(vec![]), &facts(), true).body.contains("Pushed anyway"));
+ }
+
#[test]
fn the_body_has_risk_intent_tamper_security_and_the_signature() {
let b = build(&card(vec![]), &facts(), true);
diff --git a/src/server/dev/prepush.rs b/src/server/dev/prepush.rs
index d7a43270..1f74fd7b 100644
--- a/src/server/dev/prepush.rs
+++ b/src/server/dev/prepush.rs
@@ -26,7 +26,7 @@
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, RETRIED};
+use crate::db::dev_prepush::{PrepushRow, BLOCKED, CHECKING, CLEAR, NEEDS_YOU_TRIES, OVERRIDDEN, PREPUSH_FAILED, PUSHED, RETRIED};
use crate::drivers::events::RuntimeEvent;
use crate::mcp::prod_floor;
use crate::server::AppState;
@@ -75,7 +75,9 @@ pub enum Parsed {
const SEGMENT_SPLIT: [char; 7] = [';', '&', '|', '\n', '(', ')', '`'];
/// What a bot is told when something runs before its push in the same command.
-pub const RUN_ALONE: &str = "kwant checks the commit a push sends before the command runs, so nothing else may run before `git push` in the same command (a commit, an amend, a pull or a merge would change what is sent). Run them first, then run `git push` as its own command (`cd <repo> && git push` is fine).";
+pub const RUN_ALONE: &str = "kwant checks the commit a push sends before the command runs, so nothing else may run before \
+ `git push` in the same command (a commit, an amend, a pull or a merge would change what is sent). Run them first, \
+ then run `git push` as its own command (`cd <repo> && git push` is fine).";
/// The `git push`es in `command`, in order. Finds `git` anywhere in a segment, so `env X=1 git
/// push`, `sudo git push`, `nice git push` and `bash -c 'git push'` all count; `cd <dir>` before it
@@ -259,6 +261,15 @@ pub fn blockers(card: &Value, review_failed: bool) -> Vec<Value> {
/// What the bot is told while its push waits.
pub fn deny_text(row: &PrepushRow) -> String {
+ let text = deny_text_for(row);
+ if row.folder.starts_with("mcp:") {
+ // A GitHub tool's write has no commit of its own: its files and arguments are the check
+ return format!("{text}\n(This was a GitHub tool's write, so \"push\" means that call: changing what it sends gets a new check, and the same call again gets this card.)");
+ }
+ text
+}
+
+fn deny_text_for(row: &PrepushRow) -> String {
let id = &row.id;
let branch = &row.branch;
match row.status.as_str() {
@@ -299,44 +310,158 @@ pub fn deny_text(row: &PrepushRow) -> String {
// ---------------------------------------------------------------------------------------------
// The gate
-/// Whether `command` may run now: `None` lets it run (no push, Dev mode off, the production
-/// floor asks instead, or every push it makes has a `clear` or `overridden` card), else the text
-/// the bot gets back instead of running it. `folder` is the bot's folder for the turn (set by the
-/// host, never named by the bot).
-pub async fn gate(state: &AppState, kwant_id: &str, command: &str, folder: &Path) -> Option<String> {
+/// What [`check_command`] found for a command that may run.
+#[derive(Debug, Default, Clone, PartialEq)]
+pub struct Pass {
+ /// The `overridden` cards its pushes go on: [`use_up`] turns each into `pushed` once the
+ /// command is allowed, so an override lets exactly one push go.
+ pub overrides: Vec<String>,
+ /// The command to run instead, pinned to the commit kwant checked (`git push <remote>
+ /// <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>,
+}
+
+/// Whether `command` may run now (`Ok`: no push, Dev mode off, the production floor asks
+/// instead, or every push it makes has a `clear` or `overridden` card), else the text the bot
+/// gets back instead of running it. `folder` is the bot's folder for the turn (set by the host,
+/// never named by the bot). Call [`use_up`] once the command is allowed to run.
+pub async fn check_command(state: &AppState, kwant_id: &str, command: &str, folder: &Path) -> Result<Pass, String> {
let lower = command.to_ascii_lowercase();
if !(lower.contains("git") && lower.contains("push")) {
- return None;
+ return Ok(Pass::default());
}
let parsed = pushes(command);
if parsed == Parsed::NoPush {
- return None;
+ return Ok(Pass::default());
}
// The floor reads the checked-out branch where the (first) push runs
let cwd = match &parsed {
Parsed::Pushes(list) => folder.join(&list[0].dir),
_ => folder.to_path_buf(),
};
- let (space_id, ctx) = super::floor::ctx_for_kwant(&state.db, kwant_id, Some((folder, &cwd))).await?;
+ let Some((space_id, ctx)) = super::floor::ctx_for_kwant(&state.db, kwant_id, Some((folder, &cwd))).await else {
+ return Ok(Pass::default());
+ };
// The production floor's card asks the person about this command already
if prod_floor::shell_reason(command, &ctx).is_some() {
- return None;
+ return Ok(Pass::default());
}
let list = match parsed {
- Parsed::NoPush => return None,
- Parsed::Refused(why) => return Some(why),
+ Parsed::NoPush => return Ok(Pass::default()),
+ Parsed::Refused(why) => return Err(why),
Parsed::Pushes(list) => list,
};
+ let one = list.len() == 1;
+ let mut pass = Pass::default();
for push in list {
- match gate_one(state, kwant_id, &space_id, &ctx.branch, folder, &push).await {
- Ok(()) => {}
- Err(text) => return Some(text),
+ let (checked, local_src) = gate_one(state, kwant_id, &space_id, &ctx.branch, folder, &push).await?;
+ if checked.status == OVERRIDDEN {
+ pass.overrides.push(checked.id.clone());
+ }
+ if one {
+ pass.pinned = pin(command, &checked.head_sha, &checked.branch, local_src);
+ }
+ }
+ Ok(pass)
+}
+
+/// Uses up the overrides `pass` goes on, once its command is allowed to run: `None` when it may
+/// run, else the text the bot gets back (another push used an override first).
+pub async fn use_up(state: &AppState, pass: &Pass) -> Option<String> {
+ for id in &pass.overrides {
+ match state.db.use_prepush_override(id).await {
+ Ok(true) => {
+ if let Ok(Some(r)) = state.db.prepush_card(id).await {
+ notify(state, &r);
+ }
+ }
+ Ok(false) => return Some(format!("The person's override on pre-push card {id} was for one push, and another push used it. Nothing was pushed.")),
+ Err(e) => return Some(format!("kwant couldn't use the override on pre-push card {id} ({e}). Nothing was pushed.")),
}
}
None
}
-async fn gate_one(state: &AppState, kwant_id: &str, space_id: &str, base: &str, folder: &Path, push: &Push) -> Result<(), String> {
+/// [`check_command`] then [`use_up`] in one step, for a command that runs as soon as it may:
+/// `None` lets it run, else the text the bot gets back.
+pub async fn gate(state: &AppState, kwant_id: &str, command: &str, folder: &Path) -> Option<String> {
+ match check_command(state, kwant_id, command, folder).await {
+ Err(why) => Some(why),
+ Ok(pass) => use_up(state, &pass).await,
+ }
+}
+
+/// `command` pinned to `sha` when it is exactly `[cd <dir> && ...] git push <remote> [<spec>]`
+/// with plain words and no flags: `git push <remote> <sha>:refs/heads/<branch>`, so what goes is
+/// the commit kwant checked. `None` for any other shape (flags such as `-u`, quotes, `$`,
+/// several pushes), which runs as written.
+///
+/// Only a branch push is pinned (Ada's review of #472, must-fix 1): the spec's source must be
+/// `HEAD`, `@` or a local branch (`local_src`: the caller found `refs/heads/<src>`, and no tag
+/// of that name), never a commit sha or another ref, and its destination must be `branch`
+/// (bare or as `refs/heads/<branch>`). A tag or anything else runs as written, still gated by
+/// its card, so a pin never turns it into a new branch.
+pub fn pin(command: &str, sha: &str, branch: &str, local_src: bool) -> Option<String> {
+ let plain = |w: &str| !w.is_empty() && w.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '/' | ':' | '@' | '+'));
+ if !super::git::is_sha(sha) || !super::routes::valid_branch(branch) || command.contains('\n') {
+ return None;
+ }
+ // The caller passes the push's destination as `branch`: `refs/notes/x`, `refs/remotes/…` or
+ // `refs/pull/…` there isn't a branch, and pinning it would make a branch of that name (Ada's
+ // review of #472, round 2, must-fix 1)
+ if branch.starts_with("refs/") {
+ return None;
+ }
+ let segments: Vec<&str> = command.split("&&").map(str::trim).collect();
+ let (last, cds) = segments.split_last()?;
+ let mut kept = Vec::new();
+ for seg in cds {
+ let w: Vec<&str> = seg.split_whitespace().collect();
+ if w.len() != 2 || w[0] != "cd" || !plain(w[1]) || w[1].contains(':') || w[1].starts_with('/') || w[1].split('/').any(|p| p == "..") {
+ return None;
+ }
+ kept.push(format!("cd {}", w[1]));
+ }
+ let w: Vec<&str> = last.split_whitespace().collect();
+ if w.len() < 3 || w.len() > 4 || w[0] != "git" || w[1] != "push" || w[2].starts_with('-') || !plain(w[2]) || w[2].contains(':') {
+ return None;
+ }
+ if !local_src {
+ return None;
+ }
+ if let Some(spec) = w.get(3) {
+ if !plain(spec) || spec.starts_with('-') || spec.starts_with('+') {
+ return None;
+ }
+ let (src, dst) = spec.split_once(':').unwrap_or((spec, spec));
+ if dst.strip_prefix("refs/heads/").unwrap_or(dst).starts_with("refs/") {
+ return None;
+ }
+ let src_ok = matches!(src, "HEAD" | "@") || (!super::git::is_sha(src) && (!src.starts_with("refs/") || src.starts_with("refs/heads/")));
+ let dst_ok = if spec.contains(':') {
+ dst.strip_prefix("refs/heads/").unwrap_or(dst) == branch && !dst.starts_with("refs/tags/")
+ } else {
+ matches!(dst, "HEAD" | "@") || dst.strip_prefix("refs/heads/").unwrap_or(dst) == branch
+ };
+ if !src_ok || !dst_ok {
+ return None;
+ }
+ }
+ kept.push(format!("git push {} {sha}:refs/heads/{branch}", w[2]));
+ Some(kept.join(" && "))
+}
+
+/// The card a push goes on: its id, status, branch and commit.
+struct Checked {
+ id: String,
+ status: String,
+ branch: String,
+ head_sha: String,
+}
+
+/// The card a push goes on, and whether its source is `HEAD` or a local branch (see [`pin`]).
+async fn gate_one(state: &AppState, kwant_id: &str, space_id: &str, base: &str, folder: &Path, push: &Push) -> Result<(Checked, bool), String> {
let dir = folder.join(&push.dir);
let repo = Repo::local(&dir, &state.config.data_dir)
.await
@@ -349,8 +474,43 @@ async fn gate_one(state: &AppState, kwant_id: &str, space_id: &str, base: &str,
return Err(format!("kwant checks a push before it goes, and won't pass on the branch name {}.", scan::as_data_up_to(&branch, 80)));
}
let sha = resolve(&repo, &push.src).await.map_err(|e| format!("kwant checks a push before it goes, and couldn't find {} ({e}).", scan::as_data_up_to(&push.src, 80)))?;
+ let local_src = local_branch(&repo, &push.src).await;
drop(repo);
let key = dir.canonicalize().unwrap_or(dir.clone()).to_string_lossy().into_owned();
+ let checked = gate_card(state, kwant_id, space_id, base, &key, &branch, &sha, || Source::Git(dir.clone())).await?;
+ Ok((checked, local_src))
+}
+
+/// Whether a push's source is `HEAD` or a local branch that no tag shares a name with: only
+/// then does [`pin`] write it as a branch.
+async fn local_branch(repo: &Repo, src: &str) -> bool {
+ if src == "HEAD" {
+ return true;
+ }
+ if super::git::is_sha(src) {
+ return false;
+ }
+ match src.strip_prefix("refs/heads/") {
+ Some(name) => repo.resolve(&format!("refs/heads/{name}")).await.is_ok(),
+ None if src.starts_with("refs/") => false,
+ None => repo.resolve(&format!("refs/heads/{src}")).await.is_ok() && repo.resolve(&format!("refs/tags/{src}")).await.is_err(),
+ }
+}
+
+/// The card for `(space, key, branch, sha)`: made (and its checks started from `src`) when there
+/// is none, else what it says now.
+#[allow(clippy::too_many_arguments)]
+async fn gate_card(
+ state: &AppState,
+ kwant_id: &str,
+ space_id: &str,
+ base: &str,
+ key: &str,
+ branch: &str,
+ sha: &str,
+ src: impl FnOnce() -> Source,
+) -> Result<Checked, String> {
+ let (key, branch, sha) = (key.to_string(), branch.to_string(), sha.to_string());
let mut row = state.db.prepush_card_of(space_id, &key, &branch, &sha).await.map_err(|e| format!("kwant couldn't read its pre-push card: {e}"))?;
let mut fresh_start = false;
if let Some(r) = &row {
@@ -360,6 +520,17 @@ async fn gate_one(state: &AppState, kwant_id: &str, space_id: &str, base: &str,
// The person asked for the checks again: a new card, back at try 1
row = None;
fresh_start = true;
+ } else if r.status == PUSHED {
+ // The override let one push go: this one waits for the person again
+ let again = state.db.reblock_pushed_prepush_card(&r.id).await.ok().flatten();
+ if let Some(again) = &again {
+ notify(state, again);
+ }
+ return Err(format!(
+ "The person's override on pre-push card {} was for one push of {branch}, and that push went. Nothing was pushed: \
+ the card is blocked again until the person overrides it again (or a new commit gets a new check).",
+ r.id
+ ));
}
}
let row = match row {
@@ -373,7 +544,7 @@ async fn gate_one(state: &AppState, kwant_id: &str, space_id: &str, base: &str,
match made {
Some(r) => {
notify(state, &r);
- tokio::spawn(check(state.clone(), r.clone(), dir.clone(), base.to_string()));
+ tokio::spawn(check(state.clone(), r.clone(), src(), base.to_string()));
r
}
// Another push of the same commit made it first
@@ -382,7 +553,7 @@ async fn gate_one(state: &AppState, kwant_id: &str, space_id: &str, base: &str,
}
};
match row.status.as_str() {
- CLEAR | OVERRIDDEN => Ok(()),
+ CLEAR | OVERRIDDEN => Ok(Checked { id: row.id, status: row.status, branch, head_sha: sha }),
_ => Err(deny_text(&row)),
}
}
@@ -393,10 +564,28 @@ async fn resolve(repo: &Repo, src: &str) -> Result<String, GitError> {
} else if super::git::is_sha(src) || src.starts_with("refs/") {
repo.resolve(src).await
} else {
- repo.resolve(&format!("refs/heads/{src}")).await
+ match repo.resolve(&format!("refs/heads/{src}")).await {
+ // A bare tag name (`git push origin checkpoint`): its commit gets the card, and the
+ // push runs as written (never pinned, see [`pin`])
+ Err(GitError::NotFound) => repo.resolve(&format!("refs/tags/{src}")).await,
+ r => r,
+ }
}
}
+/// The pushes the person let go anyway on `branch` (Ada's review of #456, Later 6; design
+/// b3-fresh-eyes.md): `[{card_id, head_sha, by, reason, at}]`, newest first, at most three, for
+/// the PR's review card and the review kwant posts. Empty when there were none.
+pub async fn pushed_anyway(state: &AppState, space_id: &str, branch: Option<&str>) -> Value {
+ let Some(branch) = branch.filter(|b| super::routes::valid_branch(b)) else { return json!([]) };
+ let rows = state.db.prepush_overrides_on(space_id, branch, 3).await.unwrap_or_default();
+ Value::Array(
+ rows.iter()
+ .map(|r| json!({"card_id": r.id, "head_sha": r.head_sha, "by": r.overridden_by, "reason": r.override_reason, "at": r.overridden_at}))
+ .collect(),
+ )
+}
+
/// Sends `dev_prepush {space_id, id, kwant_id, status}` on the event stream.
pub fn notify(state: &AppState, row: &PrepushRow) {
let _ = state.event_sender.send(RuntimeEvent::DevPrepush {
@@ -410,16 +599,27 @@ pub fn notify(state: &AppState, row: &PrepushRow) {
// ---------------------------------------------------------------------------------------------
// The checks
-/// Runs the checks for card `row` and stores the verdict.
-pub async fn check(state: AppState, row: PrepushRow, dir: PathBuf, base: String) {
- let (status, card) = match tokio::time::timeout(CHECK_TIMEOUT, build(&state, &row, &dir, &base)).await {
- Ok(Ok(card)) => {
- let status = if card["blockers"].as_array().is_some_and(|b| !b.is_empty()) { BLOCKED } else { CLEAR };
- (status, card)
- }
- Ok(Err(why)) => (PREPUSH_FAILED, failed_card(&row, &why)),
- Err(_) => (PREPUSH_FAILED, failed_card(&row, "the checks took longer than 12 minutes")),
- };
+/// How long the one automatic retry waits after a check that errored.
+const RETRY_PAUSE: Duration = Duration::from_secs(5);
+
+/// Runs the checks for card `row` and stores the verdict. A check that errored (kwant couldn't
+/// read the repo, or the reviewer's turn didn't answer) runs once more on its own before the
+/// card waits for the person (Ada's review of #456, Later 6): at most one more reviewer turn,
+/// within the same [`CHECK_TIMEOUT`]; a timeout is never retried.
+pub async fn check(state: AppState, row: PrepushRow, src: Source, base: String) {
+ let started = std::time::Instant::now();
+ let mut outcome = attempt(&state, &row, &src, &base, CHECK_TIMEOUT).await;
+ let mut retried = false;
+ if errored(outcome.0, &outcome.1) && started.elapsed() < CHECK_TIMEOUT / 2 {
+ tokio::time::sleep(RETRY_PAUSE).await;
+ let left = CHECK_TIMEOUT.saturating_sub(started.elapsed());
+ outcome = attempt(&state, &row, &src, &base, left).await;
+ retried = true;
+ }
+ let (status, mut card) = outcome;
+ if retried {
+ card["auto_retried"] = json!(true);
+ }
match state.db.finish_prepush_card(&row.id, status, &card.to_string()).await {
Ok(Some(r)) => notify(&state, &r),
Ok(None) => {}
@@ -427,6 +627,46 @@ pub async fn check(state: AppState, row: PrepushRow, dir: PathBuf, base: String)
}
}
+/// What a card checks: the commits in a repo kwant can read, or the files a GitHub tool sends.
+#[derive(Debug, Clone)]
+pub enum Source {
+ Git(PathBuf),
+ Mcp(McpWrite),
+}
+
+async fn attempt(state: &AppState, row: &PrepushRow, src: &Source, base: &str, limit: Duration) -> (&'static str, Value) {
+ let built = async {
+ match src {
+ Source::Git(dir) => build(state, row, dir, base).await,
+ Source::Mcp(write) => build_mcp(state, row, write, base).await,
+ }
+ };
+ match tokio::time::timeout(limit, built).await {
+ Ok(Ok(card)) => {
+ let status = if card["blockers"].as_array().is_some_and(|b| !b.is_empty()) { BLOCKED } else { CLEAR };
+ (status, card)
+ }
+ Ok(Err(why)) => (PREPUSH_FAILED, failed_card(row, &why)),
+ Err(_) => {
+ let mut card = failed_card(row, "the checks took longer than 12 minutes");
+ card["timed_out"] = json!(true);
+ (PREPUSH_FAILED, card)
+ }
+ }
+}
+
+/// Whether a check errored rather than found something: kwant couldn't check (not a timeout),
+/// or the fresh-eyes reviewer's turn didn't answer (`review_failed`, set by [`judge`]). A
+/// finding, a hit or "no reviewer" is a verdict, never retried: a reviewer's own critical or
+/// high finding also carries `source: "review"`, so the blocker's source can't tell the two
+/// apart (Ada's review of #472, must-fix 3).
+pub fn errored(status: &str, card: &Value) -> bool {
+ if status == PREPUSH_FAILED {
+ return card["timed_out"] != json!(true);
+ }
+ card["review_failed"] == json!(true)
+}
+
fn failed_card(row: &PrepushRow, why: &str) -> Value {
json!({"kind": "prepush", "branch": row.branch, "head_sha": row.head_sha, "error": why,
"blockers": [{"source": "kwant", "severity": "high", "title": format!("kwant couldn't check this push: {why}"), "file": null, "line": null}]})
@@ -475,7 +715,16 @@ async fn build(state: &AppState, row: &PrepushRow, dir: &Path, base: &str) -> Re
let semgrep = semgrep(&repo, &row.head_sha, &files).await;
security.findings.extend(semgrep.1.iter().cloned());
drop(repo);
+ let mut card = judge(state, row, base, title, files, security).await;
+ card["base_sha"] = json!(merge_base);
+ card["diffstat"] = diffstat;
+ card["security"]["semgrep"] = serde_json::to_value(&semgrep.0).unwrap_or(Value::Null);
+ Ok(card)
+}
+/// The checks every card gets once its files are read: the review card's rules over `files`
+/// and `security`, then one reviewer turn by another bot that sees only the diff.
+async fn judge(state: &AppState, row: &PrepushRow, base: &str, title: String, files: Vec<FileDiff>, security: scan::Security) -> Value {
let kwant = state.db.get_kwant(&row.kwant_id).await.ok().flatten();
let author = Author {
login: None,
@@ -516,11 +765,200 @@ async fn build(state: &AppState, row: &PrepushRow, dir: &Path, base: &str) -> Re
let (status, mut card) = super::review::card_for(&facts, picked.as_ref(), model.as_mut(), None).await;
card["kind"] = json!("prepush");
card["head_sha"] = json!(row.head_sha);
- card["base_sha"] = json!(merge_base);
- card["diffstat"] = diffstat;
- card["security"]["semgrep"] = serde_json::to_value(&semgrep.0).unwrap_or(Value::Null);
let failed = status == crate::db::dev_mode::FAILED;
card["blockers"] = Value::Array(blockers(&card, failed));
+ if failed {
+ card["review_failed"] = json!(true);
+ }
+ card
+}
+
+// ---------------------------------------------------------------------------------------------
+// kwant's own GitHub tools (Ada's review of #456, Later 6a)
+
+/// A write a GitHub MCP tool (GitHub's own server, or Composio's GitHub tools) makes to a branch:
+/// it commits on GitHub without a local push, so it gets the same card.
+#[derive(Debug, Clone, PartialEq)]
+pub struct McpWrite {
+ pub owner: String,
+ pub repo: String,
+ /// `None`: the tool names no branch (GitHub then writes to the default branch).
+ pub branch: Option<String>,
+ pub message: String,
+ /// Each file it writes, with its new text; `None` deletes the file.
+ pub files: Vec<(String, Option<String>)>,
+}
+
+/// How many files of one write are read; a write with more is refused.
+const MCP_FILES: usize = 100;
+
+/// The GitHub writes an MCP call makes: GitHub's server (`push_files`, `create_or_update_file`,
+/// `delete_file`), Composio's slugs (`GITHUB_COMMIT_MULTIPLE_FILES`,
+/// `GITHUB_CREATE_OR_UPDATE_FILE_CONTENTS`, `GITHUB_DELETE_A_FILE`), and those inside a
+/// Composio multi-execute call. A call names a repo (`owner` and `repo`), or it isn't one.
+pub fn mcp_writes(tool: &str, args: &Value) -> Vec<McpWrite> {
+ let mut out = Vec::new();
+ collect_writes(tool, args, &mut out, 0);
+ out
+}
+
+fn collect_writes(tool: &str, args: &Value, out: &mut Vec<McpWrite>, depth: usize) {
+ if depth > 2 || out.len() > 20 {
+ return;
+ }
+ // Composio's multi-execute: `tools: [{tool_slug, arguments}]`
+ if let Some(list) = args["tools"].as_array() {
+ for t in list {
+ if let Some(slug) = t["tool_slug"].as_str().or(t["slug"].as_str()) {
+ collect_writes(slug, &t["arguments"], out, depth + 1);
+ }
+ }
+ }
+ let name = tool.to_ascii_lowercase();
+ let name = name.strip_prefix("github_").unwrap_or(&name);
+ let kind = match name {
+ "push_files" | "commit_multiple_files" => 'm',
+ "create_or_update_file" | "create_or_update_file_contents" => 'w',
+ "delete_file" | "delete_a_file" => 'd',
+ _ => return,
+ };
+ let (Some(owner), Some(repo)) = (args["owner"].as_str(), args["repo"].as_str()) else { return };
+ let text = |f: &Value| -> Option<String> {
+ let content = f["content"].as_str()?;
+ if f["encoding"].as_str().is_some_and(|e| e.eq_ignore_ascii_case("base64")) {
+ use base64::Engine as _;
+ let bytes = base64::engine::general_purpose::STANDARD.decode(content.split_whitespace().collect::<String>()).ok()?;
+ return Some(String::from_utf8_lossy(&bytes).into_owned());
+ }
+ Some(content.to_string())
+ };
+ let mut files = Vec::new();
+ match kind {
+ 'w' => files.push((args["path"].as_str().unwrap_or("").to_string(), Some(text(args).unwrap_or_default()))),
+ 'd' => files.push((args["path"].as_str().unwrap_or("").to_string(), None)),
+ _ => {
+ for key in ["files", "upserts", "additions"] {
+ for f in args[key].as_array().into_iter().flatten() {
+ files.push((f["path"].as_str().unwrap_or("").to_string(), Some(text(f).unwrap_or_default())));
+ }
+ }
+ for key in ["deletes", "deletions"] {
+ for f in args[key].as_array().into_iter().flatten() {
+ let path = f.as_str().or(f["path"].as_str()).unwrap_or("");
+ files.push((path.to_string(), None));
+ }
+ }
+ }
+ }
+ out.push(McpWrite {
+ owner: owner.to_string(),
+ repo: repo.to_string(),
+ branch: args["branch"].as_str().map(str::trim).filter(|b| !b.is_empty()).map(String::from),
+ message: args["message"].as_str().unwrap_or("").to_string(),
+ files,
+ });
+}
+
+/// A stand-in commit id for a write that has none yet: the first 40 hex digits of the SHA-256 of
+/// the tool and its arguments (keys sorted), so the same call again is the same card.
+pub fn write_id(tool: &str, args: &Value) -> String {
+ use sha2::{Digest, Sha256};
+ let mut h = Sha256::new();
+ h.update(tool.as_bytes());
+ h.update([0u8]);
+ h.update(args.to_string().as_bytes());
+ let hex: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
+ hex[..40].to_string()
+}
+
+/// [`check_command`] for an MCP call: `Ok` when it writes to no GitHub branch, Dev mode is off,
+/// or the production floor asks instead; else its card must be `clear` or `overridden`. Call
+/// [`use_up`] once the call is allowed. The card's folder is `mcp:<server>/<owner>/<repo>`.
+pub async fn check_mcp(state: &AppState, kwant_id: &str, server: &str, tool: &str, args: &Value) -> Result<Pass, String> {
+ if server == crate::mcp::SELF_SERVER_NAME {
+ return Ok(Pass::default());
+ }
+ let writes = mcp_writes(tool, args);
+ if writes.is_empty() {
+ return Ok(Pass::default());
+ }
+ let Some((space_id, ctx)) = super::floor::ctx_for_kwant(&state.db, kwant_id, None).await else {
+ return Ok(Pass::default());
+ };
+ let req = crate::mcp::ToolApprovalRequest {
+ kwant_id: kwant_id.to_string(),
+ kwant_name: String::new(),
+ turn_id: String::new(),
+ tool_name: format!("mcp__{server}__{tool}"),
+ server: server.to_string(),
+ tool: tool.to_string(),
+ arguments: args.clone(),
+ builtin: None,
+ smart: None,
+ payment: None,
+ };
+ if prod_floor::reason(&req, &ctx).is_some() {
+ return Ok(Pass::default());
+ }
+ if writes.len() > 1 {
+ return Err(format!("{RUN_ALONE_MCP} This call makes {} GitHub writes: make each one its own call.", writes.len()));
+ }
+ let write = writes.into_iter().next().unwrap_or_else(|| unreachable!());
+ let Some(branch) = write.branch.clone() else {
+ return Err(format!("{RUN_ALONE_MCP} This call names no branch, so GitHub would write to the repo's default branch: name your own branch."));
+ };
+ if !super::routes::valid_branch(&branch) {
+ return Err(format!("kwant checks a GitHub write before it goes, and won't pass on the branch name {}.", scan::as_data_up_to(&branch, 80)));
+ }
+ if write.files.is_empty() || write.files.len() > MCP_FILES || write.files.iter().any(|(p, _)| p.trim().is_empty()) {
+ return Err(format!("{RUN_ALONE_MCP} kwant reads up to {MCP_FILES} files a write sends, each with a path."));
+ }
+ let key = format!("mcp:{server}/{}/{}", write.owner, write.repo);
+ let sha = write_id(tool, args);
+ let checked = gate_card(state, kwant_id, &space_id, &ctx.branch, &key, &branch, &sha, || Source::Mcp(write.clone())).await?;
+ let mut pass = Pass::default();
+ if checked.status == OVERRIDDEN {
+ pass.overrides.push(checked.id);
+ }
+ Ok(pass)
+}
+
+/// What the bot is told about a GitHub write kwant won't check as it stands.
+const RUN_ALONE_MCP: &str = "kwant checks what a GitHub tool commits before it goes, the same way it checks a push.";
+
+/// The card for a GitHub write: the files it sends, as added (or removed) lines. Semgrep needs a
+/// checkout, so it doesn't run.
+async fn build_mcp(state: &AppState, row: &PrepushRow, write: &McpWrite, base: &str) -> Result<Value, String> {
+ let mut files = Vec::new();
+ let mut contents = BTreeMap::new();
+ for (path, text) in &write.files {
+ match text {
+ Some(text) => {
+ let lines = text.lines().count() as u64;
+ let mut patch = format!("@@ -0,0 +1,{lines} @@\n");
+ for l in text.lines() {
+ if patch.len() > super::facts::DIFF_CHARS {
+ break;
+ }
+ patch.push('+');
+ patch.push_str(l);
+ patch.push('\n');
+ }
+ files.push(FileDiff { path: path.clone(), status: "added".into(), additions: lines, deletions: 0, patch: Some(patch), previous_path: None });
+ if contents.len() < 20 {
+ contents.insert(path.clone(), text.clone());
+ }
+ }
+ None => files.push(FileDiff { path: path.clone(), status: "removed".into(), additions: 0, deletions: 0, patch: None, previous_path: None }),
+ }
+ }
+ let diffstat = json!({"files": files.len(), "add": files.iter().map(|f| f.additions).sum::<u64>(), "del": 0});
+ let security = scan::scan_and_hide(&scan::Config::new(&state.config.data_dir), &mut files, contents, None).await;
+ let title = Some(write.message.lines().next().unwrap_or("").trim().to_string()).filter(|t| !t.is_empty()).unwrap_or_else(|| format!("GitHub write to {}", row.branch));
+ let mut card = judge(state, row, base, title, files, security).await;
+ card["diffstat"] = diffstat;
+ card["mcp"] = json!({"owner": write.owner, "repo": write.repo});
+ card["security"]["semgrep"] = serde_json::to_value(Tile::not_run("a GitHub tool's write has no checkout to run semgrep in")).unwrap_or(Value::Null);
Ok(card)
}
@@ -681,7 +1119,13 @@ pub fn card_json(row: &PrepushRow) -> Value {
"diffstat": card.as_ref().map(|c| c["diffstat"].clone()).filter(|d| !d.is_null()),
"checks": checks(&row.status, card.as_ref()),
"blockers": card.as_ref().and_then(|c| c["blockers"].as_array().cloned()).unwrap_or_default(),
- "override": row.overridden_by.as_ref().map(|by| json!({"by": by, "reason": row.override_reason, "at": row.overridden_at})),
+ // The person's override, while it stands (`overridden`) or once its one push went
+ // (`pushed`). A card blocked again after that keeps it in `last_override`.
+ "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})),
+ "override_used": row.status == PUSHED,
+ // The checks ran a second time on their own after the first try errored
+ "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,
"overridden_by": row.overridden_by,
"overridden_at": row.overridden_at,
@@ -873,6 +1317,46 @@ pub async fn retry_card(
mod tests {
use super::*;
+ #[test]
+ fn github_writes_are_read_from_each_tool_shape() {
+ let w = |branch: &str| json!({"owner": "o", "repo": "r", "branch": branch, "message": "Add a\nmore"});
+ let mut a = w("juno-x");
+ a["files"] = json!([{"path": "src/a.rs", "content": "fn a() {}"}, {"path": "b.md", "content": "hi"}]);
+ assert_eq!(
+ mcp_writes("push_files", &a),
+ [McpWrite { owner: "o".into(), repo: "r".into(), branch: Some("juno-x".into()), message: "Add a\nmore".into(),
+ files: vec![("src/a.rs".into(), Some("fn a() {}".into())), ("b.md".into(), Some("hi".into()))] }]
+ );
+ let mut c = w("juno-x");
+ c["upserts"] = json!([{"path": "x.txt", "content": "aGVsbG8=", "encoding": "base64"}]);
+ c["deletes"] = json!(["old.txt", {"path": "older.txt"}]);
+ assert_eq!(
+ mcp_writes("GITHUB_COMMIT_MULTIPLE_FILES", &c)[0].files,
+ [("x.txt".to_string(), Some("hello".to_string())), ("old.txt".into(), None), ("older.txt".into(), None)]
+ );
+ let mut d = w("");
+ d["path"] = json!("gone.rs");
+ let del = mcp_writes("GITHUB_DELETE_A_FILE", &d);
+ assert_eq!((del[0].branch.as_deref(), del[0].files.clone()), (None, vec![("gone.rs".to_string(), None)]));
+ let multi = json!({"tools": [{"tool_slug": "GITHUB_CREATE_OR_UPDATE_FILE_CONTENTS", "arguments": {"owner": "o", "repo": "r", "branch": "b", "path": "p", "content": "t"}}]});
+ assert_eq!(mcp_writes("COMPOSIO_MULTI_EXECUTE_TOOL", &multi).len(), 1);
+ // Not writes: reads, other tools, and a "delete_file" that names no repo (a file server's)
+ for (tool, args) in [("get_file_contents", w("b")), ("create_issue", w("b")), ("delete_file", json!({"path": "x"}))] {
+ assert!(mcp_writes(tool, &args).is_empty(), "{tool}");
+ }
+ }
+
+ #[test]
+ fn the_same_github_write_is_the_same_card() {
+ let a = json!({"owner": "o", "repo": "r", "branch": "b", "path": "p", "content": "t"});
+ let b = json!({"content": "t", "path": "p", "branch": "b", "repo": "r", "owner": "o"});
+ let id = write_id("create_or_update_file", &a);
+ assert!(super::super::git::is_sha(&id), "{id}");
+ assert_eq!(id, write_id("create_or_update_file", &b), "key order doesn't matter");
+ assert_ne!(id, write_id("create_or_update_file", &json!({"owner": "o", "repo": "r", "branch": "b", "path": "p", "content": "u"})));
+ assert_ne!(id, write_id("push_files", &a));
+ }
+
fn one(src: &str, dst: Option<&str>) -> Push {
Push { dir: PathBuf::new(), src: src.into(), dst: dst.map(str::to_string) }
}
@@ -956,6 +1440,133 @@ mod tests {
}
}
+ /// Ada's review of #456, Later 6: only a check that errored runs again on its own.
+ #[test]
+ fn only_an_errored_check_runs_again_on_its_own() {
+ 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,
+ };
+ 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");
+ slow["timed_out"] = json!(true);
+ assert!(!errored(PREPUSH_FAILED, &slow), "a timeout isn't run again");
+ let review = json!({"review_failed": true, "blockers": [{"source": "review", "severity": "high", "title": "The fresh-eyes review didn't finish"}]});
+ assert!(errored(BLOCKED, &review));
+ // Ada's review of #472, must-fix 3: the reviewer's own high finding is a verdict
+ let real = json!({"blockers": [{"source": "review", "severity": "high", "title": "count() returns 4 for any input", "file": "src/widgets.rs", "line": 2}]});
+ assert!(!errored(BLOCKED, &real), "a real finding is never run again");
+ assert!(!errored(BLOCKED, &json!({"review_failed": false, "blockers": real["blockers"]})));
+ let found = json!({"blockers": [{"source": "tamper", "severity": "high", "title": "A test was switched off"}]});
+ assert!(!errored(BLOCKED, &found), "a finding is a verdict");
+ assert!(!errored(CLEAR, &json!({"blockers": []})));
+ }
+
+ /// Ada's review of #456, Later 13: the text reads as one sentence, with no runs of spaces.
+ #[test]
+ fn the_run_alone_text_has_single_spaces() {
+ assert!(!RUN_ALONE.contains(" "), "{RUN_ALONE}");
+ assert!(RUN_ALONE.contains("run before `git push` in the same command") && RUN_ALONE.contains("first, then run"), "{RUN_ALONE}");
+ }
+
+ /// Ada's review of #456, Later 8: a plain push goes pinned to the checked commit, so a
+ /// commit made by a parallel call in the same turn isn't what goes; any other shape runs as
+ /// written.
+ #[test]
+ fn a_plain_push_is_pinned_to_the_checked_commit() {
+ let sha = "0123456789abcdef0123456789abcdef01234567";
+ let pinned = |cmd: &str| pin(cmd, sha, "juno-x", true);
+ let want = format!("git push origin {sha}:refs/heads/juno-x");
+ for cmd in ["git push origin", "git push origin juno-x", "git push origin HEAD", "git push origin HEAD:juno-x", " git push origin juno-x "] {
+ assert_eq!(pinned(cmd), Some(want.clone()), "{cmd}");
+ }
+ assert_eq!(pinned("cd kwant && cd sub && git push origin juno-x"), Some(format!("cd kwant && cd sub && {want}")));
+ assert_eq!(pinned("git push upstream juno-x"), Some(format!("git push upstream {sha}:refs/heads/juno-x")));
+ for cmd in [
+ "git push",
+ "git push -u origin juno-x",
+ "git push origin juno-x --force",
+ "git push origin +juno-x",
+ "git push origin a b",
+ "git push origin juno-x && git log -1",
+ "git push origin juno-x; git log -1",
+ "git push origin $(git commit -qam x; echo juno-x)",
+ "git push origin `echo juno-x`",
+ "git push 'origin' juno-x",
+ "git push origin juno-x > /tmp/out",
+ "git push origin juno-x\ngit push origin y",
+ "env X=1 git push origin juno-x",
+ "cd /tmp && git push origin juno-x",
+ "cd ../x && git push origin juno-x",
+ "cd a b && git push origin juno-x",
+ "git push origin juno-x || true",
+ ] {
+ assert_eq!(pinned(cmd), None, "{cmd}");
+ }
+ // Never with a commit or a branch kwant can't vouch for
+ assert_eq!(pin("git push origin juno-x", "HEAD", "juno-x", true), None);
+ assert_eq!(pin("git push origin juno-x", sha, "bad branch", true), None);
+ }
+
+ /// Ada's review of #472, must-fix 1: only a branch push is pinned. A tag, a commit sha or
+ /// another ref as the source, or a tag or another branch as the destination, runs as
+ /// written (its card still gates it).
+ #[test]
+ fn only_a_branch_push_is_pinned() {
+ let sha = "0123456789abcdef0123456789abcdef01234567";
+ let want = |b: &str| Some(format!("git push origin {sha}:refs/heads/{b}"));
+ // The source isn't a local branch (the caller found a tag, or nothing, under that name)
+ assert_eq!(pin("git push origin checkpoint", sha, "checkpoint", false), None);
+ assert_eq!(pin("git push origin", sha, "juno-x", false), None);
+ // Branch pushes still pin
+ assert_eq!(pin("git push origin HEAD:feature", sha, "feature", true), want("feature"));
+ assert_eq!(pin("git push origin @:feature", sha, "feature", true), want("feature"));
+ assert_eq!(pin("git push origin juno-x:refs/heads/juno-x", sha, "juno-x", true), want("juno-x"));
+ assert_eq!(pin("git push origin refs/heads/juno-x", sha, "juno-x", true), want("juno-x"));
+ assert_eq!(pin("git push origin HEAD", sha, "juno-x", true), want("juno-x"));
+ for cmd in [
+ "git push origin HEAD:refs/tags/x",
+ "git push origin juno-x:refs/tags/juno-x",
+ "git push origin refs/tags/x:x",
+ "git push origin refs/remotes/origin/x:x",
+ "git push origin 0123456789abcdef0123456789abcdef01234567",
+ "git push origin 0123456789abcdef0123456789abcdef01234567:x",
+ "git push origin HEAD:other",
+ "git push origin juno-x:refs/notes/x",
+ ] {
+ assert_eq!(pin(cmd, sha, "x", true), None, "{cmd}");
+ }
+ assert_eq!(pin("git push origin juno-x:refs/tags/juno-x", sha, "juno-x", true), None);
+ }
+
+ /// Ada's review of #472, round 2, must-fix 1: `pin` driven the way [`gate_one`] drives it,
+ /// with `branch` taken from the parsed push's destination. A destination under `refs/` other
+ /// than `refs/heads/` runs as written instead of becoming a branch of that name.
+ #[test]
+ fn a_push_to_another_ref_is_not_pinned_as_the_caller_drives_it() {
+ let sha = "0123456789abcdef0123456789abcdef01234567";
+ let pinned = |cmd: &str| {
+ let Parsed::Pushes(p) = pushes(cmd) else { panic!("{cmd} isn't a push") };
+ assert_eq!(p.len(), 1, "{cmd}");
+ // As gate_one: the destination, or the checked-out branch for a bare HEAD
+ let branch = p[0].dst.clone().unwrap_or_else(|| "juno-x".to_string());
+ // gate_one passes it on: valid_branch accepts `refs/notes/x` too
+ assert!(crate::server::dev::routes::valid_branch(&branch), "{cmd}: {branch}");
+ pin(cmd, sha, &branch, true)
+ };
+ for cmd in [
+ "git push origin juno-x:refs/notes/x",
+ "git push origin HEAD:refs/remotes/origin/x",
+ "git push origin HEAD:refs/pull/1/head",
+ "git push origin juno-x:refs/heads/refs/notes/x",
+ ] {
+ assert_eq!(pinned(cmd), None, "{cmd}");
+ }
+ assert_eq!(pinned("git push origin HEAD:refs/heads/feature"), Some(format!("git push origin {sha}:refs/heads/feature")));
+ assert_eq!(pinned("git push origin juno-x"), Some(format!("git push origin {sha}:refs/heads/juno-x")));
+ assert_eq!(pinned("git push origin HEAD"), Some(format!("git push origin {sha}:refs/heads/juno-x")));
+ }
+
/// Ada's review of #456, must-fix 2: the gate reads the commit before the command runs, so a
/// commit (or amend, pull, merge, reset...) before the push in the same command is refused.
#[test]
diff --git a/src/server/fresh_eyes.rs b/src/server/fresh_eyes.rs
index 461b23f0..462ca257 100644
--- a/src/server/fresh_eyes.rs
+++ b/src/server/fresh_eyes.rs
@@ -8,31 +8,40 @@
//! saved summary or cached prefix back from the store (`TurnInput::fresh_eyes`);
//! - gets none of the reviewer's own notes or lessons in its prompt, only the person's pinned team
//! and channel instructions;
-//! - is registered here for as long as it runs, and kwant's own tools that read other chats, notes,
-//! tasks or hand-offs refuse during it ([`BLOCKED_TOOLS`]).
+//! - is registered here for as long as it runs, and of kwant's own tools only [`ALLOWED_TOOLS`]
+//! are offered and run during it: a tool added later (one that reads chats, notes or facts
+//! included) is off in a review until it is put on that list.
use serde_json::{json, Value};
use std::collections::HashSet;
use std::sync::{LazyLock, Mutex};
-/// kwant's own tools a fresh-eyes turn neither sees nor runs: each reads something besides the
-/// brief and the result (chats, the reviewer's notes, other tasks' notes, hand-off results,
-/// attachments of chats, the team's truth ledger; `task_cite_fact` reads a fact onto a card).
-pub const BLOCKED_TOOLS: &[&str] = &[
- "search_history",
- "memory_search",
- "task_list",
- "delegation_status",
- "list_attachments",
- "read_attachment",
- "fact_search",
- "fact_get",
- "task_cite_fact",
+/// The only kwant tools a fresh-eyes turn sees and runs (an allowlist, Rigel's QA of #456,
+/// finding B): the two that record a review's verdict, and the bot browser and page source for a
+/// result that is a web page. Nothing here reads a chat, a note, a memory, a fact, another task or
+/// a hand-off. Any other tool, including one added later, is hidden and refused.
+pub const ALLOWED_TOOLS: &[&str] = &[
+ // A hand-off review's verdict (delegation.rs, lead review)
+ "task_review",
+ // The Swarm Auditor's challenge
+ "audit_challenge",
+ // Looking at a result that is a web page
+ "browser_open",
+ "browser_page",
+ "browser_act",
+ "browser_cite",
+ "browser_screenshot",
+ "page_source",
];
+/// Whether a fresh-eyes turn may see and run the kwant tool `name`.
+pub fn allowed(name: &str) -> bool {
+ ALLOWED_TOOLS.contains(&name)
+}
+
/// What a blocked tool answers.
pub const REFUSED_TEXT: &str = "This is a fresh-eyes review: judge only the brief or spec and the result in your prompt. \
- Tools that read chats, notes, other tasks or hand-offs are off for this turn.";
+ Only the tools that record your verdict and the browser are on for this turn.";
/// The parts a fresh-eyes reviewer is shown, in the order the label lists them.
pub const SAW_BRIEF: &str = "brief";
@@ -63,18 +72,18 @@ pub fn is_fresh(turn_id: Option<&str>) -> bool {
turn_id.is_some_and(|id| FRESH.lock().unwrap_or_else(|e| e.into_inner()).contains(id))
}
-/// Whether a fresh-eyes turn refuses the kwant tool `name`.
+/// Whether a fresh-eyes turn refuses the kwant tool `name`: any tool not in [`ALLOWED_TOOLS`].
pub fn refuses(turn_id: Option<&str>, name: &str) -> bool {
- BLOCKED_TOOLS.contains(&name) && is_fresh(turn_id)
+ !allowed(name) && is_fresh(turn_id)
}
-/// Drops the blocked tools from a `tools/list` answer for a fresh-eyes turn.
+/// Keeps only [`ALLOWED_TOOLS`] in a `tools/list` answer for a fresh-eyes turn.
pub fn filter_tools(turn_id: Option<&str>, tools: &mut Value) {
if !is_fresh(turn_id) {
return;
}
if let Some(list) = tools.as_array_mut() {
- list.retain(|t| !t["name"].as_str().is_some_and(|n| BLOCKED_TOOLS.contains(&n)));
+ list.retain(|t| t["name"].as_str().is_some_and(allowed));
}
}
@@ -107,8 +116,13 @@ mod tests {
for t in ["fact_search", "fact_get", "task_cite_fact"] {
assert!(refuses(Some("fe-turn-1"), t), "{t}");
}
- assert!(!refuses(Some("fe-turn-1"), "fact_propose"), "proposing a fact reads nothing back");
+ // An allowlist: anything not on it is off, writes and lookups alike
+ for t in ["fact_propose", "fact_dispute", "memory_add", "delegate", "skill_get", "bot_list", "ask_user", "a_tool_added_next_year"] {
+ assert!(refuses(Some("fe-turn-1"), t), "{t}");
+ }
assert!(!refuses(Some("fe-turn-1"), "audit_challenge"), "the review's own tools still run");
+ assert!(!refuses(Some("fe-turn-1"), "task_review"));
+ assert!(!refuses(Some("fe-turn-1"), "browser_page"));
assert!(!refuses(Some("fe-turn-2"), "search_history"), "another turn is untouched");
assert!(!refuses(None, "search_history"));
}
@@ -116,13 +130,15 @@ mod tests {
}
#[test]
- fn blocked_tools_are_hidden_from_a_fresh_turns_list() {
+ fn only_allowed_tools_are_in_a_fresh_turns_list() {
let _g = Guard::new("fe-turn-list");
let mut tools = json!([{"name": "search_history"}, {"name": "task_review"}, {"name": "memory_search"}, {"name": "fact_search"},
- {"name": "fact_get"}, {"name": "task_cite_fact"}, {"name": "audit_challenge"}]);
+ {"name": "fact_get"}, {"name": "task_cite_fact"}, {"name": "audit_challenge"}, {"name": "fact_propose"},
+ {"name": "chat_reader_added_later"}, {"name": "browser_page"}, {"description": "no name"}]);
filter_tools(Some("fe-turn-list"), &mut tools);
let names: Vec<&str> = tools.as_array().unwrap().iter().filter_map(|t| t["name"].as_str()).collect();
- assert_eq!(names, ["task_review", "audit_challenge"]);
+ assert_eq!(names, ["task_review", "audit_challenge", "browser_page"], "an unknown tool is absent");
+ assert_eq!(tools.as_array().unwrap().len(), 3, "a tool with no name is dropped too");
let mut other = json!([{"name": "search_history"}]);
filter_tools(Some("not-fresh"), &mut other);
assert_eq!(other.as_array().unwrap().len(), 1);
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index a9577524..208bd1c0 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -592,6 +592,40 @@ impl ToolApprover for RehearseApprover {
}
}
+/// Puts the pre-push card (B2) in front of `inner` for MCP calls that write to a GitHub branch
+/// (Ada's review of #456, Later 6a); everything else is `inner`'s.
+pub struct PrepushApprover {
+ pub inner: Arc<dyn ToolApprover>,
+ pub state: AppState,
+}
+
+#[async_trait]
+impl ToolApprover for PrepushApprover {
+ async fn approve(&self, req: ToolApprovalRequest) -> bool {
+ self.inner.approve(req).await
+ }
+
+ async fn decide(&self, req: ToolApprovalRequest) -> ApprovalOutcome {
+ self.inner.decide(req).await
+ }
+
+ async fn note(&self, req: &ToolApprovalRequest, decision: &'static str, approval_id: Option<&str>) {
+ self.inner.note(req, decision, approval_id).await
+ }
+
+ async fn tier_gate(&self, req: &ToolApprovalRequest) -> Option<String> {
+ 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_use(&self, overrides: &[String]) -> Option<String> {
+ super::dev::prepush::use_up(&self.state, &super::dev::prepush::Pass { overrides: overrides.to_vec(), pinned: None }).await
+ }
+}
+
/// [`prepare_turn_with_self`] with [`TurnApprovalOpts`].
pub async fn prepare_turn_with_opts(
state: &AppState,
@@ -651,18 +685,22 @@ pub async fn prepare_turn_with_opts(
always_ask: opts.always_ask,
data_dir: state.config.data_dir.clone(),
});
+ let approver: Arc<dyn ToolApprover> = if let Some(log) = opts.rehearse.clone() {
+ Arc::new(RehearseApprover { log })
+ } else if opts.purpose.as_deref() == Some(super::dev::tickets::BRIEF_PURPOSE) {
+ // A Dev mode brief only reads, whatever the ticket says (J7)
+ Arc::new(super::dev::tickets::tools::BriefApprover { inner: broker_approver })
+ } else if self_tools {
+ Arc::new(super::continuity::SelfToolsApprover { inner: broker_approver, always_ask: opts.always_ask, browser })
+ } else {
+ broker_approver
+ };
+ // A dry run writes nothing, so it needs no pre-push card
+ let approver: Arc<dyn ToolApprover> =
+ if opts.rehearse.is_some() { approver } else { Arc::new(PrepushApprover { inner: approver, state: state.clone() }) };
let ctx = McpTurnContext {
servers,
- approver: if let Some(log) = opts.rehearse.clone() {
- Arc::new(RehearseApprover { log })
- } else if opts.purpose.as_deref() == Some(super::dev::tickets::BRIEF_PURPOSE) {
- // A Dev mode brief only reads, whatever the ticket says (J7)
- Arc::new(super::dev::tickets::tools::BriefApprover { inner: broker_approver })
- } else if self_tools {
- Arc::new(super::continuity::SelfToolsApprover { inner: broker_approver, always_ask: opts.always_ask, browser })
- } else {
- broker_approver
- },
+ approver,
config_dir: state.config.data_dir.join("mcp"),
permission_url: Some(format!("{}/api/mcp/permission/{token}", local_base_url(state))),
gateway: Some(GatewayAccess { url: format!("{}/api/mcp/gateway", local_base_url(state)), token: token.clone() }),
@@ -930,13 +968,30 @@ pub async fn permission_endpoint(
let args = &msg["params"]["arguments"];
// B2: a bot's own push in a Dev mode space waits for its pre-push card, before any
// allow rule (each Bash call starts in the bot's folder)
- let prepush = match (args["tool_name"].as_str(), args["input"]["command"].as_str(), mcp::builtin_tools::canonical_folder(session.cwd.as_deref())) {
- (Some("Bash"), Some(command), Some(folder)) => super::dev::prepush::gate(&state, &session.kwant_id, command, &folder).await,
- _ => None,
+ let tool_name = args["tool_name"].as_str().unwrap_or("");
+ let prepush = match (tool_name, args["input"]["command"].as_str(), mcp::builtin_tools::canonical_folder(session.cwd.as_deref())) {
+ ("Bash", Some(command), Some(folder)) => super::dev::prepush::check_command(&state, &session.kwant_id, command, &folder).await,
+ // claude calls the bot's MCP servers itself: a write to a GitHub branch asks here (6a)
+ _ => match mcp::split_tool_name(tool_name).filter(|(server, _)| session.ctx.servers.iter().any(|s| s.name == *server)) {
+ Some((server, tool)) => Box::pin(super::dev::prepush::check_mcp(&state, &session.kwant_id, server, tool, &args["input"])).await,
+ None => Ok(Default::default()),
+ },
};
let decision = match prepush {
- Some(why) => json!({"behavior": "deny", "message": why}),
- None => decide(&session, args, smart).await,
+ Err(why) => json!({"behavior": "deny", "message": why}),
+ Ok(pass) => {
+ let mut decision = decide(&session, args, smart).await;
+ if decision["behavior"] == "allow" {
+ // The override goes with the push that runs, never one the person declined
+ if let Some(why) = super::dev::prepush::use_up(&state, &pass).await {
+ decision = json!({"behavior": "deny", "message": why});
+ } else if let (Some(pinned), Some(input)) = (pass.pinned, decision.get_mut("updatedInput").and_then(Value::as_object_mut)) {
+ // What goes is the commit kwant checked, even if a parallel call commits
+ input.insert("command".into(), Value::String(pinned));
+ }
+ }
+ decision
+ }
};
rpc_result(id, json!({"content": [{"type": "text", "text": decision.to_string()}]}))
}
diff --git a/src/server/missions/tools.rs b/src/server/missions/tools.rs
index 95f664e0..efe7e897 100644
--- a/src/server/missions/tools.rs
+++ b/src/server/missions/tools.rs
@@ -524,6 +524,17 @@ async fn request_check(state: &AppState, scope: &SelfScope, task: &Task, args: &
ok(v)
}
+/// The fresh-eyes label of a `task_review` (fresh-eyes-audit.md §3): `checked` only in a
+/// fresh-eyes turn, which saw the brief and the result.
+fn review_label(scope: &SelfScope) -> Value {
+ use crate::server::fresh_eyes::{is_fresh, label, SAW_BRIEF, SAW_RESULT};
+ if is_fresh(scope.turn_id.as_deref()) {
+ label(true, &[SAW_BRIEF, SAW_RESULT], "brief", Some(&scope.kwant_id))
+ } else {
+ label(false, &[], "none", Some(&scope.kwant_id))
+ }
+}
+
async fn review(state: &AppState, scope: &SelfScope, task: &Task, args: &Value) -> ToolResult {
if task.owner_kwant_id.as_deref() == Some(scope.kwant_id.as_str()) {
return fail("You can't review your own task; a teammate or the person does.");
@@ -555,10 +566,13 @@ async fn review(state: &AppState, scope: &SelfScope, task: &Task, args: &Value)
if verdict == "pass" && ids.is_empty() {
return fail("A pass must cite at least one evidence id on this task.");
}
+ // "Checked with fresh eyes" (Ada's review of #456, Later 6): a lead's hand-off review runs
+ // fresh-eyes with only the brief and the result; any other review says it wasn't
+ let fresh_eyes = review_label(scope);
let c = NewCheck {
task_id: task.id.clone(),
kind: "peer_review".into(),
- spec: json!({"note": note.chars().take(2000).collect::<String>(), "evidence_ids": ids}),
+ spec: json!({"note": note.chars().take(2000).collect::<String>(), "evidence_ids": ids, "fresh_eyes": fresh_eyes}),
required: true,
approved: true,
requested_by: scope.kwant_id.clone(),
@@ -572,7 +586,7 @@ async fn review(state: &AppState, scope: &SelfScope, task: &Task, args: &Value)
if let Err(e) = state.db.finish_check(&check.id, status, Some(note), &scope.kwant_id, None).await {
return fail(format!("Could not record the review: {e}"));
}
- let _ = state.db.log_task_event(&task.id, "review", &scope.kwant_id, &json!({"verdict": verdict, "check_id": check.id})).await;
+ let _ = state.db.log_task_event(&task.id, "review", &scope.kwant_id, &json!({"verdict": verdict, "check_id": check.id, "fresh_eyes": fresh_eyes})).await;
let after = evaluate(state, &task.id).await;
if let Some(t) = &after {
super::emit_task(state, t).await;
diff --git a/src/server/routes.rs b/src/server/routes.rs
index eefca4bf..b91d780e 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -5738,15 +5738,23 @@ pub async fn execute_tool(
let command = args["command"].as_str()
.ok_or_else(|| crate::tools::ToolError::InvalidArgs("Missing 'command' argument".into()))?;
// B2: a bot's own push in a Dev mode space waits for its pre-push card
- if let Some(why) = super::dev::prepush::gate(state, team_id.unwrap_or("default"), command, &workspace).await {
- return Err(crate::tools::ToolError::Execution(why));
- }
- if !super::computer::approve_local_shell(state, team_id.unwrap_or("default"), command, &workspace).await {
+ let pass = super::dev::prepush::check_command(state, team_id.unwrap_or("default"), command, &workspace)
+ .await
+ .map_err(crate::tools::ToolError::Execution)?;
+ // What runs (and what the person approves) is the push pinned to the checked commit
+ let 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 {
return Err(crate::tools::ToolError::Execution(
"The person did not approve this command, so it was not run.".into(),
));
}
- return crate::tools::shell::execute_shell(&workspace, args).await;
+ // The override goes with the push that runs, never one the person declined
+ if let Some(why) = super::dev::prepush::use_up(state, &pass).await {
+ return Err(crate::tools::ToolError::Execution(why));
+ }
+ let mut args = args.clone();
+ args["command"] = serde_json::Value::String(command);
+ return crate::tools::shell::execute_shell(&workspace, &args).await;
}
if tool_name == "execute_shell" {
// VM mode: commands only ever run inside the bot's or team's sandbox. With no known
@@ -5840,6 +5848,8 @@ mod tests {
assert!(TurnOpts { discussion: Some(None), ..TurnOpts::default() }.no_park());
// Its retry would run with default options, tools included
assert!(TurnOpts { no_tools: true, ..TurnOpts::default() }.no_park());
+ // A fresh-eyes turn's retry would lose its Guard and run with every tool and the history
+ assert!(TurnOpts { fresh_eyes: true, ..TurnOpts::default() }.no_park());
}
#[test]
diff --git a/tests/handoff_review_test.rs b/tests/handoff_review_test.rs
index 8fdb7b06..cfbc18c2 100644
--- a/tests/handoff_review_test.rs
+++ b/tests/handoff_review_test.rs
@@ -217,9 +217,36 @@ async fn the_lead_reviews_a_finished_hand_off_and_a_pass_verifies_it() {
let card_json = missions::task_json(&env.state, &task).await;
assert_eq!(card_json["reviewer"]["kwant_id"], json!(env.lead), "the card names its reviewer");
- let (out, err) = review(&env, &env.lead, &task.id, "pass", &ev, "Parser handles the new format").await;
+ // The review is made in the fresh-eyes turn (the fake CLI can't call tools, so the test
+ // makes the call as that turn): it is labelled "Checked with fresh eyes"
+ let bot = env.state.db.get_kwant(&env.lead).await.unwrap().unwrap();
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), turn_id: Some("fe-review-turn".into()), ..Default::default() };
+ let args = json!({"task_id": task.id, "verdict": "pass", "evidence_ids": ev, "note": "Parser handles the new format"});
+ let (out, err) = {
+ let _fresh = kwnt::server::fresh_eyes::Guard::new("fe-review-turn");
+ missions::tools::call(&env.state, &scope, "task_review", &args).await
+ };
assert!(!err, "{out}");
assert_eq!(card_state(&env, &did).await, "verified");
+ let checks = env.state.db.list_checks(&task.id).await.unwrap();
+ let peer = checks.iter().find(|c| c.kind == "peer_review").expect("the review is a check");
+ let label = &peer.spec_value()["fresh_eyes"];
+ assert_eq!(label["checked"], true, "{label}");
+ assert_eq!(label["saw"], json!(["brief", "result"]));
+ assert_eq!((label["spec_source"].as_str(), label["reviewer_kwant_id"].as_str()), (Some("brief"), Some(env.lead.as_str())));
+}
+
+/// A review made outside a fresh-eyes turn (a teammate on the board) never says it was.
+#[tokio::test]
+async fn a_review_outside_a_fresh_eyes_turn_is_not_labelled_fresh() {
+ let env = setup().await;
+ let (_, task) = finished(&env, "Check the lexer NOTFRESHMARK", "Lexer check").await;
+ let ev = result_evidence(&env, &task.id).await;
+ let (out, err) = review(&env, &env.lead, &task.id, "pass", &ev, "Lexer handles the new format").await;
+ assert!(!err, "{out}");
+ let checks = env.state.db.list_checks(&task.id).await.unwrap();
+ let label = checks.iter().find(|c| c.kind == "peer_review").unwrap().spec_value()["fresh_eyes"].clone();
+ assert_eq!((label["checked"].as_bool(), label["spec_source"].as_str()), (Some(false), Some("none")), "{label}");
}
/// A fail goes back to Ready with the lead's note and on to the teammate in the hand-off's own
diff --git a/tests/prepush_test.rs b/tests/prepush_test.rs
index 06ec2e06..5b2a9364 100644
--- a/tests/prepush_test.rs
+++ b/tests/prepush_test.rs
@@ -10,7 +10,7 @@ mod common;
use base64::Engine;
use common::*;
-use kwnt::db::dev_prepush::{BLOCKED, CHECKING, CLEAR, OVERRIDDEN};
+use kwnt::db::dev_prepush::{BLOCKED, CHECKING, CLEAR, OVERRIDDEN, PUSHED};
use kwnt::drivers::events::RuntimeEvent;
use kwnt::server::dev::prepush;
use serde_json::{json, Value};
@@ -165,11 +165,41 @@ async fn a_switched_off_test_blocks_the_push_until_the_person_overrides() {
assert_eq!(v["overridden_by"], "person");
assert_eq!(v["override"]["reason"], "the slow test is flaky, tracked in #12");
assert_eq!(v["needs_you"], false);
+ // A PR from the branch says it was pushed anyway, with the person's reason
+ let anyway = prepush::pushed_anyway(&env.state, &space, Some("juno-skip")).await;
+ assert_eq!(anyway[0]["reason"], "the slow test is flaky, tracked in #12", "{anyway}");
+ assert_eq!((anyway[0]["head_sha"].as_str(), anyway[0]["by"].as_str()), (Some(sha.as_str()), Some("person")));
+ assert_eq!(prepush::pushed_anyway(&env.state, &space, Some("juno-other")).await, json!([]));
let (s, _) = call(&env.app, "POST", &url, Some(json!({"reason": "the slow test is flaky, tracked in #12"}))).await;
assert_eq!(s.as_u16(), 409, "an overridden card can't be overridden again");
- // Now the push goes
+ // The check alone uses nothing up: a push the person then declines keeps the override
+ let pass = prepush::check_command(&env.state, &env.a, push, &folder).await.expect("overridden");
+ assert_eq!(pass.overrides, std::slice::from_ref(&row.id));
+ assert_eq!(pass.pinned, None, "`-u` runs as written");
+ let racer = prepush::check_command(&env.state, &env.a, push, &folder).await.expect("overridden");
+ assert_eq!(env.state.db.prepush_card(&row.id).await.unwrap().unwrap().status, OVERRIDDEN);
+
+ // Now the push goes, once: two parallel calls checked it, and only the first one runs
+ assert_eq!(prepush::use_up(&env.state, &pass).await, None);
+ let lost = prepush::use_up(&env.state, &racer).await.expect("the override is used up");
+ assert!(lost.contains("was for one push") && lost.contains("Nothing was pushed"), "{lost}");
+ let (_, v) = call(&env.app, "GET", &format!("/api/dev/prepush/{}", row.id), None).await;
+ assert_eq!((v["status"].as_str(), v["override_used"].as_bool()), (Some(PUSHED), Some(true)), "{v}");
+ assert_eq!(v["override"]["reason"], "the slow test is flaky, tracked in #12");
+
+ // A second push of the same commit gets a blocked card again, until the person overrides again
+ let again = prepush::gate(&env.state, &env.a, push, &folder).await.expect("a second push waits for the person");
+ assert!(again.contains("was for one push of juno-skip") && again.contains("Nothing was pushed"), "{again}");
+ let (_, v) = call(&env.app, "GET", &format!("/api/dev/prepush/{}", row.id), None).await;
+ assert_eq!((v["id"].as_str(), v["status"].as_str()), (Some(row.id.as_str()), Some(BLOCKED)), "the same card: {v}");
+ assert_eq!((v["override"].clone(), v["override_used"].as_bool()), (Value::Null, Some(false)), "{v}");
+ assert_eq!(v["last_override"]["reason"], "the slow test is flaky, tracked in #12");
+ assert!(prepush::gate(&env.state, &env.a, push, &folder).await.is_some(), "still blocked");
+ let (s, v) = call(&env.app, "POST", &url, Some(json!({"reason": "one more push for the demo build"}))).await;
+ assert_eq!((s.as_u16(), v["status"].as_str()), (200, Some(OVERRIDDEN)), "{v}");
assert_eq!(prepush::gate(&env.state, &env.a, push, &folder).await, None);
+ assert!(prepush::gate(&env.state, &env.a, push, &folder).await.is_some(), "and that override is one push too");
// A new commit on the branch is a new check
let more = commit(&folder, "src/more.rs", "pub fn more() {}\n", "More");
@@ -218,6 +248,11 @@ async fn a_clean_push_goes_once_its_card_is_clear_and_the_reviewer_never_sees_th
assert_eq!(card["blockers"], json!([]), "{card}");
assert_eq!(card["fresh_eyes"]["checked"], true, "{card}");
assert_eq!(prepush::gate(&env.state, &env.a, push, &folder).await, None, "a clear card lets the push go");
+ assert_eq!(prepush::gate(&env.state, &env.a, push, &folder).await, None, "every time");
+ // A push with a remote goes pinned to the commit kwant checked
+ let pass = prepush::check_command(&env.state, &env.a, "cd . && git push origin juno-clean", &folder).await.unwrap();
+ assert_eq!(pass.pinned, Some(format!("cd . && git push origin {sha}:refs/heads/juno-clean")));
+ assert!(pass.overrides.is_empty());
// The reviewer turn saw the diff and nothing of the author's chat
let reviews = invocations_with("CLEANMARK");
@@ -316,3 +351,284 @@ async fn the_card_store_keeps_one_card_per_commit_and_its_rules() {
assert_eq!(db.prepush_card(&stuck.id).await.unwrap(), None);
assert_eq!(db.prepush_cards("spc_x", 50).await.unwrap().len(), 4);
}
+
+/// Ada's review of #456, Later 6: a reviewer turn that didn't answer runs once more on its own;
+/// when that fails too, the card waits for the person, saying it was tried again.
+#[tokio::test]
+async fn a_review_that_errored_runs_once_more_on_its_own() {
+ let env = setup().await;
+ let space = space_of_a(&env).await;
+ let folder = repo(&env, "errored");
+ git(&folder, &["checkout", "-q", "-b", "juno-err"]);
+ commit(&folder, "src/widgets.rs", "// FAILTURN RETRYMARK\npub fn count() -> u32 { 4 }\n", "Count widgets");
+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();
+
+ assert!(prepush::gate(&env.state, &env.a, "git push origin juno-err", &folder).await.is_some());
+ let row = settled(&env, &space, "juno-err").await;
+ assert_eq!(row.status, BLOCKED, "{row:?}");
+ let card: Value = serde_json::from_str(row.card.as_deref().unwrap()).unwrap();
+ assert_eq!(card["auto_retried"], true, "{card}");
+ assert!(card["blockers"].as_array().unwrap().iter().any(|b| b["source"] == "review"), "{card}");
+ assert_eq!(card["review_failed"], true, "the retry reads this flag, not the blocker's source: {card}");
+ let turns = invocations_with("RETRYMARK").len();
+ assert!(turns >= 2, "the reviewer was asked twice: {turns}");
+ let (_, v) = call(&env.app, "GET", &format!("/api/dev/prepush/{}", row.id), None).await;
+ assert_eq!(v["auto_retried"], true, "{v}");
+ // Not a third time on its own: the next push of the same commit waits for the person
+ assert!(prepush::gate(&env.state, &env.a, "git push origin juno-err", &folder).await.is_some());
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ assert_eq!(invocations_with("RETRYMARK").len(), turns, "no more reviewer turns");
+}
+
+/// Rigel's QA of #456, finding C: an override is one push, used up once, never twice.
+#[tokio::test]
+async fn an_override_is_used_up_by_one_push_in_the_store() {
+ let env = setup().await;
+ let db = &env.state.db;
+ let sha = "b".repeat(40);
+ let row = db.insert_prepush_card("spc_o", &env.a, "/f", "juno-o", &sha, CHECKING, None, false).await.unwrap().unwrap();
+ assert!(!db.use_prepush_override(&row.id).await.unwrap(), "nothing to use while checking");
+ db.finish_prepush_card(&row.id, BLOCKED, "{}").await.unwrap();
+ assert!(!db.use_prepush_override(&row.id).await.unwrap(), "nor while blocked");
+ assert_eq!(db.reblock_pushed_prepush_card(&row.id).await.unwrap(), None, "only a pushed card is blocked again");
+ db.override_prepush_card(&row.id, "person", "a good reason here").await.unwrap().unwrap();
+ assert!(db.use_prepush_override(&row.id).await.unwrap());
+ assert!(!db.use_prepush_override(&row.id).await.unwrap(), "once");
+ assert_eq!(db.prepush_card(&row.id).await.unwrap().unwrap().status, PUSHED);
+ assert_eq!(db.override_prepush_card(&row.id, "person", "another good reason").await.unwrap(), None, "a used override isn't overridden again until blocked");
+ let again = db.reblock_pushed_prepush_card(&row.id).await.unwrap().unwrap();
+ assert_eq!((again.status.as_str(), again.override_reason.as_deref()), (BLOCKED, Some("a good reason here")), "the history stays");
+ assert_eq!(db.prepush_overrides_on("spc_o", "juno-o", 3).await.unwrap().len(), 1);
+ assert!(db.prepush_overrides_on("spc_o", "juno-p", 3).await.unwrap().is_empty());
+ // Blocked again only because its one push went: the next commit's count starts again
+ let next = db.insert_prepush_card("spc_o", &env.a, "/f", "juno-o", &"c".repeat(40), CHECKING, None, false).await.unwrap().unwrap();
+ assert_eq!(next.tries, 1);
+ db.finish_prepush_card(&next.id, BLOCKED, "{}").await.unwrap();
+ let after = db.insert_prepush_card("spc_o", &env.a, "/f", "juno-o", &"d".repeat(40), CHECKING, None, false).await.unwrap().unwrap();
+ assert_eq!(after.tries, 2, "a blocked card nobody overrode still counts");
+}
+
+/// A GitHub tool's write (`create_or_update_file`) to `branch`, with `files` as `(path, text)`.
+fn gh_write(branch: Option<&str>, path: &str, text: &str) -> Value {
+ let mut v = json!({"owner": "demo-org", "repo": "demo-app", "path": path, "content": text, "message": "Count widgets"});
+ if let Some(b) = branch {
+ v["branch"] = json!(b);
+ }
+ v
+}
+
+#[tokio::test]
+async fn kwants_own_github_tools_go_through_the_pre_push_card() {
+ let env = setup().await;
+ let space = space_of_a(&env).await;
+ let tampered = format!("{}{}", clean_review("GHWRITEMARK"), TEST_BODY.replace("#[test]\n", "#[test]\n#[ignore]\n"));
+ let args = gh_write(Some("juno-gh"), TEST_FILE, &tampered);
+
+ // Dev mode off: the write isn't held and no card is made
+ assert_eq!(prepush::check_mcp(&env.state, &env.a, "github", "create_or_update_file", &args).await, Ok(prepush::Pass::default()));
+ assert!(env.state.db.prepush_cards(&space, 50).await.unwrap().is_empty());
+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();
+
+ // Reads, kwant's own tools and tools that name no repo aren't writes
+ for (server, tool, a) in [
+ ("github", "get_file_contents", json!({"owner": "demo-org", "repo": "demo-app", "path": "README.md"})),
+ ("kwnt_tools", "create_or_update_file", args.clone()),
+ ("files", "delete_file", json!({"path": "notes.txt"})),
+ ] {
+ assert_eq!(prepush::check_mcp(&env.state, &env.a, server, tool, &a).await, Ok(prepush::Pass::default()), "{tool}");
+ }
+ assert!(env.state.db.prepush_cards(&space, 50).await.unwrap().is_empty());
+ // A write that names no branch would land on the default branch: refused without a card
+ let why = prepush::check_mcp(&env.state, &env.a, "github", "create_or_update_file", &gh_write(None, "a.txt", "hi")).await.unwrap_err();
+ assert!(why.contains("names no branch"), "{why}");
+ // Composio's multi-execute with two writes: one call each
+ let multi = json!({"tools": [
+ {"tool_slug": "GITHUB_CREATE_OR_UPDATE_FILE_CONTENTS", "arguments": gh_write(Some("juno-gh"), "a.txt", "a")},
+ {"tool_slug": "GITHUB_DELETE_A_FILE", "arguments": gh_write(Some("juno-gh"), "b.txt", "")},
+ ]});
+ let why = prepush::check_mcp(&env.state, &env.a, "composio", "COMPOSIO_MULTI_EXECUTE_TOOL", &multi).await.unwrap_err();
+ assert!(why.contains("makes 2 GitHub writes"), "{why}");
+
+ // Ada's review of #472, must-fix 2: a write to a protected branch, every merge and deleting a
+ // protected branch get the production floor's card (the person decides), not a pre-push card
+ use kwnt::mcp::prod_floor::FloorKind;
+ let floor = |server: &str, tool: &str, a: Value| {
+ let req = kwnt::mcp::ToolApprovalRequest {
+ kwant_id: env.a.clone(),
+ kwant_name: "A".into(),
+ turn_id: "t".into(),
+ tool_name: format!("mcp__{server}__{tool}"),
+ server: server.into(),
+ tool: tool.into(),
+ arguments: a,
+ builtin: None,
+ smart: None,
+ payment: None,
+ };
+ let db = env.state.db.clone();
+ async move { kwnt::server::dev::floor::for_call(&db, &req).await.map(|(f, _)| f.kind) }
+ };
+ for (server, tool, a, want) in [
+ ("github", "create_or_update_file", gh_write(Some("main"), "a.txt", "a"), FloorKind::PushMain),
+ ("github", "push_files", json!({"owner": "demo-org", "repo": "demo-app", "branch": "release/1.0", "message": "m", "files": [{"path": "a", "content": "b"}]}), FloorKind::PushMain),
+ ("composio", "GITHUB_MERGE_A_PULL_REQUEST", json!({"owner": "demo-org", "repo": "demo-app", "pull_number": 7}), FloorKind::PushMain),
+ ("github", "merge_pull_request", json!({"owner": "demo-org", "repo": "demo-app", "pull_number": 7}), FloorKind::PushMain),
+ ("github", "delete_branch", json!({"owner": "demo-org", "repo": "demo-app", "branch": "main"}), FloorKind::DeleteRef),
+ ] {
+ assert_eq!(floor(server, tool, a.clone()).await, Some(want), "{tool}");
+ assert_eq!(prepush::check_mcp(&env.state, &env.a, server, tool, &a).await, Ok(prepush::Pass::default()), "{tool}: the floor's card asks instead");
+ }
+ // A bot's own branch: no floor, and the write gets the pre-push card (below); a delete of it
+ // and creating a branch ask nothing
+ assert_eq!(floor("github", "create_or_update_file", args.clone()).await, None);
+ assert_eq!(floor("github", "delete_branch", json!({"owner": "demo-org", "repo": "demo-app", "branch": "juno-x"})).await, None);
+ assert_eq!(floor("github", "create_branch", json!({"owner": "demo-org", "repo": "demo-app", "branch": "juno-x"})).await, None);
+ assert!(env.state.db.prepush_cards(&space, 50).await.unwrap().is_empty(), "no pre-push card for any of these");
+
+ // The write waits for its card, which the switched-off test blocks
+ let first = prepush::check_mcp(&env.state, &env.a, "github", "create_or_update_file", &args).await.unwrap_err();
+ assert!(first.contains("is checking this push of juno-gh") && first.contains("GitHub tool's write"), "{first}");
+ let row = settled(&env, &space, "juno-gh").await;
+ assert_eq!(row.status, BLOCKED, "{row:?}");
+ assert_eq!(row.folder, "mcp:github/demo-org/demo-app");
+ assert_eq!(row.head_sha, prepush::write_id("create_or_update_file", &args));
+ let card: Value = serde_json::from_str(row.card.as_deref().unwrap()).unwrap();
+ assert_eq!(card["mcp"], json!({"owner": "demo-org", "repo": "demo-app"}), "{card}");
+ assert_eq!(card["blockers"].as_array().unwrap().iter().map(|b| b["source"].as_str().unwrap()).collect::<Vec<_>>(), ["tamper"], "{card}");
+ assert_eq!(card["fresh_eyes"]["checked"], true, "{card}");
+ assert_eq!(card["security"]["semgrep"]["state"], "not_run", "{card}");
+ let reviews = invocations_with("GHWRITEMARK");
+ assert_eq!(reviews.len(), 1, "one reviewer turn");
+ assert!(reviews[0].contains("counts_widgets"), "the reviewer sees what the tool sends");
+ // Still blocked, and the same card
+ assert!(prepush::check_mcp(&env.state, &env.a, "github", "create_or_update_file", &args).await.unwrap_err().contains("blocked this push"));
+ // A different write is a different card
+ assert_eq!(env.state.db.prepush_cards(&space, 50).await.unwrap().len(), 1);
+
+ // claude asks kwant's permission prompt before calling the GitHub server itself: denied there
+ let mut github = kwnt::db::models::McpServer {
+ id: "id-github".into(),
+ name: "github".into(),
+ transport: "stdio".into(),
+ command: Some("/usr/bin/true".into()),
+ args: vec![],
+ url: None,
+ env: Default::default(),
+ headers: Default::default(),
+ enabled: true,
+ timeout_secs: 10,
+ created_at: None,
+ };
+ github.enabled = true;
+ let ctx = kwnt::mcp::McpTurnContext {
+ servers: vec![github],
+ approver: std::sync::Arc::new(kwnt::mcp::FixedApprover(true)),
+ config_dir: env.tmp.path().join("mcp-gh"),
+ permission_url: None,
+ gateway: None,
+ max_tool_iterations: 8,
+ approvals: kwnt::mcp::Approvals::Ask,
+ records: Default::default(),
+ };
+ let session = kwnt::server::mcp_runtime::PermissionSession::new(env.a.clone(), "A".into(), "gh-turn".into(), ctx, None);
+ env.state.mcp_sessions.lock().await.insert("gh-tok".into(), session);
+ let ask = |input: &Value| json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": {"name": "approve", "arguments": {"tool_name": "mcp__github__create_or_update_file", "input": input, "tool_use_id": "tu_gh"}}});
+ let decision = |v: &Value| -> Value { serde_json::from_str(v["result"]["content"][0]["text"].as_str().unwrap()).unwrap() };
+ let (s, v) = call(&env.app, "POST", "/api/mcp/permission/gh-tok", Some(ask(&args))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let d = decision(&v);
+ assert_eq!(d["behavior"], "deny", "{d}");
+ assert!(d["message"].as_str().unwrap().contains("blocked this push"), "{d}");
+
+ // The person overrides: exactly one call goes, through the turn's approver
+ let (s, v) = call(&env.app, "POST", &format!("/api/dev/prepush/{}/override", row.id), Some(json!({"reason": "the test is flaky on CI, fixing next"}))).await;
+ assert_eq!((s.as_u16(), v["status"].as_str()), (200, Some(OVERRIDDEN)), "{v}");
+ let approver = kwnt::server::mcp_runtime::PrepushApprover { inner: std::sync::Arc::new(kwnt::mcp::FixedApprover(true)), state: env.state.clone() };
+ use kwnt::mcp::ToolApprover;
+ let req = kwnt::mcp::ToolApprovalRequest {
+ kwant_id: env.a.clone(),
+ kwant_name: "A".into(),
+ turn_id: "gh-turn".into(),
+ tool_name: "mcp__github__create_or_update_file".into(),
+ server: "github".into(),
+ tool: "create_or_update_file".into(),
+ arguments: args.clone(),
+ builtin: None,
+ 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);
+ 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 too
+ let d = decision(&call(&env.app, "POST", "/api/mcp/permission/gh-tok", Some(ask(&args))).await.1);
+ assert_eq!(d["behavior"], "deny", "{d}");
+ assert!(d["message"].as_str().unwrap().contains("was for one push"), "{d}");
+ assert_eq!(env.state.db.prepush_card(&row.id).await.unwrap().unwrap().status, BLOCKED);
+ // The reason goes with the PR's review
+ let anyway = prepush::pushed_anyway(&env.state, &space, Some("juno-gh")).await;
+ assert_eq!(anyway[0]["reason"], "the test is flaky on CI, fixing next", "{anyway}");
+}
+
+/// Ada's review of #472, must-fix 1: a push of a tag isn't pinned (that would make a branch of
+/// that name); it runs as written, gated by the card of the tag's commit. A branch push still pins.
+#[tokio::test]
+async fn a_tag_push_runs_as_written_and_a_branch_push_is_pinned() {
+ let env = setup().await;
+ let space = space_of_a(&env).await;
+ let folder = repo(&env, "tagged");
+ git(&folder, &["checkout", "-q", "-b", "juno-tag"]);
+ let sha = commit(&folder, "src/widgets.rs", &format!("{}pub fn count() -> u32 {{ 4 }}\n", clean_review("TAGMARK")), "Count widgets");
+ git(&folder, &["tag", "checkpoint"]);
+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();
+
+ // The tag: its commit gets a card, and once clear the push goes as written
+ assert!(prepush::check_command(&env.state, &env.a, "git push origin checkpoint", &folder).await.is_err(), "waits for its card");
+ let row = settled(&env, &space, "checkpoint").await;
+ assert_eq!((row.status.as_str(), row.head_sha.as_str()), (CLEAR, sha.as_str()), "{row:?}");
+ let pass = prepush::check_command(&env.state, &env.a, "git push origin checkpoint", &folder).await.unwrap();
+ assert_eq!(pass.pinned, None, "a tag is never pinned into refs/heads/checkpoint");
+ // The branch with the same commit: pinned to it
+ assert!(prepush::check_command(&env.state, &env.a, "git push origin juno-tag", &folder).await.is_err(), "waits for its card");
+ settled(&env, &space, "juno-tag").await;
+ for cmd in ["git push origin juno-tag", "git push origin HEAD:juno-tag"] {
+ let pass = prepush::check_command(&env.state, &env.a, cmd, &folder).await.unwrap();
+ assert_eq!(pass.pinned, Some(format!("git push origin {sha}:refs/heads/juno-tag")), "{cmd}");
+ }
+ // A branch that shares its name with a tag is ambiguous to git: run as written
+ git(&folder, &["tag", "juno-tag"]);
+ let pass = prepush::check_command(&env.state, &env.a, "git push origin juno-tag", &folder).await.unwrap();
+ assert_eq!(pass.pinned, None);
+}
+
+/// Ada's review of #472, must-fix 3: the reviewer's own high finding is a verdict. It blocks the
+/// push and is never run again on its own (a second roll could let the push go); only a
+/// reviewer turn that didn't answer is.
+#[tokio::test]
+async fn a_real_review_finding_is_never_run_again_on_its_own() {
+ let env = setup().await;
+ let space = space_of_a(&env).await;
+ let folder = repo(&env, "found");
+ git(&folder, &["checkout", "-q", "-b", "juno-found"]);
+ let reply = json!({"intent": {"asked": "Count widgets FOUNDMARK", "rows": [{"state": "ok", "text": "Counts the widgets"}]},
+ "findings": [{"severity": "high", "title": "count() ignores the widgets", "file": "src/widgets.rs", "line": 3,
+ "detail": "It always returns 4, whatever the list holds.", "fix": "Count the list."}]});
+ let marker = format!("// FOUNDMARK\n// REPLYTEXT:{}\n", base64::engine::general_purpose::STANDARD.encode(reply.to_string()));
+ commit(&folder, "src/widgets.rs", &format!("{marker}pub fn count() -> u32 {{ 4 }}\n"), "Count widgets");
+ env.state.db.put_dev_mode(&space, true, "demo-org/demo-app", "main", None, None).await.unwrap();
+
+ assert!(prepush::gate(&env.state, &env.a, "git push origin juno-found", &folder).await.is_some());
+ let row = settled(&env, &space, "juno-found").await;
+ assert_eq!(row.status, BLOCKED, "{row:?}");
+ let card: Value = serde_json::from_str(row.card.as_deref().unwrap()).unwrap();
+ let blockers = card["blockers"].as_array().unwrap();
+ assert_eq!(blockers.len(), 1, "{card}");
+ assert_eq!((blockers[0]["source"].as_str(), blockers[0]["severity"].as_str()), (Some("review"), Some("high")), "Iris's contract keeps the source");
+ assert_ne!(card["review_failed"], true, "{card}");
+ assert_ne!(card["auto_retried"], true, "{card}");
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ 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"));
+}