eust-w b47a07e8d2 chore: baseline snapshot of the Codex-delivered code before review
Imports the previously untracked working tree as-is so that the review
changes that follow (requirements -> design -> implementation) can be
reviewed as diffs and reverted if needed. No content changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:18:04 +08:00
..

GitHub App repository and PR adapter

This package implements GitHub App installation credentials and review/merge operations through the official REST API, pinned to version 2026-03-10. apps/api/src/domain/github.ts adds tenant/project/run authorization, durable operation records and exact-version merge approval. It never reads gh login caches, GH_TOKEN, browser sessions or developer-wide Git credentials.

Operator configuration

Set WF_GITHUB_APP_CONFIG_FILE to an operator-managed JSON file mounted read-only in the API. Its installation and repository IDs are not accepted from tenant requests. Example structure (IDs below are placeholders):

{
  "appId": "12345",
  "privateKeyFile": "/run/secrets/wishforge-github-app.pem",
  "apiBaseUrl": "https://api.github.com",
  "webOrigin": "https://github.com",
  "tenantInstallations": [{
    "tenantId": "tenant-id",
    "installationId": 9001,
    "repositories": [{
      "owner": "example-org",
      "name": "web-project",
      "repositoryId": 101,
      "allowedBaseBranches": ["main"],
      "allowAutomaticMerge": false
    }]
  }]
}

Alternatively use privateKeyVaultPath, for example secret/data/wishforge/github-app, instead of privateKeyFile. This requires VAULT_ADDR over HTTPS and an API-only VAULT_TOKEN; KV v2 returns the PEM in data.data.privateKey. Neither the App key nor the Vault token is sent to a worker. Missing configuration reports GITHUB_UNCONFIGURED.

The operator installs the App for the intended repository and maps it to the correct tenant out of band. Use no bypass entitlement for the App in repository rulesets. Forked PRs and arbitrary base branches are not supported by this initial adapter: both PR branches must belong to the assigned repository, and the head must be this run's wishforge/<runId> branch.

The API signs an RS256 App JWT with a ten-minute maximum iat/exp window and requests an installation token using exactly one repository_ids entry plus explicit contents and pull_requests permissions. Builders receive read; independent verifiers receive write. The returned expiry, permissions and repository scope are checked; an unexpectedly broader token is rejected. Installation tokens expire after an hour under GitHub's contract; the API does not claim they expire with its shorter worker lease. Git-over-HTTPS uses the returned username x-access-token with Basic authentication, never a token embedded in a clone URL or shell argument. GitHub App JWT documentation, installation token scope and expiry.

Callable domain interface

  • status(actor, projectId) reports configured repository capability.
  • credential(actor, project, run) issues the least-privilege token only for a currently owned, unexpired execution lease and rechecks that lease after I/O.
  • createPullRequest(actor, runId, input) accepts operationId, title/body, headBranch, baseBranch, expectedHeadSha and expectedBaseSha. The head must match the run's independent verification. The method returns a durable GitHubOperation with its generated id and observed PR snapshot.
  • reconcilePullRequest(actor, id) and readPullRequest(actor, id) inspect the previously recorded operation and remote state.
  • authorizeMerge(actor, id, {expectedHeadSha, expectedBaseSha}) requires an interactive owner/admin/deployer and binds the exact current revision/SHAs.
  • merge(actor, id) requires that approval or operator-set automatic merge preauthorization. It returns a new observation, not a deployment assertion.

Create operations are written to the database before remote POST. Reconciliation matches head/base and a stable operation marker, including closed PRs. An existing open PR without that marker causes a conflict. A lost response leaves an unknown outcome; subsequent calls inspect state and do not blindly recreate or remerge. Even an empty post-timeout listing cannot prove the write never happened, so operator reconciliation remains explicit.

Merge reads both branches again and checks mergeability. It uses the async merge API with exact head sha, merge_action: default and bypass_rules: false, so a configured merge queue remains in effect. Pending/enqueued results remain pending. The adapter reads the PR again to obtain the final merged SHA; an unmerged PR's test merge_commit_sha is deliberately discarded. If the actual merged SHA differs from the verified source, the run waits for independent reverification and its old verification/approvals are invalidated. The REST API has a head-SHA condition but no atomic base-SHA precondition; final-SHA reverification covers a base change after the preflight read. GitHub pull request and merge API.

The orchestration layer must push the verified run branch, call these methods, restore the actual merged commit, rerun protected verification and build that commit before creating a Release. This package does not equate a merged PR with an accepted or deployed application.

Validation and remaining acceptance

npx vitest run tests/github.test.ts
npm run typecheck -w @wishforge/github

Tests use a fake HTTP transport and an ephemeral RSA key. They verify scope, JWT signatures, lease ownership, PR operation identity, unknown outcomes, approval/commit checks, queued merges and final-SHA invalidation. They make no GitHub network calls and create no real PRs. A real App installation, repository rules/checks/merge-queue behavior and end-to-end merged-SHA build remain live acceptance work when an operator provides the installation mapping.

Independent verifier worker protocol

The worker-specific control-plane endpoints are scoped beneath /internal/runs/<runId>/github/{state,create,advance}. Each request includes the current leaseToken; only the assigned independent verifier can use them. Creation additionally binds the candidate checkpoint's source/base SHA and the exact branch wishforge/<runId>/<candidateSha>. The operation ID is persisted before GitHub I/O, so recovery reconciles an existing operation instead of creating another review. advance reports approval/merge-queue/unknown states explicitly and never treats them as build authorization.

apps/worker/src/github-delivery.ts provides the state/review/restore helpers. The helper requires the project integration gate before every review push or merge attempt. GitWorkspace.pushReviewBranch creates a new immutable run-owned branch with an absent-ref CAS, or accepts an existing ref only when its commit already matches. It never force-updates a target branch. A confirmed merge returns the actual merged SHA and original review base; the caller restores a fresh workspace and must rerun the independent profile plus exact-SHA manifest checks before building. An unconfigured github.com repository remains waiting and cannot fall back to the standard direct-push path.

This is an application-enforced write path, not a cryptographically branch-scoped GitHub token. Installation tokens can remain valid for up to an hour and GitHub contents permissions cover the assigned repository. A lease can expire in the short window between local preflight and an external Git/HTTP action, and an already-dispatched operation cannot be recalled by a database fence. Required branch protection, absence of App bypass rights, separate verifier isolation, credential revocation and result reconciliation remain necessary. The code and fake-transport tests do not establish completely fenced external GitHub writes.