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