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.7.1: Post a Dev mode review card to GitHub (one COMMENT review) (#340)

Oleksandr Ivanchenkoaadb90eab7bc
diff --git a/docs/dev-mode.md b/docs/dev-mode.md
index 797d6295..52df5dd4 100644
--- a/docs/dev-mode.md
+++ b/docs/dev-mode.md
@@ -1,11 +1,13 @@
# Dev mode
-Dev mode (0.7) points a space at one GitHub repo and branch. kwnt then reads the repo, **read only**,
-and turns what happens there into cards:
+Dev mode (0.7) points a space at one GitHub repo and branch. kwnt then reads the repo and turns what
+happens there into cards. It writes to GitHub only when the person presses **Post to GitHub** on a
+review card (0.7.1, see [Posting to GitHub](#posting-to-github)); nothing else is ever sent there.
- **Landed**: one card per commit that reaches the watched branch, saying what changed and how risky it is.
- **Review**: one card per open pull request head, with findings. The person can press **Fix it**
- (the finding goes to the bot that wrote the PR) or **Dismiss** on each finding.
+ (the finding goes to the bot that wrote the PR) or **Dismiss** on each finding, and **Post to
+ GitHub** to put the card on the PR as one review comment.
- **Release notes**: written on request, from the landed cards since the last tag.
It also turns on the **production floor** for the space's bots: steps that can reach production
@@ -51,7 +53,8 @@ and approvals stay as they were.
## Reading GitHub
-Reads go through the GitHub connection only, and kwnt never writes to the repo. Every read sends
+Reads go through the GitHub connection only. kwnt never pushes, merges, approves or edits anything
+in the repo; its one write is the review the person posts (below). Every read sends
the last ETag it got, so an unchanged answer costs no rate limit. A rate limit (a 403 or 429 with
`retry-after` or `x-ratelimit-remaining: 0`) backs the space off until the reset time GitHub gives,
at most an hour, or a minute for a bare 429. Another 403 is a permission error. The settings show
@@ -95,6 +98,66 @@ reviewed outside kwnt, gets a landed card that says "not verified", and it stays
that finishes later doesn't rewrite the landed card (only a CI change re-runs a card's text). That
is on purpose. Verified says what was checked before the change landed, not after.
+## Posting to GitHub
+
+`POST /api/dev/cards/:id/post` (0.7.1) puts one review card on its pull request as **one GitHub PR
+review** with `event: "COMMENT"`. kwnt never approves or requests changes, never merges, and never
+posts on its own: only the person's press posts, and the route refuses a bot's turn token like every
+Dev mode route. Landed and release notes cards can't be posted (400). An unknown card is 404. A
+review that didn't finish is 409 and makes no GitHub call: one still being written (`pending`), one
+that `failed` (its card keeps only the rule checks, so it would read as a hollow "Low" review), or
+one with no card text. The error is "This review didn't finish, so there's nothing to post. Run the
+review again first." Nothing is stored, so the card shows no `post_error`.
+
+**What is posted.** The review is pinned to the card's head (`commit_id`). Its body has the risk
+level and its reasons, the intent check (done, missing, not asked for), the test-tamper flags with
+their diff excerpts, the security tiles (secrets, new packages, OSV, Semgrep), and the findings that
+can't go on a line. It ends "Reviewed by {reviewer} ({engine}) in kwant" ("Reviewed by kwant's rule
+checks (no reviewer bot) in kwant" when no bot wrote it), then a hidden marker
+`<!-- kwant review card {id} -->`. Each finding that isn't dismissed and whose file and line are
+inside the PR's diff hunks (the new side) becomes an inline comment, `side: RIGHT`, at most 50 of
+them; the rest are listed in the body. If GitHub still answers 422 about lines, kwnt posts once more
+with everything in the body.
+
+**What is never posted.** Secrets never leave kwant. A gitleaks finding is posted only as "Possible
+secret in {file}:{line}", without its rule, excerpt or value. The body and every comment then go
+through the same redaction as bot output (`[redacted]` over keys, tokens and long hex), so a model
+finding that quotes a key doesn't carry it out either. The GitHub token is only ever a header.
+Dismissed findings and the card's model prompts aren't posted.
+
+**The token.** Posting uses the Loose ends GitHub connection, GitHub Enterprise `api_base` included.
+It needs **Pull requests: Read and write** on a fine-grained token, or `repo` (`public_repo` for a
+public repo) on a classic one. Reading alone works with read access, so posting is the only reason
+to give it more.
+
+**The answer** is always the card, with HTTP 200, carrying two fields (review cards only):
+
+```jsonc
+"posted": null | {"at": "…", "login": "octocat" | null, "url": "https://github.com/o/r/pull/24#pullrequestreview-1" | null,
+ "comments": 3, "forge": "github"},
+"post_error": null | {"kind": "read_only" | "stale" | "failed", "message": "…"}
+```
+
+- `read_only`: GitHub answered the write with 403 or 404, so the token can read but not post.
+- `stale`: the PR's head moved past the card's head (or the card is already stale). Nothing is
+ posted: a new review is on its way.
+- `failed`: anything else (no connection, a closed PR, a rate limit, a second 422). Press again to
+ retry. A successful post clears `post_error`.
+
+`posted.comments` is the number of inline comments (0 after the 422 retry). Each post emits the
+`dev_card` event.
+
+**Once only.** A posted card answers unchanged, without asking GitHub. Presses of one card wait on a
+lock, and the database only records the first post, so a double click makes one review. If GitHub
+took a post but its answer was lost, the next press finds that review by its marker and head, and
+records it instead of posting again.
+
+**Who posts.** `GET /api/spaces/:id/dev_mode` has `forge` (`"github"` once the space has a repo and a
+GitHub connection is saved, else `null`; `gitlab` and `gitea` are reserved) and `forge_login`, the
+login the post goes out as, from `GET /user`. That login is cached per connection for 15 minutes (a
+minute when it fails). Only GitHub can be posted to in 0.7.1; the code keeps it behind one function,
+`post_review` in `src/server/dev/post.rs`, so other forges can join later.
+
## The production floor
In a space with Dev mode on, these steps always show an approval card, whatever the bot's
@@ -194,6 +257,7 @@ Run these focused tests:
```sh
cargo test --lib -- server::dev:: prod_floor auth::tests::person_only zombie::github connections::tests::only_mcp
+cargo test --test dev_post_test --test dev_github_test
```
The no-tools turns have their own: `cargo test --lib -- no_tools`.
@@ -202,7 +266,9 @@ The poller runs against a mock GitHub on a private `127.0.0.1` port. The shared
`tests/support/mock_github.rs` (include it with `#[path = "support/mock_github.rs"] mod mock_github;`):
fixtures by path with ETags and 304s, `Link: next` headers (to another host too), each GitHub
error (401, 403, rate limits, secondary limits, 429, 5xx, slow answers, a lost base commit), and a
-log of every request. Anything but a GET fails the test. `tests/dev_github_test.rs` holds the
+log of every request. Anything but a GET fails the test, except a write the test queued with
+`accept_write` (`tests/dev_post_test.rs` queues the review posts and reads them back with `writes()`
+to check what was sent, the AKIA-style secret test included). `tests/dev_github_test.rs` holds the
contract tests and the canary: a token built at runtime goes through a whole poll, failures
included, and must appear nowhere but the vault (logs, errors, events, cards, the database, model
prompts, other files under the data folder).
diff --git a/src/db/dev_mode.rs b/src/db/dev_mode.rs
index d9609234..585f881a 100644
--- a/src/db/dev_mode.rs
+++ b/src/db/dev_mode.rs
@@ -119,6 +119,13 @@ pub struct DevCardRow {
pub card: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
+ /// Review cards: `{at, login, url, comments}` once posted to GitHub (post-to-github.md P1).
+ /// A column of its own, so a card regenerated after CI keeps it.
+ #[sqlx(default)]
+ pub posted: Option<String>,
+ /// Review cards: `{kind, message}` from the last post that didn't go through.
+ #[sqlx(default)]
+ pub post_error: Option<String>,
}
#[derive(Debug, Clone, FromRow, PartialEq, serde::Serialize)]
@@ -133,13 +140,22 @@ pub struct DevBackupRow {
pub taken_at: DateTime<Utc>,
}
-const CARD_COLS: &str = "id, space_id, kind, ref, head_sha, status, facts, card, created_at, updated_at";
+const CARD_COLS: &str = "id, space_id, kind, ref, head_sha, status, facts, card, created_at, updated_at, posted, post_error";
impl Database {
pub(super) async fn migrate_dev_mode(&self) -> Result<(), DbError> {
for sql in TABLES {
sqlx::query(sql).execute(&self.pool).await?;
}
+ // Posting a review to GitHub came in 0.7.1; older builds name their columns, so they
+ // still read this table
+ for column in ["posted", "post_error"] {
+ let has: Option<(String,)> =
+ sqlx::query_as("SELECT name FROM pragma_table_info('dev_cards') WHERE name = ?").bind(column).fetch_optional(&self.pool).await?;
+ if has.is_none() {
+ sqlx::query(&format!("ALTER TABLE dev_cards ADD COLUMN {column} TEXT")).execute(&self.pool).await?;
+ }
+ }
Ok(())
}
@@ -329,6 +345,29 @@ impl Database {
Ok(done.rows_affected() == 1)
}
+ /// Records a review as posted, only while none is (P6): false when another post got there
+ /// first. Clears `post_error`.
+ pub async fn set_dev_card_posted(&self, id: &str, posted: &str) -> Result<bool, DbError> {
+ let done = sqlx::query("UPDATE dev_cards SET posted = ?2, post_error = NULL, updated_at = ?3 WHERE id = ?1 AND posted IS NULL")
+ .bind(id)
+ .bind(posted)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected() == 1)
+ }
+
+ /// Records why a post didn't go through (`None` clears it). A posted card keeps no error.
+ pub async fn set_dev_card_post_error(&self, id: &str, error: Option<&str>) -> Result<(), DbError> {
+ sqlx::query("UPDATE dev_cards SET post_error = ?2, updated_at = ?3 WHERE id = ?1 AND posted IS NULL")
+ .bind(id)
+ .bind(error)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
/// A space's cards of one kind, newest first, created before `before` when given.
pub async fn dev_cards(&self, space_id: &str, kind: &str, before: Option<DateTime<Utc>>, limit: i64) -> Result<Vec<DevCardRow>, DbError> {
Ok(sqlx::query_as(&format!(
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 5bf69aaf..6ed3147f 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -894,6 +894,7 @@ mod tests {
(&post, "/api/spaces/s1/dev/backup"),
(&get, "/api/dev/cards/dvc_1"),
(&post, "/api/dev/cards/dvc_1/findings/f1"),
+ (&post, "/api/dev/cards/dvc_1/post"),
(&Method::HEAD, "/api/spaces/s1/dev/reviews"),
] {
assert!(person_only(m, p), "{m} {p}");
diff --git a/src/server/dev/mod.rs b/src/server/dev/mod.rs
index d58e9862..3b047e19 100644
--- a/src/server/dev/mod.rs
+++ b/src/server/dev/mod.rs
@@ -1,8 +1,9 @@
-//! Dev mode (docs/dev-mode.md, plan 0.7): a space watches one GitHub repo, read only. The poller
+//! Dev mode (docs/dev-mode.md, plan 0.7): a space watches one GitHub repo. It reads it, and posts
+//! a review card to its PR only when the person presses Post (`post`, 0.7.1). The poller
//! writes a pending card per merge to the watched branch and per open PR head, with its DevFacts;
//! `generate` turns them into cards. The production floor lives in `crate::mcp::prod_floor`.
//!
-//! Lin owns `facts`, `routes`, `poller`, `repo`, `backup` and `floor`; Vega owns `generate`, `landed`,
+//! Lin owns `facts`, `routes`, `poller`, `post`, `repo`, `backup` and `floor`; Vega owns `generate`, `landed`,
//! `review`, `risk`, `tamper` and `notes`; Juno owns `scan`.
pub mod backup;
@@ -12,6 +13,7 @@ pub mod generate;
pub mod landed;
pub mod notes;
pub mod poller;
+pub mod post;
pub mod repo;
pub mod review;
pub mod risk;
diff --git a/src/server/dev/post.rs b/src/server/dev/post.rs
new file mode 100644
index 00000000..dcc2a03f
--- /dev/null
+++ b/src/server/dev/post.rs
@@ -0,0 +1,670 @@
+//! Posting a review card to its pull request (0.7.1, plan/post-to-github.md P1–P8). The person
+//! presses Post; kwant sends one GitHub review with event COMMENT, pinned to the card's head. It
+//! never approves or requests changes, and nothing is posted on its own.
+//!
+//! What goes out: the risk level and reasons, the intent check, the test-tamper flags and the
+//! security tiles in the body; one inline comment per finding that isn't dismissed and whose line
+//! is inside the diff; everything else in the body. A gitleaks finding is only "Possible secret in
+//! {file}:{line}". The body and every comment go through [`redact`] before they leave.
+//!
+//! [`post_review`] is the forge step (a forge trait can wrap it later, amendment of 21:50);
+//! [`post`] is the route around it: guard, lock, record, notify.
+
+use super::facts::DevFacts;
+use super::routes::{card_json, REFUSAL};
+use super::{notify_card, repo};
+use crate::db::dev_mode::{DevCardRow, FAILED, PENDING, REVIEW, STALE};
+use crate::server::missions::autofix::redact;
+use crate::server::spaces::active_space;
+use crate::server::AppState;
+use crate::zombie::github::{GhError, GithubSource, PostError as GhPostError, ReviewComment, ReviewPost};
+use axum::{
+ extract::{Path, State},
+ http::{HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::collections::{BTreeSet, HashMap};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+/// The only forge kwant posts to in 0.7.1.
+pub const FORGE: &str = "github";
+
+/// GitHub takes a review body up to 65,536 characters; kwant stays well under it.
+const BODY_CHARS: usize = 60_000;
+/// One inline comment's text at most.
+const COMMENT_CHARS: usize = 4_000;
+/// Most inline comments in one review; the rest go in the body.
+const MAX_INLINE: usize = 50;
+
+/// `posted` on the card (contract P1).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Posted {
+ pub at: DateTime<Utc>,
+ pub login: Option<String>,
+ pub url: Option<String>,
+ pub comments: usize,
+ pub forge: String,
+}
+
+/// `post_error.kind`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ErrorKind {
+ /// The token can read the repo but not post (403, 404 or a permission error, P7).
+ ReadOnly,
+ /// The PR head moved past the card (P5): nothing was posted.
+ Stale,
+ Failed,
+}
+
+/// `post_error` on the card.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PostError {
+ pub kind: ErrorKind,
+ pub message: String,
+}
+
+impl PostError {
+ fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
+ PostError { kind, message: message.into() }
+ }
+
+ fn failed(message: impl Into<String>) -> Self {
+ Self::new(ErrorKind::Failed, message)
+ }
+}
+
+pub const READ_ONLY: &str = "GitHub refused the review: this token can read the repo but not post to it. \
+Give it Pull requests: Read and write (or the classic repo scope), then paste it again in Loose ends.";
+pub const STALE_MESSAGE: &str = "This PR has new commits, so kwant didn't post this review. A new review is on its way.";
+
+// ---------------------------------------------------------------------------------------------
+// Building the review (pure)
+
+/// New-side line numbers each file's diff hunks cover: the lines GitHub takes a `side: RIGHT`
+/// comment on (added and context lines). A file with no patch (binary, too large, unread) has
+/// none, so its findings go in the body.
+pub fn diff_lines(facts: &DevFacts) -> HashMap<String, BTreeSet<u64>> {
+ let mut out: HashMap<String, BTreeSet<u64>> = HashMap::new();
+ for f in &facts.files {
+ let Some(patch) = &f.patch else { continue };
+ let lines = out.entry(f.path.clone()).or_default();
+ let mut new_line: Option<u64> = None;
+ for line in patch.split('\n') {
+ if let Some(start) = super::scan::hunk_new_start(line) {
+ new_line = Some(start);
+ continue;
+ }
+ let Some(n) = new_line else { continue };
+ match line.as_bytes().first() {
+ Some(b'-') | Some(b'\\') => {}
+ // `+` or a context line; an empty line is a context line whose space was trimmed
+ _ => {
+ lines.insert(n);
+ new_line = Some(n + 1);
+ }
+ }
+ }
+ }
+ out
+}
+
+/// A review ready to send: the body (redacted, without the marker) and the inline comments.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Built {
+ pub body: String,
+ pub comments: Vec<ReviewComment>,
+}
+
+/// The findings a review posts: every one not dismissed (open, or sent to the author bot).
+pub fn postable(card: &Value) -> Vec<&Value> {
+ card["findings"].as_array().map_or(Vec::new(), |fs| fs.iter().filter(|f| f["state"].as_str() != Some("dismissed")).collect())
+}
+
+fn is_secret(f: &Value) -> bool {
+ f["source"].as_str() == Some("gitleaks")
+}
+
+fn location(f: &Value) -> String {
+ let file = f["file"].as_str().unwrap_or("").trim();
+ match f["line"].as_u64() {
+ Some(l) if !file.is_empty() => format!("{file}:{l}"),
+ _ => file.to_string(),
+ }
+}
+
+fn severity(f: &Value) -> String {
+ let s = f["severity"].as_str().unwrap_or("info");
+ let mut c = s.chars();
+ c.next().map_or(String::new(), |first| first.to_uppercase().chain(c).collect())
+}
+
+/// Text of one finding. A secret is only where it is (P4): no title, detail or fix, since gitleaks
+/// rule names and model text may quote the value.
+fn finding_text(f: &Value, with_location: bool) -> String {
+ if is_secret(f) {
+ return format!("Possible secret in {}", location(f));
+ }
+ let title = f["title"].as_str().unwrap_or("").trim();
+ let mut out = format!("**{}** · {title}", severity(f));
+ if with_location && !location(f).is_empty() {
+ out.push_str(&format!(" (`{}`)", location(f)));
+ }
+ for (label, key) in [("", "detail"), ("Fix: ", "fix")] {
+ let t = f[key].as_str().unwrap_or("").trim();
+ if !t.is_empty() {
+ out.push_str(&format!("\n\n{label}{t}"));
+ }
+ }
+ out
+}
+
+fn clip(s: &str, max: usize) -> String {
+ if s.chars().count() <= max {
+ return s.to_string();
+ }
+ let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
+ out.push('…');
+ out
+}
+
+fn tile_text(t: &Value, what: &str) -> String {
+ let count = t["count"].as_u64().unwrap_or(0);
+ match t["state"].as_str().unwrap_or("not_run") {
+ "pass" => "nothing found".into(),
+ "hit" => {
+ let missing = t["missing"].as_u64().unwrap_or(0);
+ let mut s = format!("{count} {what}{}", if count == 1 { "" } else { "s" });
+ if missing > 0 {
+ s.push_str(&format!(", {missing} not on the registry"));
+ }
+ s
+ }
+ "later" => "not checked yet".into(),
+ _ => match t["reason"].as_str() {
+ Some(r) if !r.trim().is_empty() => format!("not run ({})", r.trim()),
+ _ => "not run".into(),
+ },
+ }
+}
+
+/// Who wrote the review, for the last line.
+fn signature(card: &Value) -> String {
+ let r = &card["reviewer"];
+ match r["name"].as_str() {
+ Some(name) if !name.trim().is_empty() => {
+ let engine = r["engine"].as_str().filter(|e| !e.trim().is_empty()).unwrap_or("auto");
+ format!("Reviewed by {} ({engine}) in kwant", name.trim())
+ }
+ _ => "Reviewed by kwant's rule checks (no reviewer bot) in kwant".into(),
+ }
+}
+
+/// The review for `card` (P2, P3, P4). With `inline` false every finding goes in the body (the
+/// 422 retry). Redacted throughout.
+pub fn build(card: &Value, facts: &DevFacts, inline: bool) -> Built {
+ let lines = diff_lines(facts);
+ let mut comments = Vec::new();
+ let mut in_body: Vec<&Value> = Vec::new();
+ for f in postable(card) {
+ let file = f["file"].as_str().unwrap_or("");
+ let at = f["line"].as_u64().filter(|l| *l > 0 && lines.get(file).is_some_and(|ls| ls.contains(l)));
+ match at {
+ Some(line) if inline && comments.len() < MAX_INLINE => comments.push(ReviewComment {
+ path: file.to_string(),
+ line,
+ side: "RIGHT",
+ body: clip(&redact(&format!("{}\n\n<sub>kwant review</sub>", finding_text(f, false))), COMMENT_CHARS),
+ }),
+ _ => in_body.push(f),
+ }
+ }
+
+ let mut b = String::new();
+ let level = card["risk"]["level"].as_str().unwrap_or("unknown");
+ b.push_str(&format!("### kwant review · Risk: {}\n", severity(&json!({"severity": level}))));
+ for r in card["risk"]["reasons"].as_array().into_iter().flatten().filter_map(Value::as_str) {
+ b.push_str(&format!("- {r}\n"));
+ }
+
+ b.push_str("\n**Intent check**");
+ let intent = &card["intent"];
+ match intent["source"].as_str() {
+ Some("task") => b.push_str(" (against the kwant task this PR came from)\n"),
+ _ => b.push_str(" (against the PR's own title and description)\n"),
+ }
+ if let Some(asked) = intent["asked"].as_str().filter(|a| !a.trim().is_empty()) {
+ b.push_str(&format!("Asked: {}\n", asked.trim()));
+ }
+ let rows: Vec<&Value> = intent["rows"].as_array().map_or(Vec::new(), |r| r.iter().collect());
+ if rows.is_empty() {
+ b.push_str("- No intent check: the reviewer didn't answer.\n");
+ }
+ for r in rows {
+ let label = match r["state"].as_str() {
+ Some("ok") => "Done",
+ Some("missing") => "Missing",
+ Some("extra") => "Not asked for",
+ _ => "Note",
+ };
+ b.push_str(&format!("- {label}: {}\n", r["text"].as_str().unwrap_or("").trim()));
+ }
+
+ b.push_str("\n**Test tampering**\n");
+ let flags: Vec<&Value> = card["tamper"]["flags"].as_array().map_or(Vec::new(), |f| f.iter().collect());
+ if flags.is_empty() {
+ b.push_str("- None found.\n");
+ }
+ for f in flags {
+ b.push_str(&format!("- `{}:{}` {}\n", f["file"].as_str().unwrap_or(""), f["line"].as_u64().unwrap_or(0), f["why"].as_str().unwrap_or("").trim()));
+ let excerpt = f["excerpt"].as_str().unwrap_or("").trim_end();
+ if !excerpt.is_empty() {
+ let fence = if excerpt.contains("```") { "~~~~" } else { "```" };
+ b.push_str(&format!(" {fence}diff\n"));
+ for l in excerpt.lines() {
+ b.push_str(&format!(" {l}\n"));
+ }
+ b.push_str(&format!(" {fence}\n"));
+ }
+ }
+
+ let sec = &card["security"];
+ b.push_str("\n**Security**\n");
+ b.push_str(&format!("- Secrets (gitleaks): {}\n", tile_text(&sec["secrets"], "possible secret")));
+ b.push_str(&format!("- New packages: {}\n", tile_text(&sec["packages"], "package to check")));
+ b.push_str(&format!("- Known vulnerabilities (OSV): {}\n", tile_text(&sec["osv"], "")));
+ b.push_str(&format!("- Static analysis (Semgrep): {}\n", tile_text(&sec["semgrep"], "")));
+
+ if !in_body.is_empty() {
+ b.push_str(if comments.is_empty() { "\n**Findings**\n" } else { "\n**Other findings** (not on a line of this diff)\n" });
+ for f in in_body {
+ let text = finding_text(f, true).replace("\n\n", "\n ");
+ b.push_str(&format!("- {text}\n"));
+ }
+ }
+ b.push_str(&format!("\n---\n{}\n", signature(card)));
+
+ Built { body: clip(&redact(&b), BODY_CHARS), comments }
+}
+
+/// The hidden line that marks a review as this card's, so a post whose answer was lost isn't
+/// sent twice. Added after redaction: it is kwant's own card id, which redaction would mask.
+pub fn marker(card_id: &str) -> String {
+ format!("<!-- kwant review card {card_id} -->")
+}
+
+// ---------------------------------------------------------------------------------------------
+// The forge step
+
+/// Whether GitHub's 422 is about comment lines (then the retry puts everything in the body).
+fn about_lines(message: &str) -> bool {
+ let m = message.to_ascii_lowercase();
+ ["line", "path", "position", "diff", "hunk"].iter().any(|w| m.contains(w))
+}
+
+fn gh_error(e: GhError) -> PostError {
+ match e {
+ GhError::Forbidden | GhError::NotFound => PostError::new(ErrorKind::ReadOnly, READ_ONLY),
+ e => PostError::failed(e.to_string()),
+ }
+}
+
+/// The client whose connection can read PR `number`, and the PR. Same order as Dev mode's reads.
+async fn client_for_pull(state: &AppState, repo_name: &str, number: u64) -> Result<(GithubSource, crate::zombie::github::GhPull), PostError> {
+ let list = repo::clients(state).await.map_err(PostError::failed)?;
+ let mut last = GhError::NotFound;
+ for (_, c) in list {
+ match c.dev_pull(repo_name, number).await {
+ Ok(p) => return Ok((c, p)),
+ Err(e @ GhError::Limited { .. }) => return Err(gh_error(e)),
+ Err(e) => last = e,
+ }
+ }
+ Err(gh_error(last))
+}
+
+const NOT_FINISHED: &str = "This review didn't finish, so there's nothing to post. Run the review again first.";
+
+/// A review that finished: not pending or failed, with card text and no `error` in it. A failed
+/// review keeps the rule-only card (risk "Low", "the reviewer didn't answer"), which must never be
+/// posted as if it were a review (Rigel's F4).
+fn finished(row: &DevCardRow) -> bool {
+ if row.status == PENDING || row.status == FAILED {
+ return false;
+ }
+ let card: Option<Value> = row.card.as_deref().and_then(|c| serde_json::from_str(c).ok());
+ card.is_some_and(|c| c.get("error").is_none_or(Value::is_null))
+}
+
+/// Posts `card` (a review card row) to its PR: P1–P5, P7. Doesn't touch the database.
+pub async fn post_review(state: &AppState, row: &DevCardRow) -> Result<Posted, PostError> {
+ if !finished(row) {
+ return Err(PostError::failed(NOT_FINISHED));
+ }
+ if row.status == STALE {
+ return Err(PostError::new(ErrorKind::Stale, STALE_MESSAGE));
+ }
+ let facts: DevFacts = serde_json::from_str(&row.facts).map_err(|_| PostError::failed("kwant could not read this card's facts"))?;
+ let card: Value = row.card.as_deref().and_then(|c| serde_json::from_str(c).ok()).ok_or_else(|| PostError::failed("this review isn't written yet"))?;
+ let Some(number) = facts.pr else {
+ return Err(PostError::failed("this card has no pull request"));
+ };
+ let (client, pull) = client_for_pull(state, &facts.repo, number).await?;
+ if pull.head.sha != row.head_sha {
+ return Err(PostError::new(ErrorKind::Stale, STALE_MESSAGE));
+ }
+ if pull.state != "open" {
+ return Err(PostError::failed("this pull request is closed"));
+ }
+
+ // A post whose answer was lost (a timeout after GitHub took it): find it instead of posting twice
+ let mark = marker(&row.id);
+ if let Ok(reviews) = client.dev_reviews(&facts.repo, number).await {
+ if let Some(r) = reviews.iter().find(|r| r.body.as_deref().is_some_and(|b| b.contains(&mark)) && r.commit_id.as_deref() == Some(row.head_sha.as_str())) {
+ return Ok(Posted { at: Utc::now(), login: r.user.as_ref().map(|u| u.login.clone()), url: r.html_url.clone(), comments: 0, forge: FORGE.into() });
+ }
+ }
+
+ let send = |b: Built| ReviewPost { commit_id: row.head_sha.clone(), body: format!("{}\n\n{mark}", b.body), event: "COMMENT", comments: b.comments };
+ let first = build(&card, &facts, true);
+ let mut sent = first.comments.len();
+ let mut answer = client.dev_post_review(&facts.repo, number, &send(first)).await;
+ if let Err(GhPostError::Rejected(m)) = &answer {
+ if sent > 0 && about_lines(m) {
+ tracing::info!(card = %row.id, "dev: GitHub refused the inline comments ({m}); posting them in the body");
+ sent = 0;
+ answer = client.dev_post_review(&facts.repo, number, &send(build(&card, &facts, false))).await;
+ }
+ }
+ match answer {
+ Ok(r) => {
+ let login = r.user.as_ref().map(|u| u.login.clone());
+ if let Some(l) = &login {
+ remember_login(&client, l);
+ }
+ Ok(Posted { at: Utc::now(), login, url: r.html_url, comments: sent, forge: FORGE.into() })
+ }
+ Err(GhPostError::Rejected(m)) => Err(PostError::failed(format!("GitHub didn't take the review: {m}"))),
+ // A permission error can also come back as a 422 on some GitHub Enterprise versions; the
+ // 403 and 404 cases are the documented ones
+ Err(GhPostError::Gh(e)) => Err(gh_error(e)),
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// The route
+
+/// One post at a time per card (P6): a double click waits, then finds `posted`.
+fn card_lock(id: &str) -> Arc<tokio::sync::Mutex<()>> {
+ static LOCKS: OnceLock<Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>> = OnceLock::new();
+ let mut map = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
+ // Drop locks nobody holds, so the map stays small
+ map.retain(|_, l| Arc::strong_count(l) > 1);
+ map.entry(id.to_string()).or_default().clone()
+}
+
+fn error(status: StatusCode, message: &str) -> Response {
+ (status, Json(json!({"error": message}))).into_response()
+}
+
+fn internal(e: impl std::fmt::Display) -> Response {
+ tracing::warn!("dev: post: {e}");
+ error(StatusCode::INTERNAL_SERVER_ERROR, "Dev mode could not read or save that")
+}
+
+/// `POST /api/dev/cards/:id/post`: the card, 200, with `posted` or `post_error` set. 404 for no
+/// such card, 400 for a card that isn't a review, 409 for a review that didn't finish (pending, failed, or no text).
+pub async fn post(State(state): State<AppState>, headers: HeaderMap, Path(card_id): Path<String>) -> Response {
+ if let Err(r) = super::super::mcp_suggest::refuse_agent_tokens(&state, &headers, REFUSAL).await {
+ return r;
+ }
+ let card_id = card_id.trim().to_string();
+ let read = |state: AppState, id: String| async move { state.db.dev_card(&id).await };
+ let row = match read(state.clone(), card_id.clone()).await {
+ Ok(Some(r)) => r,
+ Ok(None) => return error(StatusCode::NOT_FOUND, "no such card"),
+ Err(e) => return internal(e),
+ };
+ if let Err(r) = active_space(&state, &row.space_id).await {
+ return r;
+ }
+ if row.kind != REVIEW {
+ return error(StatusCode::BAD_REQUEST, "only a review card can be posted");
+ }
+ if row.posted.is_some() {
+ return Json(card_json(&row)).into_response();
+ }
+ if !finished(&row) {
+ return error(StatusCode::CONFLICT, NOT_FINISHED);
+ }
+ let lock = card_lock(&row.id);
+ let _held = lock.lock().await;
+ // Read again under the lock: the press before this one may have posted
+ let row = match read(state.clone(), row.id.clone()).await {
+ Ok(Some(r)) => r,
+ Ok(None) => return error(StatusCode::NOT_FOUND, "no such card"),
+ Err(e) => return internal(e),
+ };
+ if row.posted.is_some() {
+ return Json(card_json(&row)).into_response();
+ }
+ if !finished(&row) {
+ return error(StatusCode::CONFLICT, NOT_FINISHED);
+ }
+ let saved = match post_review(&state, &row).await {
+ Ok(p) => state.db.set_dev_card_posted(&row.id, &json!(p).to_string()).await.map(|_| ()),
+ Err(e) => {
+ tracing::info!(card = %row.id, kind = ?e.kind, "dev: review not posted: {}", e.message);
+ state.db.set_dev_card_post_error(&row.id, Some(&json!(e).to_string())).await
+ }
+ };
+ if let Err(e) = saved {
+ return internal(e);
+ }
+ let row = match read(state.clone(), row.id.clone()).await {
+ Ok(Some(r)) => r,
+ Ok(None) => return error(StatusCode::NOT_FOUND, "no such card"),
+ Err(e) => return internal(e),
+ };
+ notify_card(&state, &row);
+ Json(card_json(&row)).into_response()
+}
+
+// ---------------------------------------------------------------------------------------------
+// Who posts (`forge_login`, P7)
+
+/// How long a connection's login is kept.
+const LOGIN_TTL: Duration = Duration::from_secs(15 * 60);
+/// How long a failed read is kept, so the settings page doesn't ask GitHub on every open.
+const LOGIN_MISS_TTL: Duration = Duration::from_secs(60);
+const LOGIN_TIMEOUT: Duration = Duration::from_secs(5);
+
+type Logins = Mutex<HashMap<(String, String), (Option<String>, Instant)>>;
+
+fn logins() -> &'static Logins {
+ static L: OnceLock<Logins> = OnceLock::new();
+ L.get_or_init(Default::default)
+}
+
+fn login_key(c: &GithubSource) -> (String, String) {
+ (c.connection_id().to_string(), c.api_base())
+}
+
+fn remember_login(c: &GithubSource, login: &str) {
+ logins().lock().unwrap_or_else(|e| e.into_inner()).insert(login_key(c), (Some(login.to_string()), Instant::now()));
+}
+
+/// The account the first GitHub connection posts as (`GET /user`), cached per connection. None
+/// with no connection, a locked vault, or a token GitHub refuses.
+pub async fn forge_login(state: &AppState) -> Option<String> {
+ let client = repo::clients(state).await.ok()?.into_iter().next()?.1;
+ let key = login_key(&client);
+ if let Some((login, at)) = logins().lock().unwrap_or_else(|e| e.into_inner()).get(&key).cloned() {
+ let ttl = if login.is_some() { LOGIN_TTL } else { LOGIN_MISS_TTL };
+ if at.elapsed() < ttl {
+ return login;
+ }
+ }
+ let login = tokio::time::timeout(LOGIN_TIMEOUT, client.dev_login()).await.ok().and_then(Result::ok);
+ logins().lock().unwrap_or_else(|e| e.into_inner()).insert(key, (login.clone(), Instant::now()));
+ login
+}
+
+/// `forge` and `forge_login` for the settings reply (amendment of 21:50): `github` when the space
+/// watches a repo and a GitHub connection is set up, else null (no Post button).
+pub async fn forge_json(state: &AppState, has_repo: bool) -> (Value, Value) {
+ if !has_repo || repo::clients(state).await.is_err() {
+ return (Value::Null, Value::Null);
+ }
+ (json!(FORGE), json!(forge_login(state).await))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::server::dev::facts::FileDiff;
+
+ /// A fake AWS-style key, built at run time so no scanner reads it as a real one.
+ fn fake_akia() -> String {
+ format!("{}{}{}", "AK", "IA", "Q7XW3MZP2KD9RT4B")
+ }
+
+ fn facts() -> DevFacts {
+ let mut f: DevFacts =
+ serde_json::from_str(&std::fs::read_to_string(format!("{}/src/server/dev/fixtures/pr301.json", env!("CARGO_MANIFEST_DIR"))).unwrap()).unwrap();
+ f.files = vec![
+ FileDiff {
+ path: "src/a.rs".into(),
+ status: "modified".into(),
+ additions: 3,
+ deletions: 1,
+ // new side: 10 (ctx), 11 (+), 12 (+), 13 (ctx); then 40..=41
+ patch: Some("@@ -10,3 +10,4 @@ fn a()\n ctx\n-old\n+new\n+newer\n ctx\n@@ -39,1 +40,2 @@\n+x\n \n\\ No newline at end of file".into()),
+ previous_path: None,
+ },
+ FileDiff { path: "img.png".into(), status: "added".into(), additions: 0, deletions: 0, patch: None, previous_path: None },
+ FileDiff { path: "gone.rs".into(), status: "removed".into(), additions: 0, deletions: 2, patch: Some("@@ -1,2 +0,0 @@\n-a\n-b".into()), previous_path: None },
+ ];
+ f
+ }
+
+ fn finding(id: &str, source: &str, file: &str, line: Option<u64>, state: &str) -> Value {
+ json!({"id": id, "severity": "high", "title": format!("Title {id}"), "file": file, "line": line, "detail": format!("Detail {id}"),
+ "fix": format!("Fix {id}"), "source": source, "state": state, "sent_at": null, "dismissed": null})
+ }
+
+ fn card(findings: Vec<Value>) -> Value {
+ json!({
+ "kind": "review",
+ "reviewer": {"id": "kw_1", "name": "Vega", "engine": "codex", "model": "gpt"},
+ "risk": {"level": "high", "reasons": ["Touches auth", "A test was switched off"]},
+ "intent": {"source": "task", "asked": "Add a sidebar", "rows": [{"state": "ok", "text": "Sidebar added"}, {"state": "missing", "text": "No mobile layout"}, {"state": "extra", "text": "Changed the logo"}], "none": false},
+ "tamper": {"flags": [{"kind": "skip", "file": "tests/a.rs", "line": 4, "excerpt": "-#[test]\n+#[ignore]", "why": "A test was switched off"}], "unread": []},
+ "security": {"secrets": {"state": "hit", "count": 1, "missing": 0}, "packages": {"state": "pass", "count": 0, "missing": 0}, "osv": {"state": "later"}, "semgrep": {"state": "later"}},
+ "findings": findings,
+ })
+ }
+
+ #[test]
+ fn hunks_give_the_new_side_lines() {
+ let l = diff_lines(&facts());
+ assert_eq!(l["src/a.rs"].iter().copied().collect::<Vec<_>>(), vec![10, 11, 12, 13, 40, 41]);
+ assert!(!l.contains_key("img.png"));
+ assert!(l["gone.rs"].is_empty());
+ }
+
+ #[test]
+ fn findings_inside_the_diff_are_inline_and_the_rest_go_in_the_body() {
+ let c = card(vec![
+ finding("f1", "review", "src/a.rs", Some(11), "open"),
+ finding("f2", "review", "src/a.rs", Some(25), "open"),
+ finding("f3", "review", "img.png", Some(1), "open"),
+ finding("f4", "review", "src/a.rs", Some(12), "dismissed"),
+ finding("f5", "review", "gone.rs", Some(1), "sent"),
+ finding("f6", "review", "src/a.rs", None, "open"),
+ ]);
+ let b = build(&c, &facts(), true);
+ assert_eq!(b.comments.len(), 1, "{b:?}");
+ assert_eq!((b.comments[0].path.as_str(), b.comments[0].line, b.comments[0].side), ("src/a.rs", 11, "RIGHT"));
+ assert!(b.comments[0].body.contains("Title f1") && b.comments[0].body.contains("Fix f1"));
+ for outside in ["Title f2", "`src/a.rs:25`", "Title f3", "Title f5", "Title f6"] {
+ assert!(b.body.contains(outside), "{outside} missing from:\n{}", b.body);
+ }
+ assert!(!b.body.contains("Title f4") && !b.body.contains("Title f1"), "{}", b.body);
+ assert!(b.body.contains("Other findings"));
+ }
+
+ #[test]
+ fn the_body_has_risk_intent_tamper_security_and_the_signature() {
+ let b = build(&card(vec![]), &facts(), true);
+ for want in [
+ "Risk: High",
+ "- Touches auth",
+ "- Done: Sidebar added",
+ "- Missing: No mobile layout",
+ "- Not asked for: Changed the logo",
+ "`tests/a.rs:4` A test was switched off",
+ "+#[ignore]",
+ "Secrets (gitleaks): 1 possible secret",
+ "New packages: nothing found",
+ "Known vulnerabilities (OSV): not checked yet",
+ ] {
+ assert!(b.body.contains(want), "{want} missing from:\n{}", b.body);
+ }
+ assert!(b.body.trim_end().ends_with("Reviewed by Vega (codex) in kwant"), "{}", b.body);
+ assert!(b.comments.is_empty());
+ }
+
+ #[test]
+ fn without_inline_everything_goes_in_the_body() {
+ let c = card(vec![finding("f1", "review", "src/a.rs", Some(11), "open"), finding("f2", "review", "src/a.rs", Some(40), "open")]);
+ let b = build(&c, &facts(), false);
+ assert!(b.comments.is_empty());
+ assert!(b.body.contains("Title f1") && b.body.contains("Title f2") && b.body.contains("**Findings**"), "{}", b.body);
+ }
+
+ #[test]
+ fn a_secret_is_only_where_it_is_and_nothing_secret_leaves() {
+ let key = fake_akia();
+ let mut leak = finding("s1", "gitleaks", "src/a.rs", Some(12), "open");
+ leak["title"] = json!(format!("Possible secret (aws-access-token {key})"));
+ leak["detail"] = json!(format!("rule aws-access-token matched {key}"));
+ let mut chatty = finding("f1", "review", "src/a.rs", Some(40), "open");
+ chatty["detail"] = json!(format!("The key {key} is hard-coded"));
+ let mut outside = finding("s2", "gitleaks", "config/prod.env", Some(3), "open");
+ outside["detail"] = json!(format!("value {key}"));
+ let mut c = card(vec![leak, chatty, outside]);
+ c["risk"]["reasons"] = json!([format!("Secret {key} found")]);
+ c["tamper"]["flags"][0]["excerpt"] = json!(format!("-let k = \"{key}\";"));
+ for inline in [true, false] {
+ let b = build(&c, &facts(), inline);
+ let all = format!("{}\n{}", b.body, b.comments.iter().map(|c| c.body.clone()).collect::<Vec<_>>().join("\n"));
+ assert!(!all.contains(&key) && !all.contains("Q7XW3MZP2KD9RT4B"), "a secret left kwant:\n{all}");
+ assert!(!all.contains("aws-access-token"), "the rule match left kwant:\n{all}");
+ assert!(all.contains("Possible secret in src/a.rs:12") && all.contains("Possible secret in config/prod.env:3"), "{all}");
+ }
+ let b = build(&c, &facts(), true);
+ let s1 = b.comments.iter().find(|c| c.line == 12).unwrap();
+ assert_eq!(s1.body, "Possible secret in src/a.rs:12\n\n<sub>kwant review</sub>");
+ }
+
+ #[test]
+ fn no_reviewer_signs_as_the_rule_checks() {
+ let mut c = card(vec![]);
+ c["reviewer"] = Value::Null;
+ assert!(build(&c, &facts(), true).body.contains("Reviewed by kwant's rule checks (no reviewer bot) in kwant"));
+ }
+
+ #[test]
+ fn only_line_errors_retry() {
+ assert!(about_lines("Unprocessable Entity: Line could not be resolved"));
+ assert!(about_lines("Pull request review thread line must be part of the diff"));
+ assert!(about_lines("Path could not be resolved"));
+ assert!(!about_lines("Validation Failed: commit_id is not part of the pull request"));
+ }
+}
diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rs
index c823050f..d547c8d4 100644
--- a/src/server/dev/routes.rs
+++ b/src/server/dev/routes.rs
@@ -46,7 +46,7 @@ async fn guard(state: &AppState, headers: &HeaderMap, id: &str) -> Result<SpaceI
pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Response> {
let row = state.db.dev_mode(space.as_str()).await.map_err(internal)?;
let calls = state.db.dev_calls_today(space.as_str()).await.map_err(internal)?;
- Ok(match row {
+ let mut v = match row {
Some(r) => row_json(&r, calls),
None => json!({
"on": false,
@@ -60,7 +60,13 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
"calls_today": calls,
"calls_cap": super::call_cap(),
}),
- })
+ };
+ // Where a review would be posted, and as whom (post-to-github.md P7 and its amendment)
+ let has_repo = v["repo"].as_str().is_some_and(|r| !r.is_empty());
+ let (forge, login) = super::post::forge_json(state, has_repo).await;
+ v["forge"] = forge;
+ v["forge_login"] = login;
+ Ok(v)
}
fn row_json(r: &DevModeRow, calls: i64) -> Value {
@@ -260,6 +266,12 @@ pub fn card_json(row: &DevCardRow) -> Value {
out.insert("kind".into(), json!(row.kind));
out.insert("status".into(), json!(row.status));
out.insert("created_at".into(), json!(row.created_at));
+ if row.kind == REVIEW {
+ // post-to-github.md P1: null until posted, null when the last post went through
+ let stored = |s: &Option<String>| s.as_deref().and_then(|v| serde_json::from_str::<Value>(v).ok()).unwrap_or(Value::Null);
+ out.insert("posted".into(), stored(&row.posted));
+ out.insert("post_error".into(), stored(&row.post_error));
+ }
Value::Object(out)
}
@@ -724,6 +736,8 @@ mod tests {
card: card.map(|c| c.to_string()),
created_at: at,
updated_at: at,
+ posted: None,
+ post_error: None,
}
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 6c0afe94..d05ce0a3 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -260,6 +260,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/spaces/:id/dev/backup", post(dev::routes::take_backup))
.route("/api/dev/cards/:id", get(dev::routes::card))
.route("/api/dev/cards/:id/findings/:fid", post(dev::routes::finding))
+ .route("/api/dev/cards/:id/post", post(dev::post::post))
.route("/api/kwants/:id/approvals", get(approval_modes::get_kwant).put(approval_modes::put_kwant))
.route("/api/settings", get(routes::get_settings).post(routes::save_settings))
.route("/api/settings/computer", get(computer::get_computer).put(computer::put_computer))
diff --git a/src/zombie/github.rs b/src/zombie/github.rs
index cbd56c18..a817e169 100644
--- a/src/zombie/github.rs
+++ b/src/zombie/github.rs
@@ -1,6 +1,8 @@
//! GitHub issues and pull requests the person opened or is assigned to, read with the REST API
-//! (GET only) and a token from the password vault. The token is only ever sent to the API base
-//! the person configured; every URL is built from it, never taken from a response.
+//! and a token from the password vault. The token is only ever sent to the API base the person
+//! configured; every URL is built from it, never taken from a response. Reads are GET only; the
+//! one write is [`GithubSource::dev_post_review`], a COMMENT review the person asked for on a Dev
+//! mode review card (docs/dev-mode.md, "Posting to GitHub").
use super::{clip, ConvKind, Conversation, MissionSource, Msg, SourceKind, MAX_MESSAGE_CHARS};
use chrono::{DateTime, Utc};
@@ -549,6 +551,123 @@ impl GithubSource {
}
}
+// ---------------------------------------------------------------------------------------------
+// Posting a review (0.7.1, post-to-github.md). kwant's only write to GitHub, made when the person
+// presses Post on a review card: one review with event COMMENT, never APPROVE or REQUEST_CHANGES.
+
+/// One inline comment, on the new side of the diff.
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct ReviewComment {
+ pub path: String,
+ pub line: u64,
+ pub side: &'static str,
+ pub body: String,
+}
+
+/// `POST /repos/{o}/{r}/pulls/{n}/reviews`. The event is always COMMENT.
+#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
+pub struct ReviewPost {
+ pub commit_id: String,
+ pub body: String,
+ pub event: &'static str,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub comments: Vec<ReviewComment>,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Default)]
+pub struct GhReview {
+ pub id: u64,
+ #[serde(default)]
+ pub user: Option<GhUser>,
+ #[serde(default)]
+ pub body: Option<String>,
+ #[serde(default)]
+ pub commit_id: Option<String>,
+ #[serde(default)]
+ pub html_url: Option<String>,
+}
+
+/// Why a review didn't post.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum PostError {
+ /// 422: GitHub couldn't take the review as sent (most often a comment line outside the
+ /// diff). GitHub's own message, which never holds the token.
+ Rejected(String),
+ Gh(GhError),
+}
+
+/// GitHub's 422 message and its `errors`, joined.
+fn unprocessable(body: &serde_json::Value) -> String {
+ let mut parts: Vec<String> = Vec::new();
+ if let Some(m) = body["message"].as_str() {
+ parts.push(m.to_string());
+ }
+ for e in body["errors"].as_array().into_iter().flatten() {
+ match e {
+ serde_json::Value::String(s) => parts.push(s.clone()),
+ v => {
+ if let Some(m) = v["message"].as_str() {
+ parts.push(m.to_string());
+ }
+ }
+ }
+ }
+ let text = parts.join(": ");
+ super::clip(&text, 300)
+}
+
+impl GithubSource {
+ /// Posts one COMMENT review on PR `number`. No redirect is followed and nothing is retried
+ /// here: the caller decides about a 422.
+ pub async fn dev_post_review(&self, repo: &str, number: u64, review: &ReviewPost) -> Result<GhReview, PostError> {
+ let repo = repo_path(repo).map_err(PostError::Gh)?;
+ let url = format!("{}/repos/{repo}/pulls/{number}/reviews", self.cfg.base());
+ let res = self
+ .http
+ .post(&url)
+ .bearer_auth(self.token.as_str())
+ .header("Accept", "application/vnd.github+json")
+ .header("X-GitHub-Api-Version", "2022-11-28")
+ .json(review)
+ .send()
+ .await
+ .map_err(|e| PostError::Gh(GhError::Other(format!("GitHub could not be reached: {}", e.without_url()))))?;
+ let status = res.status().as_u16();
+ let now = Utc::now().timestamp().max(0) as u64;
+ match status {
+ 200 | 201 => res.json().await.map_err(|_| PostError::Gh(GhError::Other("GitHub sent an answer kwant could not read".into()))),
+ 401 => Err(PostError::Gh(GhError::Auth)),
+ 404 => Err(PostError::Gh(GhError::NotFound)),
+ 422 => Err(PostError::Rejected(unprocessable(&res.json().await.unwrap_or_default()))),
+ 403 | 429 => Err(PostError::Gh(match retry_after(status, res.headers(), now) {
+ Some(s) => GhError::Limited { retry_after_s: s },
+ None => GhError::Forbidden,
+ })),
+ s => Err(PostError::Gh(GhError::Other(format!("GitHub answered {s}")))),
+ }
+ }
+
+ /// The reviews on a PR (the newest 100), to find one kwant posted before.
+ pub async fn dev_reviews(&self, repo: &str, number: u64) -> Result<Vec<GhReview>, GhError> {
+ self.get_as(&format!("/repos/{}/pulls/{number}/reviews?per_page=100", repo_path(repo)?), None).await
+ }
+
+ /// The token's account login.
+ pub async fn dev_login(&self) -> Result<String, GhError> {
+ Ok(self.get_as::<GhUser>("/user", None).await?.login)
+ }
+
+ /// The Loose ends connection id this client belongs to.
+ pub fn connection_id(&self) -> &str {
+ &self.id
+ }
+
+ /// The API base it talks to.
+ pub fn api_base(&self) -> String {
+ self.cfg.base()
+ }
+}
+
/// `owner/repo` from `https://api.github.com/repos/owner/repo`.
fn repo_of(repository_url: &str) -> Option<String> {
let mut parts = repository_url.trim_end_matches('/').rsplit('/');
diff --git a/tests/dev_post_test.rs b/tests/dev_post_test.rs
new file mode 100644
index 00000000..3036ddd4
--- /dev/null
+++ b/tests/dev_post_test.rs
@@ -0,0 +1,406 @@
+//! Post to GitHub (0.7.1, plan/post-to-github.md) against the shared mock GitHub: one COMMENT
+//! review pinned to the card's head, inline comments only on diff lines, the 422 retry with
+//! everything in the body, no secret in anything sent, stale heads, read-only tokens, one review
+//! per card however often Post is pressed, and only the person may press it.
+//!
+//! Nothing here reaches a real GitHub: every request goes to the mock on a loopback `api_base`.
+
+mod common;
+#[path = "support/mock_github.rs"]
+mod mock_github;
+
+use common::*;
+use kwnt::db::dev_mode::{FAILED, READY, RELEASE_NOTES, REVIEW, STALE};
+use kwnt::db::spaces::SpaceId;
+use kwnt::server::continuity::{SelfScope, TurnOrigin};
+use kwnt::server::mcp_runtime;
+use mock_github::*;
+use serde_json::{json, Value};
+
+const REPO: &str = "demo-org/demo-app";
+const PULL: &str = "/repos/demo-org/demo-app/pulls/24";
+const REVIEWS: &str = "/repos/demo-org/demo-app/pulls/24/reviews";
+const PORTS: [u16; 4] = [9495, 9496, 9497, 9498];
+
+fn head() -> String {
+ "c0ffee".repeat(7)[..40].to_string()
+}
+
+/// A turn token of bot `a`, as its CLI holds it.
+async fn turn_token(env: &Env) -> String {
+ let bot = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();
+ let scope = SelfScope {
+ kwant_id: bot.id.clone(),
+ kwant_name: bot.name.clone(),
+ origin: Some(TurnOrigin { direct_kwant_id: Some(bot.id.clone()), ..Default::default() }),
+ cancel: Some(tokio_util::sync::CancellationToken::new()),
+ turn_id: Some("turn-dev-post".into()),
+ sandbox_target: Some(bot.id.clone()),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(&env.state, &bot, Some("turn-dev-post".into()), None, Some(scope)).await.unwrap().1
+}
+
+/// A GitHub connection on the mock, and the token it holds.
+async fn connect(env: &Env, gh: &MockGithub) -> String {
+ let space = SpaceId::default_space();
+ env.state.db.set_space_approvals(&space, "ask").await.unwrap();
+ let token = canary_token();
+ gh.require_token(&token);
+ // Saving a connection tests it with `GET /user`
+ gh.json("/user", user("octocat"));
+ let (s, v) = call(&env.app, "POST", "/api/zombie/sources", Some(json!({"kind": "github", "label": "GitHub", "config": {"api_base": gh.base}, "secret": token}))).await;
+ assert_eq!(s.as_u16(), 201, "{v}");
+ gh.clear_hits();
+ token
+}
+
+/// The facts of PR 24 at [`head`]: `src/app.rs` has new-side lines 10–13 in its diff.
+fn facts() -> Value {
+ let mut f: Value = serde_json::from_str(&std::fs::read_to_string(format!("{}/src/server/dev/fixtures/pr301.json", env!("CARGO_MANIFEST_DIR"))).unwrap()).unwrap();
+ f["repo"] = json!(REPO);
+ f["kind"] = json!("review");
+ f["pr"] = json!(24);
+ f["head_sha"] = json!(head());
+ f["files"] = json!([
+ {"path": "src/app.rs", "status": "modified", "additions": 2, "deletions": 1, "patch": "@@ -10,3 +10,4 @@\n ctx\n-old\n+new\n+newer\n ctx", "previous_path": null},
+ {"path": "config/prod.env", "status": "added", "additions": 1, "deletions": 0, "patch": null, "previous_path": null},
+ ]);
+ f
+}
+
+fn finding(id: &str, source: &str, file: &str, line: u64, title: &str, detail: &str) -> Value {
+ json!({"id": id, "severity": "high", "title": title, "file": file, "line": line, "detail": detail, "fix": "Do it right",
+ "source": source, "state": "open", "sent_at": null, "dismissed": null})
+}
+
+fn card(findings: Vec<Value>) -> Value {
+ json!({
+ "kind": "review", "pr": 24, "title": "Sidebar",
+ "reviewer": {"id": "kw_v", "name": "Vega", "engine": "codex", "model": "gpt"},
+ "risk": {"level": "medium", "reasons": ["Touches config"]},
+ "intent": {"source": "pr", "asked": "A sidebar", "rows": [{"state": "ok", "text": "Sidebar added"}], "none": true},
+ "tamper": {"flags": [], "unread": []},
+ "security": {"secrets": {"state": "hit", "count": 1, "missing": 0}, "packages": {"state": "pass", "count": 0, "missing": 0}, "osv": {"state": "later"}, "semgrep": {"state": "later"}},
+ "findings": findings,
+ })
+}
+
+/// A ready review card for PR 24 at [`head`].
+async fn review_card(env: &Env, findings: Vec<Value>) -> String {
+ let space = SpaceId::default_space();
+ let row = env.state.db.insert_dev_card(space.as_str(), REVIEW, "pr:24", &head(), &facts().to_string()).await.unwrap().unwrap();
+ env.state.db.set_dev_card(&row.id, READY, Some(&card(findings).to_string())).await.unwrap();
+ row.id
+}
+
+fn review_reply(id: u64) -> Value {
+ json!({"id": id, "user": user("octocat"), "body": "…", "commit_id": head(), "state": "COMMENTED",
+ "html_url": format!("https://github.com/demo-org/demo-app/pull/24#pullrequestreview-{id}")})
+}
+
+fn seed(gh: &MockGithub) {
+ gh.json(PULL, pull(24, "Sidebar", ("sidebar", &head()), "main", "pixel-bot", None));
+ gh.json("/user", user("octocat"));
+}
+
+async fn press(env: &Env, id: &str) -> (u16, Value) {
+ let (s, v) = call(&env.app, "POST", &format!("/api/dev/cards/{id}/post"), None).await;
+ (s.as_u16(), v)
+}
+
+fn sent(w: &Write) -> Value {
+ serde_json::from_str(&w.body).unwrap()
+}
+
+#[tokio::test]
+async fn one_press_posts_one_comment_review_with_inline_and_body_findings() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ connect(&env, &gh).await;
+ seed(&gh);
+ gh.accept_write("POST", REVIEWS, 200, review_reply(1));
+ let id = review_card(
+ &env,
+ vec![finding("f1", "review", "src/app.rs", 11, "Unchecked unwrap", "It panics"), finding("f2", "review", "src/app.rs", 99, "Old helper", "Outside the diff")],
+ )
+ .await;
+ let mut events = env.state.event_sender.subscribe();
+
+ let (s, v) = press(&env, &id).await;
+ assert_eq!(s, 200, "{v}");
+ assert_eq!(v["post_error"], Value::Null, "{v}");
+ assert_eq!(v["posted"]["login"], "octocat");
+ assert_eq!(v["posted"]["url"], "https://github.com/demo-org/demo-app/pull/24#pullrequestreview-1");
+ assert_eq!(v["posted"]["comments"], 1);
+ assert_eq!(v["posted"]["forge"], "github");
+ assert!(v["posted"]["at"].is_string(), "{v}");
+
+ let writes = gh.writes();
+ assert_eq!(writes.len(), 1, "{writes:?}");
+ assert!(writes[0].authorized && writes[0].path == REVIEWS, "{writes:?}");
+ let body = sent(&writes[0]);
+ assert_eq!(body["event"], "COMMENT", "never APPROVE or REQUEST_CHANGES");
+ assert_eq!(body["commit_id"], head().as_str(), "pinned to the card's head");
+ assert_eq!(body["comments"].as_array().unwrap().len(), 1, "{body}");
+ assert_eq!((body["comments"][0]["path"].as_str(), body["comments"][0]["line"].as_u64(), body["comments"][0]["side"].as_str()), (Some("src/app.rs"), Some(11), Some("RIGHT")));
+ assert!(body["comments"][0]["body"].as_str().unwrap().contains("Unchecked unwrap"));
+ let text = body["body"].as_str().unwrap();
+ for want in ["Risk: Medium", "Touches config", "Done: Sidebar added", "Secrets (gitleaks): 1 possible secret", "Old helper", "`src/app.rs:99`", "Reviewed by Vega (codex) in kwant", &format!("<!-- kwant review card {id} -->")] {
+ assert!(text.contains(want), "{want} missing from:\n{text}");
+ }
+ assert!(!text.contains("Unchecked unwrap"), "an inline finding isn't repeated in the body");
+
+ // The desk hears about it
+ let mut heard = false;
+ while let Ok(e) = events.try_recv() {
+ heard |= serde_json::to_string(&e).unwrap_or_default().contains(&id);
+ }
+ assert!(heard, "a dev_card event after the post");
+
+ // The card keeps `posted`; the settings say who posts, and where
+ let (_, v) = call(&env.app, "GET", &format!("/api/dev/cards/{id}"), None).await;
+ assert_eq!(v["posted"]["comments"], 1, "{v}");
+ env.state.db.put_dev_mode(SpaceId::default_space().as_str(), false, REPO, "main", None, None).await.unwrap();
+ let (_, m) = call(&env.app, "GET", &format!("/api/spaces/{}/dev_mode", SpaceId::default_space().as_str()), None).await;
+ assert_eq!((m["forge"].as_str(), m["forge_login"].as_str()), (Some("github"), Some("octocat")), "{m}");
+ assert!(m.get("github_login").is_none(), "{m}");
+}
+
+#[tokio::test]
+async fn a_422_about_lines_posts_again_with_everything_in_the_body() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ connect(&env, &gh).await;
+ seed(&gh);
+ gh.accept_write("POST", REVIEWS, 422, json!({"message": "Unprocessable Entity", "errors": ["Line could not be resolved"]}));
+ gh.accept_write("POST", REVIEWS, 200, review_reply(2));
+ let id = review_card(&env, vec![finding("f1", "review", "src/app.rs", 12, "Unchecked unwrap", "It panics")]).await;
+
+ let (s, v) = press(&env, &id).await;
+ assert_eq!(s, 200, "{v}");
+ assert_eq!(v["posted"]["comments"], 0, "{v}");
+ let writes = gh.writes();
+ assert_eq!(writes.len(), 2, "one retry, no more: {writes:?}");
+ assert_eq!(sent(&writes[0])["comments"].as_array().map(Vec::len), Some(1));
+ let retry = sent(&writes[1]);
+ assert!(retry.get("comments").is_none(), "{retry}");
+ assert!(retry["body"].as_str().unwrap().contains("Unchecked unwrap"), "{retry}");
+ assert_eq!(retry["commit_id"], head().as_str());
+}
+
+#[tokio::test]
+async fn a_422_on_the_retry_is_a_failed_post_and_try_again_works() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ connect(&env, &gh).await;
+ seed(&gh);
+ gh.accept_write("POST", REVIEWS, 422, json!({"message": "Unprocessable Entity", "errors": ["Line could not be resolved"]}));
+ gh.accept_write("POST", REVIEWS, 422, json!({"message": "Validation Failed", "errors": [{"message": "Line could not be resolved"}]}));
+ let id = review_card(&env, vec![finding("f1", "review", "src/app.rs", 12, "Unchecked unwrap", "It panics")]).await;
+
+ let (s, v) = press(&env, &id).await;
+ assert_eq!(s, 200, "{v}");
+ assert_eq!(v["posted"], Value::Null);
+ assert_eq!(v["post_error"]["kind"], "failed", "{v}");
+ assert!(v["post_error"]["message"].as_str().unwrap().contains("Line could not be resolved"), "{v}");
+ assert_eq!(gh.writes().len(), 2);
+
+ // Try again: it goes through and the error is cleared
+ gh.accept_write("POST", REVIEWS, 200, review_reply(3));
+ let (_, v) = press(&env, &id).await;
+ assert_eq!(v["post_error"], Value::Null, "{v}");
+ assert_eq!(v["posted"]["url"], "https://github.com/demo-org/demo-app/pull/24#pullrequestreview-3");
+}
+
+#[tokio::test]
+async fn no_secret_value_is_in_anything_sent() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ let token = connect(&env, &gh).await;
+ seed(&gh);
+ gh.accept_write("POST", REVIEWS, 422, json!({"message": "Unprocessable Entity", "errors": ["Line could not be resolved"]}));
+ gh.accept_write("POST", REVIEWS, 200, review_reply(4));
+ let key = secret_like("AKIA", 16).to_uppercase();
+ let findings = vec![
+ // gitleaks, on a diff line and off it: the rule and the value stay in kwant
+ finding("s1", "gitleaks", "src/app.rs", 11, &format!("Possible secret (aws-access-token {key})"), &format!("aws-access-token matched {key}")),
+ finding("s2", "gitleaks", "config/prod.env", 1, "Possible secret (aws-access-token)", &format!("value {key}")),
+ // A model finding that quotes it: redaction masks it
+ finding("f1", "review", "src/app.rs", 12, "Hard-coded key", &format!("The key {key} is in the source")),
+ ];
+ let id = review_card(&env, findings).await;
+ let mut c: Value = serde_json::from_str(&env.state.db.dev_card(&id).await.unwrap().unwrap().card.unwrap()).unwrap();
+ c["risk"]["reasons"] = json!([format!("Secret {key} found")]);
+ c["tamper"]["flags"] = json!([{"kind": "skip", "file": "tests/a.rs", "line": 4, "excerpt": format!("-let k = \"{key}\";"), "why": "A test was switched off"}]);
+ let before = env.state.db.dev_card(&id).await.unwrap().unwrap().card;
+ assert!(env.state.db.swap_dev_card_json(&id, before.as_deref(), &c.to_string()).await.unwrap());
+
+ let (s, v) = press(&env, &id).await;
+ assert_eq!(s, 200, "{v}");
+ assert!(v["posted"].is_object(), "{v}");
+ let writes = gh.writes();
+ assert_eq!(writes.len(), 2, "the first try and the retry both checked");
+ for w in &writes {
+ assert!(!w.body.contains(&key) && !w.body.contains(&key[4..]), "the AKIA value left kwant: {}", w.body);
+ assert!(!w.body.contains("aws-access-token"), "the gitleaks rule left kwant: {}", w.body);
+ assert!(!w.body.contains(&token), "the token is never in a body");
+ assert!(w.body.contains("Possible secret in src/app.rs:11") && w.body.contains("Possible secret in config/prod.env:1"), "{}", w.body);
+ }
+ let first = sent(&writes[0]);
+ let s1 = first["comments"].as_array().unwrap().iter().find(|c| c["line"] == 11).unwrap();
+ assert_eq!(s1["body"], "Possible secret in src/app.rs:11\n\n<sub>kwant review</sub>");
+}
+
+#[tokio::test]
+async fn a_moved_head_or_a_stale_card_posts_nothing() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ connect(&env, &gh).await;
+ seed(&gh);
+ gh.json(PULL, pull(24, "Sidebar", ("sidebar", &"d".repeat(40)), "main", "pixel-bot", None));
+ let id = review_card(&env, vec![finding("f1", "review", "src/app.rs", 11, "T", "D")]).await;
+
+ let (s, v) = press(&env, &id).await;
+ assert_eq!(s, 200, "{v}");
+ assert_eq!((v["post_error"]["kind"].as_str(), v["posted"].clone()), (Some("stale"), Value::Null), "{v}");
+ assert!(gh.writes().is_empty());
+
+ // A card the poller already marked stale doesn't even ask GitHub
+ gh.clear_hits();
+ env.state.db.stale_dev_reviews(SpaceId::default_space().as_str(), "pr:24", None).await.unwrap();
+ assert_eq!(env.state.db.dev_card(&id).await.unwrap().unwrap().status, STALE);
+ let (_, v) = press(&env, &id).await;
+ assert_eq!(v["post_error"]["kind"], "stale", "{v}");
+ assert!(gh.hits_of(PULL).is_empty() && gh.writes().is_empty(), "{:?}", gh.hits());
+}
+
+#[tokio::test]
+async fn a_token_that_cannot_write_is_read_only() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ connect(&env, &gh).await;
+ seed(&gh);
+ gh.accept_write("POST", REVIEWS, 403, json!({"message": "Resource not accessible by personal access token"}));
+ let id = review_card(&env, vec![]).await;
+
+ let (s, v) = press(&env, &id).await;
+ assert_eq!(s, 200, "{v}");
+ assert_eq!(v["post_error"]["kind"], "read_only", "{v}");
+ assert!(v["post_error"]["message"].as_str().unwrap().contains("Pull requests: Read and write"), "{v}");
+ assert_eq!(v["posted"], Value::Null);
+
+ // A 404 on the write (a classic token without `repo` on a private repo) is read only too
+ gh.accept_write("POST", REVIEWS, 404, json!({"message": "Not Found"}));
+ let (_, v) = press(&env, &id).await;
+ assert_eq!(v["post_error"]["kind"], "read_only", "{v}");
+ assert_eq!(gh.writes().len(), 2);
+}
+
+#[tokio::test]
+async fn a_second_press_or_a_double_click_makes_one_review() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ connect(&env, &gh).await;
+ seed(&gh);
+ gh.accept_write("POST", REVIEWS, 200, review_reply(5));
+ let id = review_card(&env, vec![finding("f1", "review", "src/app.rs", 11, "T", "D")]).await;
+
+ // A double click: both presses at once
+ let (a, b) = tokio::join!(press(&env, &id), press(&env, &id));
+ assert_eq!((a.0, b.0), (200, 200));
+ assert_eq!(a.1["posted"], b.1["posted"], "both answer with the one review");
+ assert_eq!(gh.writes().len(), 1);
+
+ // A later press: the card comes back unchanged, and GitHub isn't asked at all
+ gh.clear_hits();
+ let (s, v) = press(&env, &id).await;
+ assert_eq!(s, 200);
+ assert_eq!(v["posted"], a.1["posted"]);
+ assert!(gh.hits().is_empty(), "{:?}", gh.hits());
+ assert_eq!(gh.writes().len(), 1);
+}
+
+#[tokio::test]
+async fn a_review_already_on_github_is_found_not_posted_again() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ connect(&env, &gh).await;
+ seed(&gh);
+ let id = review_card(&env, vec![]).await;
+ // GitHub took an earlier post whose answer was lost
+ let mut earlier = review_reply(6);
+ earlier["body"] = json!(format!("…\n\n<!-- kwant review card {id} -->"));
+ gh.json(REVIEWS, json!([earlier]));
+
+ let (_, v) = press(&env, &id).await;
+ assert_eq!(v["posted"]["url"], "https://github.com/demo-org/demo-app/pull/24#pullrequestreview-6", "{v}");
+ assert!(gh.writes().is_empty());
+}
+
+#[tokio::test]
+async fn only_the_person_posts_and_only_review_cards() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ connect(&env, &gh).await;
+ seed(&gh);
+ let id = review_card(&env, vec![]).await;
+ let uri = format!("/api/dev/cards/{id}/post");
+
+ let token = turn_token(&env).await;
+ for auth in [format!("Bearer {token}"), "Bearer not-the-person".to_string()] {
+ let (s, v) = call_with(&env.app, "POST", &uri, None, &[("authorization", auth.as_str())]).await;
+ assert_eq!(s.as_u16(), 403, "{v}");
+ }
+ assert!(call_remote(&env.app, "POST", &uri).await.is_client_error(), "a remote client without the API token is refused");
+ assert!(gh.hits().is_empty() && gh.writes().is_empty(), "a refused press never reaches GitHub: {:?}", gh.hits());
+ assert_eq!(env.state.db.dev_card(&id).await.unwrap().unwrap().post_error, None);
+
+ let (s, _) = press(&env, "dvc_nope").await;
+ assert_eq!(s, 404);
+ let notes = env.state.db.insert_dev_card(SpaceId::default_space().as_str(), RELEASE_NOTES, "since:", "20261105T210000.000", "{}").await.unwrap().unwrap();
+ let (s, v) = press(&env, &notes.id).await;
+ assert_eq!(s, 400, "{v}");
+}
+
+#[tokio::test]
+async fn no_connection_is_a_failed_post_and_no_forge() {
+ let env = setup().await;
+ let id = review_card(&env, vec![]).await;
+ let (s, v) = press(&env, &id).await;
+ assert_eq!(s, 200, "{v}");
+ assert_eq!(v["post_error"]["kind"], "failed", "{v}");
+ assert!(v["post_error"]["message"].as_str().unwrap().contains("Connect GitHub in Loose ends"), "{v}");
+ let (_, m) = call(&env.app, "GET", &format!("/api/spaces/{}/dev_mode", SpaceId::default_space().as_str()), None).await;
+ assert_eq!((m["forge"].clone(), m["forge_login"].clone()), (Value::Null, Value::Null), "{m}");
+}
+
+/// Rigel's F4: a review that failed keeps a rule-only card ("Risk: Low", "the reviewer didn't
+/// answer"). Pressing Post on it, or on one still being written, is a 409 and never reaches GitHub.
+#[tokio::test]
+async fn a_review_that_did_not_finish_is_409_and_posts_nothing() {
+ let env = setup().await;
+ let gh = MockGithub::start(&PORTS).await;
+ connect(&env, &gh).await;
+ seed(&gh);
+ gh.clear_hits();
+ let space = SpaceId::default_space();
+
+ let failed = env.state.db.insert_dev_card(space.as_str(), REVIEW, "pr:24", &head(), &facts().to_string()).await.unwrap().unwrap();
+ let mut text = card(vec![finding("f1", "review", "src/app.rs", 11, "Unchecked unwrap", "This panics on an empty list.")]);
+ text["error"] = json!("The review didn't finish: Ann couldn't write the card's text twice in a row.");
+ env.state.db.set_dev_card(&failed.id, FAILED, Some(&text.to_string())).await.unwrap();
+
+ let pending = env.state.db.insert_dev_card(space.as_str(), REVIEW, "pr:25", &head(), &facts().to_string()).await.unwrap().unwrap();
+
+ for id in [&failed.id, &pending.id] {
+ for _ in 0..2 {
+ let (s, v) = press(&env, id).await;
+ assert_eq!(s, 409, "{v}");
+ assert_eq!(v["error"], "This review didn't finish, so there's nothing to post. Run the review again first.");
+ }
+ let row = env.state.db.dev_card(id).await.unwrap().unwrap();
+ assert!(row.posted.is_none() && row.post_error.is_none(), "a 409 stores nothing");
+ }
+ assert!(gh.hits().is_empty() && gh.writes().is_empty(), "no GitHub call: {:?}", gh.hits());
+}
diff --git a/tests/support/mock_github.rs b/tests/support/mock_github.rs
index 6259ea10..213c745f 100644
--- a/tests/support/mock_github.rs
+++ b/tests/support/mock_github.rs
@@ -17,9 +17,11 @@
//! gets 304 with no body, as GitHub does.
//! - With [`MockGithub::require_token`], a request without that bearer token gets 401.
//! - Every request is logged: method, path with query, and whether `Authorization` was sent.
-//! - Dev mode only reads. Any request that isn't a GET is answered 405, logged, and fails the test:
-//! [`MockGithub::assert_read_only`] panics, and so does dropping the mock (unless the test is
-//! already failing).
+//! - Dev mode reads, and writes only a review the person posts (0.7.1). A request that isn't a GET
+//! is answered 405, logged, and fails the test (dropping the mock panics, unless the test is
+//! already failing), unless the test queued an answer for it with [`MockGithub::accept_write`].
+//! [`MockGithub::assert_read_only`] still panics on any write, accepted or not. Accepted writes
+//! keep their request body: [`MockGithub::writes`].
//! - Secret-looking strings are built at runtime ([`canary_token`], [`secret_like`]), so GitHub push
//! protection and Gitleaks never see one in the source.
@@ -68,8 +70,21 @@ pub struct Hit {
pub not_modified: bool,
}
+/// A write the mock accepted, with what was sent.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Write {
+ pub method: String,
+ pub path: String,
+ pub authorized: bool,
+ /// The request body as sent (kept raw, so a test can search all of it).
+ pub body: String,
+}
+
#[derive(Default)]
struct Inner {
+ write_replies: Mutex<HashMap<String, std::collections::VecDeque<(u16, Value)>>>,
+ writes: Mutex<Vec<Write>>,
+ refused_writes: Mutex<Vec<Hit>>,
replies: Mutex<HashMap<String, Value>>,
faults: Mutex<HashMap<String, Fault>>,
links: Mutex<HashMap<String, String>>,
@@ -149,6 +164,24 @@ impl MockGithub {
self.inner.hits.lock().unwrap().clear();
}
+ /// Queues one answer (`status`, `body`) to the next `method` `path` write (the path without
+ /// its query). Each queued answer serves one request; a write with none left fails the test.
+ pub fn accept_write(&self, method: &str, path: &str, status: u16, body: Value) -> &Self {
+ self.inner.write_replies.lock().unwrap().entry(format!("{} {path}", method.to_uppercase())).or_default().push_back((status, body));
+ self
+ }
+
+ /// The writes answered from [`MockGithub::accept_write`], oldest first.
+ pub fn writes(&self) -> Vec<Write> {
+ self.inner.writes.lock().unwrap().clone()
+ }
+
+ /// Panics if a write reached the mock that no test queued an answer for.
+ pub fn assert_no_unexpected_writes(&self) {
+ let refused = self.inner.refused_writes.lock().unwrap().clone();
+ assert!(refused.is_empty(), "the mock got writes nobody expected: {refused:?}");
+ }
+
/// Panics if anything but a GET reached the mock.
pub fn assert_read_only(&self) {
let writes: Vec<Hit> = self.hits().into_iter().filter(|h| h.method != "GET").collect();
@@ -160,7 +193,7 @@ impl Drop for MockGithub {
fn drop(&mut self) {
self.server.abort();
if !std::thread::panicking() {
- self.assert_read_only();
+ self.assert_no_unexpected_writes();
}
}
}
@@ -178,6 +211,7 @@ async fn answer(State(inner): State<Arc<Inner>>, req: Request) -> Response {
let headers = req.headers().clone();
let full = req.uri().path_and_query().map(|p| p.as_str().to_string()).unwrap_or_else(|| req.uri().path().to_string());
let path = req.uri().path().to_string();
+ let body = axum::body::to_bytes(req.into_body(), 4 << 20).await.map(|b| String::from_utf8_lossy(&b).into_owned()).unwrap_or_default();
fn find<T: Clone>(m: &Mutex<HashMap<String, T>>, full: &str, path: &str) -> Option<T> {
let m = m.lock().unwrap();
m.get(full).or_else(|| m.get(path)).cloned()
@@ -185,8 +219,14 @@ async fn answer(State(inner): State<Arc<Inner>>, req: Request) -> Response {
let mut hit = Hit { method: method.to_string(), path: full.clone(), authorized: headers.contains_key("authorization"), not_modified: false };
if method != Method::GET {
- inner.hits.lock().unwrap().push(hit);
- return (StatusCode::METHOD_NOT_ALLOWED, axum::Json(json!({"message": "the mock GitHub only answers GET"}))).into_response();
+ inner.hits.lock().unwrap().push(hit.clone());
+ let queued = inner.write_replies.lock().unwrap().get_mut(&format!("{method} {path}")).and_then(|q| q.pop_front());
+ let Some((status, reply)) = queued else {
+ inner.refused_writes.lock().unwrap().push(hit);
+ return (StatusCode::METHOD_NOT_ALLOWED, axum::Json(json!({"message": "the mock GitHub only answers GET"}))).into_response();
+ };
+ inner.writes.lock().unwrap().push(Write { method: method.to_string(), path: full, authorized: hit.authorized, body });
+ return (StatusCode::from_u16(status).unwrap_or(StatusCode::OK), axum::Json(reply)).into_response();
}
let token = inner.token.lock().unwrap().clone();
if let Some(t) = token {