| 1 | // GitHub orchestration only: the released CLI owns diff coverage, prompts, |
| 2 | // model routing, anchor validation and the final pre-publication head check. |
| 3 | // No repository checkout, project configuration, hooks, or PR code is executed. |
| 4 | // Known limits: review only, including explicit review mentions; no dollar-budget |
| 5 | // guarantee or automatic retry. Legacy direct publication has no cross-run deduplication. |
| 6 | import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; |
| 7 | import { tmpdir } from 'node:os'; |
| 8 | import { join, resolve } from 'node:path'; |
| 9 | import { fileURLToPath } from 'node:url'; |
| 10 | import { spawnSync } from 'node:child_process'; |
| 11 | import { findingsArtifact } from './findings.mjs'; |
| 12 | import { KEYS } from './setup.mjs'; |
| 13 | |
| 14 | const SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i; |
| 15 | const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; |
| 16 | const MODEL = /^[A-Za-z0-9][A-Za-z0-9_./:@+-]{0,199}$/; |
| 17 | |
| 18 | class Stop extends Error { |
| 19 | constructor(outcome, reason) { super(reason); this.outcome = outcome; this.reason = reason; } |
| 20 | } |
| 21 | const stop = (outcome, reason) => { throw new Stop(outcome, reason); }; |
| 22 | function integer(value, fallback, min, max) { |
| 23 | const text = String(value || fallback); |
| 24 | if (!/^[1-9][0-9]*$/.test(text) || Number(text) < min || Number(text) > max) { |
| 25 | stop('configuration_missing', 'invalid_limits'); |
| 26 | } |
| 27 | return Number(text); |
| 28 | } |
| 29 | |
| 30 | export function settings(env) { |
| 31 | if (!/^v\d+\.\d+\.\d+$/.test(env.CW_VERSION || '')) stop('configuration_missing', 'exact_release_required'); |
| 32 | const provider = env.CW_PROVIDER || ''; |
| 33 | if (!provider) stop('configuration_missing', 'provider_required'); |
| 34 | const model = env.CW_MODEL || ''; |
| 35 | if (!MODEL.test(model)) stop('configuration_missing', 'exact_model_required'); |
| 36 | if (env.CODEWHALE_API_KEY && provider !== 'codewhale') stop('configuration_missing', 'account_key_requires_relay'); |
| 37 | if (provider === 'codewhale') { |
| 38 | if (!env.CODEWHALE_API_KEY) stop('configuration_missing', 'account_key_required'); |
| 39 | if (!/^[A-Za-z0-9_.-]+\/.+/.test(model)) stop('configuration_missing', 'account_catalog_model_required'); |
| 40 | } else if (!Object.hasOwn(KEYS, provider) || !env[KEYS[provider]]) { |
| 41 | stop('configuration_missing', 'provider_key_required'); |
| 42 | } |
| 43 | if (!env.GH_TOKEN) stop('configuration_missing', 'github_token_required'); |
| 44 | if (!['true', 'false'].includes(env.CW_POST || 'true')) stop('configuration_missing', 'invalid_post'); |
| 45 | const reasoningEffort = env.CW_REASONING_EFFORT || 'auto'; |
| 46 | if (!['auto', 'off', 'low', 'medium', 'high', 'max'].includes(reasoningEffort)) stop('configuration_missing', 'invalid_reasoning_effort'); |
| 47 | return { |
| 48 | version: env.CW_VERSION, provider, model, reasoningEffort, post: env.CW_POST !== 'false', |
| 49 | maxChars: integer(env.CW_MAX_CHARS, 200000, 1, 8388608), |
| 50 | maxPasses: integer(env.CW_MAX_PASSES, 1, 1, 64), |
| 51 | timeout: integer(env.CW_TIMEOUT_SECONDS, 600, 30, 1200) * 1000, |
| 52 | outputTokens: env.CW_MAX_OUTPUT_TOKENS ? integer(env.CW_MAX_OUTPUT_TOKENS, 8192, 8192, 1000000) : null, |
| 53 | }; |
| 54 | } |
| 55 | |
| 56 | export function target(env, event) { |
| 57 | if (env.GITHUB_SERVER_URL && env.GITHUB_SERVER_URL !== 'https://github.com') stop('configuration_missing', 'unsupported_github_host'); |
| 58 | if (!REPO.test(env.GITHUB_REPOSITORY || '')) stop('configuration_missing', 'invalid_repository'); |
| 59 | let number; |
| 60 | if (env.GITHUB_EVENT_NAME === 'pull_request') { |
| 61 | if (!['opened', 'synchronize', 'reopened', 'ready_for_review'].includes(event.action)) stop('not_eligible', 'unsupported_pr_action'); |
| 62 | if (event.pull_request?.draft) stop('not_eligible', 'draft'); |
| 63 | if (event.pull_request?.head?.repo?.full_name !== env.GITHUB_REPOSITORY) stop('not_eligible', 'fork'); |
| 64 | if (event.pull_request?.base?.repo?.full_name !== env.GITHUB_REPOSITORY) stop('configuration_missing', 'repository_mismatch'); |
| 65 | if (!SHA.test(event.pull_request?.head?.sha || '') || !SHA.test(event.pull_request?.base?.sha || '')) stop('configuration_missing', 'invalid_revision'); |
| 66 | number = event.number; |
| 67 | } else if (env.GITHUB_EVENT_NAME === 'workflow_dispatch') { |
| 68 | number = env.CW_PR_NUMBER; |
| 69 | } else if (['issue_comment', 'pull_request_review_comment'].includes(env.GITHUB_EVENT_NAME)) { |
| 70 | if (event.action !== 'created') stop('not_eligible', 'unsupported_comment_action'); |
| 71 | if (event.comment?.user?.type !== 'User' || event.sender?.type !== 'User' |
| 72 | || event.comment.user.login !== env.GITHUB_ACTOR || event.sender.login !== env.GITHUB_ACTOR |
| 73 | || !Number.isSafeInteger(event.comment.id) || event.comment.id < 1) stop('not_eligible', 'untrusted_actor'); |
| 74 | const trigger = env.CW_TRIGGER_PHRASE || '@codewhale'; |
| 75 | if (!/^@[A-Za-z0-9][A-Za-z0-9-]{0,38}$/.test(trigger)) stop('configuration_missing', 'invalid_trigger_phrase'); |
| 76 | if (typeof event.comment.body !== 'string' |
| 77 | || event.comment.body.trim().toLowerCase() !== `${trigger.toLowerCase()} review`) stop('not_eligible', 'review_mention_required'); |
| 78 | if (env.GITHUB_EVENT_NAME === 'issue_comment') { |
| 79 | if (!event.issue?.pull_request) stop('not_eligible', 'pull_request_required'); |
| 80 | number = event.issue.number; |
| 81 | } else number = event.pull_request?.number; |
| 82 | } else { |
| 83 | // In particular, pull_request_target must not gain an inference path. |
| 84 | stop('not_eligible', 'unsupported_event'); |
| 85 | } |
| 86 | if (!/^[1-9][0-9]{0,9}$/.test(String(number || ''))) stop('configuration_missing', 'invalid_pr_number'); |
| 87 | return { repo: env.GITHUB_REPOSITORY, number: Number(number) }; |
| 88 | } |
| 89 | |
| 90 | export function validateSnapshot(pr, repo, event, env = {}) { |
| 91 | if (pr?.base?.repo?.full_name !== repo) stop('configuration_missing', 'repository_mismatch'); |
| 92 | if (pr?.head?.repo?.full_name !== repo && !(env.CW_ALLOW_FORKS === 'true' |
| 93 | && ['issue_comment', 'workflow_dispatch'].includes(env.GITHUB_EVENT_NAME))) stop('not_eligible', 'fork'); |
| 94 | if (pr.state !== 'open' || pr.draft) stop('not_eligible', 'closed_or_draft'); |
| 95 | if (!SHA.test(pr.head.sha) || !SHA.test(pr.base.sha)) stop('configuration_missing', 'invalid_revision'); |
| 96 | if (event.pull_request && (event.pull_request.head.sha !== pr.head.sha || event.pull_request.base.sha !== pr.base.sha)) { |
| 97 | stop('superseded', 'revision_changed'); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | export function authorizeRequest(env, event, repo, number, api) { |
| 102 | if (!['true', 'false'].includes(env.CW_ALLOW_FORKS || 'false')) stop('configuration_missing', 'invalid_allow_forks'); |
| 103 | const mention = ['issue_comment', 'pull_request_review_comment'].includes(env.GITHUB_EVENT_NAME); |
| 104 | if (!mention && !(env.GITHUB_EVENT_NAME === 'workflow_dispatch' && env.CW_ALLOW_FORKS === 'true')) return; |
| 105 | const actor = env.GITHUB_ACTOR; |
| 106 | const rerunner = env.GITHUB_TRIGGERING_ACTOR || actor; |
| 107 | if (event.sender?.type !== 'User' || event.sender.login !== actor |
| 108 | || ![actor, rerunner].every(login => /^[A-Za-z0-9][A-Za-z0-9-]{0,38}$/.test(login || ''))) stop('not_eligible', 'untrusted_actor'); |
| 109 | for (const login of new Set([actor, rerunner])) { |
| 110 | const permission = api(`repos/${repo}/collaborators/${login}/permission`); |
| 111 | if (permission.user?.login !== login || permission.user?.type !== 'User' |
| 112 | || !['admin', 'maintain', 'write'].includes(permission.permission)) stop('not_eligible', 'write_access_required'); |
| 113 | } |
| 114 | if (env.CW_ALLOW_FORKS === 'true') { |
| 115 | const repository = api(`repos/${repo}`); |
| 116 | if (repository.full_name !== repo || !repository.default_branch |
| 117 | || env.GITHUB_REF !== `refs/heads/${repository.default_branch}`) stop('not_eligible', 'default_branch_required'); |
| 118 | } |
| 119 | if (mention) { |
| 120 | const kind = env.GITHUB_EVENT_NAME === 'issue_comment' ? 'issues' : 'pulls'; |
| 121 | const comment = api(`repos/${repo}/${kind}/comments/${event.comment.id}`); |
| 122 | const url = env.GITHUB_EVENT_NAME === 'issue_comment' ? comment.issue_url : comment.pull_request_url; |
| 123 | const expected = `https://api.github.com/repos/${repo}/${env.GITHUB_EVENT_NAME === 'issue_comment' ? 'issues' : 'pulls'}/${number}`; |
| 124 | if (comment.id !== event.comment.id || comment.user?.login !== actor || comment.user?.type !== 'User' |
| 125 | || comment.body !== event.comment.body || comment.updated_at !== event.comment.updated_at |
| 126 | || url !== expected) stop('not_eligible', 'comment_changed_or_mismatched'); |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | // Do not persist raw stderr, prompts, findings, PR titles, provider messages, |
| 131 | // or arbitrary JSON fields: they can contain credentials or Actions commands. |
| 132 | export function classify(result, head, post, base) { |
| 133 | let data; |
| 134 | try { data = JSON.parse(result.stdout); } catch { /* fail closed below */ } |
| 135 | const publication = ['not_requested', 'not_attempted', 'uncertain', 'posted'].includes(data?.publication) |
| 136 | ? data.publication : 'unknown'; |
| 137 | const usage = {}; |
| 138 | for (const key of ['input_tokens', 'output_tokens', 'reasoning_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens']) { |
| 139 | if (Number.isSafeInteger(data?.usage?.[key]) && data.usage[key] >= 0) usage[key] = data.usage[key]; |
| 140 | } |
| 141 | const evidence = { publication, usage }; |
| 142 | const coverage = data?.receipt?.coverage; |
| 143 | if (publication === 'uncertain' || (result.error && post)) { |
| 144 | return { ...evidence, outcome: 'publication_uncertain', reason: 'inspect_github_before_retry' }; |
| 145 | } |
| 146 | if (data?.success === true && data.complete === false) { |
| 147 | return { ...evidence, outcome: 'incomplete', reason: 'coverage_incomplete' }; |
| 148 | } |
| 149 | if (data?.mode === 'review' && data.success === false && data.complete === false |
| 150 | && data.outcome === 'infrastructure' && data.review_verdict === 'not_produced') { |
| 151 | return { ...evidence, outcome: 'incomplete', reason: 'review_not_produced' }; |
| 152 | } |
| 153 | if (result.status !== 0 || data?.mode !== 'review' || data.success !== true || data.complete !== true |
| 154 | || data.pr?.head_sha !== head || !Array.isArray(data.review?.issues) |
| 155 | || !Number.isSafeInteger(data.review_passes) || data.review_passes < 1 |
| 156 | || coverage?.manifest?.head_sha !== head || coverage?.manifest?.base_sha !== base |
| 157 | || !Array.isArray(coverage?.manifest?.skipped_files) || coverage.manifest.skipped_files.length !== 0 |
| 158 | || coverage?.completed_passes?.length !== data.review_passes |
| 159 | || publication !== (post ? 'posted' : 'not_requested')) { |
| 160 | return { ...evidence, outcome: 'failed', reason: result.error ? 'process_failed' : 'review_not_completed' }; |
| 161 | } |
| 162 | return { ...evidence, outcome: data.review.issues.length ? 'reviewed_with_findings' : 'reviewed_clean', |
| 163 | reason: '', findings: data.review.issues.length, passes: data.review_passes }; |
| 164 | } |
| 165 | |
| 166 | function command(program, args, options) { |
| 167 | return spawnSync(program, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, |
| 168 | timeout: 120000, killSignal: 'SIGKILL', ...options }); |
| 169 | } |
| 170 | |
| 171 | export function run(env = process.env, execute = command) { |
| 172 | const root = mkdtempSync(join(env.RUNNER_TEMP || tmpdir(), 'codewhale-review-')); |
| 173 | const receiptPath = join(root, 'receipt.json'); |
| 174 | let findingsPath = ''; |
| 175 | let receipt = { schema_version: 1, outcome: 'failed', reason: 'setup_failed', publication: 'not_attempted' }; |
| 176 | let prUrl = ''; |
| 177 | try { |
| 178 | const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8')); |
| 179 | const { repo, number } = target(env, event); |
| 180 | const config = settings(env); |
| 181 | if (config.post && (['issue_comment', 'pull_request_review_comment'].includes(env.GITHUB_EVENT_NAME) |
| 182 | || env.CW_ALLOW_FORKS === 'true')) stop('configuration_missing', 'separate_publisher_required'); |
| 183 | receipt = { ...receipt, repository: repo, pr_number: number, version: config.version, |
| 184 | provider: config.provider, model: config.model, reasoning_effort: config.reasoningEffort, limits: { max_chars: config.maxChars, |
| 185 | max_passes: config.maxPasses, timeout_seconds: config.timeout / 1000, max_output_tokens: config.outputTokens } }; |
| 186 | // Isolate user/project configuration and retain only the selected model key. |
| 187 | // Never execute with unrelated runner credentials or Git configuration. |
| 188 | const childEnv = Object.fromEntries(['PATH', 'SystemRoot', 'TMPDIR', 'LANG'].filter(k => env[k]).map(k => [k, env[k]])); |
| 189 | Object.assign(childEnv, { HOME: join(root, 'home'), CODEWHALE_HOME: join(root, 'home', '.codewhale'), |
| 190 | GH_TOKEN: env.GH_TOKEN, GH_HOST: 'github.com', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', |
| 191 | GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', NO_COLOR: '1', CI: 'true' }); |
| 192 | childEnv[config.provider === 'codewhale' ? 'CODEWHALE_API_KEY' : KEYS[config.provider]] = |
| 193 | env[config.provider === 'codewhale' ? 'CODEWHALE_API_KEY' : KEYS[config.provider]]; |
| 194 | if (config.outputTokens) childEnv.CODEWHALE_MAX_OUTPUT_TOKENS = String(config.outputTokens); |
| 195 | mkdirSync(childEnv.CODEWHALE_HOME, { recursive: true, mode: 0o700 }); |
| 196 | if (config.reasoningEffort !== 'auto') { |
| 197 | childEnv.CODEWHALE_CONFIG_PATH = join(root, 'review.toml'); |
| 198 | writeFileSync(childEnv.CODEWHALE_CONFIG_PATH, `reasoning_effort = "${config.reasoningEffort}"\n`, { mode: 0o600 }); |
| 199 | } |
| 200 | const checked = (program, args, reason, extra = {}) => { |
| 201 | const result = execute(program, args, { env: childEnv, cwd: root, ...extra }); |
| 202 | if (result.status !== 0 || result.error) stop('failed', reason); |
| 203 | return result.stdout.trim(); |
| 204 | }; |
| 205 | let pr; |
| 206 | try { pr = JSON.parse(checked('gh', ['api', `repos/${repo}/pulls/${number}`], 'github_snapshot_unavailable')); } |
| 207 | catch (error) { if (error instanceof Stop) throw error; stop('failed', 'invalid_github_response'); } |
| 208 | validateSnapshot(pr, repo, event, env); |
| 209 | authorizeRequest(env, event, repo, number, path => { |
| 210 | try { return JSON.parse(checked('gh', ['api', path], 'github_authorization_unavailable')); } |
| 211 | catch (error) { if (error instanceof Stop) throw error; stop('failed', 'invalid_github_response'); } |
| 212 | }); |
| 213 | receipt.base_sha = pr.base.sha; |
| 214 | receipt.head_sha = pr.head.sha; |
| 215 | prUrl = `https://github.com/${repo}/pull/${number}`; |
| 216 | // Reuse the public installer: exact release, checksums, atomic fresh install. |
| 217 | const installEnv = { PATH: childEnv.PATH, HOME: childEnv.HOME, CODEWHALE_VERSION: config.version, |
| 218 | CODEWHALE_INSTALL_DIR: join(root, 'bin') }; |
| 219 | checked('sh', [join(env.CW_ACTION_PATH, 'web/public/install.sh')], 'release_install_failed', { env: installEnv, timeout: 180000 }); |
| 220 | const cli = join(root, 'bin/codewhale'); |
| 221 | if (config.provider === 'codewhale') checked(cli, ['--no-project-config', 'account', 'agent'], 'account_preflight_failed', { timeout: 60000 }); |
| 222 | const repoDir = join(root, 'repository'); |
| 223 | checked('git', ['init', '--quiet', repoDir], 'git_init_failed'); |
| 224 | const git = args => checked('git', ['-C', repoDir, '-c', 'core.hooksPath=/dev/null', '-c', 'credential.helper=', |
| 225 | '-c', 'credential.helper=!gh auth git-credential', ...args], 'git_snapshot_unavailable'); |
| 226 | git(['remote', 'add', 'origin', `https://github.com/${repo}.git`]); |
| 227 | // No checkout: fetch objects, then point HEAD at the trusted base. Core |
| 228 | // reads pinned blobs and diffs; filters, submodules and candidate code stay inert. |
| 229 | git(['fetch', '--no-tags', '--no-recurse-submodules', 'origin', pr.base.sha, `+refs/pull/${number}/head:refs/codewhale-review/head`]); |
| 230 | if (git(['rev-parse', 'refs/codewhale-review/head^{commit}']) !== pr.head.sha) stop('superseded', 'revision_changed'); |
| 231 | if (!SHA.test(git(['merge-base', '--all', pr.base.sha, pr.head.sha]))) stop('failed', 'merge_base_unavailable'); |
| 232 | git(['update-ref', 'HEAD', pr.base.sha]); |
| 233 | const args = ['--no-project-config', '--provider', config.provider, '--model', config.model, |
| 234 | 'review', '--pr', String(number), '--repo', repo, '--max-chars', String(config.maxChars), |
| 235 | '--max-passes', String(config.maxPasses), '--json', '--write-receipt', '--receipt-path', join(root, 'cli-receipt.json')]; |
| 236 | if (config.post) args.push('--post'); |
| 237 | const result = execute(cli, args, { cwd: repoDir, env: childEnv, timeout: config.timeout }); |
| 238 | receipt = { ...receipt, ...classify(result, pr.head.sha, config.post, pr.base.sha) }; |
| 239 | if (!config.post && ['reviewed_clean', 'reviewed_with_findings'].includes(receipt.outcome)) { |
| 240 | const data = JSON.parse(result.stdout); |
| 241 | if (data.pr?.number !== number || data.pr?.url !== prUrl) stop('failed', 'review_target_mismatch'); |
| 242 | let artifact; |
| 243 | try { artifact = findingsArtifact(data, receipt, env); } |
| 244 | catch { stop('failed', 'invalid_review_findings'); } |
| 245 | const path = join(root, 'findings.json'); |
| 246 | writeFileSync(path, `${JSON.stringify(artifact, null, 2)}\n`, { mode: 0o600 }); |
| 247 | findingsPath = path; |
| 248 | } |
| 249 | } catch (error) { |
| 250 | receipt = { ...receipt, outcome: error instanceof Stop ? error.outcome : 'failed', |
| 251 | reason: error instanceof Stop ? error.reason : 'setup_failed' }; |
| 252 | } |
| 253 | writeFileSync(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 }); |
| 254 | if (env.GITHUB_OUTPUT) appendFileSync(env.GITHUB_OUTPUT, `outcome=${receipt.outcome}\nreceipt=${receiptPath}\nfindings=${findingsPath}\npr-url=${prUrl}\n`); |
| 255 | if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, |
| 256 | `### Codewhale review\n\nOutcome: **${receipt.outcome}**. ${receipt.reason ? `Reason: \`${receipt.reason}\`.` : ''}\n\n` + |
| 257 | 'Only `reviewed_clean` and `reviewed_with_findings` confirm complete model review. Findings are advisory.\n'); |
| 258 | const ok = ['reviewed_clean', 'reviewed_with_findings', 'not_eligible', 'superseded'].includes(receipt.outcome); |
| 259 | // Constant vocabulary only; model/provider/repository text is never logged. |
| 260 | console.log(`${ok ? '::notice::' : '::error::'}Codewhale review: ${receipt.outcome} (${receipt.reason || 'complete'}).`); |
| 261 | return { exitCode: ok ? 0 : 1, receipt, receiptPath, findingsPath }; |
| 262 | } |
| 263 | |
| 264 | if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) process.exitCode = run().exitCode; |
| 265 |