diff --git a/.github/scripts/github-app-installation-token.mjs b/.github/scripts/github-app-installation-token.mjs deleted file mode 100755 index 01f899f..0000000 --- a/.github/scripts/github-app-installation-token.mjs +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env node - -import { createSign } from "node:crypto"; -import { readFile, writeFile } from "node:fs/promises"; - -const cachePath = process.env.GITHUB_APP_TOKEN_CACHE; - -if (cachePath) { - try { - const cached = JSON.parse(await readFile(cachePath, "utf8")); - if (Date.parse(cached.expiresAt) > Date.now() + 5 * 60 * 1000) { - process.stderr.write(`::add-mask::${cached.token}\n`); - process.stdout.write(cached.token); - process.exit(0); - } - } catch { - // A missing, stale, or invalid cache is replaced below. - } -} - -const appId = process.env.GITHUB_APP_ID; -const installationId = process.env.GITHUB_APP_INSTALLATION_ID; -const privateKeyPath = process.env.GITHUB_APP_PRIVATE_KEY_FILE; -const repository = process.env.GITHUB_APP_REPOSITORY; - -if (!appId || !installationId || !privateKeyPath) { - throw new Error("GitHub App ID, installation ID, and private key file are required"); -} - -const now = Math.floor(Date.now() / 1000); -const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url"); -const unsignedToken = `${encode({ alg: "RS256", typ: "JWT" })}.${encode({ - iat: now - 60, - exp: now + 9 * 60, - iss: appId, -})}`; -const privateKey = (await readFile(privateKeyPath, "utf8")).replaceAll("\\n", "\n"); -const signer = createSign("RSA-SHA256"); -signer.update(unsignedToken); -const jwt = `${unsignedToken}.${signer.sign(privateKey, "base64url")}`; - -const response = await fetch( - `https://api.github.com/app/installations/${installationId}/access_tokens`, - { - method: "POST", - headers: { - Accept: "application/vnd.github+json", - Authorization: `Bearer ${jwt}`, - "X-GitHub-Api-Version": "2022-11-28", - "User-Agent": "kernel-tinker-rl-weekly-maintenance", - }, - body: repository ? JSON.stringify({ repositories: [repository] }) : undefined, - }, -); - -if (!response.ok) { - throw new Error(`GitHub App token request failed with HTTP ${response.status}`); -} - -const result = await response.json(); -if (!result.token || !result.expires_at) { - throw new Error("GitHub App token response was incomplete"); -} - -process.stderr.write(`::add-mask::${result.token}\n`); -if (cachePath) { - await writeFile( - cachePath, - JSON.stringify({ token: result.token, expiresAt: result.expires_at }), - { mode: 0o600 }, - ); -} -process.stdout.write(result.token); diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 4414c8d..8957257 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -3,35 +3,4 @@ # Docs: https://gh.io/actions-lockfile version: 'v0.0.3' workflows: - '.github/workflows/weekly-maintenance.yml': - - 'actions/checkout@v4.4.0' - - 'actions/create-github-app-token@v3.3.0' - - 'actions/setup-node@v4.4.0' - - 'astral-sh/setup-uv@v6.8.0' - - 'kernel/security-workflows@main' -dependencies: - 'actions/checkout@v4.4.0': - ref: 'v4.4.0' - commit: 'sha1-11d5960a326750d5838078e36cf38b85af677262' - owner_id: 44036562 - repo_id: 197814629 - 'actions/create-github-app-token@v3.3.0': - ref: 'v3.3.0' - commit: 'sha1-64ab729a6294000f5aa4a4bc0b73d1f32bc45510' - owner_id: 44036562 - repo_id: 642580244 - 'actions/setup-node@v4.4.0': - ref: 'v4.4.0' - commit: 'sha1-49933ea5288caeca8642d1e84afbd3f7d6820020' - owner_id: 44036562 - repo_id: 189476904 - 'astral-sh/setup-uv@v6.8.0': - ref: 'v6.8.0' - commit: 'sha1-d0cc045d04ccac9d8b7881df0226f9e82c39688e' - owner_id: 115962839 - repo_id: 846733598 - 'kernel/security-workflows@main': - ref: 'main' - commit: 'sha1-56bdfc09970ce29b2ad4df3daa17adb9a7ed4ce0' - owner_id: 194616459 - repo_id: 1207196574 + '.github/workflows/weekly-maintenance.yml': [] diff --git a/.github/workflows/weekly-maintenance-prompt.md b/.github/workflows/weekly-maintenance-prompt.md index 8bc3f50..0e1ad6b 100644 --- a/.github/workflows/weekly-maintenance-prompt.md +++ b/.github/workflows/weekly-maintenance-prompt.md @@ -1,8 +1,8 @@ You are operating in a GitHub Actions runner for the kernel-tinker-rl repository. -The GitHub CLI is available as `gh`, and Git is authenticated as the `kernel-internal[bot]` GitHub App. Their credential helpers renew the installation token before it expires; use the normal `gh` and `git` commands, and never bypass the helpers or print credentials. You may push branches, create pull requests, reply to review comments, and merge pull requests. Pi Web Access is installed; call `web_enable` before using `web_search`, `fetch_content`, or `get_search_content` for release notes and migration guidance. +You run in a Docker Sandbox: a microVM with its own kernel and Docker daemon, where you have sudo. `gh` and `git` reach GitHub as the `kernel-internal[bot]` GitHub App through the sandbox proxy, which adds the credential to each request, so there is no token to handle. `gh pr checks ` reads check runs, Cursor Bugbot included, through the workflow's read-only relay. You may push branches, create pull requests, reply to review comments, and rerun workflow runs. The workflow merges the pull request, not you. Pi Web Access is installed; call `web_enable` before using `web_search`, `fetch_content`, or `get_search_content` for release notes and migration guidance. -`uv`, Node, and the Kernel CLI (`kernel`) are installed. `KERNEL_API_KEY` and `TINKER_API_KEY` are set for smoke tests and model baselines. WebJudge reaches OpenRouter with a short-lived token from `OPENROUTER_ACCESS_TOKEN_FILE`; there is no `OPENROUTER_API_KEY`, so don't ask for one. +`uv`, Node, and the Kernel CLI (`kernel`) are installed. `KERNEL_API_KEY` and `TINKER_API_KEY` are set for smoke tests and model baselines. WebJudge reads its OpenRouter credential from `OPENROUTER_ACCESS_TOKEN_FILE`. The file holds a placeholder that the sandbox proxy swaps for a short-lived token on requests to OpenRouter, so use it as is and don't ask for an `OPENROUTER_API_KEY`. # Context @@ -16,7 +16,7 @@ The repository trains a text model with Tinker (GRPO, LoRA) to drive a Kernel cl # Goal -Keep this repository current with the latest Tinker stack and a good default example model, so that someone cloning it gets the latest and greatest. Update everything in scope that is stale in one run, make the compatibility changes needed, verify with targeted and live smoke tests, open or update the evergreen pull request, address BugBot, and merge the pull request after the latest commit is green. +Keep this repository current with the latest Tinker stack and a good default example model, so that someone cloning it gets the latest and greatest. Update everything in scope that is stale in one run, make the compatibility changes needed, verify with targeted and live smoke tests, open or update the evergreen pull request, address BugBot, and hand the pull request to the merge gate once the latest commit is green. # Scope @@ -39,7 +39,7 @@ Out of scope: task data, reward design, hyperparameter tuning beyond defaults th - Never edit `uv.lock` or `core/repl_reference.md` by hand. Regenerate them with `uv` and `scripts/sync_repl_docs.py`. - Never expose secret values in logs, commits, pull request text, or comments. - If `VIRTUAL_ENV` points outside the repository, unset it before running `uv`. -- Do not finish while the pull request is open, BugBot is pending, checks are failing, or an actionable BugBot finding remains. +- Do not finish while BugBot is pending, checks are failing, or an actionable BugBot finding remains. Once the pull request is green, write `ready:` to `${OUTCOME_FILE}` and stop; the workflow merges it. # Step 1: Resume or create the evergreen branch @@ -136,22 +136,16 @@ gh api \ -f body='' ``` -Do not merge while Cursor Bugbot is pending, missing, failing, or has an unanswered actionable finding on the latest commit. Also require all other pull request checks to complete successfully. +Do not write `ready` while Cursor Bugbot is pending, missing, failing, or has an unanswered actionable finding on the latest commit. Also require all other pull request checks to complete successfully. -# Step 7: Merge and prove the outcome +# Step 7: Hand the pull request to the merge gate -When all checks are green and the latest commit has no unresolved actionable BugBot findings, squash-merge with the GitHub App identity: +When all checks are green and the latest commit has no unresolved actionable BugBot findings, write the outcome to the exact absolute path below: ```bash -gh pr merge --squash --admin --delete-branch +printf 'ready:%s\n' '' > "${OUTCOME_FILE}" ``` -The `gh` wrapper rejects `gh pr merge` unless Cursor Bugbot is green for the exact head commit. Do not bypass this gate with `/usr/bin/gh`, another client, or the merge API. +Do not merge the pull request yourself. After you exit, the workflow checks that Cursor Bugbot and every other check passed on the head commit, then squash-merges it. It fails the run if anything is pending or red, or if the head commit changed. -Verify through `gh pr view --json state` that the state is `MERGED`. Only then write the outcome to the exact absolute path below: - -```bash -printf 'merged:%s\n' '' > "${OUTCOME_FILE}" -``` - -Do not create a different outcome file. If the merge is blocked, keep diagnosing within this run. Never write an outcome that claims success, and never exit successfully with an open pull request. +Do not create a different outcome file. If checks are blocked, keep diagnosing within this run. Never write `ready` while BugBot or another check is pending or failing, and never exit successfully with an open pull request and no outcome. diff --git a/.github/workflows/weekly-maintenance.yml b/.github/workflows/weekly-maintenance.yml index 4e074ed..23fab71 100644 --- a/.github/workflows/weekly-maintenance.yml +++ b/.github/workflows/weekly-maintenance.yml @@ -7,254 +7,57 @@ on: workflow_dispatch: permissions: - contents: write - pull-requests: write - checks: read - statuses: read + contents: read concurrency: group: weekly-maintenance cancel-in-progress: false jobs: + # Pi runs in a Docker Sandbox with no GitHub or model credentials inside it; see the reusable + # workflow. update: - runs-on: ubuntu-latest - timeout-minutes: 240 permissions: - contents: write - pull-requests: write + actions: read checks: read + contents: read + pull-requests: read statuses: read id-token: write - env: - POOL_NAME: weekly-maintenance-${{ github.run_id }} + uses: kernel/security-workflows/.github/workflows/sandboxed-agent.yml@main + with: + prompt-file: .github/workflows/weekly-maintenance-prompt.md + prompt-vars: POOL_NAME + # workflows: write lets the agent push the evergreen branch after merging a main that + # changed .github/workflows/. + app-permissions: '{"actions":"write","contents":"write","pull_requests":"write","workflows":"write"}' + merge: true + evergreen-branch: automation/weekly-maintenance + timeout-minutes: 240 + env: | + POOL_NAME=weekly-maintenance-${{ github.run_id }} + setup: | + curl -LsSf https://astral.sh/uv/install.sh | sudo env UV_INSTALL_DIR=/usr/local/bin INSTALLER_NO_MODIFY_PATH=1 sh + sudo npm install -g --silent @onkernel/cli + kernel --version + uv --version + secrets: + ADMIN_APP_ID: ${{ secrets.ADMIN_APP_ID }} + ADMIN_APP_PRIVATE_KEY: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} + DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} + DOCKER_PAT: ${{ secrets.DOCKERHUB_TOKEN }} + AGENT_SECRETS: | + CURSOR_API_KEY=${{ secrets.CURSOR_API_KEY }} + KERNEL_API_KEY=${{ secrets.KERNEL_API_KEY }} + TINKER_API_KEY=${{ secrets.TINKER_API_KEY }} + + delete-pool: + needs: update + if: always() + runs-on: ubuntu-latest steps: - - name: Generate app token - id: app-token - uses: actions/create-github-app-token@v3.3.0 - with: - app-id: ${{ secrets.ADMIN_APP_ID }} - private-key: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} - owner: ${{ github.repository_owner }} - repositories: kernel-tinker-rl - - - name: Checkout repository - uses: actions/checkout@v4.4.0 - with: - fetch-depth: 0 - token: ${{ steps.app-token.outputs.token }} - - - name: Setup Node - uses: actions/setup-node@v4.4.0 - with: - node-version: "22" - - - name: Setup uv - uses: astral-sh/setup-uv@v6.8.0 - - - name: Install Kernel CLI - run: | - npm install -g --ignore-scripts @onkernel/cli - kernel --version - - - name: Install Pi and web access - env: - PI_TELEMETRY: "0" - run: | - npm install -g --ignore-scripts @earendil-works/pi-coding-agent - pi install npm:pi-web-access@latest - pi --version - pi list - - - name: Configure renewable GitHub App authentication - env: - APP_ID: ${{ secrets.ADMIN_APP_ID }} - APP_INSTALLATION_ID: ${{ steps.app-token.outputs.installation-id }} - APP_PRIVATE_KEY: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} - run: | - auth_dir="$RUNNER_TEMP/github-app-auth" - bin_dir="$auth_dir/bin" - mkdir -p "$bin_dir" - chmod 700 "$auth_dir" "$bin_dir" - - private_key_file="$auth_dir/private-key.pem" - token_helper="$auth_dir/github-app-installation-token.mjs" - printf '%s' "$APP_PRIVATE_KEY" > "$private_key_file" - cp "$GITHUB_WORKSPACE/.github/scripts/github-app-installation-token.mjs" "$token_helper" - chmod 600 "$private_key_file" "$token_helper" - - real_gh="$(command -v gh)" - cat > "$bin_dir/gh" <<'EOF' - #!/usr/bin/env bash - set -euo pipefail - token="$(node "$GITHUB_APP_TOKEN_HELPER")" - if [ "${1:-}" = "pr" ] && [ "${2:-}" = "checks" ]; then - exec env GH_TOKEN="$GITHUB_CHECKS_TOKEN" GITHUB_TOKEN="$GITHUB_CHECKS_TOKEN" "$GITHUB_REAL_GH" "$@" - fi - if [ "${1:-}" = "pr" ] && [ "${2:-}" = "merge" ]; then - pr_number="${3:-}" - if [ -z "$pr_number" ] || [[ "$pr_number" = -* ]]; then - echo "A pull request number is required for the BugBot merge gate" >&2 - exit 1 - fi - head_sha="$(env GH_TOKEN="$token" GITHUB_TOKEN="$token" "$GITHUB_REAL_GH" pr view "$pr_number" --json headRefOid --jq .headRefOid)" - check_runs="$(env GH_TOKEN="$GITHUB_CHECKS_TOKEN" GITHUB_TOKEN="$GITHUB_CHECKS_TOKEN" "$GITHUB_REAL_GH" api "repos/$GITHUB_REPOSITORY/commits/$head_sha/check-runs?filter=latest&per_page=100")" - bugbot_conclusion="$(jq -r '[.check_runs[] | select(.name == "Cursor Bugbot" and .status == "completed")] | sort_by(.completed_at) | last | .conclusion // ""' <<<"$check_runs")" - if [ "$bugbot_conclusion" != "success" ]; then - echo "Cursor Bugbot is not green for $head_sha (conclusion: ${bugbot_conclusion:-missing})" >&2 - exit 1 - fi - incomplete_checks="$(jq -r '[.check_runs[] | select(.status != "completed")] | map(.name) | join(", ")' <<<"$check_runs")" - failed_checks="$(jq -r '[.check_runs[] | select(.status == "completed" and (.conclusion | IN("success", "neutral", "skipped") | not))] | map("\(.name)=\(.conclusion)") | join(", ")' <<<"$check_runs")" - if [ -n "$incomplete_checks" ] || [ -n "$failed_checks" ]; then - echo "Pull request checks are not green for $head_sha (incomplete: ${incomplete_checks:-none}; failed: ${failed_checks:-none})" >&2 - exit 1 - fi - commit_status="$(env GH_TOKEN="$GITHUB_CHECKS_TOKEN" GITHUB_TOKEN="$GITHUB_CHECKS_TOKEN" "$GITHUB_REAL_GH" api "repos/$GITHUB_REPOSITORY/commits/$head_sha/status")" - status_count="$(jq -r .total_count <<<"$commit_status")" - status_state="$(jq -r .state <<<"$commit_status")" - if [ "$status_count" -gt 0 ] && [ "$status_state" != "success" ]; then - echo "Commit statuses are not green for $head_sha (state: $status_state)" >&2 - exit 1 - fi - fi - exec env GH_TOKEN="$token" GITHUB_TOKEN="$token" "$GITHUB_REAL_GH" "$@" - EOF - cat > "$bin_dir/git-credential-github-app" <<'EOF' - #!/usr/bin/env bash - set -euo pipefail - [ "${1:-}" = "get" ] || exit 0 - protocol="" - host="" - while IFS='=' read -r key value; do - case "$key" in - protocol) protocol="$value" ;; - host) host="$value" ;; - esac - done - [ "$protocol" = "https" ] && [ "$host" = "github.com" ] || exit 0 - printf 'username=x-access-token\n' - printf 'password=%s\n' "$(node "$GITHUB_APP_TOKEN_HELPER")" - EOF - cat > "$bin_dir/trigger-bugbot" <<'EOF' - #!/usr/bin/env bash - set -euo pipefail - pr_number="${1:-}" - if [ -z "$pr_number" ] || [[ "$pr_number" = -* ]]; then - echo "A pull request number is required" >&2 - exit 1 - fi - pr_url="$(gh pr view "$pr_number" --json url --jq .url)" - response="$(curl --silent --show-error --fail-with-body \ - --request POST \ - --url https://api.cursor.com/bugbot/review \ - --user "$CURSOR_API_KEY:" \ - --header 'Content-Type: application/json' \ - --data "$(jq -cn --arg prUrl "$pr_url" '{prUrl: $prUrl}')")" - jq -e '.outcome == "success"' <<<"$response" >/dev/null - jq -r '"Queued Cursor Bugbot review (request_id: \(.request_id))"' <<<"$response" - EOF - chmod 700 "$bin_dir/gh" "$bin_dir/git-credential-github-app" "$bin_dir/trigger-bugbot" - - git config user.name "kernel-internal[bot]" - git config user.email "260533166+kernel-internal[bot]@users.noreply.github.com" - git config --local --unset-all http.https://github.com/.extraheader || true - git config --local --unset-all credential.helper || true - git config --local --unset-all credential.https://github.com.helper || true - git config --local credential.https://github.com.helper "$bin_dir/git-credential-github-app" - - { - echo "GITHUB_APP_ID=$APP_ID" - echo "GITHUB_APP_INSTALLATION_ID=$APP_INSTALLATION_ID" - echo "GITHUB_APP_PRIVATE_KEY_FILE=$private_key_file" - echo "GITHUB_APP_REPOSITORY=kernel-tinker-rl" - echo "GITHUB_APP_TOKEN_CACHE=$auth_dir/token.json" - echo "GITHUB_APP_TOKEN_HELPER=$token_helper" - echo "GITHUB_REAL_GH=$real_gh" - echo "OUTCOME_FILE=$RUNNER_TEMP/weekly-maintenance.outcome" - } >> "$GITHUB_ENV" - echo "$bin_dir" >> "$GITHUB_PATH" - - - name: Model credentials - uses: kernel/security-workflows/.github/actions/llm-credentials@main - with: - model: ${{ vars.PI_PREFERRED_MODEL }} - anthropic-federation-rule-id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} - anthropic-organization-id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }} - anthropic-service-account-id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }} - openai-identity-provider-id: ${{ vars.OPENAI_IDENTITY_PROVIDER_ID }} - openai-service-account-id: ${{ vars.OPENAI_SERVICE_ACCOUNT_ID }} - openai-audience: ${{ vars.OPENAI_WIF_AUDIENCE }} - # WebJudge calls OpenRouter; it reads the token from OPENROUTER_ACCESS_TOKEN_FILE. - openrouter-federation-policy-id: ${{ vars.OPENROUTER_FEDERATION_POLICY_ID }} - - - name: Run weekly maintenance - env: - CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }} - GITHUB_CHECKS_TOKEN: ${{ github.token }} - GIT_TERMINAL_PROMPT: "0" - KERNEL_API_KEY: ${{ secrets.KERNEL_API_KEY }} - TINKER_API_KEY: ${{ secrets.TINKER_API_KEY }} - PI_PREFERRED_MODEL: ${{ vars.PI_PREFERRED_MODEL }} - PI_SKIP_VERSION_CHECK: "1" - PI_TELEMETRY: "0" - run: | - : "${CURSOR_API_KEY:?Set CURSOR_API_KEY with Cursor admin scope}" - : "${PI_PREFERRED_MODEL:?Set the PI_PREFERRED_MODEL organization variable}" - : "${KERNEL_API_KEY:?Set KERNEL_API_KEY}" - : "${TINKER_API_KEY:?Set TINKER_API_KEY}" - : "${OPENROUTER_ACCESS_TOKEN_FILE:?Set the OPENROUTER_FEDERATION_POLICY_ID organization variable}" - rendered_prompt="$RUNNER_TEMP/weekly-maintenance-prompt.md" - envsubst '${GITHUB_REPOSITORY} ${OUTCOME_FILE} ${POOL_NAME}' \ - < .github/workflows/weekly-maintenance-prompt.md \ - > "$rendered_prompt" - pi --print --no-session --approve \ - --model "$PI_PREFERRED_MODEL" --thinking max \ - @"$rendered_prompt" - - - name: Stop model credentials - if: always() - uses: kernel/security-workflows/.github/actions/llm-credentials@main - with: - stop: true - - - name: Confirm the run produced an outcome - run: | - outcome="$(tr -d '\r\n' < "$OUTCOME_FILE" 2>/dev/null || true)" - case "$outcome" in - no-updates) - open_pr="$(gh pr list --head automation/weekly-maintenance --state open --json number --jq '.[0].number // ""')" - if [ -n "$open_pr" ]; then - echo "::error::Agent reported no updates while PR #$open_pr remains open" - exit 1 - fi - echo "Everything in scope is current." - ;; - merged:*) - pr_number="${outcome#merged:}" - state="$(gh pr view "$pr_number" --json state --jq .state)" - if [ "$state" != "MERGED" ]; then - echo "::error::Agent reported $outcome, but PR #$pr_number is $state" - exit 1 - fi - echo "Merged PR #$pr_number." - ;; - *) - echo "::error::Agent exited without recording no-updates or merged: in $OUTCOME_FILE" - exit 1 - ;; - esac - - name: Delete the smoke-test browser pool - if: always() env: KERNEL_API_KEY: ${{ secrets.KERNEL_API_KEY }} - run: kernel browser-pools delete "$POOL_NAME" --force || true - - - name: Revoke renewable app token - if: always() - run: | - if [ -f "$GITHUB_APP_TOKEN_CACHE" ]; then - gh api --method DELETE /installation/token || true - fi - rm -rf "$RUNNER_TEMP/github-app-auth" + POOL_NAME: weekly-maintenance-${{ github.run_id }} + run: npx --yes @onkernel/cli browser-pools delete "$POOL_NAME" --force || true