Skip to content
1,179 linesCodeBlameRaw
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::UpdateIntegration,
412 Op::DisconnectIntegration,
413 Op::TestIntegration,
414 Op::GetModelRoutes,
415 Op::SetModelRoutes,
416 Op::GetContext,
417 Op::ImportIssue,
418 ],
419 ),
420];
421
422/// The section of the API reference an operation is listed under.
423fn tag(op: Op) -> &'static str {
424 SECTIONS
425 .iter()
426 .find(|(_, _, ops)| ops.contains(&op))
427 .map_or("Repositories", |(name, _, _)| name)
428}
429
430/// What an operation's page is called, as a short sentence.
431fn title(op: Op) -> &'static str {
432 match op {
433 Op::Whoami => "Get the current user",
434 Op::GetWorkspace => "Get a workspace",
435 Op::CreateWorkspace => "Create a workspace",
436 Op::DeleteWorkspace => "Delete a workspace",
437 Op::UpdateWorkspace => "Update a workspace",
438 Op::ListEmails => "List your email addresses",
439 Op::AddEmail => "Add an email address",
440 Op::RemoveEmail => "Remove an email address",
441 Op::UpdateEmailSettings => "Change your email settings",
442 Op::ListInvites => "List your invites",
443 Op::CreateInvite => "Create an invite",
444 Op::RevokeInvite => "Revoke an invite",
445 Op::ListWorkspaceInvites => "List a workspace's invites",
446 Op::InviteMember => "Invite someone to a workspace",
447 Op::RevokeWorkspaceInvite => "Revoke a workspace's invite",
448 Op::TransferRepo => "Transfer a repository",
449 Op::RenameRepo => "Rename a repository",
450 Op::RenameBranch => "Rename a branch",
451 Op::ArchiveRepo => "Archive a repository",
452 Op::UnarchiveRepo => "Unarchive a repository",
453 Op::SetRepoVisibility => "Change a repository's visibility",
454 Op::DeleteRepo => "Delete a repository",
455 Op::ListDeletedRepos => "List recently deleted repositories",
456 Op::RestoreRepo => "Restore a deleted repository",
457 Op::PurgeRepo => "Purge a deleted repository",
458 Op::ListRepos => "List repositories",
459 Op::GetRepo => "Get a repository",
460 Op::CreateRepo => "Create a repository",
461 Op::UpdateRepo => "Update a repository",
462 Op::GetRepoSettings => "Get repository settings",
463 Op::UpdateRepoSettings => "Update repository settings",
464 Op::ListCheckNames => "List check names",
465 Op::GetMergeQueue => "Get the merge queue",
466 Op::MessageAgent => "Message an agent",
467 Op::AnswerMessage => "Answer a message",
468 Op::TakeMessages => "Take new messages",
469 Op::Remember => "Remember something",
470 Op::Recall => "Recall memory",
471 Op::SearchContext => "Search the context hub",
472 Op::GetEntity => "Get a catalog entry",
473 Op::Search => "Search g1t",
474 Op::ListIssues => "List issues",
475 Op::GetIssue => "Get an issue",
476 Op::CreateIssue => "Create an issue",
477 Op::UpdateIssue => "Update an issue",
478 Op::CloseIssue => "Close an issue",
479 Op::ReopenIssue => "Reopen an issue",
480 Op::AssignIssue => "Assign an issue to g1t",
481 Op::Delegate => "Put an agent on it",
482 Op::PlanWork => "Plan work",
483 Op::GetPlan => "Get a plan",
484 Op::ApplyPlan => "Apply a plan",
485 Op::ListLabels => "List labels",
486 Op::CreateLabel => "Create a label",
487 Op::UpdateLabel => "Update a label",
488 Op::DeleteLabel => "Delete a label",
489 Op::AddDefaultLabels => "Add the default labels",
490 Op::ListIssueLabels => "List an issue's labels",
491 Op::AddIssueLabels => "Add labels to an issue",
492 Op::SetIssueLabels => "Set an issue's labels",
493 Op::RemoveIssueLabels => "Remove labels from an issue",
494 Op::ListMilestones => "List milestones",
495 Op::GetMilestone => "Get a milestone",
496 Op::CreateMilestone => "Create a milestone",
497 Op::UpdateMilestone => "Update a milestone",
498 Op::DeleteMilestone => "Delete a milestone",
499 Op::UpdatePullRequest => "Update a pull request",
500 Op::AddComment => "Add a comment",
501 Op::ReviewPullRequest => "Review a pull request",
502 Op::ListPullRequests => "List pull requests",
503 Op::GetPullRequest => "Get a pull request",
504 Op::CreatePullRequest => "Create a pull request",
505 Op::RecordSession => "Record session entries",
506 Op::ReadSession => "Read a session",
507 Op::MarkPullRequestReady => "Mark a pull request ready",
508 Op::ClosePullRequest => "Close a pull request",
509 Op::GetPullRequestChanges => "Get a pull request's changes",
510 Op::MergePullRequest => "Merge a pull request",
511 Op::ListEvents => "List repository events",
512 Op::ListIntegrations => "List integrations",
513 Op::ConnectIntegration => "Connect an integration",
514 Op::UpdateIntegration => "Update an integration",
515 Op::DisconnectIntegration => "Disconnect an integration",
516 Op::TestIntegration => "Test an integration",
517 Op::GetContext => "Look up a ticket",
518 Op::ImportIssue => "Import an issue",
519 Op::GetModelRoutes => "Get model routes",
520 Op::SetModelRoutes => "Set model routes",
521 Op::ListWebhooks => "List webhooks",
522 Op::CreateWebhook => "Create a webhook",
523 Op::UpdateWebhook => "Update a webhook",
524 Op::DeleteWebhook => "Delete a webhook",
525 Op::PingWebhook => "Ping a webhook",
526 Op::ListWebhookDeliveries => "List webhook deliveries",
527 Op::RedeliverWebhook => "Redeliver a webhook delivery",
528 Op::ListWorkflows => "List workflows",
529 Op::ListWorkflowRuns => "List workflow runs",
530 Op::GetWorkflowRun => "Get a workflow run",
531 Op::GetJobLogs => "Get a job's log",
532 Op::DispatchWorkflow => "Run a workflow",
533 Op::CancelWorkflowRun => "Cancel a workflow run",
534 Op::RerunWorkflowRun => "Re-run a workflow run",
535 Op::UpdateWorkflow => "Turn a workflow on or off",
536 Op::ListActionsSecrets => "List secrets",
537 Op::SetActionsSecret => "Set a secret",
538 Op::DeleteActionsSecret => "Delete a secret",
539 Op::ListActionsVariables => "List variables",
540 Op::SetActionsVariable => "Set a variable",
541 Op::DeleteActionsVariable => "Delete a variable",
542 Op::ListRunners => "List self-hosted runners",
543 Op::ListRunnerGroups => "List runner groups",
544 Op::GetRunnerSettings => "Get runner settings",
545 Op::CreateRunnerRegistrationToken => "Create a runner registration token",
546 Op::RemoveRunner => "Remove a self-hosted runner",
547 Op::CreateRunnerGroup => "Create a runner group",
548 Op::UpdateRunnerGroup => "Change a runner group",
549 Op::DeleteRunnerGroup => "Delete a runner group",
550 Op::UpdateRunnerSettings => "Change runner settings",
551 Op::ListCollaborators => "List who has access",
552 Op::AddCollaborator => "Add a collaborator",
553 Op::UpdateCollaborator => "Change a collaborator's role",
554 Op::RemoveCollaborator => "Remove a collaborator",
555 Op::GetCollaboratorPermission => "Get someone's permission",
556 Op::ListRepoInvitations => "List a repository's invitations",
557 Op::RevokeRepoInvitation => "Revoke a repository invitation",
558 Op::ListMyRepoInvitations => "List your repository invitations",
559 Op::AcceptRepoInvitation => "Accept a repository invitation",
560 Op::DeclineRepoInvitation => "Decline a repository invitation",
561 Op::SetBasePermission => "Set the base permission",
562 Op::ListOutsideCollaborators => "List outside collaborators",
563 Op::ListSecurityAlerts => "List security alerts",
564 Op::DismissSecurityAlert => "Dismiss a security alert",
565 Op::ReopenSecurityAlert => "Reopen a security alert",
566 Op::ListNotifications => "List notifications",
567 Op::MarkNotificationsRead => "Mark notifications read",
568 Op::GetNotificationThread => "Get a thread",
569 Op::MarkThreadRead => "Mark a thread read",
570 Op::MarkThreadDone => "Mark a thread done",
571 Op::SaveThread => "Save a thread",
572 Op::SnoozeThread => "Snooze a thread",
573 Op::GetThreadSubscription => "Get a thread subscription",
574 Op::SetThreadSubscription => "Set a thread subscription",
575 Op::DeleteThreadSubscription => "Unsubscribe from a thread",
576 Op::GetRepoSubscription => "Get how you watch a repository",
577 Op::SetRepoSubscription => "Watch a repository",
578 Op::DeleteRepoSubscription => "Stop watching a repository",
579 Op::ListWatchedRepos => "List repositories you watch",
580 Op::ListPinnedProjects => "List your pinned projects",
581 Op::GetUsage => "Get a workspace's usage",
582 Op::GetBudget => "Get a workspace's budget",
583 Op::SetBudget => "Change a workspace's budget",
584 Op::GetAiCredit => "Get a workspace's AI credit",
585 Op::BuyAiCredit => "Buy AI credit",
586 Op::ListInvoices => "List a workspace's invoices",
587 Op::GetBillingDetails => "Get a workspace's billing details",
588 Op::ListGatewayRequests => "List a workspace's AI Gateway requests",
589 Op::PinProject => "Pin a project",
590 Op::UnpinProject => "Unpin a project",
591 Op::ReorderPinnedProjects => "Reorder your pinned projects",
592 Op::ListProjects => "List a workspace's projects",
593 Op::GetProject => "Get a project",
594 Op::UpdateProject => "Update a project",
595 Op::ListTeams => "List teams",
596 Op::GetTeam => "Get a team",
597 Op::CreateTeam => "Create a team",
598 Op::UpdateTeam => "Update a team",
599 Op::DeleteTeam => "Delete a team",
600 Op::ListTeamMembers => "List a team's members",
601 Op::SetTeamMember => "Add or change a team member",
602 Op::RemoveTeamMember => "Remove a team member",
603 Op::ListChildTeams => "List child teams",
604 Op::ListTeamRepos => "List a team's repositories",
605 Op::SetTeamRepo => "Give a team a role on a repository",
606 Op::RemoveTeamRepo => "Remove a team from a repository",
607 Op::SetTeamReviewAssignment => "Set a team's review assignment",
608 Op::ListUserTeams => "List someone's teams",
609 Op::RequestReviewers => "Request reviewers",
610 Op::RemoveRequestedReviewers => "Remove requested reviewers",
611 Op::GetCodeownersErrors => "List CODEOWNERS errors",
612 Op::Security(op) => op.title(),
613 Op::Rules(op) => op.title(),
614 Op::About(op) => op.title(),
615 Op::Deployments(op) => op.title(),
616 }
617}
618
619/// Why an operation can be refused with `402 payment_required`, if it
620/// can: the ones that start an agent, when the workspace has no credit,
621/// and the ones that make a repository private in a workspace, when a free
622/// workspace's private storage has no room for it.
623fn may_need_payment(op: Op) -> Option<&'static str> {
624 match op {
625 Op::AssignIssue | Op::PlanWork | Op::ApplyPlan => Some("The workspace has no agent credit."),
626 Op::UpdateRepo | Op::SetRepoVisibility | Op::TransferRepo => Some(
627 "A free workspace's private storage has no room for this private repository.",
628 ),
629 _ => None,
630 }
631}
632
633/// What the reference says beyond each operation's own description, keyed
634/// by operation id, written by hand from what the services return: `notes`
635/// (Markdown, added to the description) and example `params` (path),
636/// `query`, `request` (body) and `response`.
637const REFERENCE: &str = include_str!("reference.json");
638
639fn examples() -> Map<String, Value> {
640 match serde_json::from_str(REFERENCE) {
641 Ok(Value::Object(examples)) => examples,
642 _ => Map::new(),
643 }
644}
645
646/// `/repos/:owner/:name` as OpenAPI writes it: `/repos/{owner}/{name}`.
647fn openapi_path(route: &Route) -> String {
648 route
649 .path
650 .split('/')
651 .map(|segment| match segment.strip_prefix(':') {
652 Some(name) => format!("{{{name}}}"),
653 None => segment.to_owned(),
654 })
655 .collect::<Vec<_>>()
656 .join("/")
657}
658
659fn error_response(description: &str) -> Value {
660 json!({
661 "description": description,
662 "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } },
663 })
664}
665
666/// A parameter in the path or the query, described by the operation's
667/// input schema where it has the same name.
668fn parameter(name: &str, place: &str, required: bool, schema: Option<&Value>) -> Value {
669 let mut schema = schema.cloned().unwrap_or_else(|| json!({ "type": "string" }));
670 let description = match name {
671 "owner" => Some(Value::from("The workspace that owns the repository.")),
672 "name" => Some(Value::from("The repository's name.")),
673 _ => schema.as_object_mut().and_then(|schema| schema.remove("description")),
674 };
675 let mut parameter = json!({
676 "name": name,
677 "in": place,
678 "required": required,
679 "schema": schema,
680 });
681 if let Some(description) = description {
682 parameter["description"] = description;
683 }
684 parameter
685}
686
687/// The operation id of a route. An operation reached at a workspace's
688/// address as well as a repository's is documented once for each, with its
689/// own id; GitHub's alternative addresses for one operation keep GitHub's
690/// names.
691fn operation_id(route: &Route) -> String {
692 let op = route.op;
693 let base = match (route.method, route.path.rsplit('/').next().unwrap_or_default()) {
694 ("PUT", "enable") => "enable_workflow".to_owned(),
695 ("PUT", "disable") => "disable_workflow".to_owned(),
696 ("POST", "rerun-failed-jobs") => "rerun_failed_jobs".to_owned(),
697 ("PATCH", ":setting") => "update_actions_variable".to_owned(),
698 ("GET", "runs") if route.path.contains("/workflows/:workflow/") => "list_runs_of_workflow".to_owned(),
699 // One repository's notifications, and an issue's subscription by
700 // its number rather than a thread's id.
701 (_, "notifications") if route.path.starts_with("/repos/") => match op {
702 Op::ListNotifications => "list_repo_notifications".to_owned(),
703 _ => "mark_repo_notifications_read".to_owned(),
704 },
705 (method, "subscription") if route.path.contains("/issues/:number/") => match method {
706 "GET" => "get_issue_subscription".to_owned(),
707 "PUT" => "set_issue_subscription".to_owned(),
708 _ => "delete_issue_subscription".to_owned(),
709 },
710 // One label off an issue, by its name in the path.
711 ("DELETE", ":label") if route.path.contains("/issues/:number/") => "remove_issue_label".to_owned(),
712 ("DELETE", "saved") => "unsave_thread".to_owned(),
713 ("DELETE", "snooze") => "unsnooze_thread".to_owned(),
714 _ => op.name().to_owned(),
715 };
716 if route.path.starts_with("/workspaces/") && ROUTES.iter().any(|other| other.op == op && other.path.starts_with("/repos/")) {
717 format!("{base}_for_workspace")
718 } else {
719 base
720 }
721}
722
723/// The summary of a route: its operation's title, or for one of GitHub's
724/// alternative addresses, what that address does.
725fn summary(route: &Route, id: &str) -> String {
726 let base = match id.trim_end_matches("_for_workspace") {
727 "enable_workflow" => "Turn a workflow on",
728 "disable_workflow" => "Turn a workflow off",
729 "rerun_failed_jobs" => "Re-run failed jobs",
730 "update_actions_variable" => "Update a variable",
731 "list_runs_of_workflow" => "List a workflow's runs",
732 "list_repo_notifications" => "List a repository's notifications",
733 "mark_repo_notifications_read" => "Mark a repository's notifications read",
734 "get_issue_subscription" => "Get your subscription to an issue",
735 "set_issue_subscription" => "Subscribe to an issue",
736 "delete_issue_subscription" => "Unsubscribe from an issue",
737 "unsave_thread" => "Unsave a thread",
738 "unsnooze_thread" => "Bring a snoozed thread back",
739 _ => title(route.op),
740 };
741 if id.ends_with("_for_workspace") {
742 format!("{base} for a workspace")
743 } else {
744 base.to_owned()
745 }
746}
747
748fn operation(route: &Route) -> Value {
749 let op = route.op;
750 let path_params: Vec<&str> = route.params().collect();
751 // `owner` and `name` in the path stand for the operation's `repo` input.
752 let covered = |name: &str| name == "repo" || path_params.contains(&name);
753 let all_properties = op.properties();
754 let mut properties = all_properties.clone();
755 properties.retain(|name, _| !covered(name));
756 let required: Vec<String> = op
757 .required()
758 .into_iter()
759 .filter(|name| !covered(name))
760 .collect();
761
762 let mut parameters: Vec<Value> = path_params
763 .iter()
764 .map(|name| parameter(name, "path", true, all_properties.get(*name)))
765 .collect();
766 let mut body = Value::Null;
767 if route.method == "GET" {
768 for (name, key) in route.query {
769 parameters.push(parameter(
770 name,
771 "query",
772 required.iter().any(|required| required == key),
773 properties.get(*key),
774 ));
775 }
776 } else if !properties.is_empty() {
777 let mut schema = json!({ "type": "object", "properties": properties });
778 if !required.is_empty() {
779 schema["required"] = json!(required);
780 }
781 body = json!({
782 "required": !required.is_empty(),
783 "content": { "application/json": { "schema": schema } },
784 });
785 }
786
787 let id = operation_id(route);
788 let mut responses = Map::new();
789 responses.insert(
790 "200".into(),
791 json!({
792 "description": "Success.",
793 "content": { "application/json": { "schema": {} } },
794 }),
795 );
796 responses.insert(
797 "401".into(),
798 error_response("A token is required, or the one sent is not valid."),
799 );
800 if let Some(reason) = may_need_payment(op) {
801 responses.insert("402".into(), error_response(reason));
802 }
803 responses.insert(
804 "403".into(),
805 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."),
806 );
807 if !matches!(op, Op::Whoami | Op::ListRepos | Op::Search) {
808 responses.insert("404".into(), error_response("It does not exist, or you cannot see it."));
809 }
810 if route.method != "GET" {
811 responses.insert(
812 "409".into(),
813 error_response("The request conflicts with the current state."),
814 );
815 }
816 if op != Op::Whoami {
817 responses.insert("422".into(), error_response("The input is not valid."));
818 }
819 // Public data can be read without a token; everything else needs one.
820 let scope: Vec<&str> = scope_for(op.name()).map(|scope| scope.as_str()).into_iter().collect();
821 let security = if op.needs_user() {
822 json!([{ "token": scope }])
823 } else {
824 json!([{ "token": scope }, {}])
825 };
826 let (tool, action) = crate::tools::TOOLS
827 .iter()
828 .find_map(|tool| {
829 tool.actions
830 .iter()
831 .find(|action| action.op == op)
832 .map(|action| (tool.name, action.name))
833 })
834 .unwrap_or_default();
835 let mut described = json!({
836 "operationId": id,
837 "tags": [tag(op)],
838 "summary": summary(route, &id),
839 "description": op.description(),
840 "x-operation": op.name(),
841 "x-mcp-tool": tool,
842 "x-mcp-action": action,
843 "x-scope": scope.first().copied(),
844 "security": security,
845 "parameters": parameters,
846 "responses": responses,
847 });
848 if !body.is_null() {
849 described["requestBody"] = body;
850 }
851 described
852}
853
854/// Entries for device sign-in, which is not an operation.
855fn onboarding() -> Map<String, Value> {
856 let paths = json!({
857 "/device/code": {
858 "post": {
859 "operationId": "device_code",
860 "tags": ["Accounts"],
861 "summary": "Start signing in",
862 "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`.",
863 "security": [],
864 "requestBody": {
865 "content": { "application/json": { "schema": {
866 "type": "object",
867 "properties": {
868 "client_name": {
869 "type": "string",
870 "description": "What is asking, shown to the person approving. For example, Claude Code.",
871 },
872 },
873 } } },
874 },
875 "responses": { "200": {
876 "description": "The codes for this sign-in.",
877 "content": { "application/json": { "schema": {
878 "type": "object",
879 "properties": {
880 "device_code": { "type": "string", "description": "Secret. Send it to /device/token." },
881 "user_code": { "type": "string", "description": "Shown to the person, like WDJB-MJHT." },
882 "verification_uri": { "type": "string" },
883 "verification_uri_complete": {
884 "type": "string",
885 "description": "The link to give the person; it carries the code.",
886 },
887 "expires_in": { "type": "integer", "description": "Seconds until the codes expire." },
888 "interval": { "type": "integer", "description": "Seconds to wait between polls." },
889 },
890 } } },
891 } },
892 },
893 },
894 "/device/token": {
895 "post": {
896 "operationId": "device_token",
897 "tags": ["Accounts"],
898 "summary": "Finish signing in",
899 "description": "Asks whether the person has approved. Poll no faster than the interval. The token is returned once.",
900 "security": [],
901 "requestBody": {
902 "required": true,
903 "content": { "application/json": { "schema": {
904 "type": "object",
905 "required": ["device_code"],
906 "properties": { "device_code": { "type": "string" } },
907 } } },
908 },
909 "responses": { "200": {
910 "description": "The state of the sign-in.",
911 "content": { "application/json": { "schema": {
912 "type": "object",
913 "required": ["status"],
914 "properties": {
915 "status": { "type": "string", "enum": ["pending", "approved", "denied", "expired"] },
916 "token": { "type": "string", "description": "Present when approved." },
917 "username": { "type": "string" },
918 "verified": {
919 "type": "boolean",
920 "description": "Whether the account's email is confirmed.",
921 },
922 },
923 } } },
924 } },
925 },
926 },
927 });
928 match paths {
929 Value::Object(paths) => paths,
930 _ => Map::new(),
931 }
932}
933
934
935/// Puts each operation's examples, where it has them, into its request
936/// and response. Path and query values go under `x-example-params` and
937/// `x-example-query`, which tools that build a request can use.
938fn attach_examples(paths: &mut Map<String, Value>) {
939 let examples = examples();
940 for methods in paths.values_mut() {
941 let Some(methods) = methods.as_object_mut() else { continue };
942 for operation in methods.values_mut() {
943 let id = operation["operationId"].as_str().unwrap_or_default().to_owned();
944 let name = operation["x-operation"].as_str().unwrap_or_default().to_owned();
945 let Some(example) = examples.get(&id).or_else(|| examples.get(&name)) else {
946 continue;
947 };
948 if let Some(notes) = example.get("notes").and_then(Value::as_str) {
949 let description = operation["description"].as_str().unwrap_or_default();
950 operation["description"] = json!(format!("{description}\n\n{notes}"));
951 }
952 if let Some(response) = example.get("response") {
953 let content = &mut operation["responses"]["200"]["content"]["application/json"];
954 if content.is_object() {
955 content["example"] = response.clone();
956 }
957 }
958 if let Some(request) = example.get("request") {
959 let content = &mut operation["requestBody"]["content"]["application/json"];
960 if content.is_object() {
961 content["example"] = request.clone();
962 }
963 }
964 for (key, extension) in [("params", "x-example-params"), ("query", "x-example-query")] {
965 if let Some(values) = example.get(key) {
966 operation[extension] = values.clone();
967 }
968 }
969 }
970 }
971}
972
973pub fn document() -> Value {
974 let mut paths = onboarding();
975 for route in ROUTES {
976 let entry = paths
977 .entry(openapi_path(route))
978 .or_insert_with(|| json!({}));
979 entry[route.method.to_lowercase()] = operation(route);
980 }
981 attach_examples(&mut paths);
982 let tags: Vec<Value> = SECTIONS
983 .iter()
984 .map(|(name, description, ops)| {
985 json!({
986 "name": name,
987 "description": description,
988 // The section's operations in reading order, by MCP tool name.
989 "x-tools": ops.iter().map(|op| op.name()).collect::<Vec<_>>(),
990 })
991 })
992 .collect();
993 let codes = ["unauthenticated", "payment_required", "forbidden", "not_found", "conflict", "invalid"];
994 json!({
995 "openapi": "3.1.0",
996 "info": {
997 "title": "g1t API",
998 "version": "1",
999 "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.",
1000 "license": { "name": "MIT", "identifier": "MIT" },
1001 },
1002 "servers": [{ "url": "https://api.g1t.sh" }],
1003 "security": [{ "token": [] }, {}],
1004 "tags": tags,
1005 "paths": paths,
1006 "components": {
1007 "securitySchemes": {
1008 "token": {
1009 "type": "http",
1010 "scheme": "bearer",
1011 "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.",
1012 },
1013 },
1014 "schemas": {
1015 "Error": {
1016 "type": "object",
1017 "required": ["error"],
1018 "properties": {
1019 "error": {
1020 "type": "object",
1021 "required": ["code", "message"],
1022 "properties": {
1023 "code": { "type": "string", "enum": codes },
1024 "message": { "type": "string" },
1025 "needed_scope": {
1026 "type": "string",
1027 "description": "On a 403 for an access token without the scope the call needs: that scope, such as `issues:write`.",
1028 },
1029 },
1030 },
1031 },
1032 },
1033 },
1034 },
1035 })
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040 use super::*;
1041
1042 #[test]
1043 fn every_route_is_documented_once() {
1044 let document = document();
1045 let mut ids = Vec::new();
1046 for (_, methods) in document["paths"].as_object().unwrap() {
1047 for (_, operation) in methods.as_object().unwrap() {
1048 ids.push(operation["operationId"].as_str().unwrap().to_owned());
1049 }
1050 }
1051 for op in Op::ALL {
1052 assert_eq!(
1053 ids.iter().filter(|id| *id == op.name()).count(),
1054 1,
1055 "{}",
1056 op.name()
1057 );
1058 }
1059 let mut unique = ids.clone();
1060 unique.sort();
1061 unique.dedup();
1062 assert_eq!(unique.len(), ids.len(), "operation ids repeat");
1063 }
1064
1065 #[test]
1066 fn path_and_query_inputs_are_not_repeated_in_the_body() {
1067 let document = document();
1068 let merge = &document["paths"]["/repos/{owner}/{name}/pulls/{number}/merge"]["post"];
1069 let body = &merge["requestBody"]["content"]["application/json"]["schema"]["properties"];
1070 assert!(body.get("keep_issue_open").is_some());
1071 assert!(body.get("repo").is_none() && body.get("number").is_none());
1072 let list = &document["paths"]["/repos"]["get"];
1073 assert_eq!(list["parameters"][0]["name"], "q");
1074 assert!(list.get("requestBody").is_none());
1075 }
1076
1077 #[test]
1078 fn every_operation_is_in_one_section() {
1079 for op in Op::ALL {
1080 let sections = SECTIONS
1081 .iter()
1082 .filter(|(_, _, ops)| ops.contains(&op))
1083 .count();
1084 assert_eq!(sections, 1, "{}", op.name());
1085 }
1086 }
1087
1088 #[test]
1089 fn titles_read_as_sentences() {
1090 assert_eq!(title(Op::CreateIssue), "Create an issue");
1091 assert_eq!(title(Op::Whoami), "Get the current user");
1092 }
1093
1094 #[test]
1095 fn every_operation_has_an_example_response() {
1096 let examples = examples();
1097 assert!(!examples.is_empty(), "reference.json does not parse");
1098 let document = document();
1099 let mut known = Vec::new();
1100 for (path, methods) in document["paths"].as_object().unwrap() {
1101 for (method, operation) in methods.as_object().unwrap() {
1102 known.push(operation["operationId"].as_str().unwrap().to_owned());
1103 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
1104 assert!(!example.is_null(), "{method} {path} has no example response");
1105 }
1106 }
1107 for id in examples.keys() {
1108 assert!(known.contains(id), "reference.json names {id}, which is not an operation");
1109 }
1110 }
1111
1112 #[test]
1113 fn example_requests_send_only_what_the_body_takes() {
1114 let document = document();
1115 for (path, methods) in document["paths"].as_object().unwrap() {
1116 for (method, operation) in methods.as_object().unwrap() {
1117 let content = &operation["requestBody"]["content"]["application/json"];
1118 let Some(example) = content["example"].as_object() else { continue };
1119 let properties = &content["schema"]["properties"];
1120 for key in example.keys() {
1121 assert!(!properties[key].is_null(), "{method} {path}: {key} is not in the body");
1122 }
1123 }
1124 }
1125 }
1126
1127 /// The docs site's copy of the document. Run with `G1T_WRITE_OPENAPI=1`
1128 /// to rewrite it after changing an operation.
1129 #[test]
1130 fn the_docs_copy_is_current() {
1131 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../docs/src/data/openapi.json");
1132 let current = serde_json::to_string_pretty(&document()).unwrap() + "\n";
1133 if std::env::var_os("G1T_WRITE_OPENAPI").is_some() {
1134 std::fs::write(path, &current).unwrap();
1135 return;
1136 }
1137 let copy = std::fs::read_to_string(path).unwrap_or_default().replace("\r\n", "\n");
1138 assert!(
1139 copy == current,
1140 "apps/docs/src/data/openapi.json is out of date: run G1T_WRITE_OPENAPI=1 cargo test -p g1t-api openapi"
1141 );
1142 }
1143
1144 /// The reference shows responses as they are sent: `snake_case`.
1145 #[test]
1146 fn example_responses_are_snake_case() {
1147 let document = document();
1148 for (path, methods) in document["paths"].as_object().unwrap() {
1149 for (method, operation) in methods.as_object().unwrap() {
1150 let example = &operation["responses"]["200"]["content"]["application/json"]["example"];
1151 let leaked = g1t_kit::wire::camel_case_keys(example);
1152 assert!(leaked.is_empty(), "{method} {path} shows {leaked:?}");
1153 }
1154 }
1155 }
1156
1157 /// Examples never hold anything that reads as a real credential, which
1158 /// secret scanners rightly flag in a public repository: they end in `…`
1159 /// after the prefix, as `whsec_…` and `g1t_…` do.
1160 #[test]
1161 fn examples_hold_no_real_looking_secrets() {
1162 let prefixes = ["whsec_", "g1t_", "g1tr_", "g1trt_", "sk_live_", "sk_test_", "ghp_", "github_pat_", "xoxb-", "AKIA"];
1163 for (line, text) in REFERENCE.lines().enumerate() {
1164 for prefix in prefixes {
1165 let mut rest = text;
1166 while let Some(at) = rest.find(prefix) {
1167 let after = &rest[at + prefix.len()..];
1168 let run = after.chars().take_while(|c| c.is_ascii_alphanumeric()).count();
1169 assert!(
1170 run < 12,
1171 "reference.json line {}: `{prefix}` followed by {run} characters reads as a real secret; write `{prefix}…`",
1172 line + 1
1173 );
1174 rest = after;
1175 }
1176 }
1177 }
1178 }
1179}