Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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