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.

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