g1t/services/work/src/retired.rs
Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 1 | //! Repositories that are archived, deleted or purged, and branches |
| 2 | //! renamed: what issues, pull requests and agents do about each. | |
| 3 | //! | |
| 4 | //! An archived repository is read-only: its issues and pull requests are | |
| 5 | //! locked and nothing new starts on it. A deleted one looks missing (repos | |
| 6 | //! hides it) and keeps its rows for a restore. A purged one is gone, and | |
| 7 | //! every row kept for it goes with it. | |
| 8 | ||
| 9 | use g1t_contracts::events::{BranchRenamed, Event, RepoArchived, RepoDeleted}; | |
| 10 | use g1t_contracts::repos::{Repo, RepoStatus, StatusByIdArgs, archived_message}; | |
| 11 | use g1t_contracts::{FailureCode, Outcome}; | |
| 12 | use g1t_contracts::time::rfc3339; | |
| 13 | use g1t_kit::now_ms; | |
| 14 | use serde::{Deserialize, Serialize}; | |
| 15 | use worker::Result; | |
| 16 | ||
| 17 | use crate::Work; | |
| 18 | ||
| 19 | /// `Ok` when `repo` may be changed; refused, saying why, when it is | |
| 20 | /// archived. | |
| 21 | pub(crate) fn writable(repo: &Repo) -> Outcome<()> { | |
| 22 | if repo.archived() { | |
| 23 | Outcome::fail(FailureCode::Forbidden, archived_message(&repo.namespace, &repo.name)) | |
| 24 | } else { | |
| 25 | Outcome::Ok(()) | |
| 26 | } | |
| 27 | } | |
| 28 | ||
| 29 | /// `repo` as found, unless it is archived: then refused, as [`writable`] | |
| 30 | /// says. For the steps g1t starts by itself, which stop on a refusal. | |
| 31 | pub(crate) fn unless_archived(repo: Outcome<Repo>) -> Outcome<Repo> { | |
| 32 | match repo { | |
| 33 | Outcome::Ok(repo) => match writable(&repo) { | |
| 34 | Outcome::Ok(()) => Outcome::Ok(repo), | |
| 35 | Outcome::Fail(failure) => Outcome::Fail(failure), | |
| 36 | }, | |
| 37 | failed => failed, | |
| 38 | } | |
| 39 | } | |
| 40 | ||
| 41 | /// `repo.purged`: every row kept for the repository, `?1` its id. Rows | |
| 42 | /// kept by pull request go first, while the pull requests still name them. | |
| 43 | pub(crate) const PURGED: &[&str] = &[ | |
| 44 | "DELETE FROM session_entries WHERE pull_id IN (SELECT id FROM pulls WHERE repo_id = ?1)", | |
| 45 | "DELETE FROM check_runs WHERE pull_id IN (SELECT id FROM pulls WHERE repo_id = ?1)", | |
| 46 | "DELETE FROM review_runs WHERE pull_id IN (SELECT id FROM pulls WHERE repo_id = ?1)", | |
| 47 | "DELETE FROM agent_messages WHERE repo_id = ?1 OR pull_id IN (SELECT id FROM pulls WHERE repo_id = ?1)", | |
| 48 | "DELETE FROM queue_entries WHERE repo_id = ?1", | |
| 49 | "DELETE FROM agent_mentions WHERE repo_id = ?1", | |
| 50 | "DELETE FROM agent_rules WHERE repo_id = ?1", | |
| Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step | 51 | "DELETE FROM pull_confidence WHERE repo_id = ?1", |
| 52 | "DELETE FROM run_confidence WHERE repo_id = ?1", | |
| 53 | "DELETE FROM confidence_rules WHERE repo_id = ?1", | |
| Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look | 54 | "DELETE FROM agent_runs WHERE repo_id = ?1", |
| 55 | "DELETE FROM commit_statuses WHERE repo_id = ?1", | |
| 56 | "DELETE FROM plans WHERE repo_id = ?1", | |
| 57 | "DELETE FROM comments WHERE repo_id = ?1", | |
| 58 | "DELETE FROM pulls WHERE repo_id = ?1", | |
| 59 | "DELETE FROM issues WHERE repo_id = ?1", | |
| 60 | "DELETE FROM counters WHERE repo_id = ?1", | |
| 61 | "DELETE FROM repo_settings WHERE repo_id = ?1", | |
| 62 | "DELETE FROM memories WHERE scope = 'project' AND scope_key = ?1", | |
| 63 | "DELETE FROM guardrails WHERE scope <> 'workspace' AND scope_key = ?1", | |
| 64 | ]; | |
| 65 | ||
| 66 | /// A repository renamed or transferred (see `g1t_kit::transfer`): runs | |
| 67 | /// waiting for an agent slot name it by path in their payload, at `$.repo` | |
| 68 | /// or `$.job.repo`; they follow it, into its workspace's queue now. | |
| 69 | pub(crate) const WAITS_MOVED: &[&str] = &[ | |
| 70 | "UPDATE agent_waits SET workspace = lower(?3), | |
| 71 | payload = json_set(payload, '$.repo.namespace', ?3, '$.repo.name', ?6) | |
| 72 | WHERE json_valid(payload) | |
| 73 | AND lower(json_extract(payload, '$.repo.namespace')) = lower(?4) | |
| 74 | AND lower(json_extract(payload, '$.repo.name')) = lower(?7)", | |
| 75 | "UPDATE agent_waits SET workspace = lower(?3), | |
| 76 | payload = json_set(payload, '$.job.repo.namespace', ?3, '$.job.repo.name', ?6) | |
| 77 | WHERE json_valid(payload) | |
| 78 | AND lower(json_extract(payload, '$.job.repo.namespace')) = lower(?4) | |
| 79 | AND lower(json_extract(payload, '$.job.repo.name')) = lower(?7)", | |
| 80 | ]; | |
| 81 | ||
| 82 | /// What a run stopped because its repository was archived or deleted says | |
| 83 | /// as its last step; [`Work::runs_in_repo`] finds such runs by it. | |
| 84 | const STOPPED_STEP: &str = "Stopped: the repository was archived or deleted."; | |
| 85 | ||
| 86 | /// `repo.deleted` and `repo.archived`: the repository's agent runs that | |
| 87 | /// are queued or running stop, `?1` the step they end on, `?2` the time, | |
| 88 | /// `?3` its id. | |
| 89 | const STOP_RUNS: &str = "UPDATE agent_runs SET status = 'stopped', step = ?1, finished_at = ?2, updated_at = ?2 | |
| 90 | WHERE repo_id = ?3 AND status IN ('queued', 'running')"; | |
| 91 | ||
| 92 | /// And runs waiting for an agent slot in it are dropped: `?1` its | |
| 93 | /// workspace, `?2` its name, as the payload names it (see [`WAITS_MOVED`]). | |
| 94 | const DROP_WAITS: &[&str] = &[ | |
| 95 | "DELETE FROM agent_waits WHERE json_valid(payload) | |
| 96 | AND lower(json_extract(payload, '$.repo.namespace')) = lower(?1) | |
| 97 | AND lower(json_extract(payload, '$.repo.name')) = lower(?2)", | |
| 98 | "DELETE FROM agent_waits WHERE json_valid(payload) | |
| 99 | AND lower(json_extract(payload, '$.job.repo.namespace')) = lower(?1) | |
| 100 | AND lower(json_extract(payload, '$.job.repo.name')) = lower(?2)", | |
| 101 | ]; | |
| 102 | ||
| 103 | /// `runs_in_repo` (internal, for the runner): the agent runs of a | |
| 104 | /// repository whose sandboxes should be stopped: those queued or running, | |
| 105 | /// and those work stopped in the last hour because the repository was | |
| 106 | /// archived or deleted. Takes `{ "repoId" }`; returns `[RepoRun]`. | |
| 107 | #[derive(Deserialize)] | |
| 108 | #[serde(rename_all = "camelCase")] | |
| 109 | pub(crate) struct RunsInRepoArgs { | |
| 110 | pub repo_id: String, | |
| 111 | } | |
| 112 | ||
| 113 | #[derive(Debug, Deserialize, Serialize)] | |
| 114 | #[serde(rename_all = "camelCase")] | |
| 115 | pub(crate) struct RepoRun { | |
| 116 | pub run_id: String, | |
| 117 | pub sandbox: String, | |
| 118 | pub kind: String, | |
| 119 | pub status: String, | |
| 120 | pub pull_id: Option<String>, | |
| 121 | } | |
| 122 | ||
| 123 | /// The repository, by id and path, that `event` says was deleted or | |
| 124 | /// archived (not unarchived): its runs stop. | |
| 125 | fn stopping(event: &Event) -> Option<(String, String, String)> { | |
| 126 | let data = event.data.clone(); | |
| 127 | match event.kind.as_str() { | |
| 128 | "repo.deleted" => serde_json::from_value::<RepoDeleted>(data).ok().map(|e| (e.repo_id, e.namespace, e.name)), | |
| 129 | "repo.archived" => serde_json::from_value::<RepoArchived>(data) | |
| 130 | .ok() | |
| 131 | .filter(|e| e.archived) | |
| 132 | .map(|e| (e.repo_id, e.namespace, e.name)), | |
| 133 | _ => None, | |
| 134 | } | |
| 135 | } | |
| 136 | ||
| 137 | /// `branch.renamed`: open pull requests from `?2` in repository `?1` | |
| 138 | /// come from `?3` now. A fork carries its change on its own default | |
| 139 | /// branch, so only branches of the repository itself are named. | |
| 140 | const BRANCH_RENAMED: &str = "UPDATE pulls SET source_branch = ?3 | |
| 141 | WHERE repo_id = ?1 AND source_branch = ?2 AND fork_repo_id IS NULL | |
| 142 | AND status IN ('draft', 'open')"; | |
| 143 | ||
| 144 | impl Work { | |
| 145 | /// Whether work may start on the repository: neither archived nor | |
| 146 | /// deleted. When repos cannot say, it is taken as active, and the | |
| 147 | /// repos calls that follow (which hide deleted repositories) decide. | |
| 148 | pub(crate) async fn repo_active(&self, repo_id: &str) -> Result<bool> { | |
| 149 | let status: Result<RepoStatus> = g1t_kit::call( | |
| 150 | &self.repos, | |
| 151 | "status_by_id", | |
| 152 | &StatusByIdArgs { | |
| 153 | id: repo_id.to_owned(), | |
| 154 | }, | |
| 155 | ) | |
| 156 | .await; | |
| 157 | Ok(match status { | |
| 158 | Ok(status) => status.active(), | |
| 159 | Err(error) => { | |
| 160 | worker::console_error!("status_by_id {repo_id}: {error}"); | |
| 161 | true | |
| 162 | } | |
| 163 | }) | |
| 164 | } | |
| 165 | ||
| 166 | /// See [`RunsInRepoArgs`]. | |
| 167 | pub(crate) async fn runs_in_repo(&self, a: RunsInRepoArgs) -> Result<Vec<RepoRun>> { | |
| 168 | let hour_ago = rfc3339(now_ms().saturating_sub(60 * 60 * 1000)); | |
| 169 | self.db | |
| 170 | .prepare( | |
| 171 | "SELECT id AS run_id, sandbox, kind, status, pull_id FROM agent_runs | |
| 172 | WHERE repo_id = ?1 AND (status IN ('queued', 'running') | |
| 173 | OR (status = 'stopped' AND step = ?2 AND finished_at >= ?3)) | |
| 174 | ORDER BY created_at LIMIT 200", | |
| 175 | ) | |
| 176 | .bind(&[a.repo_id.as_str().into(), STOPPED_STEP.into(), hour_ago.as_str().into()])? | |
| 177 | .all() | |
| 178 | .await? | |
| 179 | .results::<RepoRun>() | |
| 180 | } | |
| 181 | ||
| 182 | /// `repo.deleted` and `repo.archived`: its agent runs stop (the runner | |
| 183 | /// stops their sandboxes, see [`RunsInRepoArgs`]) and runs waiting for | |
| 184 | /// a slot in it are dropped. Rows are kept, for a restore. | |
| 185 | async fn stop_runs_in(&self, repo_id: &str, namespace: &str, name: &str) -> Result<()> { | |
| 186 | let now = rfc3339(now_ms()); | |
| 187 | let mut batch = vec![self | |
| 188 | .db | |
| 189 | .prepare(STOP_RUNS) | |
| 190 | .bind(&[STOPPED_STEP.into(), now.as_str().into(), repo_id.into()])?]; | |
| 191 | if !namespace.is_empty() && !name.is_empty() { | |
| 192 | for sql in DROP_WAITS { | |
| 193 | batch.push(self.db.prepare(*sql).bind(&[namespace.into(), name.into()])?); | |
| 194 | } | |
| 195 | } | |
| 196 | self.db.batch(batch).await?; | |
| 197 | Ok(()) | |
| 198 | } | |
| 199 | ||
| 200 | /// `repo.purged`, `repo.deleted`, `repo.archived` and `branch.renamed`. | |
| 201 | /// Says whether `event` was one this handles completely. | |
| 202 | pub(crate) async fn on_retired(&self, event: &Event) -> Result<bool> { | |
| 203 | if g1t_kit::lifecycle::on_purged(&self.db, event, PURGED).await? { | |
| 204 | return Ok(true); | |
| 205 | } | |
| 206 | if let Some((repo_id, namespace, name)) = stopping(event) { | |
| 207 | self.stop_runs_in(&repo_id, &namespace, &name).await?; | |
| 208 | return Ok(true); | |
| 209 | } | |
| 210 | if event.kind != "branch.renamed" { | |
| 211 | return Ok(false); | |
| 212 | } | |
| 213 | let Ok(renamed) = serde_json::from_value::<BranchRenamed>(event.data.clone()) else { | |
| 214 | worker::console_error!("branch.renamed {} could not be read", event.id); | |
| 215 | return Ok(true); | |
| 216 | }; | |
| 217 | if renamed.from == renamed.to { | |
| 218 | return Ok(true); | |
| 219 | } | |
| 220 | self.db | |
| 221 | .prepare(BRANCH_RENAMED) | |
| 222 | .bind(&[ | |
| 223 | renamed.repo_id.as_str().into(), | |
| 224 | renamed.from.as_str().into(), | |
| 225 | renamed.to.as_str().into(), | |
| 226 | ])? | |
| 227 | .run() | |
| 228 | .await?; | |
| 229 | Ok(true) | |
| 230 | } | |
| 231 | } | |
| 232 | ||
| 233 | #[cfg(test)] | |
| 234 | mod tests { | |
| 235 | use super::*; | |
| 236 | ||
| 237 | fn repo(archived_at: Option<&str>) -> Repo { | |
| 238 | Repo { | |
| 239 | id: "rep_1".into(), | |
| 240 | namespace: "acme".into(), | |
| 241 | name: "web".into(), | |
| 242 | description: None, | |
| 243 | is_private: false, | |
| 244 | owner_id: "usr_1".into(), | |
| 245 | default_branch: "main".into(), | |
| 246 | fork_of: None, | |
| 247 | protected: false, | |
| 248 | created_at: "2026-10-05T00:00:00Z".into(), | |
| 249 | topics: Vec::new(), | |
| 250 | website: None, | |
| 251 | archived_at: archived_at.map(str::to_owned), | |
| 252 | } | |
| 253 | } | |
| 254 | ||
| 255 | #[test] | |
| 256 | fn an_archived_repository_refuses_changes() { | |
| 257 | assert!(matches!(writable(&repo(None)), Outcome::Ok(()))); | |
| 258 | match writable(&repo(Some("2026-10-05T00:00:00Z"))) { | |
| 259 | Outcome::Fail(failure) => { | |
| 260 | assert_eq!(failure.code, FailureCode::Forbidden); | |
| 261 | assert!(failure.message.contains("acme/web is archived")); | |
| 262 | } | |
| 263 | Outcome::Ok(()) => panic!("an archived repository was writable"), | |
| 264 | } | |
| 265 | } | |
| 266 | ||
| 267 | #[test] | |
| 268 | fn purging_takes_only_the_repository_id() { | |
| 269 | for sql in PURGED { | |
| 270 | assert_eq!(g1t_kit::transfer::parameters(sql), 1, "{sql}"); | |
| 271 | } | |
| 272 | // Rows kept by pull request go before the pull requests do. | |
| 273 | let pulls = PURGED.iter().position(|sql| sql.starts_with("DELETE FROM pulls")).unwrap(); | |
| 274 | for table in ["session_entries", "check_runs", "review_runs", "agent_messages"] { | |
| 275 | let at = PURGED.iter().position(|sql| sql.contains(&format!("FROM {table} "))).unwrap(); | |
| 276 | assert!(at < pulls, "{table}"); | |
| 277 | } | |
| 278 | } | |
| 279 | ||
| 280 | fn event(kind: &str, data: serde_json::Value) -> Event { | |
| 281 | Event { | |
| 282 | id: "evt_1".into(), | |
| 283 | kind: kind.into(), | |
| 284 | source: "repos".into(), | |
| 285 | time: "2026-10-05T00:00:00Z".into(), | |
| 286 | repo_id: Some("rep_1".into()), | |
| 287 | actor: None, | |
| 288 | data, | |
| 289 | } | |
| 290 | } | |
| 291 | ||
| 292 | #[test] | |
| 293 | fn deleting_or_archiving_stops_runs_and_unarchiving_does_not() { | |
| 294 | let named = Some(("rep_1".to_owned(), "acme".to_owned(), "web".to_owned())); | |
| 295 | let data = serde_json::json!({ "repoId": "rep_1", "namespace": "acme", "name": "web", "archived": true }); | |
| 296 | assert_eq!(stopping(&event("repo.deleted", data.clone())), named); | |
| 297 | assert_eq!(stopping(&event("repo.archived", data)), named); | |
| 298 | let unarchived = serde_json::json!({ "repoId": "rep_1", "namespace": "acme", "name": "web", "archived": false }); | |
| 299 | assert_eq!(stopping(&event("repo.unarchived", unarchived.clone())), None); | |
| 300 | assert_eq!(stopping(&event("repo.archived", unarchived)), None); | |
| 301 | assert_eq!(STOP_RUNS.matches('?').count(), 4); | |
| 302 | for sql in DROP_WAITS { | |
| 303 | assert_eq!(g1t_kit::transfer::parameters(sql), 2, "{sql}"); | |
| 304 | } | |
| 305 | } | |
| 306 | ||
| 307 | #[test] | |
| 308 | fn waiting_runs_follow_with_the_names_they_bind() { | |
| 309 | for sql in WAITS_MOVED { | |
| 310 | assert_eq!(g1t_kit::transfer::parameters(sql), 7, "{sql}"); | |
| 311 | } | |
| 312 | assert_eq!(g1t_kit::transfer::parameters(BRANCH_RENAMED), 3); | |
| 313 | } | |
| 314 | } |