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