Skip to content

g1t/apps/api/src/openapi.rs

1,177 lines50,602 bytesCodeBlame
1//! The OpenAPI document, generated from the same list the routes are.
2//!
3//! The docs site builds its API reference from a copy of this document,
4//! `apps/docs/src/data/openapi.json`. A test keeps the copy current: run
5//! `G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi` to rewrite it.
6
7use g1t_contracts::scopes::scope_for;
8use serde_json::{Map, Value, json};
9
10use crate::about::AboutOp;
11use crate::deployments::DeploymentsOp;
12use crate::operations::Op;
13use crate::rules::RulesOp;
14use crate::security::SecurityOp;
15use crate::rest::{ROUTES, Route};
16
17/// The sections of the API reference: a name, what it covers, and its
18/// operations in the order a reader meets them.
19const SECTIONS: &[(&str, &str, &[Op])] = &[
20 (
21 "Accounts",
22 "Signing in from a tool, who a token acts as, and your email addresses.",
23 &[Op::Whoami, Op::ListEmails, Op::AddEmail, Op::RemoveEmail, Op::UpdateEmailSettings],
24 ),
25 (
26 "Notifications",
27 "Your inbox: a thread for each thing you were told about (an issue, a pull request, a workflow on a branch, a deployment), why you were told, and what you subscribe to and watch. Your own: personal tokens and sessions only.",
28 &[
29 Op::ListNotifications,
30 Op::MarkNotificationsRead,
31 Op::GetNotificationThread,
32 Op::MarkThreadRead,
33 Op::MarkThreadDone,
34 Op::SaveThread,
35 Op::SnoozeThread,
36 Op::GetThreadSubscription,
37 Op::SetThreadSubscription,
38 Op::DeleteThreadSubscription,
39 Op::GetRepoSubscription,
40 Op::SetRepoSubscription,
41 Op::DeleteRepoSubscription,
42 Op::ListWatchedRepos,
43 ],
44 ),
45 (
46 "Pinned projects",
47 "The projects you keep at the top of a workspace's sidebar, in your order, up to eight a workspace. Your own: personal tokens and sessions only.",
48 &[Op::ListPinnedProjects, Op::PinProject, Op::UnpinProject, Op::ReorderPinnedProjects],
49 ),
50 (
51 "Projects",
52 "A project is what a workspace builds and runs, from a repository or a root directory in one. Each says what it is, where it runs and where to find it: its homepage, docs and other links.",
53 &[Op::ListProjects, Op::GetProject, Op::UpdateProject],
54 ),
55 (
56 "Workspaces",
57 "A workspace owns repositories and is the first part of their address. People and agents work in workspaces.",
58 &[Op::GetWorkspace, Op::CreateWorkspace, Op::UpdateWorkspace, Op::DeleteWorkspace],
59 ),
60 (
61 "Invites",
62 "While g1t is invite-only, every new account needs an invite. Your invites, and inviting people into a workspace by email.",
63 &[
64 Op::ListInvites,
65 Op::CreateInvite,
66 Op::RevokeInvite,
67 Op::ListWorkspaceInvites,
68 Op::InviteMember,
69 Op::RevokeWorkspaceInvite,
70 ],
71 ),
72 (
73 "Billing",
74 "A workspace's usage, its budget, its AI credit, its invoices and its AI Gateway requests. Members read them; owners change the budget and buy credit, as people. g1t's agents never change billing.",
75 &[
76 Op::GetUsage,
77 Op::GetBudget,
78 Op::SetBudget,
79 Op::GetAiCredit,
80 Op::BuyAiCredit,
81 Op::ListInvoices,
82 Op::GetBillingDetails,
83 Op::ListGatewayRequests,
84 ],
85 ),
86 (
87 "Repositories",
88 "A repository, how it handles pull requests, and its timeline: renaming, archiving, moving and deleting it.",
89 &[
90 Op::ListRepos,
91 Op::CreateRepo,
92 Op::GetRepo,
93 Op::UpdateRepo,
94 Op::RenameRepo,
95 Op::RenameBranch,
96 Op::SetRepoVisibility,
97 Op::ArchiveRepo,
98 Op::UnarchiveRepo,
99 Op::TransferRepo,
100 Op::DeleteRepo,
101 Op::ListDeletedRepos,
102 Op::RestoreRepo,
103 Op::PurgeRepo,
104 Op::GetRepoSettings,
105 Op::UpdateRepoSettings,
106 Op::ListCheckNames,
107 Op::GetCodeownersErrors,
108 Op::ListEvents,
109 ],
110 ),
111 (
112 "Repository insights",
113 "What a repository's default branch says about it, read in the background and kept by commit: the languages it is written in, who made it, and its license.",
114 &[Op::About(AboutOp::GetLanguages), Op::About(AboutOp::ListContributors), Op::About(AboutOp::GetLicense)],
115 ),
116 (
117 "Stars",
118 "Starring a repository, to keep it and to say you like it: who starred one, and what you starred.",
119 &[
120 Op::About(AboutOp::ListStargazers),
121 Op::About(AboutOp::ListStarred),
122 Op::About(AboutOp::CheckStarred),
123 Op::About(AboutOp::Star),
124 Op::About(AboutOp::Unstar),
125 ],
126 ),
127 (
128 "Releases",
129 "A release is a tag published with a title and notes. The latest is the newest published one that is neither a draft nor a prerelease.",
130 &[
131 Op::About(AboutOp::ListReleases),
132 Op::About(AboutOp::CreateRelease),
133 Op::About(AboutOp::GetLatestRelease),
134 Op::About(AboutOp::GetReleaseByTag),
135 Op::About(AboutOp::GetRelease),
136 Op::About(AboutOp::UpdateRelease),
137 Op::About(AboutOp::DeleteRelease),
138 ],
139 ),
140 (
141 "Access",
142 "Who can do what in a repository: repository roles, people given a role on one repository (outside collaborators when they are not members), invitations, and a workspace's base permission.",
143 &[
144 Op::ListCollaborators,
145 Op::AddCollaborator,
146 Op::UpdateCollaborator,
147 Op::RemoveCollaborator,
148 Op::GetCollaboratorPermission,
149 Op::ListRepoInvitations,
150 Op::RevokeRepoInvitation,
151 Op::ListMyRepoInvitations,
152 Op::AcceptRepoInvitation,
153 Op::DeclineRepoInvitation,
154 Op::SetBasePermission,
155 Op::ListOutsideCollaborators,
156 ],
157 ),
158 (
159 "Teams",
160 "Groups of a workspace's members: given a role on repositories together, mentioned together as @workspace/team, and asked to review together. Any member may create a team; the workspace's owners and the team's maintainers manage it.",
161 &[
162 Op::ListTeams,
163 Op::CreateTeam,
164 Op::GetTeam,
165 Op::UpdateTeam,
166 Op::DeleteTeam,
167 Op::ListTeamMembers,
168 Op::SetTeamMember,
169 Op::RemoveTeamMember,
170 Op::ListChildTeams,
171 Op::ListTeamRepos,
172 Op::SetTeamRepo,
173 Op::RemoveTeamRepo,
174 Op::SetTeamReviewAssignment,
175 Op::ListUserTeams,
176 ],
177 ),
178 (
179 "Security",
180 "Secrets found in what is pushed and in a repository's history, and dependencies with known vulnerabilities: listing the alerts, and dismissing or reopening them.",
181 &[Op::ListSecurityAlerts, Op::DismissSecurityAlert, Op::ReopenSecurityAlert],
182 ),
183 (
184 "Secret scanning",
185 "Secrets found in pushes and history, where each one is, pushing past push protection with a reason (and asking for approval when the workspace delegates bypasses), checking with a secret's issuer whether it still works, and custom patterns.",
186 &[
187 Op::Security(SecurityOp::ListSecretAlerts),
188 Op::Security(SecurityOp::GetSecretAlert),
189 Op::Security(SecurityOp::UpdateSecretAlert),
190 Op::Security(SecurityOp::ListSecretLocations),
191 Op::Security(SecurityOp::BypassPushProtection),
192 Op::Security(SecurityOp::CheckSecretValidity),
193 Op::Security(SecurityOp::ListBypassRequests),
194 Op::Security(SecurityOp::ReviewBypassRequest),
195 Op::Security(SecurityOp::ListCustomPatterns),
196 Op::Security(SecurityOp::CreateCustomPattern),
197 Op::Security(SecurityOp::UpdateCustomPattern),
198 Op::Security(SecurityOp::DeleteCustomPattern),
199 Op::Security(SecurityOp::DryRunCustomPattern),
200 ],
201 ),
202 (
203 "Code scanning",
204 "Results of static analysis tools, uploaded as SARIF: alerts on the default branch, the analyses that made them, uploads, and putting g1t on an alert to fix it.",
205 &[
206 Op::Security(SecurityOp::ListCodeAlerts),
207 Op::Security(SecurityOp::GetCodeAlert),
208 Op::Security(SecurityOp::UpdateCodeAlert),
209 Op::Security(SecurityOp::ListAnalyses),
210 Op::Security(SecurityOp::UploadSarif),
211 Op::Security(SecurityOp::GetSarifUpload),
212 Op::Security(SecurityOp::FixAlert),
213 ],
214 ),
215 (
216 "Supply chain",
217 "What a repository depends on: vulnerability alerts, the dependency graph, an SPDX SBOM of it, and comparing two commits' dependencies as dependency review does.",
218 &[
219 Op::Security(SecurityOp::ListVulnerabilityAlerts),
220 Op::Security(SecurityOp::GetVulnerabilityAlert),
221 Op::Security(SecurityOp::UpdateVulnerabilityAlert),
222 Op::Security(SecurityOp::GetDependencyGraph),
223 Op::Security(SecurityOp::GetSbom),
224 Op::Security(SecurityOp::CompareDependencies),
225 ],
226 ),
227 (
228 "Security settings",
229 "When pull request checks fail, dependency review's policy, delegated bypass and validity checks, and a workspace's security overview.",
230 &[
231 Op::Security(SecurityOp::GetSettings),
232 Op::Security(SecurityOp::UpdateSettings),
233 Op::Security(SecurityOp::GetWorkspaceSettings),
234 Op::Security(SecurityOp::UpdateWorkspaceSettings),
235 Op::Security(SecurityOp::GetOverview),
236 ],
237 ),
238 (
239 "Rules",
240 "Rulesets: what may happen to a repository's branches and tags and what a pull request needs before it merges, for a repository or across a workspace; the rules that hold for one branch; and how they judged each push and merge, with insights.",
241 &[
242 Op::Rules(RulesOp::ListRepoRulesets),
243 Op::Rules(RulesOp::CreateRepoRuleset),
244 Op::Rules(RulesOp::GetRepoRuleset),
245 Op::Rules(RulesOp::UpdateRepoRuleset),
246 Op::Rules(RulesOp::DeleteRepoRuleset),
247 Op::Rules(RulesOp::GetBranchRules),
248 Op::Rules(RulesOp::ListRuleEvaluations),
249 Op::Rules(RulesOp::ListWorkspaceRulesets),
250 Op::Rules(RulesOp::CreateWorkspaceRuleset),
251 Op::Rules(RulesOp::GetWorkspaceRuleset),
252 Op::Rules(RulesOp::UpdateWorkspaceRuleset),
253 Op::Rules(RulesOp::DeleteWorkspaceRuleset),
254 Op::Rules(RulesOp::ListWorkspaceRuleEvaluations),
255 ],
256 ),
257 (
258 "Issues",
259 "What should change in a repository, with labels and comments. Issues and pull requests share one sequence of numbers.",
260 &[
261 Op::ListIssues,
262 Op::CreateIssue,
263 Op::GetIssue,
264 Op::UpdateIssue,
265 Op::CloseIssue,
266 Op::ReopenIssue,
267 Op::AssignIssue,
268 Op::Delegate,
269 Op::AddComment,
270 Op::ListIssueLabels,
271 Op::AddIssueLabels,
272 Op::SetIssueLabels,
273 Op::RemoveIssueLabels,
274 ],
275 ),
276 (
277 "Labels and milestones",
278 "A repository's labels, which issues and pull requests carry by name, and its milestones, which gather them under a goal and a due date.",
279 &[
280 Op::ListLabels,
281 Op::CreateLabel,
282 Op::UpdateLabel,
283 Op::DeleteLabel,
284 Op::AddDefaultLabels,
285 Op::ListMilestones,
286 Op::CreateMilestone,
287 Op::GetMilestone,
288 Op::UpdateMilestone,
289 Op::DeleteMilestone,
290 ],
291 ),
292 (
293 "Plans",
294 "An outcome turned into the issues that would get there, with the order they must merge in.",
295 &[Op::PlanWork, Op::GetPlan, Op::ApplyPlan],
296 ),
297 (
298 "Pull requests",
299 "A proposed change in its own fork or on a branch. Several can be made for one issue; the one merged resolves it.",
300 &[
301 Op::ListPullRequests,
302 Op::CreatePullRequest,
303 Op::GetPullRequest,
304 Op::UpdatePullRequest,
305 Op::GetPullRequestChanges,
306 Op::MarkPullRequestReady,
307 Op::RequestReviewers,
308 Op::RemoveRequestedReviewers,
309 Op::ReviewPullRequest,
310 Op::MergePullRequest,
311 Op::ClosePullRequest,
312 Op::GetMergeQueue,
313 Op::MessageAgent,
314 Op::AnswerMessage,
315 Op::TakeMessages,
316 ],
317 ),
318 (
319 "Sessions",
320 "The record of how a pull request was made: prompts, reasoning and the tools that ran.",
321 &[Op::ReadSession, Op::RecordSession],
322 ),
323 (
324 "Memory",
325 "What agents and people learned that the next agent should know, for one project or across a workspace. Members and g1t's agents only; never a secret.",
326 &[Op::Remember, Op::Recall],
327 ),
328 (
329 "Search",
330 "One search across all of g1t: repositories, code, issues, pull requests, people and workspaces. Public content for everyone, and private content in workspaces you belong to.",
331 &[Op::Search],
332 ),
333 (
334 "Context",
335 "A workspace's context hub: a catalog of what it builds and runs, built from its repositories, deployments and integrations, and one search across the catalog, docs, issues, pull requests and memory.",
336 &[Op::SearchContext, Op::GetEntity],
337 ),
338 (
339 "Actions",
340 "GitHub Actions workflows in .g1t/workflows, their runs, and their jobs' logs.",
341 &[
342 Op::ListWorkflows,
343 Op::ListWorkflowRuns,
344 Op::GetWorkflowRun,
345 Op::GetJobLogs,
346 Op::DispatchWorkflow,
347 Op::CancelWorkflowRun,
348 Op::RerunWorkflowRun,
349 Op::UpdateWorkflow,
350 ],
351 ),
352 (
353 "Deployments",
354 "A repository's deployments wherever they run: reported from any CI with these routes, made by g1t Actions jobs with an `environment:`, or built on g1t.page. Each has statuses, shows on its commit as the check `deploy / <environment>`, and belongs to an environment.",
355 &[
356 Op::Deployments(DeploymentsOp::ListDeployments),
357 Op::Deployments(DeploymentsOp::CreateDeployment),
358 Op::Deployments(DeploymentsOp::GetDeployment),
359 Op::Deployments(DeploymentsOp::ListDeploymentStatuses),
360 Op::Deployments(DeploymentsOp::CreateDeploymentStatus),
361 Op::Deployments(DeploymentsOp::ListEnvironments),
362 Op::Deployments(DeploymentsOp::GetEnvironment),
363 ],
364 ),
365 (
366 "Secrets and variables",
367 "Values that workflows and deployments read, per repository or for a whole workspace, with a row per environment.",
368 &[
369 Op::ListActionsSecrets,
370 Op::SetActionsSecret,
371 Op::DeleteActionsSecret,
372 Op::ListActionsVariables,
373 Op::SetActionsVariable,
374 Op::DeleteActionsVariable,
375 ],
376 ),
377 (
378 "Runners",
379 "Self-hosted runners: your own machines, which run your workflow jobs (and, if you choose, your agents' work) for $0 of g1t compute. They register with a short-lived token and only ever connect out.",
380 &[
381 Op::ListRunners,
382 Op::CreateRunnerRegistrationToken,
383 Op::RemoveRunner,
384 Op::ListRunnerGroups,
385 Op::CreateRunnerGroup,
386 Op::UpdateRunnerGroup,
387 Op::DeleteRunnerGroup,
388 Op::GetRunnerSettings,
389 Op::UpdateRunnerSettings,
390 ],
391 ),
392 (
393 "Webhooks",
394 "Signed HTTPS requests sent to your own address as things happen, for a repository or a whole workspace.",
395 &[
396 Op::ListWebhooks,
397 Op::CreateWebhook,
398 Op::UpdateWebhook,
399 Op::DeleteWebhook,
400 Op::PingWebhook,
401 Op::ListWebhookDeliveries,
402 Op::RedeliverWebhook,
403 ],
404 ),
405 (
406 "Integrations",
407 "A workspace's connections to outside systems: model providers, alert sources and issue trackers.",
408 &[
409 Op::ListIntegrations,
410 Op::ConnectIntegration,
411 Op::DisconnectIntegration,
412 Op::TestIntegration,
413 Op::GetModelRoutes,
414 Op::SetModelRoutes,
415 Op::GetContext,
416 Op::ImportIssue,
417 ],
418 ),
419];
420
421/// The section of the API reference an operation is listed under.
422fn tag(op: Op) -> &'static str {
423 SECTIONS
424 .iter()
425 .find(|(_, _, ops)| ops.contains(&op))
426 .map_or("Repositories", |(name, _, _)| name)
427}
428
429/// What an operation's page is called, as a short sentence.
430fn title(op: Op) -> &'static str {
431 match op {
432 Op::Whoami => "Get the current user",
433 Op::GetWorkspace => "Get a workspace",
434 Op::CreateWorkspace => "Create a workspace",
435 Op::DeleteWorkspace => "Delete a workspace",
436 Op::UpdateWorkspace => "Update a workspace",
437 Op::ListEmails => "List your email addresses",
438 Op::AddEmail => "Add an email address",
439 Op::RemoveEmail => "Remove an email address",
440 Op::UpdateEmailSettings => "Change your email settings",
441 Op::ListInvites => "List your invites",
442 Op::CreateInvite => "Create an invite",
443 Op::RevokeInvite => "Revoke an invite",
444 Op::ListWorkspaceInvites => "List a workspace's invites",
445 Op::InviteMember => "Invite someone to a workspace",
446 Op::RevokeWorkspaceInvite => "Revoke a workspace's invite",
447 Op::TransferRepo => "Transfer a repository",
448 Op::RenameRepo => "Rename a repository",
449 Op::RenameBranch => "Rename a branch",
450 Op::ArchiveRepo => "Archive a repository",
451 Op::UnarchiveRepo => "Unarchive a repository",
452 Op::SetRepoVisibility => "Change a repository's visibility",
453 Op::DeleteRepo => "Delete a repository",
454 Op::ListDeletedRepos => "List recently deleted repositories",
455 Op::RestoreRepo => "Restore a deleted repository",
456 Op::PurgeRepo => "Purge a deleted repository",
457 Op::ListRepos => "List repositories",
458 Op::GetRepo => "Get a repository",
459 Op::CreateRepo => "Create a repository",
460 Op::UpdateRepo => "Update a repository",
461 Op::GetRepoSettings => "Get repository settings",
462 Op::UpdateRepoSettings => "Update repository settings",
463 Op::ListCheckNames => "List check names",
464 Op::GetMergeQueue => "Get the merge queue",
465 Op::MessageAgent => "Message an agent",
466 Op::AnswerMessage => "Answer a message",
467 Op::TakeMessages => "Take new messages",
468 Op::Remember => "Remember something",
469 Op::Recall => "Recall memory",
470 Op::SearchContext => "Search the context hub",
471 Op::GetEntity => "Get a catalog entry",
472 Op::Search => "Search g1t",
473 Op::ListIssues => "List issues",
474 Op::GetIssue => "Get an issue",
475 Op::CreateIssue => "Create an issue",
476 Op::UpdateIssue => "Update an issue",
477 Op::CloseIssue => "Close an issue",
478 Op::ReopenIssue => "Reopen an issue",
479 Op::AssignIssue => "Assign an issue to g1t",
480 Op::Delegate => "Put an agent on it",
481 Op::PlanWork => "Plan work",
482 Op::GetPlan => "Get a plan",
483 Op::ApplyPlan => "Apply a plan",
484 Op::ListLabels => "List labels",
485 Op::CreateLabel => "Create a label",
486 Op::UpdateLabel => "Update a label",
487 Op::DeleteLabel => "Delete a label",
488 Op::AddDefaultLabels => "Add the default labels",
489 Op::ListIssueLabels => "List an issue's labels",
490 Op::AddIssueLabels => "Add labels to an issue",
491 Op::SetIssueLabels => "Set an issue's labels",
492 Op::RemoveIssueLabels => "Remove labels from an issue",
493 Op::ListMilestones => "List milestones",
494 Op::GetMilestone => "Get a milestone",
495 Op::CreateMilestone => "Create a milestone",
496 Op::UpdateMilestone => "Update a milestone",
497 Op::DeleteMilestone => "Delete a milestone",
498 Op::UpdatePullRequest => "Update a pull request",
499 Op::AddComment => "Add a comment",
500 Op::ReviewPullRequest => "Review a pull request",
501 Op::ListPullRequests => "List pull requests",
502 Op::GetPullRequest => "Get a pull request",
503 Op::CreatePullRequest => "Create a pull request",
504 Op::RecordSession => "Record session entries",
505 Op::ReadSession => "Read a session",
506 Op::MarkPullRequestReady => "Mark a pull request ready",
507 Op::ClosePullRequest => "Close a pull request",
508 Op::GetPullRequestChanges => "Get a pull request's changes",
509 Op::MergePullRequest => "Merge a pull request",
510 Op::ListEvents => "List repository events",
511 Op::ListIntegrations => "List integrations",
512 Op::ConnectIntegration => "Connect an integration",
513 Op::DisconnectIntegration => "Disconnect an integration",
514 Op::TestIntegration => "Test an integration",
515 Op::GetContext => "Look up a ticket",
516 Op::ImportIssue => "Import an issue",
517 Op::GetModelRoutes => "Get model routes",
518 Op::SetModelRoutes => "Set model routes",
519 Op::ListWebhooks => "List webhooks",
520 Op::CreateWebhook => "Create a webhook",
521 Op::UpdateWebhook => "Update a webhook",
522 Op::DeleteWebhook => "Delete a webhook",
523 Op::PingWebhook => "Ping a webhook",
524 Op::ListWebhookDeliveries => "List webhook deliveries",
525 Op::RedeliverWebhook => "Redeliver a webhook delivery",
526 Op::ListWorkflows => "List workflows",
527 Op::ListWorkflowRuns => "List workflow runs",
528 Op::GetWorkflowRun => "Get a workflow run",
529 Op::GetJobLogs => "Get a job's log",
530 Op::DispatchWorkflow => "Run a workflow",
531 Op::CancelWorkflowRun => "Cancel a workflow run",
532 Op::RerunWorkflowRun => "Re-run a workflow run",
533 Op::UpdateWorkflow => "Turn a workflow on or off",
534 Op::ListActionsSecrets => "List secrets",
535 Op::SetActionsSecret => "Set a secret",
536 Op::DeleteActionsSecret => "Delete a secret",
537 Op::ListActionsVariables => "List variables",
538 Op::SetActionsVariable => "Set a variable",
539 Op::DeleteActionsVariable => "Delete a variable",
540 Op::ListRunners => "List self-hosted runners",
541 Op::ListRunnerGroups => "List runner groups",
542 Op::GetRunnerSettings => "Get runner settings",
543 Op::CreateRunnerRegistrationToken => "Create a runner registration token",
544 Op::RemoveRunner => "Remove a self-hosted runner",
545 Op::CreateRunnerGroup => "Create a runner group",
546 Op::UpdateRunnerGroup => "Change a runner group",
547 Op::DeleteRunnerGroup => "Delete a runner group",
548 Op::UpdateRunnerSettings => "Change runner settings",
549 Op::ListCollaborators => "List who has access",
550 Op::AddCollaborator => "Add a collaborator",
551 Op::UpdateCollaborator => "Change a collaborator's role",
552 Op::RemoveCollaborator => "Remove a collaborator",
553 Op::GetCollaboratorPermission => "Get someone's permission",
554 Op::ListRepoInvitations => "List a repository's invitations",
555 Op::RevokeRepoInvitation => "Revoke a repository invitation",
556 Op::ListMyRepoInvitations => "List your repository invitations",
557 Op::AcceptRepoInvitation => "Accept a repository invitation",
558 Op::DeclineRepoInvitation => "Decline a repository invitation",
559 Op::SetBasePermission => "Set the base permission",
560 Op::ListOutsideCollaborators => "List outside collaborators",
561 Op::ListSecurityAlerts => "List security alerts",
562 Op::DismissSecurityAlert => "Dismiss a security alert",
563 Op::ReopenSecurityAlert => "Reopen a security alert",
564 Op::ListNotifications => "List notifications",
565 Op::MarkNotificationsRead => "Mark notifications read",
566 Op::GetNotificationThread => "Get a thread",
567 Op::MarkThreadRead => "Mark a thread read",
568 Op::MarkThreadDone => "Mark a thread done",
569 Op::SaveThread => "Save a thread",
570 Op::SnoozeThread => "Snooze a thread",
571 Op::GetThreadSubscription => "Get a thread subscription",
572 Op::SetThreadSubscription => "Set a thread subscription",
573 Op::DeleteThreadSubscription => "Unsubscribe from a thread",
574 Op::GetRepoSubscription => "Get how you watch a repository",
575 Op::SetRepoSubscription => "Watch a repository",
576 Op::DeleteRepoSubscription => "Stop watching a repository",
577 Op::ListWatchedRepos => "List repositories you watch",
578 Op::ListPinnedProjects => "List your pinned projects",
579 Op::GetUsage => "Get a workspace's usage",
580 Op::GetBudget => "Get a workspace's budget",
581 Op::SetBudget => "Change a workspace's budget",
582 Op::GetAiCredit => "Get a workspace's AI credit",
583 Op::BuyAiCredit => "Buy AI credit",
584 Op::ListInvoices => "List a workspace's invoices",
585 Op::GetBillingDetails => "Get a workspace's billing details",
586 Op::ListGatewayRequests => "List a workspace's AI Gateway requests",
587 Op::PinProject => "Pin a project",
588 Op::UnpinProject => "Unpin a project",
589 Op::ReorderPinnedProjects => "Reorder your pinned projects",
590 Op::ListProjects => "List a workspace's projects",
591 Op::GetProject => "Get a project",
592 Op::UpdateProject => "Update a project",
593 Op::ListTeams => "List teams",
594 Op::GetTeam => "Get a team",
595 Op::CreateTeam => "Create a team",
596 Op::UpdateTeam => "Update a team",
597 Op::DeleteTeam => "Delete a team",
598 Op::ListTeamMembers => "List a team's members",
599 Op::SetTeamMember => "Add or change a team member",
600 Op::RemoveTeamMember => "Remove a team member",
601 Op::ListChildTeams => "List child teams",
602 Op::ListTeamRepos => "List a team's repositories",
603 Op::SetTeamRepo => "Give a team a role on a repository",
604 Op::RemoveTeamRepo => "Remove a team from a repository",
605 Op::SetTeamReviewAssignment => "Set a team's review assignment",
606 Op::ListUserTeams => "List someone's teams",
607 Op::RequestReviewers => "Request reviewers",
608 Op::RemoveRequestedReviewers => "Remove requested reviewers",
609 Op::GetCodeownersErrors => "List CODEOWNERS errors",
610 Op::Security(op) => op.title(),
611 Op::Rules(op) => op.title(),
612 Op::About(op) => op.title(),
613 Op::Deployments(op) => op.title(),
614 }
615}
616
617/// Why an operation can be refused with `402 payment_required`, if it
618/// can: the ones that start an agent, when the workspace has no credit,
619/// and the ones that make a repository private in a workspace, when a free
620/// workspace's private storage has no room for it.
621fn may_need_payment(op: Op) -> Option<&'static str> {
622 match op {
623 Op::AssignIssue | Op::PlanWork | Op::ApplyPlan => Some("The workspace has no agent credit."),
624 Op::UpdateRepo | Op::SetRepoVisibility | Op::TransferRepo => Some(
625 "A free workspace's private storage has no room for this private repository.",
626 ),
627 _ => None,
628 }
629}
630
631/// What the reference says beyond each operation's own description, keyed
632/// by operation id, written by hand from what the services return: `notes`
633/// (Markdown, added to the description) and example `params` (path),
634/// `query`, `request` (body) and `response`.
635const REFERENCE: &str = include_str!("reference.json");
636
637fn examples() -> Map<String, Value> {
638 match serde_json::from_str(REFERENCE) {
639 Ok(Value::Object(examples)) => examples,
640 _ => Map::new(),
641 }
642}
643
644/// `/repos/:owner/:name` as OpenAPI writes it: `/repos/{owner}/{name}`.
645fn openapi_path(route: &Route) -> String {
646 route
647 .path
648 .split('/')
649 .map(|segment| match segment.strip_prefix(':') {
650 Some(name) => format!("{{{name}}}"),
651 None => segment.to_owned(),
652 })
653 .collect::<Vec<_>>()
654 .join("/")
655}
656
657fn error_response(description: &str) -> Value {
658 json!({
659 "description": description,
660 "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } },
661 })
662}
663
664/// A parameter in the path or the query, described by the operation's
665/// input schema where it has the same name.
666fn parameter(name: &str, place: &str, required: bool, schema: Option<&Value>) -> Value {
667 let mut schema = schema.cloned().unwrap_or_else(|| json!({ "type": "string" }));
668 let description = match name {
669 "owner" => Some(Value::from("The workspace that owns the repository.")),
670 "name" => Some(Value::from("The repository's name.")),
671 _ => schema.as_object_mut().and_then(|schema| schema.remove("description")),
672 };
673 let mut parameter = json!({
674 "name": name,
675 "in": place,
676 "required": required,
677 "schema": schema,
678 });
679 if let Some(description) = description {
680 parameter["description"] = description;
681 }
682 parameter
683}
684
685/// The operation id of a route. An operation reached at a workspace's
686/// address as well as a repository's is documented once for each, with its
687/// own id; GitHub's alternative addresses for one operation keep GitHub's
688/// names.
689fn operation_id(route: &Route) -> String {
690 let op = route.op;
691 let base = match (route.method, route.path.rsplit('/').next().unwrap_or_default()) {
692 ("PUT", "enable") => "enable_workflow".to_owned(),
693 ("PUT", "disable") => "disable_workflow".to_owned(),
694 ("POST", "rerun-failed-jobs") => "rerun_failed_jobs".to_owned(),
695 ("PATCH", ":setting") => "update_actions_variable".to_owned(),
696 ("GET", "runs") if route.path.contains("/workflows/:workflow/") => "list_runs_of_workflow".to_owned(),
697 // One repository's notifications, and an issue's subscription by
698 // its number rather than a thread's id.
699 (_, "notifications") if route.path.starts_with("/repos/") => match op {
700 Op::ListNotifications => "list_repo_notifications".to_owned(),
701 _ => "mark_repo_notifications_read".to_owned(),
702 },
703 (method, "subscription") if route.path.contains("/issues/:number/") => match method {
704 "GET" => "get_issue_subscription".to_owned(),
705 "PUT" => "set_issue_subscription".to_owned(),
706 _ => "delete_issue_subscription".to_owned(),
707 },
708 // One label off an issue, by its name in the path.
709 ("DELETE", ":label") if route.path.contains("/issues/:number/") => "remove_issue_label".to_owned(),
710 ("DELETE", "saved") => "unsave_thread".to_owned(),
711 ("DELETE", "snooze") => "unsnooze_thread".to_owned(),
712 _ => op.name().to_owned(),
713 };
714 if route.path.starts_with("/workspaces/") && ROUTES.iter().any(|other| other.op == op && other.path.starts_with("/repos/")) {
715 format!("{base}_for_workspace")
716 } else {
717 base
718 }
719}
720
721/// The summary of a route: its operation's title, or for one of GitHub's
722/// alternative addresses, what that address does.
723fn summary(route: &Route, id: &str) -> String {
724 let base = match id.trim_end_matches("_for_workspace") {
725 "enable_workflow" => "Turn a workflow on",
726 "disable_workflow" => "Turn a workflow off",
727 "rerun_failed_jobs" => "Re-run failed jobs",
728 "update_actions_variable" => "Update a variable",
729 "list_runs_of_workflow" => "List a workflow's runs",
730 "list_repo_notifications" => "List a repository's notifications",
731 "mark_repo_notifications_read" => "Mark a repository's notifications read",
732 "get_issue_subscription" => "Get your subscription to an issue",
733 "set_issue_subscription" => "Subscribe to an issue",
734 "delete_issue_subscription" => "Unsubscribe from an issue",
735 "unsave_thread" => "Unsave a thread",
736 "unsnooze_thread" => "Bring a snoozed thread back",
737 _ => title(route.op),
738 };
739 if id.ends_with("_for_workspace") {
740 format!("{base} for a workspace")
741 } else {
742 base.to_owned()
743 }
744}
745
746fn operation(route: &Route) -> Value {
747 let op = route.op;
748 let path_params: Vec<&str> = route.params().collect();
749 // `owner` and `name` in the path stand for the operation's `repo` input.
750 let covered = |name: &str| name == "repo" || path_params.contains(&name);
751 let all_properties = op.properties();
752 let mut properties = all_properties.clone();
753 properties.retain(|name, _| !covered(name));
754 let required: Vec<String> = op
755 .required()
756 .into_iter()
757 .filter(|name| !covered(name))
758 .collect();
759
760 let mut parameters: Vec<Value> = path_params
761 .iter()
762 .map(|name| parameter(name, "path", true, all_properties.get(*name)))
763 .collect();
764 let mut body = Value::Null;
765 if route.method == "GET" {
766 for (name, key) in route.query {
767 parameters.push(parameter(
768 name,
769 "query",
770 required.iter().any(|required| required == key),
771 properties.get(*key),
772 ));
773 }
774 } else if !properties.is_empty() {
775 let mut schema = json!({ "type": "object", "properties": properties });
776 if !required.is_empty() {
777 schema["required"] = json!(required);
778 }
779 body = json!({
780 "required": !required.is_empty(),
781 "content": { "application/json": { "schema": schema } },
782 });
783 }
784
785 let id = operation_id(route);
786 let mut responses = Map::new();
787 responses.insert(
788 "200".into(),
789 json!({
790 "description": "Success.",
791 "content": { "application/json": { "schema": {} } },
792 }),
793 );
794 responses.insert(
795 "401".into(),
796 error_response("A token is required, or the one sent is not valid."),
797 );
798 if let Some(reason) = may_need_payment(op) {
799 responses.insert("402".into(), error_response(reason));
800 }
801 responses.insert(
802 "403".into(),
803 error_response("Signed in, but not allowed to do this: the role you have is not enough, or the token lacks the scope it needs, which `needed_scope` names."),
804 );
805 if !matches!(op, Op::Whoami | Op::ListRepos | Op::Search) {
806 responses.insert("404".into(), error_response("It does not exist, or you cannot see it."));
807 }
808 if route.method != "GET" {
809 responses.insert(
810 "409".into(),
811 error_response("The request conflicts with the current state."),
812 );
813 }
814 if op != Op::Whoami {
815 responses.insert("422".into(), error_response("The input is not valid."));
816 }
817 // Public data can be read without a token; everything else needs one.
818 let scope: Vec<&str> = scope_for(op.name()).map(|scope| scope.as_str()).into_iter().collect();
819 let security = if op.needs_user() {
820 json!([{ "token": scope }])
821 } else {
822 json!([{ "token": scope }, {}])
823 };
824 let (tool, action) = crate::tools::TOOLS
825 .iter()
826 .find_map(|tool| {
827 tool.actions
828 .iter()
829 .find(|action| action.op == op)
830 .map(|action| (tool.name, action.name))
831 })
832 .unwrap_or_default();
833 let mut described = json!({
834 "operationId": id,
835 "tags": [tag(op)],
836 "summary": summary(route, &id),
837 "description": op.description(),
838 "x-operation": op.name(),
839 "x-mcp-tool": tool,
840 "x-mcp-action": action,
841 "x-scope": scope.first().copied(),
842 "security": security,
843 "parameters": parameters,
844 "responses": responses,
845 });
846 if !body.is_null() {
847 described["requestBody"] = body;
848 }
849 described
850}
851
852/// Entries for device sign-in, which is not an operation.
853fn onboarding() -> Map<String, Value> {
854 let paths = json!({
855 "/device/code": {
856 "post": {
857 "operationId": "device_code",
858 "tags": ["Accounts"],
859 "summary": "Start signing in",
860 "description": "Begins a device sign-in. Show the person `verification_uri_complete` and have them open it in a browser, where they sign in or register and approve the code. Then poll `/device/token`.",
861 "security": [],
862 "requestBody": {
863 "content": { "application/json": { "schema": {
864 "type": "object",
865 "properties": {
866 "client_name": {
867 "type": "string",
868 "description": "What is asking, shown to the person approving. For example, Claude Code.",
869 },
870 },
871 } } },
872 },
873 "responses": { "200": {
874 "description": "The codes for this sign-in.",
875 "content": { "application/json": { "schema": {
876 "type": "object",
877 "properties": {
878 "device_code": { "type": "string", "description": "Secret. Send it to /device/token." },
879 "user_code": { "type": "string", "description": "Shown to the person, like WDJB-MJHT." },
880 "verification_uri": { "type": "string" },
881 "verification_uri_complete": {
882 "type": "string",
883 "description": "The link to give the person; it carries the code.",
884 },
885 "expires_in": { "type": "integer", "description": "Seconds until the codes expire." },
886 "interval": { "type": "integer", "description": "Seconds to wait between polls." },
887 },
888 } } },
889 } },
890 },
891 },
892 "/device/token": {
893 "post": {
894 "operationId": "device_token",
895 "tags": ["Accounts"],
896 "summary": "Finish signing in",
897 "description": "Asks whether the person has approved. Poll no faster than the interval. The token is returned once.",
898 "security": [],
899 "requestBody": {
900 "required": true,
901 "content": { "application/json": { "schema": {
902 "type": "object",
903 "required": ["device_code"],
904 "properties": { "device_code": { "type": "string" } },
905 } } },
906 },
907 "responses": { "200": {
908 "description": "The state of the sign-in.",
909 "content": { "application/json": { "schema": {
910 "type": "object",
911 "required": ["status"],
912 "properties": {
913 "status": { "type": "string", "enum": ["pending", "approved", "denied", "expired"] },
914 "token": { "type": "string", "description": "Present when approved." },
915 "username": { "type": "string" },
916 "verified": {
917 "type": "boolean",
918 "description": "Whether the account's email is confirmed.",
919 },
920 },
921 } } },
922 } },
923 },
924 },
925 });
926 match paths {
927 Value::Object(paths) => paths,
928 _ => Map::new(),
929 }
930}
931
932
933/// Puts each operation's examples, where it has them, into its request
934/// and response. Path and query values go under `x-example-params` and
935/// `x-example-query`, which tools that build a request can use.
936fn attach_examples(paths: &mut Map<String, Value>) {
937 let examples = examples();
938 for methods in paths.values_mut() {
939 let Some(methods) = methods.as_object_mut() else { continue };
940 for operation in methods.values_mut() {
941 let id = operation["operationId"].as_str().unwrap_or_default().to_owned();
942 let name = operation["x-operation"].as_str().unwrap_or_default().to_owned();
943 let Some(example) = examples.get(&id).or_else(|| examples.get(&name)) else {
944 continue;
945 };
946 if let Some(notes) = example.get("notes").and_then(Value::as_str) {
947 let description = operation["description"].as_str().unwrap_or_default();
948 operation["description"] = json!(format!("{description}\n\n{notes}"));
949 }
950 if let Some(response) = example.get("response") {
951 let content = &mut operation["responses"]["200"]["content"]["application/json"];
952 if content.is_object() {
953 content["example"] = response.clone();
954 }
955 }
956 if let Some(request) = example.get("request") {
957 let content = &mut operation["requestBody"]["content"]["application/json"];
958 if content.is_object() {
959 content["example"] = request.clone();
960 }
961 }
962 for (key, extension) in [("params", "x-example-params"), ("query", "x-example-query")] {
963 if let Some(values) = example.get(key) {
964 operation[extension] = values.clone();
965 }
966 }
967 }
968 }
969}
970
971pub fn document() -> Value {
972 let mut paths = onboarding();
973 for route in ROUTES {
974 let entry = paths
975 .entry(openapi_path(route))
976 .or_insert_with(|| json!({}));
977 entry[route.method.to_lowercase()] = operation(route);
978 }
979 attach_examples(&mut paths);
980 let tags: Vec<Value> = SECTIONS
981 .iter()
982 .map(|(name, description, ops)| {
983 json!({
984 "name": name,
985 "description": description,
986 // The section's operations in reading order, by MCP tool name.
987 "x-tools": ops.iter().map(|op| op.name()).collect::<Vec<_>>(),
988 })
989 })
990 .collect();
991 let codes = ["unauthenticated", "payment_required", "forbidden", "not_found", "conflict", "invalid"];
992 json!({
993 "openapi": "3.1.0",
994 "info": {
995 "title": "g1t API",
996 "version": "1",
997 "description": "The REST API for g1t, a git forge built for agents. The same operations are available to agents as MCP tools at https://mcp.g1t.sh. Every name in a request or response body is `snake_case`; names you chose, such as a workflow's inputs or a secret's name, are returned as you wrote them.",
998 "license": { "name": "MIT", "identifier": "MIT" },
999 },
1000 "servers": [{ "url": "https://api.g1t.sh" }],
1001 "security": [{ "token": [] }, {}],
1002 "tags": tags,
1003 "paths": paths,
1004 "components": {
1005 "securitySchemes": {
1006 "token": {
1007 "type": "http",
1008 "scheme": "bearer",
1009 "description": "An access token, `g1t_…`. Public data needs none. Each operation names the scope a token needs for it; see https://docs.g1t.sh/guides/authentication/#scopes.",
1010 },
1011 },
1012 "schemas": {
1013 "Error": {
1014 "type": "object",
1015 "required": ["error"],
1016 "properties": {
1017 "error": {
1018 "type": "object",
1019 "required": ["code", "message"],
1020 "properties": {
1021 "code": { "type": "string", "enum": codes },
1022 "message": { "type": "string" },
1023 "needed_scope": {
1024 "type": "string",
1025 "description": "On a 403 for an access token without the scope the call needs: that scope, such as `issues:write`.",
1026 },
1027 },
1028 },
1029 },
1030 },
1031 },
1032 },
1033 })
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038 use super::*;
1039
1040 #[test]
1041 fn every_route_is_documented_once() {
1042 let document = document();
1043 let mut ids = Vec::new();
1044 for (_, methods) in document["paths"].as_object().unwrap() {
1045 for (_, operation) in methods.as_object().unwrap() {
1046 ids.push(operation["operationId"].as_str().unwrap().to_owned());
1047 }
1048 }
1049 for op in Op::ALL {
1050 assert_eq!(
1051 ids.iter().filter(|id| *id == op.name()).count(),
1052 1,
1053 "{}",
1054 op.name()
1055 );
1056 }
1057 let mut unique = ids.clone();
1058 unique.sort();
1059 unique.dedup();
1060 assert_eq!(unique.len(), ids.len(), "operation ids repeat");
1061 }
1062
1063 #[test]
1064 fn path_and_query_inputs_are_not_repeated_in_the_body() {
1065 let document = document();
1066 let merge = &document["paths"]["/repos/{owner}/{name}/pulls/{number}/merge"]["post"];
1067 let body = &merge["requestBody"]["content"]["application/json"]["schema"]["properties"];
1068 assert!(body.get("keep_issue_open").is_some());
1069 assert!(body.get("repo").is_none() && body.get("number").is_none());
1070 let list = &document["paths"]["/repos"]["get"];
1071 assert_eq!(list["parameters"][0]["name"], "q");
1072 assert!(list.get("requestBody").is_none());
1073 }
1074
1075 #[test]
1076 fn every_operation_is_in_one_section() {
1077 for op in Op::ALL {
1078 let sections = SECTIONS
1079 .iter()
1080 .filter(|(_, _, ops)| ops.contains(&op))
1081 .count();
1082 assert_eq!(sections, 1, "{}", op.name());
1083 }
1084 }
1085
1086 #[test]
1087 fn titles_read_as_sentences() {
1088 assert_eq!(title(Op::CreateIssue), "Create an issue");
1089 assert_eq!(title(Op::Whoami), "Get the current user");
1090 }
1091
1092 #[test]
1093 fn every_operation_has_an_example_response() {
1094 let examples = examples();
1095 assert!(!examples.is_empty(), "reference.json does not parse");
1096 let document = document();
1097 let mut known = Vec::new();
1098 for (path, methods) in document["paths"].as_object().unwrap() {
1099 for (method, operation) in methods.as_object().unwrap() {
1100 known.push(operation["operationId"].as_str().unwrap().to_owned());
1101 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
1102 assert!(!example.is_null(), "{method} {path} has no example response");
1103 }
1104 }
1105 for id in examples.keys() {
1106 assert!(known.contains(id), "reference.json names {id}, which is not an operation");
1107 }
1108 }
1109
1110 #[test]
1111 fn example_requests_send_only_what_the_body_takes() {
1112 let document = document();
1113 for (path, methods) in document["paths"].as_object().unwrap() {
1114 for (method, operation) in methods.as_object().unwrap() {
1115 let content = &operation["requestBody"]["content"]["application/json"];
1116 let Some(example) = content["example"].as_object() else { continue };
1117 let properties = &content["schema"]["properties"];
1118 for key in example.keys() {
1119 assert!(!properties[key].is_null(), "{method} {path}: {key} is not in the body");
1120 }
1121 }
1122 }
1123 }
1124
1125 /// The docs site's copy of the document. Run with `G1T_WRITE_OPENAPI=1`
1126 /// to rewrite it after changing an operation.
1127 #[test]
1128 fn the_docs_copy_is_current() {
1129 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../docs/src/data/openapi.json");
1130 let current = serde_json::to_string_pretty(&document()).unwrap() + "\n";
1131 if std::env::var_os("G1T_WRITE_OPENAPI").is_some() {
1132 std::fs::write(path, &current).unwrap();
1133 return;
1134 }
1135 let copy = std::fs::read_to_string(path).unwrap_or_default().replace("\r\n", "\n");
1136 assert!(
1137 copy == current,
1138 "apps/docs/src/data/openapi.json is out of date: run G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi"
1139 );
1140 }
1141
1142 /// The reference shows responses as they are sent: `snake_case`.
1143 #[test]
1144 fn example_responses_are_snake_case() {
1145 let document = document();
1146 for (path, methods) in document["paths"].as_object().unwrap() {
1147 for (method, operation) in methods.as_object().unwrap() {
1148 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
1149 let leaked = g1t_kit::wire::camel_case_keys(example);
1150 assert!(leaked.is_empty(), "{method} {path} shows {leaked:?}");
1151 }
1152 }
1153 }
1154
1155 /// Examples never hold anything that reads as a real credential, which
1156 /// secret scanners rightly flag in a public repository: they end in `…`
1157 /// after the prefix, as `whsec_…` and `g1t_…` do.
1158 #[test]
1159 fn examples_hold_no_real_looking_secrets() {
1160 let prefixes = ["whsec_", "g1t_", "g1tr_", "g1trt_", "sk_live_", "sk_test_", "ghp_", "github_pat_", "xoxb-", "AKIA"];
1161 for (line, text) in REFERENCE.lines().enumerate() {
1162 for prefix in prefixes {
1163 let mut rest = text;
1164 while let Some(at) = rest.find(prefix) {
1165 let after = &rest[at + prefix.len()..];
1166 let run = after.chars().take_while(|c| c.is_ascii_alphanumeric()).count();
1167 assert!(
1168 run < 12,
1169 "reference.json line {}: `{prefix}` followed by {run} characters reads as a real secret; write `{prefix}…`",
1170 line + 1
1171 );
1172 rest = after;
1173 }
1174 }
1175 }
1176 }
1177}