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