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