Files
Netcatty/.github/workflows/cursor-automation.yml
T
陈大猫 e2f331ebda fix(ci): stop Codex loop failing on draft conversion (#2448)
Use TRIAGE_GITHUB_TOKEN for Codex review loop jobs. Treat convert-to-draft
and mark-ready permission errors, and closed PRs, as warnings so @codex
still runs instead of failing the whole automation job.
2026-07-24 15:18:13 +08:00

2348 lines
97 KiB
YAML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
name: Cursor automation
on:
issues:
types: [opened, reopened]
issue_comment:
types: [created]
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
# Fork PRs get a read-only GITHUB_TOKEN on pull_request. pull_request_target
# (default-branch only checkout + comment) can re-@codex after contributor pushes.
pull_request_target:
types: [synchronize]
# Codex often finishes as a submitted PR review (plus optional issue summary).
pull_request_review:
types: [submitted]
# Reaction-only clean (👍 on @codex request) does not emit review events;
# poll open automation PRs so the loop can observe and mark ready.
schedule:
- cron: '*/20 * * * *'
workflow_dispatch:
inputs:
issue_number:
description: Issue number to classify/implement
required: false
type: number
pull_number:
description: PR number for own Codex fix loop or external re-@codex
required: false
type: number
concurrency:
group: >-
cursor-auto-${{
github.event.issue && !github.event.issue.pull_request && github.event.issue.number ||
github.event.pull_request && github.event.pull_request.number ||
github.event.issue && github.event.issue.pull_request && github.event.issue.number ||
inputs.issue_number ||
inputs.pull_number ||
github.run_id
}}
cancel-in-progress: false
# Default least privilege: route/bootstrap only need read. Jobs that mutate
# issues/PRs/contents declare their own write permissions.
permissions:
contents: read
issues: read
pull-requests: read
actions: read
jobs:
route:
name: Route event
runs-on: ubuntu-latest
permissions:
contents: read
issues: read
pull-requests: read
actions: read
outputs:
kind: ${{ steps.decide.outputs.kind }}
issue_number: ${{ steps.decide.outputs.issue_number }}
pull_number: ${{ steps.decide.outputs.pull_number }}
reason: ${{ steps.decide.outputs.reason }}
steps:
# Prefer control-plane helpers from the default branch. While this workflow
# is still landing, the helper may only exist on the PR head — bootstrap then.
- name: Checkout helpers
uses: actions/checkout@v5
with:
ref: ${{ github.event.repository.default_branch }}
- name: Ensure automation helper present
env:
BOOTSTRAP_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
EVENT_NAME: ${{ github.event_name }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name || '' }}
BASE_REPO: ${{ github.repository }}
run: |
set -euo pipefail
if [[ -f scripts/cursor-automation.cjs ]]; then
echo "Helper present on default branch."
exit 0
fi
# Never execute untrusted helper code under pull_request_target / fork events.
if [[ "$EVENT_NAME" == "pull_request_target" ]] || { [[ -n "$HEAD_REPO" ]] && [[ "$HEAD_REPO" != "$BASE_REPO" ]]; }; then
echo "Helper missing on default branch; refusing untrusted bootstrap for ${EVENT_NAME}." >&2
exit 1
fi
echo "Helper missing on default branch; bootstrapping from ${BOOTSTRAP_SHA}"
git fetch --depth=1 origin "${BOOTSTRAP_SHA}"
mkdir -p scripts
git show "FETCH_HEAD:scripts/cursor-automation.cjs" > scripts/cursor-automation.cjs
test -s scripts/cursor-automation.cjs
- name: Decide route
id: decide
uses: actions/github-script@v7
env:
OWN_ACTORS: ${{ vars.AUTOMATION_OWN_ACTORS || 'binaricat,netcatty-bot,github-actions[bot]' }}
DISPATCH_ISSUE: ${{ inputs.issue_number || '' }}
DISPATCH_PULL: ${{ inputs.pull_number || '' }}
with:
script: |
const auto = require(`${process.env.GITHUB_WORKSPACE}/scripts/cursor-automation.cjs`);
const event = context.eventName;
const ownActors = process.env.OWN_ACTORS;
const set = (kind, extra = {}) => {
core.setOutput('kind', kind);
core.setOutput('issue_number', extra.issue_number || '');
core.setOutput('pull_number', extra.pull_number || '');
core.setOutput('reason', extra.reason || kind);
};
if (event === 'schedule') {
return set('codex_poll', {
reason: 'scheduled poll for reaction-only clean / expired requests',
});
}
if (event === 'workflow_dispatch') {
if (process.env.DISPATCH_ISSUE) {
return set('issue_classify', {
issue_number: process.env.DISPATCH_ISSUE,
reason: 'manual issue',
});
}
if (process.env.DISPATCH_PULL) {
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number: Number(process.env.DISPATCH_PULL),
});
const eligible = auto.isFixEligiblePr(pr, {
ownActors,
repository: `${context.repo.owner}/${context.repo.repo}`,
});
return set(eligible ? 'codex_loop' : 'external_rerequest_codex', {
pull_number: String(pr.number),
reason: eligible ? 'manual own pr' : 'manual external re-@codex',
});
}
return set('skip', { reason: 'workflow_dispatch missing inputs' });
}
if (event === 'issues') {
return set('issue_classify', {
issue_number: String(context.payload.issue.number),
reason: `issues:${context.payload.action}`,
});
}
if (event === 'issue_comment') {
const issue = context.payload.issue;
const comment = context.payload.comment;
const login = comment.user?.login || '';
if (issue.pull_request) {
if (
auto.isCodexBotLogin(login) &&
auto.isCodexTerminalReviewText(comment.body)
) {
return set('codex_loop', {
pull_number: String(issue.number),
reason: 'codex terminal issue_comment on pr',
});
}
return set('skip', { reason: 'non-terminal pr issue_comment' });
}
if (comment.user?.type === 'Bot') {
return set('skip', { reason: 'bot issue comment' });
}
const labels = (issue.labels || []).map((l) =>
typeof l === 'string' ? l : l.name,
);
if (
auto.shouldReTriageIssueComment({
labels,
commenterLogin: comment.user?.login,
issueAuthorLogin: issue.user?.login,
})
) {
return set('issue_classify', {
issue_number: String(issue.number),
reason: 'author reply on needs-info',
});
}
return set('skip', { reason: 'issue comment no re-triage signal' });
}
if (event === 'pull_request_review') {
const login = context.payload.review?.user?.login || '';
const pr = context.payload.pull_request;
if (!auto.isCodexBotLogin(login)) {
return set('skip', { reason: 'non-codex review' });
}
if (
!auto.isFixEligiblePr(pr, {
ownActors,
repository: `${context.repo.owner}/${context.repo.repo}`,
})
) {
return set('skip', {
reason: 'codex review on non-fix-eligible pr',
});
}
return set('codex_loop', {
pull_number: String(pr.number),
reason: 'codex pull_request_review submitted',
});
}
if (event === 'pull_request_target') {
// Privileged path for fork comment-only re-@codex. Never implement/fix.
const pr = context.payload.pull_request;
const sameRepo =
pr.head?.repo?.full_name ===
`${context.repo.owner}/${context.repo.repo}`;
if (sameRepo) {
return set('skip', {
reason: 'same-repo uses pull_request event',
});
}
if (context.payload.action === 'synchronize') {
return set('external_rerequest_codex', {
pull_number: String(pr.number),
reason: 'fork pr push via pull_request_target — re-@codex',
});
}
return set('skip', { reason: 'pull_request_target non-synchronize' });
}
if (event === 'pull_request') {
const pr = context.payload.pull_request;
const sameRepo =
pr.head?.repo?.full_name ===
`${context.repo.owner}/${context.repo.repo}`;
const eligible = auto.isFixEligiblePr(pr, {
ownActors,
repository: `${context.repo.owner}/${context.repo.repo}`,
});
// Own/bot PRs: ensure Codex on open/ready; human synchronize re-requests.
if (eligible) {
if (['opened', 'ready_for_review', 'reopened'].includes(context.payload.action)) {
return set('codex_loop', {
pull_number: String(pr.number),
reason: 'own pr opened — ensure codex review',
});
}
if (context.payload.action === 'synchronize') {
const sender = String(context.payload.sender?.login || '');
// Only this workflow's publish jobs re-@codex after push.
// Other bots (dependabot, pre-commit, etc.) still need a request.
if (sender === 'github-actions[bot]') {
return set('skip', {
reason: 'own pr github-actions push already requested codex',
});
}
return set('own_rerequest_codex', {
pull_number: String(pr.number),
reason: 'own pr non-automation push — re-@codex',
});
}
return set('skip', {
reason: 'own pr non-open non-synchronize',
});
}
// Forks: only pull_request_target may comment (write token).
if (!sameRepo) {
return set('skip', {
reason: 'fork uses pull_request_target for re-@codex',
});
}
// Same-repo non-eligible (rare) can comment on pull_request.
if (context.payload.action === 'synchronize') {
return set('external_rerequest_codex', {
pull_number: String(pr.number),
reason: 'external same-repo push — re-@codex review',
});
}
return set('skip', {
reason: 'external pr non-synchronize (Codex auto handles open)',
});
}
return set('skip', { reason: `unhandled ${event}` });
classify:
name: Classify issue
needs: route
if: needs.route.outputs.kind == 'issue_classify'
runs-on: ubuntu-latest
timeout-minutes: 30
# Per-issue only: a global group drops pending issues (GitHub keeps one
# pending job). Same-issue retriages still serialize; daily limit is
# best-effort via triage:admitted markers.
concurrency:
group: cursor-triage-${{ needs.route.outputs.issue_number || github.run_id }}
cancel-in-progress: false
permissions:
contents: read
issues: write
pull-requests: write
actions: read
outputs:
category: ${{ steps.apply.outputs.category }}
should_implement: ${{ steps.apply.outputs.should_implement }}
issue_number: ${{ steps.prepare.outputs.issue_number }}
issue_url: ${{ steps.prepare.outputs.issue_url }}
issue_title: ${{ steps.prepare.outputs.issue_title }}
should_run: ${{ steps.prepare.outputs.should_run }}
steps:
- name: Checkout
uses: actions/checkout@v5
with:
persist-credentials: false
- name: Freeze trusted helper before agent
run: |
set -euo pipefail
test -f scripts/cursor-automation.cjs
cp scripts/cursor-automation.cjs "$RUNNER_TEMP/cursor-automation.cjs"
# Prompt copy for classify (agent must not rewrite the policy helper).
mkdir -p "$RUNNER_TEMP/cursor-prompts"
cp .github/cursor/prompts/classify.md "$RUNNER_TEMP/cursor-prompts/classify.md"
- name: Prepare issue context
id: prepare
uses: actions/github-script@v7
env:
ISSUE_NUMBER: ${{ needs.route.outputs.issue_number }}
MANUAL_RUN: ${{ github.event_name == 'workflow_dispatch' }}
DAILY_LIMIT: ${{ vars.CURSOR_TRIAGE_DAILY_LIMIT || '10' }}
with:
# Prefer bot PAT so labels/admission and later apply run as netcatty-bot.
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
await auto.prepareIssueContext({
github,
context,
core,
issueNumber: process.env.ISSUE_NUMBER,
outputPath: `${process.env.GITHUB_WORKSPACE}/.cursor-runtime/issue.json`,
dailyLimit: Number(process.env.DAILY_LIMIT),
manual: process.env.MANUAL_RUN === 'true',
});
- name: Ensure Cursor API key
if: steps.prepare.outputs.should_run == 'true'
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
run: |
if [[ -z "$CURSOR_API_KEY" ]]; then
echo "CURSOR_API_KEY is not configured." >&2
exit 1
fi
- name: Install Cursor CLI
if: steps.prepare.outputs.should_run == 'true'
run: |
curl https://cursor.com/install -fsS | bash
# Official installer places `agent` under ~/.local/bin (and sometimes ~/.cursor/bin).
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
echo "$HOME/.cursor/bin" >> "$GITHUB_PATH"
command -v agent || ls -la "$HOME/.local/bin" "$HOME/.cursor/bin" 2>/dev/null || true
- name: Classify with Cursor CLI
if: steps.prepare.outputs.should_run == 'true'
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
GITHUB_TOKEN: ''
GH_TOKEN: ''
run: |
set -euo pipefail
mkdir -p .cursor-runtime
git config --local --unset-all http.https://github.com/.extraheader || true
# Restore frozen helper in case agent rewrote workspace copy mid-run (post-step).
PROMPT="$(cat "$RUNNER_TEMP/cursor-prompts/classify.md")
----
Issue payload path: .cursor-runtime/issue.json
Hard requirement: search and open real source files in this workspace
BEFORE writing the classification JSON. Do not answer from the issue
text alone. Include code_paths + code_findings in the JSON.
Write the JSON result to .cursor-runtime/classification.json as well as printing it.
"
# GHA Ubuntu runners cannot start Cursor's sandbox (AppArmor). Rely on
# stripped GH tokens, frozen helpers, and post-run secret scans instead.
# ask mode is read-only but still allows repo search/read tools.
agent -p --mode=ask --trust --sandbox disabled --model auto --output-format text \
--workspace "$GITHUB_WORKSPACE" \
"$PROMPT" | tee .cursor-runtime/classify-raw.txt
# Always parse with the frozen helper, never workspace scripts.
if [[ ! -s .cursor-runtime/classification.json ]]; then
node -e '
const fs = require("node:fs");
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
const text = fs.readFileSync(".cursor-runtime/classify-raw.txt", "utf8");
const parsed = auto.parseClassificationText(text);
auto.writeJson(".cursor-runtime/classification.json", parsed);
'
fi
# Fail closed if the untrusted prompt caused the agent to echo the key.
node -e '
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
auto.assertFilesDoNotContainSecret(
[
".cursor-runtime/classify-raw.txt",
".cursor-runtime/classification.json",
],
process.env.CURSOR_API_KEY,
"classify-output",
);
'
- name: Apply classification
id: apply
if: steps.prepare.outputs.should_run == 'true'
uses: actions/github-script@v7
env:
ISSUE_NUMBER: ${{ steps.prepare.outputs.issue_number }}
with:
# Comments/labels/close as netcatty-bot (not github-actions).
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
await auto.applyClassification({
github,
context,
core,
issueNumber: process.env.ISSUE_NUMBER,
classificationPath: `${process.env.GITHUB_WORKSPACE}/.cursor-runtime/classification.json`,
});
- name: Notify Slack
if: steps.apply.outcome == 'success'
continue-on-error: true
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
STATUS: "Classified as ${{ steps.apply.outputs.category }}"
ISSUE_URL: ${{ steps.prepare.outputs.issue_url }}
ISSUE_TITLE: ${{ steps.prepare.outputs.issue_title }}
DETAIL: ${{ steps.apply.outputs.summary }}
WORKFLOW_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
node - <<'NODE'
const auto = require(process.env.RUNNER_TEMP + '/cursor-automation.cjs');
const payload = auto.buildSlackPayload({
status: process.env.STATUS,
issueUrl: process.env.ISSUE_URL,
issueTitle: process.env.ISSUE_TITLE,
detail: process.env.DETAIL,
workflowUrl: process.env.WORKFLOW_URL,
});
auto.sendSlackNotification(process.env.SLACK_WEBHOOK_URL, payload)
.then(({ skipped }) => skipped && console.log('Slack skipped'))
.catch((err) => {
console.error('Slack notification failed (non-blocking):', err);
process.exit(0);
});
NODE
implement:
name: Implement with Cursor CLI
needs: [route, classify]
if: >-
needs.route.outputs.kind == 'issue_classify' &&
needs.classify.result == 'success' &&
needs.classify.outputs.should_run == 'true' &&
needs.classify.outputs.should_implement == 'true'
runs-on: ubuntu-latest
timeout-minutes: 120
# Agent job: no contents write token available to the runner for publish.
permissions:
contents: read
issues: write
pull-requests: read
actions: read
outputs:
should_publish: ${{ steps.patch.outputs.should_publish || 'false' }}
branch: ${{ steps.branch.outputs.name }}
base_sha: ${{ steps.branch.outputs.base_sha }}
issue_number: ${{ needs.classify.outputs.issue_number }}
issue_title: ${{ needs.classify.outputs.issue_title }}
env:
ISSUE_NUMBER: ${{ needs.classify.outputs.issue_number }}
ISSUE_URL: ${{ needs.classify.outputs.issue_url }}
ISSUE_TITLE: ${{ needs.classify.outputs.issue_title }}
steps:
- name: Checkout main
uses: actions/checkout@v5
with:
ref: ${{ github.event.repository.default_branch }}
fetch-depth: 0
persist-credentials: false
- name: Ensure automation helper present
env:
BOOTSTRAP_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
EVENT_NAME: ${{ github.event_name }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name || '' }}
BASE_REPO: ${{ github.repository }}
run: |
set -euo pipefail
if [[ -f scripts/cursor-automation.cjs ]]; then
echo "Helper present on default branch."
exit 0
fi
if [[ "$EVENT_NAME" == "pull_request_target" ]] || { [[ -n "$HEAD_REPO" ]] && [[ "$HEAD_REPO" != "$BASE_REPO" ]]; }; then
echo "Helper missing on default branch; refusing untrusted bootstrap for ${EVENT_NAME}." >&2
exit 1
fi
echo "Helper missing on default branch; bootstrapping from ${BOOTSTRAP_SHA}"
git fetch --depth=1 origin "${BOOTSTRAP_SHA}"
mkdir -p scripts
git show "FETCH_HEAD:scripts/cursor-automation.cjs" > scripts/cursor-automation.cjs
test -s scripts/cursor-automation.cjs
- name: Freeze trusted helper
run: cp scripts/cursor-automation.cjs "$RUNNER_TEMP/cursor-automation.cjs"
- name: Skip if bot PR already open
id: existing
uses: actions/github-script@v7
with:
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
const existing = await auto.findOpenBotPrForIssue({
github,
context,
issueNumber: process.env.ISSUE_NUMBER,
});
core.setOutput('exists', existing ? 'true' : 'false');
core.setOutput('url', existing ? existing.html_url : '');
if (existing) {
await github.rest.issues.createComment({
...context.repo,
issue_number: Number(process.env.ISSUE_NUMBER),
body: [
auto.TRIAGE_MARKER,
auto.DISCLAIMER,
'',
`An automation pull request is already open or was already filed: ${existing.html_url}`,
].join('\n'),
});
}
- name: Ensure Cursor API key
if: steps.existing.outputs.exists != 'true'
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
run: |
if [[ -z "$CURSOR_API_KEY" ]]; then
echo "CURSOR_API_KEY is not configured." >&2
exit 1
fi
- name: Create working branch
if: steps.existing.outputs.exists != 'true'
id: branch
run: |
branch="cursor/issue-${ISSUE_NUMBER}-${GITHUB_RUN_ID}"
git checkout -b "$branch"
echo "name=$branch" >> "$GITHUB_OUTPUT"
echo "base_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- name: Prepare issue JSON
if: steps.existing.outputs.exists != 'true'
uses: actions/github-script@v7
with:
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
await auto.prepareIssueContext({
github,
context,
core,
issueNumber: process.env.ISSUE_NUMBER,
outputPath: `${process.env.GITHUB_WORKSPACE}/.cursor-runtime/issue.json`,
manual: true,
});
- name: Setup Node
if: steps.existing.outputs.exists != 'true'
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Install dependencies
if: steps.existing.outputs.exists != 'true'
run: npm ci
- name: Install Cursor CLI
if: steps.existing.outputs.exists != 'true'
run: |
curl https://cursor.com/install -fsS | bash
# Official installer places `agent` under ~/.local/bin (and sometimes ~/.cursor/bin).
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
echo "$HOME/.cursor/bin" >> "$GITHUB_PATH"
command -v agent || ls -la "$HOME/.local/bin" "$HOME/.cursor/bin" 2>/dev/null || true
- name: Implement with Cursor CLI
if: steps.existing.outputs.exists != 'true'
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
BASE_SHA: ${{ steps.branch.outputs.base_sha }}
# Explicitly strip GitHub credentials from the agent environment.
GITHUB_TOKEN: ''
GH_TOKEN: ''
run: |
set -euo pipefail
mkdir -p .cursor-runtime
# Drop any accidental git auth helpers for the agent process.
git config --local --unset-all http.https://github.com/.extraheader || true
PROMPT="$(cat .github/cursor/prompts/implement.md)"
# GHA cannot use Cursor sandbox; secret isolation is handled outside agent.
agent -p --force --trust --sandbox disabled --model auto --output-format text \
--workspace "$GITHUB_WORKSPACE" \
"$PROMPT" | tee .cursor-runtime/implement-raw.txt
# Do not run `git diff` here with CURSOR_API_KEY present — agent may have
# configured textconv/hooks. Committed range is scanned later via format-patch.
node -e '
const { execSync } = require("node:child_process");
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
auto.assertFilesDoNotContainSecret(
[".cursor-runtime/implement-raw.txt"],
process.env.CURSOR_API_KEY,
"implement-output",
);
const untracked = execSync(
"git -c core.hooksPath=/dev/null ls-files --others --exclude-standard",
{ encoding: "utf8" },
)
.split("\n")
.filter(Boolean)
.filter((p) => !p.startsWith(".cursor-runtime/"));
auto.assertFilesDoNotContainSecret(
untracked,
process.env.CURSOR_API_KEY,
"implement-untracked",
);
'
- name: Detect changes
if: steps.existing.outputs.exists != 'true'
id: changes
run: |
if [[ -n "$(git status --porcelain --untracked-files=all -- . ':(exclude).cursor-runtime' ':(exclude).cursor-runtime/**')" ]] \
|| [[ -n "$(git diff --name-only "${{ steps.branch.outputs.base_sha }}" HEAD 2>/dev/null || true)" ]]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
fi
- name: Check protected paths (tree + commits)
if: steps.existing.outputs.exists != 'true' && steps.changes.outputs.present == 'true'
run: |
status="$(git status --porcelain --untracked-files=all -- . ':(exclude).cursor-runtime' ':(exclude).cursor-runtime/**')"
names="$(git diff --name-only "${{ steps.branch.outputs.base_sha }}" HEAD 2>/dev/null || true)"
name_status="$(git diff --name-status -M "${{ steps.branch.outputs.base_sha }}" HEAD 2>/dev/null || true)"
node -e '
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
const hits = auto.hasProtectedChangesInSources({
gitStatusPorcelain: process.argv[1],
changedFiles: process.argv[2].split("\n").filter(Boolean),
nameStatusText: process.argv[3],
});
if (hits.length) {
console.error("Protected paths modified:", hits.join(", "));
process.exit(1);
}
' "$status" "$names" "$name_status"
- name: Report no changes
if: steps.existing.outputs.exists != 'true' && steps.changes.outputs.present != 'true'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
await auto.markNeedsHuman({
github,
context,
issueNumber: process.env.ISSUE_NUMBER,
message: 'The automatic implementation pass did not produce a safe focused change. A maintainer needs to take a look.',
});
- name: Install test shell dependencies
if: steps.existing.outputs.exists != 'true' && steps.changes.outputs.present == 'true'
run: |
# Match .github/workflows/test.yml — osc7Setup.test.ts requires fish in CI.
sudo apt-get update
sudo apt-get install -y fish
- name: Verify
if: steps.existing.outputs.exists != 'true' && steps.changes.outputs.present == 'true'
id: verify
run: |
set +e
npm run lint
lint=$?
npm test
tests=$?
npm run build
build=$?
set -e
if [[ "$lint" != "0" || "$tests" != "0" || "$build" != "0" ]]; then
echo "passed=false" >> "$GITHUB_OUTPUT"
exit 1
fi
echo "passed=true" >> "$GITHUB_OUTPUT"
- name: Prepare patch for isolated publish
if: steps.existing.outputs.exists != 'true' && steps.changes.outputs.present == 'true' && steps.verify.outputs.passed == 'true'
id: patch
# No CURSOR_API_KEY here: agent may have installed hooks. Git runs with hooks disabled.
env:
ISSUE_NUMBER: ${{ needs.route.outputs.issue_number }}
run: |
set -euo pipefail
# Neutralize agent-controlled hooks/config for all subsequent git ops.
GITH='git -c core.hooksPath=/dev/null'
$GITH config --local --unset-all core.hooksPath 2>/dev/null || true
$GITH config --local --unset-all core.fsmonitor 2>/dev/null || true
status="$($GITH status --porcelain --untracked-files=all -- . ':(exclude).cursor-runtime' ':(exclude).cursor-runtime/**')"
if [[ -n "$status" ]]; then
$GITH add -A
$GITH reset -- .cursor-runtime >/dev/null 2>&1 || true
$GITH -c user.name="netcatty-bot" -c user.email="308658023+netcatty-bot@users.noreply.github.com" \
commit -m "fix(#${ISSUE_NUMBER}): automated Cursor CLI fix" || true
fi
name_status="$($GITH diff --name-status -M "${{ steps.branch.outputs.base_sha }}" HEAD)"
node -e '
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
const hits = auto.hasProtectedChangesInSources({ nameStatusText: process.argv[1] });
if (hits.length) {
console.error("Protected paths modified:", hits.join(", "));
process.exit(1);
}
' "$name_status"
# Reject commits that still contain runtime artifacts (agent may have committed them).
runtime_hits="$($GITH diff --name-only "${{ steps.branch.outputs.base_sha }}" HEAD | grep -E '^\.cursor-runtime(/|$)' || true)"
if [[ -n "$runtime_hits" ]]; then
echo "Refusing to publish commits that include .cursor-runtime paths:" >&2
echo "$runtime_hits" >&2
exit 1
fi
mkdir -p .cursor-runtime
$GITH format-patch --stdout "${{ steps.branch.outputs.base_sha }}" > .cursor-runtime/implement.patch
test -s .cursor-runtime/implement.patch
if [[ -f .cursor-runtime/implement-status.txt ]]; then
cp .cursor-runtime/implement-status.txt .cursor-runtime/implement-status.out.txt
else
echo "OK: automated fix" > .cursor-runtime/implement-status.out.txt
fi
echo "should_publish=true" >> "$GITHUB_OUTPUT"
- name: Scan implement patch for secret leaks
if: steps.patch.outputs.should_publish == 'true'
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
run: |
set -euo pipefail
# Pure Node scan only — no git with the secret in the environment.
node -e '
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
auto.assertFilesDoNotContainSecret(
[
".cursor-runtime/implement.patch",
".cursor-runtime/implement-status.out.txt",
".cursor-runtime/implement-status.txt",
],
process.env.CURSOR_API_KEY,
"implement-publish",
);
'
- name: Upload implement patch
if: steps.patch.outputs.should_publish == 'true'
uses: actions/upload-artifact@v4
with:
name: implement-patch-${{ github.run_id }}
path: |
.cursor-runtime/implement.patch
.cursor-runtime/implement-status.out.txt
if-no-files-found: error
- name: Mark needs human on implement failure
if: failure() && steps.existing.outputs.exists != 'true'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const fs = require('node:fs');
const helper = fs.existsSync(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`)
? `${process.env.RUNNER_TEMP}/cursor-automation.cjs`
: `${process.env.GITHUB_WORKSPACE}/scripts/cursor-automation.cjs`;
const auto = require(helper);
await auto.markNeedsHuman({
github,
context,
issueNumber: process.env.ISSUE_NUMBER,
message:
'Automatic implementation did not finish cleanly (agent, protected paths, or verification failed). A maintainer needs to take a look.',
});
publish_implement:
name: Publish implement PR
needs: [implement]
if: needs.implement.outputs.should_publish == 'true'
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: write
issues: write
pull-requests: write
env:
ISSUE_NUMBER: ${{ needs.implement.outputs.issue_number }}
ISSUE_TITLE: ${{ needs.implement.outputs.issue_title }}
BRANCH: ${{ needs.implement.outputs.branch }}
BASE_SHA: ${{ needs.implement.outputs.base_sha }}
# Prefer a PAT so push/PR events trigger normal CI (GITHUB_TOKEN does not).
GH_TOKEN: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
steps:
- name: Download implement patch
uses: actions/download-artifact@v4
with:
name: implement-patch-${{ github.run_id }}
path: patch-in
- name: Publish branch from fresh runner
run: |
set -euo pipefail
PUBLISH="$RUNNER_TEMP/publish-tree"
rm -rf "$PUBLISH"
git clone --no-checkout "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "$PUBLISH"
cd "$PUBLISH"
git -c core.hooksPath=/dev/null config user.name "netcatty-bot"
git -c core.hooksPath=/dev/null config user.email "308658023+netcatty-bot@users.noreply.github.com"
git -c core.hooksPath=/dev/null fetch --depth=50 origin "${BASE_SHA}"
git -c core.hooksPath=/dev/null checkout -B "$BRANCH" "$BASE_SHA"
git -c core.hooksPath=/dev/null am --3way "$GITHUB_WORKSPACE/patch-in/implement.patch"
git -c core.hooksPath=/dev/null push origin "HEAD:$BRANCH"
- name: Checkout helper for PR body helpers
uses: actions/checkout@v5
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
path: helpers
- name: Ensure automation helper present
working-directory: helpers
env:
BOOTSTRAP_SHA: ${{ github.sha }}
EVENT_NAME: ${{ github.event_name }}
HEAD_REPO: ''
BASE_REPO: ${{ github.repository }}
run: |
set -euo pipefail
if [[ -f scripts/cursor-automation.cjs ]]; then
cp scripts/cursor-automation.cjs "$RUNNER_TEMP/cursor-automation.cjs"
exit 0
fi
git fetch --depth=1 origin "${BOOTSTRAP_SHA}"
git show "FETCH_HEAD:scripts/cursor-automation.cjs" > "$RUNNER_TEMP/cursor-automation.cjs"
test -s "$RUNNER_TEMP/cursor-automation.cjs"
- name: Open draft PR and request Codex review
uses: actions/github-script@v7
env:
BRANCH: ${{ needs.implement.outputs.branch }}
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
ISSUE_NUMBER: ${{ needs.implement.outputs.issue_number }}
ISSUE_TITLE: ${{ needs.implement.outputs.issue_title }}
with:
# GITHUB_TOKEN cannot create PRs unless the repo enables
# "Allow GitHub Actions to create and approve pull requests".
# Prefer TRIAGE_GITHUB_TOKEN (PAT) so implement can open draft PRs.
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
const fs = require('node:fs');
let summary = '';
try {
summary = fs.readFileSync(`${process.env.GITHUB_WORKSPACE}/patch-in/implement-status.out.txt`, 'utf8');
} catch {}
const title = `fix(#${process.env.ISSUE_NUMBER}): ${process.env.ISSUE_TITLE}`.slice(0, 110);
const body = auto.buildPullRequestBody({
issueNumber: process.env.ISSUE_NUMBER,
issueTitle: process.env.ISSUE_TITLE,
summary,
});
const { data: pr } = await github.rest.pulls.create({
...context.repo,
title,
head: process.env.BRANCH,
base: process.env.DEFAULT_BRANCH || 'main',
body,
draft: true,
});
await github.rest.issues.addLabels({
...context.repo,
issue_number: pr.number,
labels: ['automation:bot-pr', 'automation:codex-loop', 'triage'],
});
await github.rest.issues.createComment({
...context.repo,
issue_number: Number(process.env.ISSUE_NUMBER),
body: auto.buildPullRequestComment({
pullRequestUrl: pr.html_url,
clean: false,
}),
});
await github.rest.issues.createComment({
...context.repo,
issue_number: pr.number,
body: auto.buildCodexReviewRequestComment(1, pr.head.sha),
});
core.info(`Opened draft PR ${pr.html_url}`);
codex_loop:
name: Codex review loop
needs: route
if: needs.route.outputs.kind == 'codex_loop'
runs-on: ubuntu-latest
timeout-minutes: 120
permissions:
contents: read
issues: write
pull-requests: write
actions: read
outputs:
should_publish: ${{ steps.fixpatch.outputs.should_publish || 'false' }}
head_ref: ${{ steps.codex.outputs.head_ref }}
base_sha: ${{ steps.base.outputs.sha }}
pull_number: ${{ needs.route.outputs.pull_number }}
prev_round: ${{ steps.codex.outputs.round }}
env:
PULL_NUMBER: ${{ needs.route.outputs.pull_number }}
MAX_ROUNDS: ${{ vars.CURSOR_CODEX_FIX_MAX_ROUNDS || '40' }}
OWN_ACTORS: ${{ vars.AUTOMATION_OWN_ACTORS || 'binaricat,netcatty-bot,github-actions[bot]' }}
# Bot PAT can convert draft + comment; default GITHUB_TOKEN often cannot.
GH_TOKEN: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
steps:
- name: Checkout helpers
uses: actions/checkout@v5
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
- name: Ensure automation helper present
env:
BOOTSTRAP_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
EVENT_NAME: ${{ github.event_name }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name || '' }}
BASE_REPO: ${{ github.repository }}
run: |
set -euo pipefail
if [[ -f scripts/cursor-automation.cjs ]]; then
echo "Helper present on default branch."
exit 0
fi
if [[ "$EVENT_NAME" == "pull_request_target" ]] || { [[ -n "$HEAD_REPO" ]] && [[ "$HEAD_REPO" != "$BASE_REPO" ]]; }; then
echo "Helper missing on default branch; refusing untrusted bootstrap for ${EVENT_NAME}." >&2
exit 1
fi
echo "Helper missing on default branch; bootstrapping from ${BOOTSTRAP_SHA}"
git fetch --depth=1 origin "${BOOTSTRAP_SHA}"
mkdir -p scripts
git show "FETCH_HEAD:scripts/cursor-automation.cjs" > scripts/cursor-automation.cjs
test -s scripts/cursor-automation.cjs
- name: Freeze trusted helper
run: cp scripts/cursor-automation.cjs "$RUNNER_TEMP/cursor-automation.cjs"
- name: Inspect Codex outcome
id: codex
uses: actions/github-script@v7
with:
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
const pull_number = Number(process.env.PULL_NUMBER);
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number,
});
if (pr.state !== 'open') {
core.info(`PR #${pull_number} is ${pr.state}; skip Codex loop.`);
core.setOutput('action', 'skip');
core.setOutput('eligible', 'false');
core.setOutput('head_sha', pr.head?.sha || '');
core.setOutput('head_ref', pr.head?.ref || '');
core.setOutput('draft', pr.draft ? 'true' : 'false');
return;
}
const eligible = auto.isFixEligiblePr(pr, {
ownActors: process.env.OWN_ACTORS,
repository: `${context.repo.owner}/${context.repo.repo}`,
});
core.setOutput('eligible', eligible ? 'true' : 'false');
core.setOutput('head_sha', pr.head.sha);
core.setOutput('head_ref', pr.head.ref);
core.setOutput('draft', pr.draft ? 'true' : 'false');
const issueComments = await github.paginate(
github.rest.issues.listComments,
{
...context.repo,
issue_number: pull_number,
per_page: 100,
},
);
const reviewComments = await github.paginate(
github.rest.pulls.listReviewComments,
{
...context.repo,
pull_number,
per_page: 100,
},
);
const submittedReviews = await github.paginate(
github.rest.pulls.listReviews,
{
...context.repo,
pull_number,
per_page: 100,
},
);
const codexIssue = issueComments
.filter(
(c) =>
auto.isCodexBotLogin(c.user?.login) &&
auto.isCodexTerminalReviewText(c.body),
)
.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
const codexReviews = reviewComments.filter((c) =>
auto.isCodexBotLogin(c.user?.login),
);
const codexSubmitted = submittedReviews
.filter(
(r) =>
auto.isCodexBotLogin(r.user?.login) &&
auto.isCodexTerminalReviewText(r.body),
)
.map((r) => ({
body: r.body,
created_at: r.submitted_at || r.created_at,
// Authoritative commit for this submitted review (may lack body pin).
commit_id: r.commit_id || '',
}));
const summaryCandidates = [
...codexIssue.map((c) => ({
body: c.body,
created_at: c.created_at,
commit_id: '',
})),
...codexSubmitted,
]
.map((c) => ({
...c,
pin:
auto.extractReviewedCommitSha(c.body) ||
String(c.commit_id || '').toLowerCase(),
}))
.sort(
(a, b) =>
new Date(b.created_at || 0) - new Date(a.created_at || 0),
);
// Only summaries pinned to the current head may drive clean/dirty.
// An older clean comment must not win the sort over a new-head review.
const headSummaries = summaryCandidates.filter(
(c) =>
c.pin && auto.commitShasMatch(pr.head.sha, c.pin),
);
const summaryText = headSummaries[0]?.body || '';
const summaryCommitId = headSummaries[0]?.pin || '';
// Only trust control markers from automation bots / own actors.
const controlOpts = { ownActors: process.env.OWN_ACTORS };
const requestComments = issueComments.filter((c) =>
auto.isAutomationControlComment(c, controlOpts),
);
// Codex often 👍s the @codex request instead of posting clean prose.
const reactionsByCommentId = {};
for (const comment of requestComments.slice(-5)) {
try {
const { data: reactions } = await github.rest.reactions.listForIssueComment({
...context.repo,
comment_id: comment.id,
per_page: 100,
});
reactionsByCommentId[comment.id] = reactions;
} catch (err) {
core.warning(`Failed to list reactions for comment ${comment.id}: ${err.message}`);
}
}
const reactionResult = auto.hasCodexCleanReactionOnRequest({
requestComments,
reactionsByCommentId,
headSha: pr.head.sha,
ownActors: process.env.OWN_ACTORS,
});
const outcome = auto.parseCodexReviewOutcome({
summaryText,
reviewComments: codexReviews,
issueComments: codexIssue,
headSha: pr.head.sha,
cleanReaction: reactionResult.clean,
reactionRequestHeadSha: reactionResult.requestHeadSha || '',
summaryCommitId,
});
const round = auto.getCodexRoundFromComments(
issueComments,
controlOpts,
);
const hasCodexActivity =
Boolean(summaryText) ||
auto.filterCodexReviewCommentsForHead(codexReviews, pr.head.sha)
.length > 0 ||
reactionResult.clean;
const lastAutomationRequestAt = auto.getLatestCommentTime(
issueComments,
(c) => auto.isAutomationControlComment(c, controlOpts),
);
const latestInlineAt = auto.getLatestCommentTime(
auto.filterCodexReviewCommentsForHead(codexReviews, pr.head.sha),
() => true,
);
const lastCodexSummaryAt = Math.max(
auto.getLatestCommentTime(headSummaries, () => true),
latestInlineAt,
);
const latestRequest = [...requestComments].sort(
(a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0),
)[0];
const requestedHeadSha =
reactionResult.requestHeadSha ||
auto.extractRequestedHeadSha(latestRequest?.body || '');
const decision = auto.decideCodexLoopAction({
eligible,
outcome,
round,
maxRounds: Number(process.env.MAX_ROUNDS || '40'),
hasAutomationRequest: auto.hasAutomationCodexRequest(
issueComments,
controlOpts,
),
hasCodexActivity,
headSha: pr.head.sha,
summaryText,
lastAutomationRequestAt,
lastCodexSummaryAt,
requestedHeadSha,
forceRetry: process.env.GITHUB_EVENT_NAME === 'workflow_dispatch',
});
core.setOutput('round', String(round));
core.setOutput('clean', outcome.clean ? 'true' : 'false');
core.setOutput('reason', decision.reason);
core.setOutput('action', decision.action);
if (decision.action === 'fix') {
const findings = auto.formatCodexFindingsMarkdown({
summaryText,
reviewComments: codexReviews,
issueComments: codexIssue,
pullNumber: pull_number,
headSha: pr.head.sha,
});
const fs = require('node:fs');
fs.mkdirSync('.cursor-runtime', { recursive: true });
fs.writeFileSync('.cursor-runtime/codex-findings.md', findings);
}
- name: Request Codex review
if: steps.codex.outputs.action == 'request_review'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
const pull_number = Number(process.env.PULL_NUMBER);
await github.rest.issues.addLabels({
...context.repo,
issue_number: pull_number,
labels: ['automation:codex-loop'],
});
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number,
});
if (pr.state !== 'open') {
core.info(`PR #${pull_number} is ${pr.state}; skip Codex request.`);
return;
}
// Draft-until-clean when possible. GITHUB_TOKEN often lacks this
// mutation — warn and continue so @codex still runs.
if (!pr.draft) {
try {
const prInfo = await github.graphql(
`query($owner:String!, $name:String!, $number:Int!) {
repository(owner:$owner, name:$name) {
pullRequest(number:$number) { id isDraft }
}
}`,
{
owner: context.repo.owner,
name: context.repo.repo,
number: pull_number,
},
);
const node = prInfo.repository.pullRequest;
if (!node.isDraft) {
const converted = await github.graphql(
`mutation($id:ID!) {
convertPullRequestToDraft(input:{pullRequestId:$id}) {
pullRequest { isDraft }
}
}`,
{ id: node.id },
);
if (!converted.convertPullRequestToDraft.pullRequest.isDraft) {
core.warning(
`PR #${pull_number} still not draft after convert; continuing with @codex`,
);
}
}
} catch (err) {
core.warning(
`Could not convert PR #${pull_number} to draft (${err.message || err}); continuing with @codex`,
);
}
}
try {
await github.rest.issues.removeLabel({
...context.repo,
issue_number: pull_number,
name: 'automation:codex-clean',
});
} catch {
// optional
}
await github.rest.issues.createComment({
...context.repo,
issue_number: pull_number,
body: auto.buildCodexReviewRequestComment(1, pr.head.sha),
});
- name: Mark PR ready after clean Codex
if: steps.codex.outputs.action == 'mark_ready'
env:
GH_TOKEN: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
EXPECTED_HEAD: ${{ steps.codex.outputs.head_sha }}
run: |
set -euo pipefail
# Closed / missing PRs are not an automation failure.
state="$(gh pr view "$PULL_NUMBER" --repo "$GITHUB_REPOSITORY" --json state -q .state 2>/dev/null || echo MISSING)"
if [[ "$state" != "OPEN" ]]; then
echo "PR #$PULL_NUMBER is $state; skip mark ready."
exit 0
fi
# Refuse to approve if the head moved after the clean decision.
live_head="$(gh pr view "$PULL_NUMBER" --repo "$GITHUB_REPOSITORY" --json headRefOid -q .headRefOid)"
if [[ -z "$EXPECTED_HEAD" || -z "$live_head" ]]; then
echo "Missing expected/live head SHA; refusing to mark ready." >&2
exit 1
fi
if [[ "$live_head" != "$EXPECTED_HEAD" && "${live_head:0:7}" != "${EXPECTED_HEAD:0:7}" && "${EXPECTED_HEAD:0:7}" != "${live_head:0:7}" ]]; then
# Allow prefix match either way for short SHAs.
case "$live_head" in
"$EXPECTED_HEAD"*) ;;
*)
case "$EXPECTED_HEAD" in
"$live_head"*) ;;
*)
echo "Head moved after clean decision (expected $EXPECTED_HEAD, live $live_head). Skipping mark ready." >&2
exit 0
;;
esac
;;
esac
fi
# Tolerate already-ready / closed / permission noise.
ready_out="$(gh pr ready "$PULL_NUMBER" --repo "$GITHUB_REPOSITORY" 2>&1)" || {
if echo "$ready_out" | grep -qiE 'already ready|not a draft|is not a draft|is closed|closed\.|only draft'; then
echo "PR not convertible to ready (ok to skip): $ready_out"
exit 0
fi
echo "$ready_out" >&2
exit 1
}
# Re-check head after gh pr ready (another push could race).
live_head2="$(gh pr view "$PULL_NUMBER" --repo "$GITHUB_REPOSITORY" --json headRefOid -q .headRefOid)"
if [[ "$live_head2" != "$live_head" ]]; then
echo "Head changed during mark-ready; restoring draft." >&2
gh pr ready "$PULL_NUMBER" --repo "$GITHUB_REPOSITORY" --undo 2>/dev/null || true
exit 0
fi
gh pr edit "$PULL_NUMBER" --repo "$GITHUB_REPOSITORY" \
--add-label "automation:codex-clean" \
--add-label "automation:bot-pr" || true
gh pr edit "$PULL_NUMBER" --repo "$GITHUB_REPOSITORY" \
--remove-label "automation:codex-loop" || true
# Confirm draft=false before claiming success.
draft="$(gh pr view "$PULL_NUMBER" --repo "$GITHUB_REPOSITORY" --json isDraft -q .isDraft)"
if [[ "$draft" == "true" ]]; then
echo "Failed to convert PR out of draft (token may lack draft permission); labels still applied." >&2
exit 0
fi
gh pr comment "$PULL_NUMBER" --repo "$GITHUB_REPOSITORY" --body "$(cat <<'EOF'
<!-- cursor-automation -->
Codex reported no major issues. This PR is marked ready for human review/merge.
EOF
)"
- name: Give up after max rounds / P3 handoff
if: steps.codex.outputs.action == 'give_up'
uses: actions/github-script@v7
env:
REASON: ${{ steps.codex.outputs.reason }}
MAX_ROUNDS: ${{ env.MAX_ROUNDS }}
PULL_NUMBER: ${{ needs.route.outputs.pull_number }}
with:
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
const pull_number = Number(process.env.PULL_NUMBER);
await github.rest.issues.addLabels({
...context.repo,
issue_number: pull_number,
labels: ['ready-for-human'],
});
const reason = process.env.REASON || 'max_rounds';
const message =
reason === 'codex_p3_only'
? 'Codex only reported P3 nitpicks (no P0–P2). Automatic fix stopped; a maintainer can decide whether to polish further.'
: `Stopped after ${process.env.MAX_ROUNDS} Codex fix rounds. A maintainer needs to finish this PR.`;
await github.rest.issues.createComment({
...context.repo,
issue_number: pull_number,
body: [
auto.TRIAGE_MARKER,
auto.DISCLAIMER,
'',
message,
].join('\n'),
});
- name: Checkout PR head for fix
if: steps.codex.outputs.action == 'fix'
uses: actions/checkout@v5
with:
ref: ${{ steps.codex.outputs.head_sha }}
fetch-depth: 0
persist-credentials: false
- name: Restore findings file
if: steps.codex.outputs.action == 'fix'
uses: actions/github-script@v7
with:
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
const pull_number = Number(process.env.PULL_NUMBER);
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number,
});
const issueComments = await github.paginate(
github.rest.issues.listComments,
{
...context.repo,
issue_number: pull_number,
per_page: 100,
},
);
const reviewComments = await github.paginate(
github.rest.pulls.listReviewComments,
{
...context.repo,
pull_number,
per_page: 100,
},
);
const submittedReviews = await github.paginate(
github.rest.pulls.listReviews,
{
...context.repo,
pull_number,
per_page: 100,
},
);
const codexIssue = issueComments.filter(
(c) =>
auto.isCodexBotLogin(c.user?.login) &&
auto.isCodexTerminalReviewText(c.body),
);
const codexReviews = reviewComments.filter((c) =>
auto.isCodexBotLogin(c.user?.login),
);
const codexSubmitted = submittedReviews.filter(
(r) =>
auto.isCodexBotLogin(r.user?.login) &&
auto.isCodexTerminalReviewText(r.body),
);
const summaryCandidates = [
...codexIssue.map((c) => ({
body: c.body,
created_at: c.created_at,
pin: auto.extractReviewedCommitSha(c.body),
})),
...codexSubmitted.map((r) => ({
body: r.body,
created_at: r.submitted_at || r.created_at,
pin:
auto.extractReviewedCommitSha(r.body) ||
String(r.commit_id || '').toLowerCase(),
})),
]
.filter(
(c) =>
c.pin && auto.commitShasMatch(pr.head.sha, c.pin),
)
.sort(
(a, b) =>
new Date(b.created_at || 0) - new Date(a.created_at || 0),
);
const findings = auto.formatCodexFindingsMarkdown({
summaryText: summaryCandidates[0]?.body || '',
reviewComments: auto.filterCodexReviewCommentsForHead(
codexReviews,
pr.head.sha,
),
issueComments: codexIssue,
pullNumber: pull_number,
headSha: pr.head.sha,
});
auto.writeText('.cursor-runtime/codex-findings.md', findings);
- name: Setup Node
if: steps.codex.outputs.action == 'fix'
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Install dependencies
if: steps.codex.outputs.action == 'fix'
run: npm ci
- name: Install Cursor CLI
if: steps.codex.outputs.action == 'fix'
run: |
curl https://cursor.com/install -fsS | bash
# Official installer places `agent` under ~/.local/bin (and sometimes ~/.cursor/bin).
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
echo "$HOME/.cursor/bin" >> "$GITHUB_PATH"
command -v agent || ls -la "$HOME/.local/bin" "$HOME/.cursor/bin" 2>/dev/null || true
- name: Ensure Cursor API key
if: steps.codex.outputs.action == 'fix'
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
run: |
if [[ -z "$CURSOR_API_KEY" ]]; then
echo "CURSOR_API_KEY is not configured." >&2
exit 1
fi
- name: Record base SHA before agent
if: steps.codex.outputs.action == 'fix'
id: base
run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- name: Fix with Cursor CLI
if: steps.codex.outputs.action == 'fix'
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
BASE_SHA: ${{ steps.base.outputs.sha }}
GITHUB_TOKEN: ''
GH_TOKEN: ''
run: |
set -euo pipefail
git config --local --unset-all http.https://github.com/.extraheader || true
# Prefer trusted prompt from default branch. PR trees created before this
# automation landed may not have the fix prompt at all.
DEFAULT_BRANCH="${{ github.event.repository.default_branch }}"
PROMPT=""
if git cat-file -e "origin/${DEFAULT_BRANCH}:.github/cursor/prompts/fix-from-codex.md" 2>/dev/null; then
PROMPT="$(git show "origin/${DEFAULT_BRANCH}:.github/cursor/prompts/fix-from-codex.md")"
elif [[ -f .github/cursor/prompts/fix-from-codex.md ]]; then
PROMPT="$(cat .github/cursor/prompts/fix-from-codex.md)"
else
echo "Missing fix-from-codex.md on default branch and PR tree." >&2
exit 1
fi
agent -p --force --trust --sandbox disabled --model auto --output-format text \
--workspace "$GITHUB_WORKSPACE" \
"$PROMPT" | tee .cursor-runtime/fix-raw.txt
# Avoid git diff under CURSOR_API_KEY (textconv/hooks). Patch scan is later.
node -e '
const { execSync } = require("node:child_process");
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
auto.assertFilesDoNotContainSecret(
[".cursor-runtime/fix-raw.txt"],
process.env.CURSOR_API_KEY,
"fix-output",
);
const untracked = execSync(
"git -c core.hooksPath=/dev/null ls-files --others --exclude-standard",
{ encoding: "utf8" },
)
.split("\n")
.filter(Boolean)
.filter((p) => !p.startsWith(".cursor-runtime/"));
auto.assertFilesDoNotContainSecret(
untracked,
process.env.CURSOR_API_KEY,
"fix-untracked",
);
'
- name: Guard protected paths (tree + commits)
if: steps.codex.outputs.action == 'fix'
run: |
set -euo pipefail
status="$(git status --porcelain --untracked-files=all -- . ':(exclude).cursor-runtime' ':(exclude).cursor-runtime/**' || true)"
names="$(git diff --name-only "${{ steps.base.outputs.sha }}" HEAD 2>/dev/null || true)"
name_status="$(git diff --name-status -M "${{ steps.base.outputs.sha }}" HEAD 2>/dev/null || true)"
node -e '
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
const hits = auto.hasProtectedChangesInSources({
gitStatusPorcelain: process.argv[1],
changedFiles: process.argv[2].split("\n").filter(Boolean),
nameStatusText: process.argv[3],
});
if (hits.length) {
console.error("Protected paths modified:", hits.join(", "));
process.exit(1);
}
' "$status" "$names" "$name_status"
- name: Install test shell dependencies
if: steps.codex.outputs.action == 'fix'
run: |
# Match .github/workflows/test.yml — osc7Setup.test.ts requires fish in CI.
sudo apt-get update
sudo apt-get install -y fish
- name: Verify fix
if: steps.codex.outputs.action == 'fix'
run: |
set +e
npm run lint || exit 1
npm test || exit 1
npm run build || exit 1
- name: Prepare fix patch for isolated publish
if: steps.codex.outputs.action == 'fix'
id: fixpatch
# No CURSOR_API_KEY: git ops must not share an env with secrets after agent.
env:
BASE_SHA: ${{ steps.base.outputs.sha }}
PULL_NUMBER: ${{ needs.route.outputs.pull_number }}
run: |
set -euo pipefail
GITH='git -c core.hooksPath=/dev/null'
$GITH config --local --unset-all core.hooksPath 2>/dev/null || true
$GITH config --local --unset-all core.fsmonitor 2>/dev/null || true
status="$($GITH status --porcelain --untracked-files=all -- . ':(exclude).cursor-runtime' ':(exclude).cursor-runtime/**' || true)"
if [[ -n "$status" ]]; then
$GITH add -A
$GITH reset -- .cursor-runtime >/dev/null 2>&1 || true
$GITH -c user.name="netcatty-bot" -c user.email="308658023+netcatty-bot@users.noreply.github.com" \
commit -m "fix: address Codex review on PR #${PULL_NUMBER}" || true
fi
name_status="$($GITH diff --name-status -M "${BASE_SHA}" HEAD 2>/dev/null || true)"
node -e '
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
const hits = auto.hasProtectedChangesInSources({ nameStatusText: process.argv[1] });
if (hits.length) {
console.error("Protected paths modified:", hits.join(", "));
process.exit(1);
}
' "$name_status"
if [[ "$($GITH rev-list --count "${BASE_SHA}..HEAD")" == "0" ]]; then
echo "empty=true" >> "$GITHUB_OUTPUT"
echo "should_publish=false" >> "$GITHUB_OUTPUT"
exit 0
fi
runtime_hits="$($GITH diff --name-only "${BASE_SHA}" HEAD | grep -E '^\.cursor-runtime(/|$)' || true)"
if [[ -n "$runtime_hits" ]]; then
echo "Refusing to publish commits that include .cursor-runtime paths:" >&2
echo "$runtime_hits" >&2
exit 1
fi
mkdir -p .cursor-runtime
$GITH format-patch --stdout "${BASE_SHA}" > .cursor-runtime/fix.patch
test -s .cursor-runtime/fix.patch
echo "empty=false" >> "$GITHUB_OUTPUT"
echo "should_publish=true" >> "$GITHUB_OUTPUT"
- name: Scan fix patch for secret leaks
if: steps.codex.outputs.action == 'fix' && steps.fixpatch.outputs.should_publish == 'true'
env:
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
run: |
set -euo pipefail
node -e '
const auto = require(process.env.RUNNER_TEMP + "/cursor-automation.cjs");
auto.assertFilesDoNotContainSecret(
[".cursor-runtime/fix.patch"],
process.env.CURSOR_API_KEY,
"fix-publish",
);
'
- name: Upload fix patch
if: steps.codex.outputs.action == 'fix' && steps.fixpatch.outputs.should_publish == 'true'
uses: actions/upload-artifact@v4
with:
name: codex-fix-patch-${{ github.run_id }}
path: .cursor-runtime/fix.patch
if-no-files-found: error
- name: Mark needs human when no fix produced
if: steps.codex.outputs.action == 'fix' && steps.fixpatch.outputs.empty == 'true'
uses: actions/github-script@v7
with:
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
const pull_number = Number(process.env.PULL_NUMBER);
await github.rest.issues.createComment({
...context.repo,
issue_number: pull_number,
body: [
auto.TRIAGE_MARKER,
auto.DISCLAIMER,
'',
'Automatic fix did not produce additional code changes for the latest Codex findings. Marking for human review.',
].join('\n'),
});
await github.rest.issues.addLabels({
...context.repo,
issue_number: pull_number,
labels: ['ready-for-human'],
});
env:
PULL_NUMBER: ${{ needs.route.outputs.pull_number }}
- name: Mark needs human on fix failure
if: failure() && steps.codex.outputs.action == 'fix'
uses: actions/github-script@v7
env:
PULL_NUMBER: ${{ needs.route.outputs.pull_number }}
with:
script: |
const fs = require('node:fs');
const helper = fs.existsSync(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`)
? `${process.env.RUNNER_TEMP}/cursor-automation.cjs`
: `${process.env.GITHUB_WORKSPACE}/scripts/cursor-automation.cjs`;
const auto = require(helper);
const pull_number = Number(process.env.PULL_NUMBER);
await github.rest.issues.createComment({
...context.repo,
issue_number: pull_number,
body: [
auto.TRIAGE_MARKER,
auto.DISCLAIMER,
'',
'Automatic Codex fix did not finish cleanly (agent, protected paths, or verification failed). Marking for human review.',
].join('\n'),
});
await github.rest.issues.addLabels({
...context.repo,
issue_number: pull_number,
labels: ['ready-for-human'],
});
publish_codex_fix:
name: Publish Codex fix
needs: [codex_loop]
if: needs.codex_loop.outputs.should_publish == 'true'
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: write
issues: write
pull-requests: write
env:
# Prefer PAT so push events trigger normal CI workflows.
GH_TOKEN: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
HEAD_REF: ${{ needs.codex_loop.outputs.head_ref }}
BASE_SHA: ${{ needs.codex_loop.outputs.base_sha }}
PULL_NUMBER: ${{ needs.codex_loop.outputs.pull_number }}
PREV_ROUND: ${{ needs.codex_loop.outputs.prev_round }}
steps:
- name: Download fix patch
uses: actions/download-artifact@v4
with:
name: codex-fix-patch-${{ github.run_id }}
path: patch-in
- name: Publish fix from fresh runner
run: |
set -euo pipefail
PUBLISH="$RUNNER_TEMP/publish-fix-tree"
rm -rf "$PUBLISH"
git clone --no-checkout "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "$PUBLISH"
cd "$PUBLISH"
git -c core.hooksPath=/dev/null config user.name "netcatty-bot"
git -c core.hooksPath=/dev/null config user.email "308658023+netcatty-bot@users.noreply.github.com"
git -c core.hooksPath=/dev/null fetch --depth=50 origin "$BASE_SHA"
git -c core.hooksPath=/dev/null checkout -B "$HEAD_REF" "$BASE_SHA"
git -c core.hooksPath=/dev/null am --3way "$GITHUB_WORKSPACE/patch-in/fix.patch"
git -c core.hooksPath=/dev/null push origin "HEAD:$HEAD_REF"
- name: Checkout helper
uses: actions/checkout@v5
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
path: helpers
- name: Load helper
run: |
set -euo pipefail
if [[ -f helpers/scripts/cursor-automation.cjs ]]; then
cp helpers/scripts/cursor-automation.cjs "$RUNNER_TEMP/cursor-automation.cjs"
else
git -C helpers fetch --depth=1 origin "${{ github.sha }}"
git -C helpers show "FETCH_HEAD:scripts/cursor-automation.cjs" > "$RUNNER_TEMP/cursor-automation.cjs"
fi
test -s "$RUNNER_TEMP/cursor-automation.cjs"
- name: Re-request Codex after fix push
uses: actions/github-script@v7
with:
script: |
const auto = require(`${process.env.RUNNER_TEMP}/cursor-automation.cjs`);
const pull_number = Number(process.env.PULL_NUMBER);
const nextRound = (Number(process.env.PREV_ROUND) || 0) + 1;
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number,
});
await github.rest.issues.createComment({
...context.repo,
issue_number: pull_number,
body: auto.buildCodexReviewRequestComment(nextRound, pr.head.sha),
});
own_rerequest_codex:
name: Own PR re-request Codex
needs: route
if: needs.route.outputs.kind == 'own_rerequest_codex'
runs-on: ubuntu-latest
timeout-minutes: 10
# Must write the @codex review comment after maintainer pushes.
# Without this, the workflow default read-only GITHUB_TOKEN gets 403.
permissions:
contents: read
issues: write
pull-requests: write
env:
PULL_NUMBER: ${{ needs.route.outputs.pull_number }}
OWN_ACTORS: ${{ vars.AUTOMATION_OWN_ACTORS || 'binaricat,netcatty-bot,github-actions[bot]' }}
steps:
- name: Checkout helpers
uses: actions/checkout@v5
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
- name: Ensure automation helper present
env:
BOOTSTRAP_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
EVENT_NAME: ${{ github.event_name }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name || '' }}
BASE_REPO: ${{ github.repository }}
run: |
set -euo pipefail
if [[ -f scripts/cursor-automation.cjs ]]; then
echo "Helper present on default branch."
exit 0
fi
if [[ "$EVENT_NAME" == "pull_request_target" ]] || { [[ -n "$HEAD_REPO" ]] && [[ "$HEAD_REPO" != "$BASE_REPO" ]]; }; then
echo "Helper missing on default branch; refusing untrusted bootstrap for ${EVENT_NAME}." >&2
exit 1
fi
echo "Helper missing on default branch; bootstrapping from ${BOOTSTRAP_SHA}"
git fetch --depth=1 origin "${BOOTSTRAP_SHA}"
mkdir -p scripts
git show "FETCH_HEAD:scripts/cursor-automation.cjs" > scripts/cursor-automation.cjs
test -s scripts/cursor-automation.cjs
- name: Comment @codex review after human push
uses: actions/github-script@v7
with:
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.GITHUB_WORKSPACE}/scripts/cursor-automation.cjs`);
const pull_number = Number(process.env.PULL_NUMBER);
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number,
});
if (
!auto.isFixEligiblePr(pr, {
ownActors: process.env.OWN_ACTORS,
repository: `${context.repo.owner}/${context.repo.repo}`,
})
) {
core.info('Not fix-eligible; skip own re-request.');
return;
}
const comments = await github.paginate(
github.rest.issues.listComments,
{
...context.repo,
issue_number: pull_number,
per_page: 100,
},
);
if (
auto.shouldSkipExternalCodexRerequest({
existingComments: comments,
headSha: pr.head.sha,
ownActors: process.env.OWN_ACTORS,
})
) {
core.info(`Already re-requested Codex for ${pr.head.sha}`);
return;
}
// Human/maintainer pushes must not burn Cursor fix-round budget.
// Reuse the current round marker; only automated fix publishes increment it.
const round = Math.max(
auto.getCodexRoundFromComments(comments, {
ownActors: process.env.OWN_ACTORS,
}),
1,
);
// New head invalidates a previous clean gate — restore draft review loop.
try {
await github.rest.issues.removeLabel({
...context.repo,
issue_number: pull_number,
name: 'automation:codex-clean',
});
} catch {
// label may already be absent
}
await github.rest.issues.addLabels({
...context.repo,
issue_number: pull_number,
labels: ['automation:codex-loop'],
});
if (!pr.draft && pr.state === 'open') {
// Best-effort draft-until-clean; do not fail the job if token lacks draft mutation.
try {
const prInfo = await github.graphql(
`query($owner:String!, $name:String!, $number:Int!) {
repository(owner:$owner, name:$name) {
pullRequest(number:$number) { id isDraft }
}
}`,
{
owner: context.repo.owner,
name: context.repo.repo,
number: pull_number,
},
);
const node = prInfo.repository.pullRequest;
if (!node.isDraft) {
await github.graphql(
`mutation($id:ID!) {
convertPullRequestToDraft(input:{pullRequestId:$id}) {
pullRequest { isDraft }
}
}`,
{ id: node.id },
);
}
} catch (err) {
core.warning(
`Could not convert PR #${pull_number} to draft after human push (${err.message || err}); continuing with @codex`,
);
}
}
await github.rest.issues.createComment({
...context.repo,
issue_number: pull_number,
body: [
auto.buildCodexReviewRequestComment(round, pr.head.sha),
auto.buildExternalCodexRerequestComment(pr.head.sha),
].join('\n'),
});
external_rerequest_codex:
name: External PR re-request Codex
needs: route
if: needs.route.outputs.kind == 'external_rerequest_codex'
runs-on: ubuntu-latest
timeout-minutes: 10
# Write comments only; never checkout untrusted PR code.
permissions:
contents: read
issues: write
pull-requests: write
env:
PULL_NUMBER: ${{ needs.route.outputs.pull_number }}
OWN_ACTORS: ${{ vars.AUTOMATION_OWN_ACTORS || 'binaricat,netcatty-bot,github-actions[bot]' }}
steps:
- name: Checkout helpers
uses: actions/checkout@v5
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
- name: Ensure automation helper present
env:
BOOTSTRAP_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
EVENT_NAME: ${{ github.event_name }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name || '' }}
BASE_REPO: ${{ github.repository }}
run: |
set -euo pipefail
if [[ -f scripts/cursor-automation.cjs ]]; then
echo "Helper present on default branch."
exit 0
fi
if [[ "$EVENT_NAME" == "pull_request_target" ]] || { [[ -n "$HEAD_REPO" ]] && [[ "$HEAD_REPO" != "$BASE_REPO" ]]; }; then
echo "Helper missing on default branch; refusing untrusted bootstrap for ${EVENT_NAME}." >&2
exit 1
fi
echo "Helper missing on default branch; bootstrapping from ${BOOTSTRAP_SHA}"
git fetch --depth=1 origin "${BOOTSTRAP_SHA}"
mkdir -p scripts
git show "FETCH_HEAD:scripts/cursor-automation.cjs" > scripts/cursor-automation.cjs
test -s scripts/cursor-automation.cjs
- name: Comment @codex review after contributor push
uses: actions/github-script@v7
with:
# pull_request_target provides write GITHUB_TOKEN for forks; optional PAT override.
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.GITHUB_WORKSPACE}/scripts/cursor-automation.cjs`);
// External job checks out default branch only; tree is trusted.
const pull_number = Number(process.env.PULL_NUMBER);
const { data: pr } = await github.rest.pulls.get({
...context.repo,
pull_number,
});
// Never auto-fix third-party code paths here.
if (
auto.isFixEligiblePr(pr, {
ownActors: process.env.OWN_ACTORS,
repository: `${context.repo.owner}/${context.repo.repo}`,
})
) {
core.info('PR is fix-eligible; skipping external re-request path.');
return;
}
const comments = await github.paginate(
github.rest.issues.listComments,
{
...context.repo,
issue_number: pull_number,
per_page: 100,
},
);
const forceRetry =
process.env.GITHUB_EVENT_NAME === 'workflow_dispatch';
if (
!forceRetry &&
auto.shouldSkipExternalCodexRerequest({
existingComments: comments,
headSha: pr.head.sha,
ownActors: process.env.OWN_ACTORS,
})
) {
core.info(`Already re-requested Codex for ${pr.head.sha}`);
return;
}
await github.rest.issues.createComment({
...context.repo,
issue_number: pull_number,
body: auto.buildExternalCodexRerequestComment(pr.head.sha),
});
core.info(`Posted @codex review for external PR #${pull_number}`);
# Poll open automation PRs for reaction-only clean Codex results and expired
# unanswered @codex requests. Needed because 👍 reactions do not fire workflows.
codex_poll:
name: Poll Codex reaction / retry
needs: route
if: needs.route.outputs.kind == 'codex_poll'
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
issues: write
pull-requests: write
env:
OWN_ACTORS: ${{ vars.AUTOMATION_OWN_ACTORS || 'binaricat,netcatty-bot,github-actions[bot]' }}
MAX_ROUNDS: ${{ vars.CURSOR_CODEX_FIX_MAX_ROUNDS || '40' }}
GH_TOKEN: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
steps:
- name: Checkout helpers
uses: actions/checkout@v5
with:
ref: ${{ github.event.repository.default_branch }}
persist-credentials: false
- name: Ensure automation helper present
env:
BOOTSTRAP_SHA: ${{ github.sha }}
EVENT_NAME: ${{ github.event_name }}
run: |
set -euo pipefail
if [[ -f scripts/cursor-automation.cjs ]]; then
echo "Helper present on default branch."
exit 0
fi
echo "Helper missing on default branch; bootstrapping from ${BOOTSTRAP_SHA}"
git fetch --depth=1 origin "${BOOTSTRAP_SHA}"
mkdir -p scripts
git show "FETCH_HEAD:scripts/cursor-automation.cjs" > scripts/cursor-automation.cjs
test -s scripts/cursor-automation.cjs
- name: Poll open automation PRs
uses: actions/github-script@v7
with:
github-token: ${{ secrets.TRIAGE_GITHUB_TOKEN || secrets.GITHUB_TOKEN }}
script: |
const auto = require(`${process.env.GITHUB_WORKSPACE}/scripts/cursor-automation.cjs`);
const ownActors = process.env.OWN_ACTORS;
const controlOpts = { ownActors };
const pulls = await github.paginate(github.rest.pulls.list, {
...context.repo,
state: 'open',
per_page: 50,
});
let handled = 0;
for (const pr of pulls) {
if (handled >= 10) break;
if (
!auto.isFixEligiblePr(pr, {
ownActors,
repository: `${context.repo.owner}/${context.repo.repo}`,
})
) {
continue;
}
const labels = (pr.labels || []).map((l) =>
typeof l === 'string' ? l : l.name,
);
if (
!labels.includes('automation:codex-loop') &&
!labels.includes('automation:bot-pr')
) {
continue;
}
if (labels.includes('automation:codex-clean')) continue;
const issueComments = await github.paginate(
github.rest.issues.listComments,
{
...context.repo,
issue_number: pr.number,
per_page: 100,
},
);
const requestComments = issueComments.filter((c) =>
auto.isAutomationControlComment(c, controlOpts),
);
if (!requestComments.length) continue;
const reactionsByCommentId = {};
for (const comment of requestComments.slice(-3)) {
try {
const { data: reactions } =
await github.rest.reactions.listForIssueComment({
...context.repo,
comment_id: comment.id,
per_page: 100,
});
reactionsByCommentId[comment.id] = reactions;
} catch (err) {
core.warning(
`PR #${pr.number} reactions ${comment.id}: ${err.message}`,
);
}
}
const reactionResult = auto.hasCodexCleanReactionOnRequest({
requestComments,
reactionsByCommentId,
headSha: pr.head.sha,
ownActors,
});
const lastAutomationRequestAt = auto.getLatestCommentTime(
issueComments,
(c) => auto.isAutomationControlComment(c, controlOpts),
);
// Only current-head Codex signals count as "answered". Delayed
// reviews for older commits must not block expiry re-requests.
const headMatches = (commitId, body) => {
const reviewed =
auto.extractReviewedCommitSha(body) ||
String(commitId || '').toLowerCase();
if (!reviewed) return false;
return auto.commitShasMatch(pr.head.sha, reviewed);
};
let lastCodexActivityAt = 0;
for (const c of issueComments) {
if (!auto.isCodexBotLogin(c.user?.login)) continue;
if (!auto.isCodexTerminalReviewText(c.body)) continue;
if (!headMatches('', c.body)) continue;
const ts = Date.parse(c.created_at || '') || 0;
if (ts > lastCodexActivityAt) lastCodexActivityAt = ts;
}
let reviewComments = [];
try {
reviewComments = await github.paginate(
github.rest.pulls.listReviewComments,
{
...context.repo,
pull_number: pr.number,
per_page: 100,
},
);
for (const c of reviewComments) {
if (!auto.isCodexBotLogin(c.user?.login)) continue;
if (
!headMatches(
c.commit_id || c.original_commit_id,
c.body,
)
) {
continue;
}
const ts = Date.parse(c.created_at || '') || 0;
if (ts > lastCodexActivityAt) lastCodexActivityAt = ts;
}
} catch (err) {
core.warning(
`PR #${pr.number}: list review comments failed: ${err.message}`,
);
}
try {
const submitted = await github.paginate(
github.rest.pulls.listReviews,
{
...context.repo,
pull_number: pr.number,
per_page: 100,
},
);
for (const r of submitted) {
if (!auto.isCodexBotLogin(r.user?.login)) continue;
if (!headMatches(r.commit_id, r.body)) continue;
const ts =
Date.parse(r.submitted_at || r.created_at || '') || 0;
if (ts > lastCodexActivityAt) lastCodexActivityAt = ts;
}
} catch (err) {
core.warning(
`PR #${pr.number}: list reviews failed: ${err.message}`,
);
}
if (
reactionResult.clean &&
reactionResult.requestHeadSha &&
auto.commitShasMatch(pr.head.sha, reactionResult.requestHeadSha)
) {
// Clean reaction on a request pinned to this head answers it.
lastCodexActivityAt = Math.max(
lastCodexActivityAt,
lastAutomationRequestAt,
);
}
const requestUnanswered =
lastAutomationRequestAt > 0 &&
lastAutomationRequestAt > lastCodexActivityAt;
const requestExpired =
requestUnanswered &&
Date.now() - lastAutomationRequestAt >= auto.CODEX_REQUEST_RETRY_MS;
if (reactionResult.clean) {
const codexReviews = reviewComments.filter((c) =>
auto.isCodexBotLogin(c.user?.login),
);
const outcome = auto.parseCodexReviewOutcome({
summaryText: '',
reviewComments: codexReviews,
headSha: pr.head.sha,
cleanReaction: true,
reactionRequestHeadSha: reactionResult.requestHeadSha || '',
});
const decision = auto.decideCodexLoopAction({
eligible: true,
outcome,
hasCodexActivity: true,
hasAutomationRequest: true,
headSha: pr.head.sha,
requestedHeadSha: reactionResult.requestHeadSha || '',
lastAutomationRequestAt,
lastCodexSummaryAt: lastAutomationRequestAt,
});
if (decision.action === 'mark_ready') {
// REST pulls.update cannot leave draft; use GraphQL, then label.
try {
// Re-fetch head immediately before changing draft state.
const { data: livePr } = await github.rest.pulls.get({
...context.repo,
pull_number: pr.number,
});
if (
!auto.commitShasMatch(livePr.head.sha, pr.head.sha)
) {
core.info(
`PR #${pr.number}: head moved before mark ready (${pr.head.sha} -> ${livePr.head.sha}); skip`,
);
continue;
}
const prInfo = await github.graphql(
`query($owner:String!, $name:String!, $number:Int!) {
repository(owner:$owner, name:$name) {
pullRequest(number:$number) { id isDraft }
}
}`,
{
owner: context.repo.owner,
name: context.repo.repo,
number: pr.number,
},
);
const node = prInfo.repository.pullRequest;
if (node.isDraft) {
const converted = await github.graphql(
`mutation($id:ID!) {
markPullRequestReadyForReview(input:{pullRequestId:$id}) {
pullRequest { isDraft }
}
}`,
{ id: node.id },
);
if (
converted.markPullRequestReadyForReview.pullRequest
.isDraft
) {
throw new Error('PR still draft after ready mutation');
}
}
const { data: afterPr } = await github.rest.pulls.get({
...context.repo,
pull_number: pr.number,
});
if (!auto.commitShasMatch(afterPr.head.sha, pr.head.sha)) {
// Head raced during conversion — restore draft.
await github.graphql(
`mutation($id:ID!) {
convertPullRequestToDraft(input:{pullRequestId:$id}) {
pullRequest { isDraft }
}
}`,
{ id: node.id },
);
core.info(
`PR #${pr.number}: head moved during mark ready; restored draft`,
);
continue;
}
await github.rest.issues.addLabels({
...context.repo,
issue_number: pr.number,
labels: ['automation:codex-clean'],
});
try {
await github.rest.issues.removeLabel({
...context.repo,
issue_number: pr.number,
name: 'automation:codex-loop',
});
} catch {
// label may already be absent
}
core.info(`PR #${pr.number}: marked ready via clean reaction`);
handled += 1;
} catch (err) {
core.warning(
`PR #${pr.number}: failed to mark ready (${err.message}); will retry next poll`,
);
}
continue;
}
// Clean reaction without a head pin cannot approve this revision;
// re-request once with an explicit head marker.
if (
decision.action === 'skip' &&
decision.reason === 'clean_summary_unpinned'
) {
const alreadyPinned = requestComments.some(
(c) =>
auto.extractRequestedHeadSha(c.body) &&
auto.commitShasMatch(
pr.head.sha,
auto.extractRequestedHeadSha(c.body),
),
);
if (!alreadyPinned) {
const round =
auto.getCodexRoundFromComments(
issueComments,
controlOpts,
) || 1;
await github.rest.issues.createComment({
...context.repo,
issue_number: pr.number,
body: auto.buildCodexReviewRequestComment(
round,
pr.head.sha,
),
});
core.info(
`PR #${pr.number}: re-requested Codex with head pin after unpinned clean reaction`,
);
handled += 1;
}
continue;
}
}
if (requestExpired) {
const round =
auto.getCodexRoundFromComments(issueComments, controlOpts) || 1;
await github.rest.issues.createComment({
...context.repo,
issue_number: pr.number,
body: auto.buildCodexReviewRequestComment(round, pr.head.sha),
});
core.info(`PR #${pr.number}: re-requested Codex after timeout`);
handled += 1;
}
}
core.info(`codex_poll handled ${handled} PR(s)`);