# @render-lab/tasks-github

> ⚠️ **Experimental: proof of concept.** This package is part of the [Render Tasks](https://github.com/render-lab/render-tasks) POC and is published for testing only. It is not fully tested or production ready. Task names, inputs, outputs, and behavior can change or break in any release. Pin exact versions and expect breaking changes.

Durable GitHub tasks for [Render Workflows](https://render.com/docs/workflows).

```ts
import {
  listNewIssues,
  applyLabels,
  openPR,
  reviewPR,
  mergeWhenGreen,
  dispatchWorkflow,
  searchCode,
  searchRepositories,
  createIssue,
  getIssue,
  commentOnIssue,
  updateIssue,
  getPR,
  getFileContents,
  commitFile,
  getRepository,
  ensureOrganizationRepository,
  updateRepository,
  deleteRepository,
  listOrganizationRepositories,
  getBranch,
  createBranch,
  deleteBranch,
  listPRs,
  commitFiles,
} from "@render-lab/tasks-github";
```

| Task                                  | Input                                              | Output              |
| ------------------------------------- | -------------------------------------------------- | ------------------- |
| `github.listNewIssues`                | `{ repo, sinceISO?, limit? }`                      | `IssueDTO[]`        |
| `github.applyLabels`                  | `{ repo, issueNumber, labels }`                    | `{ issueNumber, labels }` |
| `github.openPR`                       | `{ repo, title, head, base, body?, draft? }`       | `PullRequestDTO`    |
| `github.reviewPR`                     | `{ repo, number, event, body?, comments? }`        | `ReviewResult`      |
| `github.mergeWhenGreen`               | `{ repo, number, method? }`                        | `MergeResult`       |
| `github.dispatchWorkflow`             | `{ repo, workflowId, ref, inputs? }`               | `DispatchResult`    |
| `github.searchCode`                   | `{ query, limit? }`                                | `CodeHitDTO[]`      |
| `github.searchRepositories`           | `{ query, limit? }`                                | `RepositoryDTO[]`   |
| `github.createIssue`                  | `{ repo, title, body?, labels?, assignees? }`      | `IssueDTO`          |
| `github.getIssue`                     | `{ repo, number }`                                 | `IssueDTO`          |
| `github.commentOnIssue`               | `{ repo, number, body }`                           | `{ id, url }`       |
| `github.updateIssue`                  | `{ repo, number, state?, body?, assignees?, labels? }` | `IssueDTO`      |
| `github.getPR`                        | `{ repo, number }`                                 | `PullRequestDetailDTO` |
| `github.getFileContents`              | `{ repo, path, ref? }`                             | `FileContentsDTO`   |
| `github.commitFile`                   | `{ repo, path, content, message, branch?, sha? }`  | `{ commitSha, contentSha, path }` |
| `github.getRepository`                | `{ owner, repo }`                                  | `{ repository }`    |
| `github.ensureOrganizationRepository` | `{ org, name, ...settings }`                       | `{ repository, created }` |
| `github.updateRepository`             | `{ owner, repo, ...settings }`                     | `{ repository }`    |
| `github.deleteRepository`             | `{ owner, repo }`                                  | `{ owner, repo, deleted, alreadyMissing }` |
| `github.listOrganizationRepositories` | `{ org, type?, sort?, direction?, pageSize?, startPage?, limit?, namePrefix? }` | `{ repositories, nextPage }` |
| `github.getBranch`                    | `{ owner, repo, branch }`                          | `{ branch }`        |
| `github.createBranch`                 | `{ owner, repo, branch, from? }`                   | `{ branch, sha, created }` |
| `github.deleteBranch`                 | `{ owner, repo, branch }`                          | `{ branch, deleted, alreadyMissing }` |
| `github.listPRs`                      | `{ repo, head?, base?, state?, limit? }`           | `PullRequestDTO[]`  |
| `github.commitFiles`                  | `{ owner, repo, branch, message, files, expectedHeadSha? }` | `{ commitSha, treeSha, branch, fileCount }` |

`repo` is `"owner/name"`. `listNewIssues` returns open issues, newest first, with pull requests filtered out. `applyLabels` is a **pure writer** — dry-run behavior belongs in the caller, not this task, so it never silently no-ops on other consumers.

`reviewPR` accepts optional inline `comments: [{ path, position?, line?, side?, body }]`. `position` is a location in the PR's unified diff, not a file line number — for a file the PR adds from scratch, diff position ≈ line index + 1. Prefer `line`/`side` where possible.

`deleteBranch` is convergent (an already-missing branch returns `alreadyMissing: true`), and `listPRs` filters by head branch — the pair a cleanup flow needs to close a branch's PR and remove the branch. `createBranch` is **find-or-create** (convergent): it resolves the base head (`from`, defaulting to the repository's default branch) and creates the ref; if the branch already exists it returns the existing head with `created: false` instead of throwing, so retries and re-runs never fail on their own earlier success.

`mergeWhenGreen` is a **durable wait**: SDK 1.0 has no native await primitive, so it polls PR check state via throw-to-retry — it throws (`checks pending`) while checks run, which the baked-in `GITHUB_RETRY` re-runs until they resolve. Green → it merges; failing → it throws `checks failing` so a human is alerted instead of the PR silently merging.

`getFileContents` decodes GitHub's base64 blob to UTF-8. `commitFile` is a **read-modify-write**: pass a `sha` to update a known blob, or omit it and the task looks up the current file's SHA first (creating the file if it doesn't exist) so an update never 409s on a stale/absent SHA.

`RepositoryDTO` is a stable repository shape: `{ id, nodeId, owner, name, fullName, htmlUrl, cloneUrl, sshUrl, defaultBranch, visibility, isTemplate, archived, disabled, createdAt, updatedAt, pushedAt, stars, forks, isFork, language, topics, openIssues }`. Organization-scoped repository tasks take `org` separately instead of `repo: "owner/name"`.

`searchRepositories` searches GitHub repositories (e.g. `topic:render`, `org:render-lab`) and returns them sorted by stars, mapped through `RepositoryDTO`.

`ensureOrganizationRepository` finds the exact `org/name` repository before creating it. Existing repositories are reused only when safety-relevant settings match: `visibility` and `isTemplate` are compatibility checks today. A retry after a create timeout re-finds the repository by exact name to avoid duplicate creation.

`updateRepository` forwards GitHub repository settings such as visibility, default branch, `isTemplate`, feature flags, and archive state. Repeating the same update is convergent.

`deleteRepository` is convergent: GitHub `404` is returned as `alreadyMissing: true` with `deleted: true`. Permission errors still fail.

`listOrganizationRepositories` paginates organization repositories, applies `namePrefix` after retrieval, and returns `nextPage` when more pages may remain.

`commitFiles` creates blobs, a tree, a commit, and updates the branch ref. It rejects duplicate paths, absolute paths, parent-directory segments, and total inline file content over 3.5 MB. Pass `expectedHeadSha` to enforce optimistic concurrency before the branch ref is updated.

## Webhook adapter

Use `@render-lab/tasks-github/webhooks` from a trigger web service to verify GitHub webhooks and map verified events to Workflow task runs:

```ts
import { githubAdapter } from "@render-lab/tasks-github/webhooks";
import { serveDispatchServer } from "@render-lab/triggers";

serveDispatchServer({
  webhooks: {
    github: githubAdapter({
      onEvent: ({ event, payload }) => {
        if (event !== "issues" || payload.action !== "opened") return null;
        const repo = payload.repository?.full_name;
        if (typeof repo !== "string") return null;
        return { task: "triage.runTriage", args: [{ repo }] };
      },
    }),
  },
});
```

The `/webhooks` subpath does not import the package root, register `github.*` tasks, initialize Octokit, or read credentials at import time. Keep provider event mapping in the trigger service because task names are workflow-specific.

## Install

```bash
pnpm add @render-lab/tasks-github @renderinc/sdk
```

`@renderinc/sdk` is a peer dependency; `@octokit/rest` is a regular dependency encapsulated inside the tasks.
If you use the webhook adapter in a trigger web service, also install `@render-lab/triggers`.

## Environment contract

| Variable       | Required                              | Purpose                                                             |
| -------------- | ------------------------------------- | ------------------------------------------------------------------- |
| `GITHUB_TOKEN` | for writes, search, and higher read rate limits | GitHub token, read lazily at first API call. Most reads (`listNewIssues`, `getRepository`, etc. on public repos) work unauthenticated (rate-limited). `searchCode` and `searchRepositories` are the exception — GitHub's search endpoints always require authentication, even for public repos, and fail with a clear error if `GITHUB_TOKEN` is missing. The write tasks (`applyLabels`, `openPR`, `reviewPR`, `mergeWhenGreen`, `dispatchWorkflow`) require a token with the matching scopes (`issues`/`pull_requests`/`actions: write`). |
| `GITHUB_WEBHOOK_SECRET` | for the GitHub webhook adapter | HMAC secret used by `@render-lab/tasks-github/webhooks` to verify `X-Hub-Signature-256` before dispatch. This belongs on the trigger web service, not the Workflow service. |

## Extending & testing

Both operations export the wrapped task and its raw `*Impl`. The impls depend on a small `GitHubPort` interface, so they unit-test without touching the network:

```ts
import { listNewIssuesImpl, type GitHubPort } from "@render-lab/tasks-github";

const github: GitHubPort = {
  listIssues: async () => [/* IssueDTO[] */],
  addLabels: async () => {},
  // ...implement the remaining port methods your test calls
};
await listNewIssuesImpl({ repo: "owner/name" }, { github });
```

Run the tests with `pnpm -C packages/tasks-github test`.
