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