Skip to content

g1t/apps/api/src/openapi.rs

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