Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / infra / agents / agentd / src / issues.rs
issues.rs371 lines · 15.1 KiBRaw
| 1 | //! GitHub glue for issue-linked tasks: fetching an issue at task creation, |
| 2 | //! and posting the after-push comment + label. |
| 3 | //! |
| 4 | //! The sandbox never sees the token: [`github_client`] reads it from the |
| 5 | //! process environment (`AGENTD_GITHUB_TOKEN`) in agentd, and all calls are |
| 6 | //! plain read/write through [`crate::github::GitHub`]. |
| 7 | //! |
| 8 | //! [`after_push`] is the hook the parallel worker's `hooks.rs` will call |
| 9 | //! from the Approve path (it does not exist on this branch yet): |
| 10 | //! |
| 11 | //! ```ignore |
| 12 | //! // hooks.rs (other worker): |
| 13 | //! let issue_note = crate::issues::after_push(&ctx, &task).await; |
| 14 | //! ``` |
| 15 | //! |
| 16 | //! It never panics and never fails the push: failures are logged and |
| 17 | //! returned as [`AfterPush::Failed`] for the caller to surface (e.g. as a |
| 18 | //! `status` event and on the review UI). |
| 19 | |
| 20 | use crate::config::Config; |
| 21 | use crate::github::{GitHub, Issue, SOLVED_LABEL}; |
| 22 | |
| 23 | /// Build a [`GitHub`] client from config: repo from `AGENTD_GITHUB_REPO` |
| 24 | /// (default `vayun-mathur/Modern-Apps`), API base from `AGENTD_GITHUB_API` |
| 25 | /// (default `https://api.github.com`, overridden in tests to a mock |
| 26 | /// server), token from `Config::github_token` (`AGENTD_GITHUB_TOKEN`). |
| 27 | pub fn github_client(config: &Config) -> Result<GitHub, crate::github::Error> { |
| 28 | GitHub::with_base_url(&config.github_api_base, &config.github_repo, config.github_token.clone()) |
| 29 | } |
| 30 | |
| 31 | /// Fetch one issue for the start-from-issue flow. |
| 32 | pub async fn fetch_issue(config: &Config, number: u64) -> Result<Issue, crate::github::Error> { |
| 33 | github_client(config)?.read_issue(number).await |
| 34 | } |
| 35 | |
| 36 | /// Whether a token is configured (after_push no-ops without one). |
| 37 | // Called from the merge-time `hooks.rs` Approve path; unused until then. |
| 38 | pub fn token_configured(config: &Config) -> bool { |
| 39 | config.github_token.as_ref().is_some_and(|t| !t.trim().is_empty()) |
| 40 | } |
| 41 | |
| 42 | /// Outcome of [`after_push`], for the caller to surface in the UI. |
| 43 | // Called from the merge-time `hooks.rs` Approve path; unused until then. |
| 44 | #[derive(Debug, Clone)] |
| 45 | pub enum AfterPush { |
| 46 | /// Comment posted and label added (holds the comment URL). |
| 47 | Posted { comment_url: String }, |
| 48 | /// No linked issue: nothing to do. |
| 49 | NoIssue, |
| 50 | /// No `AGENTD_GITHUB_TOKEN` configured: skipped. |
| 51 | NoToken, |
| 52 | /// A step failed; the push itself already succeeded. The string is |
| 53 | /// human-readable for a `status` event. |
| 54 | Failed { message: String }, |
| 55 | } |
| 56 | |
| 57 | /// Comment body for a pushed fix. Marked as agent-written. |
| 58 | // Called from the merge-time `hooks.rs` Approve path; unused until then. |
| 59 | pub fn after_push_comment(task_title: &str, branch: &str, sha: &str, summary: &str) -> String { |
| 60 | let short: String = sha.chars().take(12).collect(); |
| 61 | format!( |
| 62 | "🤖 Agent fix pushed for \"{task_title}\".\n\n\ |
| 63 | Branch: `{branch}`\n\ |
| 64 | Commit: `{short}`\n\ |
| 65 | Upstream: https://git.maproj.org/Modern-Apps.git (`{branch}`)\n\n\ |
| 66 | {summary}\n\n\ |
| 67 | _Posted by the agent after operator approval._" |
| 68 | ) |
| 69 | } |
| 70 | |
| 71 | /// Post-push hook: if the task links a GitHub issue and a token is |
| 72 | /// configured, post a comment (summary, branch, short sha, upstream link, |
| 73 | /// marked as from the agent) and add the `solved for next release` label. |
| 74 | /// |
| 75 | /// Never panics; failures are logged and returned as [`AfterPush::Failed`] |
| 76 | /// (the caller emits a `status` event). Failures never block the push. |
| 77 | // Called from the merge-time `hooks.rs` Approve path; unused until then. |
| 78 | pub async fn after_push( |
| 79 | ctx: &crate::agent::DriverCtx, |
| 80 | task: &crate::models::Task, |
| 81 | ) -> AfterPush { |
| 82 | let Some(issue_number) = task.issue_number.filter(|n| *n > 0) else { |
| 83 | return AfterPush::NoIssue; |
| 84 | }; |
| 85 | let issue_number = issue_number as u64; |
| 86 | if !token_configured(&ctx.config) { |
| 87 | tracing::info!( |
| 88 | "after_push: task {} links issue #{issue_number} but no github token is set; skipping comment", |
| 89 | task.id |
| 90 | ); |
| 91 | return AfterPush::NoToken; |
| 92 | } |
| 93 | let sha = task |
| 94 | .pushed_sha |
| 95 | .clone() |
| 96 | .or_else(|| task.commit_sha.clone()) |
| 97 | .unwrap_or_else(|| "(unknown sha)".to_string()); |
| 98 | let summary = task.summary.clone().unwrap_or_default(); |
| 99 | let body = after_push_comment(&task.title, &task.branch, &sha, &summary); |
| 100 | let gh = match github_client(&ctx.config) { |
| 101 | Ok(gh) => gh, |
| 102 | Err(e) => { |
| 103 | let message = format!("GitHub comment for issue #{issue_number} skipped: {e}"); |
| 104 | tracing::warn!("after_push task {}: {message}", task.id); |
| 105 | return AfterPush::Failed { message }; |
| 106 | } |
| 107 | }; |
| 108 | let comment_url = match gh.post_comment(issue_number, &body).await { |
| 109 | Ok(url) => url, |
| 110 | Err(e) => { |
| 111 | let message = format!("GitHub comment on issue #{issue_number} failed: {e}"); |
| 112 | tracing::warn!("after_push task {}: {message}", task.id); |
| 113 | return AfterPush::Failed { message }; |
| 114 | } |
| 115 | }; |
| 116 | if let Err(e) = gh.add_labels(issue_number, &[SOLVED_LABEL.to_string()]).await { |
| 117 | let message = format!( |
| 118 | "comment posted on issue #{issue_number} ({comment_url}) but adding label {SOLVED_LABEL:?} failed: {e}" |
| 119 | ); |
| 120 | tracing::warn!("after_push task {}: {message}", task.id); |
| 121 | return AfterPush::Failed { message }; |
| 122 | } |
| 123 | tracing::info!( |
| 124 | "after_push task {}: commented on issue #{issue_number} and added {SOLVED_LABEL:?}", |
| 125 | task.id |
| 126 | ); |
| 127 | AfterPush::Posted { comment_url } |
| 128 | } |
| 129 | |
| 130 | /// Prefill for the start-from-issue form: `(title, prompt, module_scope)`. |
| 131 | /// Form values win over issue-derived ones when the user typed them — the |
| 132 | /// caller implements that; this returns the issue-derived triple. |
| 133 | pub fn prefill_from_issue(issue: &Issue) -> (String, String, Option<String>) { |
| 134 | crate::github::task_from_issue(issue) |
| 135 | } |
| 136 | |
| 137 | #[cfg(test)] |
| 138 | mod tests { |
| 139 | use super::*; |
| 140 | use axum::response::IntoResponse as _; |
| 141 | use std::collections::HashMap; |
| 142 | use std::sync::{Arc, Mutex}; |
| 143 | |
| 144 | const ISSUE_903: &str = include_str!("testdata/github/issue_903.json"); |
| 145 | const COMMENTS_903: &str = include_str!("testdata/github/comments_903.json"); |
| 146 | |
| 147 | #[derive(Debug, Clone)] |
| 148 | struct Recorded { |
| 149 | method: String, |
| 150 | path: String, |
| 151 | body: Vec<u8>, |
| 152 | } |
| 153 | |
| 154 | #[derive(Clone, Default)] |
| 155 | struct Mock { |
| 156 | recorded: Arc<Mutex<Vec<Recorded>>>, |
| 157 | responses: Arc<Mutex<HashMap<String, String>>>, |
| 158 | /// When true, write endpoints (comment/label POSTs) return 500. |
| 159 | fail_writes: Arc<std::sync::atomic::AtomicBool>, |
| 160 | } |
| 161 | |
| 162 | impl Mock { |
| 163 | fn requests(&self) -> Vec<Recorded> { |
| 164 | self.recorded.lock().unwrap().clone() |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | async fn handler( |
| 169 | axum::extract::State(st): axum::extract::State<Mock>, |
| 170 | req: axum::http::Request<axum::body::Body>, |
| 171 | ) -> impl axum::response::IntoResponse { |
| 172 | use axum::http::StatusCode; |
| 173 | let (parts, body) = req.into_parts(); |
| 174 | let body = axum::body::to_bytes(body, 1024 * 1024).await.unwrap_or_default().to_vec(); |
| 175 | st.recorded.lock().unwrap().push(Recorded { |
| 176 | method: parts.method.to_string(), |
| 177 | path: parts.uri.path().to_string(), |
| 178 | body, |
| 179 | }); |
| 180 | let path = parts.uri.path().to_string(); |
| 181 | // Write endpoints take precedence over recorded GET fixtures sharing |
| 182 | // the same path (e.g. the comments list). |
| 183 | if parts.method == axum::http::Method::POST && path.ends_with("/comments") { |
| 184 | if st.fail_writes.load(std::sync::atomic::Ordering::SeqCst) { |
| 185 | return (StatusCode::INTERNAL_SERVER_ERROR, "mock write failure".to_string()) |
| 186 | .into_response(); |
| 187 | } |
| 188 | return ( |
| 189 | StatusCode::CREATED, |
| 190 | r#"{"html_url":"https://github.com/vayun-mathur/Modern-Apps/issues/903#issuecomment-9"}"#.to_string(), |
| 191 | ) |
| 192 | .into_response(); |
| 193 | } |
| 194 | if parts.method == axum::http::Method::POST && path.ends_with("/labels") { |
| 195 | if st.fail_writes.load(std::sync::atomic::Ordering::SeqCst) { |
| 196 | return (StatusCode::INTERNAL_SERVER_ERROR, "mock write failure".to_string()) |
| 197 | .into_response(); |
| 198 | } |
| 199 | return (StatusCode::OK, r#"[{"name":"solved for next release"}]"#.to_string()) |
| 200 | .into_response(); |
| 201 | } |
| 202 | if let Some(found) = st.responses.lock().unwrap().get(parts.uri.path()) { |
| 203 | return (StatusCode::OK, found.clone()).into_response(); |
| 204 | } |
| 205 | (StatusCode::NOT_FOUND, "no mock".to_string()).into_response() |
| 206 | } |
| 207 | |
| 208 | fn test_config(base: &str, token: Option<&str>) -> Config { |
| 209 | Config { |
| 210 | openrouter_api_key: "k".into(), |
| 211 | openrouter_base_url: "http://127.0.0.1:9".into(), |
| 212 | password_hash: "h".into(), |
| 213 | git_push_token: "g".into(), |
| 214 | repo_url: "r".into(), |
| 215 | public_origin: "o".into(), |
| 216 | default_model: "m".into(), |
| 217 | runner_url: "http://127.0.0.1:9".into(), |
| 218 | state_dir: std::path::PathBuf::from("/tmp"), |
| 219 | mirror_dir: std::path::PathBuf::from("/tmp"), |
| 220 | release_signal: std::path::PathBuf::from("/tmp/signal"), |
| 221 | listen: "127.0.0.1:0".into(), |
| 222 | slots: 1, |
| 223 | github_repo: "vayun-mathur/Modern-Apps".into(), |
| 224 | github_api_base: base.to_string(), |
| 225 | github_token: token.map(str::to_string), |
| 226 | test: Default::default(), |
| 227 | test_skip_release_wait: false, |
| 228 | triage_enabled: true, |
| 229 | triage_interval_secs: 120, |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | fn test_task(issue_number: Option<i64>) -> crate::models::Task { |
| 234 | crate::models::Task { |
| 235 | id: 7, |
| 236 | title: "Fix widgets".into(), |
| 237 | prompt: "p".into(), |
| 238 | module_scope: "weather".into(), |
| 239 | model: "m".into(), |
| 240 | kind: crate::models::TASK_KIND_TASK.to_string(), |
| 241 | status: crate::models::TaskStatus::Succeeded, |
| 242 | slot: None, |
| 243 | branch: "agent/7-fix-widgets".into(), |
| 244 | base_sha: None, |
| 245 | commit_sha: Some("abc123def456".into()), |
| 246 | pushed: true, |
| 247 | created_at: 0, |
| 248 | updated_at: 0, |
| 249 | started_at: None, |
| 250 | finished_at: None, |
| 251 | steps: 1, |
| 252 | prompt_tokens: 0, |
| 253 | completion_tokens: 0, |
| 254 | cost_usd: 0.0, |
| 255 | budget_steps: 60, |
| 256 | budget_usd: 2.0, |
| 257 | error: None, |
| 258 | summary: Some("Fixed the unit handling.".into()), |
| 259 | pending: None, |
| 260 | todos_json: None, |
| 261 | plan_md: None, |
| 262 | rules_json: None, |
| 263 | require_plan: false, |
| 264 | plan_approved: false, |
| 265 | wip_sha: None, |
| 266 | pushed_sha: Some("abc123def456789".into()), |
| 267 | final_diff: None, |
| 268 | commit_message: None, |
| 269 | issue_number, |
| 270 | stop_requested: false, |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | fn test_ctx(config: Config) -> crate::agent::DriverCtx { |
| 275 | let dir = tempfile::tempdir().unwrap(); |
| 276 | let store = crate::store::Store::open(dir.path()).unwrap(); |
| 277 | // Keep the tempdir alive for the ctx lifetime in these tests by |
| 278 | // leaking: the store holds an open sqlite file, not the path. |
| 279 | std::mem::forget(dir); |
| 280 | let (events_tx, _) = tokio::sync::broadcast::channel(8); |
| 281 | crate::agent::DriverCtx { |
| 282 | config: Arc::new(config), |
| 283 | store, |
| 284 | runner: crate::runner::Runner::new("http://127.0.0.1:9".into()), |
| 285 | openrouter: crate::openrouter::OpenRouter::new( |
| 286 | "http://127.0.0.1:9".into(), |
| 287 | "k".into(), |
| 288 | ), |
| 289 | events_tx, |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | async fn spawn_mock() -> (String, Mock) { |
| 294 | let mock = Mock::default(); |
| 295 | mock.responses.lock().unwrap().insert( |
| 296 | "/repos/vayun-mathur/Modern-Apps/issues/903".into(), |
| 297 | ISSUE_903.to_string(), |
| 298 | ); |
| 299 | mock.responses.lock().unwrap().insert( |
| 300 | "/repos/vayun-mathur/Modern-Apps/issues/903/comments".into(), |
| 301 | COMMENTS_903.to_string(), |
| 302 | ); |
| 303 | let app = axum::Router::new().fallback(handler).with_state(mock.clone()); |
| 304 | let lis = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 305 | let addr = lis.local_addr().unwrap(); |
| 306 | tokio::spawn(async move { axum::serve(lis, app).await.unwrap() }); |
| 307 | (format!("http://{addr}"), mock) |
| 308 | } |
| 309 | |
| 310 | #[test] |
| 311 | fn comment_body_marks_agent_summary_branch_sha_and_link() { |
| 312 | let body = after_push_comment("Fix widgets", "agent/7-fix-widgets", "abc123def456789", "Fixed units."); |
| 313 | assert!(body.contains("agent/7-fix-widgets"), "{body}"); |
| 314 | assert!(body.contains("abc123def456"), "{body}"); |
| 315 | assert!(body.contains("https://git.maproj.org/Modern-Apps.git"), "{body}"); |
| 316 | assert!(body.contains("Fixed units."), "{body}"); |
| 317 | assert!(body.contains("agent"), "{body}"); |
| 318 | } |
| 319 | |
| 320 | #[tokio::test] |
| 321 | async fn after_push_posts_comment_and_label() { |
| 322 | let (base, mock) = spawn_mock().await; |
| 323 | let ctx = test_ctx(test_config(&base, Some("tok"))); |
| 324 | let out = after_push(&ctx, &test_task(Some(903))).await; |
| 325 | let url = match out { |
| 326 | AfterPush::Posted { comment_url } => comment_url, |
| 327 | other => panic!("expected Posted, got {other:?}"), |
| 328 | }; |
| 329 | assert!(url.contains("issuecomment"), "{url}"); |
| 330 | let reqs = mock.requests(); |
| 331 | let comment = reqs |
| 332 | .iter() |
| 333 | .find(|r| r.method == "POST" && r.path.ends_with("/issues/903/comments")) |
| 334 | .expect("comment POST"); |
| 335 | let v: serde_json::Value = serde_json::from_slice(&comment.body).unwrap(); |
| 336 | let text = v.get("body").and_then(|b| b.as_str()).unwrap_or(""); |
| 337 | assert!(text.contains("agent/7-fix-widgets"), "{text}"); |
| 338 | assert!(text.contains("abc123def456"), "{text}"); |
| 339 | assert!(text.contains("Fixed the unit handling."), "{text}"); |
| 340 | let labels = reqs |
| 341 | .iter() |
| 342 | .find(|r| r.method == "POST" && r.path.ends_with("/issues/903/labels")) |
| 343 | .expect("labels POST"); |
| 344 | let v: serde_json::Value = serde_json::from_slice(&labels.body).unwrap(); |
| 345 | assert_eq!(v, serde_json::json!({"labels": ["solved for next release"]})); |
| 346 | } |
| 347 | |
| 348 | #[tokio::test] |
| 349 | async fn after_push_noops_without_token_and_without_issue() { |
| 350 | let (base, mock) = spawn_mock().await; |
| 351 | // No token: no HTTP at all. |
| 352 | let ctx = test_ctx(test_config(&base, None)); |
| 353 | assert!(matches!(after_push(&ctx, &test_task(Some(903))).await, AfterPush::NoToken)); |
| 354 | assert!(mock.requests().is_empty(), "no requests without token"); |
| 355 | // No linked issue: nothing to do (even with a token). |
| 356 | let ctx = test_ctx(test_config(&base, Some("tok"))); |
| 357 | assert!(matches!(after_push(&ctx, &test_task(None)).await, AfterPush::NoIssue)); |
| 358 | assert!(mock.requests().is_empty(), "no requests without issue"); |
| 359 | } |
| 360 | |
| 361 | #[tokio::test] |
| 362 | async fn after_push_failure_is_surfaced_not_raised() { |
| 363 | let (base, mock) = spawn_mock().await; |
| 364 | mock.fail_writes.store(true, std::sync::atomic::Ordering::SeqCst); |
| 365 | let ctx = test_ctx(test_config(&base, Some("tok"))); |
| 366 | match after_push(&ctx, &test_task(Some(903))).await { |
| 367 | AfterPush::Failed { message } => assert!(message.contains("#903"), "{message}"), |
| 368 | other => panic!("expected Failed, got {other:?}"), |
| 369 | } |
| 370 | } |
| 371 | } |