Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Security and behavior changes

## 0.1.0-beta.2

- Treat GitHub required reviews as qualifying App/user approvals rather than additional humans; retain explicit Human-in-the-Loop policy and native GitHub enforcement, including last-push/CODEOWNER rules.
- Preserve manual review and explicit-only merge settings. Add the website copyright footer.
- Live approval-rule retesting was explicitly waived by the operator; unknown/unmet GitHub review evidence remains non-merging.

## 0.1.0-beta.1 — CLI onboarding release

Native review decisions, automatic owner-consented reviews, autonomous and optional human-supervised merging. Browser ChatGPT onboarding remains explicitly deferred and disabled. Repository opt-in and all actual GitHub protections remain mandatory.
Expand Down
4 changes: 2 additions & 2 deletions docs/acceptance.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Perform each mutation through reviewed disposable configuration/PR changes. Do n
| Advisory/uncertain/binary/large/truncated/essential-context missing | COMMENT and no merge; irrelevant supplementary omissions alone do not invalidate a tiny PR |
| Head/base/default-policy/source pin changes during review | Old result cannot approve or merge the new context; new request required |
| Review accepted then response lost / publisher crash | Reconcile same pending/submitted App review; no duplicate approval; merge separate |
| Ready protected PR, passing required CI and the mode/GitHub-required independent humans | Native expected-head merge only after separate merge authorization and explicit --merge or admitted automatic policy intent |
| Ready protected PR, passing required CI and GitHub-qualified reviews and the mode’s additional independent humans | Native expected-head merge only after separate merge authorization and explicit --merge or admitted automatic policy intent |
| Pending required CI with App-bound required guard | Native intent may queue; guard stays pending; backend rechecks before disabling intent/releasing guard/final guarded merge |
| Known failed/missing/unknown CI, conflicts or required human missing | No merge; no native intent when failure/human denial is known |
| Bot approval would otherwise satisfy human count | Independent exact-head non-author humans still required at configured/branch/ruleset minimum |
Expand All @@ -51,7 +51,7 @@ Perform each mutation through reviewed disposable configuration/PR changes. Do n
| Required merge queue | Explicit manual-only outcome; no direct merge or queue bypass |
| Two installations, same repository/actor history | Installation-bound session lookup/lease/AAD; old ciphertext cannot be used in the new installation |

Enable MERGE_DEPLOYMENT_AUTHORIZED only after recording the applicable rows as passed, then opt in repository policy and the separate whitelist. The check source must be this App's ID (REST app_id / ruleset integration_id), not any integration. When human approvals are required by the selected mode or GitHub, count current-head APPROVED reviews from distinct write-capable users other than the author. Include CODEOWNERS, stale-approval dismissal and rulesets in the live matrix; bot approval is never counted as a human.
Enable MERGE_DEPLOYMENT_AUTHORIZED only after recording the applicable rows as passed, then opt in repository policy and the separate whitelist. The check source must be this App's ID (REST app_id / ruleset integration_id), not any integration. For additional human approvals required by CodexBot policy, count current-head APPROVED reviews from distinct write-capable users other than the author. Include CODEOWNERS, stale-approval dismissal and rulesets in the live matrix; bot approval is never counted as a human.

## Optional real OpenAI protocol acceptance

Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Human-in-the-Loop uses the same configuration with `minimum_human_approvals: 1`

With automatic merge-on-approval disabled, only an authorized `--merge` can request merging. With it enabled, a separately merge-authorized review/event actor receives a durable automatic intent at admission. Review-only actors still receive reviews but cannot cause merging. The publisher, retries, cancellation and recovery use that same intent, recheck current authorization/policy/credentials and require a genuine native APPROVE. Any finding, incomplete analysis or failed check prevents merging.

Compatible autonomous GitHub protection requires a protected PR-only default branch and required CI, with no bot/admin bypass. Set GitHub's required human approval count to zero and do not require CODEOWNER or last-push approval if no human will participate. CodexBot conservatively honors the larger configured/branch/ruleset count; CODEOWNER or last-push requirements impose at least one independent human. Keep signature and other rules enabled when desired: GitHub's native expected-head merge remains the final authority and does not bypass them. Required merge queues remain unsupported/manual. Pending CI requires the guard check bound to this App's numeric ID, Checks write and Administration read. Unknown evidence never authorizes merging.
Compatible autonomous GitHub protection requires a protected PR-only default branch and required CI, with no bot/admin bypass. Keep GitHub Required approvals at 1 (or your chosen stronger count). GitHub required reviews are qualifying approvals, not an additional CodexBot human minimum: an App approval counts only when GitHub reports APPROVED for the actual PR. GitHub also decides whether CODEOWNER and last-push requirements are satisfied; REVIEW_REQUIRED or unverifiable approval evidence blocks merging. Only merge.minimum_human_approvals adds independently checked non-author humans. An App that made the last reviewable push cannot supply its own last-push approval; preserve that rule and obtain another qualifying reviewer when GitHub requires one. Keep signature and other rules enabled when desired: GitHub's native expected-head merge remains the final authority and does not bypass them. Required merge queues remain unsupported/manual. Pending CI requires the guard check bound to this App's numeric ID, Checks write and Administration read. Unknown evidence never authorizes merging.

Without an explicit assignment, automatic PR events use the authorized event actor’s own connection. The assignment below permits unattended reviews of authorized contributors without their own provider connection.

Expand Down
2 changes: 1 addition & 1 deletion docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ The installed minute cron handles bounded dispatch/publication recovery and clea

CHATGPT_DEPLOYMENT_AUTHORIZED=false is mandatory until OpenAI confirms eligibility for the actual local/hosted/ephemeral Actions topology. Public source or a successful token exchange does not grant hosted ChatGPT-plan rights. API-key mode works independently with each actor's own key and separate billing.

MERGE_DEPLOYMENT_AUTHORIZED=false remains until the disposable advisory/verdict/protection acceptance matrix passes. Then explicitly enable repository merge policy and independent whitelist. Never add the App to branch/ruleset bypass lists. Require current human approvals and CI. For pending CI, require check "CodexBot reviewed commit" with integration/app_id equal to this App's numeric ID; allowing any source is insufficient. No automated merge-queue implementation is claimed.
MERGE_DEPLOYMENT_AUTHORIZED=false remains until the disposable advisory/verdict/protection acceptance matrix passes. Then explicitly enable repository merge policy and independent whitelist. Never add the App to branch/ruleset bypass lists. Require GitHub-qualified approvals, any explicitly configured additional human approvals, and CI. For pending CI, require check "CodexBot reviewed commit" with integration/app_id equal to this App's numeric ID; allowing any source is insufficient. No automated merge-queue implementation is claimed.

## Capacity and hosting

Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "codexbot",
"version": "0.1.0-beta.1",
"version": "0.1.0-beta.2",
"private": true,
"description": "Self-hostable GitHub App for isolated Codex pull request reviews",
"license": "Apache-2.0",
Expand Down
2 changes: 1 addition & 1 deletion src/worker/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async function route(request: Request, env: Env): Promise<Response> {
requireCondition(publicPage || url.origin === canonical, 'non_canonical_backend_origin', 421);
const origin = request.headers.get('origin');
requireCondition(!origin || origin === canonical, 'cross_origin_request_denied', 403);
if (url.pathname === '/health' && request.method === 'GET') return Response.json({ status: 'ok', version: '0.1.0-beta.1' });
if (url.pathname === '/health' && request.method === 'GET') return Response.json({ status: 'ok', version: '0.1.0-beta.2' });
if (url.pathname === '/' && request.method === 'GET') return onboarding(env);
const web = await webRoute(request, env); if (web) return web;
if (url.pathname === '/v1/workload/check' && request.method === 'POST') {
Expand Down
17 changes: 11 additions & 6 deletions src/worker/merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,11 @@ export async function controlMerge(github: Octokit, snapshot: RequestSnapshot, c
let protection: Awaited<ReturnType<typeof github.rest.repos.getBranchProtection>>['data'] | undefined;
try { protection = (await github.rest.repos.getBranchProtection({ ...repo, branch: pr.baseRefName })).data; }
catch (error) { requireCondition(error && typeof error === 'object' && 'status' in error && error.status === 404 && rules.length > 0, 'branch_protection_not_verifiable', 403); }
const specialHumanRules = protection?.required_pull_request_reviews?.require_code_owner_reviews || protection?.required_pull_request_reviews?.require_last_push_approval ||
rules.some(rule => rule.type === 'pull_request' && (rule.parameters?.require_code_owner_review || rule.parameters?.require_last_push_approval));
const humanMinimum = Math.max(config.merge.minimum_human_approvals, specialHumanRules ? 1 : 0, protection?.required_pull_request_reviews?.required_approving_review_count ?? 0,
...rules.filter(x => x.type === 'pull_request').map(x => x.parameters?.required_approving_review_count ?? 0));
const githubApprovalRequired = Boolean(protection?.required_pull_request_reviews && (
(protection.required_pull_request_reviews.required_approving_review_count ?? 0) > 0 || protection.required_pull_request_reviews.require_code_owner_reviews || protection.required_pull_request_reviews.require_last_push_approval)) ||
rules.some(rule => rule.type === 'pull_request' && ((rule.parameters?.required_approving_review_count ?? 0) > 0 || rule.parameters?.require_code_owner_review || rule.parameters?.require_last_push_approval));
// GitHub qualifies App/CODEOWNER/last-push reviews; only repository policy adds humans.
const humanMinimum = config.merge.minimum_human_approvals;
const reviews = await github.paginate(github.rest.pulls.listReviews, { ...repo, pull_number: snapshot.pr, per_page: 100 }, response => {
requireCondition(response.data.length < 100, 'human_review_history_requires_manual_review'); return response.data;
});
Expand All @@ -70,10 +71,10 @@ export async function controlMerge(github: Octokit, snapshot: RequestSnapshot, c
let humans = 0;
let permissionChecks = 0;
for (const [userId, review] of [...latest].reverse()) {
if (humans >= humanMinimum) break;
if (review.state !== 'APPROVED' || review.commit_id !== snapshot.head) continue;
if (++permissionChecks > 8) return stop('human_permission_budget_requires_manual_review');
if (['write','maintain','admin'].includes(await permission(github, snapshot.repository, review.user!.login, userId))) humans++;
if (humans >= humanMinimum) break;
}
if (pr.reviewDecision==='CHANGES_REQUESTED') return stop('human_changes_requested');
const contexts = pr.commits.nodes[0]?.commit.statusCheckRollup?.contexts;
Expand All @@ -85,11 +86,15 @@ export async function controlMerge(github: Octokit, snapshot: RequestSnapshot, c
...rules.filter(x => x.type === 'required_status_checks').flatMap(x => x.parameters?.required_status_checks ?? []).map(x => ({ name: x.context, app: x.integration_id }))];
const guarded = required.some(x => x.name === config.merge.guard_check && x.app === options.appId);
const missing = required.filter(x => x.name !== config.merge.guard_check).some(required => !checks.some(x => (x.name ?? x.context) === required.name && (!required.app || required.app === -1 || x.checkSuite?.app?.databaseId === required.app)));
if (humans < humanMinimum || pr.reviewDecision==='REVIEW_REQUIRED') {
if (humans < humanMinimum) {
await stop('independent_human_approvals_required');
// Keep only the durable worker intent. Native auto-merge stays disabled until real humans qualify.
return 'queued';
}
if (pr.reviewDecision==='REVIEW_REQUIRED' || (githubApprovalRequired && pr.reviewDecision!=='APPROVED')) {
await stop('github_approval_requirements_not_satisfied');
return 'queued';
}
const disposition = mergeDisposition({ head: pr.headRefOid, expectedHead: snapshot.head, open: pr.state === 'OPEN', draft: pr.isDraft,
mergeStateStatus: pr.mergeStateStatus, reviewDecision: pr.reviewDecision, authorized: true, explicitlyRequested: snapshot.command.merge,
event: 'APPROVE', checks: missing ? 'pending' : status, humans: humans >= humanMinimum, protected: branch.protected, queue: false }, config);
Expand Down
2 changes: 1 addition & 1 deletion src/worker/onboarding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { Config } from '../core/config.js';
import catalog from '../core/model-catalog.json' with { type: 'json' };
export function html(value: unknown): string { return String(value ?? '').replace(/[&<>"']/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;' })[c]!); }
export function page(title: string, content: string, session?: BrowserSession, canonical?: string): Response {
return new Response(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>${html(title)} · CodexBot</title>${canonical ? `<link rel="canonical" href="${html(canonical)}/">` : ''}<link rel="stylesheet" href="/assets/app.css"><script src="/assets/app.js" defer></script></head><body><a class="skip" href="#main">Skip to content</a><header><a class="brand" href="/">C<span>/</span>B <b>CodexBot</b></a><nav aria-label="Main"><a href="https://github.com/AppSolves/codexbot">Source</a>${session ? '<a href="/dashboard">Repositories</a><a href="/dashboard/account">Account</a>' : '<a href="https://github.com/AppSolves/codexbot#installation">Set up ↗</a>'}<button id="theme" type="button" aria-label="Switch color theme">◐</button></nav></header><main id="main">${content}</main><footer><span>CodexBot · Apache 2.0</span><span>Your repository. Your infrastructure.</span></footer></body></html>`, { headers: { 'Content-Type':'text/html; charset=utf-8' } });
return new Response(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light dark"><title>${html(title)} · CodexBot</title>${canonical ? `<link rel="canonical" href="${html(canonical)}/">` : ''}<link rel="stylesheet" href="/assets/app.css"><script src="/assets/app.js" defer></script></head><body><a class="skip" href="#main">Skip to content</a><header><a class="brand" href="/">C<span>/</span>B <b>CodexBot</b></a><nav aria-label="Main"><a href="https://github.com/AppSolves/codexbot">Source</a>${session ? '<a href="/dashboard">Repositories</a><a href="/dashboard/account">Account</a>' : '<a href="https://github.com/AppSolves/codexbot#installation">Set up ↗</a>'}<button id="theme" type="button" aria-label="Switch color theme">◐</button></nav></header><main id="main">${content}</main><footer><span>CodexBot · Apache 2.0</span><span>Your repository. Your infrastructure.</span><span>Copyright &copy; 2026 Kaan Gönüldinc</span></footer></body></html>`, { headers: { 'Content-Type':'text/html; charset=utf-8' } });
}
export function onboarding(env: BackendConfig & {WEB_ENABLED?:string}): Response {
const slug = /^[a-zA-Z0-9-]+$/.test(env.GITHUB_APP_SLUG) ? env.GITHUB_APP_SLUG : 'codexbot';
Expand Down
6 changes: 3 additions & 3 deletions tests/github-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { snapshot, HEAD, BASE, WORKFLOW, files } from './fixtures.js';
export function githubFixture() {
const config = snapshot().config;
const state = { privateRepository:false, head: HEAD, base: BASE, permission: 'write', permissionAfterReview: null as string | null, userId: 5, author: 'alice', mergeState: 'CLEAN',
reviewDecision: 'APPROVED', autoMergeAllowed: true, reviews: [] as Record<string, unknown>[], installationId: 1, suspended: false, merged: false,
ci: 'SUCCESS', guarded: false, requiredHumans: 1, rules: [] as Record<string, unknown>[], autoMergeOwner: null as string | null,
reviewDecision: 'APPROVED' as string | null, autoMergeAllowed: true, reviews: [] as Record<string, unknown>[], installationId: 1, suspended: false, merged: false,
ci: 'SUCCESS', guarded: false, requiredApprovals: 1, rules: [] as Record<string, unknown>[], autoMergeOwner: null as string | null,
humans: [{ id: 80, state: 'APPROVED', commit_id: HEAD, user: { id: 6, login: 'bob', type: 'User' } }] as Record<string, unknown>[],
checks: [] as Record<string, unknown>[], contextTruncated: false, comments: [] as Record<string, unknown>[], runStatus: 'in_progress', runConclusion: null as string | null,
permissionsByLogin: {} as Record<string,string>,
Expand All @@ -23,7 +23,7 @@ export function githubFixture() {
if (path === '/repos/owner/repo') return ok(repo);
if (path === '/repos/owner/repo/branches/main') return ok({ commit: { sha: WORKFLOW }, protected: true });
if (path === '/repos/owner/repo/rules/branches/main') return ok(state.rules);
if (path === '/repos/owner/repo/branches/main/protection') return ok({ required_status_checks: { checks: [{ context: 'ci', app_id: null }, ...(state.guarded ? [{ context: config.merge.guard_check, app_id: 42 }] : [])] }, required_pull_request_reviews: { required_approving_review_count: state.requiredHumans } });
if (path === '/repos/owner/repo/branches/main/protection') return ok({ required_status_checks: { checks: [{ context: 'ci', app_id: null }, ...(state.guarded ? [{ context: config.merge.guard_check, app_id: 42 }] : [])] }, required_pull_request_reviews: { required_approving_review_count: state.requiredApprovals } });
if (path === '/repos/owner/repo/contents/.codexbot.yml') return ok({ type: 'file', size: 1000, content: Buffer.from(stringify(config)).toString('base64') });
if (path.includes('/collaborators/') && path.endsWith('/permission')) { const login = decodeURIComponent(path.split('/').at(-2)!); return ok({ permission: state.permissionsByLogin[login] ?? state.permission, user: { id: login === 'github-actions[bot]' ? 41898282 : login === 'alice' ? state.userId : 6, login, type: login === 'github-actions[bot]' ? 'Bot' : 'User' } }); }
if(path==='/users/bob')return ok({id:6,login:'bob',type:'User'});
Expand Down
Loading