Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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