The best way to control Claude Code, Codex and more from any computer or phone

main
ts 678 lines 19 KB
Raw
1 import * as Repos from "@distilled.cloud/github/repos";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import { withBaseUrl, gitHubBaseUrlChanged } from "./BaseUrl.ts";
9 import type * as GitHub from "./Providers.ts";
10
11 export interface RulesetProps {
12 /**
13 * Repository owner — a user or organization login.
14 */
15 owner: string;
16
17 /**
18 * Repository name.
19 */
20 repository: string;
21
22 /**
23 * Ruleset name. The name is displayed in the GitHub UI and can be updated.
24 */
25 name: string;
26
27 /**
28 * The enforcement level of the ruleset. Can be `disabled`, `active`, or
29 * `evaluate` (log-only mode).
30 * @default "active"
31 */
32 enforcement?: "disabled" | "active" | "evaluate";
33
34 /**
35 * Whether the ruleset targets branches or tags.
36 * @default "branch"
37 */
38 target?: "branch" | "tag";
39
40 /**
41 * Conditions for targeting refs. When omitted, applies to all refs of the
42 * target type.
43 */
44 conditions?: {
45 /**
46 * Ref patterns to include (e.g. `["refs/heads/main", "refs/heads/release/*"]`).
47 * Supports glob patterns.
48 */
49 include?: string[];
50
51 /**
52 * Ref patterns to exclude (e.g. `["refs/heads/dev/*"]`).
53 * Supports glob patterns.
54 */
55 exclude?: string[];
56 };
57
58 /**
59 * Actors allowed to bypass the ruleset. Omit to allow no bypasses.
60 */
61 bypassActors?: Array<{
62 /**
63 * The type of actor that can bypass the ruleset.
64 */
65 actorType: "RepositoryRole" | "Team" | "Integration" | "OrganizationAdmin";
66
67 /**
68 * The ID of the actor (role ID, team ID, or integration ID).
69 * RepositoryRole IDs are 2 for write, 4 for maintain, and 5 for admin.
70 */
71 actorId?: number;
72
73 /**
74 * Whether the actor can always bypass or only through pull requests.
75 * @default "always"
76 */
77 bypassMode?: "always" | "pull_request";
78 }>;
79
80 /**
81 * Require status checks to pass before merging.
82 */
83 requiredStatusChecks?: {
84 /**
85 * Status checks that must pass. Each entry is a context name or
86 * integration ID.
87 */
88 checks: Array<{
89 /**
90 * The status check context name.
91 */
92 context: string;
93
94 /**
95 * Optional integration ID.
96 */
97 integrationId?: number;
98 }>;
99
100 /**
101 * Whether to require branches to be up to date before merging.
102 * @default false
103 */
104 strictRequiredStatusChecksPolicy?: boolean;
105 };
106
107 /**
108 * Require commits to be signed.
109 */
110 requiredSignatures?: boolean;
111
112 /**
113 * Require pull request before merging.
114 */
115 pullRequest?: {
116 /**
117 * Number of required approving reviews.
118 */
119 requiredApprovingReviewCount?: number;
120
121 /**
122 * Dismiss stale reviews when new commits are pushed.
123 */
124 dismissStaleReviewsOnPush?: boolean;
125
126 /**
127 * Require review from code owners.
128 */
129 requireCodeOwnerReview?: boolean;
130
131 /**
132 * Require approval of the most recent reviewable push.
133 */
134 requireLastPushApproval?: boolean;
135
136 /**
137 * Required review thread resolution.
138 */
139 requiredReviewThreadResolution?: boolean;
140
141 /**
142 * Merge methods allowed for pull requests. GitHub allows all three when omitted.
143 */
144 allowedMergeMethods?: Array<"merge" | "squash" | "rebase">;
145
146 /**
147 * Require another approval for changes pushed by someone other than the commit author.
148 * @default true
149 */
150 requireExtraApprovalForUnattributedChanges?: boolean;
151 };
152
153 /**
154 * Prevent creation of matching refs.
155 */
156 creation?: boolean;
157
158 /**
159 * Prevent updates to matching refs.
160 */
161 update?: boolean;
162
163 /**
164 * Prevent deletion of matching refs.
165 */
166 deletion?: boolean;
167
168 /**
169 * Require linear history.
170 */
171 requiredLinearHistory?: boolean;
172
173 /**
174 * Prevent force pushes.
175 */
176 nonFastForward?: boolean;
177
178 /**
179 * Require pull requests to merge through a merge queue. Only applies to
180 * branch rulesets in organization-owned repositories.
181 */
182 mergeQueue?: {
183 /**
184 * Method used to merge the queued pull requests.
185 * @default "MERGE"
186 */
187 mergeMethod?: "MERGE" | "SQUASH" | "REBASE";
188
189 /**
190 * `ALLGREEN` requires every entry's checks to pass; `HEADGREEN` only
191 * requires the checks of the group's head commit.
192 * @default "ALLGREEN"
193 */
194 groupingStrategy?: "ALLGREEN" | "HEADGREEN";
195
196 /**
197 * Maximum number of queued pull requests building at the same time.
198 * @default 5
199 */
200 maxEntriesToBuild?: number;
201
202 /**
203 * Minimum number of pull requests merged together in a group.
204 * @default 1
205 */
206 minEntriesToMerge?: number;
207
208 /**
209 * Maximum number of pull requests merged together in a group.
210 * @default 5
211 */
212 maxEntriesToMerge?: number;
213
214 /**
215 * Minutes to wait for `minEntriesToMerge` pull requests after the first
216 * one is queued before merging a smaller group.
217 * @default 5
218 */
219 minEntriesToMergeWaitMinutes?: number;
220
221 /**
222 * Minutes to wait for a required status check before treating it as failed.
223 * @default 60
224 */
225 checkResponseTimeoutMinutes?: number;
226 };
227
228 /**
229 * Override the GitHub host or API base URL for this resource only (e.g.
230 * `github.example.com` for GitHub Enterprise). Falls back to
231 * `GitHub.providers({ baseUrl })`, then to the host resolved by the auth
232 * provider. Changing it replaces the resource — the same name on a
233 * different GitHub instance is a different physical resource.
234 */
235 baseUrl?: string;
236 }
237
238 /**
239 * Props as persisted before the rules moved from a nested `rules` object to
240 * the top level. Only previously deployed state can still have this shape.
241 */
242 type PersistedRulesetProps = RulesetProps & {
243 rules?: Pick<
244 RulesetProps,
245 | "requiredStatusChecks"
246 | "requiredSignatures"
247 | "pullRequest"
248 | "creation"
249 | "update"
250 | "deletion"
251 | "requiredLinearHistory"
252 | "nonFastForward"
253 | "mergeQueue"
254 >;
255 };
256
257 /**
258 * Lifts the rules of persisted props out of the legacy nested `rules` object.
259 */
260 const upgradeProps = ({ rules, ...props }: PersistedRulesetProps): RulesetProps => ({
261 ...rules,
262 ...props,
263 });
264
265 export interface Ruleset extends Resource<
266 "GitHub.Ruleset",
267 RulesetProps,
268 {
269 /**
270 * Numeric GitHub ruleset ID.
271 */
272 rulesetId: number;
273
274 /**
275 * GraphQL node ID of the ruleset, when returned by GitHub.
276 */
277 nodeId: string | undefined;
278
279 /**
280 * The ruleset name.
281 */
282 name: string;
283
284 /**
285 * ISO-8601 timestamp of when the ruleset was created.
286 */
287 createdAt: string | undefined;
288
289 /**
290 * ISO-8601 timestamp of the last update.
291 */
292 updatedAt: string | undefined;
293 },
294 never,
295 GitHub.Providers
296 > {}
297
298 /**
299 * A GitHub repository ruleset.
300 *
301 * `Ruleset` manages branch and tag protection rules at the repository level.
302 * Rulesets replace the legacy branch protection API with a more flexible
303 * system that can target multiple branches or tags with a single ruleset.
304 *
305 * Rulesets default to **retain** on removal — destroying the stack does NOT
306 * delete the ruleset on GitHub, protecting production branches from
307 * accidental removal. Opt in to actual deletion by wrapping the resource in
308 * {@link destroy}() from `alchemy/RemovalPolicy`.
309 *
310 * Authentication is resolved via the GitHub `Credentials` service supplied by
311 * `GitHub.providers()` (env, stored PAT, `gh` CLI, or OAuth). The token needs
312 * `repo` scope, or repository Administration write permission for a
313 * fine-grained token. Ruleset deletion does not require `delete_repo`.
314 *
315 * ### Creating a Ruleset
316 * **Example:** Protect Main Branch
317 * ```typescript
318 * yield* GitHub.Ruleset("main-protection", {
319 * owner: "my-org",
320 * repository: "my-repo",
321 * name: "main protection",
322 * target: "branch",
323 * conditions: {
324 * include: ["refs/heads/main"],
325 * },
326 * nonFastForward: true,
327 * deletion: true,
328 * requiredLinearHistory: true,
329 * })
330 * ```
331 *
332 * **Example:** Require PR Reviews
333 * ```typescript
334 * yield* GitHub.Ruleset("pr-reviews", {
335 * owner: "my-org",
336 * repository: "my-repo",
337 * name: "require reviews",
338 * target: "branch",
339 * conditions: {
340 * include: ["refs/heads/main", "refs/heads/release/*"],
341 * },
342 * pullRequest: {
343 * requiredApprovingReviewCount: 2,
344 * requireCodeOwnerReview: true,
345 * dismissStaleReviewsOnPush: true,
346 * requiredReviewThreadResolution: true,
347 * },
348 * })
349 * ```
350 *
351 * ### Status Checks
352 * **Example:** Require CI to Pass
353 * ```typescript
354 * yield* GitHub.Ruleset("ci-checks", {
355 * owner: "my-org",
356 * repository: "my-repo",
357 * name: "CI required",
358 * target: "branch",
359 * conditions: {
360 * include: ["refs/heads/main"],
361 * },
362 * requiredStatusChecks: {
363 * checks: [
364 * { context: "ci/test" },
365 * { context: "ci/lint" },
366 * ],
367 * strictRequiredStatusChecksPolicy: true,
368 * },
369 * })
370 * ```
371 *
372 * ### Merge Queue
373 * GitHub only supports merge queues on branch rulesets in
374 * organization-owned repositories.
375 *
376 * **Example:** Merge Through a Squash Merge Queue
377 * ```typescript
378 * yield* GitHub.Ruleset("merge-queue", {
379 * owner: "my-org",
380 * repository: "my-repo",
381 * name: "Merge queue",
382 * conditions: {
383 * include: ["~DEFAULT_BRANCH"],
384 * },
385 * mergeQueue: {
386 * mergeMethod: "SQUASH",
387 * groupingStrategy: "ALLGREEN",
388 * maxEntriesToBuild: 2,
389 * maxEntriesToMerge: 1,
390 * minEntriesToMergeWaitMinutes: 1,
391 * },
392 * })
393 * ```
394 *
395 * ### Bypass Actors
396 * **Example:** Allow Admins to Bypass
397 * ```typescript
398 * yield* GitHub.Ruleset("protected-with-bypass", {
399 * owner: "my-org",
400 * repository: "my-repo",
401 * name: "protected with bypass",
402 * target: "branch",
403 * conditions: {
404 * include: ["refs/heads/main"],
405 * },
406 * bypassActors: [
407 * { actorType: "RepositoryRole", actorId: 5 },
408 * ],
409 * nonFastForward: true,
410 * })
411 * ```
412 *
413 * ### Adopting an Existing Ruleset
414 * Ruleset names are unique per repository. A ruleset that already exists
415 * with the same name is foreign until you opt in with `adopt(true)` or
416 * `--adopt`; adoption then converges it to the declared props in place.
417 *
418 * **Example:** Take over a ruleset created in the GitHub UI
419 * ```typescript
420 * import { adopt } from "alchemy/AdoptPolicy";
421 *
422 * yield* GitHub.Ruleset("main-protection", {
423 * owner: "my-org",
424 * repository: "my-repo",
425 * name: "main protection",
426 * conditions: {
427 * include: ["~DEFAULT_BRANCH"],
428 * },
429 * deletion: true,
430 * nonFastForward: true,
431 * }).pipe(adopt(true))
432 * ```
433 *
434 * @resource
435 * @product Repository
436 */
437 export const Ruleset = Resource<Ruleset>("GitHub.Ruleset", {
438 defaultRemovalPolicy: "retain",
439 });
440
441 export const RulesetProvider = () =>
442 Provider.succeed(Ruleset, {
443 stables: ["rulesetId", "nodeId"],
444
445 diff: Effect.fn(function* ({ news, olds: persisted }) {
446 if (!isResolved(news)) return;
447 if (persisted === undefined) return;
448 const olds = upgradeProps(persisted);
449 if (
450 news.owner !== olds.owner ||
451 news.repository !== olds.repository ||
452 (yield* gitHubBaseUrlChanged(olds, news))
453 ) {
454 return { action: "replace" };
455 }
456 // State persisted with nested rules declares the same ruleset as the
457 // top-level rules it upgrades to.
458 if ("rules" in persisted && deepEqual(olds, news, { stripNullish: true })) {
459 return { action: "noop" };
460 }
461 }),
462
463 reconcile: Effect.fn(
464 function* ({ news, output }) {
465 let observed = output === undefined ? undefined : yield* getRuleset(news, output.rulesetId);
466
467 const rules: NonNullable<Repos.CreateRepoRulesetRequest["rules"]> = [];
468
469 if (news.creation) {
470 rules.push({ type: "creation" });
471 }
472 if (news.update) {
473 rules.push({
474 type: "update",
475 parameters: { update_allows_fetch_and_merge: false },
476 });
477 }
478 if (news.deletion) {
479 rules.push({ type: "deletion" });
480 }
481 if (news.nonFastForward) {
482 rules.push({ type: "non_fast_forward" });
483 }
484 if (news.requiredLinearHistory) {
485 rules.push({ type: "required_linear_history" });
486 }
487 if (news.requiredSignatures) {
488 rules.push({ type: "required_signatures" });
489 }
490 if (news.pullRequest) {
491 const pullRequest = news.pullRequest;
492 // `require_extra_approval_for_unattributed_changes` is accepted by the API but missing
493 // from its OpenAPI description, so it is added outside the typed literal.
494 const parameters = {
495 required_approving_review_count: pullRequest.requiredApprovingReviewCount ?? 0,
496 dismiss_stale_reviews_on_push: pullRequest.dismissStaleReviewsOnPush ?? false,
497 require_code_owner_review: pullRequest.requireCodeOwnerReview ?? false,
498 require_last_push_approval: pullRequest.requireLastPushApproval ?? false,
499 required_review_thread_resolution: pullRequest.requiredReviewThreadResolution ?? false,
500 ...(pullRequest.allowedMergeMethods !== undefined && {
501 allowed_merge_methods: pullRequest.allowedMergeMethods,
502 }),
503 ...(pullRequest.requireExtraApprovalForUnattributedChanges !== undefined && {
504 require_extra_approval_for_unattributed_changes:
505 pullRequest.requireExtraApprovalForUnattributedChanges,
506 }),
507 };
508 rules.push({ type: "pull_request", parameters });
509 }
510 if (news.mergeQueue) {
511 const mergeQueue = news.mergeQueue;
512 rules.push({
513 type: "merge_queue",
514 parameters: {
515 merge_method: mergeQueue.mergeMethod ?? "MERGE",
516 grouping_strategy: mergeQueue.groupingStrategy ?? "ALLGREEN",
517 max_entries_to_build: mergeQueue.maxEntriesToBuild ?? 5,
518 min_entries_to_merge: mergeQueue.minEntriesToMerge ?? 1,
519 max_entries_to_merge: mergeQueue.maxEntriesToMerge ?? 5,
520 min_entries_to_merge_wait_minutes: mergeQueue.minEntriesToMergeWaitMinutes ?? 5,
521 check_response_timeout_minutes: mergeQueue.checkResponseTimeoutMinutes ?? 60,
522 },
523 });
524 }
525 if (news.requiredStatusChecks) {
526 rules.push({
527 type: "required_status_checks",
528 parameters: {
529 required_status_checks: news.requiredStatusChecks.checks.map((check) => ({
530 context: check.context,
531 integration_id: check.integrationId,
532 })),
533 strict_required_status_checks_policy:
534 news.requiredStatusChecks.strictRequiredStatusChecksPolicy ?? false,
535 },
536 });
537 }
538
539 const conditions = {
540 ref_name: {
541 include: news.conditions?.include ?? ["~ALL"],
542 exclude: news.conditions?.exclude ?? [],
543 },
544 };
545
546 // Build the bypass actors payload
547 const bypassActors = news.bypassActors?.map((actor) => ({
548 actor_type: actor.actorType,
549 actor_id: actor.actorId,
550 bypass_mode: actor.bypassMode ?? "always",
551 }));
552
553 const desired = {
554 name: news.name,
555 target: news.target ?? "branch",
556 enforcement: news.enforcement ?? "active",
557 bypass_actors: bypassActors ?? [],
558 conditions,
559 rules,
560 } satisfies Omit<Repos.CreateRepoRulesetRequest, "owner" | "repo">;
561
562 if (observed === undefined) {
563 observed = yield* Repos.createRepoRuleset({
564 owner: news.owner,
565 repo: news.repository,
566 ...desired,
567 });
568 }
569
570 if (
571 !deepEqual(
572 {
573 name: observed.name,
574 target: observed.target,
575 enforcement: observed.enforcement,
576 bypass_actors: observed.bypass_actors ?? [],
577 conditions: observed.conditions,
578 rules: observed.rules ?? [],
579 },
580 desired,
581 )
582 ) {
583 const rulesetId = observed.id;
584 observed = yield* Repos.updateRepoRuleset({
585 owner: news.owner,
586 repo: news.repository,
587 ruleset_id: rulesetId,
588 ...desired,
589 });
590 }
591
592 return attrsOf(observed);
593 },
594 (effect, { news }) => effect.pipe(withBaseUrl(news.baseUrl)),
595 ),
596
597 read: Effect.fn(
598 function* ({ olds, output }) {
599 if (output !== undefined) {
600 const observed = yield* getRuleset(olds, output.rulesetId);
601 return observed === undefined ? undefined : attrsOf(observed);
602 }
603 const rulesets = yield* Stream.runCollect(
604 Repos.getRepoRulesets.items({
605 owner: olds.owner,
606 repo: olds.repository,
607 includes_parents: false,
608 per_page: 100,
609 }),
610 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([])));
611 const match = rulesets.find((ruleset) => ruleset.name === olds.name);
612 if (match === undefined) return undefined;
613 const observed = yield* getRuleset(olds, match.id);
614 return observed === undefined ? undefined : Unowned(attrsOf(observed));
615 },
616 (effect, { olds }) => effect.pipe(withBaseUrl(olds.baseUrl)),
617 ),
618
619 list: Effect.fn(function* () {
620 const repos = yield* Stream.runCollect(
621 Repos.listForAuthenticatedUser.items({ per_page: 100 }),
622 );
623 const perRepo = yield* Effect.forEach(
624 repos,
625 (repo) =>
626 Stream.runCollect(
627 Repos.getRepoRulesets.items({
628 owner: repo.owner.login,
629 repo: repo.name,
630 includes_parents: false,
631 per_page: 100,
632 }),
633 ).pipe(
634 Effect.map((rulesets) => rulesets.map(attrsOf)),
635 Effect.catchTag(["Forbidden", "NotFound"], () => Effect.succeed([])),
636 ),
637 { concurrency: 10 },
638 );
639 return perRepo.flat();
640 }),
641
642 delete: Effect.fn(
643 function* ({ olds, output }) {
644 if (output?.rulesetId === undefined) return;
645 yield* Repos.deleteRepoRuleset({
646 owner: olds.owner,
647 repo: olds.repository,
648 ruleset_id: output.rulesetId,
649 }).pipe(Effect.catchTag("NotFound", () => Effect.void));
650 },
651 (effect, { olds }) => effect.pipe(withBaseUrl(olds.baseUrl)),
652 ),
653 });
654
655 const getRuleset = Effect.fn(
656 function* (props: Pick<RulesetProps, "owner" | "repository" | "baseUrl">, rulesetId: number) {
657 return yield* Repos.getRepoRuleset({
658 owner: props.owner,
659 repo: props.repository,
660 ruleset_id: rulesetId,
661 }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
662 },
663 (effect, props) => effect.pipe(withBaseUrl(props.baseUrl)),
664 );
665
666 const attrsOf = (ruleset: {
667 id: number;
668 node_id?: string;
669 name: string;
670 created_at?: string;
671 updated_at?: string;
672 }) => ({
673 rulesetId: ruleset.id,
674 nodeId: ruleset.node_id,
675 name: ruleset.name,
676 createdAt: ruleset.created_at,
677 updatedAt: ruleset.updated_at,
678 });