Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / infra / agents / agentd / src / github.rs
github.rs1683 lines · 57.1 KiBRaw
| 1 | #![allow(dead_code)] |
| 2 | //! Minimal GitHub REST client for agentd's issue tools. |
| 3 | //! |
| 4 | //! Covers exactly what the orchestrator needs: searching issues, |
| 5 | //! reading one issue with its comments, posting a comment, and adding |
| 6 | //! labels (the last two need `AGENTD_GITHUB_TOKEN`). The base URL defaults |
| 7 | //! to `https://api.github.com` and is overridable so tests can point at a |
| 8 | //! local mock server. |
| 9 | //! |
| 10 | //! Pure helpers ([`app_module_for_labels`], [`render_issue_for_model`], |
| 11 | //! [`render_search_for_model`], [`task_from_issue`]) shape GitHub data for |
| 12 | //! the model and the scheduler. |
| 13 | |
| 14 | use std::time::Duration; |
| 15 | |
| 16 | use serde::{Deserialize, Serialize}; |
| 17 | |
| 18 | /// Default API root; override per client for tests. |
| 19 | pub const DEFAULT_BASE_URL: &str = "https://api.github.com"; |
| 20 | /// Pinned GitHub API version sent on every request. |
| 21 | pub const API_VERSION: &str = "2022-11-28"; |
| 22 | /// `User-Agent` sent on every request. |
| 23 | pub const USER_AGENT: &str = "agentd"; |
| 24 | /// Label agentd adds after a user-approved successful push. |
| 25 | pub const SOLVED_LABEL: &str = "solved for next release"; |
| 26 | /// Total budget in bytes for an issue body plus its comment bodies. |
| 27 | pub const BODY_BUDGET_BYTES: usize = 12 * 1024; |
| 28 | /// Comment pages (`per_page=100`) followed when reading an issue. |
| 29 | pub const MAX_COMMENT_PAGES: u32 = 3; |
| 30 | /// `per_page` used when listing comments. |
| 31 | pub const COMMENTS_PER_PAGE: u32 = 100; |
| 32 | |
| 33 | /// Errors from the GitHub client. |
| 34 | #[derive(Debug)] |
| 35 | pub enum Error { |
| 36 | /// A write call (`post_comment`, `add_labels`) without a token. |
| 37 | NoToken(&'static str), |
| 38 | /// Transport failure (connect, timeout, bad body, ...). |
| 39 | Transport(reqwest::Error), |
| 40 | /// Non-success status that is not a rate limit. |
| 41 | Api { status: u16, message: String }, |
| 42 | /// HTTP 429, or HTTP 403 with `x-ratelimit-remaining: 0`. |
| 43 | RateLimited { status: u16, reset: Option<String> }, |
| 44 | } |
| 45 | |
| 46 | impl std::fmt::Display for Error { |
| 47 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 48 | match self { |
| 49 | Error::NoToken(op) => { |
| 50 | write!(f, "GitHub token required for {op} (set AGENTD_GITHUB_TOKEN)") |
| 51 | } |
| 52 | Error::Transport(e) => write!(f, "GitHub request failed: {e}"), |
| 53 | Error::Api { status, message } => { |
| 54 | write!(f, "GitHub API error (HTTP {status}): {message}") |
| 55 | } |
| 56 | Error::RateLimited { status, reset } => write!( |
| 57 | f, |
| 58 | "GitHub rate limit exceeded (HTTP {status}); resets at {}", |
| 59 | reset.as_deref().unwrap_or("unknown") |
| 60 | ), |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | impl std::error::Error for Error {} |
| 66 | |
| 67 | /// Which issues a search/list call includes. |
| 68 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 69 | pub enum IssueState { |
| 70 | Open, |
| 71 | Closed, |
| 72 | All, |
| 73 | } |
| 74 | |
| 75 | impl IssueState { |
| 76 | /// Lowercase value the GitHub API expects. |
| 77 | pub fn as_str(self) -> &'static str { |
| 78 | match self { |
| 79 | IssueState::Open => "open", |
| 80 | IssueState::Closed => "closed", |
| 81 | IssueState::All => "all", |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// One row from a search or list call. |
| 87 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 88 | pub struct IssueSummary { |
| 89 | pub number: u64, |
| 90 | pub title: String, |
| 91 | pub state: String, |
| 92 | pub labels: Vec<String>, |
| 93 | pub comments: u64, |
| 94 | pub created_at: String, |
| 95 | pub updated_at: String, |
| 96 | pub is_pr: bool, |
| 97 | } |
| 98 | |
| 99 | /// A single issue comment. |
| 100 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 101 | pub struct Comment { |
| 102 | pub author: String, |
| 103 | pub created_at: String, |
| 104 | pub body: String, |
| 105 | } |
| 106 | |
| 107 | /// A full issue with comments. `body` plus `comments` fit in |
| 108 | /// [`BODY_BUDGET_BYTES`]; `truncated` is set when anything was cut. |
| 109 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 110 | pub struct Issue { |
| 111 | pub number: u64, |
| 112 | pub title: String, |
| 113 | pub state: String, |
| 114 | pub labels: Vec<String>, |
| 115 | pub body: String, |
| 116 | pub author: String, |
| 117 | pub created_at: String, |
| 118 | pub comments: Vec<Comment>, |
| 119 | pub truncated: bool, |
| 120 | } |
| 121 | |
| 122 | #[derive(Debug, Clone, Deserialize)] |
| 123 | struct ApiLabel { |
| 124 | #[serde(default)] |
| 125 | name: String, |
| 126 | } |
| 127 | |
| 128 | #[derive(Debug, Clone, Deserialize)] |
| 129 | struct ApiUser { |
| 130 | #[serde(default)] |
| 131 | login: String, |
| 132 | } |
| 133 | |
| 134 | /// Subset of the issue object agentd reads. Everything defaults so a |
| 135 | /// minimal mock (or a future API field change) still parses. |
| 136 | #[derive(Debug, Clone, Deserialize)] |
| 137 | struct ApiIssue { |
| 138 | #[serde(default)] |
| 139 | number: u64, |
| 140 | #[serde(default)] |
| 141 | title: String, |
| 142 | #[serde(default)] |
| 143 | state: String, |
| 144 | #[serde(default)] |
| 145 | labels: Vec<ApiLabel>, |
| 146 | #[serde(default)] |
| 147 | body: Option<String>, |
| 148 | #[serde(default)] |
| 149 | user: Option<ApiUser>, |
| 150 | #[serde(default)] |
| 151 | created_at: String, |
| 152 | #[serde(default)] |
| 153 | updated_at: String, |
| 154 | #[serde(default)] |
| 155 | comments: u64, |
| 156 | #[serde(default)] |
| 157 | pull_request: Option<serde_json::Value>, |
| 158 | } |
| 159 | |
| 160 | impl ApiIssue { |
| 161 | fn is_pr(&self) -> bool { |
| 162 | self.pull_request.is_some() |
| 163 | } |
| 164 | |
| 165 | fn label_names(&self) -> Vec<String> { |
| 166 | self.labels.iter().map(|l| l.name.clone()).collect() |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | #[derive(Debug, Clone, Deserialize)] |
| 171 | struct ApiComment { |
| 172 | #[serde(default)] |
| 173 | user: Option<ApiUser>, |
| 174 | #[serde(default)] |
| 175 | created_at: String, |
| 176 | #[serde(default)] |
| 177 | body: Option<String>, |
| 178 | } |
| 179 | |
| 180 | impl From<ApiComment> for Comment { |
| 181 | fn from(c: ApiComment) -> Comment { |
| 182 | Comment { |
| 183 | author: c.user.map(|u| u.login).unwrap_or_default(), |
| 184 | created_at: c.created_at, |
| 185 | body: c.body.unwrap_or_default(), |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | #[derive(Debug, Clone, Deserialize)] |
| 191 | struct SearchResponse { |
| 192 | #[serde(default)] |
| 193 | items: Vec<ApiIssue>, |
| 194 | } |
| 195 | |
| 196 | #[derive(Debug, Clone, Deserialize)] |
| 197 | struct ApiErrorBody { |
| 198 | #[serde(default)] |
| 199 | message: String, |
| 200 | } |
| 201 | |
| 202 | #[derive(Debug, Clone, Deserialize)] |
| 203 | struct PostedComment { |
| 204 | #[serde(default)] |
| 205 | html_url: String, |
| 206 | } |
| 207 | |
| 208 | /// GitHub API client scoped to one `owner/name` repo. |
| 209 | #[derive(Clone)] |
| 210 | pub struct GitHub { |
| 211 | base_url: String, |
| 212 | repo: String, |
| 213 | token: Option<String>, |
| 214 | http: reqwest::Client, |
| 215 | } |
| 216 | |
| 217 | impl GitHub { |
| 218 | /// Client against `https://api.github.com`. |
| 219 | pub fn new(repo: impl Into<String>, token: Option<String>) -> Result<GitHub, Error> { |
| 220 | GitHub::with_base_url(DEFAULT_BASE_URL, repo, token) |
| 221 | } |
| 222 | |
| 223 | /// Client against an explicit API root (tests point at a mock server). |
| 224 | pub fn with_base_url( |
| 225 | base_url: impl Into<String>, |
| 226 | repo: impl Into<String>, |
| 227 | token: Option<String>, |
| 228 | ) -> Result<GitHub, Error> { |
| 229 | let http = reqwest::Client::builder() |
| 230 | .connect_timeout(Duration::from_secs(10)) |
| 231 | .timeout(Duration::from_secs(30)) |
| 232 | .no_proxy() |
| 233 | .build() |
| 234 | .map_err(Error::Transport)?; |
| 235 | Ok(GitHub { |
| 236 | base_url: base_url.into().trim_end_matches('/').to_string(), |
| 237 | repo: repo.into(), |
| 238 | token, |
| 239 | http, |
| 240 | }) |
| 241 | } |
| 242 | |
| 243 | /// Client for `repo` with the token from `AGENTD_GITHUB_TOKEN` (if set). |
| 244 | pub fn new_from_env(repo: impl Into<String>) -> Result<GitHub, Error> { |
| 245 | let token = std::env::var("AGENTD_GITHUB_TOKEN") |
| 246 | .ok() |
| 247 | .filter(|t| !t.trim().is_empty()); |
| 248 | GitHub::new(repo, token) |
| 249 | } |
| 250 | |
| 251 | fn request(&self, method: reqwest::Method, path: &str) -> reqwest::RequestBuilder { |
| 252 | // Pagination `Link` headers are absolute URLs. Only follow ones on our |
| 253 | // API base so the bearer token can never be sent to another host. |
| 254 | let url = if path.starts_with("http") { |
| 255 | if path.starts_with(&format!("{}/", self.base_url)) { |
| 256 | path.to_string() |
| 257 | } else { |
| 258 | format!("{}/invalid-pagination-link", self.base_url) |
| 259 | } |
| 260 | } else { |
| 261 | format!("{}{path}", self.base_url) |
| 262 | }; |
| 263 | let mut req = self |
| 264 | .http |
| 265 | .request(method, url) |
| 266 | .header(reqwest::header::USER_AGENT, USER_AGENT) |
| 267 | .header(reqwest::header::ACCEPT, "application/vnd.github+json") |
| 268 | .header("X-GitHub-Api-Version", API_VERSION); |
| 269 | if let Some(token) = &self.token { |
| 270 | req = req.header( |
| 271 | reqwest::header::AUTHORIZATION, |
| 272 | format!("Bearer {token}"), |
| 273 | ); |
| 274 | } |
| 275 | req |
| 276 | } |
| 277 | |
| 278 | /// Send a request, mapping rate limits and API errors. |
| 279 | async fn send(&self, req: reqwest::RequestBuilder) -> Result<reqwest::Response, Error> { |
| 280 | let resp = req.send().await.map_err(Error::Transport)?; |
| 281 | let status = resp.status(); |
| 282 | let rate_limited = status.as_u16() == 429 |
| 283 | || (status.as_u16() == 403 |
| 284 | && matches!( |
| 285 | resp.headers() |
| 286 | .get("x-ratelimit-remaining") |
| 287 | .and_then(|v| v.to_str().ok()), |
| 288 | Some("0") |
| 289 | )); |
| 290 | if rate_limited { |
| 291 | let reset = resp |
| 292 | .headers() |
| 293 | .get("x-ratelimit-reset") |
| 294 | .and_then(|v| v.to_str().ok()) |
| 295 | .map(str::to_string); |
| 296 | return Err(Error::RateLimited { |
| 297 | status: status.as_u16(), |
| 298 | reset, |
| 299 | }); |
| 300 | } |
| 301 | if !status.is_success() { |
| 302 | let message = resp |
| 303 | .json::<ApiErrorBody>() |
| 304 | .await |
| 305 | .map(|e| e.message) |
| 306 | .unwrap_or_else(|_| format!("HTTP {status}")); |
| 307 | return Err(Error::Api { |
| 308 | status: status.as_u16(), |
| 309 | message, |
| 310 | }); |
| 311 | } |
| 312 | Ok(resp) |
| 313 | } |
| 314 | |
| 315 | /// Search issues. With `query` the Search API is used |
| 316 | /// (`q=repo:<repo> is:issue ...`, labels folded in as `label:".."`), |
| 317 | /// otherwise the list endpoint with a `labels` filter. Pull requests |
| 318 | /// are always excluded. |
| 319 | pub async fn search_issues( |
| 320 | &self, |
| 321 | query: Option<&str>, |
| 322 | labels: &[String], |
| 323 | state: IssueState, |
| 324 | limit: u32, |
| 325 | ) -> Result<Vec<IssueSummary>, Error> { |
| 326 | let per_page = limit.clamp(1, 100); |
| 327 | if let Some(query) = query { |
| 328 | let mut q = format!("repo:{} is:issue {query}", self.repo); |
| 329 | match state { |
| 330 | IssueState::Open => q.push_str(" state:open"), |
| 331 | IssueState::Closed => q.push_str(" state:closed"), |
| 332 | IssueState::All => {} |
| 333 | } |
| 334 | for label in labels { |
| 335 | q.push_str(&format!(" label:\"{label}\"")); |
| 336 | } |
| 337 | let resp = self |
| 338 | .send(self.request(reqwest::Method::GET, "/search/issues").query(&[ |
| 339 | ("q", q), |
| 340 | ("per_page", per_page.to_string()), |
| 341 | ])) |
| 342 | .await?; |
| 343 | let found: SearchResponse = resp.json().await.map_err(Error::Transport)?; |
| 344 | Ok(found |
| 345 | .items |
| 346 | .into_iter() |
| 347 | .filter(|i| !i.is_pr()) |
| 348 | .map(summary_from) |
| 349 | .collect()) |
| 350 | } else { |
| 351 | let mut params: Vec<(&str, String)> = vec![ |
| 352 | ("state", state.as_str().to_string()), |
| 353 | ("per_page", per_page.to_string()), |
| 354 | ("sort", "updated".to_string()), |
| 355 | ("direction", "desc".to_string()), |
| 356 | ]; |
| 357 | if !labels.is_empty() { |
| 358 | params.push(("labels", labels.join(","))); |
| 359 | } |
| 360 | let path = format!("/repos/{}/issues", self.repo); |
| 361 | let resp = self |
| 362 | .send(self.request(reqwest::Method::GET, &path).query(¶ms)) |
| 363 | .await?; |
| 364 | let found: Vec<ApiIssue> = resp.json().await.map_err(Error::Transport)?; |
| 365 | Ok(found |
| 366 | .into_iter() |
| 367 | .filter(|i| !i.is_pr()) |
| 368 | .map(summary_from) |
| 369 | .collect()) |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | /// Read one issue with its comments (paginated, up to |
| 374 | /// [`MAX_COMMENT_PAGES`] pages). Body plus comments are capped at |
| 375 | /// [`BODY_BUDGET_BYTES`] total; `truncated` notes when anything was cut. |
| 376 | pub async fn read_issue(&self, number: u64) -> Result<Issue, Error> { |
| 377 | let path = format!("/repos/{}/issues/{number}", self.repo); |
| 378 | let resp = self |
| 379 | .send(self.request(reqwest::Method::GET, &path)) |
| 380 | .await?; |
| 381 | let raw: ApiIssue = resp.json().await.map_err(Error::Transport)?; |
| 382 | |
| 383 | let mut comments = Vec::new(); |
| 384 | let mut next: Option<String> = Some(format!( |
| 385 | "/repos/{}/issues/{number}/comments?per_page={COMMENTS_PER_PAGE}", |
| 386 | self.repo |
| 387 | )); |
| 388 | let mut pages: u32 = 0; |
| 389 | let mut more_available = false; |
| 390 | while let Some(url) = next.take() { |
| 391 | if pages >= MAX_COMMENT_PAGES { |
| 392 | more_available = true; |
| 393 | break; |
| 394 | } |
| 395 | pages += 1; |
| 396 | let resp = self.send(self.request(reqwest::Method::GET, &url)).await?; |
| 397 | // Presence of a `rel="next"` link governs paging (a short last |
| 398 | // page still carries none); the page cap above bounds runaway |
| 399 | // `Link` headers. |
| 400 | next = next_link(resp.headers()) |
| 401 | .filter(|u| u.starts_with(&format!("{}/", self.base_url))); |
| 402 | let batch: Vec<ApiComment> = resp.json().await.map_err(Error::Transport)?; |
| 403 | comments.extend(batch.into_iter().map(Comment::from)); |
| 404 | } |
| 405 | |
| 406 | let labels = raw.label_names(); |
| 407 | let (body, comments, mut truncated) = |
| 408 | apply_budget(raw.body.unwrap_or_default(), comments); |
| 409 | if more_available { |
| 410 | truncated = true; |
| 411 | } |
| 412 | Ok(Issue { |
| 413 | number: raw.number, |
| 414 | title: raw.title, |
| 415 | state: raw.state, |
| 416 | labels, |
| 417 | body, |
| 418 | author: raw.user.map(|u| u.login).unwrap_or_default(), |
| 419 | created_at: raw.created_at, |
| 420 | comments, |
| 421 | truncated, |
| 422 | }) |
| 423 | } |
| 424 | |
| 425 | /// Post a comment; returns the comment's HTML URL. Needs a token. |
| 426 | pub async fn post_comment(&self, number: u64, body: &str) -> Result<String, Error> { |
| 427 | if self.token.is_none() { |
| 428 | return Err(Error::NoToken("post_comment")); |
| 429 | } |
| 430 | let path = format!("/repos/{}/issues/{number}/comments", self.repo); |
| 431 | let resp = self |
| 432 | .send( |
| 433 | self.request(reqwest::Method::POST, &path) |
| 434 | .json(&serde_json::json!({ "body": body })), |
| 435 | ) |
| 436 | .await?; |
| 437 | let posted: PostedComment = resp.json().await.map_err(Error::Transport)?; |
| 438 | if posted.html_url.is_empty() { |
| 439 | return Err(Error::Api { |
| 440 | status: 200, |
| 441 | message: "comment response carried no html_url".to_string(), |
| 442 | }); |
| 443 | } |
| 444 | Ok(posted.html_url) |
| 445 | } |
| 446 | |
| 447 | /// Add labels to an issue. Needs a token. |
| 448 | pub async fn add_labels(&self, number: u64, labels: &[String]) -> Result<(), Error> { |
| 449 | if self.token.is_none() { |
| 450 | return Err(Error::NoToken("add_labels")); |
| 451 | } |
| 452 | let path = format!("/repos/{}/issues/{number}/labels", self.repo); |
| 453 | self.send( |
| 454 | self.request(reqwest::Method::POST, &path) |
| 455 | .json(&serde_json::json!({ "labels": labels })), |
| 456 | ) |
| 457 | .await?; |
| 458 | Ok(()) |
| 459 | } |
| 460 | |
| 461 | /// Whether a token is configured (write calls need one). |
| 462 | pub fn has_token(&self) -> bool { |
| 463 | self.token.as_ref().is_some_and(|t| !t.trim().is_empty()) |
| 464 | } |
| 465 | |
| 466 | /// Remove one label from an issue. Needs a token. A 404 means the label |
| 467 | /// (or issue) is already gone, so it succeeds. |
| 468 | pub async fn remove_label(&self, number: u64, name: &str) -> Result<(), Error> { |
| 469 | if !self.has_token() { |
| 470 | return Err(Error::NoToken("remove_label")); |
| 471 | } |
| 472 | let path = format!( |
| 473 | "/repos/{}/issues/{number}/labels/{}", |
| 474 | self.repo, |
| 475 | percent_encode_label(name) |
| 476 | ); |
| 477 | let resp = self.send(self.request(reqwest::Method::DELETE, &path)).await; |
| 478 | match resp { |
| 479 | Err(Error::Api { status: 404, .. }) => Ok(()), |
| 480 | other => other.map(|_| ()), |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | /// List recent issues created after `created_after` (RFC3339 UTC), oldest |
| 485 | /// first. PRs are excluded. The list endpoint returns |
| 486 | /// `state=all&sort=created&direction=asc`; `created_at > created_after` |
| 487 | /// filters server-ascending output (RFC3339 `Z` strings compare |
| 488 | /// lexicographically once normalized). |
| 489 | pub async fn list_issues_since( |
| 490 | &self, |
| 491 | created_after: &str, |
| 492 | limit: u32, |
| 493 | ) -> Result<Vec<IssueSummary>, Error> { |
| 494 | let per_page = limit.clamp(1, 100); |
| 495 | let path = format!("/repos/{}/issues", self.repo); |
| 496 | let resp = self |
| 497 | .send(self.request(reqwest::Method::GET, &path).query(&[ |
| 498 | ("state", "all".to_string()), |
| 499 | ("sort", "created".to_string()), |
| 500 | ("direction", "asc".to_string()), |
| 501 | ("per_page", per_page.to_string()), |
| 502 | ])) |
| 503 | .await?; |
| 504 | let found: Vec<ApiIssue> = resp.json().await.map_err(Error::Transport)?; |
| 505 | let after = normalize_rfc3339(created_after); |
| 506 | Ok(found |
| 507 | .into_iter() |
| 508 | .filter(|i| !i.is_pr()) |
| 509 | .map(summary_from) |
| 510 | .filter(|s| normalize_rfc3339(&s.created_at) > after) |
| 511 | .collect()) |
| 512 | } |
| 513 | |
| 514 | /// Whether any comment on the issue contains `marker` (paginated like |
| 515 | /// [`GitHub::read_issue`]). Read-only: works without a token. |
| 516 | pub async fn issue_has_marker(&self, number: u64, marker: &str) -> Result<bool, Error> { |
| 517 | let mut next: Option<String> = Some(format!( |
| 518 | "/repos/{}/issues/{number}/comments?per_page={COMMENTS_PER_PAGE}", |
| 519 | self.repo |
| 520 | )); |
| 521 | let mut pages: u32 = 0; |
| 522 | while let Some(url) = next.take() { |
| 523 | if pages >= MAX_COMMENT_PAGES { |
| 524 | break; |
| 525 | } |
| 526 | pages += 1; |
| 527 | let resp = self.send(self.request(reqwest::Method::GET, &url)).await?; |
| 528 | next = next_link(resp.headers()) |
| 529 | .filter(|u| u.starts_with(&format!("{}/", self.base_url))); |
| 530 | let batch: Vec<ApiComment> = resp.json().await.map_err(Error::Transport)?; |
| 531 | if batch |
| 532 | .iter() |
| 533 | .any(|c| c.body.as_deref().unwrap_or_default().contains(marker)) |
| 534 | { |
| 535 | return Ok(true); |
| 536 | } |
| 537 | } |
| 538 | Ok(false) |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | /// Percent-encode a label name for the `DELETE .../labels/{name}` path |
| 543 | /// segment (RFC 3986 unreserved set passes through; everything else, |
| 544 | /// including `/` and spaces, is `%XX` uppercase hex). |
| 545 | pub fn percent_encode_label(name: &str) -> String { |
| 546 | const UNRESERVED: &[u8] = |
| 547 | b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"; |
| 548 | let mut out = String::with_capacity(name.len()); |
| 549 | for b in name.bytes() { |
| 550 | if UNRESERVED.contains(&b) { |
| 551 | out.push(b as char); |
| 552 | } else { |
| 553 | out.push_str(&format!("%{b:02X}")); |
| 554 | } |
| 555 | } |
| 556 | out |
| 557 | } |
| 558 | |
| 559 | /// Normalize an RFC3339 timestamp to canonical `Z` UTC form so lexicographic |
| 560 | /// comparison equals chronological order. Non-`Z` offsets are rare from this |
| 561 | /// API (it returns `Z`); anything unparseable is returned unchanged. |
| 562 | /// |
| 563 | /// Handles `+00:00` → `Z` and fractional seconds. |
| 564 | pub fn normalize_rfc3339(s: &str) -> String { |
| 565 | let s = s.trim(); |
| 566 | if let Some(base) = s.strip_suffix('Z') { |
| 567 | return format!("{base}Z"); |
| 568 | } |
| 569 | if let Some(base) = s.strip_suffix("+00:00") { |
| 570 | return format!("{base}Z"); |
| 571 | } |
| 572 | s.to_string() |
| 573 | } |
| 574 | |
| 575 | /// Every label the issue labeler treats as an app name (mirrors |
| 576 | /// [`app_module_for_label`]). Triage passes these as the app-label universe |
| 577 | /// for [`crate::triage::plan_label_changes`]. |
| 578 | pub const ALL_APP_LABELS: &[&str] = &[ |
| 579 | "appstore", |
| 580 | "arrows", |
| 581 | "astronomy", |
| 582 | "auto", |
| 583 | "backup", |
| 584 | "calculator", |
| 585 | "calendar", |
| 586 | "camera", |
| 587 | "cast", |
| 588 | "chess", |
| 589 | "clock", |
| 590 | "code", |
| 591 | "communicate", |
| 592 | "contacts", |
| 593 | "education", |
| 594 | "email", |
| 595 | "emergency", |
| 596 | "euicc", |
| 597 | "everysync", |
| 598 | "files", |
| 599 | "findfamily", |
| 600 | "flashcards", |
| 601 | "fooddelivery", |
| 602 | "globalesim", |
| 603 | "health", |
| 604 | "hub", |
| 605 | "kart", |
| 606 | "keyboard", |
| 607 | "launcher", |
| 608 | "logicgate", |
| 609 | "logviewer", |
| 610 | "maps", |
| 611 | "measure", |
| 612 | "minesweeper", |
| 613 | "music", |
| 614 | "networklocation", |
| 615 | "nonogram", |
| 616 | "notes", |
| 617 | "office", |
| 618 | "openassistant", |
| 619 | "parentalcontrols", |
| 620 | "passwords", |
| 621 | "pdf", |
| 622 | "photos", |
| 623 | "pipes", |
| 624 | "screentime", |
| 625 | "securemail", |
| 626 | "setupwizard", |
| 627 | "share", |
| 628 | "shop", |
| 629 | "solitaire", |
| 630 | "speech", |
| 631 | "sudoku", |
| 632 | "taxi", |
| 633 | "things", |
| 634 | "todo", |
| 635 | "translate", |
| 636 | "travel", |
| 637 | "tuner", |
| 638 | "unblockjam", |
| 639 | "uniflix", |
| 640 | "updater", |
| 641 | "voxels", |
| 642 | "vpn", |
| 643 | "watch", |
| 644 | "weather", |
| 645 | "web", |
| 646 | "wordmaker", |
| 647 | "youpipe", |
| 648 | ]; |
| 649 | |
| 650 | fn summary_from(i: ApiIssue) -> IssueSummary { |
| 651 | let labels = i.label_names(); |
| 652 | let is_pr = i.is_pr(); |
| 653 | IssueSummary { |
| 654 | number: i.number, |
| 655 | title: i.title, |
| 656 | state: i.state, |
| 657 | labels, |
| 658 | comments: i.comments, |
| 659 | created_at: i.created_at, |
| 660 | updated_at: i.updated_at, |
| 661 | is_pr, |
| 662 | } |
| 663 | } |
| 664 | |
| 665 | /// Extract the `rel="next"` URL from a GitHub `Link` header, if present. |
| 666 | fn next_link(headers: &reqwest::header::HeaderMap) -> Option<String> { |
| 667 | let link = headers.get(reqwest::header::LINK)?.to_str().ok()?; |
| 668 | for part in link.split(',') { |
| 669 | let mut halves = part.splitn(2, ';'); |
| 670 | let url = halves.next()?.trim(); |
| 671 | let params = halves.next().unwrap_or("").trim(); |
| 672 | if params.contains("rel=\"next\"") { |
| 673 | let url = url.strip_prefix('<')?.strip_suffix('>')?; |
| 674 | return Some(url.to_string()); |
| 675 | } |
| 676 | } |
| 677 | None |
| 678 | } |
| 679 | |
| 680 | const TRUNC_MARKER: &str = "\n[…truncated]"; |
| 681 | |
| 682 | /// Cut `s` to at most `max_bytes` (char boundary), noting the cut. |
| 683 | fn truncate_text(s: &str, max_bytes: usize) -> String { |
| 684 | if s.len() <= max_bytes { |
| 685 | return s.to_string(); |
| 686 | } |
| 687 | let mut end = max_bytes.saturating_sub(TRUNC_MARKER.len()); |
| 688 | while end > 0 && !s.is_char_boundary(end) { |
| 689 | end -= 1; |
| 690 | } |
| 691 | format!("{}{TRUNC_MARKER}", &s[..end]) |
| 692 | } |
| 693 | |
| 694 | /// Fit an issue body plus comments into [`BODY_BUDGET_BYTES`]. The body wins; |
| 695 | /// comments fill the rest in order, the last one fragmented if it partly |
| 696 | /// fits. Returns `(body, comments, truncated)`. |
| 697 | fn apply_budget(body: String, comments: Vec<Comment>) -> (String, Vec<Comment>, bool) { |
| 698 | if body.len() > BODY_BUDGET_BYTES { |
| 699 | return (truncate_text(&body, BODY_BUDGET_BYTES), Vec::new(), true); |
| 700 | } |
| 701 | let mut kept = Vec::with_capacity(comments.len()); |
| 702 | let mut remaining = BODY_BUDGET_BYTES - body.len(); |
| 703 | let mut truncated = false; |
| 704 | for c in comments { |
| 705 | if c.body.len() <= remaining { |
| 706 | remaining -= c.body.len(); |
| 707 | kept.push(c); |
| 708 | } else { |
| 709 | if remaining > 0 { |
| 710 | kept.push(Comment { |
| 711 | body: truncate_text(&c.body, remaining), |
| 712 | ..c |
| 713 | }); |
| 714 | } |
| 715 | truncated = true; |
| 716 | break; |
| 717 | } |
| 718 | } |
| 719 | (body, kept, truncated) |
| 720 | } |
| 721 | |
| 722 | /// Map an issue-labeler app name to its repo module dir. |
| 723 | /// |
| 724 | /// Derived from the `validApps` list in |
| 725 | /// `.github/workflows/issue_labeler.yml`: most app names equal the top-level |
| 726 | /// dir (`weather` → `weather`); games live under `games/` (`chess` → |
| 727 | /// `games/chess`). Names with no module dir (`watch`) map to `None`, as do |
| 728 | /// non-app labels (`bug`, `enhancement`, versions). |
| 729 | fn app_module_for_label(label: &str) -> Option<String> { |
| 730 | let label = label.trim().to_lowercase(); |
| 731 | let module = match label.as_str() { |
| 732 | "arrows" | "chess" | "hub" | "kart" | "logicgate" | "minesweeper" | "nonogram" |
| 733 | | "pipes" | "solitaire" | "sudoku" | "unblockjam" | "voxels" | "wordmaker" => { |
| 734 | format!("games/{label}") |
| 735 | } |
| 736 | "appstore" | "astronomy" | "auto" | "backup" | "calculator" | "calendar" | "camera" |
| 737 | | "cast" | "clock" | "code" | "communicate" | "contacts" | "education" | "email" |
| 738 | | "emergency" | "euicc" | "everysync" | "files" | "findfamily" | "flashcards" |
| 739 | | "fooddelivery" | "globalesim" | "health" | "keyboard" | "launcher" | "logviewer" |
| 740 | | "maps" | "measure" | "music" | "networklocation" | "notes" | "office" |
| 741 | | "openassistant" | "passwords" | "pdf" | "photos" | "parentalcontrols" | "screentime" |
| 742 | | "setupwizard" | "share" | "shop" | "securemail" | "speech" | "taxi" | "things" |
| 743 | | "todo" | "translate" | "travel" | "tuner" | "uniflix" | "updater" | "vpn" | "weather" |
| 744 | | "web" | "youpipe" => label, |
| 745 | _ => return None, |
| 746 | }; |
| 747 | Some(module) |
| 748 | } |
| 749 | |
| 750 | /// First app-label hit wins; non-app labels are skipped. |
| 751 | pub fn app_module_for_labels(labels: &[String]) -> Option<String> { |
| 752 | labels.iter().find_map(|l| app_module_for_label(l)) |
| 753 | } |
| 754 | |
| 755 | /// Every repo module dir an app label can map to (compile-time list; the |
| 756 | /// `mapped_module_dirs_exist_in_worktree` test checks each against the |
| 757 | /// filesystem). |
| 758 | pub const ALL_APP_MODULES: &[&str] = &[ |
| 759 | "appstore", |
| 760 | "astronomy", |
| 761 | "auto", |
| 762 | "backup", |
| 763 | "calculator", |
| 764 | "calendar", |
| 765 | "camera", |
| 766 | "cast", |
| 767 | "clock", |
| 768 | "code", |
| 769 | "communicate", |
| 770 | "contacts", |
| 771 | "education", |
| 772 | "email", |
| 773 | "emergency", |
| 774 | "euicc", |
| 775 | "everysync", |
| 776 | "files", |
| 777 | "findfamily", |
| 778 | "flashcards", |
| 779 | "fooddelivery", |
| 780 | "games/arrows", |
| 781 | "games/chess", |
| 782 | "games/hub", |
| 783 | "games/kart", |
| 784 | "games/logicgate", |
| 785 | "games/minesweeper", |
| 786 | "games/nonogram", |
| 787 | "games/pipes", |
| 788 | "games/solitaire", |
| 789 | "games/sudoku", |
| 790 | "games/unblockjam", |
| 791 | "games/voxels", |
| 792 | "games/wordmaker", |
| 793 | "globalesim", |
| 794 | "health", |
| 795 | "keyboard", |
| 796 | "launcher", |
| 797 | "logviewer", |
| 798 | "maps", |
| 799 | "measure", |
| 800 | "music", |
| 801 | "networklocation", |
| 802 | "notes", |
| 803 | "office", |
| 804 | "openassistant", |
| 805 | "parentalcontrols", |
| 806 | "passwords", |
| 807 | "pdf", |
| 808 | "photos", |
| 809 | "screentime", |
| 810 | "securemail", |
| 811 | "setupwizard", |
| 812 | "share", |
| 813 | "shop", |
| 814 | "speech", |
| 815 | "taxi", |
| 816 | "things", |
| 817 | "todo", |
| 818 | "translate", |
| 819 | "travel", |
| 820 | "tuner", |
| 821 | "uniflix", |
| 822 | "updater", |
| 823 | "vpn", |
| 824 | "weather", |
| 825 | "web", |
| 826 | "youpipe", |
| 827 | ]; |
| 828 | |
| 829 | /// Compact one-issue rendering for model context. |
| 830 | pub fn render_issue_for_model(issue: &Issue) -> String { |
| 831 | let mut s = format!("#{} [{}] {}\n", issue.number, issue.state, issue.title); |
| 832 | s.push_str(&format!("labels: {}\n", issue.labels.join(", "))); |
| 833 | s.push_str(&format!( |
| 834 | "author: {} opened: {}\n\n{}\n", |
| 835 | issue.author, issue.created_at, issue.body |
| 836 | )); |
| 837 | if !issue.comments.is_empty() { |
| 838 | s.push_str(&format!("\n--- {} comment(s) ---\n", issue.comments.len())); |
| 839 | for c in &issue.comments { |
| 840 | s.push_str(&format!("\n[{} @ {}]\n{}\n", c.author, c.created_at, c.body)); |
| 841 | } |
| 842 | } |
| 843 | if issue.truncated { |
| 844 | s.push_str("\n[note: body/comments truncated to fit the context budget]\n"); |
| 845 | } |
| 846 | s |
| 847 | } |
| 848 | |
| 849 | /// One line per issue for model context. |
| 850 | pub fn render_search_for_model(issues: &[IssueSummary]) -> String { |
| 851 | issues |
| 852 | .iter() |
| 853 | .map(|i| { |
| 854 | format!( |
| 855 | "#{} [{}] ({} comments) [{}] {} — updated {}", |
| 856 | i.number, |
| 857 | i.state, |
| 858 | i.comments, |
| 859 | i.labels.join(", "), |
| 860 | i.title, |
| 861 | i.updated_at |
| 862 | ) |
| 863 | }) |
| 864 | .collect::<Vec<_>>() |
| 865 | .join("\n") |
| 866 | } |
| 867 | |
| 868 | fn trim_chars(s: &str, max_chars: usize) -> String { |
| 869 | if s.chars().count() <= max_chars { |
| 870 | s.to_string() |
| 871 | } else { |
| 872 | s.chars().take(max_chars).collect() |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | /// Build a scheduler task from an issue: `(title, prompt, module)`. The title |
| 877 | /// is `"#<n> <issue title>"` trimmed to 80 chars; the prompt carries the body |
| 878 | /// plus comments and instructs the agent to reference `(#n)` in the commit |
| 879 | /// subject. |
| 880 | pub fn task_from_issue(issue: &Issue) -> (String, String, Option<String>) { |
| 881 | let title = trim_chars(&format!("#{} {}", issue.number, issue.title), 80); |
| 882 | let module = app_module_for_labels(&issue.labels); |
| 883 | let labels = if issue.labels.is_empty() { |
| 884 | "(none)".to_string() |
| 885 | } else { |
| 886 | issue.labels.join(", ") |
| 887 | }; |
| 888 | let mut prompt = format!( |
| 889 | "GitHub issue #{}: {}\nState: {} | Labels: {} | Author: {}\n\n{}\n", |
| 890 | issue.number, issue.title, issue.state, labels, issue.author, issue.body |
| 891 | ); |
| 892 | if !issue.comments.is_empty() { |
| 893 | prompt.push_str(&format!("\nKey comments ({}):\n", issue.comments.len())); |
| 894 | for c in &issue.comments { |
| 895 | prompt.push_str(&format!( |
| 896 | "\n[{} @ {}]\n{}\n", |
| 897 | c.author, c.created_at, c.body |
| 898 | )); |
| 899 | } |
| 900 | } |
| 901 | if issue.truncated { |
| 902 | prompt.push_str("\n[note: issue body/comments were truncated to fit the context budget]\n"); |
| 903 | } |
| 904 | if let Some(m) = &module { |
| 905 | prompt.push_str(&format!("\nWork in module `{m}` (repo-relative).\n")); |
| 906 | } |
| 907 | prompt.push_str(&format!( |
| 908 | "\nWhen you commit the fix, reference (#{}) in the commit subject, e.g. `<module>: <short description> (#{})`.\n", |
| 909 | issue.number, issue.number |
| 910 | )); |
| 911 | (title, prompt, module) |
| 912 | } |
| 913 | |
| 914 | #[cfg(test)] |
| 915 | mod tests { |
| 916 | use super::*; |
| 917 | use axum::body::Body; |
| 918 | use axum::extract::State; |
| 919 | use axum::http::{HeaderMap, StatusCode}; |
| 920 | use axum::response::IntoResponse; |
| 921 | use std::collections::HashMap; |
| 922 | use std::sync::{Arc, Mutex}; |
| 923 | |
| 924 | const ISSUE_903: &str = include_str!("testdata/github/issue_903.json"); |
| 925 | const COMMENTS_903: &str = include_str!("testdata/github/comments_903.json"); |
| 926 | const COMMENTS_891: &str = include_str!("testdata/github/comments_891.json"); |
| 927 | const SEARCH_WEATHER: &str = include_str!("testdata/github/search_weather.json"); |
| 928 | const LIST_WEATHER: &str = include_str!("testdata/github/list_weather.json"); |
| 929 | |
| 930 | #[derive(Debug, Clone)] |
| 931 | struct RecordedRequest { |
| 932 | method: String, |
| 933 | path: String, |
| 934 | query: String, |
| 935 | headers: HeaderMap, |
| 936 | body: Vec<u8>, |
| 937 | } |
| 938 | |
| 939 | #[derive(Debug, Clone)] |
| 940 | struct MockResponse { |
| 941 | status: u16, |
| 942 | headers: Vec<(String, String)>, |
| 943 | body: Vec<u8>, |
| 944 | } |
| 945 | |
| 946 | #[derive(Debug, Clone, Default)] |
| 947 | struct Mock { |
| 948 | recorded: Arc<Mutex<Vec<RecordedRequest>>>, |
| 949 | responses: Arc<Mutex<HashMap<String, MockResponse>>>, |
| 950 | } |
| 951 | |
| 952 | impl Mock { |
| 953 | fn respond( |
| 954 | &self, |
| 955 | path: &str, |
| 956 | status: u16, |
| 957 | headers: &[(&str, &str)], |
| 958 | body: impl Into<Vec<u8>>, |
| 959 | ) { |
| 960 | self.responses.lock().unwrap().insert( |
| 961 | path.to_string(), |
| 962 | MockResponse { |
| 963 | status, |
| 964 | headers: headers |
| 965 | .iter() |
| 966 | .map(|(k, v)| ((*k).to_string(), (*v).to_string())) |
| 967 | .collect(), |
| 968 | body: body.into(), |
| 969 | }, |
| 970 | ); |
| 971 | } |
| 972 | |
| 973 | fn requests(&self) -> Vec<RecordedRequest> { |
| 974 | self.recorded.lock().unwrap().clone() |
| 975 | } |
| 976 | } |
| 977 | |
| 978 | async fn mock_handler( |
| 979 | State(mock): State<Mock>, |
| 980 | req: axum::http::Request<Body>, |
| 981 | ) -> impl IntoResponse { |
| 982 | let (parts, body) = req.into_parts(); |
| 983 | let body = axum::body::to_bytes(body, 4 * 1024 * 1024) |
| 984 | .await |
| 985 | .unwrap_or_default() |
| 986 | .to_vec(); |
| 987 | mock.recorded.lock().unwrap().push(RecordedRequest { |
| 988 | method: parts.method.to_string(), |
| 989 | path: parts.uri.path().to_string(), |
| 990 | query: parts.uri.query().unwrap_or_default().to_string(), |
| 991 | headers: parts.headers.clone(), |
| 992 | body, |
| 993 | }); |
| 994 | let found = mock |
| 995 | .responses |
| 996 | .lock() |
| 997 | .unwrap() |
| 998 | .get(parts.uri.path()) |
| 999 | .cloned(); |
| 1000 | match found { |
| 1001 | Some(r) => { |
| 1002 | let mut builder = axum::http::Response::builder() |
| 1003 | .status(StatusCode::from_u16(r.status).unwrap_or(StatusCode::OK)); |
| 1004 | for (k, v) in &r.headers { |
| 1005 | builder = builder.header(k, v); |
| 1006 | } |
| 1007 | builder.body(Body::from(r.body)).unwrap() |
| 1008 | } |
| 1009 | None => axum::http::Response::builder() |
| 1010 | .status(StatusCode::NOT_FOUND) |
| 1011 | .body(Body::from("no mock for path")) |
| 1012 | .unwrap(), |
| 1013 | } |
| 1014 | } |
| 1015 | |
| 1016 | async fn spawn_mock(mock: Mock) -> String { |
| 1017 | let app = axum::Router::new() |
| 1018 | .fallback(mock_handler) |
| 1019 | .with_state(mock); |
| 1020 | let lis = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 1021 | .await |
| 1022 | .unwrap(); |
| 1023 | let addr = lis.local_addr().unwrap(); |
| 1024 | tokio::spawn(async move { axum::serve(lis, app).await.unwrap() }); |
| 1025 | format!("http://{addr}") |
| 1026 | } |
| 1027 | |
| 1028 | fn client(base: &str, token: Option<&str>) -> GitHub { |
| 1029 | GitHub::with_base_url(base, "test-owner/test-repo", token.map(str::to_string)).unwrap() |
| 1030 | } |
| 1031 | |
| 1032 | fn json() -> [(&'static str, &'static str); 1] { |
| 1033 | [("content-type", "application/json")] |
| 1034 | } |
| 1035 | |
| 1036 | /// Decode `application/x-www-form-urlencoded` enough for assertions. |
| 1037 | fn decode_query(q: &str) -> String { |
| 1038 | let mut out = String::new(); |
| 1039 | let bytes = q.as_bytes(); |
| 1040 | let mut i = 0; |
| 1041 | while i < bytes.len() { |
| 1042 | match bytes[i] { |
| 1043 | b'+' => { |
| 1044 | out.push(' '); |
| 1045 | i += 1; |
| 1046 | } |
| 1047 | b'%' if i + 2 < bytes.len() => { |
| 1048 | if let Ok(b) = u8::from_str_radix(&q[i + 1..i + 3], 16) { |
| 1049 | out.push(b as char); |
| 1050 | } |
| 1051 | i += 3; |
| 1052 | } |
| 1053 | b => { |
| 1054 | out.push(b as char); |
| 1055 | i += 1; |
| 1056 | } |
| 1057 | } |
| 1058 | } |
| 1059 | out |
| 1060 | } |
| 1061 | |
| 1062 | fn sample_issue() -> Issue { |
| 1063 | Issue { |
| 1064 | number: 903, |
| 1065 | title: "Weather widgets only show Celsius".to_string(), |
| 1066 | state: "open".to_string(), |
| 1067 | labels: vec!["bug".to_string(), "weather".to_string()], |
| 1068 | body: "Widget shows C only.".to_string(), |
| 1069 | author: "coolpx".to_string(), |
| 1070 | created_at: "2026-11-05T04:51:07Z".to_string(), |
| 1071 | comments: vec![Comment { |
| 1072 | author: "vayun-mathur".to_string(), |
| 1073 | created_at: "2026-11-05T10:00:00Z".to_string(), |
| 1074 | body: "Reproduced, fixing.".to_string(), |
| 1075 | }], |
| 1076 | truncated: false, |
| 1077 | } |
| 1078 | } |
| 1079 | |
| 1080 | #[test] |
| 1081 | fn foreign_pagination_links_never_get_the_token() { |
| 1082 | let gh = GitHub::with_base_url("https://api.github.com", "o/r", Some("tok".into())).unwrap(); |
| 1083 | let ok = gh.request(reqwest::Method::GET, "https://api.github.com/repos/o/r/issues/1/comments?page=2").build().unwrap(); |
| 1084 | assert_eq!(ok.url().host_str(), Some("api.github.com")); |
| 1085 | let evil = gh.request(reqwest::Method::GET, "https://evil.example/steal").build().unwrap(); |
| 1086 | assert_eq!(evil.url().host_str(), Some("api.github.com")); |
| 1087 | let sneaky = gh.request(reqwest::Method::GET, "https://api.github.com.evil.example/x").build().unwrap(); |
| 1088 | assert_eq!(sneaky.url().host_str(), Some("api.github.com")); |
| 1089 | } |
| 1090 | |
| 1091 | #[tokio::test] |
| 1092 | async fn search_uses_search_api_with_query() { |
| 1093 | let mock = Mock::default(); |
| 1094 | mock.respond("/search/issues", 200, &json(), SEARCH_WEATHER); |
| 1095 | let base = spawn_mock(mock.clone()).await; |
| 1096 | let gh = client(&base, None); |
| 1097 | |
| 1098 | let out = gh |
| 1099 | .search_issues(Some("celsius"), &["weather".to_string()], IssueState::Open, 5) |
| 1100 | .await |
| 1101 | .unwrap(); |
| 1102 | assert_eq!(out.len(), 3); |
| 1103 | assert!(out.iter().all(|i| !i.is_pr)); |
| 1104 | let nums: Vec<u64> = out.iter().map(|i| i.number).collect(); |
| 1105 | assert!(nums.contains(&903)); |
| 1106 | |
| 1107 | let reqs = mock.requests(); |
| 1108 | assert_eq!(reqs.len(), 1); |
| 1109 | assert_eq!(reqs[0].method, "GET"); |
| 1110 | assert_eq!(reqs[0].path, "/search/issues"); |
| 1111 | let q = decode_query(&reqs[0].query); |
| 1112 | assert!(q.contains("repo:test-owner/test-repo"), "q={q}"); |
| 1113 | assert!(q.contains("is:issue"), "q={q}"); |
| 1114 | assert!(q.contains("celsius"), "q={q}"); |
| 1115 | assert!(q.contains("state:open"), "q={q}"); |
| 1116 | assert!(q.contains("label:\"weather\""), "q={q}"); |
| 1117 | |
| 1118 | assert_eq!(reqs[0].headers.get("user-agent").unwrap(), "agentd"); |
| 1119 | assert_eq!( |
| 1120 | reqs[0].headers.get("accept").unwrap(), |
| 1121 | "application/vnd.github+json" |
| 1122 | ); |
| 1123 | assert_eq!( |
| 1124 | reqs[0].headers.get("x-github-api-version").unwrap(), |
| 1125 | "2022-11-28" |
| 1126 | ); |
| 1127 | assert!(reqs[0].headers.get("authorization").is_none()); |
| 1128 | } |
| 1129 | |
| 1130 | #[tokio::test] |
| 1131 | async fn list_endpoint_used_without_query() { |
| 1132 | let mock = Mock::default(); |
| 1133 | mock.respond("/repos/test-owner/test-repo/issues", 200, &json(), LIST_WEATHER); |
| 1134 | let base = spawn_mock(mock.clone()).await; |
| 1135 | let gh = client(&base, None); |
| 1136 | |
| 1137 | let out = gh |
| 1138 | .search_issues(None, &["weather".to_string()], IssueState::Open, 5) |
| 1139 | .await |
| 1140 | .unwrap(); |
| 1141 | assert_eq!(out.len(), 3); |
| 1142 | assert!(out.iter().all(|i| !i.is_pr)); |
| 1143 | |
| 1144 | let reqs = mock.requests(); |
| 1145 | assert_eq!(reqs.len(), 1); |
| 1146 | assert_eq!(reqs[0].path, "/repos/test-owner/test-repo/issues"); |
| 1147 | let q = decode_query(&reqs[0].query); |
| 1148 | assert!(q.contains("labels=weather"), "q={q}"); |
| 1149 | assert!(q.contains("state=open"), "q={q}"); |
| 1150 | } |
| 1151 | |
| 1152 | #[tokio::test] |
| 1153 | async fn search_excludes_pull_requests() { |
| 1154 | let body = serde_json::json!({ |
| 1155 | "total_count": 2, |
| 1156 | "incomplete_results": false, |
| 1157 | "items": [ |
| 1158 | {"number": 10, "title": "Real issue", "state": "open", |
| 1159 | "labels": [], "comments": 0, "updated_at": "2026-11-05T00:00:00Z"}, |
| 1160 | {"number": 11, "title": "A PR", "state": "open", |
| 1161 | "labels": [], "comments": 0, "updated_at": "2026-11-05T00:00:00Z", |
| 1162 | "pull_request": {"url": "https://api.github.com/x", "html_url": "https://github.com/x"}}, |
| 1163 | ], |
| 1164 | }); |
| 1165 | let mock = Mock::default(); |
| 1166 | mock.respond( |
| 1167 | "/search/issues", |
| 1168 | 200, |
| 1169 | &json(), |
| 1170 | serde_json::to_vec(&body).unwrap(), |
| 1171 | ); |
| 1172 | let base = spawn_mock(mock.clone()).await; |
| 1173 | let gh = client(&base, None); |
| 1174 | |
| 1175 | let out = gh |
| 1176 | .search_issues(Some("x"), &[], IssueState::All, 10) |
| 1177 | .await |
| 1178 | .unwrap(); |
| 1179 | assert_eq!(out.len(), 1); |
| 1180 | assert_eq!(out[0].number, 10); |
| 1181 | } |
| 1182 | |
| 1183 | #[tokio::test] |
| 1184 | async fn read_issue_parses_fixture() { |
| 1185 | let mock = Mock::default(); |
| 1186 | mock.respond("/repos/test-owner/test-repo/issues/903", 200, &json(), ISSUE_903); |
| 1187 | mock.respond( |
| 1188 | "/repos/test-owner/test-repo/issues/903/comments", |
| 1189 | 200, |
| 1190 | &json(), |
| 1191 | COMMENTS_903, |
| 1192 | ); |
| 1193 | let base = spawn_mock(mock.clone()).await; |
| 1194 | let gh = client(&base, None); |
| 1195 | |
| 1196 | let issue = gh.read_issue(903).await.unwrap(); |
| 1197 | assert_eq!(issue.number, 903); |
| 1198 | assert_eq!(issue.title, "[bug]: Weather widgets only show Celsius"); |
| 1199 | assert_eq!(issue.state, "open"); |
| 1200 | assert_eq!(issue.author, "coolpx"); |
| 1201 | assert!(issue.labels.contains(&"weather".to_string())); |
| 1202 | assert!(issue.labels.contains(&"bug".to_string())); |
| 1203 | assert!(issue.body.contains("Celsius")); |
| 1204 | assert!(issue.comments.is_empty()); |
| 1205 | assert!(!issue.truncated); |
| 1206 | } |
| 1207 | |
| 1208 | #[tokio::test] |
| 1209 | async fn read_issue_follows_comment_pagination() { |
| 1210 | let mock = Mock::default(); |
| 1211 | let base = spawn_mock(mock.clone()).await; |
| 1212 | // Register pages after the base URL is known so the `Link` |
| 1213 | // header can point at the absolute mock URL (the handler |
| 1214 | // looks responses up at request time, so this is race-free here: |
| 1215 | // the client issues no request until below). |
| 1216 | mock.respond( |
| 1217 | "/repos/test-owner/test-repo/issues/42", |
| 1218 | 200, |
| 1219 | &json(), |
| 1220 | r#"{"number":42,"title":"T","state":"open","labels":[],"user":{"login":"a"}, |
| 1221 | "created_at":"2026-11-05T00:00:00Z","body":"b"}"#, |
| 1222 | ); |
| 1223 | mock.respond( |
| 1224 | "/repos/test-owner/test-repo/issues/42/comments", |
| 1225 | 200, |
| 1226 | &[ |
| 1227 | ("content-type", "application/json"), |
| 1228 | ( |
| 1229 | "link", |
| 1230 | &format!("<{base}/page2>; rel=\"next\", <{base}/page2>; rel=\"last\""), |
| 1231 | ), |
| 1232 | ], |
| 1233 | r#"[{"id":1,"user":{"login":"a"},"created_at":"2026-11-05T01:00:00Z","body":"first"}]"#, |
| 1234 | ); |
| 1235 | mock.respond( |
| 1236 | "/page2", |
| 1237 | 200, |
| 1238 | &json(), |
| 1239 | r#"[{"id":2,"user":{"login":"b"},"created_at":"2026-11-05T02:00:00Z","body":"second"}]"#, |
| 1240 | ); |
| 1241 | let gh = client(&base, None); |
| 1242 | |
| 1243 | let issue = gh.read_issue(42).await.unwrap(); |
| 1244 | assert_eq!(issue.comments.len(), 2); |
| 1245 | assert_eq!(issue.comments[0].body, "first"); |
| 1246 | assert_eq!(issue.comments[1].author, "b"); |
| 1247 | assert!(!issue.truncated); |
| 1248 | let paths: Vec<String> = mock.requests().iter().map(|r| r.path.clone()).collect(); |
| 1249 | assert!(paths.contains(&"/page2".to_string()), "{paths:?}"); |
| 1250 | } |
| 1251 | |
| 1252 | #[tokio::test] |
| 1253 | async fn read_issue_truncates_to_budget() { |
| 1254 | let mock = Mock::default(); |
| 1255 | mock.respond( |
| 1256 | "/repos/test-owner/test-repo/issues/903", |
| 1257 | 200, |
| 1258 | &json(), |
| 1259 | ISSUE_903, |
| 1260 | ); |
| 1261 | // Real comment fixture plus a synthetic long comment so the total |
| 1262 | // exceeds the 12 KB budget (recorded bodies alone fit). |
| 1263 | let mut comments: Vec<serde_json::Value> = |
| 1264 | serde_json::from_str(COMMENTS_891).unwrap(); |
| 1265 | comments.push(serde_json::json!({ |
| 1266 | "id": 999, "user": {"login": "someone"}, |
| 1267 | "created_at": "2026-11-05T03:00:00Z", |
| 1268 | "body": "y".repeat(20_000), |
| 1269 | })); |
| 1270 | mock.respond( |
| 1271 | "/repos/test-owner/test-repo/issues/903/comments", |
| 1272 | 200, |
| 1273 | &json(), |
| 1274 | serde_json::to_vec(&comments).unwrap(), |
| 1275 | ); |
| 1276 | let base = spawn_mock(mock.clone()).await; |
| 1277 | let gh = client(&base, None); |
| 1278 | |
| 1279 | let issue = gh.read_issue(903).await.unwrap(); |
| 1280 | assert!(issue.truncated); |
| 1281 | let total: usize = |
| 1282 | issue.body.len() + issue.comments.iter().map(|c| c.body.len()).sum::<usize>(); |
| 1283 | assert!(total <= BODY_BUDGET_BYTES, "total={total}"); |
| 1284 | // The over-budget tail comment is kept but fragmented in place. |
| 1285 | let last = issue.comments.last().unwrap(); |
| 1286 | assert!(last.body.ends_with("[…truncated]"), "last={:?}", &last.body[last.body.len().saturating_sub(20)..]); |
| 1287 | } |
| 1288 | |
| 1289 | #[test] |
| 1290 | fn apply_budget_truncates_oversize_body() { |
| 1291 | let (body, comments, truncated) = apply_budget("x".repeat(20_000), vec![sample_issue().comments.remove(0)]); |
| 1292 | assert!(truncated); |
| 1293 | assert!(body.len() <= BODY_BUDGET_BYTES); |
| 1294 | assert!(body.ends_with(TRUNC_MARKER)); |
| 1295 | assert!(comments.is_empty()); |
| 1296 | } |
| 1297 | |
| 1298 | #[tokio::test] |
| 1299 | async fn auth_header_sent_only_with_token() { |
| 1300 | let mock = Mock::default(); |
| 1301 | mock.respond("/search/issues", 200, &json(), SEARCH_WEATHER); |
| 1302 | let base = spawn_mock(mock.clone()).await; |
| 1303 | |
| 1304 | client(&base, Some("tok123")) |
| 1305 | .search_issues(Some("q"), &[], IssueState::Open, 1) |
| 1306 | .await |
| 1307 | .unwrap(); |
| 1308 | client(&base, None) |
| 1309 | .search_issues(Some("q"), &[], IssueState::Open, 1) |
| 1310 | .await |
| 1311 | .unwrap(); |
| 1312 | |
| 1313 | let reqs = mock.requests(); |
| 1314 | assert_eq!(reqs.len(), 2); |
| 1315 | assert_eq!(reqs[0].headers.get("authorization").unwrap(), "Bearer tok123"); |
| 1316 | assert!(reqs[1].headers.get("authorization").is_none()); |
| 1317 | } |
| 1318 | |
| 1319 | #[tokio::test] |
| 1320 | async fn rate_limit_errors_carry_reset_time() { |
| 1321 | let mock = Mock::default(); |
| 1322 | mock.respond( |
| 1323 | "/search/issues", |
| 1324 | 403, |
| 1325 | &[ |
| 1326 | ("content-type", "application/json"), |
| 1327 | ("x-ratelimit-remaining", "0"), |
| 1328 | ("x-ratelimit-reset", "1793900736"), |
| 1329 | ], |
| 1330 | r#"{"message":"API rate limit exceeded"}"#, |
| 1331 | ); |
| 1332 | mock.respond( |
| 1333 | "/repos/test-owner/test-repo/issues", |
| 1334 | 429, |
| 1335 | &[("content-type", "application/json"), ("retry-after", "60")], |
| 1336 | r#"{"message":"slow down"}"#, |
| 1337 | ); |
| 1338 | let base = spawn_mock(mock.clone()).await; |
| 1339 | let gh = client(&base, None); |
| 1340 | |
| 1341 | let err = gh |
| 1342 | .search_issues(Some("q"), &[], IssueState::Open, 1) |
| 1343 | .await |
| 1344 | .unwrap_err(); |
| 1345 | assert!(matches!(err, Error::RateLimited { .. }), "{err:?}"); |
| 1346 | assert!(err.to_string().contains("1793900736"), "{err}"); |
| 1347 | |
| 1348 | let err = gh |
| 1349 | .search_issues(None, &[], IssueState::Open, 1) |
| 1350 | .await |
| 1351 | .unwrap_err(); |
| 1352 | assert!(matches!(err, Error::RateLimited { .. }), "{err:?}"); |
| 1353 | |
| 1354 | // A plain 403 without rate-limit headers is a normal API error. |
| 1355 | let mock2 = Mock::default(); |
| 1356 | mock2.respond( |
| 1357 | "/repos/test-owner/test-repo/issues/1", |
| 1358 | 403, |
| 1359 | &json(), |
| 1360 | r#"{"message":"Forbidden"}"#, |
| 1361 | ); |
| 1362 | let base2 = spawn_mock(mock2.clone()).await; |
| 1363 | let err = client(&base2, None).read_issue(1).await.unwrap_err(); |
| 1364 | assert!(matches!(err, Error::Api { status: 403, .. }), "{err:?}"); |
| 1365 | assert!(err.to_string().contains("Forbidden"), "{err}"); |
| 1366 | } |
| 1367 | |
| 1368 | #[tokio::test] |
| 1369 | async fn post_comment_shape_and_token_required() { |
| 1370 | let mock = Mock::default(); |
| 1371 | mock.respond( |
| 1372 | "/repos/test-owner/test-repo/issues/1/comments", |
| 1373 | 201, |
| 1374 | &json(), |
| 1375 | r#"{"html_url":"https://github.com/test-owner/test-repo/issues/1#issuecomment-9"}"#, |
| 1376 | ); |
| 1377 | let base = spawn_mock(mock.clone()).await; |
| 1378 | |
| 1379 | let url = client(&base, Some("tok")) |
| 1380 | .post_comment(1, "hello") |
| 1381 | .await |
| 1382 | .unwrap(); |
| 1383 | assert_eq!( |
| 1384 | url, |
| 1385 | "https://github.com/test-owner/test-repo/issues/1#issuecomment-9" |
| 1386 | ); |
| 1387 | let reqs = mock.requests(); |
| 1388 | assert_eq!(reqs.len(), 1); |
| 1389 | assert_eq!(reqs[0].method, "POST"); |
| 1390 | let v: serde_json::Value = serde_json::from_slice(&reqs[0].body).unwrap(); |
| 1391 | assert_eq!(v, serde_json::json!({ "body": "hello" })); |
| 1392 | |
| 1393 | // No token: error before any HTTP call (unreachable base proves it). |
| 1394 | let offline = |
| 1395 | GitHub::with_base_url("http://127.0.0.1:9", "o/r", None).unwrap(); |
| 1396 | assert!(matches!( |
| 1397 | offline.post_comment(1, "x").await, |
| 1398 | Err(Error::NoToken(_)) |
| 1399 | )); |
| 1400 | assert!(matches!( |
| 1401 | offline.add_labels(1, &["a".to_string()]).await, |
| 1402 | Err(Error::NoToken(_)) |
| 1403 | )); |
| 1404 | } |
| 1405 | |
| 1406 | #[tokio::test] |
| 1407 | async fn add_labels_shape() { |
| 1408 | let mock = Mock::default(); |
| 1409 | mock.respond( |
| 1410 | "/repos/test-owner/test-repo/issues/1/labels", |
| 1411 | 200, |
| 1412 | &json(), |
| 1413 | r#"[{"name":"solved for next release"}]"#, |
| 1414 | ); |
| 1415 | let base = spawn_mock(mock.clone()).await; |
| 1416 | |
| 1417 | client(&base, Some("tok")) |
| 1418 | .add_labels(1, &["solved for next release".to_string()]) |
| 1419 | .await |
| 1420 | .unwrap(); |
| 1421 | let reqs = mock.requests(); |
| 1422 | assert_eq!(reqs.len(), 1); |
| 1423 | assert_eq!(reqs[0].method, "POST"); |
| 1424 | assert_eq!(reqs[0].path, "/repos/test-owner/test-repo/issues/1/labels"); |
| 1425 | let v: serde_json::Value = serde_json::from_slice(&reqs[0].body).unwrap(); |
| 1426 | assert_eq!(v, serde_json::json!({ "labels": ["solved for next release"] })); |
| 1427 | } |
| 1428 | |
| 1429 | #[test] |
| 1430 | fn label_to_module_spot_checks() { |
| 1431 | let app = |s: &str| app_module_for_labels(&[s.to_string()]); |
| 1432 | assert_eq!(app("weather"), Some("weather".to_string())); |
| 1433 | assert_eq!(app("chess"), Some("games/chess".to_string())); |
| 1434 | assert_eq!(app("logicgate"), Some("games/logicgate".to_string())); |
| 1435 | assert_eq!(app("hub"), Some("games/hub".to_string())); |
| 1436 | assert_eq!(app("voxels"), Some("games/voxels".to_string())); |
| 1437 | assert_eq!(app("Weather"), Some("weather".to_string())); |
| 1438 | assert_eq!(app("watch"), None); |
| 1439 | assert_eq!(app("bug"), None); |
| 1440 | assert_eq!(app("enhancement"), None); |
| 1441 | assert_eq!(app("2.6.12"), None); |
| 1442 | assert_eq!(app("solved for next release"), None); |
| 1443 | // First app label wins over non-app labels. |
| 1444 | assert_eq!( |
| 1445 | app_module_for_labels(&[ |
| 1446 | "bug".to_string(), |
| 1447 | "2.6.12".to_string(), |
| 1448 | "kart".to_string() |
| 1449 | ]), |
| 1450 | Some("games/kart".to_string()) |
| 1451 | ); |
| 1452 | assert_eq!(app_module_for_labels(&["bug".to_string()]), None); |
| 1453 | } |
| 1454 | |
| 1455 | #[test] |
| 1456 | fn mapped_module_dirs_exist_in_worktree() { |
| 1457 | let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); |
| 1458 | assert!(root.join("settings.gradle.kts").is_file()); |
| 1459 | for m in ALL_APP_MODULES { |
| 1460 | assert!(root.join(m).is_dir(), "module dir missing: {m}"); |
| 1461 | } |
| 1462 | } |
| 1463 | |
| 1464 | #[test] |
| 1465 | fn task_from_issue_shapes_title_prompt_module() { |
| 1466 | let (title, prompt, module) = task_from_issue(&sample_issue()); |
| 1467 | assert_eq!(title, "#903 Weather widgets only show Celsius"); |
| 1468 | assert_eq!(module, Some("weather".to_string())); |
| 1469 | assert!(prompt.contains("Widget shows C only."), "{prompt}"); |
| 1470 | assert!(prompt.contains("Reproduced, fixing."), "{prompt}"); |
| 1471 | assert!(prompt.contains("(#903)"), "{prompt}"); |
| 1472 | |
| 1473 | let mut long = sample_issue(); |
| 1474 | long.title = "x".repeat(100); |
| 1475 | let (title, _, _) = task_from_issue(&long); |
| 1476 | assert!(title.chars().count() <= 80, "{title}"); |
| 1477 | assert!(title.starts_with("#903 "), "{title}"); |
| 1478 | } |
| 1479 | |
| 1480 | #[test] |
| 1481 | fn percent_encode_label_cases() { |
| 1482 | assert_eq!(percent_encode_label("bug"), "bug"); |
| 1483 | assert_eq!(percent_encode_label("solved for next release"), "solved%20for%20next%20release"); |
| 1484 | assert_eq!(percent_encode_label("2.6.12"), "2.6.12"); |
| 1485 | assert_eq!(percent_encode_label("a/b+c"), "a%2Fb%2Bc"); |
| 1486 | assert_eq!(percent_encode_label("~x-_."), "~x-_."); |
| 1487 | } |
| 1488 | |
| 1489 | #[test] |
| 1490 | fn normalize_rfc3339_cases() { |
| 1491 | assert_eq!(normalize_rfc3339("2026-11-05T00:00:00Z"), "2026-11-05T00:00:00Z"); |
| 1492 | assert_eq!(normalize_rfc3339("2026-11-05T00:00:00+00:00"), "2026-11-05T00:00:00Z"); |
| 1493 | // Unparseable / other offsets pass through unchanged. |
| 1494 | assert_eq!(normalize_rfc3339("garbage"), "garbage"); |
| 1495 | // Normalized strings compare chronologically. |
| 1496 | assert!(normalize_rfc3339("2026-11-05T04:51:08Z") > normalize_rfc3339("2026-11-05T04:51:07+00:00")); |
| 1497 | } |
| 1498 | |
| 1499 | #[test] |
| 1500 | fn app_labels_cover_all_app_modules() { |
| 1501 | // Every label mapping to a module dir appears in ALL_APP_LABELS |
| 1502 | // (probes beyond the spot checks in label_to_module_spot_checks). |
| 1503 | for probe in [ |
| 1504 | "weather", "chess", "hub", "voxels", "logicgate", "notes", "watch", |
| 1505 | ] { |
| 1506 | assert!(ALL_APP_LABELS.contains(&probe), "missing {probe}"); |
| 1507 | // `watch` has no module dir but is still an app-name label. |
| 1508 | } |
| 1509 | // Non-app labels are not in the universe. |
| 1510 | for non in ["bug", "enhancement", "2.6.12", "solved for next release"] { |
| 1511 | assert!(!ALL_APP_LABELS.contains(&non), "unexpected {non}"); |
| 1512 | } |
| 1513 | // Every module-mapped label resolves back to a known module. |
| 1514 | for label in ALL_APP_LABELS { |
| 1515 | if *label == "watch" { |
| 1516 | assert_eq!(app_module_for_labels(&[label.to_string()]), None); |
| 1517 | } else { |
| 1518 | assert!(app_module_for_labels(&[label.to_string()]).is_some(), "no module for {label}"); |
| 1519 | } |
| 1520 | } |
| 1521 | } |
| 1522 | |
| 1523 | /// Issues list fixture for `list_issues_since`: PR filtered in the |
| 1524 | /// client, one stale (before watermark), two fresh. |
| 1525 | fn list_since_body() -> Vec<u8> { |
| 1526 | serde_json::to_vec(&serde_json::json!([ |
| 1527 | {"number": 800, "title": "Old", "state": "open", "labels": [], |
| 1528 | "comments": 0, "created_at": "2026-10-01T00:00:00Z", |
| 1529 | "updated_at": "2026-10-01T00:00:00Z"}, |
| 1530 | {"number": 901, "title": "A PR", "state": "open", "labels": [], |
| 1531 | "comments": 0, "created_at": "2026-11-06T00:00:00Z", |
| 1532 | "updated_at": "2026-11-06T00:00:00Z", |
| 1533 | "pull_request": {"url": "https://api.github.com/x"}}, |
| 1534 | {"number": 902, "title": "Fresh one", "state": "closed", "labels": [{"name": "bug"}], |
| 1535 | "comments": 1, "created_at": "2026-11-06T01:00:00Z", |
| 1536 | "updated_at": "2026-11-06T02:00:00Z"}, |
| 1537 | {"number": 903, "title": "Fresh two", "state": "open", |
| 1538 | "labels": [{"name": "weather"}], "comments": 0, |
| 1539 | "created_at": "2026-11-06T03:00:00.500Z", |
| 1540 | "updated_at": "2026-11-06T03:00:00Z"}, |
| 1541 | ])) |
| 1542 | .unwrap() |
| 1543 | } |
| 1544 | |
| 1545 | #[tokio::test] |
| 1546 | async fn list_issues_since_filters_and_shapes_request() { |
| 1547 | let mock = Mock::default(); |
| 1548 | mock.respond( |
| 1549 | "/repos/test-owner/test-repo/issues", |
| 1550 | 200, |
| 1551 | &json(), |
| 1552 | list_since_body(), |
| 1553 | ); |
| 1554 | let base = spawn_mock(mock.clone()).await; |
| 1555 | let gh = client(&base, None); |
| 1556 | |
| 1557 | let out = gh |
| 1558 | .list_issues_since("2026-11-05T00:00:00Z", 50) |
| 1559 | .await |
| 1560 | .unwrap(); |
| 1561 | assert_eq!(out.len(), 2); |
| 1562 | assert_eq!(out[0].number, 902); |
| 1563 | assert_eq!(out[1].number, 903); |
| 1564 | assert_eq!(out[1].created_at, "2026-11-06T03:00:00.500Z"); |
| 1565 | assert_eq!(out[0].labels, vec!["bug".to_string()]); |
| 1566 | |
| 1567 | let reqs = mock.requests(); |
| 1568 | assert_eq!(reqs.len(), 1); |
| 1569 | assert_eq!(reqs[0].method, "GET"); |
| 1570 | assert_eq!(reqs[0].path, "/repos/test-owner/test-repo/issues"); |
| 1571 | let q = decode_query(&reqs[0].query); |
| 1572 | assert!(q.contains("state=all"), "q={q}"); |
| 1573 | assert!(q.contains("sort=created"), "q={q}"); |
| 1574 | assert!(q.contains("direction=asc"), "q={q}"); |
| 1575 | assert!(q.contains("per_page=50"), "q={q}"); |
| 1576 | } |
| 1577 | |
| 1578 | #[tokio::test] |
| 1579 | async fn list_issues_since_normalizes_watermark_offset() { |
| 1580 | let mock = Mock::default(); |
| 1581 | mock.respond( |
| 1582 | "/repos/test-owner/test-repo/issues", |
| 1583 | 200, |
| 1584 | &json(), |
| 1585 | list_since_body(), |
| 1586 | ); |
| 1587 | let base = spawn_mock(mock.clone()).await; |
| 1588 | let gh = client(&base, None); |
| 1589 | |
| 1590 | // `+00:00` watermark behaves like `Z`. |
| 1591 | let out = gh |
| 1592 | .list_issues_since("2026-11-06T01:00:00+00:00", 50) |
| 1593 | .await |
| 1594 | .unwrap(); |
| 1595 | assert_eq!(out.len(), 1); |
| 1596 | assert_eq!(out[0].number, 903); |
| 1597 | } |
| 1598 | |
| 1599 | #[tokio::test] |
| 1600 | async fn remove_label_encodes_path_and_tolerates_404() { |
| 1601 | let mock = Mock::default(); |
| 1602 | mock.respond( |
| 1603 | "/repos/test-owner/test-repo/issues/1/labels/enhancement", |
| 1604 | 200, |
| 1605 | &json(), |
| 1606 | r#"[]"#, |
| 1607 | ); |
| 1608 | let base = spawn_mock(mock.clone()).await; |
| 1609 | let gh = client(&base, Some("tok")); |
| 1610 | |
| 1611 | gh.remove_label(1, "enhancement").await.unwrap(); |
| 1612 | // Space in the label is percent-encoded; the mock has no such path |
| 1613 | // → 404 → Ok (already gone). |
| 1614 | gh.remove_label(1, "solved for next release").await.unwrap(); |
| 1615 | |
| 1616 | let reqs = mock.requests(); |
| 1617 | assert_eq!(reqs.len(), 2); |
| 1618 | assert!(reqs.iter().all(|r| r.method == "DELETE")); |
| 1619 | assert_eq!(reqs[0].path, "/repos/test-owner/test-repo/issues/1/labels/enhancement"); |
| 1620 | assert_eq!( |
| 1621 | reqs[1].path, |
| 1622 | "/repos/test-owner/test-repo/issues/1/labels/solved%20for%20next%20release" |
| 1623 | ); |
| 1624 | |
| 1625 | // No token: error before any HTTP call. |
| 1626 | let offline = GitHub::with_base_url("http://127.0.0.1:9", "o/r", None).unwrap(); |
| 1627 | assert!(!offline.has_token()); |
| 1628 | assert!(matches!( |
| 1629 | offline.remove_label(1, "bug").await, |
| 1630 | Err(Error::NoToken(_)) |
| 1631 | )); |
| 1632 | assert!(client(&base, Some("tok")).has_token()); |
| 1633 | } |
| 1634 | |
| 1635 | #[tokio::test] |
| 1636 | async fn issue_has_marker_scans_comments() { |
| 1637 | let mock = Mock::default(); |
| 1638 | mock.respond( |
| 1639 | "/repos/test-owner/test-repo/issues/10/comments", |
| 1640 | 200, |
| 1641 | &json(), |
| 1642 | r#"[{"id":1,"user":{"login":"a"},"created_at":"2026-11-06T00:00:00Z","body":"plain comment"}, |
| 1643 | {"id":2,"user":{"login":"b"},"created_at":"2026-11-06T01:00:00Z","body":"x <!-- agentd-triage --> y"}]"#, |
| 1644 | ); |
| 1645 | mock.respond( |
| 1646 | "/repos/test-owner/test-repo/issues/11/comments", |
| 1647 | 200, |
| 1648 | &json(), |
| 1649 | r#"[{"id":3,"user":{"login":"a"},"created_at":"2026-11-06T00:00:00Z","body":"nothing here"}]"#, |
| 1650 | ); |
| 1651 | let base = spawn_mock(mock.clone()).await; |
| 1652 | let gh = client(&base, None); |
| 1653 | |
| 1654 | assert!(gh.issue_has_marker(10, "<!-- agentd-triage -->").await.unwrap()); |
| 1655 | assert!(!gh.issue_has_marker(11, "<!-- agentd-triage -->").await.unwrap()); |
| 1656 | // Substring search: partial marker still matches scanner semantics. |
| 1657 | assert!(gh.issue_has_marker(10, "agentd-triage").await.unwrap()); |
| 1658 | } |
| 1659 | |
| 1660 | #[test] |
| 1661 | fn render_helpers_include_key_fields() { |
| 1662 | let issue = sample_issue(); |
| 1663 | let text = render_issue_for_model(&issue); |
| 1664 | assert!(text.contains("#903")); |
| 1665 | assert!(text.contains("Weather widgets only show Celsius")); |
| 1666 | assert!(text.contains("weather")); |
| 1667 | assert!(text.contains("vayun-mathur")); |
| 1668 | |
| 1669 | let summaries = vec![IssueSummary { |
| 1670 | number: 903, |
| 1671 | title: "T".to_string(), |
| 1672 | state: "open".to_string(), |
| 1673 | labels: vec!["weather".to_string()], |
| 1674 | comments: 2, |
| 1675 | created_at: "2026-11-05T00:00:00Z".to_string(), |
| 1676 | updated_at: "2026-11-05T00:00:00Z".to_string(), |
| 1677 | is_pr: false, |
| 1678 | }]; |
| 1679 | let text = render_search_for_model(&summaries); |
| 1680 | assert!(text.contains("#903")); |
| 1681 | assert!(text.contains("weather")); |
| 1682 | } |
| 1683 | } |