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.

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