From b9278a4c6b9efe454388a0e74fbff4ee418aa556 Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:17:47 +0000 Subject: [PATCH 1/4] Scope admin app tokens to the permissions each use needs --- .github/scripts/github-app-installation-token.mjs | 10 +++++++--- .github/workflows/weekly-maintenance.yml | 2 ++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/scripts/github-app-installation-token.mjs b/.github/scripts/github-app-installation-token.mjs index 01f899f..ed4dc2a 100755 --- a/.github/scripts/github-app-installation-token.mjs +++ b/.github/scripts/github-app-installation-token.mjs @@ -22,9 +22,10 @@ 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; +const permissions = process.env.GITHUB_APP_PERMISSIONS; -if (!appId || !installationId || !privateKeyPath) { - throw new Error("GitHub App ID, installation ID, and private key file are required"); +if (!appId || !installationId || !privateKeyPath || !permissions) { + throw new Error("GitHub App ID, installation ID, private key file, and permissions are required"); } const now = Math.floor(Date.now() / 1000); @@ -49,7 +50,10 @@ const response = await fetch( "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "kernel-tinker-rl-weekly-maintenance", }, - body: repository ? JSON.stringify({ repositories: [repository] }) : undefined, + body: JSON.stringify({ + ...(repository ? { repositories: [repository] } : {}), + permissions: JSON.parse(permissions), + }), }, ); diff --git a/.github/workflows/weekly-maintenance.yml b/.github/workflows/weekly-maintenance.yml index 4e074ed..d991143 100644 --- a/.github/workflows/weekly-maintenance.yml +++ b/.github/workflows/weekly-maintenance.yml @@ -37,6 +37,7 @@ jobs: private-key: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} owner: ${{ github.repository_owner }} repositories: kernel-tinker-rl + permission-contents: read - name: Checkout repository uses: actions/checkout@v4.4.0 @@ -168,6 +169,7 @@ jobs: 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_PERMISSIONS={"actions":"read","contents":"write","pull_requests":"write"}' echo "GITHUB_APP_TOKEN_CACHE=$auth_dir/token.json" echo "GITHUB_APP_TOKEN_HELPER=$token_helper" echo "GITHUB_REAL_GH=$real_gh" From a18b68de6743b560739dfc7e18220184de2f7842 Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:43:42 +0000 Subject: [PATCH 2/4] Run Pi in a container that cannot reach the app private key --- .../scripts/github-app-installation-token.mjs | 77 ------ .github/scripts/github-app-token-broker.mjs | 98 +++++++ .github/scripts/pi-agent-sandbox.sh | 254 ++++++++++++++++++ .../workflows/weekly-maintenance-prompt.md | 2 +- .github/workflows/weekly-maintenance.yml | 154 +++-------- 5 files changed, 384 insertions(+), 201 deletions(-) delete mode 100755 .github/scripts/github-app-installation-token.mjs create mode 100755 .github/scripts/github-app-token-broker.mjs create mode 100755 .github/scripts/pi-agent-sandbox.sh diff --git a/.github/scripts/github-app-installation-token.mjs b/.github/scripts/github-app-installation-token.mjs deleted file mode 100755 index ed4dc2a..0000000 --- a/.github/scripts/github-app-installation-token.mjs +++ /dev/null @@ -1,77 +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; -const permissions = process.env.GITHUB_APP_PERMISSIONS; - -if (!appId || !installationId || !privateKeyPath || !permissions) { - throw new Error("GitHub App ID, installation ID, private key file, and permissions 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: JSON.stringify({ - ...(repository ? { repositories: [repository] } : {}), - permissions: JSON.parse(permissions), - }), - }, -); - -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/scripts/github-app-token-broker.mjs b/.github/scripts/github-app-token-broker.mjs new file mode 100755 index 0000000..9c7d058 --- /dev/null +++ b/.github/scripts/github-app-token-broker.mjs @@ -0,0 +1,98 @@ +#!/usr/bin/env node + +// Serves installation tokens for one repository with fixed permissions, so the GitHub App private +// key stays in this process and never reaches the agent. The key is read from stdin rather than +// the environment, so it does not show up in /proc//environ. + +import { createSign } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { createServer } from "node:http"; + +const rawPrivateKey = readFileSync(0, "utf8"); +const { + GITHUB_APP_ID: appId, + GITHUB_APP_INSTALLATION_ID: installationId, + GITHUB_APP_REPOSITORY: repository, + GITHUB_APP_PERMISSIONS: permissionsJson, + GITHUB_APP_BROKER_HOST: host, + GITHUB_APP_BROKER_PORT: port, +} = process.env; + +if (!appId || !installationId || !rawPrivateKey || !repository || !permissionsJson || !host || !port) { + throw new Error( + "GitHub App ID, installation ID, private key, repository, permissions, and broker address are required", + ); +} + +const privateKey = rawPrivateKey.replaceAll("\\n", "\n"); +const permissions = JSON.parse(permissionsJson); +let cached; +let pending; + +async function mint() { + 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 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": "github-app-token-broker", + }, + body: JSON.stringify({ repositories: [repository], permissions }), + }, + ); + 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"); + } + console.log( + `minted a token for ${repository} expiring ${result.expires_at} with ${JSON.stringify(result.permissions)}`, + ); + return { token: result.token, expiresAt: result.expires_at }; +} + +async function token() { + if (cached && Date.parse(cached.expiresAt) > Date.now() + 5 * 60 * 1000) { + return cached.token; + } + pending ??= mint() + .then((minted) => { + cached = minted; + return minted.token; + }) + .finally(() => { + pending = undefined; + }); + return pending; +} + +createServer(async (request, response) => { + if (request.method !== "GET" || request.url !== "/token") { + response.writeHead(404).end(); + return; + } + try { + response.writeHead(200, { "Content-Type": "text/plain" }).end(await token()); + } catch (error) { + console.error(error.message); + response.writeHead(502).end(); + } +}).listen(Number(port), host, () => { + console.log(`serving ${repository} tokens on ${host}:${port}`); +}); diff --git a/.github/scripts/pi-agent-sandbox.sh b/.github/scripts/pi-agent-sandbox.sh new file mode 100755 index 0000000..909758d --- /dev/null +++ b/.github/scripts/pi-agent-sandbox.sh @@ -0,0 +1,254 @@ +#!/bin/bash +# Runs Pi in a container that cannot reach the GitHub App private key. +# +# pi-agent-sandbox.sh setup start the token broker, install the gh and git wrappers, and +# prepare the agent's home with a copy of the checkout +# pi-agent-sandbox.sh exec CMD... run CMD in the agent container, in its copy of the checkout +# pi-agent-sandbox.sh teardown stop the agent container, revoke the token, and stop the broker +# +# The runner user has passwordless sudo and Docker, and the runner keeps every job secret, the +# private key included, in memory for the whole job. Any process on this VM that gets code run as +# the runner user can therefore reach the key, and much of the hosted image is world-writable, so a +# second Unix user is not enough. The agent runs in a container instead, as the unprivileged +# pi-agent user with no capabilities, no Docker socket and no view of the host's processes. The +# host's /usr, /opt and /etc are mounted read-only so the job's tools work, and the agent's home is +# the only host path it can write. It reaches GitHub through a broker on the Docker bridge that +# keeps the key in memory and serves installation tokens limited to GITHUB_APP_REPOSITORY and +# GITHUB_APP_PERMISSIONS. +# +# setup needs GITHUB_APP_ID, GITHUB_APP_INSTALLATION_ID, GITHUB_APP_PRIVATE_KEY, +# GITHUB_APP_REPOSITORY and GITHUB_APP_PERMISSIONS (a JSON permissions object). exec passes the +# container only the variables named in PI_AGENT_ENV, plus the model credentials that +# kernel/security-workflows' llm-credentials action keeps refreshed, copied into the agent's home. +set -euo pipefail + +agent=pi-agent +agent_home=/home/$agent +agent_credentials=$agent_home/.pi/credentials +image=pi-agent-sandbox +bin_dir=/usr/local/libexec/github-app-auth +state=$RUNNER_TEMP/github-app-broker +port=8377 +script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) + +bridge_ip() { + ip -4 -o addr show docker0 | awk '{ split($4, a, "/"); print a[1] }' +} + +as_agent() { + sudo -u "$agent" env -i HOME="$agent_home" PATH=/usr/bin:/bin "$@" +} + +install_wrappers() { + local token_url=$1 tmp + tmp=$(mktemp -d) + + cat > "$tmp/gh" <<'EOF' +#!/bin/bash +set -euo pipefail +token="$(@CURL@ -fsS "@TOKEN_URL@")" +printf '::add-mask::%s\n' "$token" >&2 +if [ "${1:-}" = "pr" ] && [ "${2:-}" = "checks" ]; then + exec env GH_TOKEN="$GITHUB_CHECKS_TOKEN" GITHUB_TOKEN="$GITHUB_CHECKS_TOKEN" "@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" "@REAL_GH@" pr view "$pr_number" --json headRefOid --jq .headRefOid)" + check_runs="$(env GH_TOKEN="$GITHUB_CHECKS_TOKEN" GITHUB_TOKEN="$GITHUB_CHECKS_TOKEN" "@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" "@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" "@REAL_GH@" "$@" +EOF + + cat > "$tmp/git-credential-github-app" <<'EOF' +#!/bin/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' "$(@CURL@ -fsS "@TOKEN_URL@")" +EOF + + cat > "$tmp/trigger-bugbot" <<'EOF' +#!/bin/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="$(@BIN_DIR@/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 + + sed -i "s|@TOKEN_URL@|$token_url|g; s|@REAL_GH@|$(command -v gh)|g; s|@CURL@|$(command -v curl)|g; s|@JQ@|$(command -v jq)|g; s|@BIN_DIR@|$bin_dir|g" "$tmp"/* + sudo install -d -o root -g root -m 755 "$bin_dir" + sudo install -o root -g root -m 755 "$tmp/gh" "$tmp/git-credential-github-app" "$tmp/trigger-bugbot" "$bin_dir/" + rm -rf "$tmp" +} + +# An image with nothing in it but the merged-/usr symlinks; exec mounts the host's userland. +build_image() { + local root + root=$(mktemp -d) + mkdir -p "$root"/{usr,etc,opt,home,root,proc,sys,dev,run,tmp,var/tmp} + chmod 1777 "$root/tmp" "$root/var/tmp" + ln -s usr/bin "$root/bin" + ln -s usr/sbin "$root/sbin" + ln -s usr/lib "$root/lib" + ln -s usr/lib64 "$root/lib64" + tar -C "$root" -c . | docker import - "$image" >/dev/null + rm -rf "$root" +} + +setup() { + : "${GITHUB_APP_PRIVATE_KEY:?}" "${GITHUB_APP_REPOSITORY:?}" "${GITHUB_APP_PERMISSIONS:?}" + local private_key=$GITHUB_APP_PRIVATE_KEY host token_url + unset GITHUB_APP_PRIVATE_KEY + host=$(bridge_ip) + token_url=http://$host:$port/token + + mkdir -p "$state" + chmod 700 "$state" + printf '%s' "$private_key" | GITHUB_APP_BROKER_HOST=$host GITHUB_APP_BROKER_PORT=$port \ + setsid node "$script_dir/github-app-token-broker.mjs" >>"$state/broker.log" 2>&1 & + echo "$!" > "$state/broker.pid" + unset private_key + for _ in $(seq 1 30); do + curl -fsS -o /dev/null "$token_url" && break + sleep 1 + done + if ! curl -fsS -o /dev/null "$token_url"; then + cat "$state/broker.log" >&2 + echo "::error::The GitHub App token broker did not start" >&2 + exit 1 + fi + cat "$state/broker.log" + + install_wrappers "$token_url" + build_image + + sudo useradd --create-home --shell /bin/bash "$agent" + sudo chmod 700 "$agent_home" + sudo cp -a "$GITHUB_WORKSPACE" "$agent_home/repo" + sudo chown -R "$agent:$agent" "$agent_home/repo" + as_agent mkdir -p "$agent_home/.pi/agent" "$agent_credentials" "$agent_home/.npm-global" + as_agent git -C "$agent_home/repo" config --local --unset-all http.https://github.com/.extraheader || true + as_agent git -C "$agent_home/repo" config --local --unset-all credential.helper || true + as_agent git -C "$agent_home/repo" config --local credential.https://github.com.helper "$bin_dir/git-credential-github-app" + as_agent git -C "$agent_home/repo" config --local user.name "kernel-internal[bot]" + as_agent git -C "$agent_home/repo" config --local user.email "260533166+kernel-internal[bot]@users.noreply.github.com" + + echo "PI_AGENT_HOME=$agent_home" >> "$GITHUB_ENV" + echo "$bin_dir" >> "$GITHUB_PATH" +} + +# The llm-credentials action refreshes model credentials as the runner user, in files only that +# user can read. Copy each one into the agent's home, as the agent, whenever the action replaces it. +declare -A copied=() +copy_credential() { + local source=$1 target=$2 stamp + [ -n "$source" ] && [ -f "$source" ] || return 0 + stamp=$(stat -c '%i %Y %s' "$source") + [ "${copied[$target]:-}" = "$stamp" ] && return 0 + # shellcheck disable=SC2024 # the runner user reads the source; the agent writes the copy + sudo -u "$agent" /bin/sh -c 'cat > "$1.tmp" && mv -f "$1.tmp" "$1"' sh "$target" < "$source" + copied[$target]=$stamp +} + +sync_credentials() { + copy_credential "${ANTHROPIC_IDENTITY_TOKEN_FILE:-}" "$agent_credentials/anthropic-identity-token" + copy_credential "${OPENROUTER_ACCESS_TOKEN_FILE:-}" "$agent_credentials/openrouter-access-token" + copy_credential "${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}/auth.json" "$agent_home/.pi/agent/auth.json" +} + +run_as_agent() { + local args=( + --rm --name "$agent" + --user "$(id -u "$agent"):$(id -g "$agent")" + --cap-drop ALL --security-opt no-new-privileges + --volume /usr:/usr:ro --volume /opt:/opt:ro --volume /etc:/etc:ro + --volume "$agent_home:$agent_home" + --workdir "$agent_home/repo" + --env HOME="$agent_home" --env USER="$agent" --env LOGNAME="$agent" --env SHELL=/bin/bash + --env LANG=C.UTF-8 --env CI=true --env GITHUB_ACTIONS=true + --env GITHUB_REPOSITORY="$GITHUB_REPOSITORY" --env GIT_TERMINAL_PROMPT=0 + --env NPM_CONFIG_PREFIX="$agent_home/.npm-global" + --env PATH="$bin_dir:$agent_home/.npm-global/bin:$agent_home/.local/bin:$PATH" + ) + local name + # Values come from this process's environment rather than the command line. + for name in ${PI_AGENT_ENV:-}; do + args+=(--env "$name") + done + if [ -n "${ANTHROPIC_IDENTITY_TOKEN_FILE:-}" ]; then + args+=( + --env ANTHROPIC_FEDERATION_RULE_ID --env ANTHROPIC_ORGANIZATION_ID + --env ANTHROPIC_SERVICE_ACCOUNT_ID + --env ANTHROPIC_IDENTITY_TOKEN_FILE="$agent_credentials/anthropic-identity-token" + ) + fi + if [ -n "${OPENROUTER_ACCESS_TOKEN_FILE:-}" ]; then + args+=(--env OPENROUTER_ACCESS_TOKEN_FILE="$agent_credentials/openrouter-access-token") + fi + + sync_credentials + (while sleep 2; do sync_credentials || true; done) & + relay=$! + trap 'kill "$relay" 2>/dev/null || true' EXIT + docker run "${args[@]}" "$image" "$@" +} + +teardown() { + docker rm --force "$agent" >/dev/null 2>&1 || true + "$bin_dir/gh" api --method DELETE /installation/token || true + if [ -f "$state/broker.pid" ]; then + kill "$(cat "$state/broker.pid")" 2>/dev/null || true + fi + if [ -f "$state/broker.log" ]; then + cat "$state/broker.log" + fi +} + +case "${1:-}" in + setup) setup ;; + exec) shift; run_as_agent "$@" ;; + teardown) teardown ;; + *) echo "usage: $0 setup | exec CMD... | teardown" >&2; exit 2 ;; +esac diff --git a/.github/workflows/weekly-maintenance-prompt.md b/.github/workflows/weekly-maintenance-prompt.md index 8bc3f50..57a64b6 100644 --- a/.github/workflows/weekly-maintenance-prompt.md +++ b/.github/workflows/weekly-maintenance-prompt.md @@ -1,6 +1,6 @@ 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. +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 run in a container as an unprivileged user, with no sudo or Docker and a read-only view of the runner's tools; install anything else under your home directory. 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. `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. diff --git a/.github/workflows/weekly-maintenance.yml b/.github/workflows/weekly-maintenance.yml index d991143..b103e08 100644 --- a/.github/workflows/weekly-maintenance.yml +++ b/.github/workflows/weekly-maintenance.yml @@ -7,9 +7,10 @@ on: workflow_dispatch: permissions: - contents: write - pull-requests: write + actions: read checks: read + contents: read + pull-requests: read statuses: read concurrency: @@ -20,10 +21,13 @@ jobs: update: runs-on: ubuntu-latest timeout-minutes: 240 + # github.token reaches the agent only as GITHUB_CHECKS_TOKEN, for reading checks and statuses. + # Writes go through the GitHub App token broker. permissions: - contents: write - pull-requests: write + actions: read checks: read + contents: read + pull-requests: read statuses: read id-token: write env: @@ -63,119 +67,24 @@ jobs: 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 + # Pi runs in a container that cannot reach the app private key; it gets scoped + # installation tokens from a broker that holds the key. See the script for details. + - name: Start the agent sandbox env: - APP_ID: ${{ secrets.ADMIN_APP_ID }} - APP_INSTALLATION_ID: ${{ steps.app-token.outputs.installation-id }} - APP_PRIVATE_KEY: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} + GITHUB_APP_ID: ${{ secrets.ADMIN_APP_ID }} + GITHUB_APP_INSTALLATION_ID: ${{ steps.app-token.outputs.installation-id }} + GITHUB_APP_PRIVATE_KEY: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} + GITHUB_APP_REPOSITORY: kernel-tinker-rl + GITHUB_APP_PERMISSIONS: '{"actions":"read","contents":"write","pull_requests":"write"}' + PI_TELEMETRY: "0" + PI_AGENT_ENV: PI_TELEMETRY 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_PERMISSIONS={"actions":"read","contents":"write","pull_requests":"write"}' - 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" + bash .github/scripts/pi-agent-sandbox.sh setup + bash .github/scripts/pi-agent-sandbox.sh exec pi install npm:pi-web-access@latest + bash .github/scripts/pi-agent-sandbox.sh exec pi list + echo "OUTCOME_FILE=$PI_AGENT_HOME/weekly-maintenance.outcome" >> "$GITHUB_ENV" - name: Model credentials uses: kernel/security-workflows/.github/actions/llm-credentials@main @@ -200,17 +109,20 @@ jobs: PI_PREFERRED_MODEL: ${{ vars.PI_PREFERRED_MODEL }} PI_SKIP_VERSION_CHECK: "1" PI_TELEMETRY: "0" + PI_AGENT_ENV: >- + CURSOR_API_KEY GITHUB_CHECKS_TOKEN KERNEL_API_KEY TINKER_API_KEY OUTCOME_FILE POOL_NAME + PI_PREFERRED_MODEL PI_SKIP_VERSION_CHECK PI_TELEMETRY 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" + rendered_prompt="$PI_AGENT_HOME/weekly-maintenance-prompt.md" envsubst '${GITHUB_REPOSITORY} ${OUTCOME_FILE} ${POOL_NAME}' \ < .github/workflows/weekly-maintenance-prompt.md \ - > "$rendered_prompt" - pi --print --no-session --approve \ + | sudo -u pi-agent tee "$rendered_prompt" >/dev/null + bash .github/scripts/pi-agent-sandbox.sh exec pi --print --no-session --approve \ --model "$PI_PREFERRED_MODEL" --thinking max \ @"$rendered_prompt" @@ -222,7 +134,7 @@ jobs: - name: Confirm the run produced an outcome run: | - outcome="$(tr -d '\r\n' < "$OUTCOME_FILE" 2>/dev/null || true)" + outcome="$(sudo -u pi-agent cat "$OUTCOME_FILE" 2>/dev/null | tr -d '\r\n' || true)" case "$outcome" in no-updates) open_pr="$(gh pr list --head automation/weekly-maintenance --state open --json number --jq '.[0].number // ""')" @@ -253,10 +165,6 @@ jobs: KERNEL_API_KEY: ${{ secrets.KERNEL_API_KEY }} run: kernel browser-pools delete "$POOL_NAME" --force || true - - name: Revoke renewable app token + - name: Stop the agent sandbox 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" + run: bash .github/scripts/pi-agent-sandbox.sh teardown From cf28f74e47d7cf08dbd11c852c7cce066642db85 Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:21:44 +0000 Subject: [PATCH 3/4] Run the agent through the shared sandboxed-agent workflow --- .github/scripts/github-app-token-broker.mjs | 98 ------- .github/scripts/pi-agent-sandbox.sh | 254 ------------------ .github/workflows/actions.lock | 33 +-- .../workflows/weekly-maintenance-prompt.md | 24 +- .github/workflows/weekly-maintenance.yml | 177 +++--------- 5 files changed, 45 insertions(+), 541 deletions(-) delete mode 100755 .github/scripts/github-app-token-broker.mjs delete mode 100755 .github/scripts/pi-agent-sandbox.sh diff --git a/.github/scripts/github-app-token-broker.mjs b/.github/scripts/github-app-token-broker.mjs deleted file mode 100755 index 9c7d058..0000000 --- a/.github/scripts/github-app-token-broker.mjs +++ /dev/null @@ -1,98 +0,0 @@ -#!/usr/bin/env node - -// Serves installation tokens for one repository with fixed permissions, so the GitHub App private -// key stays in this process and never reaches the agent. The key is read from stdin rather than -// the environment, so it does not show up in /proc//environ. - -import { createSign } from "node:crypto"; -import { readFileSync } from "node:fs"; -import { createServer } from "node:http"; - -const rawPrivateKey = readFileSync(0, "utf8"); -const { - GITHUB_APP_ID: appId, - GITHUB_APP_INSTALLATION_ID: installationId, - GITHUB_APP_REPOSITORY: repository, - GITHUB_APP_PERMISSIONS: permissionsJson, - GITHUB_APP_BROKER_HOST: host, - GITHUB_APP_BROKER_PORT: port, -} = process.env; - -if (!appId || !installationId || !rawPrivateKey || !repository || !permissionsJson || !host || !port) { - throw new Error( - "GitHub App ID, installation ID, private key, repository, permissions, and broker address are required", - ); -} - -const privateKey = rawPrivateKey.replaceAll("\\n", "\n"); -const permissions = JSON.parse(permissionsJson); -let cached; -let pending; - -async function mint() { - 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 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": "github-app-token-broker", - }, - body: JSON.stringify({ repositories: [repository], permissions }), - }, - ); - 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"); - } - console.log( - `minted a token for ${repository} expiring ${result.expires_at} with ${JSON.stringify(result.permissions)}`, - ); - return { token: result.token, expiresAt: result.expires_at }; -} - -async function token() { - if (cached && Date.parse(cached.expiresAt) > Date.now() + 5 * 60 * 1000) { - return cached.token; - } - pending ??= mint() - .then((minted) => { - cached = minted; - return minted.token; - }) - .finally(() => { - pending = undefined; - }); - return pending; -} - -createServer(async (request, response) => { - if (request.method !== "GET" || request.url !== "/token") { - response.writeHead(404).end(); - return; - } - try { - response.writeHead(200, { "Content-Type": "text/plain" }).end(await token()); - } catch (error) { - console.error(error.message); - response.writeHead(502).end(); - } -}).listen(Number(port), host, () => { - console.log(`serving ${repository} tokens on ${host}:${port}`); -}); diff --git a/.github/scripts/pi-agent-sandbox.sh b/.github/scripts/pi-agent-sandbox.sh deleted file mode 100755 index 909758d..0000000 --- a/.github/scripts/pi-agent-sandbox.sh +++ /dev/null @@ -1,254 +0,0 @@ -#!/bin/bash -# Runs Pi in a container that cannot reach the GitHub App private key. -# -# pi-agent-sandbox.sh setup start the token broker, install the gh and git wrappers, and -# prepare the agent's home with a copy of the checkout -# pi-agent-sandbox.sh exec CMD... run CMD in the agent container, in its copy of the checkout -# pi-agent-sandbox.sh teardown stop the agent container, revoke the token, and stop the broker -# -# The runner user has passwordless sudo and Docker, and the runner keeps every job secret, the -# private key included, in memory for the whole job. Any process on this VM that gets code run as -# the runner user can therefore reach the key, and much of the hosted image is world-writable, so a -# second Unix user is not enough. The agent runs in a container instead, as the unprivileged -# pi-agent user with no capabilities, no Docker socket and no view of the host's processes. The -# host's /usr, /opt and /etc are mounted read-only so the job's tools work, and the agent's home is -# the only host path it can write. It reaches GitHub through a broker on the Docker bridge that -# keeps the key in memory and serves installation tokens limited to GITHUB_APP_REPOSITORY and -# GITHUB_APP_PERMISSIONS. -# -# setup needs GITHUB_APP_ID, GITHUB_APP_INSTALLATION_ID, GITHUB_APP_PRIVATE_KEY, -# GITHUB_APP_REPOSITORY and GITHUB_APP_PERMISSIONS (a JSON permissions object). exec passes the -# container only the variables named in PI_AGENT_ENV, plus the model credentials that -# kernel/security-workflows' llm-credentials action keeps refreshed, copied into the agent's home. -set -euo pipefail - -agent=pi-agent -agent_home=/home/$agent -agent_credentials=$agent_home/.pi/credentials -image=pi-agent-sandbox -bin_dir=/usr/local/libexec/github-app-auth -state=$RUNNER_TEMP/github-app-broker -port=8377 -script_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) - -bridge_ip() { - ip -4 -o addr show docker0 | awk '{ split($4, a, "/"); print a[1] }' -} - -as_agent() { - sudo -u "$agent" env -i HOME="$agent_home" PATH=/usr/bin:/bin "$@" -} - -install_wrappers() { - local token_url=$1 tmp - tmp=$(mktemp -d) - - cat > "$tmp/gh" <<'EOF' -#!/bin/bash -set -euo pipefail -token="$(@CURL@ -fsS "@TOKEN_URL@")" -printf '::add-mask::%s\n' "$token" >&2 -if [ "${1:-}" = "pr" ] && [ "${2:-}" = "checks" ]; then - exec env GH_TOKEN="$GITHUB_CHECKS_TOKEN" GITHUB_TOKEN="$GITHUB_CHECKS_TOKEN" "@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" "@REAL_GH@" pr view "$pr_number" --json headRefOid --jq .headRefOid)" - check_runs="$(env GH_TOKEN="$GITHUB_CHECKS_TOKEN" GITHUB_TOKEN="$GITHUB_CHECKS_TOKEN" "@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" "@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" "@REAL_GH@" "$@" -EOF - - cat > "$tmp/git-credential-github-app" <<'EOF' -#!/bin/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' "$(@CURL@ -fsS "@TOKEN_URL@")" -EOF - - cat > "$tmp/trigger-bugbot" <<'EOF' -#!/bin/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="$(@BIN_DIR@/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 - - sed -i "s|@TOKEN_URL@|$token_url|g; s|@REAL_GH@|$(command -v gh)|g; s|@CURL@|$(command -v curl)|g; s|@JQ@|$(command -v jq)|g; s|@BIN_DIR@|$bin_dir|g" "$tmp"/* - sudo install -d -o root -g root -m 755 "$bin_dir" - sudo install -o root -g root -m 755 "$tmp/gh" "$tmp/git-credential-github-app" "$tmp/trigger-bugbot" "$bin_dir/" - rm -rf "$tmp" -} - -# An image with nothing in it but the merged-/usr symlinks; exec mounts the host's userland. -build_image() { - local root - root=$(mktemp -d) - mkdir -p "$root"/{usr,etc,opt,home,root,proc,sys,dev,run,tmp,var/tmp} - chmod 1777 "$root/tmp" "$root/var/tmp" - ln -s usr/bin "$root/bin" - ln -s usr/sbin "$root/sbin" - ln -s usr/lib "$root/lib" - ln -s usr/lib64 "$root/lib64" - tar -C "$root" -c . | docker import - "$image" >/dev/null - rm -rf "$root" -} - -setup() { - : "${GITHUB_APP_PRIVATE_KEY:?}" "${GITHUB_APP_REPOSITORY:?}" "${GITHUB_APP_PERMISSIONS:?}" - local private_key=$GITHUB_APP_PRIVATE_KEY host token_url - unset GITHUB_APP_PRIVATE_KEY - host=$(bridge_ip) - token_url=http://$host:$port/token - - mkdir -p "$state" - chmod 700 "$state" - printf '%s' "$private_key" | GITHUB_APP_BROKER_HOST=$host GITHUB_APP_BROKER_PORT=$port \ - setsid node "$script_dir/github-app-token-broker.mjs" >>"$state/broker.log" 2>&1 & - echo "$!" > "$state/broker.pid" - unset private_key - for _ in $(seq 1 30); do - curl -fsS -o /dev/null "$token_url" && break - sleep 1 - done - if ! curl -fsS -o /dev/null "$token_url"; then - cat "$state/broker.log" >&2 - echo "::error::The GitHub App token broker did not start" >&2 - exit 1 - fi - cat "$state/broker.log" - - install_wrappers "$token_url" - build_image - - sudo useradd --create-home --shell /bin/bash "$agent" - sudo chmod 700 "$agent_home" - sudo cp -a "$GITHUB_WORKSPACE" "$agent_home/repo" - sudo chown -R "$agent:$agent" "$agent_home/repo" - as_agent mkdir -p "$agent_home/.pi/agent" "$agent_credentials" "$agent_home/.npm-global" - as_agent git -C "$agent_home/repo" config --local --unset-all http.https://github.com/.extraheader || true - as_agent git -C "$agent_home/repo" config --local --unset-all credential.helper || true - as_agent git -C "$agent_home/repo" config --local credential.https://github.com.helper "$bin_dir/git-credential-github-app" - as_agent git -C "$agent_home/repo" config --local user.name "kernel-internal[bot]" - as_agent git -C "$agent_home/repo" config --local user.email "260533166+kernel-internal[bot]@users.noreply.github.com" - - echo "PI_AGENT_HOME=$agent_home" >> "$GITHUB_ENV" - echo "$bin_dir" >> "$GITHUB_PATH" -} - -# The llm-credentials action refreshes model credentials as the runner user, in files only that -# user can read. Copy each one into the agent's home, as the agent, whenever the action replaces it. -declare -A copied=() -copy_credential() { - local source=$1 target=$2 stamp - [ -n "$source" ] && [ -f "$source" ] || return 0 - stamp=$(stat -c '%i %Y %s' "$source") - [ "${copied[$target]:-}" = "$stamp" ] && return 0 - # shellcheck disable=SC2024 # the runner user reads the source; the agent writes the copy - sudo -u "$agent" /bin/sh -c 'cat > "$1.tmp" && mv -f "$1.tmp" "$1"' sh "$target" < "$source" - copied[$target]=$stamp -} - -sync_credentials() { - copy_credential "${ANTHROPIC_IDENTITY_TOKEN_FILE:-}" "$agent_credentials/anthropic-identity-token" - copy_credential "${OPENROUTER_ACCESS_TOKEN_FILE:-}" "$agent_credentials/openrouter-access-token" - copy_credential "${PI_CODING_AGENT_DIR:-$HOME/.pi/agent}/auth.json" "$agent_home/.pi/agent/auth.json" -} - -run_as_agent() { - local args=( - --rm --name "$agent" - --user "$(id -u "$agent"):$(id -g "$agent")" - --cap-drop ALL --security-opt no-new-privileges - --volume /usr:/usr:ro --volume /opt:/opt:ro --volume /etc:/etc:ro - --volume "$agent_home:$agent_home" - --workdir "$agent_home/repo" - --env HOME="$agent_home" --env USER="$agent" --env LOGNAME="$agent" --env SHELL=/bin/bash - --env LANG=C.UTF-8 --env CI=true --env GITHUB_ACTIONS=true - --env GITHUB_REPOSITORY="$GITHUB_REPOSITORY" --env GIT_TERMINAL_PROMPT=0 - --env NPM_CONFIG_PREFIX="$agent_home/.npm-global" - --env PATH="$bin_dir:$agent_home/.npm-global/bin:$agent_home/.local/bin:$PATH" - ) - local name - # Values come from this process's environment rather than the command line. - for name in ${PI_AGENT_ENV:-}; do - args+=(--env "$name") - done - if [ -n "${ANTHROPIC_IDENTITY_TOKEN_FILE:-}" ]; then - args+=( - --env ANTHROPIC_FEDERATION_RULE_ID --env ANTHROPIC_ORGANIZATION_ID - --env ANTHROPIC_SERVICE_ACCOUNT_ID - --env ANTHROPIC_IDENTITY_TOKEN_FILE="$agent_credentials/anthropic-identity-token" - ) - fi - if [ -n "${OPENROUTER_ACCESS_TOKEN_FILE:-}" ]; then - args+=(--env OPENROUTER_ACCESS_TOKEN_FILE="$agent_credentials/openrouter-access-token") - fi - - sync_credentials - (while sleep 2; do sync_credentials || true; done) & - relay=$! - trap 'kill "$relay" 2>/dev/null || true' EXIT - docker run "${args[@]}" "$image" "$@" -} - -teardown() { - docker rm --force "$agent" >/dev/null 2>&1 || true - "$bin_dir/gh" api --method DELETE /installation/token || true - if [ -f "$state/broker.pid" ]; then - kill "$(cat "$state/broker.pid")" 2>/dev/null || true - fi - if [ -f "$state/broker.log" ]; then - cat "$state/broker.log" - fi -} - -case "${1:-}" in - setup) setup ;; - exec) shift; run_as_agent "$@" ;; - teardown) teardown ;; - *) echo "usage: $0 setup | exec CMD... | teardown" >&2; exit 2 ;; -esac 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 57a64b6..b4418ea 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 run in a container as an unprivileged user, with no sudo or Docker and a read-only view of the runner's tools; install anything else under your home directory. 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 @@ -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 b103e08..23fab71 100644 --- a/.github/workflows/weekly-maintenance.yml +++ b/.github/workflows/weekly-maintenance.yml @@ -7,22 +7,16 @@ on: workflow_dispatch: permissions: - actions: read - checks: read contents: read - pull-requests: read - statuses: 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 - # github.token reaches the agent only as GITHUB_CHECKS_TOKEN, for reading checks and statuses. - # Writes go through the GitHub App token broker. permissions: actions: read checks: read @@ -30,141 +24,40 @@ jobs: 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 - permission-contents: read - - - 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 --version - - # Pi runs in a container that cannot reach the app private key; it gets scoped - # installation tokens from a broker that holds the key. See the script for details. - - name: Start the agent sandbox - env: - GITHUB_APP_ID: ${{ secrets.ADMIN_APP_ID }} - GITHUB_APP_INSTALLATION_ID: ${{ steps.app-token.outputs.installation-id }} - GITHUB_APP_PRIVATE_KEY: ${{ secrets.ADMIN_APP_PRIVATE_KEY }} - GITHUB_APP_REPOSITORY: kernel-tinker-rl - GITHUB_APP_PERMISSIONS: '{"actions":"read","contents":"write","pull_requests":"write"}' - PI_TELEMETRY: "0" - PI_AGENT_ENV: PI_TELEMETRY - run: | - bash .github/scripts/pi-agent-sandbox.sh setup - bash .github/scripts/pi-agent-sandbox.sh exec pi install npm:pi-web-access@latest - bash .github/scripts/pi-agent-sandbox.sh exec pi list - echo "OUTCOME_FILE=$PI_AGENT_HOME/weekly-maintenance.outcome" >> "$GITHUB_ENV" - - - 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" - PI_AGENT_ENV: >- - CURSOR_API_KEY GITHUB_CHECKS_TOKEN KERNEL_API_KEY TINKER_API_KEY OUTCOME_FILE POOL_NAME - PI_PREFERRED_MODEL PI_SKIP_VERSION_CHECK PI_TELEMETRY - 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="$PI_AGENT_HOME/weekly-maintenance-prompt.md" - envsubst '${GITHUB_REPOSITORY} ${OUTCOME_FILE} ${POOL_NAME}' \ - < .github/workflows/weekly-maintenance-prompt.md \ - | sudo -u pi-agent tee "$rendered_prompt" >/dev/null - bash .github/scripts/pi-agent-sandbox.sh exec 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="$(sudo -u pi-agent cat "$OUTCOME_FILE" 2>/dev/null | tr -d '\r\n' || 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: Stop the agent sandbox - if: always() - run: bash .github/scripts/pi-agent-sandbox.sh teardown + POOL_NAME: weekly-maintenance-${{ github.run_id }} + run: npx --yes @onkernel/cli browser-pools delete "$POOL_NAME" --force || true From e79880a4c6cb705dc00e25e8ce9af488a6dda982 Mon Sep 17 00:00:00 2001 From: rgarcia <72655+rgarcia@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:32:13 +0000 Subject: [PATCH 4/4] Let the agent stop at a green pull request in the prompt rules --- .github/workflows/weekly-maintenance-prompt.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/weekly-maintenance-prompt.md b/.github/workflows/weekly-maintenance-prompt.md index b4418ea..0e1ad6b 100644 --- a/.github/workflows/weekly-maintenance-prompt.md +++ b/.github/workflows/weekly-maintenance-prompt.md @@ -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