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