Skip to content
1,212 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 }
Merge branch 'worktree-agent-a3abfcce648e87dca'529 // What a workflow job's own token did starts no workflows, as on
530 // GitHub, so a workflow cannot set itself off; only
531 // `workflow_dispatch` and `repository_dispatch` do.
532 if let Some(run) = caused_by_job(&event.data) {
533 worker::console_log!("actions: {} {} came from run {run}'s token; no workflows start for it", event.kind, event.id);
534 return Ok(());
535 }
GitHub Actions on g1t, part two: running workflows536 let sender = self.username(event.actor.as_deref()).await?.unwrap_or_else(|| repo.namespace.clone());
537 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 for538 // Issues and comments start the default branch's workflows,
539 // which the synced table lists: when none listens, nothing is
540 // read from git. Agents make many of these events.
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts541 // Deployments' statuses are as frequent (every g1t.page build
542 // reports several), so they look there first too.
543 if matches!(event_name, "issues" | "issue_comment" | "deployment" | "deployment_status")
544 && self.listens(repo_id, event_name).await? == Some(false)
545 {
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 for546 continue;
547 }
GitHub Actions on g1t, part two: running workflows548 let Some(mut subject) = self.subject(event, event_name, action, &repo, &ws, &sender).await? else {
549 continue;
550 };
551 let read = self.read_workflows(&subject.source, &ws, subject.source_ref.as_deref()).await?;
A repository has its own sidebar, as settings do552 // A pull request's head runs each workflow once, however many
553 // events say it is there (marked ready, and pushed).
554 let key = match subject.pull {
555 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 timeouts556 // Reopened or made a draft again runs anew, at a head
557 // that may have run before.
558 let phase = match action {
559 Some("closed") => "closed".to_owned(),
560 Some(again @ ("reopened" | "converted_to_draft")) => format!("{again}:{}", event.id),
561 _ => "open".to_owned(),
562 };
A repository has its own sidebar, as settings do563 format!("{event_name}:{number}:{}:{phase}", subject.sha)
564 }
Merge branch 'worktree-agent-a3abfcce648e87dca'565 _ if event_name == "create" => format!("{}:create", event.id),
A repository has its own sidebar, as settings do566 _ => event.id.clone(),
567 };
568 self.start_matching(&repo, &ws, read, &mut subject, event_name, action, &key, event.actor.as_deref(), &sender)
GitHub Actions on g1t, part two: running workflows569 .await?;
570 }
571 Ok(())
572 }
573
574 #[allow(clippy::too_many_arguments)]
575 async fn start_matching(
576 &self,
577 repo: &Repo,
578 ws: &User,
579 read: Read,
580 subject: &mut Subject,
581 event_name: &str,
582 action: Option<&str>,
583 event_key: &str,
584 actor_id: Option<&str>,
585 sender: &str,
586 ) -> Result<()> {
587 for file in read.files {
588 let parsed = workflow::parse(&file.source);
589 let workflow = match parsed {
590 Ok(workflow) => workflow,
591 Err(problem) => {
592 // A push shows a broken workflow as a failed run, as GitHub does.
593 if event_name == "push" && file.source.contains("on") {
594 self.record_invalid(repo, &file.path, &file.source, subject, event_key, actor_id, sender, &problem)
595 .await?;
596 }
597 continue;
598 }
599 };
600 let Some(trigger) = workflow.trigger(event_name) else { continue };
Actions: workflow_run, workflow.completed, artifacts on the run page, Node 24601 // workflow_run follows the workflows it names.
602 if event_name == "workflow_run" {
603 let followed = subject.payload["workflow_run"]["name"].as_str().unwrap_or_default();
604 if !trigger.workflows.iter().any(|name| name == followed) {
605 continue;
606 }
607 }
GitHub Actions on g1t, part two: running workflows608 if !trigger.wants_type(action) || !self.passes(repo, ws, trigger, subject, event_name).await? {
609 continue;
610 }
611 if self.disabled(&repo.id, &file.path).await? {
612 continue;
613 }
614 self.create_run(NewRun {
615 repo: repo.clone(),
616 path: file.path,
617 source: file.source,
618 info: self.run_info(repo, &workflow, event_name, subject, sender, actor_id),
619 workflow,
620 action: action.map(str::to_owned),
621 pull: subject.pull,
622 title: subject.title.clone(),
623 inputs: Map::new(),
624 event_key: event_key.to_owned(),
625 actor_id: actor_id.map(str::to_owned),
626 actor: Some(sender.to_owned()),
627 trusted: subject.trusted,
Merge branch 'worktree-agent-a3abfcce648e87dca'628 approval: subject.approval.clone(),
GitHub Actions on g1t, part two: running workflows629 })
630 .await?;
631 }
632 Ok(())
633 }
634
635 /// Whether the branch, tag and path filters let the event through.
636 async fn passes(&self, repo: &Repo, ws: &User, trigger: &Trigger, subject: &mut Subject, event_name: &str) -> Result<bool> {
637 let git_ref = subject.filter_ref.as_str();
638 if let Some(tag) = git_ref.strip_prefix("refs/tags/") {
639 // A tag push runs a workflow that filters tags, or filters nothing.
640 if trigger.tags.is_set() {
641 if !trigger.tags.allows(tag) {
642 return Ok(false);
643 }
644 } else if trigger.branches.is_set() {
645 return Ok(false);
646 }
647 // Paths are not checked for tags, as on GitHub.
648 return Ok(true);
649 }
650 let branch = git_ref.strip_prefix("refs/heads/").unwrap_or(git_ref);
651 if trigger.branches.is_set() {
652 if !trigger.branches.allows(branch) {
653 return Ok(false);
654 }
655 } else if event_name == "push" && trigger.tags.is_set() {
656 return Ok(false);
657 }
658 if trigger.paths.is_set() {
659 if subject.paths.is_none() {
660 let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone()));
661 subject.paths = Some(self.changed_paths(repo, ws, base, head).await?);
662 }
663 if !trigger.paths.allows_paths(subject.paths.as_deref().unwrap_or_default()) {
664 return Ok(false);
665 }
666 }
667 Ok(true)
668 }
669
670 async fn disabled(&self, repo_id: &str, path: &str) -> Result<bool> {
671 let row = self
672 .db
673 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND path = ?")
674 .bind(&[repo_id.into(), path.into()])?
675 .first::<WorkflowRow>(None)
676 .await?;
677 Ok(row.is_some_and(|row| row.state == "disabled"))
678 }
679
680 fn run_info(&self, repo: &Repo, workflow: &Workflow, event_name: &str, subject: &Subject, sender: &str, actor_id: Option<&str>) -> RunInfo {
681 RunInfo {
682 repository: format!("{}/{}", repo.namespace, repo.name),
683 repository_id: repo.id.clone(),
684 default_branch: repo.default_branch.clone(),
685 event_name: event_name.to_owned(),
686 event: subject.payload.clone(),
687 git_ref: subject.git_ref.clone(),
688 sha: subject.sha.clone(),
689 head_ref: subject.head_ref.clone(),
690 base_ref: subject.base_ref.clone(),
691 actor: sender.to_owned(),
692 actor_id: actor_id.unwrap_or_default().to_owned(),
693 triggering_actor: sender.to_owned(),
694 run_id: String::new(),
695 run_number: 0,
696 run_attempt: 1,
697 workflow: workflow.name.clone().unwrap_or_default(),
698 workflow_path: String::new(),
699 server_url: SITE.to_owned(),
700 api_url: API.to_owned(),
701 }
702 }
703
704 #[allow(clippy::too_many_arguments)]
705 async fn record_invalid(
706 &self,
707 repo: &Repo,
708 path: &str,
709 source: &str,
710 subject: &Subject,
711 event_key: &str,
712 actor_id: Option<&str>,
713 sender: &str,
714 problem: &str,
715 ) -> Result<()> {
716 let row = self.workflow_row(repo, path, path, source).await?;
717 self.record_failed_run(&row, subject.git_ref.as_str(), &subject.sha, event_key, actor_id, sender, problem).await
718 }
719
720 /// Scheduled workflows whose cron fires this minute, on the default branch.
721 pub async fn run_schedules(&self, minute: u64) -> Result<()> {
722 let rows = self
723 .db
724 .prepare("SELECT * FROM workflows WHERE state = 'active' AND crons != '[]' AND error IS NULL")
725 .all()
726 .await?
727 .results::<WorkflowRow>()?;
728 for row in rows {
729 let crons: Vec<String> = serde_json::from_str(&row.crons).unwrap_or_default();
730 let Some(cron) = crons.iter().find(|cron| g1t_actions::cron::Schedule::parse(cron).is_ok_and(|s| s.fires_at(minute))) else {
731 continue;
732 };
733 let Ok(workflow) = workflow::parse(&row.source) else { continue };
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look734 // Schedules wait while a repository is archived; a deleted one is not found.
735 let Some((repo, _ws)) = self.repo_by_id(&row.repo_id).await?.filter(|(repo, _)| !repo.archived()) else { continue };
GitHub Actions on g1t, part two: running workflows736 let Some(sha) = self.default_head(&repo).await? else { continue };
737 let payload = json!({ "schedule": cron, "repository": payload::repository(&repo), "workflow": row.path });
738 let mut subject = Subject {
739 source: Self::repo_path(&repo),
740 source_ref: None,
741 git_ref: format!("refs/heads/{}", repo.default_branch),
742 sha,
743 head_ref: None,
744 base_ref: None,
745 pull: None,
746 filter_ref: String::new(),
747 paths: None,
748 compare: None,
749 payload,
750 title: format!("Scheduled: {cron}"),
751 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'752 approval: None,
GitHub Actions on g1t, part two: running workflows753 };
754 subject.filter_ref = subject.git_ref.clone();
755 let info = self.run_info(&repo, &workflow, "schedule", &subject, &repo.namespace, None);
756 self.create_run(NewRun {
757 repo: repo.clone(),
758 path: row.path.clone(),
759 source: row.source.clone(),
760 workflow,
761 info,
762 action: None,
763 pull: None,
764 title: subject.title.clone(),
765 inputs: Map::new(),
766 event_key: format!("schedule:{minute}"),
767 actor_id: None,
768 actor: None,
769 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'770 approval: None,
GitHub Actions on g1t, part two: running workflows771 })
772 .await?;
773 }
774 Ok(())
775 }
776
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look777 /// `dispatch`: someone with the Write role runs a workflow that has
778 /// `workflow_dispatch`.
GitHub Actions on g1t, part two: running workflows779 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 look780 let repo = check!(self.may(&a.actor, &a.repo, Capability::Run).await?);
781 if repo.archived() {
782 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
GitHub Actions on g1t, part two: running workflows783 }
784 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
785 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
786 };
787 let git_ref = a.git_ref.clone().unwrap_or_else(|| repo.default_branch.clone());
788 let full_ref = if git_ref.starts_with("refs/") {
789 git_ref.clone()
790 } else {
791 // A branch if there is one by that name, otherwise a tag.
792 let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call(
793 &self.repos,
794 "branches",
795 &g1t_contracts::repos::BranchesArgs {
796 path: Self::repo_path(&repo),
797 viewer: Some(ws.clone()),
798 },
799 )
800 .await?;
801 let is_branch = branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == git_ref);
802 format!("refs/{}/{git_ref}", if is_branch { "heads" } else { "tags" })
803 };
804 let short = full_ref.trim_start_matches("refs/heads/").trim_start_matches("refs/tags/").to_owned();
805 let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&short)).await?;
806 let Some(sha) = read.head.clone() else {
807 return Ok(fail(FailureCode::NotFound, format!("There is no branch or tag called {short}.")));
808 };
Search across all of g1t, Explore, and a command palette809 // A workflow is named by its file (`build.yml`), its path, or its id
810 // (`wfl_…`), which stands for the path it was read from.
811 let by_id = if a.workflow.starts_with("wfl_") {
812 self.db
813 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND id = ?")
814 .bind(&[repo.id.as_str().into(), a.workflow.as_str().into()])?
815 .first::<WorkflowRow>(None)
816 .await?
817 .map(|row| row.path)
818 } else {
819 None
820 };
821 let named = by_id.as_deref().unwrap_or(&a.workflow);
822 let wanted = named.trim_start_matches(".g1t/workflows/");
GitHub Actions on g1t, part two: running workflows823 let Some(file) = read.files.iter().find(|file| {
Search across all of g1t, Explore, and a command palette824 file.path.rsplit('/').next() == Some(wanted) || file.path == named
GitHub Actions on g1t, part two: running workflows825 }) else {
826 return Ok(fail(FailureCode::NotFound, format!("There is no workflow {wanted} on {short}.")));
827 };
828 let workflow = match workflow::parse(&file.source) {
829 Ok(workflow) => workflow,
830 Err(problem) => return Ok(fail(FailureCode::Invalid, format!("The workflow does not read: {problem}"))),
831 };
832 let Some(trigger) = workflow.trigger("workflow_dispatch") else {
833 return Ok(fail(FailureCode::Invalid, "That workflow cannot be run by hand: it has no `workflow_dispatch` trigger."));
834 };
835 let inputs = check!(dispatch_inputs(trigger, &a.inputs));
836 let payload = json!({
837 "inputs": inputs,
838 "ref": full_ref,
839 "repository": payload::repository(&repo),
840 "sender": payload::user(&a.actor.username),
841 "workflow": file.path,
842 });
843 let subject = Subject {
844 source: Self::repo_path(&repo),
845 source_ref: Some(sha.clone()),
846 git_ref: full_ref.clone(),
847 sha,
848 head_ref: None,
849 base_ref: None,
850 pull: None,
851 filter_ref: full_ref,
852 paths: None,
853 compare: None,
854 payload,
855 title: format!("{} run by {}", workflow.display_name(&file.path), a.actor.username),
856 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'857 approval: None,
GitHub Actions on g1t, part two: running workflows858 };
859 let info = self.run_info(&repo, &workflow, "workflow_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
860 let created = self
861 .create_run(NewRun {
862 repo: repo.clone(),
863 path: file.path.clone(),
864 source: file.source.clone(),
865 workflow,
866 info,
867 action: None,
868 pull: None,
869 title: subject.title.clone(),
870 inputs,
871 event_key: format!("dispatch:{}", new_id("dsp", now_ms())),
872 actor_id: Some(a.actor.id.clone()),
873 actor: Some(a.actor.username.clone()),
874 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'875 approval: None,
GitHub Actions on g1t, part two: running workflows876 })
877 .await?;
878 match created {
879 Some(id) => self.run_summary(&id).await,
880 None => Ok(fail(FailureCode::Conflict, "It did not start.")),
881 }
882 }
Merge branch 'worktree-agent-a3abfcce648e87dca'883
884 /// `repository_dispatch`: an outside event, by name, starts the default
885 /// branch's workflows that run `on: repository_dispatch` with that type
886 /// (or with no `types`). A workflow job's token may send one: this,
887 /// with `workflow_dispatch`, is how a workflow starts another.
888 pub async fn repository_dispatch(&self, a: RepositoryDispatchArgs) -> Result<Outcome<u32>> {
889 let repo = check!(self.may(&a.actor, &a.repo, Capability::Push).await?);
890 if repo.archived() {
891 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
892 }
893 let event_type = a.event_type.trim().to_owned();
894 if event_type.is_empty() || event_type.chars().count() > 100 {
895 return Ok(fail(FailureCode::Invalid, "event_type is 1 to 100 characters."));
896 }
897 let client_payload = match a.client_payload {
898 Value::Null => json!({}),
899 Value::Object(map) if map.len() <= 10 => Value::Object(map),
900 Value::Object(_) => return Ok(fail(FailureCode::Invalid, "client_payload has at most 10 top-level properties.")),
901 _ => return Ok(fail(FailureCode::Invalid, "client_payload is a JSON object.")),
902 };
903 if serde_json::to_string(&client_payload).map_or(0, |text| text.len()) > 64 * 1024 {
904 return Ok(fail(FailureCode::Invalid, "client_payload is at most 64 KB."));
905 }
906 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
907 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
908 };
909 let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&repo.default_branch)).await?;
910 let Some(sha) = read.head.clone() else {
911 return Ok(fail(FailureCode::NotFound, "The repository has no default branch to run on yet."));
912 };
913 let git_ref = format!("refs/heads/{}", repo.default_branch);
914 let payload = json!({
915 "action": event_type,
916 "branch": repo.default_branch,
917 "client_payload": client_payload,
918 "repository": payload::repository(&repo),
919 "sender": payload::user(&a.actor.username),
920 });
921 let key = format!("repository_dispatch:{}", new_id("dsp", now_ms()));
922 let mut started = 0u32;
923 for file in read.files {
924 let Ok(workflow) = workflow::parse(&file.source) else { continue };
925 let Some(trigger) = workflow.trigger("repository_dispatch") else { continue };
926 if !trigger.wants_type(Some(&event_type)) || self.disabled(&repo.id, &file.path).await? {
927 continue;
928 }
929 let subject = Subject {
930 source: Self::repo_path(&repo),
931 source_ref: Some(sha.clone()),
932 git_ref: git_ref.clone(),
933 sha: sha.clone(),
934 head_ref: None,
935 base_ref: None,
936 pull: None,
937 filter_ref: git_ref.clone(),
938 paths: None,
939 compare: None,
940 payload: payload.clone(),
941 title: event_type.clone(),
942 trusted: true,
943 approval: None,
944 };
945 let info = self.run_info(&repo, &workflow, "repository_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
946 let created = self
947 .create_run(NewRun {
948 repo: repo.clone(),
949 path: file.path.clone(),
950 source: file.source.clone(),
951 workflow,
952 info,
953 action: Some(event_type.clone()),
954 pull: None,
955 title: subject.title.clone(),
956 inputs: Map::new(),
957 event_key: key.clone(),
958 actor_id: Some(a.actor.id.clone()),
959 actor: Some(a.actor.username.clone()),
960 trusted: true,
961 approval: None,
962 })
963 .await?;
964 if created.is_some() {
965 started += 1;
966 }
967 }
968 Ok(Outcome::Ok(started))
969 }
GitHub Actions on g1t, part two: running workflows970}
971
Sidebar: the panels really slide972#[derive(serde::Deserialize)]
973#[serde(rename_all = "camelCase")]
974pub struct MergeGroupArgs {
975 pub repo_id: String,
976 pub entry: String,
977 pub sha: String,
978 pub head_ref: String,
979 #[serde(default)]
980 pub base_sha: Option<String>,
981 pub number: u32,
982 #[serde(default)]
983 pub ahead: Vec<u32>,
984}
985
986impl Actions {
987 /// `merge_group`: the merge queue built a state and its checks passed.
988 /// Starts the workflows that run `on: merge_group` on it, as GitHub's
989 /// queue does, and says how many started; the queue waits for their
990 /// statuses on that commit.
991 pub async fn merge_group(&self, a: MergeGroupArgs) -> Result<Outcome<Value>> {
992 let Some((repo, ws)) = self.repo_by_id(&a.repo_id).await? else {
993 return Ok(Outcome::Ok(json!({ "runs": 0 })));
994 };
995 let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&a.sha)).await?;
996 let head_commit = self.commits(&repo, &ws, &a.sha, None).await?.pop();
997 let payload = json!({
998 "action": "checks_requested",
999 "merge_group": {
1000 "head_sha": a.sha,
1001 "head_ref": a.head_ref,
1002 "base_sha": a.base_sha,
1003 "base_ref": format!("refs/heads/{}", repo.default_branch),
1004 "head_commit": head_commit.as_ref().map(|c| payload::commit(&repo, c)),
1005 },
1006 "repository": payload::repository(&repo),
1007 "sender": payload::user(&repo.namespace),
1008 });
1009 let mut started = 0u32;
1010 for file in read.files {
1011 let Ok(workflow) = workflow::parse(&file.source) else { continue };
1012 let Some(trigger) = workflow.trigger("merge_group") else { continue };
1013 if !trigger.wants_type(Some("checks_requested")) || self.disabled(&repo.id, &file.path).await? {
1014 continue;
1015 }
1016 // Branch filters on merge_group name the branch it merges into.
1017 if trigger.branches.is_set() && !trigger.branches.allows(&repo.default_branch) {
1018 continue;
1019 }
1020 let ahead = if a.ahead.is_empty() {
1021 String::new()
1022 } else {
1023 format!(" after {}", a.ahead.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", "))
1024 };
1025 let subject = Subject {
1026 source: Self::repo_path(&repo),
1027 source_ref: Some(a.sha.clone()),
1028 git_ref: a.head_ref.clone(),
1029 sha: a.sha.clone(),
1030 head_ref: None,
1031 base_ref: Some(repo.default_branch.clone()),
1032 pull: Some(a.number),
1033 filter_ref: format!("refs/heads/{}", repo.default_branch),
1034 paths: None,
1035 compare: None,
1036 payload: payload.clone(),
1037 title: format!("Merge queue: #{}{ahead}", a.number),
1038 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'1039 approval: None,
Sidebar: the panels really slide1040 };
1041 let info = self.run_info(&repo, &workflow, "merge_group", &subject, &repo.namespace, None);
1042 let created = self
1043 .create_run(NewRun {
1044 repo: repo.clone(),
1045 path: file.path.clone(),
1046 source: file.source.clone(),
1047 workflow,
1048 info,
1049 action: Some("checks_requested".to_owned()),
1050 pull: Some(a.number),
1051 title: subject.title.clone(),
1052 inputs: Map::new(),
1053 event_key: format!("merge_group:{}:{}", a.entry, a.sha),
1054 actor_id: None,
1055 actor: None,
1056 trusted: true,
Merge branch 'worktree-agent-a3abfcce648e87dca'1057 approval: None,
Sidebar: the panels really slide1058 })
1059 .await?;
1060 if created.is_some() {
1061 started += 1;
1062 }
1063 }
1064 Ok(Outcome::Ok(json!({ "runs": started })))
GitHub Actions on g1t, part two: running workflows1065 }
1066}
1067
1068/// The inputs of a manual run: what was given, checked against the
1069/// workflow's declared inputs, with their defaults filled in.
1070fn dispatch_inputs(trigger: &Trigger, given: &Map<String, Value>) -> Outcome<Map<String, Value>> {
1071 let mut inputs = Map::new();
1072 for (name, spec) in &trigger.inputs {
1073 let kind = spec.get("type").and_then(Value::as_str).unwrap_or("string");
1074 let value = given.get(name).cloned().or_else(|| spec.get("default").cloned());
1075 let required = spec.get("required").and_then(Value::as_bool).unwrap_or(false);
1076 let value = match value {
1077 Some(Value::Null) | None if required => return fail(FailureCode::Invalid, format!("The input `{name}` is required.")),
1078 Some(Value::Null) | None => match kind {
1079 "boolean" => Value::Bool(false),
1080 _ => Value::String(String::new()),
1081 },
1082 Some(value) => match kind {
1083 "boolean" => Value::Bool(match &value {
1084 Value::Bool(flag) => *flag,
1085 Value::String(text) => text == "true",
1086 _ => false,
1087 }),
1088 "number" => match &value {
1089 Value::Number(_) => value,
1090 Value::String(text) => match text.parse::<f64>().ok().and_then(serde_json::Number::from_f64) {
1091 Some(number) => Value::Number(number),
1092 None => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
1093 },
1094 _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
1095 },
1096 "choice" => {
1097 let text = g1t_actions::expr::to_text(&value);
1098 let options: Vec<String> =
1099 spec.get("options").and_then(Value::as_array).map(|o| o.iter().map(g1t_actions::expr::to_text).collect()).unwrap_or_default();
1100 if !options.is_empty() && !options.contains(&text) {
1101 return fail(FailureCode::Invalid, format!("The input `{name}` is one of {}.", options.join(", ")));
1102 }
1103 Value::String(text)
1104 }
1105 _ => Value::String(g1t_actions::expr::to_text(&value)),
1106 },
1107 };
1108 inputs.insert(name.clone(), value);
1109 }
1110 Outcome::Ok(inputs)
1111}
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights1112
1113#[cfg(test)]
1114mod tests {
1115 use super::*;
1116 use g1t_contracts::work::{Pull, g1t_author};
1117 use g1t_contracts::{Membership, PrincipalKind};
1118
1119 fn repo() -> Repo {
1120 serde_json::from_value(json!({
1121 "id": "rep_1", "namespace": "acme", "name": "web", "description": null, "isPrivate": true,
1122 "ownerId": "ws_1", "defaultBranch": "main", "forkOf": null, "createdAt": ""
1123 }))
1124 .unwrap()
1125 }
1126
1127 fn person(id: &str, username: &str) -> User {
1128 User { id: id.into(), username: username.into(), kind: PrincipalKind::User, ..User::default() }
1129 }
1130
1131 fn made_for(asker: User) -> Pull {
1132 serde_json::from_value(json!({
1133 "id": "pr_1", "repoId": "rep_1", "number": 14, "issue": 12, "title": "Fix it", "body": null,
1134 "agent": "g1t", "runtime": "hosted", "status": "open",
1135 "fork": { "namespace": "pulls", "name": "pr_1" }, "forkRepoId": "rep_f",
1136 "branch": null, "headCommit": "abc", "mergeBase": null, "mergedBy": null, "mergedAt": null,
1137 "supersededBy": null, "checkStatus": null,
1138 "author": g1t_author(), "requestedBy": asker,
1139 "createdAt": "", "updatedAt": ""
1140 }))
1141 .unwrap()
1142 }
1143
1144 #[test]
1145 fn g1t_s_change_for_someone_is_trusted_as_they_are() {
1146 // Stored people carry no memberships, so identity is asked about
1147 // them; being g1t's change gives it nothing more.
1148 let pull = made_for(person("usr_2", "ana"));
1149 assert!(!trusted_outright(pull.owner(), &repo()));
1150 // Someone known to be able to push is trusted at once.
1151 let mut member = person("usr_1", "syntaqx");
1152 member.workspaces.push(Membership::member("acme"));
1153 let pull = made_for(member);
1154 assert!(trusted_outright(pull.owner(), &repo()));
1155 }
1156
1157 #[test]
1158 fn the_payload_names_g1t_as_its_user_and_who_asked_for_it() {
1159 let pull = made_for(person("usr_1", "syntaqx"));
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1160 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 rights1161 assert_eq!(event["user"]["login"], "g1t");
1162 assert_eq!(event["user"]["type"], "Bot");
1163 assert_eq!(event["requested_by"]["login"], "syntaqx");
1164 assert_eq!(event["requested_by"]["type"], "User");
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1165 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 rights1166 assert_eq!(as_issue["user"]["login"], "g1t");
1167 assert_eq!(as_issue["requested_by"]["login"], "syntaqx");
1168 }
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1169
1170 #[test]
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts1171 fn releases_deployments_and_deleted_comments_read_as_githubs() {
1172 let release = payload::release(
1173 &repo(),
1174 &json!({ "id": "rel_1", "tagName": "v1.2.0", "target": "abc", "name": null, "body": "Notes", "draft": false,
1175 "prerelease": true, "author": "ana", "createdAt": "2026-10-08T00:00:00Z", "publishedAt": "2026-10-08T00:00:00Z" }),
1176 );
1177 assert_eq!(release["tag_name"], "v1.2.0");
1178 assert_eq!(release["name"], "v1.2.0");
1179 assert_eq!(release["prerelease"], true);
1180 assert_eq!(release["author"]["login"], "ana");
1181 assert_eq!(release["html_url"], "https://g1t.sh/acme/web/releases/tag/v1.2.0");
1182 let deployment = json!({ "id": "dep_1", "sha": "abc", "ref": "main", "environment": "staging", "creator": "ana",
1183 "production_environment": false, "created_at": "t", "updated_at": "t" });
1184 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);
1185 assert_eq!(status["state"], "success");
1186 assert_eq!(status["environment"], "staging");
1187 assert_eq!(status["environment_url"], "https://s.example");
1188 assert_eq!(payload::deployment(&repo(), &deployment)["payload"], json!({}));
1189 let gone = payload::deleted_comment(&repo(), 7, &json!({ "id": "cmt_1", "body": "hi", "author": { "id": "usr_1", "username": "bo" }, "createdAt": "t" }), true);
1190 assert_eq!(gone["user"]["login"], "bo");
1191 assert_eq!(gone["html_url"], "https://g1t.sh/acme/web/pull/7#cmt_1");
1192 assert!(is_commit("0123456789abcdef0123456789abcdef01234567"));
1193 assert!(!is_commit("main"));
1194 }
1195
1196 #[test]
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1197 fn a_pull_request_names_its_own_base_labels_and_milestone() {
1198 let mut pull = made_for(person("usr_1", "syntaqx"));
1199 let event = payload::pull(&repo(), &pull);
1200 assert_eq!(event["base"]["ref"], repo().default_branch);
1201 pull.base = Some("release/1.x".into());
1202 pull.labels = vec!["bug".into()];
1203 pull.milestone = Some(g1t_contracts::work::MilestoneRef { number: 2, title: "1.1".into() });
1204 let event = payload::pull(&repo(), &pull);
1205 assert_eq!(event["base"]["ref"], "release/1.x");
1206 assert_eq!(event["labels"], serde_json::json!([{ "name": "bug" }]));
1207 assert_eq!(event["milestone"]["title"], "1.1");
1208 let mut labeled = serde_json::json!({ "action": "labeled" });
1209 payload::changed(&mut labeled, &serde_json::json!({ "label": { "name": "bug", "color": "d73a4a" } }));
1210 assert_eq!(labeled["label"]["color"], "d73a4a");
1211 }
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights1212}

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