Skip to content
1,258 linesCodeBlameRaw

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.

GitHub Actions on g1t, part two: running workflows1//! What starts a run: an event on the bus, a schedule, or someone running a
2//! workflow by hand. Each finds the workflows that want it, at the commit
3//! the event is about, and checks their filters.
4
5use g1t_actions::events::{RunInfo, github_events};
6use g1t_actions::workflow::{self, Trigger, Workflow};
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look7use g1t_contracts::access::{self, Capability};
Merge branch 'worktree-agent-a3abfcce648e87dca'8use g1t_contracts::actions::{DispatchArgs, RepositoryDispatchArgs, WorkflowRun};
9use g1t_contracts::events::{Event, caused_by_job};
Free while g1t is being built out; agents can check out their own forks10use g1t_contracts::identity::{AGENT_ID, AGENT_NAME, UsernamesArgs};
GitHub Actions on g1t, part two: running workflows11use g1t_contracts::repos::{Commit, CompareArgs, Comparison, LogArgs, Repo, RepoPath};
12use g1t_contracts::work::{IssueDetail, PullDetail, ViewArgs};
Free while g1t is being built out; agents can check out their own forks13use g1t_contracts::{FailureCode, Outcome, User, new_id};
GitHub Actions on g1t, part two: running workflows14use g1t_kit::now_ms;
15use serde_json::{Map, Value, json};
16use worker::Result;
17
18use crate::plan::NewRun;
19use crate::sync::{Read, WorkflowRow};
20use crate::{API, Actions, SITE, check, fail, payload};
21
22/// What an event is about, worked out once for every workflow it starts.
23struct Subject {
24 /// Where the workflow files are read, and at which commit.
25 source: RepoPath,
26 source_ref: Option<String>,
27 git_ref: String,
28 sha: String,
29 head_ref: Option<String>,
30 base_ref: Option<String>,
31 pull: Option<u32>,
32 /// The branch or tag for `branches`/`tags` filters; for pull requests,
33 /// the branch they merge into.
34 filter_ref: String,
35 /// The files it changes, for `paths` filters; `None` until needed.
36 paths: Option<Vec<String>>,
37 /// For a push, what to compare to find the files.
38 compare: Option<(Option<String>, String)>,
39 payload: Value,
40 title: String,
41 trusted: bool,
Merge branch 'worktree-agent-a3abfcce648e87dca'42 /// Why its runs wait for approval first: a pull request from outside,
43 /// by the repository's approval policy (protection.rs).
44 approval: Option<String>,
GitHub Actions on g1t, part two: running workflows45}
46
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts47/// Whether a deployment's `ref` is a commit's full hash rather than a
48/// branch or tag.
49fn is_commit(name: &str) -> bool {
50 name.len() == 40 && name.chars().all(|c| c.is_ascii_hexdigit())
51}
52
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights53/// Whether whoever a pull request is for is trusted without asking
54/// identity: g1t's agent in work nobody asked it for, or someone whose
55/// role here is known to allow pushing.
56fn trusted_outright(owner: &User, repo: &Repo) -> bool {
57 owner.id == AGENT_ID || access::can(Some(owner), repo, Capability::Push)
58}
59
GitHub Actions on g1t, part two: running workflows60impl Actions {
61 async fn username(&self, id: Option<&str>) -> Result<Option<String>> {
62 let Some(id) = id else { return Ok(None) };
63 if id == AGENT_ID {
64 return Ok(Some(AGENT_NAME.to_owned()));
65 }
66 let names: std::collections::HashMap<String, String> =
67 g1t_kit::call(&self.identity, "usernames", &UsernamesArgs { ids: vec![id.to_owned()] }).await?;
68 Ok(names.get(id).cloned())
69 }
70
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights71 /// Whether whoever a pull request is for (Pull::owner: whoever asked
72 /// g1t for it, or its author) could push to the repository, so its
73 /// runs get the secrets and a token. Anyone else's, a reader's included
74 /// (who may open one on a private repository too), runs without them.
75 /// A change g1t made for someone is trusted as they are.
76 async fn insider(&self, owner: &User, repo: &Repo, ws: &User) -> Result<bool> {
77 if trusted_outright(owner, repo) {
GitHub Actions on g1t, part two: running workflows78 return Ok(true);
79 }
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look80 // Stored authors carry no memberships or grants: ask identity, as
81 // the workspace (which may see anyone's permission).
82 let permission: Outcome<access::PermissionInfo> = g1t_kit::call(
Free while g1t is being built out; agents can check out their own forks83 &self.identity,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look84 "collaborator_permission",
85 &access::CollaboratorPermissionArgs {
86 viewer: Some(ws.clone()),
87 path: RepoPath { namespace: repo.namespace.clone(), name: repo.name.clone() },
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights88 username: owner.username.clone(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look89 },
Free while g1t is being built out; agents can check out their own forks90 )
91 .await?;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look92 Ok(permission
93 .into_result()
94 .ok()
95 .and_then(|info| info.role)
96 .is_some_and(|role| access::allows(role, Capability::Push)))
GitHub Actions on g1t, part two: running workflows97 }
98
99 async fn commits(&self, repo: &Repo, actor: &User, after: &str, before: Option<&str>) -> Result<Vec<Commit>> {
100 let log: Outcome<Vec<Commit>> = g1t_kit::call(
101 &self.repos,
102 "log",
103 &LogArgs {
104 path: RepoPath {
105 namespace: repo.namespace.clone(),
106 name: repo.name.clone(),
107 },
108 viewer: Some(actor.clone()),
109 git_ref: Some(after.to_owned()),
110 limit: 20,
111 },
112 )
113 .await?;
114 let mut commits: Vec<Commit> = log.into_result().unwrap_or_default();
115 if let Some(before) = before
116 && let Some(at) = commits.iter().position(|commit| commit.hash == before)
117 {
118 commits.truncate(at);
119 }
120 // GitHub lists them oldest first, with the head commit last.
121 commits.reverse();
122 Ok(commits)
123 }
124
125 async fn changed_paths(&self, repo: &Repo, actor: &User, base: Option<String>, head: String) -> Result<Vec<String>> {
126 let compared: Outcome<Comparison> = g1t_kit::call(
127 &self.repos,
128 "compare",
129 &CompareArgs {
130 repo_id: repo.id.clone(),
131 viewer: Some(actor.clone()),
132 base,
133 head: Some(head),
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar134 base_branch: None,
GitHub Actions on g1t, part two: running workflows135 },
136 )
137 .await?;
138 Ok(compared.into_result().map(|c| c.files.into_iter().map(|f| f.path).collect()).unwrap_or_default())
139 }
140
141 async fn default_head(&self, repo: &Repo) -> Result<Option<String>> {
142 g1t_kit::call(
143 &self.repos,
144 "head",
145 &g1t_contracts::repos::HeadArgs {
146 repo_id: repo.id.clone(),
147 branch: repo.default_branch.clone(),
148 },
149 )
150 .await
151 }
152
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts153 /// Whether `name` is one of the repository's branches.
154 async fn is_branch(&self, repo: &Repo, ws: &User, name: &str) -> Result<bool> {
155 let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call(
156 &self.repos,
157 "branches",
158 &g1t_contracts::repos::BranchesArgs {
159 path: Self::repo_path(repo),
160 viewer: Some(ws.clone()),
161 },
162 )
163 .await?;
164 Ok(branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == name))
165 }
166
GitHub Actions on g1t, part two: running workflows167 fn repo_path(repo: &Repo) -> RepoPath {
168 RepoPath {
169 namespace: repo.namespace.clone(),
170 name: repo.name.clone(),
171 }
172 }
173
174 /// The subject of an event of `kind`, as GitHub's `event_name`.
175 async fn subject(&self, event: &Event, event_name: &str, action: Option<&str>, repo: &Repo, ws: &User, sender: &str) -> Result<Option<Subject>> {
176 let path = Self::repo_path(repo);
177 let data = &event.data;
178 let on_default = |sha: String, payload: Value, title: String, pull: Option<u32>| Subject {
179 source: path.clone(),
180 source_ref: None,
181 git_ref: format!("refs/heads/{}", repo.default_branch),
182 sha,
183 head_ref: None,
184 base_ref: None,
185 pull,
186 filter_ref: format!("refs/heads/{}", repo.default_branch),
187 paths: None,
188 compare: None,
189 payload,
190 title,
191 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'192 approval: None,
GitHub Actions on g1t, part two: running workflows193 };
194 let view = |number: u32| ViewArgs {
195 repo: path.clone(),
196 number,
197 viewer: Some(ws.clone()),
198 after_seq: 0,
199 };
200 Ok(match event_name {
201 "push" => {
202 let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else {
203 return Ok(None);
204 };
Sidebar: the panels really slide205 // The merge queue's states run merge_group workflows, not push ones.
206 if git_ref.starts_with("refs/heads/g1t-queue/") {
207 return Ok(None);
208 }
GitHub Actions on g1t, part two: running workflows209 let before = data["before"].as_str();
210 let commits = self.commits(repo, ws, after, before).await?;
211 let title = commits.last().map(|c| c.message.lines().next().unwrap_or_default().to_owned()).unwrap_or_default();
212 let mut payload = payload::push(repo, git_ref, before, after, &commits, sender);
213 if let Some(head) = commits.last() {
214 payload["head_commit"] = payload::commit(repo, head);
215 }
216 Some(Subject {
217 source: path.clone(),
218 source_ref: Some(after.to_owned()),
219 git_ref: git_ref.to_owned(),
220 sha: after.to_owned(),
221 head_ref: None,
222 base_ref: None,
223 pull: None,
224 filter_ref: git_ref.to_owned(),
225 paths: None,
226 compare: Some((before.map(str::to_owned), after.to_owned())),
227 payload,
228 title,
229 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'230 approval: None,
GitHub Actions on g1t, part two: running workflows231 })
232 }
Merge branch 'worktree-agent-a3abfcce648e87dca'233 // A branch or tag was made: its own commit, as on GitHub.
234 "create" => {
235 let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else {
236 return Ok(None);
237 };
238 if git_ref.starts_with("refs/heads/g1t-queue/") || !data["before"].is_null() {
239 return Ok(None);
240 }
241 let (ref_type, name) = match (git_ref.strip_prefix("refs/heads/"), git_ref.strip_prefix("refs/tags/")) {
242 (Some(branch), _) => ("branch", branch),
243 (_, Some(tag)) => ("tag", tag),
244 _ => return Ok(None),
245 };
246 let payload = json!({
247 "ref": name,
248 "ref_type": ref_type,
249 "master_branch": repo.default_branch,
250 "description": repo.description,
251 "pusher_type": "user",
252 "repository": payload::repository(repo),
253 "sender": payload::user(sender),
254 });
255 Some(Subject {
256 source: path.clone(),
257 source_ref: Some(after.to_owned()),
258 git_ref: git_ref.to_owned(),
259 sha: after.to_owned(),
260 head_ref: None,
261 base_ref: None,
262 pull: None,
263 filter_ref: git_ref.to_owned(),
264 paths: None,
265 compare: None,
266 payload,
267 title: format!("Created {ref_type} {name}"),
268 trusted: true,
269 approval: None,
270 })
271 }
GitHub Actions on g1t, part two: running workflows272 "pull_request" | "pull_request_target" | "pull_request_review" => {
273 let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) };
274 let detail: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?;
275 let Outcome::Ok(detail) = detail else { return Ok(None) };
276 let pull = &detail.pull;
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar277 let base_ref = pull.base_branch(&repo.default_branch).to_owned();
GitHub Actions on g1t, part two: running workflows278 let mut payload = json!({
279 "action": action,
280 "number": pull.number,
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar281 "pull_request": payload::pull(repo, pull),
GitHub Actions on g1t, part two: running workflows282 "repository": payload::repository(repo),
283 "sender": payload::user(sender),
284 });
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar285 payload::changed(&mut payload, data);
GitHub Actions on g1t, part two: running workflows286 if event_name == "pull_request_review" {
287 let review = detail.comments.iter().rev().find(|c| c.verdict.is_some());
288 payload["review"] = json!({
289 "state": review.and_then(|r| r.verdict).map(|v| format!("{v:?}").to_lowercase()),
290 "body": review.map(|r| r.body.clone()),
291 "user": review.map(|r| payload::user(&r.author.username)),
292 });
293 }
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights294 let trusted = self.insider(pull.owner(), repo, ws).await?;
Merge branch 'worktree-agent-a3abfcce648e87dca'295 // A pull request from outside may wait for approval before
296 // its head's code runs. `pull_request_target` runs the
297 // base's code, and a merged one's run the commit it landed
298 // as, so neither waits.
299 let approval = if event_name != "pull_request_target" && action != Some("closed") {
300 self.approval_needed(repo, pull.owner(), ws).await?
301 } else {
302 None
303 };
GitHub Actions on g1t, part two: running workflows304 let head_ref = payload::head_ref(pull);
305 if event_name == "pull_request_target" {
306 // In the base's context: its workflows, its head.
307 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
308 let mut subject = on_default(sha, payload, pull.title.clone(), Some(pull.number));
309 subject.head_ref = Some(head_ref);
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar310 subject.base_ref = Some(base_ref.clone());
311 subject.filter_ref = format!("refs/heads/{base_ref}");
GitHub Actions on g1t, part two: running workflows312 subject.paths = Some(pull.files.iter().map(|f| f.path.clone()).collect());
313 return Ok(Some(subject));
314 }
A repository has its own sidebar, as settings do315 // A merged pull request's run is on the commit it landed as,
316 // in the repository; otherwise on its head, where that is.
317 let landed = match (action, data["commit"].as_str()) {
318 (Some("closed"), Some(commit)) => Some(commit.to_owned()),
319 _ => None,
320 };
321 let sha = match (&landed, data["commit"].as_str(), &pull.head_commit) {
322 (Some(commit), _, _) => commit.clone(),
323 (None, Some(commit), _) => commit.to_owned(),
324 (None, None, Some(head)) => head.clone(),
325 (None, None, None) => return Ok(None),
326 };
327 let source = match landed {
328 Some(_) => path.clone(),
329 None => pull.fork.clone().unwrap_or_else(|| path.clone()),
GitHub Actions on g1t, part two: running workflows330 };
331 Some(Subject {
A repository has its own sidebar, as settings do332 source,
GitHub Actions on g1t, part two: running workflows333 source_ref: Some(sha.clone()),
334 git_ref: format!("refs/pull/{}/merge", pull.number),
335 sha,
336 head_ref: Some(head_ref),
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar337 base_ref: Some(base_ref.clone()),
GitHub Actions on g1t, part two: running workflows338 pull: Some(pull.number),
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar339 // `branches` filters on pull requests name the base.
340 filter_ref: format!("refs/heads/{base_ref}"),
GitHub Actions on g1t, part two: running workflows341 paths: Some(pull.files.iter().map(|f| f.path.clone()).collect()),
342 compare: None,
343 payload,
344 title: pull.title.clone(),
345 trusted,
Merge branch 'worktree-agent-a3abfcce648e87dca'346 approval,
GitHub Actions on g1t, part two: running workflows347 })
348 }
Actions: workflow_run, workflow.completed, artifacts on the run page, Node 24349 "workflow_run" => {
350 // A run of a workflow_run workflow does not start another,
351 // so two such workflows cannot set each other off.
352 if data["event"].as_str() == Some("workflow_run") {
353 return Ok(None);
354 }
355 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
356 let head_branch = data["ref"].as_str().unwrap_or_default().trim_start_matches("refs/heads/").to_owned();
357 let name = data["workflow"].as_str().unwrap_or_default();
358 let payload = json!({
359 "action": "completed",
360 "workflow_run": {
361 "id": data["runId"],
362 "name": name,
363 "path": data["path"],
364 "event": data["event"],
365 "status": "completed",
366 "conclusion": data["conclusion"],
367 "head_sha": data["sha"],
368 "head_branch": head_branch,
369 "run_number": data["number"],
370 "html_url": format!("{SITE}/{}/{}/actions/runs/{}", repo.namespace, repo.name, data["runId"].as_str().unwrap_or_default()),
371 "pull_requests": data["pull"].as_u64().map(|n| vec![json!({ "number": n })]).unwrap_or_default(),
372 },
373 "workflow": { "name": name, "path": data["path"] },
374 "repository": payload::repository(repo),
375 "sender": payload::user(sender),
376 });
377 let mut subject = on_default(sha, payload, format!("After {name}"), None);
378 // Branch filters apply to the branch the followed run was on.
379 subject.filter_ref = format!("refs/heads/{head_branch}");
380 Some(subject)
381 }
GitHub Actions on g1t, part two: running workflows382 "issues" | "issue_comment" => {
383 let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) };
384 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
385 let issue: Outcome<IssueDetail> = g1t_kit::call(&self.work, "get_issue", &view(number)).await?;
386 let (issue_json, comments, title, on_pull) = match issue {
387 Outcome::Ok(detail) => (payload::issue(repo, &detail.issue), detail.comments, detail.issue.title.clone(), false),
388 Outcome::Fail(_) => {
389 let pull: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?;
390 let Outcome::Ok(detail) = pull else { return Ok(None) };
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar391 (payload::pull_as_issue(repo, &detail.pull), detail.comments, detail.pull.title.clone(), true)
GitHub Actions on g1t, part two: running workflows392 }
393 };
394 let mut payload = json!({
395 "action": action,
396 "issue": issue_json,
397 "repository": payload::repository(repo),
398 "sender": payload::user(sender),
399 });
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar400 payload::changed(&mut payload, data);
GitHub Actions on g1t, part two: running workflows401 if event_name == "issue_comment" {
402 let comment_id = data["commentId"].as_str();
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts403 if action == Some("deleted") {
404 // Gone by now: as the event kept it.
405 match data.get("comment").filter(|kept| kept.is_object()) {
406 Some(kept) => payload["comment"] = payload::deleted_comment(repo, number, kept, on_pull),
407 None => return Ok(None),
408 }
409 } else {
410 let comment = comments.iter().find(|c| Some(c.id.as_str()) == comment_id);
411 // A new comment is the newest; an edited one must be found.
412 let comment = if action == Some("created") { comment.or(comments.last()) } else { comment };
413 match comment {
414 Some(comment) => payload["comment"] = payload::comment(repo, number, comment, on_pull),
415 None => return Ok(None),
416 }
417 }
418 // `edited`: what the body was before.
419 if let Some(changes) = data.get("changes").filter(|changes| changes.is_object()) {
420 payload["changes"] = changes.clone();
GitHub Actions on g1t, part two: running workflows421 }
422 }
423 Some(on_default(sha, payload, title, on_pull.then_some(number)))
424 }
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts425 // A release: on its tag, at the commit the tag named.
426 "release" => {
427 let release = &data["release"];
428 let Some(tag) = data["tagName"].as_str().or_else(|| release["tagName"].as_str()) else { return Ok(None) };
429 let sha = match release["target"].as_str().filter(|target| !target.is_empty()) {
430 Some(target) => target.to_owned(),
431 None => match self.default_head(repo).await? {
432 Some(head) => head,
433 None => return Ok(None),
434 },
435 };
436 let git_ref = format!("refs/tags/{tag}");
437 let mut payload = json!({
438 "action": action,
439 "release": payload::release(repo, release),
440 "repository": payload::repository(repo),
441 "sender": payload::user(sender),
442 });
443 if let Some(changes) = data.get("changes").filter(|changes| changes.is_object()) {
444 payload["changes"] = changes.clone();
445 }
446 let name = release["name"].as_str().filter(|name| !name.is_empty()).unwrap_or(tag);
447 Some(Subject {
448 source: path.clone(),
449 source_ref: Some(sha.clone()),
450 git_ref: git_ref.clone(),
451 sha,
452 head_ref: None,
453 base_ref: None,
454 pull: None,
455 filter_ref: git_ref,
456 paths: None,
457 compare: None,
458 payload,
459 title: format!("Release {name} {}", action.unwrap_or("changed")),
460 trusted: true,
461 approval: None,
462 })
463 }
464 // A deployment, or a new status of one: at the commit deployed,
465 // on the branch or tag it names (none for a bare commit).
466 "deployment" | "deployment_status" => {
467 let deployment = &data["deployment"];
468 let Some(sha) = deployment["sha"].as_str().filter(|sha| !sha.is_empty()).map(str::to_owned) else { return Ok(None) };
469 let named = deployment["ref"].as_str().unwrap_or_default();
470 let git_ref = if named.is_empty() || named == sha || is_commit(named) {
471 String::new()
472 } else if named.starts_with("refs/") {
473 named.to_owned()
474 } else if self.is_branch(repo, ws, named).await? {
475 format!("refs/heads/{named}")
476 } else {
477 format!("refs/tags/{named}")
478 };
479 let environment = deployment["environment"].as_str().unwrap_or_default();
480 let mut payload = json!({
481 "action": "created",
482 "deployment": payload::deployment(repo, deployment),
483 "repository": payload::repository(repo),
484 "sender": payload::user(sender),
485 });
486 let title = if event_name == "deployment_status" {
487 let status = &data["deploymentStatus"];
488 payload["deployment_status"] = payload::deployment_status(repo, status, deployment);
489 format!("Deployment to {environment}: {}", status["state"].as_str().unwrap_or("changed"))
490 } else {
491 format!("Deployment to {environment}")
492 };
493 Some(Subject {
494 source: path.clone(),
495 source_ref: Some(sha.clone()),
496 filter_ref: git_ref.clone(),
497 git_ref,
498 sha,
499 head_ref: None,
500 base_ref: None,
501 pull: None,
502 paths: None,
503 compare: None,
504 payload,
505 title,
506 trusted: true,
507 approval: None,
508 })
509 }
GitHub Actions on g1t, part two: running workflows510 _ => None,
511 })
512 }
513
514 pub async fn on_event(&self, event: &Event) -> Result<()> {
515 let Some(repo_id) = event.repo_id.as_deref() else { return Ok(()) };
Merge branch 'worktree-agent-a3abfcce648e87dca'516 let mut mapped = github_events(&event.kind);
517 // A new branch or tag is also `create`.
518 if event.kind == "git.push" && event.data["before"].is_null() {
519 mapped.push(("create", None));
520 }
GitHub Actions on g1t, part two: running workflows521 let pushed_default = event.kind == "git.push" && event.data["defaultBranch"].as_bool() == Some(true);
522 if mapped.is_empty() && !pushed_default {
523 return Ok(());
524 }
525 let Some((repo, ws)) = self.repo_by_id(repo_id).await? else { return Ok(()) };
526 if pushed_default {
527 self.sync(&repo, &ws).await?;
528 }
Mirrors in work, Actions, deployments and the inbox529 // A mirror runs only what its state says (mirrored.rs).
530 let copied_in = event.kind == "git.push" && event.data["mirrored"].as_bool() == Some(true);
531 let policy = crate::mirrored::policy(repo.mirror.as_ref(), copied_in);
532 if !policy.runs {
533 return Ok(());
534 }
Merge branch 'worktree-agent-a3abfcce648e87dca'535 // What a workflow job's own token did starts no workflows, as on
536 // GitHub, so a workflow cannot set itself off; only
537 // `workflow_dispatch` and `repository_dispatch` do.
538 if let Some(run) = caused_by_job(&event.data) {
539 worker::console_log!("actions: {} {} came from run {run}'s token; no workflows start for it", event.kind, event.id);
540 return Ok(());
541 }
GitHub Actions on g1t, part two: running workflows542 let sender = self.username(event.actor.as_deref()).await?.unwrap_or_else(|| repo.namespace.clone());
543 for (event_name, action) in mapped {
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for544 // Issues and comments start the default branch's workflows,
545 // which the synced table lists: when none listens, nothing is
546 // read from git. Agents make many of these events.
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts547 // Deployments' statuses are as frequent (every g1t.page build
548 // reports several), so they look there first too.
549 if matches!(event_name, "issues" | "issue_comment" | "deployment" | "deployment_status")
550 && self.listens(repo_id, event_name).await? == Some(false)
551 {
Fewer Artifacts reads: the store is asked for a handle only when needed, objects are kept in the isolate, and issue events read no workflows nobody listens for552 continue;
553 }
GitHub Actions on g1t, part two: running workflows554 let Some(mut subject) = self.subject(event, event_name, action, &repo, &ws, &sender).await? else {
555 continue;
556 };
Mirrors in work, Actions, deployments and the inbox557 // A change to workflows made on the remote, by someone g1t
558 // knows nothing of, waits before it may use this repository's
559 // secrets.
560 if copied_in && matches!(event_name, "push" | "create") {
561 if subject.paths.is_none() {
562 let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone()));
563 subject.paths = Some(self.changed_paths(&repo, &ws, base, head).await?);
564 }
565 if crate::mirrored::touches_workflows(subject.paths.as_deref().unwrap_or_default())
566 && let Some(mirror) = &repo.mirror
567 {
568 subject.approval = subject.approval.take().or_else(|| Some(crate::mirrored::copied_workflows(&mirror.remote)));
569 }
570 }
571 // A pull request from a fork reads the fork's files.
572 let read = if subject.source == Self::repo_path(&repo) {
573 self.read_for(&repo, &ws, subject.source_ref.as_deref(), policy.github).await?
574 } else {
575 self.read_workflows(&subject.source, &ws, subject.source_ref.as_deref()).await?
576 };
A repository has its own sidebar, as settings do577 // A pull request's head runs each workflow once, however many
578 // events say it is there (marked ready, and pushed).
579 let key = match subject.pull {
580 Some(number) if event_name.starts_with("pull_request") && event_name != "pull_request_review" => {
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts581 // Reopened or made a draft again runs anew, at a head
582 // that may have run before.
583 let phase = match action {
584 Some("closed") => "closed".to_owned(),
585 Some(again @ ("reopened" | "converted_to_draft")) => format!("{again}:{}", event.id),
586 _ => "open".to_owned(),
587 };
A repository has its own sidebar, as settings do588 format!("{event_name}:{number}:{}:{phase}", subject.sha)
589 }
Merge branch 'worktree-agent-a3abfcce648e87dca'590 _ if event_name == "create" => format!("{}:create", event.id),
A repository has its own sidebar, as settings do591 _ => event.id.clone(),
592 };
593 self.start_matching(&repo, &ws, read, &mut subject, event_name, action, &key, event.actor.as_deref(), &sender)
GitHub Actions on g1t, part two: running workflows594 .await?;
595 }
596 Ok(())
597 }
598
599 #[allow(clippy::too_many_arguments)]
600 async fn start_matching(
601 &self,
602 repo: &Repo,
603 ws: &User,
604 read: Read,
605 subject: &mut Subject,
606 event_name: &str,
607 action: Option<&str>,
608 event_key: &str,
609 actor_id: Option<&str>,
610 sender: &str,
611 ) -> Result<()> {
612 for file in read.files {
613 let parsed = workflow::parse(&file.source);
614 let workflow = match parsed {
615 Ok(workflow) => workflow,
616 Err(problem) => {
617 // A push shows a broken workflow as a failed run, as GitHub does.
618 if event_name == "push" && file.source.contains("on") {
619 self.record_invalid(repo, &file.path, &file.source, subject, event_key, actor_id, sender, &problem)
620 .await?;
621 }
622 continue;
623 }
624 };
625 let Some(trigger) = workflow.trigger(event_name) else { continue };
Actions: workflow_run, workflow.completed, artifacts on the run page, Node 24626 // workflow_run follows the workflows it names.
627 if event_name == "workflow_run" {
628 let followed = subject.payload["workflow_run"]["name"].as_str().unwrap_or_default();
629 if !trigger.workflows.iter().any(|name| name == followed) {
630 continue;
631 }
632 }
GitHub Actions on g1t, part two: running workflows633 if !trigger.wants_type(action) || !self.passes(repo, ws, trigger, subject, event_name).await? {
634 continue;
635 }
636 if self.disabled(&repo.id, &file.path).await? {
637 continue;
638 }
Mirrors in work, Actions, deployments and the inbox639 // On a mirror the remote may deploy too: a workflow that deploys
640 // waits for approval (mirrored.rs).
641 let held = crate::mirrored::policy(repo.mirror.as_ref(), false)
642 .hold
643 .zip(crate::mirrored::deploys_to(&workflow))
644 .map(|(remote, environment)| crate::mirrored::held(&remote, &environment));
GitHub Actions on g1t, part two: running workflows645 self.create_run(NewRun {
646 repo: repo.clone(),
647 path: file.path,
648 source: file.source,
649 info: self.run_info(repo, &workflow, event_name, subject, sender, actor_id),
650 workflow,
651 action: action.map(str::to_owned),
652 pull: subject.pull,
653 title: subject.title.clone(),
654 inputs: Map::new(),
655 event_key: event_key.to_owned(),
656 actor_id: actor_id.map(str::to_owned),
657 actor: Some(sender.to_owned()),
658 trusted: subject.trusted,
Mirrors in work, Actions, deployments and the inbox659 approval: subject.approval.clone().or(held),
GitHub Actions on g1t, part two: running workflows660 })
661 .await?;
662 }
663 Ok(())
664 }
665
666 /// Whether the branch, tag and path filters let the event through.
667 async fn passes(&self, repo: &Repo, ws: &User, trigger: &Trigger, subject: &mut Subject, event_name: &str) -> Result<bool> {
668 let git_ref = subject.filter_ref.as_str();
669 if let Some(tag) = git_ref.strip_prefix("refs/tags/") {
670 // A tag push runs a workflow that filters tags, or filters nothing.
671 if trigger.tags.is_set() {
672 if !trigger.tags.allows(tag) {
673 return Ok(false);
674 }
675 } else if trigger.branches.is_set() {
676 return Ok(false);
677 }
678 // Paths are not checked for tags, as on GitHub.
679 return Ok(true);
680 }
681 let branch = git_ref.strip_prefix("refs/heads/").unwrap_or(git_ref);
682 if trigger.branches.is_set() {
683 if !trigger.branches.allows(branch) {
684 return Ok(false);
685 }
686 } else if event_name == "push" && trigger.tags.is_set() {
687 return Ok(false);
688 }
689 if trigger.paths.is_set() {
690 if subject.paths.is_none() {
691 let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone()));
692 subject.paths = Some(self.changed_paths(repo, ws, base, head).await?);
693 }
694 if !trigger.paths.allows_paths(subject.paths.as_deref().unwrap_or_default()) {
695 return Ok(false);
696 }
697 }
698 Ok(true)
699 }
700
701 async fn disabled(&self, repo_id: &str, path: &str) -> Result<bool> {
702 let row = self
703 .db
704 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND path = ?")
705 .bind(&[repo_id.into(), path.into()])?
706 .first::<WorkflowRow>(None)
707 .await?;
708 Ok(row.is_some_and(|row| row.state == "disabled"))
709 }
710
711 fn run_info(&self, repo: &Repo, workflow: &Workflow, event_name: &str, subject: &Subject, sender: &str, actor_id: Option<&str>) -> RunInfo {
712 RunInfo {
713 repository: format!("{}/{}", repo.namespace, repo.name),
714 repository_id: repo.id.clone(),
715 default_branch: repo.default_branch.clone(),
716 event_name: event_name.to_owned(),
717 event: subject.payload.clone(),
718 git_ref: subject.git_ref.clone(),
719 sha: subject.sha.clone(),
720 head_ref: subject.head_ref.clone(),
721 base_ref: subject.base_ref.clone(),
722 actor: sender.to_owned(),
723 actor_id: actor_id.unwrap_or_default().to_owned(),
724 triggering_actor: sender.to_owned(),
725 run_id: String::new(),
726 run_number: 0,
727 run_attempt: 1,
728 workflow: workflow.name.clone().unwrap_or_default(),
729 workflow_path: String::new(),
730 server_url: SITE.to_owned(),
731 api_url: API.to_owned(),
732 }
733 }
734
735 #[allow(clippy::too_many_arguments)]
736 async fn record_invalid(
737 &self,
738 repo: &Repo,
739 path: &str,
740 source: &str,
741 subject: &Subject,
742 event_key: &str,
743 actor_id: Option<&str>,
744 sender: &str,
745 problem: &str,
746 ) -> Result<()> {
747 let row = self.workflow_row(repo, path, path, source).await?;
748 self.record_failed_run(&row, subject.git_ref.as_str(), &subject.sha, event_key, actor_id, sender, problem).await
749 }
750
751 /// Scheduled workflows whose cron fires this minute, on the default branch.
752 pub async fn run_schedules(&self, minute: u64) -> Result<()> {
753 let rows = self
754 .db
755 .prepare("SELECT * FROM workflows WHERE state = 'active' AND crons != '[]' AND error IS NULL")
756 .all()
757 .await?
758 .results::<WorkflowRow>()?;
759 for row in rows {
760 let crons: Vec<String> = serde_json::from_str(&row.crons).unwrap_or_default();
761 let Some(cron) = crons.iter().find(|cron| g1t_actions::cron::Schedule::parse(cron).is_ok_and(|s| s.fires_at(minute))) else {
762 continue;
763 };
764 let Ok(workflow) = workflow::parse(&row.source) else { continue };
Mirrors in work, Actions, deployments and the inbox765 // Schedules wait while a repository is archived, or a mirror runs
766 // nothing; a deleted one is not found.
767 let Some((repo, _ws)) = self
768 .repo_by_id(&row.repo_id)
769 .await?
770 .filter(|(repo, _)| !repo.archived() && crate::mirrored::policy(repo.mirror.as_ref(), false).runs)
771 else {
772 continue;
773 };
GitHub Actions on g1t, part two: running workflows774 let Some(sha) = self.default_head(&repo).await? else { continue };
775 let payload = json!({ "schedule": cron, "repository": payload::repository(&repo), "workflow": row.path });
776 let mut subject = Subject {
777 source: Self::repo_path(&repo),
778 source_ref: None,
779 git_ref: format!("refs/heads/{}", repo.default_branch),
780 sha,
781 head_ref: None,
782 base_ref: None,
783 pull: None,
784 filter_ref: String::new(),
785 paths: None,
786 compare: None,
787 payload,
788 title: format!("Scheduled: {cron}"),
789 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'790 approval: None,
GitHub Actions on g1t, part two: running workflows791 };
792 subject.filter_ref = subject.git_ref.clone();
793 let info = self.run_info(&repo, &workflow, "schedule", &subject, &repo.namespace, None);
794 self.create_run(NewRun {
795 repo: repo.clone(),
796 path: row.path.clone(),
797 source: row.source.clone(),
798 workflow,
799 info,
800 action: None,
801 pull: None,
802 title: subject.title.clone(),
803 inputs: Map::new(),
804 event_key: format!("schedule:{minute}"),
805 actor_id: None,
806 actor: None,
807 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'808 approval: None,
GitHub Actions on g1t, part two: running workflows809 })
810 .await?;
811 }
812 Ok(())
813 }
814
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look815 /// `dispatch`: someone with the Write role runs a workflow that has
816 /// `workflow_dispatch`.
GitHub Actions on g1t, part two: running workflows817 pub async fn dispatch(&self, a: DispatchArgs) -> Result<Outcome<WorkflowRun>> {
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look818 let repo = check!(self.may(&a.actor, &a.repo, Capability::Run).await?);
819 if repo.archived() {
820 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
GitHub Actions on g1t, part two: running workflows821 }
822 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
823 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
824 };
825 let git_ref = a.git_ref.clone().unwrap_or_else(|| repo.default_branch.clone());
826 let full_ref = if git_ref.starts_with("refs/") {
827 git_ref.clone()
828 } else {
829 // A branch if there is one by that name, otherwise a tag.
830 let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call(
831 &self.repos,
832 "branches",
833 &g1t_contracts::repos::BranchesArgs {
834 path: Self::repo_path(&repo),
835 viewer: Some(ws.clone()),
836 },
837 )
838 .await?;
839 let is_branch = branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == git_ref);
840 format!("refs/{}/{git_ref}", if is_branch { "heads" } else { "tags" })
841 };
842 let short = full_ref.trim_start_matches("refs/heads/").trim_start_matches("refs/tags/").to_owned();
Mirrors in work, Actions, deployments and the inbox843 let policy = crate::mirrored::policy(repo.mirror.as_ref(), false);
844 if let Some(mirror) = repo.mirror.as_ref().filter(|_| !policy.runs) {
845 return Ok(fail(FailureCode::Forbidden, crate::mirrored::refused(&repo.namespace, &repo.name, mirror)));
846 }
847 let read = self.read_for(&repo, &ws, Some(&short), policy.github).await?;
GitHub Actions on g1t, part two: running workflows848 let Some(sha) = read.head.clone() else {
849 return Ok(fail(FailureCode::NotFound, format!("There is no branch or tag called {short}.")));
850 };
Search across all of g1t, Explore, and a command palette851 // A workflow is named by its file (`build.yml`), its path, or its id
852 // (`wfl_…`), which stands for the path it was read from.
853 let by_id = if a.workflow.starts_with("wfl_") {
854 self.db
855 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND id = ?")
856 .bind(&[repo.id.as_str().into(), a.workflow.as_str().into()])?
857 .first::<WorkflowRow>(None)
858 .await?
859 .map(|row| row.path)
860 } else {
861 None
862 };
863 let named = by_id.as_deref().unwrap_or(&a.workflow);
864 let wanted = named.trim_start_matches(".g1t/workflows/");
GitHub Actions on g1t, part two: running workflows865 let Some(file) = read.files.iter().find(|file| {
Search across all of g1t, Explore, and a command palette866 file.path.rsplit('/').next() == Some(wanted) || file.path == named
GitHub Actions on g1t, part two: running workflows867 }) else {
868 return Ok(fail(FailureCode::NotFound, format!("There is no workflow {wanted} on {short}.")));
869 };
870 let workflow = match workflow::parse(&file.source) {
871 Ok(workflow) => workflow,
872 Err(problem) => return Ok(fail(FailureCode::Invalid, format!("The workflow does not read: {problem}"))),
873 };
874 let Some(trigger) = workflow.trigger("workflow_dispatch") else {
875 return Ok(fail(FailureCode::Invalid, "That workflow cannot be run by hand: it has no `workflow_dispatch` trigger."));
876 };
877 let inputs = check!(dispatch_inputs(trigger, &a.inputs));
878 let payload = json!({
879 "inputs": inputs,
880 "ref": full_ref,
881 "repository": payload::repository(&repo),
882 "sender": payload::user(&a.actor.username),
883 "workflow": file.path,
884 });
885 let subject = Subject {
886 source: Self::repo_path(&repo),
887 source_ref: Some(sha.clone()),
888 git_ref: full_ref.clone(),
889 sha,
890 head_ref: None,
891 base_ref: None,
892 pull: None,
893 filter_ref: full_ref,
894 paths: None,
895 compare: None,
896 payload,
897 title: format!("{} run by {}", workflow.display_name(&file.path), a.actor.username),
898 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'899 approval: None,
GitHub Actions on g1t, part two: running workflows900 };
901 let info = self.run_info(&repo, &workflow, "workflow_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
902 let created = self
903 .create_run(NewRun {
904 repo: repo.clone(),
905 path: file.path.clone(),
906 source: file.source.clone(),
907 workflow,
908 info,
909 action: None,
910 pull: None,
911 title: subject.title.clone(),
912 inputs,
913 event_key: format!("dispatch:{}", new_id("dsp", now_ms())),
914 actor_id: Some(a.actor.id.clone()),
915 actor: Some(a.actor.username.clone()),
916 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'917 approval: None,
GitHub Actions on g1t, part two: running workflows918 })
919 .await?;
920 match created {
921 Some(id) => self.run_summary(&id).await,
922 None => Ok(fail(FailureCode::Conflict, "It did not start.")),
923 }
924 }
Merge branch 'worktree-agent-a3abfcce648e87dca'925
926 /// `repository_dispatch`: an outside event, by name, starts the default
927 /// branch's workflows that run `on: repository_dispatch` with that type
928 /// (or with no `types`). A workflow job's token may send one: this,
929 /// with `workflow_dispatch`, is how a workflow starts another.
930 pub async fn repository_dispatch(&self, a: RepositoryDispatchArgs) -> Result<Outcome<u32>> {
931 let repo = check!(self.may(&a.actor, &a.repo, Capability::Push).await?);
932 if repo.archived() {
933 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
934 }
935 let event_type = a.event_type.trim().to_owned();
936 if event_type.is_empty() || event_type.chars().count() > 100 {
937 return Ok(fail(FailureCode::Invalid, "event_type is 1 to 100 characters."));
938 }
939 let client_payload = match a.client_payload {
940 Value::Null => json!({}),
941 Value::Object(map) if map.len() <= 10 => Value::Object(map),
942 Value::Object(_) => return Ok(fail(FailureCode::Invalid, "client_payload has at most 10 top-level properties.")),
943 _ => return Ok(fail(FailureCode::Invalid, "client_payload is a JSON object.")),
944 };
945 if serde_json::to_string(&client_payload).map_or(0, |text| text.len()) > 64 * 1024 {
946 return Ok(fail(FailureCode::Invalid, "client_payload is at most 64 KB."));
947 }
948 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
949 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
950 };
Mirrors in work, Actions, deployments and the inbox951 let policy = crate::mirrored::policy(repo.mirror.as_ref(), false);
952 if let Some(mirror) = repo.mirror.as_ref().filter(|_| !policy.runs) {
953 return Ok(fail(FailureCode::Forbidden, crate::mirrored::refused(&repo.namespace, &repo.name, mirror)));
954 }
955 let read = self.read_for(&repo, &ws, Some(&repo.default_branch), policy.github).await?;
Merge branch 'worktree-agent-a3abfcce648e87dca'956 let Some(sha) = read.head.clone() else {
957 return Ok(fail(FailureCode::NotFound, "The repository has no default branch to run on yet."));
958 };
959 let git_ref = format!("refs/heads/{}", repo.default_branch);
960 let payload = json!({
961 "action": event_type,
962 "branch": repo.default_branch,
963 "client_payload": client_payload,
964 "repository": payload::repository(&repo),
965 "sender": payload::user(&a.actor.username),
966 });
967 let key = format!("repository_dispatch:{}", new_id("dsp", now_ms()));
968 let mut started = 0u32;
969 for file in read.files {
970 let Ok(workflow) = workflow::parse(&file.source) else { continue };
971 let Some(trigger) = workflow.trigger("repository_dispatch") else { continue };
972 if !trigger.wants_type(Some(&event_type)) || self.disabled(&repo.id, &file.path).await? {
973 continue;
974 }
975 let subject = Subject {
976 source: Self::repo_path(&repo),
977 source_ref: Some(sha.clone()),
978 git_ref: git_ref.clone(),
979 sha: sha.clone(),
980 head_ref: None,
981 base_ref: None,
982 pull: None,
983 filter_ref: git_ref.clone(),
984 paths: None,
985 compare: None,
986 payload: payload.clone(),
987 title: event_type.clone(),
988 trusted: true,
989 approval: None,
990 };
991 let info = self.run_info(&repo, &workflow, "repository_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
992 let created = self
993 .create_run(NewRun {
994 repo: repo.clone(),
995 path: file.path.clone(),
996 source: file.source.clone(),
997 workflow,
998 info,
999 action: Some(event_type.clone()),
1000 pull: None,
1001 title: subject.title.clone(),
1002 inputs: Map::new(),
1003 event_key: key.clone(),
1004 actor_id: Some(a.actor.id.clone()),
1005 actor: Some(a.actor.username.clone()),
1006 trusted: true,
1007 approval: None,
1008 })
1009 .await?;
1010 if created.is_some() {
1011 started += 1;
1012 }
1013 }
1014 Ok(Outcome::Ok(started))
1015 }
GitHub Actions on g1t, part two: running workflows1016}
1017
Sidebar: the panels really slide1018#[derive(serde::Deserialize)]
1019#[serde(rename_all = "camelCase")]
1020pub struct MergeGroupArgs {
1021 pub repo_id: String,
1022 pub entry: String,
1023 pub sha: String,
1024 pub head_ref: String,
1025 #[serde(default)]
1026 pub base_sha: Option<String>,
1027 pub number: u32,
1028 #[serde(default)]
1029 pub ahead: Vec<u32>,
1030}
1031
1032impl Actions {
1033 /// `merge_group`: the merge queue built a state and its checks passed.
1034 /// Starts the workflows that run `on: merge_group` on it, as GitHub's
1035 /// queue does, and says how many started; the queue waits for their
1036 /// statuses on that commit.
1037 pub async fn merge_group(&self, a: MergeGroupArgs) -> Result<Outcome<Value>> {
1038 let Some((repo, ws)) = self.repo_by_id(&a.repo_id).await? else {
1039 return Ok(Outcome::Ok(json!({ "runs": 0 })));
1040 };
1041 let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&a.sha)).await?;
1042 let head_commit = self.commits(&repo, &ws, &a.sha, None).await?.pop();
1043 let payload = json!({
1044 "action": "checks_requested",
1045 "merge_group": {
1046 "head_sha": a.sha,
1047 "head_ref": a.head_ref,
1048 "base_sha": a.base_sha,
1049 "base_ref": format!("refs/heads/{}", repo.default_branch),
1050 "head_commit": head_commit.as_ref().map(|c| payload::commit(&repo, c)),
1051 },
1052 "repository": payload::repository(&repo),
1053 "sender": payload::user(&repo.namespace),
1054 });
1055 let mut started = 0u32;
1056 for file in read.files {
1057 let Ok(workflow) = workflow::parse(&file.source) else { continue };
1058 let Some(trigger) = workflow.trigger("merge_group") else { continue };
1059 if !trigger.wants_type(Some("checks_requested")) || self.disabled(&repo.id, &file.path).await? {
1060 continue;
1061 }
1062 // Branch filters on merge_group name the branch it merges into.
1063 if trigger.branches.is_set() && !trigger.branches.allows(&repo.default_branch) {
1064 continue;
1065 }
1066 let ahead = if a.ahead.is_empty() {
1067 String::new()
1068 } else {
1069 format!(" after {}", a.ahead.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", "))
1070 };
1071 let subject = Subject {
1072 source: Self::repo_path(&repo),
1073 source_ref: Some(a.sha.clone()),
1074 git_ref: a.head_ref.clone(),
1075 sha: a.sha.clone(),
1076 head_ref: None,
1077 base_ref: Some(repo.default_branch.clone()),
1078 pull: Some(a.number),
1079 filter_ref: format!("refs/heads/{}", repo.default_branch),
1080 paths: None,
1081 compare: None,
1082 payload: payload.clone(),
1083 title: format!("Merge queue: #{}{ahead}", a.number),
1084 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'1085 approval: None,
Sidebar: the panels really slide1086 };
1087 let info = self.run_info(&repo, &workflow, "merge_group", &subject, &repo.namespace, None);
1088 let created = self
1089 .create_run(NewRun {
1090 repo: repo.clone(),
1091 path: file.path.clone(),
1092 source: file.source.clone(),
1093 workflow,
1094 info,
1095 action: Some("checks_requested".to_owned()),
1096 pull: Some(a.number),
1097 title: subject.title.clone(),
1098 inputs: Map::new(),
1099 event_key: format!("merge_group:{}:{}", a.entry, a.sha),
1100 actor_id: None,
1101 actor: None,
1102 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'1103 approval: None,
Sidebar: the panels really slide1104 })
1105 .await?;
1106 if created.is_some() {
1107 started += 1;
1108 }
1109 }
1110 Ok(Outcome::Ok(json!({ "runs": started })))
GitHub Actions on g1t, part two: running workflows1111 }
1112}
1113
1114/// The inputs of a manual run: what was given, checked against the
1115/// workflow's declared inputs, with their defaults filled in.
1116fn dispatch_inputs(trigger: &Trigger, given: &Map<String, Value>) -> Outcome<Map<String, Value>> {
1117 let mut inputs = Map::new();
1118 for (name, spec) in &trigger.inputs {
1119 let kind = spec.get("type").and_then(Value::as_str).unwrap_or("string");
1120 let value = given.get(name).cloned().or_else(|| spec.get("default").cloned());
1121 let required = spec.get("required").and_then(Value::as_bool).unwrap_or(false);
1122 let value = match value {
1123 Some(Value::Null) | None if required => return fail(FailureCode::Invalid, format!("The input `{name}` is required.")),
1124 Some(Value::Null) | None => match kind {
1125 "boolean" => Value::Bool(false),
1126 _ => Value::String(String::new()),
1127 },
1128 Some(value) => match kind {
1129 "boolean" => Value::Bool(match &value {
1130 Value::Bool(flag) => *flag,
1131 Value::String(text) => text == "true",
1132 _ => false,
1133 }),
1134 "number" => match &value {
1135 Value::Number(_) => value,
1136 Value::String(text) => match text.parse::<f64>().ok().and_then(serde_json::Number::from_f64) {
1137 Some(number) => Value::Number(number),
1138 None => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
1139 },
1140 _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
1141 },
1142 "choice" => {
1143 let text = g1t_actions::expr::to_text(&value);
1144 let options: Vec<String> =
1145 spec.get("options").and_then(Value::as_array).map(|o| o.iter().map(g1t_actions::expr::to_text).collect()).unwrap_or_default();
1146 if !options.is_empty() && !options.contains(&text) {
1147 return fail(FailureCode::Invalid, format!("The input `{name}` is one of {}.", options.join(", ")));
1148 }
1149 Value::String(text)
1150 }
1151 _ => Value::String(g1t_actions::expr::to_text(&value)),
1152 },
1153 };
1154 inputs.insert(name.clone(), value);
1155 }
1156 Outcome::Ok(inputs)
1157}
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights1158
1159#[cfg(test)]
1160mod tests {
1161 use super::*;
1162 use g1t_contracts::work::{Pull, g1t_author};
1163 use g1t_contracts::{Membership, PrincipalKind};
1164
1165 fn repo() -> Repo {
1166 serde_json::from_value(json!({
1167 "id": "rep_1", "namespace": "acme", "name": "web", "description": null, "isPrivate": true,
1168 "ownerId": "ws_1", "defaultBranch": "main", "forkOf": null, "createdAt": ""
1169 }))
1170 .unwrap()
1171 }
1172
1173 fn person(id: &str, username: &str) -> User {
1174 User { id: id.into(), username: username.into(), kind: PrincipalKind::User, ..User::default() }
1175 }
1176
1177 fn made_for(asker: User) -> Pull {
1178 serde_json::from_value(json!({
1179 "id": "pr_1", "repoId": "rep_1", "number": 14, "issue": 12, "title": "Fix it", "body": null,
1180 "agent": "g1t", "runtime": "hosted", "status": "open",
1181 "fork": { "namespace": "pulls", "name": "pr_1" }, "forkRepoId": "rep_f",
1182 "branch": null, "headCommit": "abc", "mergeBase": null, "mergedBy": null, "mergedAt": null,
1183 "supersededBy": null, "checkStatus": null,
1184 "author": g1t_author(), "requestedBy": asker,
1185 "createdAt": "", "updatedAt": ""
1186 }))
1187 .unwrap()
1188 }
1189
1190 #[test]
1191 fn g1t_s_change_for_someone_is_trusted_as_they_are() {
1192 // Stored people carry no memberships, so identity is asked about
1193 // them; being g1t's change gives it nothing more.
1194 let pull = made_for(person("usr_2", "ana"));
1195 assert!(!trusted_outright(pull.owner(), &repo()));
1196 // Someone known to be able to push is trusted at once.
1197 let mut member = person("usr_1", "syntaqx");
1198 member.workspaces.push(Membership::member("acme"));
1199 let pull = made_for(member);
1200 assert!(trusted_outright(pull.owner(), &repo()));
1201 }
1202
1203 #[test]
1204 fn the_payload_names_g1t_as_its_user_and_who_asked_for_it() {
1205 let pull = made_for(person("usr_1", "syntaqx"));
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1206 let event = payload::pull(&repo(), &pull);
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights1207 assert_eq!(event["user"]["login"], "g1t");
1208 assert_eq!(event["user"]["type"], "Bot");
1209 assert_eq!(event["requested_by"]["login"], "syntaqx");
1210 assert_eq!(event["requested_by"]["type"], "User");
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1211 let as_issue = payload::pull_as_issue(&repo(), &pull);
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights1212 assert_eq!(as_issue["user"]["login"], "g1t");
1213 assert_eq!(as_issue["requested_by"]["login"], "syntaqx");
1214 }
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1215
1216 #[test]
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts1217 fn releases_deployments_and_deleted_comments_read_as_githubs() {
1218 let release = payload::release(
1219 &repo(),
1220 &json!({ "id": "rel_1", "tagName": "v1.2.0", "target": "abc", "name": null, "body": "Notes", "draft": false,
1221 "prerelease": true, "author": "ana", "createdAt": "2026-10-08T00:00:00Z", "publishedAt": "2026-10-08T00:00:00Z" }),
1222 );
1223 assert_eq!(release["tag_name"], "v1.2.0");
1224 assert_eq!(release["name"], "v1.2.0");
1225 assert_eq!(release["prerelease"], true);
1226 assert_eq!(release["author"]["login"], "ana");
1227 assert_eq!(release["html_url"], "https://g1t.sh/acme/web/releases/tag/v1.2.0");
1228 let deployment = json!({ "id": "dep_1", "sha": "abc", "ref": "main", "environment": "staging", "creator": "ana",
1229 "production_environment": false, "created_at": "t", "updated_at": "t" });
1230 let status = payload::deployment_status(&repo(), &json!({ "id": "dst_1", "state": "success", "environment_url": "https://s.example", "log_url": null, "creator": "g1t", "created_at": "t" }), &deployment);
1231 assert_eq!(status["state"], "success");
1232 assert_eq!(status["environment"], "staging");
1233 assert_eq!(status["environment_url"], "https://s.example");
1234 assert_eq!(payload::deployment(&repo(), &deployment)["payload"], json!({}));
1235 let gone = payload::deleted_comment(&repo(), 7, &json!({ "id": "cmt_1", "body": "hi", "author": { "id": "usr_1", "username": "bo" }, "createdAt": "t" }), true);
1236 assert_eq!(gone["user"]["login"], "bo");
1237 assert_eq!(gone["html_url"], "https://g1t.sh/acme/web/pull/7#cmt_1");
1238 assert!(is_commit("0123456789abcdef0123456789abcdef01234567"));
1239 assert!(!is_commit("main"));
1240 }
1241
1242 #[test]
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1243 fn a_pull_request_names_its_own_base_labels_and_milestone() {
1244 let mut pull = made_for(person("usr_1", "syntaqx"));
1245 let event = payload::pull(&repo(), &pull);
1246 assert_eq!(event["base"]["ref"], repo().default_branch);
1247 pull.base = Some("release/1.x".into());
1248 pull.labels = vec!["bug".into()];
1249 pull.milestone = Some(g1t_contracts::work::MilestoneRef { number: 2, title: "1.1".into() });
1250 let event = payload::pull(&repo(), &pull);
1251 assert_eq!(event["base"]["ref"], "release/1.x");
1252 assert_eq!(event["labels"], serde_json::json!([{ "name": "bug" }]));
1253 assert_eq!(event["milestone"]["title"], "1.1");
1254 let mut labeled = serde_json::json!({ "action": "labeled" });
1255 payload::changed(&mut labeled, &serde_json::json!({ "label": { "name": "bug", "color": "d73a4a" } }));
1256 assert_eq!(labeled["label"]["color"], "d73a4a");
1257 }
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights1258}

This file's history is long; its oldest lines are credited to the oldest commit read.