diff --git a/.github/actions/check-e2e-authorization/action.yml b/.github/actions/check-e2e-authorization/action.yml index fdcc1fc6fc..d0398855c5 100644 --- a/.github/actions/check-e2e-authorization/action.yml +++ b/.github/actions/check-e2e-authorization/action.yml @@ -65,6 +65,11 @@ outputs: PR head sha a /ok-to-test comment authorized or refused (empty for an untrusted commenter and in other modes) value: ${{ steps.check.outputs.head_sha }} + live: + description: >- + true when an authorized comment was `/ok-to-test live`, asking for + the live behaviour and playback suites as well + value: ${{ steps.check.outputs.live }} runs: using: composite @@ -119,7 +124,7 @@ runs: " ;; issue_comment:missing_sha) - body+="\`/ok-to-test\` must name the commit you reviewed, as its full 40-character sha: \`/ok-to-test \`. The PR head is now \`${HEAD_SHA}\`; if that is not the commit you reviewed, review it first. A later push needs a new comment. + body+="\`/ok-to-test\` must name the commit you reviewed, as its full 40-character sha: \`/ok-to-test \`, or \`/ok-to-test live\` to run the live suites too. The PR head is now \`${HEAD_SHA}\`; if that is not the commit you reviewed, review it first. A later push needs a new comment. " ;; issue_comment:untrusted_commenter) diff --git a/.github/actions/install-fullsend-cli/action.yml b/.github/actions/install-fullsend-cli/action.yml index 1ea0d689d1..f02c0253ba 100644 --- a/.github/actions/install-fullsend-cli/action.yml +++ b/.github/actions/install-fullsend-cli/action.yml @@ -19,6 +19,15 @@ inputs: github_token: description: Token for cloning the workflow repository. default: ${{ github.token }} + install_dir: + description: Directory where the fullsend binary is installed. + default: ${{ runner.temp }}/fullsend + add_to_path: + description: Add the install directory to PATH for subsequent steps. + default: 'true' + source_dir: + description: Directory used for an upstream source checkout and build. + default: ${{ runner.temp }}/fullsend-src outputs: fullsend-path: @@ -28,23 +37,43 @@ outputs: runs: using: composite steps: + - name: Validate install inputs + shell: bash + env: + INSTALL_DIR: ${{ inputs.install_dir }} + ADD_TO_PATH: ${{ inputs.add_to_path }} + run: | + set -euo pipefail + if [[ "${ADD_TO_PATH}" != "true" && "${ADD_TO_PATH}" != "false" ]]; then + echo "add_to_path must be true or false" >&2 + exit 1 + fi + if [[ "${INSTALL_DIR}" == *$'\n'* || "${INSTALL_DIR}" == *$'\r'* ]]; then + echo "install_dir must not contain newlines" >&2 + exit 1 + fi + - name: Install vendored binary id: install-vendored if: inputs.mode == 'vendored' shell: bash env: VENDORED: ${{ inputs.vendored_path }} + INSTALL_DIR: ${{ inputs.install_dir }} + ADD_TO_PATH: ${{ inputs.add_to_path }} run: | set -euo pipefail if [[ ! -f "${VENDORED}" ]]; then echo "vendored binary not found" >&2 exit 1 fi - mkdir -p "${RUNNER_TEMP}/fullsend" - cp "${VENDORED}" "${RUNNER_TEMP}/fullsend/fullsend" - chmod +x "${RUNNER_TEMP}/fullsend/fullsend" - echo "${RUNNER_TEMP}/fullsend" >> "${GITHUB_PATH}" - echo "fullsend-path=${RUNNER_TEMP}/fullsend/fullsend" >> "${GITHUB_OUTPUT}" + mkdir -p "${INSTALL_DIR}" + cp "${VENDORED}" "${INSTALL_DIR}/fullsend" + chmod +x "${INSTALL_DIR}/fullsend" + if [[ "${ADD_TO_PATH}" == "true" ]]; then + echo "${INSTALL_DIR}" >> "${GITHUB_PATH}" + fi + echo "fullsend-path=${INSTALL_DIR}/fullsend" >> "${GITHUB_OUTPUT}" - name: Resolve SHA to release tag id: resolve-tag @@ -126,6 +155,8 @@ runs: GH_TOKEN: ${{ inputs.github_token }} RUNNER_OS: ${{ runner.os }} RUNNER_ARCH: ${{ runner.arch }} + INSTALL_DIR: ${{ inputs.install_dir }} + ADD_TO_PATH: ${{ inputs.add_to_path }} run: | set -euo pipefail retry() { @@ -155,14 +186,16 @@ runs: esac ASSET="fullsend_${VERSION}_${os}_${arch}.tar.gz" - mkdir -p "${RUNNER_TEMP}/fullsend" + mkdir -p "${INSTALL_DIR}" echo "Downloading ${ASSET} from release ${TAG}" - retry gh release download "${TAG}" -R "${WORKFLOW_REPOSITORY}" -p "${ASSET}" -D "${RUNNER_TEMP}/fullsend" --clobber - tar -xzf "${RUNNER_TEMP}/fullsend/${ASSET}" -C "${RUNNER_TEMP}/fullsend" - rm -f "${RUNNER_TEMP}/fullsend/${ASSET}" - chmod +x "${RUNNER_TEMP}/fullsend/fullsend" - echo "${RUNNER_TEMP}/fullsend" >> "${GITHUB_PATH}" - echo "fullsend-path=${RUNNER_TEMP}/fullsend/fullsend" >> "${GITHUB_OUTPUT}" + retry gh release download "${TAG}" -R "${WORKFLOW_REPOSITORY}" -p "${ASSET}" -D "${INSTALL_DIR}" --clobber + tar -xzf "${INSTALL_DIR}/${ASSET}" -C "${INSTALL_DIR}" + rm -f "${INSTALL_DIR}/${ASSET}" + chmod +x "${INSTALL_DIR}/fullsend" + if [[ "${ADD_TO_PATH}" == "true" ]]; then + echo "${INSTALL_DIR}" >> "${GITHUB_PATH}" + fi + echo "fullsend-path=${INSTALL_DIR}/fullsend" >> "${GITHUB_OUTPUT}" - name: Clone fullsend at workflow SHA for source build if: inputs.mode == 'upstream' && (steps.resolve-tag.outputs.tag == '' || steps.install-release.outcome == 'failure') @@ -172,13 +205,14 @@ runs: WORKFLOW_SHA: ${{ inputs.workflow_sha }} GH_TOKEN: ${{ inputs.github_token }} INSTALL_RELEASE_OUTCOME: ${{ steps.install-release.outcome }} + SOURCE_DIR: ${{ inputs.source_dir }} run: | set -euo pipefail if [[ "${INSTALL_RELEASE_OUTCOME}" == "failure" ]]; then echo "::warning::Release download failed; falling back to source build" fi echo "::add-mask::${GH_TOKEN}" - SRC="${RUNNER_TEMP}/fullsend-src" + SRC="${SOURCE_DIR}" REMOTE="https://x-access-token:${GH_TOKEN}@github.com/${WORKFLOW_REPOSITORY}.git" echo "Cloning ${WORKFLOW_REPOSITORY} at ref: ${WORKFLOW_SHA}" git init "${SRC}" @@ -196,22 +230,32 @@ runs: if: inputs.mode == 'upstream' && (steps.resolve-tag.outputs.tag == '' || steps.install-release.outcome == 'failure') uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 with: - go-version-file: ${{ runner.temp }}/fullsend-src/go.mod - cache-dependency-path: ${{ runner.temp }}/fullsend-src/go.sum + go-version-file: ${{ inputs.source_dir }}/go.mod + cache-dependency-path: ${{ inputs.source_dir }}/go.sum - name: Build fullsend from source id: install-upstream if: inputs.mode == 'upstream' && (steps.resolve-tag.outputs.tag == '' || steps.install-release.outcome == 'failure') shell: bash + env: + INSTALL_DIR: ${{ inputs.install_dir }} + ADD_TO_PATH: ${{ inputs.add_to_path }} + SOURCE_DIR: ${{ inputs.source_dir }} run: | set -euo pipefail - mkdir -p "${RUNNER_TEMP}/fullsend" - cd "${RUNNER_TEMP}/fullsend-src" + mkdir -p "${INSTALL_DIR}" + cd "${SOURCE_DIR}" make go-build - cp bin/fullsend "${RUNNER_TEMP}/fullsend/fullsend" - echo "${RUNNER_TEMP}/fullsend" >> "${GITHUB_PATH}" - echo "fullsend-path=${RUNNER_TEMP}/fullsend/fullsend" >> "${GITHUB_OUTPUT}" + cp bin/fullsend "${INSTALL_DIR}/fullsend" + chmod +x "${INSTALL_DIR}/fullsend" + if [[ "${ADD_TO_PATH}" == "true" ]]; then + echo "${INSTALL_DIR}" >> "${GITHUB_PATH}" + fi + echo "fullsend-path=${INSTALL_DIR}/fullsend" >> "${GITHUB_OUTPUT}" - name: Print fullsend version shell: bash - run: fullsend --version + env: + INSTALL_DIR: ${{ inputs.install_dir }} + run: | + "${INSTALL_DIR}/fullsend" --version diff --git a/.github/safe-settings/deployment-settings.yml b/.github/safe-settings/deployment-settings.yml new file mode 100644 index 0000000000..8b35f4a91b --- /dev/null +++ b/.github/safe-settings/deployment-settings.yml @@ -0,0 +1,6 @@ +# Safe-settings deployment config for this repo's own run. The include list +# restricts the sync to this repository only, so it never touches sibling +# repos that the org repo's safe-settings run manages. +restrictedRepos: + include: + - fullsend diff --git a/.github/safe-settings/settings.yml b/.github/safe-settings/settings.yml new file mode 100644 index 0000000000..41ff6b7cca --- /dev/null +++ b/.github/safe-settings/settings.yml @@ -0,0 +1,34 @@ +# Environments for this repo, managed by safe-settings full-sync. This run +# is scoped to this repository only (see deployment-settings.yml); everything +# else -- rulesets, repository settings -- stays managed by the org repo's +# safe-settings run (github.com/fullsend-ai/org). +# Environments are total-state: unlisted ones are deleted on apply. The +# same goes for per-environment variables, reviewers, wait timers, and +# protection rules -- anything added later through the GitHub UI is removed +# by the next run. Edit this file, not the UI. +environments: + - name: dev + - name: e2e-org-pool + # safe-settings cannot manage environment secrets; these three live only on + # GitHub (write-only via the API): TEST_ACTOR_TRIAGE_PAT, + # TEST_ACTOR_WRITE_PAT, TEST_BOTSEND_PAT. + deployment_branch_policy: + protected_branches: false + custom_branch_policies: + - main + - name: evals + - name: forgejo-dev + - name: forgejo-stage + - name: functional-tests + - name: github-pages + deployment_branch_policy: + protected_branches: false + custom_branch_policies: + - main + - name: site-preview + - name: site-production + - name: stage + deployment_branch_policy: + protected_branches: false + custom_branch_policies: + - main diff --git a/.github/scripts/review-diff-hash-test.sh b/.github/scripts/review-diff-hash-test.sh deleted file mode 100755 index 8815fc6a19..0000000000 --- a/.github/scripts/review-diff-hash-test.sh +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env bash -# review-diff-hash-test.sh — canonicalizer and workflow-contract tests. -# -# The workflow-side guard is intentionally fail-open: only a complete diff, -# an approved review at the recorded head, and a stable PR snapshot may skip. -# Keep these cases close to the workflow so changes to the routing contract -# are visible in `make script-test`. - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -SCRIPT="${SCRIPT_DIR}/review-diff-hash.sh" -WORKFLOW="${SCRIPT_DIR}/../workflows/reusable-dispatch.yml" -TMPDIR="$(mktemp -d)" -trap 'rm -rf "${TMPDIR}"' EXIT - -fail() { echo "FAIL: $*" >&2; exit 1; } -contains() { grep -Fq -- "$2" "$1" || fail "${1} does not contain ${2}"; } - -contains "${WORKFLOW}" 'name: Check unchanged review diff' -contains "${WORKFLOW}" 'if [[ "${prior_state}" != "APPROVED"' -contains "${WORKFLOW}" '"${base_before}" != "${base_after}"' -contains "${WORKFLOW}" '"${head_before}" != "${head_after}"' -contains "${WORKFLOW}" 'No app-verified previous review found; running review' -contains "${WORKFLOW}" 'defaults_root: .fullsend/.defaults' -contains "${WORKFLOW}" 'ln -s .fullsend/.defaults .defaults' -contains "${WORKFLOW}" 'Fullsend'"'"'s earlier unchanged-diff skip note was superseded' - -# This is the workflow guard's decision contract. Keep the cases explicit so -# a refactor cannot accidentally turn a missing or stale approval into a skip. -dedup_decision() { - local current_hash="$1" prior_hash="$2" state="$3" reviewed_head="$4" - local current_head="$5" before_head="$6" after_head="$7" - if [[ -z "${current_hash}" || "${current_hash}" != "${prior_hash}" ]]; then - echo run - elif [[ "${state}" != APPROVED || "${reviewed_head}" != "${before_head}" ]]; then - echo run - elif [[ "${before_head}" != "${after_head}" || "${after_head}" != "${current_head}" ]]; then - echo run - else - echo skip - fi -} - -[[ "$(dedup_decision hash hash APPROVED head head head head)" == skip ]] || fail "approved unchanged diff must skip" -[[ "$(dedup_decision '' hash APPROVED head head head head)" == run ]] || fail "missing hash must run" -[[ "$(dedup_decision hash hash COMMENTED head head head head)" == run ]] || fail "non-approving review must run" -[[ "$(dedup_decision hash hash DISMISSED head head head head)" == run ]] || fail "dismissed approval must run" -[[ "$(dedup_decision hash hash APPROVED head new-head head head)" == run ]] || fail "changed head must run" -[[ "$(dedup_decision hash hash APPROVED head head head new-head)" == run ]] || fail "head changed during fetch must run" - -cat >"${TMPDIR}/base.json" <<'EOF' -{"file.txt":"100644"} -EOF -cat >"${TMPDIR}/head.json" <<'EOF' -{"file.txt":"100644"} -EOF -cat >"${TMPDIR}/same.json" <<'EOF' -{"filename":"file.txt","previous_filename":"","status":"modified","patch":"@@ -1 +1 @@\n-a\n+b"} -EOF - -same_hash="$("${SCRIPT}" "${TMPDIR}/base.json" "${TMPDIR}/head.json" <"${TMPDIR}/same.json")" -[[ "${same_hash}" =~ ^[0-9a-f]{64}$ ]] || fail "complete diff did not produce a SHA-256 hash" - -empty_hash="$(printf '' | "${SCRIPT}" "${TMPDIR}/base.json" "${TMPDIR}/head.json")" -[[ -z "${empty_hash}" ]] || fail "empty diff must fail open" - -missing_mode_hash="$(printf '%s\n' '{"filename":"missing.txt","previous_filename":"","status":"modified","patch":"@@ -1 +1 @@"}' | "${SCRIPT}" "${TMPDIR}/base.json" "${TMPDIR}/head.json")" -[[ -z "${missing_mode_hash}" ]] || fail "unverified mode metadata must fail open" - -echo "review diff hash and workflow-contract tests passed" diff --git a/.github/scripts/review-diff-hash.sh b/.github/scripts/review-diff-hash.sh deleted file mode 100755 index 8f1756ab04..0000000000 --- a/.github/scripts/review-diff-hash.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -# Keep this projection byte-for-byte aligned with pullRequestDiffHash in -# internal/cli/postreview.go. The Go parity test executes this script directly. -# Tree-mode maps are passed as files so large repositories do not hit the -# operating system's command-line argument limit. -base_modes_file=${1:?base tree modes JSON file is required} -head_modes_file=${2:?head tree modes JSON file is required} - -if ! hash_input=$(jq -s -c --slurpfile base_modes "${base_modes_file}" --slurpfile head_modes "${head_modes_file}" ' - if length == 0 or any(.[]; .patch == null or .patch == "") then - empty - else - sort_by(.filename, .previous_filename, .status) - | map(. + {old_mode: ($base_modes[0][(if .status == "added" then "" elif (.previous_filename // "") == "" then .filename else .previous_filename end)] // ""), new_mode: ($head_modes[0][(if .status == "removed" then "" else .filename end)] // "")}) - | if any(.[]; (.status == "added" and .new_mode == "") or (.status == "removed" and .old_mode == "") or ((.status != "added" and .status != "removed") and (.old_mode == "" or .new_mode == ""))) then empty else map({filename: .filename, previous_filename: .previous_filename, status: .status, old_mode: .old_mode, new_mode: .new_mode, patch: .patch}) end - end'); then - exit 0 -fi - -if [[ -z "${hash_input}" ]]; then - exit 0 -fi - -# Match Go encoding/json with HTML escaping disabled: jq escapes DEL while Go -# emits it literally, and Go escapes U+2028/U+2029 in JSON strings. -if ! hash_input=$(printf '%s' "${hash_input}" | perl -CS -pe 's/(? live` also runs the live behaviour and playback jobs for +# that sha, as the merge queue does, and reports them as behaviour-live and +# playback-live. Those names are not required checks, so a live run on a PR +# never stands in for, or blocks on, the required behaviour and playback. +# # No caller-level concurrency: e2e.yml queues /ok-to-test runs in its own # e2e-ok-to-test-{n} group, and sharing a group with the callee deadlocks. @@ -39,6 +44,9 @@ jobs: outputs: authorized: ${{ steps.auth.outputs.authorized }} head_sha: ${{ steps.auth.outputs.head_sha }} + live: ${{ steps.auth.outputs.live }} + behaviour_live_check_id: ${{ steps.checks.outputs.behaviour_live }} + playback_live_check_id: ${{ steps.checks.outputs.playback_live }} forgejo_behaviour_check_id: ${{ steps.checks.outputs.forgejo_behaviour }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -65,19 +73,23 @@ jobs: run: | [[ "${HEAD_SHA}" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::bad head sha '${HEAD_SHA}'"; exit 1; } - - name: Create the Forgejo behaviour check on the PR head + - name: Create the E2E checks on the PR head id: checks if: steps.auth.outputs.authorized == 'true' env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} HEAD_SHA: ${{ steps.auth.outputs.head_sha }} + LIVE: ${{ steps.auth.outputs.live }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | set -euo pipefail # Behaviour and playback run on a GitHub emulator for every pull - # request (behaviour-github-emulator.yml), so /ok-to-test runs only Forgejo. - for name in forgejo-behaviour; do + # request (behaviour-github-emulator.yml), so /ok-to-test runs only + # Forgejo, plus the live suites when the comment asked for them. + names=(forgejo-behaviour) + [[ "${LIVE}" == "true" ]] && names+=(behaviour-live playback-live) + for name in "${names[@]}"; do id=$(gh api -X POST "repos/${REPO}/check-runs" \ -f name="${name}" -f head_sha="${HEAD_SHA}" -f status=in_progress \ -f details_url="${RUN_URL}" \ @@ -86,6 +98,8 @@ jobs: --jq .id) case "${name}" in forgejo-behaviour) key=forgejo_behaviour ;; + behaviour-live) key=behaviour_live ;; + playback-live) key=playback_live ;; *) key=${name} ;; esac echo "${key}=${id}" >> "$GITHUB_OUTPUT" @@ -98,9 +112,12 @@ jobs: REPO: ${{ github.repository }} PR_NUMBER: ${{ github.event.issue.number }} HEAD_SHA: ${{ steps.auth.outputs.head_sha }} + LIVE: ${{ steps.auth.outputs.live }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | - body="E2E authorized for \`${HEAD_SHA}\` ([run](${RUN_URL})). A new push needs a new \`/ok-to-test \`." + suites="" + [[ "${LIVE}" == "true" ]] && suites=", with the live behaviour and playback suites" + body="E2E authorized for \`${HEAD_SHA}\`${suites} ([run](${RUN_URL})). A new push needs a new \`/ok-to-test \`." gh api -X POST "repos/${REPO}/issues/${PR_NUMBER}/comments" -f body="${body}" --silent run: @@ -117,6 +134,7 @@ jobs: with: pr_number: ${{ github.event.issue.number }} head_sha: ${{ needs.authorize.outputs.head_sha }} + live: ${{ needs.authorize.outputs.live == 'true' }} secrets: inherit report: @@ -127,13 +145,18 @@ jobs: permissions: checks: write steps: - - name: Complete the Forgejo behaviour check + - name: Complete the E2E checks env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} RUN_RESULT: ${{ needs.run.result }} FORGEJO_BEHAVIOUR_ID: ${{ needs.authorize.outputs.forgejo_behaviour_check_id }} FORGEJO_BEHAVIOUR_RESULT: ${{ needs.run.outputs.forgejo_behaviour_result }} + LIVE: ${{ needs.authorize.outputs.live }} + BEHAVIOUR_LIVE_ID: ${{ needs.authorize.outputs.behaviour_live_check_id }} + BEHAVIOUR_LIVE_RESULT: ${{ needs.run.outputs.behaviour_result }} + PLAYBACK_LIVE_ID: ${{ needs.authorize.outputs.playback_live_check_id }} + PLAYBACK_LIVE_RESULT: ${{ needs.run.outputs.playback_result }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | set -euo pipefail @@ -147,6 +170,10 @@ jobs: } status=0 pairs=("forgejo-behaviour:${FORGEJO_BEHAVIOUR_ID}:${FORGEJO_BEHAVIOUR_RESULT}") + if [[ "${LIVE}" == "true" ]]; then + pairs+=("behaviour-live:${BEHAVIOUR_LIVE_ID}:${BEHAVIOUR_LIVE_RESULT}") + pairs+=("playback-live:${PLAYBACK_LIVE_ID}:${PLAYBACK_LIVE_RESULT}") + fi for pair in "${pairs[@]}"; do IFS=: read -r name id result <<<"${pair}" [[ -n "${id}" ]] || { echo "::error::no ${name} check run id"; status=1; continue; } diff --git a/.github/workflows/e2e-org-pool.yml b/.github/workflows/e2e-org-pool.yml new file mode 100644 index 0000000000..3c92755064 --- /dev/null +++ b/.github/workflows/e2e-org-pool.yml @@ -0,0 +1,149 @@ +name: E2E Org Pool + +# Keeps the e2e pool orgs configured. Runs that touch GitHub (pushes to +# main, manual dispatches, the weekly schedule) execute setup-org.sh for +# real from main and correct drift. Pull requests never touch GitHub: +# they run the stub-based setup-org_test.sh on the PR head, with no +# secrets, so PR changes are exercised without exposing credentials. + +permissions: {} + +on: + push: + branches: [main] + paths: + - 'e2e/org-pool/**' + - '.github/workflows/e2e-org-pool.yml' + - 'pkg/behaviourtest/drivers/install/slotpool.go' + pull_request: + types: [opened, synchronize, reopened] + paths: + - 'e2e/org-pool/**' + - '.github/workflows/e2e-org-pool.yml' + - 'pkg/behaviourtest/drivers/install/slotpool.go' + merge_group: + workflow_dispatch: + inputs: + dry_run: + description: 'Verify only; print planned changes without mutating' + type: boolean + default: false + schedule: + # Weekly, so out-of-band drift is corrected even when nobody edits + # e2e/org-pool. Runs on the default branch (main). + - cron: '0 4 * * 1' + +# Concurrency is set per job: the mutating configure job gets the plain +# workflow group (runs must not overlap, and a queued run must not cancel +# a mutating run mid-loop), while the read-only PR test job gets its own +# group so PR validation never queues behind — or displaces — a mutating +# run. + +jobs: + test: + # PR validation: stubbed gh, no secrets, PR-head code. + if: >- + github.event_name == 'pull_request' || + github.event_name == 'merge_group' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + concurrency: + group: ${{ github.workflow }}-test-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + steps: + - name: Check for relevant changes + id: changes + if: github.event_name == 'merge_group' + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + MERGE_GROUP_BASE: ${{ github.event.merge_group.base_sha }} + MERGE_GROUP_HEAD: ${{ github.event.merge_group.head_sha }} + # SYNC-WITH: push.paths / pull_request.paths filters above + run: | + FILES=$(gh api "repos/${REPO}/compare/${MERGE_GROUP_BASE}...${MERGE_GROUP_HEAD}" \ + --jq '.files[].filename') || { + echo "::warning::Failed to fetch merge group files — running as a precaution" + echo "relevant=true" >> "$GITHUB_OUTPUT" + exit 0 + } + FILE_COUNT=$(echo "$FILES" | wc -l) + if [ "$FILE_COUNT" -ge 300 ]; then + echo "::warning::Compare API returned $FILE_COUNT files (possible truncation) — running as a precaution" + echo "relevant=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if echo "$FILES" | grep -qE '^e2e/org-pool/|^\.github/workflows/e2e-org-pool\.yml$|^pkg/behaviourtest/drivers/install/slotpool\.go$'; then + echo "relevant=true" >> "$GITHUB_OUTPUT" + else + echo "::notice::No relevant files changed — skipping" + echo "relevant=false" >> "$GITHUB_OUTPUT" + fi + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + if: steps.changes.outputs.relevant != 'false' + with: + # The workflow file and slotpool.go are read by setup-org_test.sh + # to keep the workflow's org list in sync with DevPoolOrgCount. + sparse-checkout: | + e2e/org-pool + .github/workflows/e2e-org-pool.yml + pkg/behaviourtest/drivers/install/slotpool.go + # Non-cone mode: the list above names individual files, which + # cone mode would round up to their whole parent directories. + sparse-checkout-cone-mode: false + persist-credentials: false + + - name: Run org pool setup tests + if: steps.changes.outputs.relevant != 'false' + run: bash e2e/org-pool/setup-org_test.sh + + configure: + # Drift correction. The PAT secrets live in the 'e2e-org-pool' + # environment, which must be restricted to the main branch, so + # pull_request runs can never reach the org-admin token. + if: >- + github.event_name != 'pull_request' && + github.event_name != 'merge_group' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + environment: e2e-org-pool + concurrency: + group: ${{ github.workflow }} + cancel-in-progress: false + steps: + # Main-branch scripts only: the org-admin token below must never + # run PR-head code. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + sparse-checkout: e2e/org-pool + persist-credentials: false + + - name: Configure pool orgs + shell: bash + env: + # Org-admin token for botsend; runs main-branch setup-org.sh only. + TEST_BOTSEND_PAT: ${{ secrets.TEST_BOTSEND_PAT }} + TEST_ACTOR_WRITE_PAT: ${{ secrets.TEST_ACTOR_WRITE_PAT }} + TEST_ACTOR_TRIAGE_PAT: ${{ secrets.TEST_ACTOR_TRIAGE_PAT }} + DRY_RUN_INPUT: ${{ inputs.dry_run }} + run: | + : "${TEST_BOTSEND_PAT:?TEST_BOTSEND_PAT secret is not set}" + export GH_TOKEN="${TEST_BOTSEND_PAT}" + if [[ "${DRY_RUN_INPUT}" == "true" ]]; then + dry_run="--dry-run" + else + dry_run="" + fi + # STAGE org halfsend plus the dev pool halfsend-01..halfsend-22; + # keep in sync with e2e/org-pool/README.md. + orgs="halfsend $(seq -f 'halfsend-%02g' 1 22)" + failed=() + for org in ${orgs}; do + e2e/org-pool/setup-org.sh ${dry_run} "${org}" || failed+=("${org}") + done + if (( ${#failed[@]} )); then + echo "::error::setup-org.sh failed for: ${failed[*]}" + exit 1 + fi diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 6bb66ee595..dab3ab6859 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -72,6 +72,11 @@ on: description: PR head sha the comment authorized (checked out by each test job) type: string required: true + live: + description: The comment was `/ok-to-test live`; also run live behaviour and playback + type: boolean + required: false + default: false outputs: behaviour_result: description: behaviour job status (success, failure or cancelled) @@ -137,10 +142,11 @@ jobs: group: ${{ github.workflow }}-${{ github.run_id }}-${{ github.event_name == 'push' && 'stage-org' || 'behaviour-dev' }} cancel-in-progress: false # Gate authorization protects checkout of untrusted PR-head code with secrets. - # Runs only on merge_group (required check; treated as PR-class / dev) - # and push to main (stage). Pull requests run behaviour-github-emulator.yml - # instead; this job skips there, which the required check accepts. - # Skip workflow_dispatch. + # Runs on merge_group (required check; treated as PR-class / dev), push to + # main (stage), and an authorized `/ok-to-test live` (dev; reported + # by e2e-ok-to-test.yml as behaviour-live). Pull requests run + # behaviour-github-emulator.yml instead; this job skips there, which the + # required check accepts. Skip workflow_dispatch. # Environment uses event_name, not github.ref: pull_request sets # github.ref to refs/pull/N/merge and issue_comment to the default branch. needs: gate @@ -148,7 +154,8 @@ jobs: !cancelled() && ( (github.event_name == 'push' && github.ref == 'refs/heads/main') || - (github.event_name == 'merge_group') + (github.event_name == 'merge_group') || + (github.event_name == 'issue_comment' && inputs.head_sha != '' && inputs.live) ) # Scalar form keeps default deployment: true so runs list under Environments. environment: ${{ github.event_name == 'push' && 'stage' || 'dev' }} @@ -162,7 +169,7 @@ jobs: contents: read id-token: write outputs: - # Read by e2e-ok-to-test.yml to complete the behaviour check run on the PR head. + # Read by e2e-ok-to-test.yml to complete the behaviour-live check run on the PR head. result: ${{ steps.result.outputs.result }} env: ENVIRONMENT: ${{ github.event_name == 'push' && 'stage' || 'dev' }} @@ -450,13 +457,15 @@ jobs: group: ${{ github.workflow }}-${{ github.run_id }}-${{ github.event_name == 'push' && 'stage-org' || 'playback-dev' }} cancel-in-progress: false # Manual dispatch uses the selected trusted branch and the dev environment. + # An authorized `/ok-to-test live` runs it on that sha (dev). needs: gate if: >- !cancelled() && ( (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'merge_group') || - (github.event_name == 'workflow_dispatch' && inputs.run_playback) + (github.event_name == 'workflow_dispatch' && inputs.run_playback) || + (github.event_name == 'issue_comment' && inputs.head_sha != '' && inputs.live) ) # Scalar form keeps default deployment: true so runs list under Environments. environment: ${{ github.event_name == 'push' && 'stage' || 'dev' }} @@ -470,7 +479,7 @@ jobs: contents: read id-token: write outputs: - # Read by e2e-ok-to-test.yml to complete the playback check run on the PR head. + # Read by e2e-ok-to-test.yml to complete the playback-live check run on the PR head. result: ${{ steps.result.outputs.result }} env: ENVIRONMENT: ${{ github.event_name == 'push' && 'stage' || 'dev' }} diff --git a/.github/workflows/fullsend-fork-pr.yaml b/.github/workflows/fullsend-fork-pr.yaml new file mode 100644 index 0000000000..f66dc3d746 --- /dev/null +++ b/.github/workflows/fullsend-fork-pr.yaml @@ -0,0 +1,41 @@ +# This file is managed by fullsend. Do not edit it directly. +# Upstream: https://github.com/fullsend-ai/fullsend/blob/main/internal/scaffold/fullsend-repo/.github/workflows/fullsend-fork-pr.yaml +--- +# fullsend fork pull request stub (per-repo installation mode, GitHub only) +# +# A fork's pull_request run gets no secrets and no OIDC token, so the +# fullsend shim (fullsend.yaml) skips fork pull requests. This workflow runs +# on those events instead and does nothing: it has no permissions, checks +# out nothing, and uploads nothing. When its run completes, GitHub starts +# the shim's workflow_run trigger from the default branch. That run looks +# the pull request up through the API: an open PR is reviewed when its +# author has triage access or higher, a closed one gets a retro when a user +# with write access closed it. Labels do not start a fork PR review: no +# trusted record ties a label to the head it was added on, so a maintainer +# comments /fs-review instead. +# +# The fork controls the copy of this file that runs for its pull request, so +# the shim trusts nothing this run produces. It reads only what GitHub +# records about the run: event, conclusion, file path, head repository, +# head SHA and creation time. +name: fullsend-fork-pr + +on: + pull_request: + types: [opened, synchronize, ready_for_review, closed] + +permissions: {} + +jobs: + fork-pr: + # Fork pull requests only: same-repository pull requests go through the + # shim directly. + if: github.event.pull_request.head.repo.id != github.repository_id + # A GitHub-hosted runner, not the repository's configured runner: the + # fork controls the copy of this file that runs, so a self-hosted + # runner here would run fork-chosen steps on it. The job only echoes. + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Hand the event to the fullsend workflow + run: echo "Fork pull request event recorded; the fullsend workflow resolves it from the default branch." diff --git a/.github/workflows/fullsend.yaml b/.github/workflows/fullsend.yaml index 12034cf404..d8be8c1f86 100644 --- a/.github/workflows/fullsend.yaml +++ b/.github/workflows/fullsend.yaml @@ -11,18 +11,30 @@ # copy and forwards the repository secrets, so the dispatch job runs only for # same-repo PRs, whose authors already have write access. Fork PRs are skipped # here and again in reusable-dispatch.yml (a fork cannot edit the upstream -# copy; a vendored copy runs from the PR); a maintainer comments /fs-review -# to review one. In private repositories keep "Send secrets to workflows -# from pull requests" and "Send write tokens to workflows from pull -# requests" (Settings > Actions > General) turned off. +# copy; a vendored copy runs from the PR). In private repositories keep +# "Send secrets to workflows from pull requests" and "Send write tokens to +# workflows from pull requests" (Settings > Actions > General) turned off. # reusable-dispatch.yml checks out the base side for pull request events. # +# Fork PRs: fullsend-fork-pr.yaml runs on fork PR events with no permissions +# and no secrets. When its run completes, workflow_run starts this workflow +# from the default branch, with secrets. The fork controls the copy of the +# stub that ran, so this workflow trusts only what GitHub records about that +# run: the dispatch job runs for a successful pull_request run of the stub's +# file from a fork, and reusable-dispatch.yml looks the PR up by head SHA +# through the API, skips a run whose SHA is no longer the PR head, and +# authorizes the PR author (review) or closer (retro). Labels do not start +# a fork PR review. It never downloads the stub run's artifacts or checks +# out PR code. A maintainer can still comment /fs-review on any PR. +# # Routing: this shim forwards the raw event context to reusable-dispatch.yml, # which determines the stage and runs the agent inline (ADR 62). # Adding a new stage requires only a job in reusable-dispatch.yml — zero changes to this repo. # # Concurrency: per-role cancel-in-progress groups live in reusable-dispatch.yml -# stage jobs with -agent- suffix. Roles operate independently (#2452). +# stage jobs with -agent- suffix. Roles operate independently (#2452). A fork +# PR's workflow_run joins the same per-PR groups, so a newer push supersedes +# a review still in progress. name: fullsend on: @@ -34,6 +46,9 @@ on: types: [opened, synchronize, ready_for_review, closed, labeled, unlabeled] pull_request_review: types: [submitted] + workflow_run: + workflows: [fullsend-fork-pr] + types: [completed] permissions: {} @@ -46,6 +61,11 @@ jobs: || github.event.pull_request.head.repo.id == github.repository_id) && (github.event_name != 'issue_comment' || startsWith(github.event.comment.body, '/fs-')) + && (github.event_name != 'workflow_run' + || (github.event.workflow_run.event == 'pull_request' + && github.event.workflow_run.conclusion == 'success' + && github.event.workflow_run.path == '.github/workflows/fullsend-fork-pr.yaml' + && github.event.workflow_run.head_repository.id != github.repository_id)) permissions: actions: write id-token: write diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7844fa5a3a..bb6b73ae0c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,7 +26,7 @@ jobs: go-version-file: go.mod - name: Install cosign - uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3 + uses: sigstore/cosign-installer@881c63bd87e38389154debd8331404ce7ca8a3ab # v4.1.4 # A final tag can share its commit with the release candidate it # promotes (vX.Y.Z and vX.Y.Z-rc.N on one commit). GoReleaser picks @@ -224,7 +224,7 @@ jobs: steps: - name: Generate agents repo token id: agents-token - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3 + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3 with: app-id: ${{ vars.RELEASE_APP_ID }} private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} diff --git a/.github/workflows/renovate.yml b/.github/workflows/renovate.yml index bd82a4f0d6..a8cd574960 100644 --- a/.github/workflows/renovate.yml +++ b/.github/workflows/renovate.yml @@ -33,13 +33,13 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3 + - uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3 id: app-token with: app-id: ${{ vars.RENOVATE_APP_ID }} private-key: ${{ secrets.RENOVATE_PRIVATE_KEY }} - - uses: renovatebot/github-action@acdd6bda8b035c99ce59d5675816af2aa65a1774 # v46.3.14 + - uses: renovatebot/github-action@ebcbb513d07ead4d9c0c2139064301db05e84a3e # v46.3.15 with: token: ${{ steps.app-token.outputs.token }} configurationFile: renovate.json diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 84a985b42a..0cec1eea30 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -146,6 +146,9 @@ jobs: stage: ${{ steps.review-skip-publish.outputs.skipped != 'true' && steps.agent-check.outputs.skipped != 'true' && steps.route.outputs.stage || '' }} trigger_source: ${{ steps.route.outputs.trigger_source }} event_payload: ${{ steps.payload.outputs.event_payload }} + # The fork PR number for workflow_run events, whose payload has none; + # the stage concurrency groups fall back to it. + pr_number: ${{ steps.fork-pr.outputs.number }} steps: - name: Validate event_action if: ${{ inputs.event_action == '' }} @@ -171,18 +174,197 @@ jobs: .defaults/.github/actions/mint-token/ .defaults/.github/actions/prepare-workspace/ .defaults/.github/actions/validate-enrollment/ - .defaults/.github/scripts/review-diff-hash.sh .defaults/internal/scaffold/fullsend-repo/ .fullsend/.defaults/action.yml .fullsend/.defaults/.github/actions/mint-token/ .fullsend/.defaults/.github/actions/prepare-workspace/ .fullsend/.defaults/.github/actions/validate-enrollment/ - .fullsend/.defaults/.github/scripts/review-diff-hash.sh .fullsend/.defaults/internal/scaffold/fullsend-repo/ + .fullsend/bin/fullsend /OWNERS /OWNERS_ALIASES sparse-checkout-cone-mode: false + # Fork pull requests arrive as workflow_run: the shim's trigger on the + # completed run of the no-permission fullsend-fork-pr.yaml stub. It + # runs from the default branch with secrets and OIDC, which is why it + # can review a fork PR that its own pull_request run could not. + # github/gh-aw does not dispatch PR events through workflow_run, and + # its CTR-021 check flags a workflow_run trigger without a branches: + # filter. A branches: filter cannot help here: for a fork PR the + # stub run's head_branch is a branch name the fork chose. + # + # The fork controls the stub copy that ran, so nothing that run + # produced (artifacts, run name, logs) is read, and PR code is never + # checked out. Its head_repository, head_branch, head_sha, path and + # created_at are lookup metadata a fork can influence, not + # provenance: they only say which PR to look up. What authorizes a + # run, all checked here before any token mint or agent step with the + # read-only GITHUB_TOKEN, is: + # - the PR as the API returns it for this repository, whose + # head.repo.id and head.sha must match the run (a run whose SHA is + # no longer an open PR's head is skipped; the newer push has its + # own run); + # - "Determine stage" checking the PR author or closer the + # API reports, as for a same-repo pull_request event. + # The action the run stands for is rebuilt from API data: closed for a + # closed PR, otherwise opened, ready_for_review or synchronize, all + # checked against the PR author. A label never starts a fork PR + # review: a fork's stub copy can run on any label event, so nothing + # trusted ties a label to the head it was added on; a maintainer + # comments /fs-review instead. A closed PR counts only if it closed + # within FORK_PR_WINDOW seconds before the stub run was created, so + # one close cannot start retro again later: GitHub creates the stub + # run seconds after the event, and five minutes absorbs Actions event + # backlog. The issue events API documents no order, so events are + # sorted by time. + - name: Resolve fork pull request for workflow_run + id: fork-pr + if: github.event_name == 'workflow_run' + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY_ID: ${{ github.repository_id }} + STUB_PATH: .github/workflows/fullsend-fork-pr.yaml + FORK_PR_WINDOW: "300" + WR_EVENT: ${{ github.event.workflow_run.event }} + WR_CONCLUSION: ${{ github.event.workflow_run.conclusion }} + WR_PATH: ${{ github.event.workflow_run.path }} + WR_HEAD_REPO_ID: ${{ github.event.workflow_run.head_repository.id }} + WR_HEAD_OWNER: ${{ github.event.workflow_run.head_repository.owner.login }} + WR_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }} + WR_HEAD_SHA: ${{ github.event.workflow_run.head_sha }} + WR_CREATED_AT: ${{ github.event.workflow_run.created_at }} + run: | + set -euo pipefail + echo "resolved=false" >> "${GITHUB_OUTPUT}" + skip() { + echo "::notice::Fork pull request run not routed: $1" + exit 0 + } + # A close or label that should have started a run but fell + # outside its checks is a warning, so a lost retro or review shows. + skip_warn() { + echo "::warning::Fork pull request run not routed: $1" + exit 0 + } + [[ "${WR_EVENT}" == "pull_request" ]] || skip "the stub run was not started by a pull_request event" + [[ "${WR_CONCLUSION}" == "success" ]] || skip "the stub run did not succeed" + [[ "${WR_PATH}" == "${STUB_PATH}" ]] || skip "the completed run is not ${STUB_PATH}" + [[ "${WR_HEAD_REPO_ID}" =~ ^[0-9]+$ && "${WR_HEAD_REPO_ID}" != "${REPOSITORY_ID}" ]] || skip "the head repository is not a fork" + [[ "${WR_HEAD_SHA}" =~ ^[0-9a-f]{40}([0-9a-f]{24})?$ ]] || skip "the run has no valid head SHA" + [[ "${WR_HEAD_OWNER}" =~ ^[A-Za-z0-9-]+$ && -n "${WR_HEAD_BRANCH}" ]] || skip "the run has no head owner or branch" + [[ -n "${WR_CREATED_AT}" ]] || skip "the run has no creation time" + + api() { + local out err + err=$(mktemp) + if ! out=$(gh api "$@" 2>"${err}"); then + echo "::error::GitHub API call failed: $(LC_ALL=C tr -d '\000-\037:%' < "${err}" | head -c 300)" >&2 + rm -f "${err}" + exit 1 + fi + rm -f "${err}" + printf '%s' "${out}" + } + + # The head filter takes the fork owner's login and the branch name; + # gh encodes them as query parameters. + PRS=$(api --method GET "repos/${GITHUB_REPOSITORY}/pulls" \ + -f state=all -f per_page=100 -f "head=${WR_HEAD_OWNER}:${WR_HEAD_BRANCH}") + NUMBER=$(jq -r --arg sha "${WR_HEAD_SHA}" --argjson hid "${WR_HEAD_REPO_ID}" ' + [.[] | select(.head.sha == $sha and (.head.repo.id // -1) == $hid)] + | sort_by(.state != "open", -.number) | .[0].number // empty' <<<"${PRS}") + if [[ -z "${NUMBER}" ]]; then + if jq -e 'any(.[]; .state == "open")' <<<"${PRS}" >/dev/null; then + skip "the run's head SHA is no longer the pull request head (a newer push has its own run)" + fi + skip "no pull request has the run's head SHA" + fi + [[ "${NUMBER}" =~ ^[0-9]+$ ]] || skip "the pull request number is malformed" + + WORK_DIR="${RUNNER_TEMP}/fullsend-fork-pr" + mkdir -p "${WORK_DIR}" + PR_FILE="${WORK_DIR}/pull_request.json" + api "repos/${GITHUB_REPOSITORY}/pulls/${NUMBER}" > "${PR_FILE}" + STATE=$(jq -r '.state // ""' "${PR_FILE}") + AUTHOR=$(jq -r '.user.login // ""' "${PR_FILE}") + if ! jq -e --arg sha "${WR_HEAD_SHA}" --argjson hid "${WR_HEAD_REPO_ID}" \ + '.head.sha == $sha and (.head.repo.id // -1) == $hid' "${PR_FILE}" >/dev/null; then + skip "the run's head SHA is no longer the pull request head (a newer push has its own run)" + fi + EVENTS=$(api --paginate "repos/${GITHUB_REPOSITORY}/issues/${NUMBER}/events?per_page=100" | jq -s 'add // [] | sort_by(.created_at)') + # last_event : the newest issue event matching filter. + last_event() { + jq -c "[.[] | select($1)] | last // {}" <<<"${EVENTS}" + } + + # within : is it in [run created - window, run created + 60 s]? + # The 60 s allows for clock differences between GitHub services. + within() { + jq -en --arg t "$1" --arg created "${WR_CREATED_AT}" --argjson window "${FORK_PR_WINDOW}" ' + ($t | sub("\\.[0-9]+"; "") | fromdateiso8601) as $t + | ($created | sub("\\.[0-9]+"; "") | fromdateiso8601) as $c + | $t >= ($c - $window) and $t <= ($c + 60)' >/dev/null 2>&1 + } + + ACTION="" + CLOSER="" + case "${STATE}" in + closed) + CLOSED_AT=$(jq -r '.closed_at // ""' "${PR_FILE}") + if [[ -z "${CLOSED_AT}" ]] || ! within "${CLOSED_AT}"; then + skip_warn "the pull request did not close within ${FORK_PR_WINDOW} s before the run" + fi + ACTION="closed" + CLOSER=$(jq -r 'if .merged == true then (.merged_by.login // "") else "" end' "${PR_FILE}") + if [[ -z "${CLOSER}" ]]; then + CLOSE_EVENT=$(last_event '.event == "closed"') + CLOSE_EVENT_AT=$(jq -r '.created_at // ""' <<<"${CLOSE_EVENT}") + if [[ -z "${CLOSE_EVENT_AT}" ]] || ! within "${CLOSE_EVENT_AT}"; then + skip_warn "no close event within ${FORK_PR_WINDOW} s before the run names the closer" + fi + CLOSER=$(jq -r '.actor.login // ""' <<<"${CLOSE_EVENT}") + fi + ;; + open) + READY_AT=$(jq -r '.created_at // ""' <<<"$(last_event '.event == "ready_for_review"')") + CREATED_AT=$(jq -r '.created_at // ""' "${PR_FILE}") + if [[ -n "${CREATED_AT}" ]] && within "${CREATED_AT}"; then + ACTION="opened" + elif [[ -n "${READY_AT}" ]] && within "${READY_AT}"; then + ACTION="ready_for_review" + else + ACTION="synchronize" + fi + ;; + *) + skip "the pull request state is not open or closed" + ;; + esac + for login in "${AUTHOR}" "${CLOSER}"; do + [[ -z "${login}" || "${login}" =~ ^[A-Za-z0-9-]+(\[bot\])?$ ]] || skip "a login has an unexpected format" + done + + # The same fields the issue_comment path merges into the event + # payload (see "Resolve PR head for issue_comment events"). + PR_JSON=$(jq -c '{number, html_url, + head: {ref: .head.ref, sha: .head.sha, repo: {full_name: .head.repo.full_name}}, + base: {ref: .base.ref, repo: {full_name: .base.repo.full_name}}}' "${PR_FILE}") + echo "::notice::Fork pull request #${NUMBER} (${STATE}, ${ACTION})" + DELIM="PR_$(openssl rand -hex 8)" + { + echo "resolved=true" + echo "number=${NUMBER}" + echo "state=${STATE}" + echo "action=${ACTION}" + echo "author=${AUTHOR}" + echo "closer=${CLOSER}" + echo "pr_file=${PR_FILE}" + echo "pr_json<<${DELIM}" + echo "${PR_JSON}" + echo "${DELIM}" + } >> "${GITHUB_OUTPUT}" + - name: Determine stage id: bash-route env: @@ -208,6 +390,11 @@ jobs: ORG_NAME: ${{ github.repository_owner }} FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET || 'fullsend-ai' }} GH_TOKEN: ${{ github.token }} + FORK_PR_RESOLVED: ${{ steps.fork-pr.outputs.resolved }} + FORK_PR_STATE: ${{ steps.fork-pr.outputs.state }} + FORK_PR_ACTION: ${{ steps.fork-pr.outputs.action }} + FORK_PR_AUTHOR: ${{ steps.fork-pr.outputs.author }} + FORK_PR_CLOSER: ${{ steps.fork-pr.outputs.closer }} run: | set -euo pipefail @@ -462,6 +649,39 @@ jobs: esac ;; + workflow_run) + # A fork pull request event, resolved from the API by "Resolve + # fork pull request for workflow_run". The same rules as the + # pull_request case above, except that labels do not apply (see + # "Resolve fork pull request"): a closed PR needs a write + # closer, and any other event needs a triage+ PR author. Unlike a + # same-repo PR, a [bot] author is not trusted on its own: any + # registered GitHub App can open a PR from a fork. + # event_action and event_sender name the equivalent + # pull_request event for the CEL route steps. + if [[ "${FORK_PR_RESOLVED:-}" == "true" ]]; then + ROUTED_ACTION="" + ROUTED_SENDER="" + if [[ "${FORK_PR_STATE}" == "closed" ]]; then + ROUTED_ACTION="closed" + ROUTED_SENDER="${FORK_PR_CLOSER}" + if is_event_actor_authorized "${FORK_PR_CLOSER}"; then + STAGE="retro" + fi + else + ROUTED_ACTION="${FORK_PR_ACTION}" + ROUTED_SENDER="${FORK_PR_AUTHOR}" + if is_event_actor_authorized "${FORK_PR_AUTHOR}" triage; then + STAGE="review" + fi + fi + { + echo "event_action=${ROUTED_ACTION}" + echo "event_sender=${ROUTED_SENDER}" + } >> "${GITHUB_OUTPUT}" + fi + ;; + pull_request_review) if [[ "${EVENT_ACTION}" == "submitted" && "${REVIEW_STATE}" == "changes_requested" ]]; then REVIEW_BOT="${ORG_NAME}-review[bot]" @@ -506,7 +726,7 @@ jobs: # still enforce the same policy for the final routed stage. - name: Check review deduplication guards id: review-dedup-guard - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && (github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && (github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) shell: bash run: | set -euo pipefail @@ -553,212 +773,154 @@ jobs: echo "allowed=${allowed}" >> "${GITHUB_OUTPUT}" echo "prevalidated=${prevalidated}" >> "${GITHUB_OUTPUT}" - # The diff check is read-only and must have its canonicalizer before it - # runs. Vendored callers already provide it in the caller checkout; - # fetch only this script for callers using upstream defaults. - - name: Checkout review diff canonicalizer - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && (github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) && steps.review-dedup-guard.outputs.allowed == 'true' && hashFiles('.defaults/action.yml', '.fullsend/.defaults/action.yml') == '' + # The CLI is the single implementation of review-diff hashing, prior + # review validation, and skip-note publication. Vendored callers provide + # the binary; default callers install the trusted workflow build. + - name: Detect review dedup CLI + id: review-cli-mode + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && (github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) && steps.review-dedup-guard.outputs.allowed == 'true' continue-on-error: true - timeout-minutes: 2 + shell: bash + run: | + set -euo pipefail + if [[ -f .fullsend/bin/fullsend ]] && .fullsend/bin/fullsend review-dedup --help >/dev/null 2>&1; then + echo "mode=vendored" >> "${GITHUB_OUTPUT}" + else + echo "mode=upstream" >> "${GITHUB_OUTPUT}" + fi + + - name: Restore fullsend CLI cache for review dedup + id: review-cli-cache + if: steps.review-cli-mode.outcome == 'success' && steps.review-cli-mode.outputs.mode == 'upstream' + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/fullsend-cache + key: fullsend-review-dedup-cli-${{ steps.review-cli-mode.outputs.mode }}-${{ runner.arch }}-${{ hashFiles('.fullsend/bin/fullsend') }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + + - name: Validate cached fullsend CLI for review dedup + id: review-cli-cache-validation + if: steps.review-cli-mode.outputs.mode == 'upstream' && steps.review-cli-cache.outputs.cache-hit == 'true' + continue-on-error: true + shell: bash + run: | + set -euo pipefail + if [[ -x "${RUNNER_TEMP}/fullsend-cache/fullsend" ]] && "${RUNNER_TEMP}/fullsend-cache/fullsend" review-dedup --help >/dev/null 2>&1; then + echo "valid=true" >> "${GITHUB_OUTPUT}" + else + echo "valid=false" >> "${GITHUB_OUTPUT}" + fi + + - name: Install review dedup CLI (vendored) + if: steps.review-cli-mode.outputs.mode == 'vendored' + continue-on-error: true + shell: bash + run: | + set -euo pipefail + mkdir -p "${RUNNER_TEMP}/fullsend-review-dedup" + cp .fullsend/bin/fullsend "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" + chmod +x "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" + + - name: Checkout review dedup CLI installer + if: steps.review-cli-mode.outputs.mode == 'upstream' && (steps.review-cli-cache.outputs.cache-hit != 'true' || steps.review-cli-cache-validation.outputs.valid != 'true') + continue-on-error: true + timeout-minutes: 5 uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: ${{ job.workflow_repository }} ref: ${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} - path: .review-diff-defaults + path: .review-dedup-actions fetch-depth: 1 sparse-checkout: | - .github/scripts/review-diff-hash.sh + .github/actions/install-fullsend-cli/ sparse-checkout-cone-mode: false + - name: Install review dedup CLI (upstream) + if: steps.review-cli-mode.outputs.mode == 'upstream' && (steps.review-cli-cache.outputs.cache-hit != 'true' || steps.review-cli-cache-validation.outputs.valid != 'true') + continue-on-error: true + timeout-minutes: 5 + uses: ./.review-dedup-actions/.github/actions/install-fullsend-cli + with: + mode: upstream + install_dir: ${{ runner.temp }}/fullsend-review-dedup + add_to_path: 'false' + source_dir: ${{ runner.temp }}/fullsend-review-dedup-src + workflow_repository: ${{ job.workflow_repository }} + workflow_sha: ${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + github_token: ${{ github.token }} + + - name: Expose cached fullsend CLI for review dedup + if: steps.review-cli-mode.outputs.mode == 'upstream' && steps.review-cli-cache-validation.outputs.valid == 'true' + continue-on-error: true + shell: bash + run: | + set -euo pipefail + install_dir="${RUNNER_TEMP}/fullsend-review-dedup" + mkdir -p "${install_dir}" + cp "${RUNNER_TEMP}/fullsend-cache/fullsend" "${install_dir}/fullsend" + chmod +x "${install_dir}/fullsend" + + - name: Prepare fullsend CLI cache artifact for review dedup + id: review-cli-cache-prepare + if: steps.review-cli-mode.outputs.mode == 'upstream' && (steps.review-cli-cache.outputs.cache-hit != 'true' || steps.review-cli-cache-validation.outputs.valid != 'true') + continue-on-error: true + shell: bash + run: | + set -euo pipefail + if [[ ! -x "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" ]]; then + echo "ready=false" >> "${GITHUB_OUTPUT}" + exit 0 + fi + mkdir -p "${RUNNER_TEMP}/fullsend-cache" + cp "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" "${RUNNER_TEMP}/fullsend-cache/fullsend" + "${RUNNER_TEMP}/fullsend-cache/fullsend" review-dedup --help >/dev/null 2>&1 + echo "ready=true" >> "${GITHUB_OUTPUT}" + + - name: Save fullsend CLI cache for review dedup + if: steps.review-cli-mode.outputs.mode == 'upstream' && (steps.review-cli-cache.outputs.cache-hit != 'true' || steps.review-cli-cache-validation.outputs.valid != 'true') && steps.review-cli-cache-prepare.outcome == 'success' && steps.review-cli-cache-prepare.outputs.ready == 'true' + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/fullsend-cache + key: fullsend-review-dedup-cli-${{ steps.review-cli-mode.outputs.mode }}-${{ runner.arch }}-${{ hashFiles('.fullsend/bin/fullsend') }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + # A synchronize event can be caused by merging the base branch into a - # PR without changing the PR's effective diff. Avoid paying for another - # full review when the previous review recorded the same complete diff. - # Missing or incomplete metadata deliberately fails open. + # PR without changing its effective diff. A fork PR push comes in as + # the shim's workflow_run with event_action synchronize (see "Resolve + # fork pull request for workflow_run") and gets the same check. Missing or incomplete + # metadata deliberately fails open in the CLI. - name: Check unchanged review diff id: review-diff - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && (github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) && steps.review-dedup-guard.outputs.allowed == 'true' + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && (github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) && steps.review-dedup-guard.outputs.allowed == 'true' env: GH_TOKEN: ${{ github.token }} SOURCE_REPO: ${{ github.repository }} - PR_NUMBER: ${{ github.event.pull_request.number }} - ORG_NAME: ${{ github.repository_owner }} + PR_NUMBER: ${{ github.event.pull_request.number || steps.fork-pr.outputs.number }} FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET || 'fullsend-ai' }} REVIEW_APP_CLIENT_ID: ${{ vars.FULLSEND_REVIEW_CLIENT_ID }} shell: bash run: | set -euo pipefail - echo "skip=false" >> "${GITHUB_OUTPUT}" - - REVIEW_BOT="${ORG_NAME}-review[bot]" - SHARED_REVIEW_BOT="fullsend-ai-review[bot]" - CUSTOM_REVIEW_BOT="" - if [[ -n "${FULLSEND_APP_SET}" ]]; then - CUSTOM_REVIEW_BOT="${FULLSEND_APP_SET}-review[bot]" - fi - - if ! pr_before=$(gh api "repos/${SOURCE_REPO}/pulls/${PR_NUMBER}" --jq '{base_sha: .base.sha, head_sha: .head.sha}'); then - echo "::warning::Could not read PR base/head metadata; running review" - exit 0 - fi - base_before="$(printf '%s' "${pr_before}" | jq -r '.base_sha // ""')" - head_before="$(printf '%s' "${pr_before}" | jq -r '.head_sha // ""')" - if [[ -z "${base_before}" || -z "${head_before}" ]]; then - echo "::warning::PR base or head tree metadata is incomplete; running review" - exit 0 - fi - base_sha="${base_before}" - head_sha="${head_before}" - if ! merge_base_sha=$(gh api "repos/${SOURCE_REPO}/compare/${base_sha}...${head_sha}" --jq '.merge_base_commit.sha // ""'); then - echo "::notice::Could not determine the PR merge base; running review" - exit 0 - fi - if [[ -z "${merge_base_sha}" ]]; then - echo "::notice::PR compare metadata did not include a merge base; running review" - exit 0 - fi - - if ! file_json=$(gh api "repos/${SOURCE_REPO}/pulls/${PR_NUMBER}/files" \ - --paginate --jq '.[] | {filename, previous_filename: (.previous_filename // ""), status: (.status // ""), patch}'); then - echo "::warning::Could not fetch PR file diffs; running review" - exit 0 - fi - - if ! expected_files=$(gh api "repos/${SOURCE_REPO}/pulls/${PR_NUMBER}" --jq '.changed_files'); then - echo "::warning::Could not verify the complete PR file list; running review" - exit 0 - fi - if [[ ! "${expected_files}" =~ ^[0-9]+$ || "${expected_files}" -ge 3000 ]]; then - echo "::notice::PR file count cannot be proven complete; running review" - exit 0 - fi - actual_files=$(printf '%s\n' "${file_json}" | jq -s 'length') - if [[ "${actual_files}" != "${expected_files}" ]]; then - echo "::notice::PR file list is incomplete (${actual_files}/${expected_files}); running review" + dedup_cli="${RUNNER_TEMP}/fullsend-review-dedup/fullsend" + if [[ ! -x "${dedup_cli}" ]]; then + echo "::warning::Review deduplication CLI unavailable; running review" exit 0 fi - - if ! base_modes=$(gh api "repos/${SOURCE_REPO}/git/trees/${merge_base_sha}?recursive=1" --jq 'if .truncated then error("base tree truncated") else [.tree[] | select(.type == "blob") | {key: .path, value: .mode}] | from_entries end'); then - echo "::notice::Could not verify base file modes; running review" - exit 0 - fi - if ! head_modes=$(gh api "repos/${SOURCE_REPO}/git/trees/${head_sha}?recursive=1" --jq 'if .truncated then error("head tree truncated") else [.tree[] | select(.type == "blob") | {key: .path, value: .mode}] | from_entries end'); then - echo "::notice::Could not verify head file modes; running review" + if ! decision="$("${dedup_cli}" review-dedup \ + --repo "${SOURCE_REPO}" \ + --pr "${PR_NUMBER}" \ + --app-set "${FULLSEND_APP_SET}" \ + --app-client-id "${REVIEW_APP_CLIENT_ID}")"; then + echo "::warning::Review deduplication CLI failed; running review" exit 0 fi - - base_modes_file=$(mktemp) || { - echo "::warning::Could not create a temporary base-mode file; running review" - exit 0 - } - head_modes_file=$(mktemp) || { - rm -f "${base_modes_file}" - echo "::warning::Could not create a temporary head-mode file; running review" - exit 0 - } - trap 'rm -f "${base_modes_file}" "${head_modes_file}"' EXIT - if ! printf '%s' "${base_modes}" >"${base_modes_file}" || ! printf '%s' "${head_modes}" >"${head_modes_file}"; then - echo "::warning::Could not persist file modes for canonicalization; running review" - exit 0 - fi - defaults_dir=".defaults" - if [[ -f .fullsend/.defaults/action.yml ]]; then - defaults_dir=".fullsend/.defaults" - elif [[ ! -f .defaults/.github/scripts/review-diff-hash.sh ]]; then - defaults_dir=".review-diff-defaults" - fi - if ! current_hash=$(printf '%s\n' "${file_json}" | "${defaults_dir}/.github/scripts/review-diff-hash.sh" "${base_modes_file}" "${head_modes_file}"); then - echo "::warning::Could not canonicalize PR file diffs; running review" - exit 0 - fi - if [[ -z "${current_hash}" ]]; then - echo "::notice::PR diff is incomplete or empty; running review" - exit 0 - fi - - if ! pr_after=$(gh api "repos/${SOURCE_REPO}/pulls/${PR_NUMBER}" --jq '{base_sha: .base.sha, head_sha: .head.sha}'); then - echo "::warning::Could not verify PR base/head after diff fetch; running review" - exit 0 - fi - base_after="$(printf '%s' "${pr_after}" | jq -r '.base_sha // ""')" - head_after="$(printf '%s' "${pr_after}" | jq -r '.head_sha // ""')" - if [[ -z "${base_after}" || -z "${head_after}" || "${base_before}" != "${base_after}" || "${head_before}" != "${head_after}" ]]; then - echo "::notice::PR base or head changed while fetching the diff; running review" - exit 0 - fi - current_head_sha="${head_after}" - current_base_sha="${base_after}" - - if ! prior_review=$(gh api "repos/${SOURCE_REPO}/issues/${PR_NUMBER}/comments" \ - --paginate --jq '.[]' \ - | jq --arg bot "${REVIEW_BOT}" --arg shared_bot "${SHARED_REVIEW_BOT}" \ - --arg custom_bot "${CUSTOM_REVIEW_BOT}" --arg client_id "${REVIEW_APP_CLIENT_ID}" -s -c ' - [.[] | select((.user.login == $bot or .user.login == $shared_bot - or ($custom_bot != "" and .user.login == $custom_bot)) - and (.body | contains("")) - and ($client_id != "" and (.performed_via_github_app.client_id // "") == $client_id))] - | sort_by(.created_at) | last // {}'); then - echo "::warning::Could not fetch the previous review; running review" - exit 0 - fi - if [[ -z "${prior_review}" || "${prior_review}" == "{}" ]]; then - echo "::notice::No app-verified previous review found; running review" - exit 0 - fi - prior_body="$(printf '%s' "${prior_review}" | jq -r '.body // ""')" - prior_url="$(printf '%s' "${prior_review}" | jq -r '.html_url // ""')" - - prior_section="${prior_body%%*}" - prior_hash="$(printf '%s\n' "${prior_section}" \ - | sed -nE 's/^$/\1/p' \ - | head -1 || true)" - if [[ -z "${prior_hash}" ]]; then - echo "::notice::Previous review has no complete diff hash; running review" - exit 0 - fi - prior_reviewed_head="$(printf '%s\n' "${prior_section}" \ - | sed -nE 's/^$/\1/p' \ - | head -1 || true)" - if [[ -z "${prior_reviewed_head}" ]]; then - echo "::notice::Previous review has no verified reviewed HEAD; running review" - exit 0 - fi - - if ! prior_formal_review=$(gh api "repos/${SOURCE_REPO}/pulls/${PR_NUMBER}/reviews" \ - --paginate --jq '.[]' \ - | jq --arg bot "${REVIEW_BOT}" --arg shared_bot "${SHARED_REVIEW_BOT}" \ - --arg custom_bot "${CUSTOM_REVIEW_BOT}" -s -c ' - [.[] | select((.user.login == $bot or .user.login == $shared_bot - or ($custom_bot != "" and .user.login == $custom_bot)) - and ((.submitted_at // "") != ""))] - | sort_by(.submitted_at) | last // {}'); then - echo "::warning::Could not determine the previous formal review verdict; running review" - exit 0 - fi - prior_state="$(printf '%s' "${prior_formal_review}" | jq -r '.state // ""')" - prior_commit_sha="$(printf '%s' "${prior_formal_review}" | jq -r '.commit_id // ""')" - if [[ "${prior_state}" != "APPROVED" || "${prior_commit_sha}" != "${prior_reviewed_head}" ]]; then - echo "::notice::No approved bot review for the reviewed diff; running review" - exit 0 - fi - - if [[ "${current_hash}" == "${prior_hash}" ]]; then - if ! final_pr=$(gh api "repos/${SOURCE_REPO}/pulls/${PR_NUMBER}" --jq '{base_sha: .base.sha, head_sha: .head.sha}'); then - echo "::warning::Could not verify PR base/head before skip; running review" - exit 0 - fi - final_base_sha="$(printf '%s' "${final_pr}" | jq -r '.base_sha // ""')" - final_head_sha="$(printf '%s' "${final_pr}" | jq -r '.head_sha // ""')" - if [[ "${final_base_sha}" != "${current_base_sha}" || "${final_head_sha}" != "${current_head_sha}" ]]; then - echo "::notice::PR base or head changed before skip; running review" - exit 0 - fi - echo "prior_url=${prior_url}" >> "${GITHUB_OUTPUT}" - echo "skip=true" >> "${GITHUB_OUTPUT}" - else - echo "::notice::PR effective diff changed; running review" - fi - + printf '%s\n' "${decision}" + while IFS='=' read -r key value; do + case "${key}" in + skip|prior_url) echo "${key}=${value}" >> "${GITHUB_OUTPUT}" ;; + esac + done <<< "${decision}" # CEL routing (#8726). A repository moves a built-in stage's routing # from the bash rules above to a CEL trigger by setting agents[].trigger # on the agent's entry in config.yaml; a harness trigger: never does. @@ -774,8 +936,10 @@ jobs: - name: Detect CEL route opt-in id: cel-opt-in # A fork or Dependabot PR on pull_request is never routed (see - # "Determine stage"), by CEL either: a maintainer comments /fs-review. - if: ${{ github.event_name == 'pull_request_target' || (github.event_name == 'pull_request' && (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) || github.event_name == 'issue_comment' || github.event_name == 'issues' }} + # "Determine stage"), by CEL either. A fork PR is routed through the + # workflow_run event the shim gets once the fork PR stub completes, + # as the pull_request event "Determine stage" rebuilt from the API. + if: ${{ github.event_name == 'pull_request_target' || (github.event_name == 'pull_request' && (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) || github.event_name == 'issue_comment' || github.event_name == 'issues' || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action != '') }} continue-on-error: true shell: bash env: @@ -784,8 +948,15 @@ jobs: COMMENT_BODY: ${{ github.event.comment.body }} ISSUE_IS_PR: ${{ github.event.issue.pull_request && 'true' || 'false' }} BASH_STAGE: ${{ steps.bash-route.outputs.stage }} + ROUTED_ACTION: ${{ steps.bash-route.outputs.event_action }} run: | set -euo pipefail + # A fork PR's workflow_run stands for the pull_request event + # "Determine stage" rebuilt (see "Resolve fork pull request"). + if [[ "${EVENT_NAME}" == "workflow_run" ]]; then + EVENT_NAME="pull_request" + EVENT_ACTION="${ROUTED_ACTION:-}" + fi # Pick the one agent whose CEL route covers this event, among those # `fullsend dispatch --route` supports (routableAgents in # internal/cli/dispatch_route.go), and only when bash chose that @@ -951,13 +1122,26 @@ jobs: uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/fullsend-cache - key: fullsend-cli-${{ steps.cel-cli-mode.outputs.mode }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + key: fullsend-cli-${{ steps.cel-cli-mode.outputs.mode }}-${{ runner.arch }}-${{ hashFiles('cel-route/.fullsend/bin/fullsend') }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + + - name: Validate cached fullsend CLI for CEL route + id: cel-cli-cache-validation + if: steps.cel-config.outcome == 'success' && steps.cel-cli-cache.outputs.cache-hit == 'true' + continue-on-error: true + shell: bash + run: | + set -euo pipefail + if [[ -x "${RUNNER_TEMP}/fullsend-cache/fullsend" ]] && "${RUNNER_TEMP}/fullsend-cache/fullsend" dispatch --help >/dev/null 2>&1; then + echo "valid=true" >> "${GITHUB_OUTPUT}" + else + echo "valid=false" >> "${GITHUB_OUTPUT}" + fi # Vendored installs copy the committed binary directly, so the step does # not depend on where the vendored defaults (.defaults/ or # .fullsend/.defaults/) live. - name: Install fullsend CLI for CEL route (vendored) - if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'vendored' && steps.cel-cli-cache.outputs.cache-hit != 'true' + if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'vendored' && (steps.cel-cli-cache.outputs.cache-hit != 'true' || steps.cel-cli-cache-validation.outputs.valid != 'true') continue-on-error: true shell: bash run: | @@ -972,7 +1156,7 @@ jobs: echo "${RUNNER_TEMP}/fullsend" >> "${GITHUB_PATH}" - name: Checkout upstream install action for CEL route - if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'upstream' && steps.cel-cli-cache.outputs.cache-hit != 'true' + if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'upstream' && (steps.cel-cli-cache.outputs.cache-hit != 'true' || steps.cel-cli-cache-validation.outputs.valid != 'true') continue-on-error: true uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -989,7 +1173,7 @@ jobs: # the trigger can come from a different agents ref than the one the # agent's job runs. - name: Install fullsend CLI for CEL route (upstream workflow) - if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'upstream' && steps.cel-cli-cache.outputs.cache-hit != 'true' + if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'upstream' && (steps.cel-cli-cache.outputs.cache-hit != 'true' || steps.cel-cli-cache-validation.outputs.valid != 'true') continue-on-error: true uses: ./.workflow-actions/.github/actions/install-fullsend-cli with: @@ -999,7 +1183,7 @@ jobs: github_token: ${{ github.token }} - name: Expose cached fullsend CLI for CEL route - if: steps.cel-config.outcome == 'success' && steps.cel-cli-cache.outputs.cache-hit == 'true' + if: steps.cel-config.outcome == 'success' && steps.cel-cli-cache-validation.outputs.valid == 'true' continue-on-error: true shell: bash run: | @@ -1008,24 +1192,25 @@ jobs: mkdir -p "${install_dir}" cp "${RUNNER_TEMP}/fullsend-cache/fullsend" "${install_dir}/fullsend" chmod +x "${install_dir}/fullsend" - echo "${install_dir}" >> "${GITHUB_PATH}" - name: Prepare fullsend CLI cache artifact for CEL route - if: steps.cel-config.outcome == 'success' && steps.cel-cli-cache.outputs.cache-hit != 'true' + id: cel-cli-cache-prepare + if: steps.cel-config.outcome == 'success' && (steps.cel-cli-cache.outputs.cache-hit != 'true' || steps.cel-cli-cache-validation.outputs.valid != 'true') continue-on-error: true shell: bash run: | set -euo pipefail mkdir -p "${RUNNER_TEMP}/fullsend-cache" cp "${RUNNER_TEMP}/fullsend/fullsend" "${RUNNER_TEMP}/fullsend-cache/fullsend" + "${RUNNER_TEMP}/fullsend-cache/fullsend" dispatch --help >/dev/null 2>&1 - name: Save fullsend CLI cache for CEL route - if: steps.cel-config.outcome == 'success' && steps.cel-cli-cache.outputs.cache-hit != 'true' + if: steps.cel-config.outcome == 'success' && (steps.cel-cli-cache.outputs.cache-hit != 'true' || steps.cel-cli-cache-validation.outputs.valid != 'true') && steps.cel-cli-cache-prepare.outcome == 'success' continue-on-error: true uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/fullsend-cache - key: fullsend-cli-${{ steps.cel-cli-mode.outputs.mode }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + key: fullsend-cli-${{ steps.cel-cli-mode.outputs.mode }}-${{ runner.arch }}-${{ hashFiles('cel-route/.fullsend/bin/fullsend') }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} - name: Evaluate CEL route id: cel-route @@ -1038,6 +1223,9 @@ jobs: EVENT_ACTION: ${{ inputs.event_action }} ROUTE_AGENT: ${{ steps.cel-opt-in.outputs.agent }} FULLSEND_MINT_URL: ${{ inputs.mint_url }} + FORK_PR_FILE: ${{ steps.fork-pr.outputs.pr_file }} + ROUTED_ACTION: ${{ steps.bash-route.outputs.event_action }} + ROUTED_SENDER: ${{ steps.bash-route.outputs.event_sender }} run: | set -euo pipefail # gha_text makes a value safe inside a ::notice::/::warning::/::error:: @@ -1051,7 +1239,21 @@ jobs: while [[ "${v}" == *::* ]]; do v=${v//::/: :}; done printf '%s' "${v}" } - DECISION_JSON=$(fullsend dispatch \ + # A fork PR's workflow_run is evaluated as the pull_request event + # "Determine stage" rebuilt from the API (see "Resolve fork pull + # request"): the PR as the API returns it, the action, and the + # author or closer as the sender. + if [[ "${GITHUB_EVENT_NAME:-}" == "workflow_run" ]]; then + FORK_PR_EVENT="$(dirname "${FORK_PR_FILE}")/event.json" + jq -n --slurpfile pr "${FORK_PR_FILE}" --arg action "${ROUTED_ACTION}" --arg sender "${ROUTED_SENDER}" ' + {action: $action, pull_request: $pr[0], + repository: $pr[0].base.repo, + sender: {login: $sender, type: (if ($sender | endswith("[bot]")) then "Bot" else "User" end)}}' > "${FORK_PR_EVENT}" + export GITHUB_EVENT_PATH="${FORK_PR_EVENT}" + export GITHUB_EVENT_NAME="pull_request" + EVENT_ACTION="${ROUTED_ACTION}" + fi + DECISION_JSON=$("${RUNNER_TEMP}/fullsend/fullsend" dispatch \ --input-driver gha-event \ --config-dir cel-route/.fullsend \ --event-action "${EVENT_ACTION}" \ @@ -1079,7 +1281,7 @@ jobs: env: BASH_STAGE: ${{ steps.bash-route.outputs.stage }} BASH_TRIGGER_SOURCE: ${{ steps.bash-route.outputs.trigger_source }} - CLOSED_PULL_REQUEST: ${{ (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'closed' }} + CLOSED_PULL_REQUEST: ${{ ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'closed') || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'closed') }} ROUTE_AGENT: ${{ steps.cel-opt-in.outputs.agent }} CEL_OPT_IN_OUTCOME: ${{ steps.cel-opt-in.outcome }} CEL_CONFIG_OUTCOME: ${{ steps.cel-config.outcome }} @@ -1158,7 +1360,7 @@ jobs: # Only obtain a write-capable review token after final routing has # authorized the review stage. The diff check above remains read-only. - name: Checkout upstream defaults for review skip note - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.defaults/action.yml', '.fullsend/.defaults/action.yml') == '' + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.defaults/action.yml', '.fullsend/.defaults/action.yml') == '' continue-on-error: true timeout-minutes: 2 uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -1173,7 +1375,7 @@ jobs: sparse-checkout-cone-mode: false - name: Prepare workspace for review skip note - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') == '' + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') == '' id: review-token-workspace continue-on-error: true timeout-minutes: 2 @@ -1185,12 +1387,12 @@ jobs: # .defaults path internally. Provide that compatibility path while # the action's defaults_root input is adopted by existing callers. - name: Stage nested defaults compatibility path - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') != '' + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') != '' shell: bash run: ln -s .fullsend/.defaults .defaults - name: Prepare workspace for review skip note (nested vendor) - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') != '' + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') != '' id: review-token-workspace-nested continue-on-error: true timeout-minutes: 2 @@ -1200,7 +1402,7 @@ jobs: source_repo: ${{ github.repository }} - name: Mint review token for review skip note - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') == '' && steps.review-token-workspace.outcome == 'success' + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') == '' && steps.review-token-workspace.outcome == 'success' id: review-token continue-on-error: true timeout-minutes: 2 @@ -1212,7 +1414,7 @@ jobs: mint_url: ${{ inputs.mint_url }} - name: Mint review token for review skip note (nested vendor) - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') != '' && steps.review-token-workspace-nested.outcome == 'success' + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' && hashFiles('.fullsend/.defaults/action.yml') != '' && steps.review-token-workspace-nested.outcome == 'success' id: review-token-nested continue-on-error: true timeout-minutes: 2 @@ -1225,17 +1427,15 @@ jobs: - name: Publish review skip note id: review-skip-publish - if: (github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' + if: ((github.event_name == 'pull_request_target' || github.event_name == 'pull_request') && inputs.event_action == 'synchronize' || (github.event_name == 'workflow_run' && steps.bash-route.outputs.event_action == 'synchronize')) && steps.route.outputs.stage == 'review' && steps.review-diff.outputs.skip == 'true' continue-on-error: true env: GH_TOKEN: ${{ steps.review-token.outputs.token || steps.review-token-nested.outputs.token || github.token }} REVIEW_TOKEN: ${{ steps.review-token.outputs.token || steps.review-token-nested.outputs.token }} SOURCE_REPO: ${{ github.repository }} - PR_NUMBER: ${{ github.event.pull_request.number }} - ORG_NAME: ${{ github.repository_owner }} + PR_NUMBER: ${{ github.event.pull_request.number || steps.fork-pr.outputs.number }} FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET || 'fullsend-ai' }} REVIEW_APP_CLIENT_ID: ${{ vars.FULLSEND_REVIEW_CLIENT_ID }} - REVIEW_PRIOR_URL: ${{ steps.review-diff.outputs.prior_url }} shell: bash run: | set -euo pipefail @@ -1244,33 +1444,25 @@ jobs: echo "::notice::Review-App token was unavailable; running the full review" exit 0 fi - skip_body=""$'\n'"Fullsend skipped this synchronize review because the effective diff is unchanged from the previous approved review${REVIEW_PRIOR_URL:+ (${REVIEW_PRIOR_URL})}. No new review findings were generated." - REVIEW_BOT="${ORG_NAME}-review[bot]" - SHARED_REVIEW_BOT="fullsend-ai-review[bot]" - CUSTOM_REVIEW_BOT="" - if [[ -n "${FULLSEND_APP_SET}" ]]; then - CUSTOM_REVIEW_BOT="${FULLSEND_APP_SET}-review[bot]" - fi - if ! status_comment_id="$(gh api "repos/${SOURCE_REPO}/issues/${PR_NUMBER}/comments" \ - --paginate --jq '.[]' \ - | jq --arg bot "${REVIEW_BOT}" --arg shared_bot "${SHARED_REVIEW_BOT}" \ - --arg custom_bot "${CUSTOM_REVIEW_BOT}" --arg client_id "${REVIEW_APP_CLIENT_ID}" -s -r ' - [.[] | select((.user.login == $bot or .user.login == $shared_bot - or ($custom_bot != "" and .user.login == $custom_bot)) - and (.body | startswith("")) - and ($client_id != "" and (.performed_via_github_app.client_id // "") == $client_id))] - | sort_by(.created_at) | last // {} | .id // ""' \ - | tail -1)"; then - echo "::warning::Could not verify an existing review-skip status note; running review" + dedup_cli="${RUNNER_TEMP}/fullsend-review-dedup/fullsend" + if [[ ! -x "${dedup_cli}" ]]; then + echo "::warning::Review deduplication CLI unavailable; running review" exit 0 fi - if [[ -n "${status_comment_id}" ]]; then - gh api --method PATCH "repos/${SOURCE_REPO}/issues/comments/${status_comment_id}" -f body="${skip_body}" >/dev/null - else - gh api --method POST "repos/${SOURCE_REPO}/issues/${PR_NUMBER}/comments" -f body="${skip_body}" >/dev/null + if ! decision="$("${dedup_cli}" review-dedup \ + --repo "${SOURCE_REPO}" \ + --pr "${PR_NUMBER}" \ + --app-set "${FULLSEND_APP_SET}" \ + --app-client-id "${REVIEW_APP_CLIENT_ID}" \ + --publish)"; then + echo "::warning::Review deduplication CLI failed to publish the skip note; running review" + exit 0 + fi + printf '%s\n' "${decision}" + if grep -qx 'skipped=true' <<<"${decision}"; then + echo "::notice::Skipping review after final routing: synchronize event has the same effective diff as the previous review" + echo "skipped=true" >> "${GITHUB_OUTPUT}" fi - echo "::notice::Skipping review after final routing: synchronize event has the same effective diff as the previous review" - echo "skipped=true" >> "${GITHUB_OUTPUT}" - name: Validate routed stage if: steps.route.outputs.stage != '' @@ -1483,7 +1675,9 @@ jobs: id: payload if: steps.route.outputs.stage != '' env: - PR_HEAD_JSON: ${{ steps.pr-head.outputs.pr_json }} + # A fork PR's workflow_run event carries no pull_request: merge the + # one "Resolve fork pull request for workflow_run" fetched. + PR_HEAD_JSON: ${{ steps.pr-head.outputs.pr_json || steps.fork-pr.outputs.pr_json }} run: | set -euo pipefail EVENT_PAYLOAD=$(jq -c '{ @@ -1848,7 +2042,7 @@ jobs: if: needs.route.outputs.stage == 'review' runs-on: ${{ inputs.runner_image }} concurrency: - group: fullsend-review-${{ github.repository }}-${{ github.event.pull_request.number || github.event.issue.number }} + group: fullsend-review-${{ github.repository }}-${{ github.event.pull_request.number || github.event.issue.number || needs.route.outputs.pr_number }} cancel-in-progress: true permissions: actions: write @@ -1879,6 +2073,115 @@ jobs: internal/scaffold/fullsend-repo/ action.yml + # The review job is separate from route, so it must install its own + # copy before using the CLI to supersede an earlier skip note. + - name: Detect review dedup CLI + id: review-cli-mode + continue-on-error: true + shell: bash + run: | + set -euo pipefail + if [[ -f .fullsend/bin/fullsend ]] && .fullsend/bin/fullsend review-dedup --help >/dev/null 2>&1; then + echo "mode=vendored" >> "${GITHUB_OUTPUT}" + else + echo "mode=upstream" >> "${GITHUB_OUTPUT}" + fi + + - name: Restore fullsend CLI cache for review job + id: review-job-cli-cache + if: steps.review-cli-mode.outputs.mode == 'upstream' + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/fullsend-cache + key: fullsend-review-dedup-cli-${{ steps.review-cli-mode.outputs.mode }}-${{ runner.arch }}-${{ hashFiles('.fullsend/bin/fullsend') }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + + - name: Validate cached fullsend CLI for review job + id: review-job-cli-cache-validation + if: steps.review-cli-mode.outputs.mode == 'upstream' && steps.review-job-cli-cache.outputs.cache-hit == 'true' + continue-on-error: true + shell: bash + run: | + set -euo pipefail + if [[ -x "${RUNNER_TEMP}/fullsend-cache/fullsend" ]] && "${RUNNER_TEMP}/fullsend-cache/fullsend" review-dedup --help >/dev/null 2>&1; then + echo "valid=true" >> "${GITHUB_OUTPUT}" + else + echo "valid=false" >> "${GITHUB_OUTPUT}" + fi + + - name: Install review dedup CLI (vendored) + if: steps.review-cli-mode.outputs.mode == 'vendored' + continue-on-error: true + shell: bash + run: | + set -euo pipefail + mkdir -p "${RUNNER_TEMP}/fullsend-review-dedup" + cp .fullsend/bin/fullsend "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" + chmod +x "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" + + - name: Checkout review dedup CLI installer + if: steps.review-cli-mode.outputs.mode == 'upstream' && (steps.review-job-cli-cache.outputs.cache-hit != 'true' || steps.review-job-cli-cache-validation.outputs.valid != 'true') + continue-on-error: true + timeout-minutes: 5 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + path: .review-dedup-actions + fetch-depth: 1 + sparse-checkout: | + .github/actions/install-fullsend-cli/ + sparse-checkout-cone-mode: false + + - name: Install review dedup CLI (upstream) + if: steps.review-cli-mode.outputs.mode == 'upstream' && (steps.review-job-cli-cache.outputs.cache-hit != 'true' || steps.review-job-cli-cache-validation.outputs.valid != 'true') + continue-on-error: true + timeout-minutes: 5 + uses: ./.review-dedup-actions/.github/actions/install-fullsend-cli + with: + mode: upstream + install_dir: ${{ runner.temp }}/fullsend-review-dedup + add_to_path: 'false' + source_dir: ${{ runner.temp }}/fullsend-review-dedup-src + workflow_repository: ${{ job.workflow_repository }} + workflow_sha: ${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + github_token: ${{ github.token }} + + - name: Expose cached fullsend CLI for review job + if: steps.review-cli-mode.outputs.mode == 'upstream' && steps.review-job-cli-cache-validation.outputs.valid == 'true' + continue-on-error: true + shell: bash + run: | + set -euo pipefail + install_dir="${RUNNER_TEMP}/fullsend-review-dedup" + mkdir -p "${install_dir}" + cp "${RUNNER_TEMP}/fullsend-cache/fullsend" "${install_dir}/fullsend" + chmod +x "${install_dir}/fullsend" + + - name: Prepare fullsend CLI cache artifact for review job + id: review-job-cli-cache-prepare + if: steps.review-cli-mode.outputs.mode == 'upstream' && (steps.review-job-cli-cache.outputs.cache-hit != 'true' || steps.review-job-cli-cache-validation.outputs.valid != 'true') + continue-on-error: true + shell: bash + run: | + set -euo pipefail + if [[ ! -x "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" ]]; then + echo "ready=false" >> "${GITHUB_OUTPUT}" + exit 0 + fi + mkdir -p "${RUNNER_TEMP}/fullsend-cache" + cp "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" "${RUNNER_TEMP}/fullsend-cache/fullsend" + "${RUNNER_TEMP}/fullsend-cache/fullsend" review-dedup --help >/dev/null 2>&1 + echo "ready=true" >> "${GITHUB_OUTPUT}" + + - name: Save fullsend CLI cache for review job + if: steps.review-cli-mode.outputs.mode == 'upstream' && (steps.review-job-cli-cache.outputs.cache-hit != 'true' || steps.review-job-cli-cache-validation.outputs.valid != 'true') && steps.review-job-cli-cache-prepare.outcome == 'success' && steps.review-job-cli-cache-prepare.outputs.ready == 'true' + continue-on-error: true + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/fullsend-cache + key: fullsend-review-dedup-cli-${{ steps.review-cli-mode.outputs.mode }}-${{ runner.arch }}-${{ hashFiles('.fullsend/bin/fullsend') }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + - name: Prepare workspace id: workspace uses: ./.defaults/.github/actions/prepare-workspace @@ -1931,37 +2234,23 @@ jobs: GH_TOKEN: ${{ steps.app-token.outputs.token }} SOURCE_REPO: ${{ github.repository }} PR_NUMBER: ${{ fromJSON(needs.route.outputs.event_payload).pull_request.number || fromJSON(needs.route.outputs.event_payload).issue.number }} - ORG_NAME: ${{ github.repository_owner }} FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET || 'fullsend-ai' }} REVIEW_APP_CLIENT_ID: ${{ vars.FULLSEND_REVIEW_CLIENT_ID }} REVIEW_HEAD_SHA: ${{ fromJSON(needs.route.outputs.event_payload).pull_request.head.sha || '' }} shell: bash run: | set -euo pipefail - REVIEW_BOT="${ORG_NAME}-review[bot]" - SHARED_REVIEW_BOT="fullsend-ai-review[bot]" - CUSTOM_REVIEW_BOT="" - if [[ -n "${FULLSEND_APP_SET}" ]]; then - CUSTOM_REVIEW_BOT="${FULLSEND_APP_SET}-review[bot]" - fi - if [[ ! "${REVIEW_HEAD_SHA}" =~ ^[0-9a-fA-F]{40,64}$ ]]; then - REVIEW_HEAD_SHA="unknown head" - fi - superseded_body=""$'\n'"Fullsend's earlier unchanged-diff skip note was superseded by a full review for commit ${REVIEW_HEAD_SHA}." - comment_ids=$(gh api "repos/${SOURCE_REPO}/issues/${PR_NUMBER}/comments" \ - --paginate --jq '.[]' \ - | jq --arg bot "${REVIEW_BOT}" --arg shared_bot "${SHARED_REVIEW_BOT}" \ - --arg custom_bot "${CUSTOM_REVIEW_BOT}" --arg client_id "${REVIEW_APP_CLIENT_ID}" -r -s ' - [.[] | select((.user.login == $bot or .user.login == $shared_bot - or ($custom_bot != "" and .user.login == $custom_bot)) - and (.body | startswith("")) - and ($client_id != "" and (.performed_via_github_app.client_id // "") == $client_id)) - | .id] | .[]' ) - while IFS= read -r comment_id; do - [[ -z "${comment_id}" ]] && continue - gh api --method PATCH "repos/${SOURCE_REPO}/issues/comments/${comment_id}" \ - -f body="${superseded_body}" >/dev/null - done <<<"${comment_ids}" + if [[ ! -x "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" ]]; then + echo "::warning::Review deduplication CLI unavailable; skipping supersede" + exit 0 + fi + "${RUNNER_TEMP}/fullsend-review-dedup/fullsend" review-dedup \ + --repo "${SOURCE_REPO}" \ + --pr "${PR_NUMBER}" \ + --app-set "${FULLSEND_APP_SET}" \ + --app-client-id "${REVIEW_APP_CLIENT_ID}" \ + --head-sha "${REVIEW_HEAD_SHA}" \ + --supersede - name: Setup agent environment env: @@ -2372,7 +2661,7 @@ jobs: if: needs.route.outputs.stage == 'retro' runs-on: ${{ inputs.runner_image }} concurrency: - group: fullsend-retro-${{ github.repository }}-${{ github.event.pull_request.number || github.event.issue.number }} + group: fullsend-retro-${{ github.repository }}-${{ github.event.pull_request.number || github.event.issue.number || needs.route.outputs.pr_number }} cancel-in-progress: true permissions: actions: write @@ -2651,8 +2940,11 @@ jobs: harness-dispatch: name: Harness dispatch # A fork or Dependabot PR on pull_request never dispatches (see - # "Determine stage" in the route job, #9221). - if: ${{ inputs.matrix == '' && (github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) }} + # "Determine stage" in the route job, #9221). Neither does the shim's + # workflow_run for a fork PR: `fullsend dispatch` has no mapping for + # that event, and the route job handles it for the built-in agents. A + # caller that passes a precomputed matrix skips this job anyway. + if: ${{ inputs.matrix == '' && github.event_name != 'workflow_run' && (github.event_name != 'pull_request' || (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && github.actor != 'dependabot[bot]')) }} runs-on: ${{ inputs.runner_image }} permissions: actions: write @@ -2735,10 +3027,23 @@ jobs: uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/fullsend-cache - key: fullsend-cli-${{ steps.mode.outputs.mode }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + key: fullsend-cli-${{ steps.mode.outputs.mode }}-${{ runner.arch }}-${{ hashFiles('.fullsend/bin/fullsend') }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + + - name: Validate cached fullsend CLI + if: steps.triggers.outputs.has_triggers == 'true' && steps.cli-cache.outputs.cache-hit == 'true' + id: cli-cache-validation + continue-on-error: true + shell: bash + run: | + set -euo pipefail + if [[ -x "${RUNNER_TEMP}/fullsend-cache/fullsend" ]] && "${RUNNER_TEMP}/fullsend-cache/fullsend" dispatch --help >/dev/null 2>&1; then + echo "valid=true" >> "${GITHUB_OUTPUT}" + else + echo "valid=false" >> "${GITHUB_OUTPUT}" + fi - name: Install fullsend CLI (vendored defaults) - if: steps.triggers.outputs.has_triggers == 'true' && steps.mode.outputs.mode == 'vendored' && steps.cli-cache.outputs.cache-hit != 'true' + if: steps.triggers.outputs.has_triggers == 'true' && steps.mode.outputs.mode == 'vendored' && (steps.cli-cache.outputs.cache-hit != 'true' || steps.cli-cache-validation.outputs.valid != 'true') uses: ./.defaults/.github/actions/install-fullsend-cli with: mode: vendored @@ -2746,7 +3051,7 @@ jobs: github_token: ${{ github.token }} - name: Checkout upstream install action - if: steps.triggers.outputs.has_triggers == 'true' && steps.mode.outputs.mode == 'upstream' && steps.cli-cache.outputs.cache-hit != 'true' + if: steps.triggers.outputs.has_triggers == 'true' && steps.mode.outputs.mode == 'upstream' && (steps.cli-cache.outputs.cache-hit != 'true' || steps.cli-cache-validation.outputs.valid != 'true') uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: ${{ job.workflow_repository }} @@ -2758,7 +3063,7 @@ jobs: sparse-checkout-cone-mode: false - name: Install fullsend CLI (upstream workflow) - if: steps.triggers.outputs.has_triggers == 'true' && steps.mode.outputs.mode == 'upstream' && steps.cli-cache.outputs.cache-hit != 'true' + if: steps.triggers.outputs.has_triggers == 'true' && steps.mode.outputs.mode == 'upstream' && (steps.cli-cache.outputs.cache-hit != 'true' || steps.cli-cache-validation.outputs.valid != 'true') uses: ./.workflow-actions/.github/actions/install-fullsend-cli with: mode: upstream @@ -2767,7 +3072,7 @@ jobs: github_token: ${{ github.token }} - name: Expose cached fullsend CLI - if: steps.triggers.outputs.has_triggers == 'true' && steps.cli-cache.outputs.cache-hit == 'true' + if: steps.triggers.outputs.has_triggers == 'true' && steps.cli-cache-validation.outputs.valid == 'true' shell: bash run: | set -euo pipefail @@ -2778,19 +3083,21 @@ jobs: echo "${install_dir}" >> "${GITHUB_PATH}" - name: Prepare fullsend CLI cache artifact - if: steps.triggers.outputs.has_triggers == 'true' && steps.cli-cache.outputs.cache-hit != 'true' + if: steps.triggers.outputs.has_triggers == 'true' && (steps.cli-cache.outputs.cache-hit != 'true' || steps.cli-cache-validation.outputs.valid != 'true') + id: cli-cache-prepare shell: bash run: | set -euo pipefail mkdir -p "${RUNNER_TEMP}/fullsend-cache" cp "${RUNNER_TEMP}/fullsend/fullsend" "${RUNNER_TEMP}/fullsend-cache/fullsend" + "${RUNNER_TEMP}/fullsend-cache/fullsend" dispatch --help >/dev/null 2>&1 - name: Save fullsend CLI cache - if: steps.triggers.outputs.has_triggers == 'true' && steps.cli-cache.outputs.cache-hit != 'true' + if: steps.triggers.outputs.has_triggers == 'true' && (steps.cli-cache.outputs.cache-hit != 'true' || steps.cli-cache-validation.outputs.valid != 'true') && steps.cli-cache-prepare.outcome == 'success' uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/fullsend-cache - key: fullsend-cli-${{ steps.mode.outputs.mode }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} + key: fullsend-cli-${{ steps.mode.outputs.mode }}-${{ runner.arch }}-${{ hashFiles('.fullsend/bin/fullsend') }}-${{ (github.event_name == 'pull_request' && job.workflow_sha == github.sha && github.event.pull_request.base.sha || job.workflow_sha) }} - name: Run fullsend dispatch id: dispatch diff --git a/.github/workflows/reusable-poll-jira.yml b/.github/workflows/reusable-poll-jira.yml index 0bbe60e618..91252c17dd 100644 --- a/.github/workflows/reusable-poll-jira.yml +++ b/.github/workflows/reusable-poll-jira.yml @@ -6,30 +6,36 @@ # - Optional secrets: FULLSEND_JIRA_TOKEN / FULLSEND_JIRA_EMAIL for API-token # authentication, or FULLSEND_JIRA_CLIENT_ID / FULLSEND_JIRA_CLIENT_SECRET # for OAuth 2.0 client credentials. The Jira client validates the pair. -# - Optional inputs: runner_image (runner for the poll job) and timeout_minutes -# (job timeout; defaults to 15 minutes and can be raised by the caller). +# - Optional secrets FULLSEND_JIRA_WRITE_GROUPS, FULLSEND_JIRA_WRITE_ACCOUNTS, +# FULLSEND_JIRA_TRIAGE_GROUPS and FULLSEND_JIRA_TRIAGE_ACCOUNTS: the jira +# authorization lists that .fullsend/config.yaml reads with groups_from and +# accounts_from, so the lists stay out of a public repository (#9132). +# - Optional inputs: runner_image (runner for both jobs) and timeout_minutes +# (timeout of each job; defaults to 15 minutes and can be raised by the +# caller). # - Output: matrix is the JSON include matrix for reusable-dispatch.yml; an -# empty include array means there were no Jira issues to dispatch. +# empty include array means there were no Jira issues to dispatch. The matrix +# job sets it, not the poll job (see the comment on that job). # Runs `fullsend poll --input-driver jira-poll` against the caller's # .fullsend/config.yaml and returns the dispatch matrix to the caller. The # caller passes it to reusable-dispatch.yml at the same ref (ADR 62). # The poll normally completes within 15 minutes; the caller controls the job # timeout through timeout_minutes to account for its runner and Jira latency. # -# Security: Jira credentials reach only the poll step. They are never -# forwarded to agents or the runner-secret bundle. +# Security: Jira credentials reach only the poll and check steps. They are +# never forwarded to agents or the runner-secret bundle. name: Jira poll on: workflow_call: inputs: runner_image: - description: GitHub Actions runner image for the poll job. + description: GitHub Actions runner image for the Jira poll jobs. type: string required: false default: "ubuntu-24.04" timeout_minutes: - description: Maximum runtime in minutes for the Jira poll job. + description: Maximum runtime in minutes for each Jira poll job. type: number required: false default: 15 @@ -42,10 +48,18 @@ on: required: false FULLSEND_JIRA_CLIENT_SECRET: required: false + FULLSEND_JIRA_WRITE_GROUPS: + required: false + FULLSEND_JIRA_WRITE_ACCOUNTS: + required: false + FULLSEND_JIRA_TRIAGE_GROUPS: + required: false + FULLSEND_JIRA_TRIAGE_ACCOUNTS: + required: false outputs: matrix: description: Dispatch matrix accepted by reusable-dispatch.yml. - value: ${{ jobs.poll.outputs.matrix }} + value: ${{ jobs.matrix.outputs.matrix || '{"include":[]}' }} jobs: poll: @@ -55,7 +69,8 @@ jobs: permissions: contents: read outputs: - matrix: ${{ steps.matrix.outputs.matrix }} + dispatch_count: ${{ steps.check.outputs.count }} + artifact_suffix: ${{ steps.check.outputs.artifact_suffix }} steps: - name: Checkout caller repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -104,6 +119,12 @@ jobs: FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + # The poller reads these only when config.yaml names them with + # groups_from or accounts_from, and never prints them. + FULLSEND_JIRA_WRITE_GROUPS: ${{ secrets.FULLSEND_JIRA_WRITE_GROUPS }} + FULLSEND_JIRA_WRITE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_WRITE_ACCOUNTS }} + FULLSEND_JIRA_TRIAGE_GROUPS: ${{ secrets.FULLSEND_JIRA_TRIAGE_GROUPS }} + FULLSEND_JIRA_TRIAGE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_TRIAGE_ACCOUNTS }} TARGET_REPO: ${{ github.repository }} run: | set -euo pipefail @@ -113,16 +134,95 @@ jobs: --output dispatches.json \ --fullsend-dir .fullsend + # The matrix job has no secrets, so GitHub no longer blocks a Jira + # credential in its output. Check for one here instead. + - name: Check dispatches + id: check + env: + FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }} + FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} + FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} + FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + run: | + set -euo pipefail + jq -e 'type == "array"' dispatches.json > /dev/null + # JSON escapes characters such as quotes, so search the decoded + # strings, not the file. + jq -r '.. | strings' dispatches.json > dispatch-strings.txt + for name in FULLSEND_JIRA_TOKEN FULLSEND_JIRA_EMAIL FULLSEND_JIRA_CLIENT_ID FULLSEND_JIRA_CLIENT_SECRET; do + # Trim the value as the CLI does. An empty grep pattern matches + # every line, and a padded one matches nothing. + value="$(sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e '/^$/d' <<< "${!name}")" + if [[ -n "${value}" ]] && grep -qF -f <(printf '%s\n' "${value}") dispatch-strings.txt; then + echo "::error::dispatches.json contains ${name}; not passing it on." + exit 1 + fi + done + # A run can call this workflow more than once, and artifact names are + # unique per run, so each call names its artifact with its own suffix. + echo "artifact_suffix=$(openssl rand -hex 8)" >> "${GITHUB_OUTPUT}" + echo "count=$(jq length dispatches.json)" >> "${GITHUB_OUTPUT}" + + # The poller has already advanced its Jira checkpoints, so a failed + # upload would lose this cycle's dispatches. Try it twice. + - name: Save dispatches + id: save + if: ${{ steps.check.outputs.count != '0' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fullsend-jira-dispatches-${{ steps.check.outputs.artifact_suffix }} + path: dispatches.json + if-no-files-found: error + retention-days: 1 + overwrite: true + + - name: Save dispatches (second try) + if: ${{ steps.save.outcome == 'failure' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fullsend-jira-dispatches-${{ steps.check.outputs.artifact_suffix }} + path: dispatches.json + if-no-files-found: error + retention-days: 1 + overwrite: true + + # Builds the matrix in a job without secrets. GitHub drops a job output that + # contains the value of a secret the job has, and the matrix holds the ID of + # the account that acted, which can equal a list secret such as + # FULLSEND_JIRA_WRITE_ACCOUNTS. + matrix: + name: Build dispatch matrix + needs: poll + # "!= '0'", not "> 0": an empty (dropped) count still runs this job. + if: ${{ needs.poll.outputs.dispatch_count != '0' }} + runs-on: ${{ inputs.runner_image }} + timeout-minutes: ${{ inputs.timeout_minutes }} + permissions: {} + outputs: + matrix: ${{ steps.matrix.outputs.matrix }} + steps: + # If both tries fail, "Re-run failed jobs" reads the artifact again + # while it is kept (1 day). "Re-run all jobs" would poll again and find + # nothing. + - name: Read dispatches + id: read + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: fullsend-jira-dispatches-${{ needs.poll.outputs.artifact_suffix }} + + - name: Read dispatches (second try) + if: ${{ steps.read.outcome == 'failure' }} + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: fullsend-jira-dispatches-${{ needs.poll.outputs.artifact_suffix }} + - name: Build dispatch matrix id: matrix run: | set -euo pipefail - jq -e 'type == "array"' dispatches.json > /dev/null - if jq -e 'length == 0' dispatches.json > /dev/null; then - echo "No dispatches." - echo 'matrix={"include":[]}' >> "${GITHUB_OUTPUT}" - exit 0 - fi + jq -e 'type == "array" and length > 0' dispatches.json > /dev/null MATRIX=$(jq -c '{include: .}' dispatches.json) DELIM="MATRIX_$(openssl rand -hex 8)" { diff --git a/.github/workflows/runner-image.yml b/.github/workflows/runner-image.yml index faf9e1790b..1ef7b8f21e 100644 --- a/.github/workflows/runner-image.yml +++ b/.github/workflows/runner-image.yml @@ -14,6 +14,8 @@ on: - ".dockerignore" - ".github/workflows/runner-image.yml" - ".github/scripts/openshell-version.sh" + - "internal/security/mlscan*.go" + - "internal/security/onnxguard*.go" - go.mod - go.sum pull_request: @@ -22,6 +24,8 @@ on: - ".dockerignore" - ".github/workflows/runner-image.yml" - ".github/scripts/openshell-version.sh" + - "internal/security/mlscan*.go" + - "internal/security/onnxguard*.go" - go.mod - go.sum workflow_dispatch: @@ -165,10 +169,19 @@ jobs: # Regression guard: a SAFE verdict returns no INJECTION label, # which the scanner once treated as a fail-closed error. - benign=$(EVENT_PAYLOAD="{\"issue\":{\"body\":\"The CLI panics when the config file is missing.\"}}" \ + # Runs without the image ENV to test the ORT telemetry opt-out + # in the binary itself (#9777). + benign=$(env -u ORT_DISABLE_TELEMETRY EVENT_PAYLOAD="{\"issue\":{\"body\":\"The CLI panics when the config file is missing.\"}}" \ fullsend scan input 2>&1 || true) echo "${benign}" | grep -q "no findings" \ || fail "ML scan flagged benign input: ${benign}" + ! echo "${benign}" | grep -q "ML scanner unavailable" \ + || fail "ML scanner did not start: ${benign}" + + # ORT writes a device ID and event store here when its + # telemetry uploader starts. + test ! -e "${HOME}/.cache/Microsoft" \ + || fail "ONNX Runtime telemetry started: ${HOME}/.cache/Microsoft exists" ' # Push this platform's image by digest, gated on the smoke test diff --git a/.github/workflows/safe-settings.yml b/.github/workflows/safe-settings.yml new file mode 100644 index 0000000000..42471b17da --- /dev/null +++ b/.github/workflows/safe-settings.yml @@ -0,0 +1,217 @@ +# Environment configuration via safe-settings full-sync, scoped to this +# repository only (config under .github/safe-settings/). Everything else -- +# rulesets, repository settings -- stays managed by the org repo's +# safe-settings run. +# +# No pull_request trigger: full-sync needs the governance App private key, +# and a PR must never be able to run code that holds it. Validation happens +# through a workflow_dispatch dry run (dry_run defaults to true) before the +# first real apply; the daily schedule then reconciles drift. +name: safe-settings + +on: + schedule: + - cron: '0 8 * * *' # daily reconcile against drift; offset from the org run + workflow_dispatch: + inputs: + dry_run: + description: 'Log what would change without applying (FULL_SYNC_NOP)' + type: boolean + default: true + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +env: + # Pinned to the commit the 3.0.0 tag pointed at; tags are mutable. + SAFE_SETTINGS_VERSION: a9a1f366ad6a738b55682d346d94f8d6c4893b09 # 3.0.0 + SAFE_SETTINGS_CODE_DIR: ${{ github.workspace }}/.safe-settings-code + # Points safe-settings at our deployment config so the sync is restricted + # to this repository (restrictedRepos.include). + DEPLOYMENT_CONFIG_FILE: ${{ github.workspace }}/.github/safe-settings/deployment-settings.yml + +jobs: + apply: + # Main only: a dispatch from another branch would apply main's config + # with that branch's repo scoping. + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: github-community-projects/safe-settings + ref: ${{ env.SAFE_SETTINGS_VERSION }} + path: ${{ env.SAFE_SETTINGS_CODE_DIR }} + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version-file: ${{ env.SAFE_SETTINGS_CODE_DIR }}/.nvmrc + - run: npm ci --ignore-scripts + working-directory: ${{ env.SAFE_SETTINGS_CODE_DIR }} + # Fail closed: if the deployment config is missing or no longer scoped + # to exactly this repo, safe-settings falls back to a denylist and the + # total-state sync would reach every org repo. + - name: Verify repo scoping + run: | + python3 - <<'EOF' + import os, sys, yaml + path = os.environ["DEPLOYMENT_CONFIG_FILE"] + with open(path) as f: + cfg = yaml.safe_load(f) or {} + include = (cfg.get("restrictedRepos") or {}).get("include") + if include != ["fullsend"]: + sys.exit(f"restrictedRepos.include is {include!r}, expected ['fullsend']") + EOF + # Fail closed: if settings.yml lost its environments key (e.g. a YAML + # indentation slip), the total-state sync would delete every environment. + - name: Verify environments config + run: | + python3 - <<'EOF' + import sys, yaml + with open(".github/safe-settings/settings.yml") as f: + cfg = yaml.safe_load(f) + if not isinstance(cfg, dict) or not isinstance(cfg.get("environments"), list): + sys.exit("settings.yml must be a mapping with an 'environments' list") + EOF + # safe-settings 3.0.0's environments plugin discards its NopCommands, + # so FULL_SYNC_NOP cannot report environment drift. Compute the diff + # here, read-only, so dry runs have something trustworthy to review. + # Compares every attribute the environments plugin reconciles, with + # omitted config fields treated as the plugin's defaults. + - name: Report environment drift + working-directory: ${{ env.SAFE_SETTINGS_CODE_DIR }} + env: + APP_ID: ${{ vars.GOVERNANCE_APP_ID }} + PRIVATE_KEY: ${{ secrets.GOVERNANCE_PRIVATE_KEY }} + SETTINGS_PATH: ${{ github.workspace }}/.github/safe-settings/settings.yml + run: | + node <<'EOF' + const fs = require("fs"); + const yaml = require("js-yaml"); + const { App } = require("octokit"); + + const ORG = "fullsend-ai"; + const REPO = "fullsend"; + + // Canonical view of one environment, covering every attribute the + // safe-settings environments plugin reconciles. Omitted config + // fields use the same defaults the plugin applies (getChanged). + // Config reviewers are {id, type}; the live API nests the ID under + // protection_rules[].reviewers[].reviewer. Normalize both to {id, type}. + function canonicalReviewers(list) { + return (list || []) + .map(r => ({ id: r.reviewer ? r.reviewer.id : r.id, type: r.type })) + .filter(r => r.id !== undefined) + .sort((a, b) => a.id - b.id); + } + function canonical(env) { + const rule = (env.protection_rules || []).find(r => r.type === "wait_timer"); + const reviewers = (env.protection_rules || []).find(r => r.type === "required_reviewers"); + const pol = env.deployment_branch_policy; + // Config policies are either plain strings or {type, names: [...]}; + // expand both forms into one {name, type} per policy. + const policies = (pol && pol.custom_branch_policies || []).flatMap(p => + typeof p === "string" + ? [{ name: p, type: "branch" }] + : (p.names || [p.name]).map(n => ({ name: n, type: p.type })) + ); + return JSON.stringify({ + wait_timer: (env.wait_timer !== undefined ? env.wait_timer : (rule || {}).wait_timer) || 0, + prevent_self_review: !!(env.prevent_self_review !== undefined ? env.prevent_self_review : (reviewers || {}).prevent_self_review), + reviewers: canonicalReviewers(env.reviewers || (reviewers || {}).reviewers), + variables: (env.variables || []).map(v => ({ name: v.name.toLowerCase(), value: v.value })).sort((a, b) => a.name.localeCompare(b.name)), + deployment_protection_rules: (env.deployment_protection_rules || []).map(r => ({ app_id: r.app_id })).sort((a, b) => a.app_id - b.app_id), + deployment_branch_policy: pol === null || pol === undefined + ? null + : { + protected_branches: !!pol.protected_branches, + custom_branch_policies: policies + .filter(p => p.name !== undefined) + .sort((a, b) => String(a.name).localeCompare(String(b.name))) + } + }); + } + + async function main() { + const desired = yaml.load(fs.readFileSync(process.env.SETTINGS_PATH, "utf8")).environments; + const app = new App({ appId: process.env.APP_ID, privateKey: process.env.PRIVATE_KEY }); + const installations = await app.octokit.request("GET /app/installations"); + const inst = installations.data.find(i => i.account.login === ORG); + if (!inst) throw new Error(`no app installation for ${ORG}`); + const octokit = await app.getInstallationOctokit(inst.id); + + const live = await octokit.paginate( + "GET /repos/{owner}/{repo}/environments", + { owner: ORG, repo: REPO }, + r => r.data + ); + for (const env of live) { + if (env.deployment_branch_policy && env.deployment_branch_policy.custom_branch_policies) { + const pols = await octokit.paginate( + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", + { owner: ORG, repo: REPO, environment_name: env.name } + ); + env.deployment_branch_policy.custom_branch_policies = pols.map(p => ({ name: p.name, type: p.type })); + } + env.variables = await octokit.paginate( + "GET /repos/{owner}/{repo}/environments/{environment_name}/variables", + { owner: ORG, repo: REPO, environment_name: env.name, per_page: 100 }, + r => Array.isArray(r.data) ? r.data : (r.data.variables || []) + ); + const dpr = await octokit.request( + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules", + { owner: ORG, repo: REPO, environment_name: env.name } + ); + env.deployment_protection_rules = dpr.data.custom_deployment_protection_rules.map(r => ({ app_id: r.app.id })); + } + + const lines = []; + const extra = live.map(e => e.name).filter(n => !desired.some(d => d.name === n)); + const missing = desired.map(d => d.name).filter(n => !live.some(e => e.name === n)); + if (extra.length) lines.push(` delete (live only, removed on apply): ${extra.join(", ")}`); + if (missing.length) lines.push(` create (config only): ${missing.join(", ")}`); + for (const d of desired) { + const l = live.find(e => e.name === d.name); + if (!l) continue; + const want = canonical(d); + const have = canonical(l); + if (want !== have) { + lines.push(` update ${d.name}: differs`); + // Log only variable names that changed; values may not be + // meant for public Actions logs. + const wantVars = new Map(JSON.parse(want).variables.map(v => [v.name, v.value])); + const haveVars = new Map(JSON.parse(have).variables.map(v => [v.name, v.value])); + const varChanges = []; + for (const n of new Set([...wantVars.keys(), ...haveVars.keys()])) { + if (!haveVars.has(n)) varChanges.push(`+${n}`); + else if (!wantVars.has(n)) varChanges.push(`-${n}`); + else if (wantVars.get(n) !== haveVars.get(n)) varChanges.push(`~${n}`); + } + if (varChanges.length) lines.push(` variables: ${varChanges.join(", ")}`); + } + } + if (lines.length === 0) { + console.log("Environment drift: none"); + } else { + console.log("Environment drift:"); + for (const line of lines) console.log(line); + } + } + main().catch(e => { console.error(e); process.exit(1); }); + EOF + - run: npm run full-sync + working-directory: ${{ env.SAFE_SETTINGS_CODE_DIR }} + env: + GH_ORG: fullsend-ai + APP_ID: ${{ vars.GOVERNANCE_APP_ID }} + PRIVATE_KEY: ${{ secrets.GOVERNANCE_PRIVATE_KEY }} + ADMIN_REPO: fullsend + CONFIG_PATH: .github/safe-settings + FULL_SYNC_NOP: ${{ inputs.dry_run && 'true' || 'false' }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0349e77620..44a451b8f5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -34,7 +34,7 @@ repos: hooks: - id: ty name: ty check - entry: uvx ty@0.0.99 check --ignore import-not-found --ignore unresolved-attribute + entry: uvx ty@0.0.109 check --ignore import-not-found --ignore missing-attribute --ignore missing-union-attribute language: system types: [python] @@ -85,7 +85,7 @@ repos: pass_filenames: false - repo: https://github.com/rhysd/actionlint - rev: v1.7.11 + rev: v1.7.12 hooks: - id: actionlint files: | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6a09b83c08..cd233d7f77 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,6 +53,9 @@ contribution. lines you changed. Tables, code blocks, headings, and long URLs are exceptions. See [Documentation § Line wrapping](docs/contributing/documentation.md#line-wrapping). +- Every PR must pass the required `behaviour-github-emulator` check. To find + why it failed and re-run it, see + [Behaviour testing § On a pull request](docs/guides/dev/behaviour-testing.md#on-a-pull-request). - Keep PRs focused. One problem area or decision per PR is easier to review than a grab-bag. - If your change touches a problem doc, make sure the "Open questions" section still makes sense after your edit. diff --git a/LADDER.md b/LADDER.md index 67191fbf44..ed8a6e18ba 100644 --- a/LADDER.md +++ b/LADDER.md @@ -73,8 +73,9 @@ repository. - Pull requests from any author, forks included, run the behaviour and playback scenarios on the GitHub emulator automatically (the required `behaviour-github-emulator` check). - `/ok-to-test `, from someone with the Write role, authorizes only - the optional Forgejo behaviour suite on your PRs. + `/ok-to-test `, from someone with the Write role, authorizes the + optional Forgejo behaviour suite on your PRs; `/ok-to-test live` + also runs the live behaviour and playback suites. **Criteria:** @@ -123,6 +124,9 @@ repository. a `/ok-to-test ` comment for it, which you may post yourself. The required `behaviour-github-emulator` check needs no authorization: every PR, forks included, runs it +- Running the live behaviour and playback suites on a PR, by commenting + `/ok-to-test live` (reported as `behaviour-live` and + `playback-live`) **Criteria:** diff --git a/Makefile b/Makefile index e4e9e0f2e1..6e8d860500 100644 --- a/Makefile +++ b/Makefile @@ -90,7 +90,7 @@ lint-all: ensure-hooks check: uvx ruff@0.15.7 check . - uvx ty@0.0.99 check hack/ + uvx ty@0.0.109 check hack/ fmt: uvx ruff@0.15.7 format . @@ -196,7 +196,6 @@ script-test: $(call run-timed,bash .github/scripts/check-fix-eligibility-test.sh) $(call run-timed,bash .github/scripts/count-fix-commits-test.sh) $(call run-timed,bash .github/scripts/pre-fetch-review-body-test.sh) - $(call run-timed,bash .github/scripts/review-diff-hash-test.sh) $(call run-timed,bash .github/scripts/report-agent-startup-failure-test.sh) $(call run-timed,bash .github/scripts/retry-with-backoff-test.sh) $(call run-timed,bash scripts/check-agents-gate-pin-test.sh) @@ -287,6 +286,10 @@ ci-local: # on demand with fetch-allowlist-gate added to BEHAVIOUR_CAPABILITIES, on # dev against the fix or on stage once it is on main; when that passes, # declare it here (#9291). +# fork-pr-workflow-run (features/dispatch/fork-bash-routing.feature) needs +# GitHub's workflow_run event, which the GitHub emulator does not send. Like +# fetch-allowlist-gate it is not declared until its scenario has passed one +# live run; run it on demand with fork-pr-workflow-run added. BEHAVIOUR_CAPABILITIES ?= runtime-pi,inference-gateway,inference-gateway-api-key,runner-secret-overlay-guard # Runs through scripts/run-with-infra-retry.sh: a failed attempt whose diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 1ac07ab0fe..2e45987978 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -234,6 +234,7 @@ export default defineConfig({ { text: "fullsend inference", link: "/cli/inference" }, { text: "fullsend lint", link: "/cli/lint" }, { text: "fullsend mint", link: "/cli/mint" }, + { text: "fullsend prepare", link: "/cli/prepare" }, { text: "fullsend repos", link: "/cli/repos" }, { text: "fullsend run", link: "/cli/run" }, { text: "fullsend self-update", link: "/cli/self-update" }, diff --git a/docs/ADRs/0007-per-role-github-apps.md b/docs/ADRs/0007-per-role-github-apps.md index 17d0eba9e1..5611a9ada3 100644 --- a/docs/ADRs/0007-per-role-github-apps.md +++ b/docs/ADRs/0007-per-role-github-apps.md @@ -18,6 +18,12 @@ Date: 2026-04-02 Accepted +**Read-only token sharing:** +[ADR 0071](0071-share-github-api-cache-with-read-only-mint-tokens.md) +introduces a limited exception: roles authorized for identical read +permissions and scope may share a minted token; write credentials remain +per-role. + ## Context Agents need forge credentials to act on repos. A single shared credential for all agent roles violates least-privilege: a review agent would hold write permissions it should never use. The identity model must scope permissions per role while keeping setup automatable. See [agent-architecture.md](../problems/agent-architecture.md) and [security-threat-model.md](../problems/security-threat-model.md). diff --git a/docs/ADRs/0063-polling-based-work-discovery.md b/docs/ADRs/0063-polling-based-work-discovery.md index 81c97c5a54..bf7af21111 100644 --- a/docs/ADRs/0063-polling-based-work-discovery.md +++ b/docs/ADRs/0063-polling-based-work-discovery.md @@ -49,6 +49,15 @@ on candidates whose Jira `updated` is newer than their checkpoint, and M and N become configurable within bounds. The lock protocol and the random pick among candidates remain. +[ADR 0085](0085-serve-every-changed-jira-issue.md) partially +supersedes the coordination decisions below for the `jira-poll` driver. One +poller runs per repository, and issues that changed within the driver's +backfill window are served, oldest change first by default, up to a +per-cycle dispatch limit. The row limit on the candidate pool, the random pick, and the +per-issue lock are replaced, together with what depends on the lock (the lock +held during agent runs, the lock settings, the lock handling of +`fullsend poll cancel`, and the expectation of several concurrent pollers). + ## Context Fullsend's primary dispatch path is **event-driven**: forge webhooks are normalized diff --git a/docs/ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md b/docs/ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md new file mode 100644 index 0000000000..1d34511753 --- /dev/null +++ b/docs/ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md @@ -0,0 +1,135 @@ +--- +title: "71. Share GitHub API caching through ghproxy and read-only mint tokens" +status: Accepted +relates_to: + - agent-infrastructure + - agent-architecture + - security-threat-model +topics: + - github + - caching + - mint + - least-privilege +--- + +# 71. Share GitHub API caching through ghproxy and read-only mint tokens + +Date: 2026-11-02 + +## Status + +Accepted + +## Context + +Different agents and processes fetch the same GitHub entities, spending API +quota repeatedly (see [agent infrastructure](../problems/agent-infrastructure.md)). +Fullsend already keeps an ETag cache for selected GETs within each +[`LiveClient`][client-code], but separate clients cannot share it. +[ghproxy][ghproxy] shares an HTTP response cache across clients; +[ghcache][ghcache] revalidates cached responses with conditional requests and +coalesces concurrent reads. Authenticated, unchanged responses returning +`304` do not consume GitHub's [primary REST rate limit][github-limits]. + +ghproxy [partitions caches by the authorization header][ghcache-code], so +independently minted tokens fragment the cache even when they grant identical +access. The current [`mintToken`][mint-code] selects the requested role's App +and creates a token per request. This builds on the named permission levels +in [ADR 0073](0073-named-mint-privilege-levels.md) and introduces a narrow +read-only sharing exception to the per-role identities in +[ADR 0007](0007-per-role-github-apps.md). It complements the discovery-query +coalescing in [ADR 0149](0149-coalesce-entity-source-discovery-queries.md). +Sharing credentials must preserve the authorization boundaries described in +[agent architecture](../problems/agent-architecture.md) and the +[security threat model](../problems/security-threat-model.md). + +This ADR aims to conserve GitHub API quota across agents and processes by +sharing response caches and equivalent read-only credentials without widening +any caller's authorized access. + +## Options + +### Process-level caching + +Keep cached responses within each Fullsend process, extending the existing +client cache where useful. This avoids another service and keeps credential +lifetimes unchanged, but separate agents and processes still fetch and cache +the same entities independently; restarting a process also loses its cache. +It saves quota within a process without addressing reuse across processes. + +### ghproxy without further Fullsend changes + +Route existing clients through an externally deployed ghproxy while leaving +Fullsend's token issuance unchanged. This adds shared cache infrastructure +without changing the mint, and requests using the same token can benefit. +However, independently minted tokens still select different cache partitions, +so agents and processes with equivalent access cannot reliably share cached +responses. Deployment-specific routing also leaves consistent client and +agent-tool configuration to each operator. + +### ghproxy with a mint-level read-token cache + +Configure ghproxy routing in Fullsend and reuse mint-issued read-only tokens +by effective permission set and authorized scope. Equivalent requests from +different roles and processes use the same token and cache partition. This +addresses both response-cache sharing and token fragmentation, at the cost of +credential-cache storage, shared token lifecycle management, and explicit +audit attribution for cross-role reuse. + +## Decision + +We adopt optional ghproxy routing with a permission-keyed, read-only token +cache in the mint to make repeated GitHub reads share cached responses. +Configure the proxy through Fullsend's usual +[layered configuration](../guides/infrastructure/layered-config-reference.md), +following [ADR 0080](0080-config-yaml-vs-agent-env-var-scope.md), with no +separate environment-variable configuration surface. The resolved settings +apply to Fullsend's GitHub clients and supported agent API tools. With no +configured endpoint, retain direct GitHub access. + +Cache only tokens whose **actual granted permissions are all read-only**; +role and level names do not establish eligibility. Key entries by the +order-independent set of effective permission name/value pairs, within the +mint trust domain, GitHub host, target organization, and exact repository +scope. Equivalent roles and separate processes may receive the **same token +value**; tokens granting write or admin access remain unshared. + +Authorize each request, including the requested role's installation access, +before reusing a token, and never return broader access than that caller is +authorized to receive. A shared token may come from another authorized role's +App: this is the read-only exception to ADR 0007. Record the requesting role +and actual issuer separately, and use unshared credentials for operations +that require a particular App identity. Reuse must honor expiry, revocation, +and changes to the issuer's access or the authorized scope. + +Treat the proxy and mint cache as trusted credential-handling infrastructure. +Preserve credential isolation, authorization boundaries, and ghproxy's +authenticated cache partitions and conditional revalidation; a cache failure +must not broaden access or substitute stale data for successful revalidation. +Storage, replica coordination, transport wiring, and telemetry remain +implementation concerns. + +## Forge scope + +GitHub only, including GitHub Enterprise Server where the configured ghproxy +supports that API origin; hosts have separate cache namespaces. GitLab and +Forgejo are excluded because ghproxy and GitHub App installation tokens are +GitHub-specific; their credential and API routing contracts are unchanged. + +## Consequences + +- Equivalent reads across agents and processes can save primary REST quota, + but cache misses, changed resources, and secondary limits still matter. +- Read-only roles can share a token without sharing write authority, while + mint audit records preserve attribution that the shared GitHub identity loses. +- The proxy and token cache become credential-handling infrastructure whose + access controls and availability need operational ownership. +- Expiry and revocation affect all users of a shared token, so refresh and + cleanup must respect shared ownership and preserve authorization checks. + +[client-code]: https://github.com/fullsend-ai/fullsend/blob/93ff87e845f898f4d344ad90433bc30f5bddbfa1/internal/forge/github/github.go#L60-L80 +[mint-code]: https://github.com/fullsend-ai/fullsend/blob/93ff87e845f898f4d344ad90433bc30f5bddbfa1/internal/mintcore/handler.go#L517-L553 +[ghproxy]: https://docs.prow.k8s.io/docs/ghproxy/ +[ghcache]: https://docs.prow.k8s.io/docs/ghproxy/ghcache/ +[ghcache-code]: https://github.com/kubernetes-sigs/prow/blob/c06373a3e2cdcf0de2a087b4ed1db426366694b8/pkg/ghcache/ghcache.go#L390-L437 +[github-limits]: https://docs.github.com/en/rest/guides/best-practices-for-using-the-rest-api#use-conditional-requests diff --git a/docs/ADRs/0079-bind-entity-execution-through-named-sources.md b/docs/ADRs/0079-bind-entity-execution-through-named-sources.md new file mode 100644 index 0000000000..f8704d3f59 --- /dev/null +++ b/docs/ADRs/0079-bind-entity-execution-through-named-sources.md @@ -0,0 +1,473 @@ +--- +title: "79. Bind entity-driven execution through named connections and sources" +status: Accepted +relates_to: + - agent-architecture + - agent-infrastructure +topics: + - configuration + - entities + - dispatch + - polling +--- + +# 79. Bind entity-driven execution through named connections and sources + +Date: 2026-11-08 + +## Status + +Accepted + +Refines [ADR 0098](0098-entity-first-harness-evaluation.md): harnesses declare +named entity slots and their kinds; repository configuration binds those slots +to concrete sources. +Partially supersedes [ADR 0149](0149-coalesce-entity-source-discovery-queries.md): +source membership uses native provider semantics and may be checked remotely, +rather than requiring local reproduction over actor-filtered data. Its combined +search, current-membership, coverage, and retry requirements remain. The +lifecycles in [ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md) +remain unchanged. + +## Context + +The current `tracker` mapping selects one issue backend and its issue-creation +policy, as specified in [issue #9074](https://github.com/fullsend-ai/fullsend/issues/9074). +[PR #9091](https://github.com/fullsend-ai/fullsend/pull/9091) added the +Jira connection and polling configuration contract. The +[review proposal](https://github.com/fullsend-ai/fullsend/pull/9091#discussion_r4465261777) +separates reusable connections, named entity sources, and agent bindings: one +connection can supply several entity kinds, and one agent can process equivalent +work from several systems. + +[ADR 0098](0098-entity-first-harness-evaluation.md), +[ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md), and +[ADR 0149](0149-coalesce-entity-source-discovery-queries.md) define entity +evaluation, reusable run processes, and combined discovery, but leave the +configuration and CI integration incomplete. +This ADR aims to connect those decisions through one repository-owned binding +model, while keeping agent coordination in entity state and predicates. + +## Options + +### Keep the current `tracker` syntax + +The existing syntax is compact and already understood by the issue commands, +Jira poller, and configuration tooling. For example: + +```yaml +tracker: + jira: + base_url: https://example.atlassian.net + project: PROJ1 + allowed_targets: + projects: [PROJ2] + poll: + enabled: true + query: 'statusCategory != Done ORDER BY updated DESC' +``` + +This selects Jira for issue commands, supplies one primary project and polling +query, and permits issue creation in the additional project. It works for a +single tracker, including Jira used from a repository hosted on GitHub or GitLab. +Keeping it avoids a configuration migration. + +The mapping accepts at most one provider block. It has no names for multiple +instances of a provider, no per-agent source bindings, and no source/target +entity-kind declarations. The example cannot express a triage agent reading +both native and Jira work items while a code agent reads only Jira and produces +native change proposals. Those concepts would have to be added to or alongside +`tracker`; the current shape is insufficient as the shared entity-execution +configuration model. It remains useful as a compatibility input. + +### Separate connections, sources, and harness bindings + +Named connections describe service instances, sources describe what to select, +and harness bindings connect those sources to an agent's needs. This supports +multiple providers and instances without putting repository-specific names in +reusable harnesses. It introduces more configuration concepts and requires a +compatibility adapter, but each concept has one role and can be shared across +agents. This is the selected option. + +## Decision + +Adopt named connections and entity sources as the binding between portable +agent harnesses and the shared discovery, dispatch, and run path. The +[entity-source configuration v1 contract](../normative/entity-source-configuration/v1/README.md) +defines the fields, defaults, layering, destination policy, and compatibility +translation. The sections below describe the target design; existing +deployments use `tracker` until their consumers migrate. + +### Configuration responsibilities + +The model separates four concepts: + +- A **connection** identifies a service instance, such as a Jira site or GitHub + Enterprise host. Repository configuration defines it under `connections`. +- An **entity source** identifies a connection, repository or project scope, and + selection query. Repository configuration defines it under `entity_sources`. +- A **slot** names an entity requirement of a harness. The harness's + `entity_kinds` map declares each slot's kind, such as `work_item` (an issue) + or `change_proposal` (a pull or merge request). +- A **binding** assigns a list of entity sources to a slot. Repository + configuration defines it under `agents[].entities`. + +Connections share the registry proposed for Vault in +[PR #9097](https://github.com/fullsend-ai/fullsend/pull/9097); a connection's +`kind` selects its service type. Sources do not have a `kind` field. Fullsend +checks that each source's provider and query support the consuming slot's kind. +Bindings select where an agent can look for entities; credentials and permission +checks remain separate. + +### Harness slots and defaults + +Only the `source` slot drives automatic discovery and scheduling. Its binding +list is a union of possible inputs: each run processes one source entity. +`target` gives the run its default destinations for new entities. Additional +slots give it other named scopes to query or use. Those slots do not start +polling loops, fetch every entity in advance, or create combinations of inputs. +Every slot accepts a list. When several output destinations are possible, the +operation must choose one explicitly; a list does not broadcast writes. + +Apply defaults after all configuration layers have been combined: + +- In the harness, the `source` kind defaults to `work_item`; the `target` kind + defaults to the effective source kind. Additional slots require a kind. +- In `agents[].entities`, `source` defaults to `[native]`; an omitted `target` + copies the effective source list. An explicit target, including an inherited + one, takes precedence. Additional slots require explicit nonempty bindings. +- Omitted slot values inherit. An explicit binding list replaces that slot's + inherited list. `source: []` disables source-based execution; `target: []` + removes the default output scope. + +Copying a source list to `target` copies names, not entities or kinds. For +example, a Jira work-item source cannot supply a `change_proposal` target; that +agent must bind its target to a compatible source, such as `[native]`. Unknown +slots and incompatible bindings fail validation. An old event-only harness +stays on its existing path until it is explicitly migrated; these defaults do +not opt it into entity execution. + +### Repository and harness examples + +The following YAML illustrates the target contract, not fields supported by the +current CLI. Repository configuration supplies connections, scopes, and bindings: + +```yaml +# .fullsend/config.yaml +connections: + jira1: + kind: jira + base_url: https://example.atlassian.net + api_url: https://api.atlassian.com + +entity_sources: + github: + # Customizes native selection when the configuration was cloned from GitHub. + query: 'is:open -label:blocked' + jira_work: + connection: jira1 + projects: [PROJ1] + query: 'statusCategory != Done' + discovery: true + jira_related: + connection: jira1 + projects: [PROJ1, PROJ2] + query: '' # No additional filter within these projects. + +agents: + - name: code + entities: + source: [jira_work] + target: [native] + related_work: [jira_related] + - name: triage + entities: + source: [native, jira_work] + # target is omitted, so it defaults to [native, jira_work]. +``` + +The same body can live in a preset installed as `.fullsend/config.base.yaml`, +or under `defaults.config`, `github.config`, `gitlab.config`, or a repository +entry's `config` in `repos.yaml` +([layered configuration](../guides/infrastructure/layered-config-reference.md)). +An overlay can replace one slot's list while inheriting the other slots. + +The corresponding code harness declares the kinds of its slots and its +predicate over the primary source entity: + +```yaml +# Harness YAML; other agent, policy, and runtime fields omitted. +entity_kinds: + source: work_item + target: change_proposal + related_work: work_item +entity_filters: + source: + github: 'is:open label:"needs-code" no:assignee' + gitlab: open + jira: 'statusCategory != Done' +trigger: >- + entity.kind == "work_item" && + entity.state == "open" && + "needs-code" in entity.labels +``` + +With the code binding above, this harness receives Jira work items, targets +native change proposals, and can query `related_work` when needed. `entity` in +CEL is the one source entity for the run. The example predicate works without +an event. After successful processing, the agent must remove the request signal +or use a predicate that checks whether it has already handled the work. A +predicate that reads event fields must first check `event != null`. Labels used +by CEL remain subject to the actor-authorization rules. + +Harness `entity_filters` maps slot names to provider-specific queries. Each +filter narrows the bound source's query and trusted scope; it cannot widen them. +Missing provider entries add no restriction. Only source filters participate in +automatic discovery and dispatch; other slot filters constrain explicit searches. +Filters do not inherit from source to target. They filter searches, not creation +destinations or lookups by an explicit entity identity. Matching a filter is +required for source-based execution, but the full harness CEL predicate must +also pass. + +For a work-item agent using the default kinds, the declaration can be: + +```yaml +# Harness YAML; source defaults to work_item and target defaults to source. +entity_kinds: {} +``` + +Together with the triage binding above, this means native and Jira work-item +inputs and the same native/Jira choices for new work-item targets. Creating in +Jira still needs an independent connection policy grant. If both binding keys +are omitted, they resolve to `source: [native]` and `target: [native]`. +Additional named slots require explicit bindings. The agent names in these +examples illustrate roles; they do not define a fixed inventory. + +### Resolving native sources + +`native` is an entity-source selector. Resolve it in three steps: + +1. The repository from which fullsend configuration was cloned selects the + provider: GitHub, GitLab, or Forgejo. The platform running fullsend does not + select it. +2. The corresponding reserved source name (`github`, `gitlab`, or `forgejo`) + uses the provider-default connection with the same name. It cannot use a + differently named connection. +3. That connection selects the instance. A trusted override of its `base_url` + can select another instance. For the origin provider, the reserved source's + repository path defaults to the clone path on that instance; its explicit + scope can select another path. Sources for other providers need explicit + repository scopes. + +Reserved connection names imply their provider kind; an explicit `kind` must +agree. For example, a GitHub.com configuration clone can use a GitHub Enterprise +instance as its native forge: + +```yaml +# Configuration cloned from https://github.com/example/project. +connections: + github: + kind: github + base_url: https://github.example.com +entity_sources: + github: + query: 'is:open -label:blocked' +agents: + - name: triage + entities: + source: [native] +``` + +Here `[native]` and `[github]` both select `example/project` on +`github.example.com`, including when fullsend runs on standalone Kubernetes or +in GitLab CI. Set `entity_sources.github.repositories` if the repository path +differs. The override selects an instance; access still requires credentials and +permissions for that instance. + +Provider source names can also be bound explicitly for external systems. A +GitHub-origin configuration can use `[gitlab]` when a GitLab connection and +repository scope are configured, without changing its native provider. The +contract includes a complete cross-provider example. A matching provider name +and `native` are aliases for the same effective source and do not duplicate +runs. Without a native-source override, selection includes all lifecycle states. +Defining `entity_sources.native` is forbidden. Additional names may be reserved +in future revisions, with validation of existing definitions. + +### Candidate selection and CEL evaluation + +Source queries and harness provider filters use the same language for each +provider: + +- Jira uses native JQL. Fullsend combines selection conditions with `OR` inside + the configured project scope and manages traversal order separately. +- GitHub uses the contract's subset of UI filters: state, labels, + author/assignee, milestone, issue type, missing metadata, dates, and PR + draft/branch fields, with Boolean combinations and exclusions. Full-text and + history/review search filters are outside the initial subset. Lifecycle + filters use `is:open` or `is:closed`; an empty query adds no restriction. +- GitLab initially uses `open`, `closed`, and `all` presets. For change + proposals, `closed` expands to the union of native `state=closed` and + `state=merged` results; work items use native `state=closed`. Adapter support + may expand without requiring the same query language on every provider. + +For each source binding, require both the repository's source query and the +harness filter, within the configured repository or project scope. Combine +those effective selections across enabled harnesses so discovery retrieves +candidates needed by any of them. A provider adapter may retrieve a broader +shared set if it can then check each harness's selection exactly. It must still +account for pagination, provider limits, and missed or incomplete results. + +Source membership means that an entity currently matches this effective +selection. Use the provider's semantics. Reuse fetched data only when a local +check can prove the same answer; otherwise batch the remaining membership +checks through the provider, including Jira's +[JQL match API](https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-search/#api-rest-api-3-jql-match-post). +Equivalent queries and repeated references to the same entity share work when +their credential and authorization scopes are compatible. Unknown membership +remains unresolved and retryable; it is not evidence that no work exists. + +For GitHub, prefer GraphQL advanced search and request fields based on the +enabled harnesses' compiled CEL expressions. Fetch inexpensive shared fields +first, then additional fields and history only where evaluation remains +unresolved. Include the authorship and coverage evidence needed for +authorization, even when CEL does not reference those fields directly. +[ADR 0147](0147-evaluate-entity-cel-over-selectively-acquired-data.md) governs +these partial-data checks. Selecting fewer fields does not remove search caps +or pagination requirements. + +An entity matching a provider query is only a candidate. Before execution, +fullsend must establish authorized invocation, a current source match, and a +true harness predicate over actor-filtered data. It must also prepare filtered +model context under [ADR 0141](0141-deterministic-filtered-entity-context-staging.md). +Provider-native fields may include changes that CEL is not allowed to use, so +query membership can select or suppress candidates but never proves an actor's +authority. This is the explicit change to ADR 0149's source-membership rule. + +### CI coordination and run modes + +Webhooks and polling supply candidates to the same fullsend selection and +authorization path. Each dispatch identifies the agent, target repository, +canonical source entity, and resolved configuration revision. A resolved plan +contains the connections, source queries, slot bindings, and harness requirements +for that revision. Source aliases are not entity identities. + +Fullsend decides whether an agent should act. CI provides trusted invocation, +capacity, job deadlines, execution serialization, and result publication. +Existing jobs may remain as execution wrappers during migration; migrated jobs +use fullsend's decisions rather than separate stage-routing conditions. + +Agents coordinate by changing entity state and recording completed work, which +other agents' predicates can observe. For example, triage can make a work item +eligible for a code agent, and a resulting change proposal can become eligible +for review. This introduces no workflow graph or automatic next-agent step. + +This binding model supplies the entities and eligibility checks needed by +[ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md). Its run modes remain: + +- `once`: one discovery cycle for `fullsend poll`, or one eligibility check and + at most one sandbox cycle for an entity-bound `fullsend run`, then exit. +- `poll`: repeat checks while waiting for work. An entity-bound run exits after + a finite idle period; the discovery process may stay alive until stopped. +- `timed`: repeat checks within a hard deadline, with the same idle exit for an + entity-bound run and enough budget reserved for each sandbox cycle it starts. + +An entity-bound run stays associated with one canonical entity and rechecks its +current source membership and predicate before each sandbox cycle. Reusing the +host process does not reuse the sandbox or model session. `fullsend poll` still +defaults to `once`. Bound runs default to `once` outside CI; the automatic CI +choice of `timed` also requires a usable deadline, sufficient initial-cycle +budget, permission for eventless checks, and working recurring discovery. + +Installation sets up recurring discovery for enabled source bindings. Before a +run can repeat checks without events, fullsend must verify that discovery is +operational for its current plan and can recover work after the run exits. An +installed workflow file alone is insufficient. Missing or stale discovery +evidence keeps the automatic `once` fallback or rejects an explicit request to +repeat eventless checks. A configuration change invalidates old readiness; an +existing process stops starting new cycles under the obsolete plan. ADR 0144's +pending-work, cancellation, and rediscovery rules continue to preserve unfinished +work. + +### Destinations and standalone commands + +Inside a run, new entity creation defaults to the `target` slot. Updates to an +existing entity use that entity's canonical origin; a native target does not +redirect comments on a Jira source issue. Connection-scoped +`allowed_targets` remains an independent policy for work-item creation. A source +binding or query match does not grant write access. The contract defines the +destination checks and explicit cross-project creation rules. No separate +`issue_commands` configuration block is introduced. + +Standalone issue commands select one named source with the proposed +`--entity-source ` flag, or explicitly select `native` after resolving the +origin's provider and configured connection/source overrides. The command +supplies the `work_item` kind; no harness or agent binding is needed. Infer the +project or repository only when the selected scope has one choice; otherwise +require explicit selection. For example, using `jira_work` from the repository +example: + +```sh +fullsend issues get --fullsend-dir .fullsend --entity-source jira_work --number 123 +fullsend issues get --fullsend-dir .fullsend --entity-source native --number 123 +``` + +The first command retrieves PROJ1-123 from Jira; the second retrieves issue 123 +from the effective native source, including any instance override. Operations +with an explicit entity identity use the connection and lookup scope without +applying discovery filters, so the first command also works for a closed issue. +Creation remains subject to independent permissions. These flags describe the +target CLI, not current functionality. Omitting the selector is an error unless +the compatibility adapter can preserve legacy command selection. An explicit +source overrides legacy defaults; combining `--entity-source` and `--tracker` +is an error. + +### Migration and activation + +Accept deprecated `tracker` mappings by translating them in memory, with +actionable warnings and no automatic file rewrite. Preserve connection settings, +queries, polling enablement, command defaults, credentials, and creation +permissions. The old syntax remains usable while its consumers migrate. + +Scripts that read raw tracker YAML must migrate to effective configuration before +new-only configurations are enabled. Syntax translation alone does not move an +agent from event reconstruction to entity-state execution. + +First make configuration loading and existing consumers understand both forms. +Then deliver the provider adapters, CI integration, and entity-capable harnesses. +Switch each agent/source binding once; its old and new dispatch paths must not +run in parallel. Activation requires the normalized-entity contract, a provider +query protocol with coverage guarantees, the new major authorization contract +required by ADR 0149, and model-context support for the provider and entity kind. +That authorization contract must account for native source-membership semantics. +This configuration contract does not replace those prerequisites. +Implementation is tracked under +[#8418](https://github.com/fullsend-ai/fullsend/issues/8418), with entity and +discovery contracts in [#8420](https://github.com/fullsend-ai/fullsend/issues/8420) +and [#8421](https://github.com/fullsend-ai/fullsend/issues/8421). + +## Forge scope + +The initial entity-adapter targets are GitHub and GitLab work items and change +proposals, plus Jira work items. A Jira project remains distinct from the code +repository where the agent works. Forgejo and additional kinds such as +conversations use the same binding model, but remain disabled until the required +entity, discovery, context, and execution support is available and validated. + +GitHub Actions and GitLab CI are the first CI integrations. Source providers are +independent of execution platforms; the same configuration-resolution rules +apply to standalone runtimes, including Kubernetes. Each combination activates +only when its adapters satisfy the relevant contracts. Existing event-only paths +remain available. + +## Consequences + +- Agents can process equivalent entities from several systems without knowing + deployment-specific connection names. +- Explicit connections, sources, and bindings add configuration concepts that + the single-tracker model did not require. +- Provider queries remain expressive, and shared discovery and selective reads + can reduce API work, subject to exact membership and coverage checks. +- Existing tracker configurations continue working, but raw-YAML consumers and + CI require a coordinated migration. +- Coverage readiness and adapter conformance become explicit activation + requirements for resident runs. diff --git a/docs/ADRs/0085-serve-every-changed-jira-issue.md b/docs/ADRs/0085-serve-every-changed-jira-issue.md new file mode 100644 index 0000000000..221294493e --- /dev/null +++ b/docs/ADRs/0085-serve-every-changed-jira-issue.md @@ -0,0 +1,255 @@ +--- +title: "85. Serve every changed Jira issue with one poller per repository" +status: Accepted +relates_to: + - agent-infrastructure + - agent-architecture + - security-threat-model +topics: + - polling + - jira + - dispatch + - scheduling + - configuration +--- + +# 85. Serve every changed Jira issue with one poller per repository + +Date: 2026-11-19 + +## Status + +Accepted + +Partially supersedes +[ADR 0160](0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md): +the row limit on the candidate pool, the random pick, the use of the per-issue +lock, and both configuration keys are replaced. Its activity filter and its +checkpoint clause remain. + +Partially supersedes [ADR 0063](0063-polling-based-work-discovery.md) for the +`jira-poll` driver: the row limit on the candidate pool, the random pick, and +the per-issue lock are replaced, together with what depends on the lock (the +lock held during agent runs, the lock settings, the lock handling of +`fullsend poll cancel`, and the expectation of several concurrent pollers). +Its change detection and its authorization path remain. + +## Context + +[ADR 0063](0063-polling-based-work-discovery.md) has the `jira-poll` driver +read the first M results of the configured query (50), drop the issues another +poller has locked, and process N of the rest picked at random (5). +[ADR 0160](0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md) +added a filter that skips issues with nothing new and kept the rest; it is not +implemented yet. Under sustained load this loses requests. An issue outside +the first M results is never examined, an issue inside them can lose the draw +cycle after cycle, and a request that is not processed within the driver's +24-hour backfill window is dropped (see +[Poll coordination](../guides/user/jira-integration.md#poll-coordination)). +ADR 0160 records starvation beyond the first M results as unmitigated. + +The lock and the random pick both exist so that several pollers can work the +same issues at once. The managed poll jobs do not do that: on GitHub +([Scheduled workflow](../guides/user/jira-integration.md#scheduled-workflow)) +and on GitLab +([GitLab runtime](../guides/user/jira-integration.md#gitlab-runtime)) +they run one cycle at a time per repository. The lock and the checkpoint are +also named per target repository, so repositories that share a Jira project +never coordinated through the lock +([Multi-repo polling](../guides/user/jira-integration.md#multi-repo-polling)). +ADR 0160 rejected an oldest-first order only because pollers that sort alike +would race on those locks. + +Two limits of the GitHub hand-off have to survive the change. The managed +workflow passes the whole batch to the dispatch step as one job output and +runs each dispatch record as one job of a job matrix. GitHub allows at most +[256 jobs in a matrix](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idstrategymatrix) +and +[1 MB in a job's outputs](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idoutputs), +and the driver commits an issue's checkpoint before the dispatch step runs, so +a batch over either limit is lost whole. Nothing enforces either limit today; +five issues per cycle only makes a large batch rare. + +[ADR 0098](0098-entity-first-harness-evaluation.md) and +[ADR 0149](0149-coalesce-entity-source-discovery-queries.md) set the durable +direction for discovery, and no Jira adapter for it exists yet, so the +`jira-poll` driver stays in service. This ADR aims to stop that driver from +losing requests to its row limit and its random pick, with one change that +leaves change detection and authorization alone. It also lets a deployment +choose the length of the backfill window, so that a longer outage need not +lose requests. + +## Decision + +We run one `jira-poll` poller per repository and serve every issue that +changed within the backfill window, oldest change first by default, to +remove the row limit, the random pick, and the lock. + +1. **One poller per repository.** The driver neither reads nor writes the lock + property, and it ignores lock properties left by earlier versions. What + ADR 0063 builds on the lock is withdrawn for this driver along with it: + the lock held during agent runs, the lock settings, and the lock handling + of `fullsend poll cancel`. The managed GitHub workflow and the managed + GitLab schedule already run one cycle at a time per repository. A + scheduler other than the managed ones must itself keep two cycles for one + repository from overlapping; overlapping cycles dispatch the same requests + twice. Before it reads an issue's comments and history, the driver + confirms that it can write to the issue, as the lock write did; an issue + that fails yields no records, and the driver warns and carries on with the + other issues. A cycle in which every issue fails this check ends in an + error, as today, so a credential that cannot write shows as a failed run. + How the driver confirms it is left to the implementation. +2. **Pool.** The issues that match the configured query and whose `updated` + value falls within the driver's backfill window, read in the search's + sort order, with no row limit. The window is the one the driver already + uses to bound a first poll and to clamp an old checkpoint. Its length is + fixed at 24 hours today and becomes a setting, + `tracker.jira.poll.backfill_window_hours` (default 24, a whole number of + hours, at least 1, with no upper limit). The search is sorted oldest + change first unless the configured query carries its own sort clause, + which the driver keeps, as it does today. The default query sorts newest + first today; it no longer carries a sort clause, so it is served oldest + change first. When the configured query sorts newest change first + (`ORDER BY updated DESC`), as the documented examples do today, the driver + warns once per cycle that oldest change first is recommended; any other + order draws no warning. A candidate is active as ADR 0160 defines it, with + the checkpoint returned by the search itself. That value is used only to + skip idle issues; processing still reads the checkpoint from the issue, as + today. +3. **Selection.** The driver processes active issues in that order until the + cycle holds `tracker.jira.poll.max_dispatches_per_cycle` dispatch records + (default 100, from 1 to 250), until on the GitHub target the next issue's + records would take the serialized batch past 768 KB, or until five minutes + have passed since the cycle started. The five minutes include the search + and the per-issue reads: the driver checks the clock between Jira calls, + and the rest of the job's time is left for committing checkpoints and + dispatching. Reading one issue is limited to two minutes. An issue that + takes longer is treated as a failed read is today: the driver warns, + naming the issue, takes none of its records, leaves its checkpoint where + it was, and goes on to the next issue. All of an issue's records go out + in the same cycle, so an issue that does not fit in the room left waits + for the next cycle; the driver does not skip ahead to a + smaller issue. An issue is always taken when the cycle holds no records + yet, so a cycle can exceed the configured limit by that one issue. One + issue contributes at most 250 records and, on the GitHub target, 768 KB: + the driver keeps the oldest records, drops the rest with a warning, and + advances the checkpoint. The drop is deliberate and follows today's cap: + one issue does not honestly produce that many records in a cycle, so the + limit bounds the runs that a rewound checkpoint or a bulk change can + start. The warning names the issue. Today's cap of 100 events per issue, + which also drops its overflow and advances the checkpoint, is unchanged. At any of these limits the driver + stops reading, leaves an issue it has not finished for the next cycle, + dispatches what it has completed, commits those checkpoints, and exits + normally. A cycle in which every issue the driver tried failed or timed + out ends in an error, as today, so a poller blocked by slow issues shows + as a failed run. +4. **Bounds.** 250 is GitHub's 256-job matrix limit less a small margin; it + bounds a cycle and a single issue, and it applies on both targets. The + default is 100 because the limit sets how fast a backlog drains, and a + request that waits past the window is lost; it is twenty times today's + five issues per cycle when each issue yields one record. + 768 KB is three quarters of GitHub's 1 MB limit on a job's outputs, + measured as GitHub measures it; the margin is there because GitHub + describes its measure as approximate. It applies on the GitHub target only, + since GitLab starts each pipeline separately and has no batch output. Five + minutes is the managed GitHub schedule's interval and leaves ten minutes of + that poll job's default 15-minute timeout. Two minutes per issue is many + times what an ordinary issue takes, and it leaves room for an issue with + the longest comment and history listings the driver reads. The default, + the size limit, and the two time limits are initial values; revisit them + when a deployment needs more. The window has no upper limit because no + one length suits every project: what a project can afford depends on how + many of its issues change, so the operator chooses. + `max_dispatches_per_cycle` replaces both keys of ADR 0160, neither of + which shipped. +5. **Unchanged.** Change detection, bot filtering, authorization, the + window's clamps (only the window's length becomes a setting) and + ADR 0160's one log line per cycle naming the clamped + candidates, the checkpoint commit with ADR 0160's `updated` clause, + and on GitLab the record-by-record dispatch with its retry of an issue + whose dispatch failed. + +## Forge scope + +Applies to the `jira-poll` input driver on both of its targets: GitHub, where +the managed workflow turns the dispatch file into a job matrix, and GitLab, +where the driver starts the agent pipelines itself. The 250 limit comes from +GitHub and is applied on GitLab too, so that there is one rule. The size limit +applies on GitHub only. The GitLab-native cron poller +([ADR 0067](0067-gitlab-cron-polling-event-dispatch.md)) and webhook fast path +([ADR 0125](0125-gitlab-hybrid-webhook-poller-dispatch.md)) are unaffected. +Forgejo has no Jira poll target. + +## Consequences + +- Every issue that changed within the window is eligible each cycle, so none + is cut off by a row limit or lost to chance. Position still matters under + a backlog, behind slow issues, and under a configured order, as the + bullets below say. +- Requests are still lost when issues change faster than the driver can + process them within the window, when the poller is stopped for longer than + the window, or when one issue produces more than 250 dispatch records, or on + GitHub more than 768 KB of them, in one cycle; removing the window is left + to the entity-based design. +- On the GitHub target a batch is still lost whole when GitHub discards the + job output, which it does when the output contains one of the poll job's + secret values, or when the dispatch step fails after checkpoints are + committed. A checkpoint commit that fails after the write check passed + fails the poll step, and the issues whose commits succeeded lose their + requests. All three exist today, and a larger batch raises what is lost; + changing the hand-over is left to a separate change. +- An issue the driver cannot write to, or cannot read within two minutes, is + tried again every cycle until its change leaves the window. Its requests + are not served. It takes no record room from other issues, and a slow one + costs up to two minutes of each cycle. Two or three slow issues at the + front of the line can use up a whole cycle, and the issues behind them are + then not reached and can lose their requests. Such a cycle ends in an + error, so the stall shows as failed runs. This ADR accepts the stall and + adds no way to set a slow issue aside. +- A configured query that sets another order is served in that order. Under + a sustained backlog, an order other than oldest change first can leave + older requests waiting until they leave the window, so the guide and the + config reference recommend oldest change first, say what another order + costs, and drop the newest-first sort clause from their example queries. +- A longer window lets requests survive a longer outage, at three costs. A + missing or rewound checkpoint replays requests as old as the window. An + issue the driver cannot write to, or cannot read in time, is retried for + as long as the window. A window that holds more issues than a cycle can list makes the driver fall + behind without failing, so recent requests are not served and the run still + looks healthy. The guide and the config reference say how to choose the + length and what a long one costs. +- Under oldest change first, any change to a waiting issue, including a + comment from anyone allowed to comment, moves it to the back of the line; + under a sustained backlog that can cost the issue its request. +- A rewound checkpoint can replay old requests from every issue that changed + within the window, where today it reaches five issues per cycle; the + per-cycle limit bounds the runs that starts. A rewind does not move an + issue in the line, so an editor who keeps rewinding issues near the front + can hold the requests behind them back. The random pick did not allow + that; this ADR accepts it and extends the + [Jira guide](../guides/user/jira-integration.md)'s rule that Edit Issues on + a polled project is part of the trust boundary. +- The config loader rejects unknown keys under `tracker.jira.poll`, so a + repository that sets either new key while its workflow still pins an older + fullsend fails to load its config and stops polling; the keys are adopted + after the upgrade, and the config reference names the version that + introduces them. +- Each cycle reads the search rows of every issue that changed within the + window, including those already handled, and no longer makes the lock calls + or the per-issue pause. The number of Jira calls in a cycle is now bounded + by the time limit, not by a count. +- The implementation must show that a batch at the record limit and a batch at + the size limit, built from the largest records the driver can produce, are + each dispatched whole, that an issue larger than the configured limit is + dispatched alone and does not hold back the issues behind it, that a + cycle stopped by the time limit leaves undispatched requests eligible for + the next one, and that a pool larger than the 10,000 rows the search + client stops at today is not cut short silently; the [Jira guide](../guides/user/jira-integration.md), the + [config reference](../reference/config-reference.md), and the + [custom poller example](../guides/user/custom-poller-example.md) change + with it. +- If entity-based discovery + ([ADR 0098](0098-entity-first-harness-evaluation.md), + [ADR 0149](0149-coalesce-entity-source-discovery-queries.md)) fully + replaces the `jira-poll` driver, this change is retired with it. Until then + it is needed, because the driver loses requests today. diff --git a/docs/ADRs/0098-entity-first-harness-evaluation.md b/docs/ADRs/0098-entity-first-harness-evaluation.md index e2b084052b..c248a466e9 100644 --- a/docs/ADRs/0098-entity-first-harness-evaluation.md +++ b/docs/ADRs/0098-entity-first-harness-evaluation.md @@ -62,10 +62,14 @@ one combined logical search per source scope and local per-harness routing. For source-backed harnesses, even an event-supplied candidate must pass a current local source-query membership check before sandbox admission. -Living contract: -[Normalized entity v1](../normative/normalized-entity/v1/README.md) specifies -the logical `entity` value, coverage states, and partial-data invariants that -this ADR requires. +The [Normalized entity v1 contract](../normative/normalized-entity/v1/README.md) +specifies the logical `entity` value, coverage states, and partial-data +invariants that this ADR requires. + +[ADR 0079](0079-bind-entity-execution-through-named-sources.md) refines source +declarations into named, typed harness slots and repository-owned binding lists. +It also permits native provider membership checks as a separate selection gate; +actor-filtered CEL and model-context admission remain required. ## Context diff --git a/docs/ADRs/0149-coalesce-entity-source-discovery-queries.md b/docs/ADRs/0149-coalesce-entity-source-discovery-queries.md index a7c9f3a44f..15b5e87bcc 100644 --- a/docs/ADRs/0149-coalesce-entity-source-discovery-queries.md +++ b/docs/ADRs/0149-coalesce-entity-source-discovery-queries.md @@ -25,6 +25,13 @@ candidate and to let a harness act on it. poll and bound-run lifecycles. This ADR adds a local source check before each sandbox cycle for an entity-driven harness. +[ADR 0079](0079-bind-entity-execution-through-named-sources.md) partially +supersedes the local-reproduction and actor-filtered source-query requirements: +membership follows native provider semantics, with exact local checks where +possible and batched provider checks otherwise. Combined enumeration, current +membership, coverage, and retry remain required; actor-filtered harness CEL +and model-context admission are independent gates. + ## Context ADR 0098 lets harnesses declare entity sources, but allows sharing only when diff --git a/docs/ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md b/docs/ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md index 8e2ba89d4c..1e007b8498 100644 --- a/docs/ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md +++ b/docs/ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md @@ -32,6 +32,13 @@ change detection, and authorization path of ADR 0063 and are unchanged; the checkpoint rule gains one clause, so that the checkpoint also advances to at least the issue's `updated` value. +[ADR 0085](0085-serve-every-changed-jira-issue.md) partially +supersedes this decision: one poller runs per repository and serves every +issue that changed within the driver's backfill window, oldest change first +by default, up to a per-cycle dispatch limit. The row limit on the candidate pool, +the random pick, the use of the per-issue lock, and both configuration keys +are replaced. The activity filter and the checkpoint clause remain. + ## Context [ADR 0063](0063-polling-based-work-discovery.md) defines how the `jira-poll` diff --git a/docs/ADRs/0161-repo-config-limits-run-artifact-content.md b/docs/ADRs/0161-repo-config-limits-run-artifact-content.md index 485749a5fa..a40f08eb5c 100644 --- a/docs/ADRs/0161-repo-config-limits-run-artifact-content.md +++ b/docs/ADRs/0161-repo-config-limits-run-artifact-content.md @@ -134,6 +134,10 @@ The rest of ADR 0021 stands: full transcripts by default, and credential scanning as an invariant check. Per-agent levels and artifact retention are out of scope. +Journal commits are outside this ADR's run-artifact filtering scope. Their +access and evidence-retention requirements are defined in +[ADR 0165](0165-recover-work-through-repository-owned-operation-journals.md). + ## Forge scope - **GitHub:** the existing upload step uploads the staged copy and skips the diff --git a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md new file mode 100644 index 0000000000..74c5f9f3e5 --- /dev/null +++ b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md @@ -0,0 +1,159 @@ +--- +title: "165. Primitives for repository-owned operation journals" +status: Accepted +relates_to: + - durable-work-recovery + - agent-architecture + - agent-infrastructure +topics: + - coordination + - recovery +--- + +# 165. Primitives for repository-owned operation journals + +Date: 2026-11-10 + +## Status + +Accepted + +## Context + +Per-subject serialization ([ADR 0106](0106-serialize-agent-runs-and-coalesce-subsequent-events.md)) +and occurrence-aware poll state +([ADR 0132](0132-occurrence-aware-shared-poller-state.md)) reduce duplicate +dispatch. They do not reserve an operation across scheduling, worker failure +and external publication. Runtime workflow packaging in +[#8225](https://github.com/fullsend-ai/fullsend/pull/8225) addresses another +boundary: delivering a sequence to an agent runtime. + +[Durable work recovery](../problems/durable-work-recovery.md) describes the +failure cases. Workflows such as CVE resolution need durable state to track +required work, continue after interruption and retain evidence within bounded +retries. This ADR aims to keep admitted work recoverable across hosts without +making a model or a central daemon the coordination authority. + +## Options + +Integration-owned databases offer flexibility but repeat the same recovery +controls. A mandatory workflow service adds an operated dependency. A +repository-owned journal reuses forge state and existing schedulers, at the +cost of conditional writes and explicit reconciliation. + +An opt-in local stage engine can retain accepted stage outputs and enforce +ordering without a mandatory service. It may complement the journal, but +cross-host recovery also requires state transfer, ownership fencing and +reconciliation of external actions. Stage progress alone does not provide +those guarantees, so it does not replace the journal for this decision. + +## Decision + +Fullsend adopts a durable saga journal stored as versioned JSON files in a +control repository. This repository holds recovery state and may be separate +from the repositories where agent runs execute and source code lives. A saga +records progress across separate external actions and recovers individual +steps without claiming an atomic transaction across services. It covers +admission, target resolution, dispatch, execution, publication and accounting +for every required target, including multiple branches. Each participating +workflow supplies a trusted host adapter: integration code that claims +admitted work, dispatches attempts and returns to reconcile unfinished +operations. The journal stores and checks transitions; it does not drive the +workflow itself. Domain dispatch and assessment semantics remain in these +adapters. This ADR defines their recovery contract, not their implementation +or packaging. + +The journal retains stable operation identities, input bindings, work bounds, +effect intents and separate scheduling, execution and publication receipts. +Execution receipts retain recovery state and references to runs and available +traces; detailed execution history remains in run telemetry. The journal +determines what work needs recovery, while telemetry records what happened +within a run. Correlation mechanisms remain an implementation choice. +Conditional updates, integrity checks and ownership fencing prevent competing +or superseded workers from accepting results or admitting new effects. An +external request admitted before ownership loss remains in-flight until its +outcome is reconciled. Ownership expiry, supersession or result acceptance +does not release a running attempt's concurrency reservation. Release requires +reconciled scheduler termination. + +Trusted host adapters persist intent before external actions and confirm +receipts after verified acceptance. They reconcile ambiguous outcomes before +retrying; an empty eventually consistent search does not prove a write failed. +Retained validated evidence permits publication recovery without repeating +inference, subject to current source, authorization and policy checks. Missing, +exhausted or unresolved targets remain visible and cannot imply completion. +Domain adapters define completion and any compensating actions. + +Journal-backed recovery is an explicit workflow opt-in. Workflows installed by +fullsend require explicit integration to use these primitives. Participating +workflows connect their pre/post scripts and agent or harness contracts to +trusted host adapters and reconcilers. Existing webhook and poll dispatch +paths do not automatically journal every run; their selection and dispatch behavior +remains unchanged unless explicitly integrated. Once a workflow admits work to +the journal, the recovery contract covers all its required targets and effects. + +Shared journal operations are callable by authorized host scripts and +reconcilers. Running as a pre/post script does not itself grant journal +access. Incremental checkpoints and periodic reconciliation provide recovery +when execution stops. CI cleanup supplies a best-effort checkpoint; it is not +the recovery guarantee. This is a deterministic host capability, not a +coordinator agent. + +Only authorized trusted host code writes the journal. Assessment runs, +including their pre/post scripts and agent sandboxes, receive admitted context +without journal-write credentials. A trusted host adapter outside that run +claims work and records its results. Journal state contains bounded +identities, digests and receipts. Workflow integrators must ensure journal +contents and retained evidence are accessible only to readers authorized for +that data; journal storage may use a separate private repository. The run-artifact filters +in [ADR 0161](0161-repo-config-limits-run-artifact-content.md) limit uploaded +logs and transcripts; they do not filter journal commits. With artifact levels of +`metadata` or `none`, evidence needed for recovery requires a separate store +permitted by the source's disclosure and retention policies. Its location and +access controls are integration choices. Journal contents grant no authority, +and integrity failure stops scheduling and publication rather than resetting +state and repeating work. + +## Entity state and journal state + +[ADR 0098](0098-entity-first-harness-evaluation.md) and +[ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md) retain business and +handled state on the entity. Trackers hold applicability, human workflow status +and assessment handoffs. Entity-first discovery must still find eligible work +whose trigger was lost before admission; a journal cannot recover unrecorded work. + +The journal records mechanical progress of admitted work. It adds no separate +business handled-state or revision-deduplication gate. Existing actor, entity, +disclosure and repository checks remain authoritative. Journal storage does +not require one tracker per branch; tracker-first dispatch is a domain decision +tracked separately in [#9260](https://github.com/fullsend-ai/fullsend/issues/9260). + +## Forge scope + +Execution host, journal storage, source forge and tracker are independent +bindings. The initial journal backend is the GitLab control repository, which +can coordinate GitHub, GitLab or Forgejo source repositories and Jira trackers. +Source repositories need no journal or journal-write credential. + +The same journal contract applies to GitHub and Forgejo control repositories; +their storage adapters require conformance before enablement. Source and +publication adapters retain their own authorization and enablement requirements. +Jira issue properties do not satisfy the journal's conditional-update contract. + +## Consequences + +- The full saga can recover individual branches and external effects without + keeping a host or model session alive. +- Control-repository history makes state inspectable and avoids a mandatory + central service, at the cost of commit volume, retention and compaction. +- Conditional updates, ownership fencing and ambiguous-effect reconciliation + require backend conformance; delivery is not claimed to be exactly once. +- Shared script operations and periodic reconciliation are both required. + Assessment runs retain their existing source-access boundaries. +- Tracker-state reconciliation and publish-only retry can ship independently + without narrowing the saga's scope. + +Implementation layout, script interfaces, credentials, reconciliation schedules +and detailed acceptance tests belong to +[#9253](https://github.com/fullsend-ai/fullsend/issues/9253). This ADR records +the decision; the journal capability is not yet implemented. diff --git a/docs/agents/README.md b/docs/agents/README.md index b36e915578..0bd9e9d4fa 100644 --- a/docs/agents/README.md +++ b/docs/agents/README.md @@ -13,7 +13,10 @@ Custom agents can be registered via the `agents:` field in the repository-local Built-in agents resolve automatically through repository configuration or the [`fullsend-ai/agents`](https://github.com/fullsend-ai/agents) repository -fallback. Additional agents, such as Scribe, are opt-in and must be added +fallback. When `FULLSEND_FORGEJO_URL` is set, a configured Forgejo instance +replaces that GitHub fallback (see +[Agent definitions from a Forgejo instance](../cli/run.md#agent-definitions-from-a-forgejo-instance)). +Additional agents, such as Scribe, are opt-in and must be added explicitly with `fullsend agent add`. | Agent | Summary | diff --git a/docs/agents/retro.md b/docs/agents/retro.md index 4ed905c253..29ca9a229f 100644 --- a/docs/agents/retro.md +++ b/docs/agents/retro.md @@ -48,8 +48,11 @@ to focus on: - `/fs-retro the code agent spent 30 minutes on a 2-line fix, what went wrong` The retro agent also runs automatically when a same-repository PR is closed -(merged or not) by an actor with write access. Fork PRs get no automatic -retro; a user with write access can run `/fs-retro` on a closed or merged fork PR. +(merged or not) by an actor with write access. On GitHub, a fork PR closed +by such an actor gets the same automatic retro, through the managed +`fullsend-fork-pr.yaml` workflow (see +[Fork pull requests](../guides/getting-started/repo-management.md#fork-pull-requests)); a user with +write access can also run `/fs-retro` on a closed or merged fork PR. Merge-queue events follow the same rule: the event sender must have write access. Other automated senders without repository write access do not start retro; a write-authorized user can run `/fs-retro` diff --git a/docs/agents/review.md b/docs/agents/review.md index a7084e83dc..4a2719b620 100644 --- a/docs/agents/review.md +++ b/docs/agents/review.md @@ -37,7 +37,7 @@ write or higher. The `/fs-review` command does not accept arguments and always forces a review. The review agent also runs automatically on a same-repository PR when it is opened, when its effective diff changes on a synchronize event, or when it is moved out of draft by a user with triage-level repository permission or higher. -Fork and Dependabot PRs are not reviewed automatically; someone with triage access or higher (or an OWNERS approver or reviewer) can comment `/fs-review` on them. +On GitHub, a fork PR is reviewed automatically under the same rules (a bot author is checked like any other author), through the managed `fullsend-fork-pr.yaml` workflow (see [Fork pull requests](../guides/getting-started/repo-management.md#fork-pull-requests)); the `ready-for-review` label does not start a fork PR review. Dependabot PRs are not reviewed automatically. On either, someone with triage access or higher (or an OWNERS approver or reviewer) can comment `/fs-review`. For GitHub `pull_request` synchronize events (and `pull_request_target` from shims that have not been upgraded), the review is skipped when the complete effective diff matches the previous app-verified approved review. The guard posts or updates one PR-visible `fullsend:review-skip` status comment linking the previous approved review. GitLab diff metadata uses the same normalized model, but the GitLab poller does not consume this marker yet and continues to review synchronized merge requests. The deduplication check runs before final Bash/CEL stage selection, so CEL-selected review routes participate as well. File modes are part of the compared effective diff identity, so executable-bit changes cannot be hidden by an otherwise identical textual patch. The guard fails open and runs the review when there is no prior diff hash, the prior review cannot be verified, a required hash/head or base/head tree-mode API call fails, @@ -86,8 +86,13 @@ the loop. Dispatch is keyed on the head SHA, so later polls that see the same head do not review it again. Diff versions do not record who pushed, so the poller cannot authorize the pusher. It therefore reviews pushes only to same-project MRs, where any pusher already has project push access. A push to -a fork MR is not reviewed automatically, and re-review of fork MR pushes is -currently unsupported (the router also denies slash commands on fork MRs). +a fork MR is not reviewed automatically. To review a fork MR after a push, or +an existing fork MR that predates the installation, someone with Developer +access or higher comments `/fs-review` on it (the router accepts Reporter, but +the agent job requires Developer). `/fs-review` is the only slash +command that dispatches on a fork MR: write-capable commands such as `/fs-fix` +and `/fs-code`, and the `ready-for-review` label, do not dispatch on fork MRs. +When the poller skips an event, its log names the reason. ## Control labels diff --git a/docs/architecture.md b/docs/architecture.md index 66d9bcb657..5dc2838825 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -55,7 +55,8 @@ sole supported installation model - Event-source routing for status notifications: the notification destination for run-status comments and reactions is dynamically determined by event provenance — a Jira-triggered run posts status to Jira, a GitHub-triggered run posts to GitHub — rather than being hardwired to the code-output forge. Status notifications route through `tracker.Client`; reactions are an optional `tracker.Reactor` capability (Jira Cloud supports comment reactions but not issue reactions, so `Reactor` is not implemented for Jira currently) ([ADR 0093](ADRs/0093-tracker-routed-status-notifications.md)). - Installation model: the CLI installs per repository only (`fullsend github setup `, `fullsend admin install ` (deprecated), `fullsend repos install`); per-org CLI installation was removed ([ADR 0044](ADRs/0044-deprecate-per-org-installation-mode.md)). The concrete layers of the ordered layer stack (vendor-binary, secrets, inference, and the per-org workflows layer) were removed along with per-org mode; `internal/layers` keeps only the `Layer` interface and shared helpers, and the CLI no longer orchestrates a layer stack ([ADR 0006](ADRs/0006-ordered-layer-model.md)). - Dispatch: each repository's `.github/workflows/fullsend.yaml` shim calls the upstream `reusable-dispatch.yml` via `workflow_call`; that workflow mints OIDC tokens exchanged at a central token mint (GCP Cloud Function or Cloudflare Worker) for scoped GitHub App installation tokens per agent role. App PEM secrets are stored in Secret Manager (GCF mint), Worker secrets (CF mint), or the local filesystem (standalone mint), not the config repo ([ADR 0008](ADRs/0008-workflow-dispatch-for-cross-repo-dispatch.md)). -- Shim workflow security: the shim's PR events run on `pull_request`, so the shim runs from the PR's own copy and forwards the repository's secrets. Its dispatch job therefore runs only for same-repo PRs (head repository id equals the base repository id), whose authors already have write access; fork and Dependabot PRs get no automatic run and are reviewed when someone authorized for `/fs-review` (triage access or higher, or an OWNERS approver or reviewer) comments it. `reusable-dispatch.yml` refuses those PRs again (a fork cannot edit the upstream copy; a vendored copy runs from the PR, so vendored installs rely on GitHub not sending secrets to fork PR runs), takes the base side for every checkout (base SHA, or the default branch where a checkout used the event default), runs no PR code, and still accepts `pull_request_target` from shims that have not upgraded, with a warning. The mint accepts only OIDC tokens whose `job_workflow_ref` names an allowed workflow host repository ([ADR 0164](ADRs/0164-run-the-shim-on-pull-request-for-same-repo-prs.md), superseding the `pull_request_target` shim of [ADR 0009](ADRs/0009-pull-request-target-in-shim-workflows.md)). +- Shim workflow security: the shim's PR events run on `pull_request`, so the shim runs from the PR's own copy and forwards the repository's secrets. Its dispatch job therefore runs only for same-repo PRs (head repository id equals the base repository id), whose authors already have write access; Dependabot PRs get no automatic run, and someone authorized for `/fs-review` (triage access or higher, or an OWNERS approver or reviewer) comments it. `reusable-dispatch.yml` refuses fork and Dependabot PRs on `pull_request` again (a fork cannot edit the upstream copy; a vendored copy runs from the PR, so vendored installs rely on GitHub not sending secrets to fork PR runs), takes the base side for every checkout (base SHA, or the default branch where a checkout used the event default), runs no PR code, and still accepts `pull_request_target` from shims that have not upgraded, with a warning. The mint accepts only OIDC tokens whose `job_workflow_ref` names an allowed workflow host repository ([ADR 0164](ADRs/0164-run-the-shim-on-pull-request-for-same-repo-prs.md), superseding the `pull_request_target` shim of [ADR 0009](ADRs/0009-pull-request-target-in-shim-workflows.md)). +- Fork PRs (GitHub): a fork PR's events run the managed `fullsend-fork-pr.yaml` workflow, which has no permissions and does nothing. Its completed run starts the shim through `workflow_run` from the default branch, with the repository's secrets. The fields of that run (head repository, branch, SHA, path, creation time) are only used to look the PR up through the API; the dispatch re-checks the PR's head repository id and head SHA, then authorizes the PR author (triage access or higher) for review or the closer (write access) for retro. The `ready-for-review` label does not start a fork PR review; for other fork PRs a maintainer comments `/fs-review`. It never reads the fork run's output or runs PR code. - Installer scaffold: per-repo installs deploy content from an embedded scaffold (`internal/scaffold/`), keeping deployable files as real files under version control rather than Go string constants. The per-org dispatch, repo-maintenance, and enrollment-reconciliation scaffolds were removed with the rest of per-org mode ([ADR 0044](ADRs/0044-deprecate-per-org-installation-mode.md)). - Reusable workflows: each repository's `fullsend.yaml` shim calls the upstream `reusable-dispatch.yml` (`fullsend-ai/fullsend/.github/workflows/reusable-dispatch.yml`), which runs every agent stage as an inline job; the only standalone stage workflow is `reusable-prioritize.yml`, called by the explicit prioritize thin caller. The per-org thin stage callers and `reusable-{code,fix,review,retro,triage}.yml` were removed with per-org mode (the per-org architecture described in the linked ADRs is historical and deprecated). Infrastructure patches ship once upstream and propagate to all repositories without re-install ([ADR 0031](ADRs/0031-reusable-workflows-for-action-installed-distribution.md)). **Vendoring** (`vendor: true` in `repos.yaml` for `repos install`, `--vendor` for `github setup`; [ADR 0047](ADRs/0047-vendored-installs-with-vendor-flag.md)) commits workflows and agent content at install time; layered installs (default) fetch upstream at runtime. - Event-driven stage dispatch: eliminate `workflow_dispatch` + `gh workflow run` fan-out from the (now removed per-org) `dispatch.yml` in favor of synchronous `workflow_call` so the dispatched run stays linked to the caller ([ADR 0041](ADRs/0041-synchronous-workflow-call-event-dispatch.md)). @@ -94,7 +95,11 @@ sole supported installation model role who can run a default-branch pipeline can read the Poller and role credentials ([ADR 0175](ADRs/0175-allow-insecure-gitlab-pipeline-variable-restriction-opt-in.md), - amending ADR 0131; CLI shape tracked in #9597). Managed schedules carry no + amending ADR 0131). The opt-in is `allow_insecure_pipeline_variables` on a + concrete GitLab manifest entry, and it also lets the webhook fast path and + trigger account provision ([Opting in to a relaxed + setting](guides/getting-started/configuring-gitlab.md#opting-in-to-a-relaxed-setting)). + Managed schedules carry no pipeline variables; job rules select poll mode from the schedule description, and typed activation only reads managed schedules and fails while any still sets a pipeline variable (including an obsolete `FULLSEND_POLL_MODE` override, @@ -478,9 +483,20 @@ Identity is not the same as trust. An agent's identity lets it authenticate to e **Decided:** +- Shared GitHub reads: optional ghproxy routing through the usual layered + configuration will let agents and processes reuse HTTP responses, backed + by a mint cache of tokens whose granted permissions are exclusively + read-only. Cache keys use the effective permission set within an exact host, + target organization, repository scope, and mint trust domain; equivalent + roles may share a token + after independent authorization, with the actual issuer recorded separately + from the requesting role. Write tokens stay unshared + ([ADR 0071](ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md)). + Decided, not yet implemented. + - Credential delivery model: four tiers — (1) prefetch + post-process for agents with enumerable inputs (zero credential access), (2) OpenShell providers + L7 egress policies for static token auth (credentials never enter sandbox), (3) host-side REST server for operations providers cannot handle — long-running operations, sandbox capability gaps, credentials in request bodies, response transformation, and multi-step atomic operations (see [ADR 0046](ADRs/0046-host-side-api-server-design.md)), (4) host files + L7 policies for complex auth requiring in-sandbox credential files. L7 policies enforce both method + path and binary-level restrictions. Providers are preferred over REST servers when viable ([ADR 0017](ADRs/0017-credential-isolation-for-sandboxed-agents.md), extended by [ADR 0025](ADRs/0025-provider-credential-delivery-for-sandboxed-agents.md)). OpenAI inference on the pi runtime is the first tier-2 use: the runner exchanges the job's GitHub OIDC token for a short-lived OpenAI access token and hands it to a run-scoped OpenShell provider, so no OpenAI credential enters the sandbox ([ADR 0092](ADRs/0092-openai-wif-credential-delivery.md)); the codex runtime reuses that provider and follows its refreshes by re-reading a runner-seeded token file through codex's `auth.command`, since its process environment cannot carry a placeholder that survives a refresh ([ADR 0099](ADRs/0099-codex-agent-runtime.md)). - Inference gateway route: a committed `inference.gateway` block in `.fullsend/config.yaml` names an LLM gateway (`url` and `audience`) that trusts the forge's OIDC issuer directly. The route is runtime-neutral: the credential is re-seeded through a route-aware seeder (the OpenAI seeder generalised, with independent handoffs when a run uses both routes), and each runtime keeps the gateway URL runner-owned. pi, codex and Claude Code use it, and on each the `gateway/` model prefix opts a model in: pi through the pi-inference-gateway extension, codex through a runner-owned `fullsend-gateway` provider in its digest-guarded `config.toml`, on the Responses API only, and Claude Code through a runner-owned `ANTHROPIC_BASE_URL`, cleared and re-exported after `.env`, with its credential from an `apiKeyHelper` that re-reads the re-seeded token file. The runner seeds the job's OIDC token, fetched with the gateway's audience, into a run-scoped OpenShell provider as an endpoint-bound placeholder and re-seeds it before `exp`, scheduled from each token's own `exp` and `iat`. The gateway holds the upstream provider key, so the forge stores no reusable provider key. The route is selected per model by provider prefix, with no precedence order against WIF or the static key: `openai/` and other providers keep their routes, one run can mix them, and a gateway that fails never falls back. The runner owns the route only when a complete block applies; without one, the plugin-carried setup for local runs is unchanged. On pi the route is a separate `gateway` provider served by pi-inference-gateway, with a runner-rendered, digest-guarded model list taken from inline `models` or a validated `models_file` ([ADR 0137](ADRs/0137-inference-gateway-credential-route.md)). The block's `auth` field selects the credential: `oidc` (the default, as above) or `api-key`, a supported mode for gateways that cannot trust forge OIDC. In `api-key` mode the runner reads a gateway key from `FULLSEND_INFERENCE_GATEWAY_API_KEY` and puts it behind the same placeholder, egress profile and guards, with no re-seed loop. The block then applies on local runs too. There is no fallback between modes, and because the mode relies on a long-lived secret, setup and status warn about it ([ADR 0138](ADRs/0138-inference-gateway-api-key-credential-mode.md)). An opt-in setting on the block, `messages_auth_header: x-api-key`, sends the gateway credential as `x-api-key` instead of `Authorization: Bearer` for Messages-dialect models (pi `anthropic-messages` models and Claude Code), for gateways that read the key where Anthropic documents it for that API. It is valid only with `auth: api-key`; an `oidc` block that sets it is a config error. The default stays `authorization`, the other dialects and codex keep Bearer, and an `x-api-key` gateway must replace the caller's key with its own on the upstream hop ([ADR 0142](ADRs/0142-inference-gateway-x-api-key-header-for-messages-models.md); implementation in [#8370](https://github.com/fullsend-ai/fullsend/issues/8370)). -- GitHub Packages for sandboxed installs: the job's Actions workflow token is preserved as `GH_WORKFLOW_TOKEN`, refused at every harness `${}` site and in child environments and read by provider credential expansion, and a repo-level provider binds it to `npm.pkg.github.com` (read-only, enforced) and the tarball CDN (which serves pre-signed URLs); forge identity stays the minted App token, which cannot read public packages owned by another org ([ADR 0114](ADRs/0114-github-packages-via-host-bound-workflow-token-provider.md)). On GitHub Actions the runner also reads the token itself to pull a private `ghcr.io` sandbox image before sandbox creation ([#9019](https://github.com/fullsend-ai/fullsend/issues/9019)). +- GitHub Packages for sandboxed installs: the job's Actions workflow token is preserved as `GH_WORKFLOW_TOKEN`, refused at every harness `${}` site and in child environments and read by provider credential expansion, and a repo-level provider binds it to `npm.pkg.github.com` (read-only, enforced) and the tarball CDN (which serves pre-signed URLs); forge identity stays the minted App token, which cannot read public packages owned by another org ([ADR 0114](ADRs/0114-github-packages-via-host-bound-workflow-token-provider.md)). On GitHub Actions the runner also reads the token itself to pull a private `ghcr.io` sandbox image before sandbox creation ([#9019](https://github.com/fullsend-ai/fullsend/issues/9019)); on GitLab CI it pulls an image on the instance's container registry with the job's `CI_REGISTRY_USER` and `CI_REGISTRY_PASSWORD`, and `fullsend prepare` uses the same pull before parallel runs, and its preflight sandbox makes the gateway pull the image. - Host-side API server design: Credential delivery tier 3 servers follow a uniform process contract (`--port`, `--token`, `--bind-address`, `/healthz`, `/tools.json`, `SIGTERM`). Network access is controlled via composable provider profiles — atomic capability profiles composed per-harness. Per-run UUID bearer tokens are delivered through OpenShell provider placeholders. File transfer uses `openshell sandbox upload/download` ([ADR 0046](ADRs/0046-host-side-api-server-design.md)). - Per-role GitHub Apps with manifest-based creation. Each agent role gets its own app with scoped permissions. PEMs stored in Secret Manager as `fullsend-{role}-app-pem` — one secret per role, shared across orgs on a mint. `ROLE_APP_IDS` uses the same shared-per-role model (`coder` → app ID). Caller authorization is per-repo enrollment (`PER_REPO_WIF_REPOS`); org isolation is enforced via WIF conditions and installation verification ([ADR 0007](ADRs/0007-per-role-github-apps.md), [ADR 0033](ADRs/0033-per-repo-installation-mode.md)). Public multi-tenant mint (`PER_REPO_WIF_REPOS=*`) with workflow provenance limited to the shared host allowlist (upstream plus `WORKFLOW_HOST_REPOS`) is defined in [ADR 0059](ADRs/0059-public-mint-mode-with-wildcard-allowlists.md); upstream-only provenance limits which workflows can call the mint, complementing [ADR 0029](ADRs/0029-central-token-mint-secretless-fullsend.md) multi-tenant blast-radius concerns. - Cross-org mint authorization: workflows may request tokens for a different org via optional `target_org` when the target org installs the role App and sets `FULLSEND_FOREIGN__REPOS` ([ADR 0060](ADRs/0060-cross-org-mint-authorization-via-org-variables.md)). Repo-level `FULLSEND_FOREIGN__REPOS` variables enable per-repo foreign grants (scoped to the specific target repo) and intra-org cross-repo access for per-repo callers, with disjoint authorization boundaries from org-level grants — repo-level for repo-scoped requests, org-level for installation-wide requests ([ADR 0083](ADRs/0083-repo-level-foreign-allow-list.md)). @@ -547,12 +563,20 @@ The existing design principle is that [the repo is the coordinator](problems/age input drivers to discover work from remote systems (Jira first), coordinates via source-native write-then-verify locks, and feeds the same dispatch pipeline as webhooks ([ADR 0063](ADRs/0063-polling-based-work-discovery.md)). Initial - scope is per-repo mode only. -- Jira poll candidate selection spends per-cycle slots only on candidates - whose Jira `updated` is newer than their per-repository checkpoint, picks - at random among them, and reads the per-cycle caps (N, default 5, and M, - default 50) from `tracker.jira.poll` within fixed bounds - ([ADR 0160](ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md)). + scope is per-repo mode only. In the target state the `jira-poll` driver no + longer uses those locks (see the next item). +- Jira poll candidate selection (target state): one poller per repository + reads every issue that changed within the backfill window + (`tracker.jira.poll.backfill_window_hours`, default 24), oldest change + first unless the configured query sets its own order, skips issues whose + Jira `updated` is not newer than their + per-repository checkpoint, and dispatches up to + `tracker.jira.poll.max_dispatches_per_cycle` records per cycle (default 100, + at most 250) within a five-minute cycle limit, with no row limit on the + candidate pool, no random pick, and no per-issue lock + ([ADR 0085](ADRs/0085-serve-every-changed-jira-issue.md), partially + superseding [ADR 0063](ADRs/0063-polling-based-work-discovery.md) and + [ADR 0160](ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md)). - Jira poll actor authorization does not require the poller to administer the Jira project once a repository adds a `jira` provider under `authorization:`. With no `jira` entry, every Jira event resolves through the @@ -602,6 +626,42 @@ The existing design principle is that [the repo is the coordinator](problems/age or explicit receipts to decide whether work has already been handled ([ADR 0098](ADRs/0098-entity-first-harness-evaluation.md), partially superseding [ADR 0063](ADRs/0063-polling-based-work-discovery.md)). +- Entity binding and CI integration (target state): harness `entity_kinds` maps + named slots to kinds, with source defaulting to work item and target to the + source kind. Repository `agents[].entities` maps those slots to lists of + scopes. Source defaults to `[native]`; omitted target copies the effective + source list, while additional slots require explicit bindings. + The configuration clone selects the native provider independently of the + runtime or CI platform. Its host and repository path supply defaults; + provider-default connections (`github`, `gitlab`, `forgejo`) can override the + instance, including GitHub.com to GitHub Enterprise. Reserved source names + default to those connections and can override queries and repository scopes. + The matching provider source and `native` resolve identically. Other provider names + require explicit external connections and scopes when bound. A source named + `native` is forbidden. Only source schedules work. + Harness `entity_filters` narrows each slot's source queries + by provider; primary selections combine for discovery and are checked before + full CEL admission. Other slot filters apply to explicit searches only. + GitHub source queries and harness filters share a bounded subset of native + UI metadata filters and Boolean combinations; unsupported syntax is rejected. + GitHub prefers GraphQL discovery with selective projections derived from + compiled CEL dependencies, progressively acquiring further decision and actor + evidence under ADR 0147. + The same resolved plan drives event + dispatch, broad polling, and bound-run checks, with CI providing trusted + invocation and execution rather than separate agent-routing decisions. + Installation verifies recurring discovery coverage for the effective plan + before resident eventless cycles can run. The target + [entity discovery contract](normative/entity-discovery/v1/) defines poll-pass + outcomes, coverage evidence, in-memory retry, and older-candidate backfill. + Target and additional slots make + typed scopes available to the run without implicit joins or broadcast writes. + Creation policy stays on connections independently of discovery; standalone + commands without context require explicit scope selection. Deprecated + `tracker` mappings translate in memory with warnings and preserved legacy + command defaults + ([ADR 0079](ADRs/0079-bind-entity-execution-through-named-sources.md), + [configuration contract](normative/entity-source-configuration/v1/)). - GitLab dispatch uses a native webhook fast-path for low-latency candidates and the cron-poller as the authoritative reconciliation backstop ([ADR 0125](ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). Native `merge_request_event` dispatch stays removed ([#7322](https://github.com/fullsend-ai/fullsend/issues/7322)). No external webhook bridge (see [ADR 0067](ADRs/0067-gitlab-cron-polling-event-dispatch.md) for the poller, credentials, and in-job gate). - Conversation participation: GitHub Discussions (and future chat systems) enter dispatch as resolved entities with `entity.kind: conversation`; when a @@ -707,15 +767,31 @@ The existing design principle is that [the repo is the coordinator](problems/age [ADR 0151](ADRs/0151-harness-human-role-minimums.md), [Authorization Contract v2](normative/authorization/v2/)). -- Entity-source discovery (target state): `fullsend poll` combines admissible - harness queries into one logical candidate search per source scope and routes - possible matches locally. A bound `run` rechecks source-query membership - before event-backed or eventless sandbox cycles - ([ADR 0149](ADRs/0149-coalesce-entity-source-discovery-queries.md)). +- Entity-source discovery (target state): `fullsend poll` combines source + queries into one logical candidate search per source scope. Source membership + follows native provider semantics, with exact checks over already-fetched + data or batched provider checks; Jira accepts native JQL, GitHub accepts a + bounded subset of UI metadata filters and Boolean combinations, and GitLab + starts with open/closed/all state selections. A bound `run` rechecks current + membership before event-backed or eventless sandbox cycles. Provider-native + selection can reflect changes excluded from the actor-filtered CEL view; it + grants no authority and does not admit content to the model + ([ADR 0149](ADRs/0149-coalesce-entity-source-discovery-queries.md), partially + superseded by [ADR 0079](ADRs/0079-bind-entity-execution-through-named-sources.md)). Implementation and the normative query protocol are tracked in [#8418](https://github.com/fullsend-ai/fullsend/issues/8418) and [#8421](https://github.com/fullsend-ai/fullsend/issues/8421). +- Decided, not yet implemented: a saga journal stores versioned JSON in the + control repository, initially on GitLab, independently of the source forge + and tracker. Workflow-supplied trusted host adapters claim work and reconcile + it on subsequent invocations. They retain separate dispatch, execution and + publication receipts for each target. + Conditional updates and ownership generations support cross-host recovery; + CI finalization provides only a best-effort checkpoint. Domain adapters + retain operation, completion and compensation semantics + ([ADR 0165](ADRs/0165-recover-work-through-repository-owned-operation-journals.md)). + **Open questions:** - What provider query plans can support entity-first evaluation over the @@ -724,18 +800,30 @@ The existing design principle is that [the repo is the coordinator](problems/age [ADR 0147](ADRs/0147-evaluate-entity-cel-over-selectively-acquired-data.md) for selective acquisition and its authorization rules, and [ADR 0149](ADRs/0149-coalesce-entity-source-discovery-queries.md) - for query combination and local routing. The normative discovery protocol, - including query syntax, adapter mappings, and discovery coverage evidence, - remains open. + for query combination and local routing. Named source bindings and provider + query configuration are decided in + [ADR 0079](ADRs/0079-bind-entity-execution-through-named-sources.md) and the + [Entity-source configuration v1 contract](normative/entity-source-configuration/v1/README.md). + Provider-adapter mappings, pagination and consistency proofs, and coverage + evidence needed to establish complete discovery remain open for the discovery + protocol. - Is GitHub's event system sufficient for forge-native duplicate protection, or do we need additional coordination beyond label/state conventions and agent idempotency? (Jira polling per ADR 0063 uses entity-property locks and runner - lock refresh; ADR 0098 does not resolve this question.) + lock refresh, which ADR 0085 removes for the `jira-poll` driver in favor of + one poller per repository; ADR 0165 chooses an operation journal for + recoverable effects, while adapter implementation and external-system + guarantees remain open.) - How does work assignment interact with the backlog/priority agent described in [agent-architecture.md](problems/agent-architecture.md)? - How should explicit cancellation, retry, and reassignment interact with the automatic event-coalescing policy in [ADR 0106](ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md)? -- Does the coordinator need state (a queue, a lock, a claim system), or can it be stateless and event-driven? +- Does the coordinator need state (a queue, a lock, a claim system), or can it + be stateless and event-driven? (ADR 0165 requires durable claims for workflows + that opt in. Adapter implementation and packaging remain open in + [#9253](https://github.com/fullsend-ai/fullsend/issues/9253) and the + tracker-first integration in + [#9260](https://github.com/fullsend-ai/fullsend/issues/9260).) - When should a conversation or thread be linked to a work item (e.g. Discussion → issue) so a conversation-native agent can hand off to `/fs-code` without violating entity-context separation ([ADR 0076](ADRs/0076-slash-command-entity-context-separation.md), @@ -847,7 +935,7 @@ the inheritance model: fullsend defaults, then repo baseline (`config.base.yaml` **Decided:** - Config-level agent registration: an `agents` list in the per-repo config declares agent harness sources as pinned URLs or local paths, replacing compiled-in agent discovery ([ADR 0058](ADRs/0058-agent-registration.md)). -- Runtime resolution: `fullsend run ` resolves agents in two tiers: (1) entries from the config's `agents` list (highest priority), (2) runtime fallback to the `fullsend-ai/agents` repository for known first-party agents not in config. The agents-repo fallback is a transitional mechanism for the agent extraction; it will be removed once all users have migrated to config-driven registration (ADR 0058 Phase 5). On a GitHub host other than github.com (`GITHUB_SERVER_URL`, with `GITHUB_API_URL` set to that instance's API), the fallback resolves the ref and reads the harness through that host's API, recording it under `https:///fullsend-ai/agents/raw//…`, which must be covered by `allowed_remote_resources`; that host is also added to the run's fetch policy, which otherwise admits only `github.com` and `raw.githubusercontent.com`. The relative companion files that harness references (agent, policy, scripts) are read the same way, pinned to the same commit and subject to the same allowlist. Directory resources (a relative skill or plugin directory, or the helper files next to a script) are read the same way: the directory is listed and its files are read through that host's API at the same commit, with the same token and allowlist check, instead of by git sparse checkout from `raw.githubusercontent.com`, and are bounded by the same file-count and size limits. The offline cache lookup does not yet resolve on such a host: it still uses the `raw.githubusercontent.com` prefix. +- Runtime resolution: `fullsend run ` resolves agents in two tiers: (1) entries from the config's `agents` list (highest priority), (2) runtime fallback to the `fullsend-ai/agents` repository for known first-party agents not in config. The agents-repo fallback is a transitional mechanism for the agent extraction; it will be removed once all users have migrated to config-driven registration (ADR 0058 Phase 5). On a GitHub host other than github.com (`GITHUB_SERVER_URL`, with `GITHUB_API_URL` set to that instance's API), the fallback resolves the ref and reads the harness through that host's API, recording it under `https:///fullsend-ai/agents/raw//…`, which must be covered by `allowed_remote_resources`; that host is also added to the run's fetch policy, which otherwise admits only `github.com` and `raw.githubusercontent.com`. The relative companion files that harness references (agent, policy, scripts) are read the same way, pinned to the same commit and subject to the same allowlist. Directory resources (a relative skill or plugin directory, or the helper files next to a script) are read the same way: the directory is listed and its files are read through that host's API at the same commit, with the same token and allowlist check, instead of by git sparse checkout from `raw.githubusercontent.com`, and are bounded by the same file-count and size limits. The offline cache lookup does not yet resolve on such a host: it still uses the `raw.githubusercontent.com` prefix. When a Forgejo agent source is configured (`FULLSEND_FORGEJO_URL`, `FULLSEND_FORGEJO_AGENTS_REPO`, `FULLSEND_FORGEJO_AGENTS_REF`), it replaces the GitHub fallback: definitions are read from that Forgejo instance, pinned to a full commit SHA, and recorded under Forgejo raw URLs that `allowed_remote_resources` must cover. A failure to resolve or read from the Forgejo source is an error; there is no fallback to GitHub (see [`fullsend run`](cli/run.md)). - Config lookup: config entries are looked up directly via `findConfigAgentEntry`; the agents-repo fallback operates independently when the agent is not found in config. Builds on [ADR 0045](ADRs/0045-forge-portable-harness-schema.md) harness identity model. - CLI management: `fullsend agent add|list|set|update|remove` manages config entries and auto-pins URLs to a commit SHA with an integrity hash. - Agent generation: `fullsend agent new ` writes a complete custom agent — harness, agent definition, result schema, post-script, and the base policy a per-repo install does not vendor; its built-in providers are bare names whose definitions and profiles come from the `fullsend` binary — validates it with the loader dispatch uses, and registers it through the `agent add` path above. A `trigger:` is mandatory, because a trigger-less harness registers and validates and is then silently never dispatched; `--role` is a closed table of the roles the hosted mint serves, so an unservable role fails locally rather than as a `403` at first dispatch ([ADR 0102](ADRs/0102-generate-custom-agents-from-the-cli.md)). @@ -1264,9 +1352,10 @@ GitHub event ──► SHIM WORKFLOW (.github/workflows/fullsend.yaml in the rep ║ │ │ ║ ║ │ Extracts from destroyed sandbox: │ ║ ║ │ /sandbox/workspace/output/, JSONL transcripts, │ ║ - ║ │ SafeDownload repo (sanitize symlinks, strip hooks) │ ║ - ║ │ replacement refs, grafts, commit graphs removed │ ║ - ║ │ root shallow state restored from pre-upload snapshot │ ║ + ║ │ SafeDownload repo: sanitized, host settings restored │ ║ + ║ │ hooks, symlinks and ancestry overrides removed │ ║ + ║ │ downloaded Git config rebuilt from declared format │ ║ + ║ │ shallow state restored from pre-upload snapshot │ ║ ║ │ Post-agent secret scan (redact from extracted output). │ ║ ║ │ │ ║ ║ │ Post-script (scripts/post-code.sh, with PUSH_TOKEN): │ ║ diff --git a/docs/cli/README.md b/docs/cli/README.md index 3d36da979d..a0f32c2a2d 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -27,8 +27,10 @@ To update an installed binary later, run [`fullsend self-update`](self-update.md | Command | Description | |---------|-------------| | [`fullsend run`](run.md) | Execute an agent locally in a sandbox. See [running agents locally](../guides/user/running-agents-locally.md). | -| `fullsend poll` | Discover forge events and dispatch agent pipelines. `--forge gitlab` runs the cron poller ([ADR 0067](../ADRs/0067-gitlab-cron-polling-event-dispatch.md)); events-mode polling also recovers issue opens whose webhook delivery was missed. `--input-driver jira-poll` polls Jira (see [Jira integration](../guides/user/jira-integration.md)). It reads the Jira site, API gateway, project, and query only from the effective `tracker.jira` config (`base_url` and `project` required; the removed `--jira-url`, `--jira-project`, and `--jql` flags are rejected), authenticates with `FULLSEND_JIRA_TOKEN` (plus `FULLSEND_JIRA_EMAIL` for a bot user) or with OAuth 2.0 client credentials via `FULLSEND_JIRA_CLIENT_ID` and `FULLSEND_JIRA_CLIENT_SECRET`, and skips the cycle unless `tracker.jira.poll.enabled` is `true`; by default it writes dispatch records (`--output`) for a GitHub repository (`--target-repo`, an `owner/repo` slug; one that contains `..` is refused), and with `--target-forge gitlab` it starts the protected agent pipelines of the GitLab project named by `--project` (full path, nested groups allowed; default `CI_PROJECT_PATH`) on the https `--gitlab-url` instance, through the same signed, typed-input dispatch route and Poller credential as the GitLab poller, advancing a Jira issue's checkpoint only once its pipelines are created ([GitLab runtime](../guides/user/jira-integration.md#gitlab-runtime)). `--input-driver gitlab-webhook` is the GitLab dispatcher job's webhook fast-path ([ADR 0125](../ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). It reads the native webhook body from the file-type `TRIGGER_PAYLOAD` variable, re-validates it against the GitLab API, and creates each routed stage's pipeline (typed inputs, `FULLSEND_DISPATCH_SECRET` HMAC) with the poller-role credential (the `api` route, the default). Scheduled cron polling and the webhook fast path run as the trigger-only service account: once its dispatch activation is recorded, the managed webhook carries the account's pipeline trigger token ([#8509](https://github.com/fullsend-ai/fullsend/issues/8509)), the scaffold sets `FULLSEND_GITLAB_DISPATCH_ROUTE=child-pipeline`, and the command instead starts each pipeline with the job's own `CI_JOB_TOKEN` through the pipeline trigger API (`source=pipeline`); an unknown route, or `child-pipeline` without `CI_JOB_TOKEN`, fails closed. `fullsend poll --forge gitlab --print-dispatch-routes` prints the routes the CLI supports (`api` and `child-pipeline`) and exits; the scaffold runs it before selecting `child-pipeline`, and a CLI that predates the route rejects the flag, so the job stops before any dispatch. It requires `--project`, which has no `CI_PROJECT_PATH` fallback. It deduplicates against the poller's per-mode state on the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches, so an event the webhook dispatched is not dispatched again by the poller, and the reverse. Shared poller state is occurrence-aware (label additions are keyed on the resource label event ID, dispatched keys are retained for the webhook freshness window, and a failed label dispatch is handed back to the poller as a pending retry); legacy persisted keys keep working. Older pollers do not recognise the new label keys, so before a rollback or mixed-version run, follow the [ADR 0132](../ADRs/0132-occurrence-aware-shared-poller-state.md) guidance to drain in-flight poll jobs or pin every poller to one version. Both GitLab drivers dispatch the fix stage only for a changes-requested marker note authored by the registered Analyst, whose numeric user ID the scaffold exports as the job-local `FULLSEND_GITLAB_ANALYST_USER_ID`. | -| `fullsend dispatch` | Evaluate harness CEL triggers for one forge event and print the dispatch matrix (`--output-driver gha-matrix` or `json`); used by the dispatch workflow's `Harness dispatch` job. `--route ` (`review`, `retro`, `triage` or `prioritize`) instead decides routing for that built-in agent and prints one JSON line, `{"agent":"","decision":"run\|skip\|bash","reason":"…","harness":"config:\|agents@"}` (`harness` is optional: it is omitted when the harness cannot be resolved or the decision did not need it, as for `bash`): `run` or `skip` when the repository set `agents[].trigger` on the agent's entry ([Choosing when review runs](../guides/user/customizing-agents.md#choosing-when-review-runs), [Choosing when retro runs](../guides/user/customizing-agents.md#choosing-when-retro-runs), [Choosing when triage and prioritize run](../guides/user/customizing-agents.md#choosing-when-triage-and-prioritize-run)), `bash` to leave the decision to the workflow's built-in rules. The dispatch workflow's `Route` job runs it. With `--input-driver gha-event`, a GitHub bot actor's registered fullsend role is looked up first through the mint (a layered `mint_url`, else `FULLSEND_MINT_URL`) with the job's Actions OIDC token, so the job needs `id-token: write` ([ADR 0107](../ADRs/0107-bot-identity-resolution-for-dispatch-authorization.md)); label-added events skip the lookup, and an unregistered bot or a failed lookup is denied (an empty matrix, or a `skip` decision) rather than failing the command. An absent config falls back to `FULLSEND_MINT_URL`, but a config that fails to load or parse is a failed lookup, not a fallback. | +| `fullsend review-dedup` | Decide whether an unchanged synchronize event can skip review, publish the skip note, or supersede an earlier skip note. | +| [`fullsend prepare`](prepare.md) | Resolve an agent's sandbox image as `fullsend run` does, pre-pull a private image with the CI job's registry credential (`ghcr.io` on GitHub Actions, `CI_REGISTRY` on GitLab CI) as `run` does, and create and delete a restrictive preflight sandbox, which makes the gateway pull the image. Run it once before many parallel runs. `--json` prints the resolved image, architecture, and result. | +| `fullsend poll` | Discover forge events and dispatch agent pipelines. `--forge gitlab` runs the cron poller ([ADR 0067](../ADRs/0067-gitlab-cron-polling-event-dispatch.md)); events-mode polling also recovers issue opens whose webhook delivery was missed. `--input-driver jira-poll` polls Jira (see [Jira integration](../guides/user/jira-integration.md)). It reads the Jira site, API gateway, projects, and query only from the effective entity-source configuration: the source translated from `tracker.jira` (`base_url` and `project` required) or an explicit Jira `entity_sources` entry bound in an enabled agent's `entities.source` (the removed `--jira-url`, `--jira-project`, and `--jql` flags are rejected). It authenticates with `FULLSEND_JIRA_TOKEN` (plus `FULLSEND_JIRA_EMAIL` for a bot user) or with OAuth 2.0 client credentials via `FULLSEND_JIRA_CLIENT_ID` and `FULLSEND_JIRA_CLIENT_SECRET`. Those credentials are reused only for the connection translated from `tracker.jira`; a source on an explicit Jira connection is refused until a separately provisioned credential binding exists, and explicit sources are refused when enabled agents bind different `entities.source` lists. It skips the cycle unless a selected source permits discovery (`tracker.jira.poll.enabled` is `true` for the translated source); by default it writes dispatch records (`--output`) for a GitHub repository (`--target-repo`, an `owner/repo` slug; one that contains `..` is refused), and with `--target-forge gitlab` it starts the protected agent pipelines of the GitLab project named by `--project` (full path, nested groups allowed; default `CI_PROJECT_PATH`) on the https `--gitlab-url` instance, through the same signed, typed-input dispatch route and Poller credential as the GitLab poller, advancing a Jira issue's checkpoint only once its pipelines are created ([GitLab runtime](../guides/user/jira-integration.md#gitlab-runtime)). `--input-driver gitlab-webhook` is the GitLab dispatcher job's webhook fast-path ([ADR 0125](../ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). It reads the native webhook body from the file-type `TRIGGER_PAYLOAD` variable, re-validates it against the GitLab API, and creates each routed stage's pipeline (typed inputs, `FULLSEND_DISPATCH_SECRET` HMAC) with the poller-role credential (the `api` route, the default). Scheduled cron polling and the webhook fast path run as the trigger-only service account: once its dispatch activation is recorded, the managed webhook carries the account's pipeline trigger token ([#8509](https://github.com/fullsend-ai/fullsend/issues/8509)), the scaffold sets `FULLSEND_GITLAB_DISPATCH_ROUTE=child-pipeline`, and the command instead starts each pipeline with the job's own `CI_JOB_TOKEN` through the pipeline trigger API (`source=pipeline`); an unknown route, or `child-pipeline` without `CI_JOB_TOKEN`, fails closed. `fullsend poll --forge gitlab --print-dispatch-routes` prints the routes the CLI supports (`api` and `child-pipeline`) and exits; the scaffold runs it before selecting `child-pipeline`, and a CLI that predates the route rejects the flag, so the job stops before any dispatch. It requires `--project`, which has no `CI_PROJECT_PATH` fallback. It deduplicates against the poller's per-mode state on the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches, so an event the webhook dispatched is not dispatched again by the poller, and the reverse. Shared poller state is occurrence-aware (label additions are keyed on the resource label event ID, dispatched keys are retained for the webhook freshness window, and a failed label dispatch is handed back to the poller as a pending retry); legacy persisted keys keep working. Older pollers do not recognise the new label keys, so before a rollback or mixed-version run, follow the [ADR 0132](../ADRs/0132-occurrence-aware-shared-poller-state.md) guidance to drain in-flight poll jobs or pin every poller to one version. Both GitLab drivers dispatch the fix stage only for a changes-requested marker note authored by the registered Analyst, whose numeric user ID the scaffold exports as the job-local `FULLSEND_GITLAB_ANALYST_USER_ID`. | +| `fullsend dispatch` | Evaluate harness CEL triggers for one forge event and print the dispatch matrix (`--output-driver gha-matrix` or `json`); used by the dispatch workflow's `Harness dispatch` job. `--route ` (`review`, `retro`, `triage` or `prioritize`) instead decides routing for that built-in agent and prints one JSON line, `{"agent":"","decision":"run\|skip\|bash","reason":"…","harness":"config:\|agents@"}` (`harness` is optional: it is omitted when the harness cannot be resolved or the decision did not need it, as for `bash`): `run` or `skip` when the repository set `agents[].trigger` on the agent's entry ([Choosing when review runs](../guides/user/customizing-agents.md#choosing-when-review-runs), [Choosing when retro runs](../guides/user/customizing-agents.md#choosing-when-retro-runs), [Choosing when triage and prioritize run](../guides/user/customizing-agents.md#choosing-when-triage-and-prioritize-run)), `bash` to leave the decision to the workflow's built-in rules. Built-in agents resolve from a configured Forgejo instance when `FULLSEND_FORGEJO_URL` is set, as in [`fullsend run`](run.md#agent-definitions-from-a-forgejo-instance). The dispatch workflow's `Route` job runs it. With `--input-driver gha-event`, a GitHub bot actor's registered fullsend role is looked up first through the mint (a layered `mint_url`, else `FULLSEND_MINT_URL`) with the job's Actions OIDC token, so the job needs `id-token: write` ([ADR 0107](../ADRs/0107-bot-identity-resolution-for-dispatch-authorization.md)); label-added events skip the lookup, and an unregistered bot or a failed lookup is denied (an empty matrix, or a `skip` decision) rather than failing the command. An absent config falls back to `FULLSEND_MINT_URL`, but a config that fails to load or parse is a failed lookup, not a fallback. `--input-driver forgejo-event` maps a Forgejo Actions event payload (`FORGEJO_EVENT_PATH`, bound to `FORGEJO_SERVER_URL` and the repository); it is the default when `FORGEJO_ACTIONS` or `GITEA_ACTIONS` is `true`, even when `GITHUB_EVENT_PATH` is also set. This changes the default for pipelines on Forgejo or Gitea runners that relied on the implicit `gha-event` driver; pass `--input-driver gha-event` to restore the previous behavior. No Forgejo permission lookup is wired yet, so its events are denied by the authorization gate ([Forgejo adapter notes](../normative/normalized-event/v1/README.md#forgejo-adapter-notes)). | | `fullsend lock [agent-name]` | Pin remote dependencies to `lock.yaml`. If `lock.yaml` exists but cannot be parsed or declares an unsupported version, the command exits without writing and leaves the file unchanged. An entry is stale when the harness file or the `harness:` block of the agent's `agents:` entry has changed. When it composes a harness (a new or stale entry, or `--update`), it also prints the harness diagnostics, including [reserved `env.sandbox` keys](run.md#reserved-envsandbox-keys). A current entry is not composed, so its keys are not checked, and `lock` composes without event context, so keys from event-guarded overlays are reported only by `fullsend run`. A harness whose runtime fetch service can start (`allow_runtime_fetch: true`, URL-sourced skill or plugin directories, or a bare, deprecated `allowed_remote_resources` declaration) must have every harness-level `allowed_remote_resources` prefix covered by the config-level allowlist — `config.yaml`'s `allowed_remote_resources` plus the built-in default prefixes (the defaults are included when the list is omitted or non-empty; an explicit `allowed_remote_resources: []` stays deny-all and excludes them); `lock` fails naming an uncovered prefix, and fails closed when no repository config (`config.yaml` or `config.base.yaml`) exists. With a `harness:` block on the agent's entry, the prefixes checked are the ones the block sets. | | `fullsend lint` | Lint `config.yaml` and agent harness definitions — deprecations, misconfigurations, and file checks, with diagnostics for each enabled agent, or for one agent with `fullsend lint `. See [`fullsend lint`](lint.md), and [Checking a trigger before you merge](../guides/user/cel-triggers-reference.md#checking-a-trigger-before-you-merge) for a walkthrough. | | `fullsend scan` | Run security scanners on agent input/output | diff --git a/docs/cli/lint.md b/docs/cli/lint.md index 45a87d70f9..1dd9dc7990 100644 --- a/docs/cli/lint.md +++ b/docs/cli/lint.md @@ -42,7 +42,10 @@ Each enabled `agents:` entry is resolved and composed through the same machinery fetched from the allowlisted hosts with caching. - Override-only entries (settings only, `source:` unset) resolve their harness from the [agents repository](https://github.com/fullsend-ai/agents), exactly as run does — - linting a built-in agent lints the fetched upstream harness. Under `--offline` these + linting a built-in agent lints the fetched upstream harness. When `FULLSEND_FORGEJO_URL` + is set, they resolve from the configured Forgejo repository at its pinned commit + instead (see [Agent definitions from a Forgejo instance](run.md#agent-definitions-from-a-forgejo-instance)). + Under `--offline` these use the agents revision most recently cached by an online run in the same `.fullsend` directory. Run that online run with the same forge (`--forge` or CI auto-detection) as the offline run; otherwise the forge-specific files are not cached and the diff --git a/docs/cli/prepare.md b/docs/cli/prepare.md new file mode 100644 index 0000000000..6458c45e02 --- /dev/null +++ b/docs/cli/prepare.md @@ -0,0 +1,174 @@ +--- +sidebar_label: fullsend prepare +--- + +# fullsend prepare + +Prepare the environment for an agent without running it. `fullsend prepare` +resolves the agent's sandbox image the same way [`fullsend run`](run.md) does. +It pre-pulls a private image with the CI job's registry credential (the workflow +token for `ghcr.io` on GitHub Actions, the job's registry login for the +instance's container registry on GitLab CI), as `fullsend run` does. Then it creates and deletes a minimal sandbox. The OpenShell gateway pulls +the image into its own image store when that sandbox starts, which also checks +that the gateway can start one. + +It runs no pre-script, agent, validation, post-script, or inference, and it +mints no tokens. + +Run it once before you start many `fullsend run` invocations in parallel, for +example in an evaluation harness. The image is then pulled once instead of by +every run, and a broken environment fails once, with a named cause, instead of +failing every parallel run. + +## Usage + +```bash +fullsend prepare [flags] +``` + +## Flags + +| Flag | Description | +|------|-------------| +| `--fullsend-dir` | Path to the `.fullsend` configuration directory (default `.fullsend`) | +| `--env-file` | Load environment variables from a dotenv file (repeatable), as with `fullsend run` | +| `--forge` | Forge platform (`github`, `gitlab`). When omitted, resolved as `fullsend run` resolves it | +| `--event-file` | Normalized event JSON file for overlay resolution. When omitted, the dispatch payload is read, as with `fullsend run` | +| `--json` | Print the result as JSON on stdout. Progress goes to stderr | +| `--offline` | Reject network fetches; only use cached remote resources | + +Pass the same `--fullsend-dir`, `--forge`, `--event-file`, and environment +that the runs use. The image can depend on all of them. + +## What it does + +1. Composes the agent's harness through the same code path as `fullsend run`: + the agent source from `config.yaml` or the agents repository, the `base:` + chain, the agent's `harness:` blocks, `lock.yaml` pins, and overlays. The + agents repository can be a Forgejo repository when `FULLSEND_FORGEJO_URL` and + the other `FULLSEND_FORGEJO_*` variables are set (see + [Agent definitions from a Forgejo instance](run.md#agent-definitions-from-a-forgejo-instance)). +2. Applies the `FULLSEND_SANDBOX_IMAGE` override, if set. +3. Checks that the OpenShell CLI is installed and that a gateway is running. +4. Pre-pulls the image the way `fullsend run` does (see + [Registry credentials](#registry-credentials)). This applies only to a + private image on `ghcr.io` on GitHub Actions or on the instance's container + registry on GitLab CI, and only into the local Podman store. It does not warm the gateway's image store, and `fullsend prepare` + does not try to find out where that store is: + - With no credential, or for any other image, nothing is pulled locally. + - With a credential, an image already in the local Podman store is not + pulled again, and a missing one is pulled with the credential. If the + pull fails, or Podman is not installed, the command warns and goes on, as + `fullsend run` does: the gateway pulls the image without the credential, + so a public image keeps working. A full disk is reported by the preflight. +5. Creates one sandbox from the image, with no providers and no workload, under + a restrictive policy (the base policy generated agents use: filesystem, + Landlock, and process rules, and no network access). It waits until the + sandbox is ready. The wait uses the harness `sandbox_timeout_seconds`, and + interrupting the command stops it. The gateway pulls any image of its own + that it needs at this point, such as its supervisor image, and the image + counts as `ready` only when this sandbox starts from it. The command then + deletes the sandbox. A sandbox that fails to start is also deleted. A + sandbox that cannot be deleted fails the command with `sandbox-cleanup`, + and the hint names the `openshell sandbox delete` command to run. The + preflight makes one attempt, so a broken environment fails fast. + +The preflight runs even when the image is already in the local Podman store. + +### Registry credentials + +`fullsend prepare` pulls with the same code, and the same job-scoped credential, +that `fullsend run` uses before it creates a sandbox: + +- On GitHub Actions, the workflow token for an image on `ghcr.io`. `fullsend run` + gets it as `GH_WORKFLOW_TOKEN` when it mints its agent token. `fullsend prepare` + mints nothing, so it uses an exported `GH_WORKFLOW_TOKEN` or, when that is not + set, the job's `GH_TOKEN` (or, when that is empty, `GITHUB_TOKEN`), which must + look like a token. It does not export the token. See + [GitHub Packages credentials](run.md#github-packages-credentials). +- On GitLab CI, the job's `CI_REGISTRY_USER` and `CI_REGISTRY_PASSWORD` for an + image on the instance's container registry (`CI_REGISTRY`). + +The credential is written to an auth file in a private temporary directory +and removed after the pull. It is redacted from every message. + +Unlike `fullsend run`, `fullsend prepare` does not consume the runner secrets +bundle (`FULLSEND_GITHUB_RUNNER_SECRETS` and +`FULLSEND_GITHUB_RUNNER_SECRETS_FILE`), so the runs that follow can still read +it. It hides the bundle from every process it starts, such as Podman and +OpenShell, while it runs, and restores it when it exits. The bundle file is +not deleted. + +## Exit status and failures + +The command exits `0` when the preflight sandbox started from the image. Otherwise it exits non-zero and names the cause. When it recognizes +the cause, it also prints a hint, for example to free disk space. The `kind` +field of the JSON result names the cause: + +| Kind | Cause | +|------|-------| +| `configuration` | The harness could not be resolved, or a flag, env file, event file, or `config.yaml` is invalid. An unknown agent is reported this way too | +| `openshell-unavailable` | The OpenShell CLI is not installed | +| `gateway-unavailable` | No OpenShell gateway is running | +| `disk-space` | The gateway ran out of disk space while pulling the image or starting the sandbox | +| `registry-auth` | The registry refused the gateway's pull | +| `image-unresolvable` | The image reference could not be resolved | +| `sandbox-preflight` | The preflight sandbox did not start for another reason | +| `sandbox-cleanup` | The preflight sandbox started but could not be deleted | +| `canceled` | The command was interrupted | + +## JSON output + +With `--json`, stdout holds one JSON object, also when the command fails: + +```json +{ + "ok": true, + "agent": "code", + "harness": "/work/repo/.fullsend/harness/code.yaml", + "arch": "amd64", + "images": [ + { + "role": "sandbox", + "ref": "ghcr.io/fullsend-ai/fullsend-code:latest", + "source": "harness", + "status": "ready", + "detail": "pulled into the local Podman store with the job's registry credential; the preflight sandbox started from it, so the gateway has pulled it" + } + ], + "preflight": { + "sandbox": "fs-cod-1a2b3c4d5e6f", + "status": "passed" + } +} +``` + +| Field | Description | +|-------|-------------| +| `ok` | `true` when preparation succeeded | +| `agent` | The agent name | +| `harness` | The harness file the agent resolved to | +| `arch` | The sandbox architecture: the host's, or `FULLSEND_SANDBOX_ARCH` when set to a supported value | +| `images[].role` | `sandbox` | +| `images[].ref` | The resolved image reference. Empty when the harness sets no image and the gateway uses its default sandbox image | +| `images[].source` | `harness`, `FULLSEND_SANDBOX_IMAGE`, or `gateway-default` | +| `images[].status` | `ready` (the preflight sandbox started from it), `failed` (the gateway could not pull or resolve it), or `unverified` (the preflight did not get that far, or failed for another reason). A local pull alone never makes it `ready` | +| `images[].detail` | What happened in the local Podman store, and what the gateway does | +| `preflight.sandbox` | The name of the preflight sandbox | +| `preflight.status` | `passed` or `failed` | +| `preflight.cleanup` | `deleted` or `failed` once a sandbox was created. `failed` means the sandbox may still exist | +| `error.kind` | The cause of a failure (see the table above) | +| `error.message` | The error message | +| `error.hint` | What to try next, when the cause is recognized | + +## Example + +Prepare once, then fan out: + +```bash +fullsend prepare code --fullsend-dir .fullsend --json > prepare.json || exit 1 +for case in cases/*; do + fullsend run code --fullsend-dir .fullsend --target-repo "$case" & +done +wait +``` diff --git a/docs/cli/repos.md b/docs/cli/repos.md index a7390fc080..f64fe38546 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -15,6 +15,23 @@ These flags are inherited by all `repos` subcommands: | `--gitlab-token` | | GitLab personal or project access token (overrides `GITLAB_TOKEN` env var) | | `--verbose` | `false` | Show the underlying API error text (for example the GitLab HTTP status and server message) instead of `(server error text withheld)`, and log each GitLab API request to stderr as `gitlab api: -> ` | +### GitLab token permissions + +For `repos install` on GitLab, use a project-scoped fine-grained personal +access token from a user with the Maintainer (or Owner) role on the project. +Grant it the permissions in +[Configuring GitLab § Installer token permissions](../guides/getting-started/configuring-gitlab.md#installer-token-permissions). +That set was validated end to end for an MR-based installation; it is not a +guaranteed minimum for every GitLab version, tier, or project state. Without +the optional Resource Group permissions, install warns and skips +resource-group lock healing. Without Push Rule: Read, it skips the push-rule +branch-name preflight. Add Project: Update when you ask fullsend to change +`ci_pipeline_variables_minimum_override_role`. `repos uninstall` needs more: +at least Resource Access Token: Read to list and revoke role project access +tokens. Where fine-grained tokens are not available, or a fine-grained token +lacks a permission, use a personal or group access token with the legacy +`api` scope. + ### Verbose output By default, API failures from credential-bearing calls are reported without @@ -59,7 +76,7 @@ The former `repos migrate ` command (per-org to per-repo migration) has bee fullsend repos install [repos...] [flags] ``` -Converge repos to the desired state defined in a manifest. This is the primary command for managing per-repo installations — it provisions repositories declared in the manifest, repairs component drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — a disabled GitLab schedule is reported as drift and reactivated only when `--reactivate-schedules` is passed; typed GitLab jobs require verified `no_one_allowed` before template delivery, even with `FULLSEND_GITLAB_PIPELINE_VAR_RESTRICTION=enforced` — see [GitLab Role-Credential Contract](../contributing/gitlab-role-credentials.md#how-a-job-selects-its-credential)), repairs scaffold content drift (including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref), and upgrades scaffold refs. +Converge repos to the desired state defined in a manifest. This is the primary command for managing per-repo installations — it provisions repositories declared in the manifest, repairs component drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — a disabled GitLab schedule is reported as drift and reactivated only when `--reactivate-schedules` is passed; typed GitLab jobs require verified `no_one_allowed` before template delivery, even with `FULLSEND_GITLAB_PIPELINE_VAR_RESTRICTION=enforced`, unless the repository entry sets `allow_insecure_pipeline_variables` — see [GitLab Role-Credential Contract](../contributing/gitlab-role-credentials.md#how-a-job-selects-its-credential)), repairs scaffold content drift (including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref), and upgrades scaffold refs. `repos.yaml` is the single source of persistent, non-secret install settings and of repository membership. Install reads every setting from the manifest; its flags supply only credentials, local vendoring artifacts, and controls for one run (see [Flags](#flags)). To change a setting or add a repository, edit `repos.yaml` or use [`repos set`](#repos-set), then run install. Moving from `github setup` or from the removed configuration flags is covered in [Migrating to manifest-driven `repos install`](../guides/getting-started/migrating-from-github-setup.md). @@ -85,6 +102,15 @@ Runs in two phases: 1. **Select** — the repositories to converge are chosen from the entries declared in the manifest (see [Selecting repositories](#selecting-repositories)). Positional arguments only filter declared entries; they never create, copy, or carve out entries. Every selected repository must resolve an [inference authentication selection](#inference-authentication-selection), and its [effective infrastructure values](#effective-infrastructure-values) must be consistent, or that repository fails before any write. 2. **Converge** — all selected repos are converged through a unified probe → diff → apply pipeline. Repos whose shim workflow is not yet on the default branch are freshly installed (scaffold files, variables, secrets, a declared configuration preset as `.fullsend/config.base.yaml`, and a canonical managed `.fullsend/config.yaml`) onto the initialization branch (`fullsend/scaffold-install`). That includes a re-run while the initialization PR/MR is still open: variables and secrets may already exist from the first run, but the installer still updates the same initialization PR rather than opening a competing upgrade PR. Repos whose workflow is already on the default branch are checked for drift (workflow, thin callers, variables, secrets, pipeline schedules, GitLab poller protected-ref pipeline access — repaired automatically, except a disabled GitLab schedule, which is reported as drift and reactivated only with `--reactivate-schedules`; typed GitLab dispatch's required pipeline-variable restriction; legacy variable-based wrappers are refused, and a leftover pipeline variable on a managed schedule is not repaired and must be removed manually), scaffold content drift (repaired automatically, including structural rewrites of `.gitlab/ci/fullsend-pipeline.yml` at an unchanged template ref), declared configuration-preset drift against `.fullsend/config.base.yaml` (replaced wholesale; `.fullsend/config.yaml` is preserved), managed `.fullsend/config.yaml` drift (replaced wholesale; an existing file without the ownership marker stops that repository before any writes until it is adopted, while the other selected repositories still converge), and scaffold ref drift (upgraded automatically). When no configuration preset resolves for a repo, the desired state is no `.fullsend/config.base.yaml`. An existing base file then stops that repo's fresh or repeat install, including `--dry-run`, before any writes, with an error telling you to declare a `config_base` source or remove the file. A declared preset that cannot be loaded (fetch failure, `sha256` mismatch, invalid content) fails only that repository: install reports the error in that repository's result, converges the other selected repositories, and exits non-zero. An HTTPS preset fetch that fails at the transport level (for example, a dropped connection reported as `EOF`) is retried once, and the error names the phase that failed (DNS, connect, TLS handshake, awaiting the response), the remote address, and the elapsed time. +```bash +fullsend repos install -f repos.yaml +fullsend repos install --dry-run +fullsend repos install acme/api acme/web +fullsend repos install "acme/*" --direct --concurrency 8 +``` + +### Managed configuration + `defaults.config`, `github.config`, `gitlab.config`, and per-repository `config` declare a sparse typed managed configuration for `.fullsend/config.yaml` ([ADR 0122](../ADRs/0122-declarative-repo-configuration.md)). Each accepts every @@ -198,12 +224,36 @@ github: - name: acme/plain # no config key: still managed (sparse, marker only) ``` -```bash -fullsend repos install -f repos.yaml -fullsend repos install --dry-run -fullsend repos install acme/api acme/web -fullsend repos install "acme/*" --direct --concurrency 8 -``` +The `# Source manifest:` line becomes part of the target repository's Git +history, which may be public. A file without this line still carries the +ownership marker, so it never requires adoption. + +An existing zero-byte `.fullsend/config.yaml` counts as an existing file +without the marker, so it also requires adoption. When install skips a +repository for adoption, it prints the same guidance as `repos status`: the +proposed `repos.yaml` entry, the difference between the existing file and the +managed file adoption would produce, and the effective layered-configuration +change (see [`repos status` output](#output)). + +The pre-write safety gate reads each compared key through the full overlay → +base → code-defaults chain. Omitted keys fall through rather than being treated +as unset, and an explicit empty `allowed_remote_resources: []` remains +deny-all. A blanket adoption acknowledgement does not satisfy the gate: each +relaxation must be declared in the manifest. Install checks +`.fullsend/config.yaml` and `.fullsend/config.base.yaml` together, before any +manifest or forge write. When the overlay needs adoption and the base needs +action, install reports both problems. The same checks run again inside +convergence. They apply to repositories with an explicit entry and to +glob-covered repositories. A malformed or non-per-repo file, or a read error, +fails with a clear error and is never replaced. + +A manifest is read-only when it is an HTTPS URL, a pipe or FIFO such as +`<(cmd)`, or a local file without write permission or on a read-only file +system. From a read-only manifest, install fails before any manifest write and +prints the exact entry to add to its source. That includes a glob-covered +repository whose first-install `tracker` default needs its own entry. +`--dry-run`, a live install and `repos status` agree. Trace signing keys follow +their own rule; see [Trace signing keys](#trace-signing-keys). ### Configuration schema of a pinned ref @@ -225,10 +275,21 @@ or later. For a ref on an older schema, install fails that repository with an error that names the entry, and `repos status` reports a block that is already in the installed file as `incompatible`. +Entity-source configuration needs a ref that declares schema version 4. A +managed configuration or installed file that declares `entity_sources`, an +entity connection (a `connections` entry of kind `github`, `gitlab`, `forgejo` +or `jira`, or a reserved provider name) or an agent entry's `entities:` +bindings fails that repository with an error that names the setting when the +ref declares schema version 3 or earlier. Upgrade `fullsend_ref` to a release +that reads entity-source configuration, or remove the setting. `repos status` +reports such a setting that is already in the installed file as +`incompatible`. + The pinned ref is looked up only when the managed configuration or the -installed file declares `tracker`, `create_issues` or a `harness:` block on an -agent entry, the only settings that known schemas read differently. Looking it -up needs the upstream GitHub client. +installed file declares `tracker`, `create_issues`, a `harness:` block on an +agent entry, `entity_sources`, an entity connection or an agent entry's +`entities:` bindings, the only settings that known schemas read differently. +Looking it up needs the upstream GitHub client. When the ref or its schema cannot be determined (the ref does not resolve, no upstream client is available, or the ref declares a schema version this CLI does not know), install leaves `.fullsend/config.yaml` unchanged and fails that @@ -406,6 +467,8 @@ Every repo that `repos install` converges or `repos status` checks must resolve | `openai-api-key` | OpenAI through an API key | | `openai-wif` | OpenAI through Workload Identity Federation (GitHub only; see [OpenAI Workload Identity](../guides/infrastructure/openai-workload-identity.md)) | +A repo can select more than one method by listing them, for example an OpenAI API key parent with Vertex sub-agents (`auth: [openai-api-key, vertex-wif]`), or an OpenAI WIF parent that also stores an API key (`auth: [openai-wif, openai-api-key]`). In that last mix the key is not a runtime fallback: the agent job uses the WIF identifiers whenever they are set, and a failed WIF exchange does not fall back to the key, so the stored key sits unused while the identifiers are complete. Every combination is accepted on GitHub. On GitLab, a list that includes `openai-wif` is rejected like `openai-wif` alone. Each method can be listed only once, and the order of the list is ignored: the methods form a set, and the parent and sub-agent providers come from the harness and model configuration, not from list position. A list at a narrower level replaces the inherited selection; it is not merged with it. A list may not be empty or contain an empty entry. `repos set` takes a mix as a comma-separated value, for example `fullsend repos set 'github.repos["acme/api"].inference.auth' openai-api-key,vertex-wif`. Fullsend writes a mix as that comma-separated scalar (`auth: openai-api-key,vertex-wif`) whenever it writes the manifest, and still reads the list form. A mix needs a fullsend CLI at or above the release that ships mixed selections: older CLIs reject a manifest that holds one, so a pinned older CLI stops working on that manifest until it is upgraded. + `inference.auth` can be set under `defaults`, in a forge section (`github` / `gitlab`), and on repo or glob entries. Resolution goes entry → forge section → `defaults`, using the normal entry matching rules: an explicit entry wins over a glob, and among globs the first match wins. A value on one entry never affects sibling repos. Only the selection is stored in this manifest-level `inference` key. Credentials and secret references do not belong there, and unknown keys there fail validation. Non-secret GCP values (`inference.project`, `inference.region`, `inference.wif_provider`, and on GitLab `inference.wif_audience` and `inference.service_account`) are declared in the managed configuration instead, for example `defaults.config.inference.region`; see [Effective infrastructure values](#effective-infrastructure-values). ```yaml @@ -470,7 +533,7 @@ Install, `--dry-run`, and `repos status` derive each repository's infrastructure - **Private mode.** `mint_mode: private` has no built-in mint URL. Declare it as `mint_url` (in the `github` section or on the entry), as `config.mint_url`, or in a `config_base` preset. A `config.mint_url` alone is enough; you do not have to repeat it as `github.mint_url`. Manifest validation does not load presets, so a repository whose URL comes only from a preset is checked when install, dry run, and status resolve its effective configuration, and a repository that still has no URL fails there. - **Mint URL conflicts.** When the manifest's explicit `mint_url` (in the `github` section or on the entry) and a `mint_url` declared in the managed configuration or preset differ, install, dry run, and status report a conflict for that repository before any write. Make the values match or unset one, for example `fullsend repos set --unset github.mint_url`. A `mint_url` that only a remote `config_base` preset supplies (none in the managed configuration) and that differs from the manifest-resolved value is accepted only when the preset is pinned with `config_base.sha256`; otherwise the preset's owner could redirect the mint endpoint without a `repos.yaml` change. Pin the preset or declare `mint_url` in `repos.yaml`. -- **Region.** When the effective configuration declares `inference.region` (in `defaults.config`, a forge section's `config`, the entry's `config`, or the preset), the region is managed: `FULLSEND_GCP_REGION` is checked against the declared value whether or not it exists, so a changed value and a missing variable are both drift. Install repairs the drift, `--dry-run` previews the change, and `repos status` reports it. This holds on a repeat install that supplies no credential inputs, as well as on fresh installs and whenever Vertex credentials are written. When no region is declared, an existing `FULLSEND_GCP_REGION` is preserved as is, with no drift reported, the same way an undeclared `app_set` keeps an existing `FULLSEND_APP_SET`; `global` is written only where the variable is missing and Vertex credentials are being written (a fresh install or a credential write). `openai-api-key` repositories never get it, and an existing one is removed once the OpenAI key is established. Make the region managed with, for example, `fullsend repos set defaults.config.inference.region us-east5`. +- **Region.** When the effective configuration declares `inference.region` (in `defaults.config`, a forge section's `config`, the entry's `config`, or the preset), the region is managed: `FULLSEND_GCP_REGION` is checked against the declared value whether or not it exists, so a changed value and a missing variable are both drift. Install repairs the drift, `--dry-run` previews the change, and `repos status` reports it. This holds on a repeat install that supplies no credential inputs, as well as on fresh installs and whenever Vertex credentials are written. When no region is declared, an existing `FULLSEND_GCP_REGION` is preserved as is, with no drift reported, the same way an undeclared `app_set` keeps an existing `FULLSEND_APP_SET`; `global` is written only where the variable is missing and Vertex credentials are being written (a fresh install or a credential write). Repositories whose `inference.auth` includes neither `vertex-wif` nor `openai-wif` (`openai-api-key` alone) never get it, and an existing one is removed once the OpenAI key is established. A mix such as `openai-wif,openai-api-key` includes `openai-wif`, so it keeps the region. Make the region managed with, for example, `fullsend repos set defaults.config.inference.region us-east5`. - **Project and WIF provider.** A flag that disagrees with a declared `inference.project` or `inference.wif_provider` fails that repository before any write. Declared values count as supplied credentials: secret values cannot be read back to compare, so every install rewrites `FULLSEND_GCP_PROJECT_ID` and `FULLSEND_GCP_WIF_PROVIDER` from them. That lets a `github setup` installation whose project and provider lived only in layered configuration migrate without flags. A WIF provider (flag or declared) without a project is an error, and a declared `inference.wif_provider` requires a declared `inference.project` (`--vertex-project` alone does not satisfy it), so `repos status` and install agree. A project without a WIF provider derives the project number through the GCP Resource Manager API, which needs Application Default Credentials; declare `inference.wif_provider` or pass `--vertex-wif-provider` to skip the lookup. Existing secrets are reused only when neither a flag nor the effective configuration supplies a project. - **Existing WIF provider (GitLab).** `inference.wif_audience` and `inference.service_account` let a GitLab `vertex-wif` repository use a @@ -485,8 +548,11 @@ Install, `--dry-run`, and `repos status` derive each repository's infrastructure `gitlab.config` or on `gitlab.repos` entries; either key in `github.config` or on a `github.repos` entry fails validation. Values a GitHub repository inherits from `defaults.config`, or that reach a GitLab repository whose - `inference.auth` is not `vertex-wif`, are ignored there (format is still - checked). Install makes no GCP calls to check them. When + `inference.auth` does not include `vertex-wif`, are ignored there (format + is still checked). A GitLab repository whose `inference.auth` is a mix + that includes `vertex-wif`, such as `openai-api-key,vertex-wif`, applies + them and so needs an explicit WIF provider like any other `vertex-wif` + repository. Install makes no GCP calls to check them. When `inference.service_account` is not declared (or does not apply), an existing `FULLSEND_GCP_SERVICE_ACCOUNT` variable is obsolete: `repos status` reports it as drift (`--json` shows `expected absent`) and install deletes @@ -508,10 +574,12 @@ Each repo's effective `inference.auth` decides which credentials `repos install` | `openai-api-key` | `FULLSEND_OPENAI_API_KEY` (GitHub secret or masked GitLab CI/CD variable) | `--openai-api-key` | | `openai-wif` | None required. `FULLSEND_GCP_PROJECT_ID` and `FULLSEND_GCP_WIF_PROVIDER` are written only when Vertex inputs are supplied, for Vertex sub-agents; `FULLSEND_GCP_REGION` follows the [region rules](#effective-infrastructure-values) | Optional `--vertex-project` / `--vertex-wif-provider`, or the declared equivalents | +- **A mix of methods.** A repo that lists several methods gets the credentials of each one, as in the table. Each method is validated on its own: a method's secrets must exist or be supplied, and supplying another method's inputs does not make up for them. A run can supply inputs for one method and reuse the existing secrets of the other. The GCP pair is required when the list includes `vertex-wif`. With only `openai-wif` and `openai-api-key` it stays optional. Only the fullsend-managed secrets that no listed method uses count as obsolete. For example, `[openai-api-key, vertex-wif]` keeps `FULLSEND_OPENAI_API_KEY` and the GCP pair, and `[vertex-wif, openai-wif]` makes only `FULLSEND_OPENAI_API_KEY` obsolete. A list with `openai-api-key` but not `openai-wif` is still rejected while OpenAI WIF identifiers remain (see below). With `openai-wif` also listed, the identifiers are expected, and the API key is stored but not used while they are set. On GitLab, a mix that includes `vertex-wif` applies the existing-provider options (`inference.wif_audience`, `inference.service_account`) and so needs an explicit WIF provider. + - **Per repo, before any write.** Every selected repo is validated against its own method before anything is written. A repo whose method's secrets are missing, with no inputs supplied for that method (by flags or declared configuration), fails with an error that names the repo and the parameters to supply. Inputs for one method are accepted when any selected repo uses it; repos with another method ignore them, so a mixed fleet can be installed in one run. - **Reuse and replacement.** When no inputs are supplied for a method, existing secrets are reused unchanged, and re-running is a no-op (including while an initialization PR/MR is open). Supplied inputs, including a declared `inference.project`, replace the existing values on every run. On GitLab, an existing `FULLSEND_OPENAI_API_KEY` is reused only when it is a masked, protected environment variable (not a file-type variable) with the wildcard `*` environment scope; otherwise the repo fails without echoing the value, so repair the variable or supply `--openai-api-key` to replace it. - **No GCP lookups for OpenAI-only repos.** `openai-api-key` repos get no GCP secrets or region variable. The GCP project number is looked up only when a repo's project has no WIF provider from `--vertex-wif-provider` or a declared `inference.wif_provider`. The per-repo WIF provider derivation is unchanged. -- **Changing `inference.auth`.** Install writes the new credentials first and only after every convergence step for the repo succeeded deletes the fullsend-managed secrets of the other method (`FULLSEND_GCP_PROJECT_ID`/`FULLSEND_GCP_WIF_PROVIDER` or `FULLSEND_OPENAI_API_KEY`). If any write fails, the old credentials are kept. The cleanup is attempted on every run once the selected method is established, so a deletion that failed earlier is retried by the next run. GitLab's unprefixed `OPENAI_API_KEY` variable is never deleted. +- **Changing `inference.auth`.** Install writes the new credentials first. Only after every convergence step for the repo has succeeded does it delete the fullsend-managed secrets that no selected method uses (`FULLSEND_GCP_PROJECT_ID`/`FULLSEND_GCP_WIF_PROVIDER` or `FULLSEND_OPENAI_API_KEY`). If any write fails, the old credentials are kept. The cleanup is attempted on every run once the selected method is established, so a deletion that failed earlier is retried by the next run. GitLab's unprefixed `OPENAI_API_KEY` variable is never deleted. - **`--openai-api-key` value.** Surrounding whitespace is trimmed. On GitLab the key must be storable as a masked CI/CD variable (at least 8 characters from `A-Z a-z 0-9 _ + = / @ : . ~ -`, no whitespace); otherwise the repo fails instead of the key being stored unmasked. - **Dry run.** `--dry-run` lists the secrets that would be written or deleted, by name only. It reports credentials that would be kept when the replacement is not yet live or inherited-variable scopes cannot be verified. Values are never printed. - **`openai-wif` identifiers.** An `openai-wif` repo needs a complete set of OpenAI WIF identifiers, resolved like the runtime: when any of the `FULLSEND_OPENAI_AUDIENCE`, `FULLSEND_OPENAI_IDENTITY_PROVIDER_ID` or `FULLSEND_OPENAI_SERVICE_ACCOUNT_ID` Actions variables is set (a repository variable wins over an organization variable of the same name, as in the workflow `vars` context), those three variables are the only source and must all be set. Otherwise `inference.openai` (`audience`, `identity_provider_id`, `service_account_id`) in `.fullsend/config.yaml` is used, each identifier falling back to `.fullsend/config.base.yaml`. The two sources are never mixed. Install accounts for the managed configuration and configuration preset it is about to deliver. A repo with no identifiers or a partial set fails before anything is written, with an error that names the missing identifiers (never their values). The reusable workflows must also forward these variables and must not require GCP secrets the repo will not have (`FULLSEND_GCP_PROJECT_ID` and `FULLSEND_GCP_WIF_PROVIDER`, unless the repo already has them or the install supplies them with `--vertex-project` or a declared `inference.project`). Non-vendored reusable workflows are read from the pinned `fullsend_ref`, or from the release-default ref when none is pinned; rendered shim and thin callers must grant `id-token: write` before installation can change variables, secrets, or scaffold files. Vendored reusable workflows are checked from the actual vendor source. An established installation with no ref or planned scaffold delivery must have compatible installed workflows. An unpinned OpenAI WIF installation converges its callers to the running release’s upstream ref, including migration from an existing `github setup` installation. Otherwise the install is rejected and an existing `FULLSEND_OPENAI_API_KEY` is kept. @@ -677,6 +745,16 @@ flag or environment variable supplies them. When install manages the caller, it checks that its upstream ref contains `reusable-poll-jira.yml`. An older pin fails with no credential or workflow changes; upgrade the pin to a ref that includes the workflow. + When the `jira` authorization entry reads a list with `groups_from` or + `accounts_from`, the poll job also receives the + `FULLSEND_JIRA_WRITE_GROUPS`, `FULLSEND_JIRA_WRITE_ACCOUNTS`, + `FULLSEND_JIRA_TRIAGE_GROUPS`, or `FULLSEND_JIRA_TRIAGE_ACCOUNTS` secret it + names. Install warns about any other name, which the caller cannot pass. + It also warns when a poll workflow you maintain calls + `reusable-poll-jira.yml` without passing a secret the entry names. + You set these secrets + yourself; install and uninstall never write or delete them. See + [Keeping the lists out of the repository](../guides/user/jira-integration.md#keeping-the-lists-out-of-the-repository). Install changes the file only when it carries the `# fullsend-component: jira-poll` marker line. A workflow at that path without the marker, such as one copied from the Jira guide, is reported and @@ -692,7 +770,12 @@ flag or environment variable supplies them. environment variable available to all environments. The same rules apply to `--jira-client-secret` and an existing `FULLSEND_JIRA_CLIENT_SECRET`. Supplying any Jira credential flag when no selected repo enables polling - fails the run. + fails the run. When the `jira` authorization entry uses `groups_from` or + `accounts_from` and `fullsend_ref` pins a release that predates them, the + repo fails before any write, on GitHub and GitLab, with polling enabled or + not. On GitHub with polling enabled, it also fails when a poll workflow you + maintain calls a `reusable-poll-jira.yml` that predates them, unless the + install is vendored. `repos status` reports the same errors. - **Dry run.** `--dry-run` lists Jira secrets by name only and reports the poll-resource changes it would make. - **Command-line only.** `--jira-token`, `--jira-email`, `--jira-client-id`, @@ -834,7 +917,7 @@ Install flags supply only secrets and sensitive provisioning inputs, local vendo | `--reactivate-schedules` | `false` | Reactivate required GitLab pipeline schedules that exist but are disabled (leave disabled by default so off-system polling setups are not silently reverted). A schedule the GitLab trigger account owns can be edited only by that account, so the trigger-account stage reactivates it by replacing it | | `--vertex-project` | | GCP project ID for Vertex inference, written as the `FULLSEND_GCP_PROJECT_ID` secret. Optional when the effective configuration declares `inference.project`; a different value from the declared one fails that repo. See [Effective infrastructure values](#effective-infrastructure-values) | | `--vertex-wif-provider` | | Full WIF provider resource name (`projects/{number}/locations/global/workloadIdentityPools/{pool}/providers/{id}`), written as the `FULLSEND_GCP_WIF_PROVIDER` secret instead of deriving per-repo providers. The project number is embedded in the path, so no lookup is needed. Optional when the effective configuration declares `inference.wif_provider`; a different value from the declared one fails that repo. Requires a project | -| `--openai-api-key` | | OpenAI API key written as `FULLSEND_OPENAI_API_KEY` to selected repos whose `inference.auth` is `openai-api-key` (GitHub and GitLab). Command-line only: never written to `repos.yaml` and never logged. See [Inference credentials](#inference-credentials). | +| `--openai-api-key` | | OpenAI API key written as `FULLSEND_OPENAI_API_KEY` to selected repos whose `inference.auth` is or includes `openai-api-key` (GitHub and GitLab). Command-line only: never written to `repos.yaml` and never logged. See [Inference credentials](#inference-credentials). | | `--jira-token` | | Jira API token written as `FULLSEND_JIRA_TOKEN` to selected repos whose effective `tracker.jira.poll.enabled` is `true`. Required when such a repo has neither token nor client credentials; if omitted, the existing secret is kept. Command-line only: never written to `repos.yaml` and never logged. See [Jira polling](#jira-polling). | | `--jira-email` | | Optional Jira account email written as `FULLSEND_JIRA_EMAIL` to selected repos whose effective `tracker.jira.poll.enabled` is `true`. If omitted, the existing secret is kept. Command-line only. See [Jira polling](#jira-polling). | | `--jira-client-id` | | Atlassian service account OAuth 2.0 client ID written as `FULLSEND_JIRA_CLIENT_ID`, instead of `--jira-token`, to selected repos whose effective `tracker.jira.poll.enabled` is `true`. If omitted, the existing secret is kept. Command-line only. See [Jira polling](#jira-polling). | @@ -1784,7 +1867,7 @@ The command returns a non-zero exit code when any repo has drift, is not install ### Authentication -Requires a GitHub token via `GH_TOKEN`, `GITHUB_TOKEN`, or `gh auth token`. For GitLab repos, set the `GITLAB_TOKEN` environment variable or pass `--gitlab-token` to the `repos` command group. +Requires a GitHub token via `GH_TOKEN`, `GITHUB_TOKEN`, or `gh auth token`. For GitLab repos, set the `GITLAB_TOKEN` environment variable or pass `--gitlab-token` to the `repos` command group. For Forgejo repos, set the per-instance variable or use the OAuth login described in [Forgejo credentials](#forgejo-credentials). ## `repos uninstall` @@ -1993,6 +2076,17 @@ fullsend repos set gitlab.agent_runner_tags '[fullsend-agent, gpu-runner]' fullsend repos set gitlab.control_runner_tags '[fullsend-api]' ``` +Opt one GitLab project in to a "Minimum role to use pipeline variables" +weaker than "No one allowed". The field is accepted only on a concrete GitLab +repository entry. Install and status then accept the weaker setting on every +run, and `repos install` warns each time. Read +[Opting in to a relaxed setting](../guides/getting-started/configuring-gitlab.md#opting-in-to-a-relaxed-setting) +for what it exposes before you set it: + +```bash +fullsend repos set 'gitlab.repos["group/project"].allow_insecure_pipeline_variables' true +``` + Set the GitLab instance URL and pin a ref: ```bash @@ -2028,6 +2122,143 @@ Differences to watch for in scripts: - Keys outside the old list, including `defaults.config.*`, `github.config.*`, `gitlab.config.*`, and repository entries, can now be set directly. - `repos set` edits the file in place and validates the whole result, so it rejects an edit that leaves the manifest invalid (for example adding a GitLab entry before `gitlab.url` is set). +## Forgejo instances + +`repos install`, `repos status` and `repos uninstall` also manage repositories declared on named Forgejo instances. Declare each instance under `forgejo.instances` with an alias, its base URL, and its repositories as `owner/repo` paths relative to that URL: + +```yaml +version: 1 +forgejo: + instances: + - alias: home + url: https://git.example.com/forgejo # a path prefix is preserved + oauth: # optional: enables browser login + client_id: 7d2b0c1e-5f3a-4c8e-9b1d-2a6f0e4c3b9a + repos: + - name: org/app + - alias: codeberg + url: https://codeberg.org + repos: + - name: org/app + - name: team/tool +``` + +The `forgejo:` key needs a `fullsend` CLI version that includes Forgejo support; an older binary rejects a manifest that declares it as an unknown field. A repository's identity is its alias plus its path, so the same path can be declared on more than one instance. The base URL must use `https`. Plain `http` is accepted only for loopback hosts, such as a local development stack. The URL must not contain credentials, a query, or a fragment. Aliases are case-insensitively unique. + +### Selecting Forgejo repositories + +- `forgejo://` always selects that instance's repository. The `/` part may be a glob, for example `forgejo:home/org/*`. +- A bare `owner/repo` selector or glob selects a Forgejo repository only when every path it matches is declared on exactly one instance. Otherwise the command fails before any credential lookup or write, and lists the qualified choices. With the manifest above, `team/tool` selects `forgejo:codeberg/team/tool`, while `org/app` fails and lists `forgejo:codeberg/org/app` and `forgejo:home/org/app`. +- An unknown alias, or a repository the selected instance does not declare, is an error. The selector never falls through to another instance. +- A bare selector that matches both a Forgejo repository and a `github`/`gitlab` declaration is ambiguous. Qualify the Forgejo repository instead. A bare glob that matches only Forgejo repositories (such as `fj/*` next to an unrelated `github` entry) is not ambiguous. Two globs are ambiguous only when some path matches both, so `org/[ab]` next to a declared `org/[cd]` is not. +- `repos install` validates the whole selection, including every selector left for `github`/`gitlab`, before it writes to any forge. `repos uninstall` asks for one confirmation covering every selected repository, Forgejo and `github`/`gitlab` together, before it tears anything down. +- With no selector, `repos install` and `repos status` act on every declared repository. `repos uninstall` always needs explicit selectors. + +### Forgejo credentials + +Each instance reads its API token from `FULLSEND_FORGEJO__TOKEN`. To normalize the alias, uppercase it and replace each run of non-alphanumeric characters with one underscore. For example, alias `home` reads `FULLSEND_FORGEJO_HOME_TOKEN` and alias `code-berg` reads `FULLSEND_FORGEJO_CODE_BERG_TOKEN`. Two aliases that normalize to the same variable are rejected. Tokens are never read from or written to `repos.yaml`. + +The command resolves selectors first. It then gets a credential for every +selected instance, and only then makes its first Forgejo write. Each selected +instance tries these sources in order: + +1. Its `FULLSEND_FORGEJO__TOKEN` variable. When the variable + is set, the CLI uses it and skips the keyring and OAuth. +2. An OAuth token cached in the operating-system keyring (macOS Keychain, + Windows Credential Manager, or the Secret Service on Linux). This source + needs `oauth.client_id` on the instance. The CLI refreshes an expired + token, then checks the token against the instance. When the instance + rejects it, for example because you revoked it, the CLI removes it from + the keyring. +3. An interactive browser login. This source also needs `oauth.client_id`, + and runs only when the command runs in a terminal. + +A selected instance that still has no credential fails the command. The error +names each alias and variable, and the command changes nothing. The CLI +reports every such instance before any login starts, so it asks you to log in +only when the command can succeed. A non-interactive command (CI, or stdin not +a terminal) never opens a browser: it uses a usable cached token or fails. The +CLI never contacts or prompts for an unselected instance, and never uses one +alias's token for another. The CLI sends the API token only to the configured +URL. The Forgejo client refuses to follow any redirect, so a redirect cannot +carry the token to another origin or over plain HTTP. + +#### OAuth login + +To turn on browser login for an instance, register a public OAuth2 +application on it: + +1. In Forgejo, open **Settings → Applications → Manage OAuth2 applications**. +2. Clear **Confidential client**. +3. Set the redirect URI to `http://127.0.0.1/callback`. Forgejo accepts any + port on a loopback redirect URI, so the CLI can listen on a random local + port. +4. Put the application's client ID in `forgejo.instances[].oauth.client_id`. + +The client ID is not secret. The login uses no client secret, and +`repos.yaml` rejects a `client_secret` field. Older `fullsend` CLIs reject a +manifest that sets `oauth.client_id`, so use a CLI version with OAuth support. + +The login uses the Authorization Code flow with PKCE (`S256`). Forgejo +redirects the browser to a listener on `127.0.0.1`, and the CLI rejects a +callback whose `state` value does not match. The authorize and token endpoints +(`/login/oauth/authorize` and `/login/oauth/access_token`) keep the base URL's +path prefix. The CLI waits up to five minutes for the browser callback. It +writes prompts and progress to stderr, so `--json` output stays parseable. + +::: warning OAuth tokens carry your full Forgejo permissions +Forgejo does not implement OAuth scopes, so an OAuth token can act with your +full Forgejo user permissions on that instance. That covers every repository, +organization, and setting your account can reach, not only the selected +repositories. Before each login the CLI explains this and asks you to confirm +(`[y/N]`). If you decline, the CLI opens no browser and the command fails. +Prefer a scoped access token in `FULLSEND_FORGEJO__TOKEN`; +it always takes precedence. Only the local CLI uses the OAuth token. Agent +workflows never use it. +::: + +The CLI stores the access and refresh tokens only in the operating-system +keyring, under the service name `fullsend-forgejo-oauth`, keyed to the alias, +base URL, and client ID. It never writes them to `repos.yaml` or prints them. +If the CLI cannot read or write the keyring, for example on a headless Linux +host without a Secret Service, it warns. It then uses the token for the +current command only, and asks you to log in again next time. To sign out, +delete the `fullsend-forgejo-oauth` entry from your keyring, or revoke the +application under **Settings → Applications** on the instance. + +### Forgejo workflow hosts + +Fullsend's Forgejo workflows run on the same Forgejo instance as the repositories that use them; no generated workflow reference points at GitHub or at another instance. Each instance either declares one workflow-host repository, or its repositories vendor their own copy of the workflows: + +```yaml +forgejo: + instances: + - alias: home + url: https://git.example.com/forgejo + repos: + - name: fullsend/workflows + workflow_host: true # receives the published workflow bundle + - name: org/app # pins its shim to the bundle on fullsend/workflows + - name: org/standalone + vendor: true # carries its own copy; needs no host +``` + +- **Workflow bundle.** The bundle holds Fullsend's reusable Forgejo workflows and their helpers. Its version is derived from its content, so a new `fullsend` release that changes the bundle produces a new version. `repos install` publishes the bundle to the workflow host in a single commit on its default branch and tags that commit `fullsend-bundle-`. Running install again makes no changes until the bundle changes. +- **Consumer shims.** Every non-host repository receives `.forgejo/workflows/fullsend.yml`. In a non-vendored repository the shim calls the host's `.forgejo/workflows/fullsend-dispatch.yml` by the instance's full URL, including any path prefix, pinned to the tagged commit SHA. That reference is immutable. Before pinning, install checks that every bundle file at the tagged commit matches the bundle, so a moved or hand-made tag is refused. A vendored repository receives the bundle files and a shim that calls its local copy. +- **Missing host.** When a selected non-vendored repository's instance declares no workflow host, `repos install` fails before any credential lookup or write and names the instance. Declare a host with `workflow_host: true`, or set `vendor: true` on the repository (or `defaults.vendor: true`). An instance has at most one workflow host, and a workflow host cannot set `vendor: true`. +- **Install order.** A host selected in the same run is published before its consumers, so the consumers pin the new version. When the host is not selected, install only reads its tag. If the current bundle version has not been published, the consumer fails and names the `repos install` command for the host. +- **Uninstall protection.** `repos uninstall` refuses to remove a workflow host's bundle while any non-vendored repository on the same instance is still declared in `repos.yaml`. It lists those consumers and keeps the host's manifest entry. Uninstalling the consumers in the same run, or removing them from the manifest first, releases the host. A consumer whose workflow files are left in place (for example because its index lost the ownership marker) does not release the host. Only consumers declared in `repos.yaml` can be checked; repositories outside the manifest that call the host are not detected. Version tags are kept on uninstall, so a pinned commit stays reachable. + +### Forgejo lifecycle + +The Fullsend-managed resources on Forgejo are the managed `.fullsend/config.yaml`, which carries the ownership marker and `defaults.config`, and the workflow files above. A workflow host receives only the bundle. `.fullsend/forgejo-workflows.yaml` lists the workflow files Fullsend owns in each repository; only files it lists are updated or removed, and it can claim only paths under `.forgejo/workflows/fullsend` or `.fullsend/forgejo` (which includes the index itself). It can never claim `.fullsend/config.yaml`, which keeps its own ownership marker check. The index carries a `version` field (currently `1`); a newer version makes install and uninstall stop with an upgrade hint. A workflow update is committed together with a conditional rewrite of the index revision that authorized it, so ownership withdrawn concurrently rejects the commit. Install verifies every bundle file at a newly created tag before any consumer is pinned to it, and a shim's workflow reference is pinned to a full commit SHA. + +- `repos install` creates missing files and rewrites drifted ones. Running it again makes no changes. A `.fullsend/config.yaml` without the ownership marker, or a workflow file that exists but is not listed in `.fullsend/forgejo-workflows.yaml`, is never overwritten: install reports an error for that repository before writing anything to it. Updates and deletes are conditional on the revision that was checked, so a file replaced in between causes a conflict error instead of an overwrite or delete. The workflow files of a repository change together in one commit. `--dry-run` reports what would change without writing. +- `repos status` is read-only. Each selected repository is reported as `up-to-date`, `drift`, `not-installed`, `unmanaged` (a file Fullsend does not own), or `error`, in a `FORGEJO REPO` table or in the `forgejo` array of `--json` output. A workflow host also reports drift when the current bundle version is not tagged, and a consumer when its shim is not pinned to the current version. Each `--json` result carries a `role` of `workflow-host` or `vendored` (omitted for a consumer). A non-vendored repository whose instance declares no workflow host is reported as `error` by `repos status`, not only by `repos install`; this includes repositories installed before workflow hosts existed. To migrate, declare the instance's host with `workflow_host: true`, or set `vendor: true` on the repository (or `defaults.vendor: true`). Any state other than `up-to-date` gives a non-zero exit code. In `--json` output, `summary` covers only the `github`/`gitlab` repositories; Forgejo results appear only in the separate `forgejo` array, so a run that selects only Forgejo repositories has an empty `repos` array and a zeroed `summary` even when a Forgejo repository errored. Check the `forgejo` array or the exit code. +- `repos uninstall` deletes the managed files and then removes the repository's entry from `repos.yaml`. A file Fullsend does not own is never deleted. The entry is removed only when teardown succeeded. A repository whose `.fullsend/forgejo-workflows.yaml` is missing has no ownership record: if a shim or dispatch workflow file remains at `.forgejo/workflows/fullsend*`, uninstall reports the repository as `unmanaged`, keeps the file, and keeps the `repos.yaml` entry, where earlier versions reported `not-installed`. Delete the file by hand to finish the removal. `--uninstall-only`, `--manifest-only`, `--dry-run` and `--yes` behave as they do for other forges. Forgejo file changes are committed directly to the default branch, whether or not `--direct` is set. + +Forgejo agent stages are tracked separately under [#9642](https://github.com/fullsend-ai/fullsend/issues/9642). + ## See also - [Getting Started](../guides/getting-started/) — Standard per-repo installation diff --git a/docs/cli/run.md b/docs/cli/run.md index 5fb0b03177..1a92d9c253 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -33,7 +33,7 @@ root of `--fullsend-dir`. A run that finds it only in a sibling | `--model` | Override the harness/agent model for this run (alias, model id, or `provider/id` on pi, codex, and opencode — codex takes OpenAI ids and `gateway/` only); also `FULLSEND_MODEL` | | `--effort` | Override the harness effort level for this run (`low`…`max`); also `FULLSEND_EFFORT` | | `--output-dir` | Base directory for run output (default: `/tmp/fullsend`) | -| `--target-repo` | Path to the target repository | +| `--target-repo` | Path to the target repository; see the layout and setting restrictions below | | `--fullsend-binary` | Path to a Linux fullsend binary to copy into the sandbox | | `--env-file` | Load environment variables from a dotenv file (repeatable) | | `--no-post-script` | Skip post-script execution | @@ -44,11 +44,41 @@ root of `--fullsend-dir`. A run that finds it only in a sibling | `--max-depth` | Maximum dependency depth for transitive resolution (0 disables) | `--target-repo` accepts a plain directory or a valid checkout with a real root -`.git` directory. `.git` files (linked worktrees and submodules), symlinked -`.git` entries, and bare repositories are unsupported. Fullsend validates the -target after the pre-script and before upload, and sanitizes and validates the -returned tree before publication; a plain directory may come back as a plain -directory or a valid checkout, while a checkout must come back as a checkout. +`.git` directory. A root `.git` file (for example a linked worktree), a +symlinked `.git` entry, a bare repository, and a checkout with registered +worktrees are unsupported; normal submodules inside the checkout are supported +through their in-tree gitfiles. A plain directory that already contains a +nested Git checkout is rejected. So is a checkout containing a nested `.git` +directory of its own (a vendored clone or an unabsorbed embedded repository), +and any Git-shaped subdirectory — one holding `HEAD` plus `objects` and +`refs`, such as a committed `testdata/x.git` fixture: absorb the clone as a +registered submodule, or keep the fixture outside the downloaded target +tree — a Git-shaped directory the target carries at upload is rejected +before the run, and a bare-shaped directory the sandbox creates is rejected +at download; a fixture extracted in the sandbox must be removed before the +repository is returned. Destinations naming the `ext` transport helper are +rejected, and so is a shallow submodule initialization inside the sandbox: a +module store that returns a shallow boundary the host never captured fails +the download. Fullsend validates the target after the +pre-script and before upload, and sanitizes and validates the returned tree +before publication; a plain directory may come back as a plain directory or a +valid checkout, while a checkout must come back as a checkout. Fullsend +discards downloaded Git configuration and restores selected settings from the +host checkout, including identity, remote destinations, submodule activation, +sparse-checkout settings, and the `http..sslCAInfo` and `.sslCAPath` +certificate authority paths CI runners write for private-CA instances. +Settings outside the restored list, including `filter.lfs.*` and +`core.sshCommand`, are discarded; an LFS checkout therefore comes back with +its filters unset. Partial clones are rejected in both their forms, as is a +relative local submodule destination in the target checkout that does not +resolve on the host (a relative destination in a module store's own config +is rejected regardless); re-apply dropped settings such as LFS filters in a +post-script if a workflow needs them. To migrate a rejected layout, replace a +linked-worktree +target with a fresh normal checkout of the same commit — commit or stash its +local changes first, since `git worktree remove` deletes a worktree rather +than converting it — use absolute submodule URLs, and replace a bare or +nested-checkout target with a normal `.git` checkout or a plain directory. Reftable ref storage requires Git 2.53 or newer on the host running Fullsend. Fullsend rejects a downloaded `.git/packed-refs` larger than 32 MiB and a downloaded `.git/shallow` larger than 4 MiB. @@ -597,6 +627,21 @@ When `GITHUB_SERVER_URL` names a GitHub server other than github.com, such as Gi The server URL follows the rule the GitHub API client uses: `https`, no userinfo, path, query or fragment. A URL that breaks this rule leaves the run on github.com. GHE.com (`*.ghe.com`) is not bound: `gh` calls `api.` there and reads `GH_TOKEN`. +## Agent definitions from a Forgejo instance + +By default a built-in agent that `config.yaml` does not register with a `source:` (triage, code, review, …) is fetched from `fullsend-ai/agents` on GitHub. A Forgejo installation can instead host these agent definitions in a repository on its own Forgejo instance. Set these environment variables: + +| Variable | Meaning | +|----------|---------| +| `FULLSEND_FORGEJO_URL` | Base URL of the Forgejo instance. It may include a path prefix. Must use `https`; plain `http` is accepted only for a loopback host such as the local development stack. | +| `FULLSEND_FORGEJO_AGENTS_REPO` | `owner/repo` of the agent-definition repository on that instance. Default: `fullsend-ai/agents`. | +| `FULLSEND_FORGEJO_AGENTS_REF` | Full commit SHA (40 or 64 lowercase hex characters) the definitions are pinned to. Branches, tags and abbreviated SHAs are rejected. | +| `FORGEJO_TOKEN` | Optional API token for the instance. Without it, the repository is read anonymously, which is enough for a public repository. | + +Once any of the first three variables is set, built-in agents resolve only from this source. If the configuration is incomplete or invalid, or the file cannot be read, the run fails with an error. It never falls back to GitHub. The harness, its relative companion files (agent prompt, policy, scripts) and its skill and plugin directories are all read at the pinned commit. Forgejo's git data API addresses them by object ID, so a branch named like the commit cannot stand in for it, and every file is checked against its git object ID. Symlinks and submodules are refused, and directories are bounded like git sparse checkout. The token is sent only to the configured instance, and the client does not follow redirects. + +Source checks still apply. Files are recorded under Forgejo raw URLs: `///raw/commit//`. These URLs must be admitted by `allowed_remote_resources`. The Forgejo host is not one of the default prefixes, so add `///raw/` to `config.yaml`. Content is cached by SHA-256 and recorded in the fetch audit log. In offline mode, the pinned URLs resolve from the cache. `fullsend lint`, `fullsend dispatch --route` and the eval measurement manifest lookup use the same source. + ## GitHub Packages credentials On GitHub Actions, `fullsend run` copies the pre-mint `GH_TOKEN` (the job's workflow token) to @@ -615,8 +660,10 @@ temporary directory, removed after the pull), so the image can be a private pack shipped code and fix workflows grant `packages: read`, so a private image works on code and fix harnesses; on other agents a private image is denied and sandbox creation fails. The package must also allow Actions access from the repository. If the pull fails, the runner logs a warning and the -OpenShell gateway attempts its own unauthenticated pull, so public images keep working. For images -on other registries the runner adds no credentials. See +OpenShell gateway attempts its own unauthenticated pull, so public images keep working. On GitLab CI +the runner pulls an image on the instance's container registry (`CI_REGISTRY`) the same way, with the +job's `CI_REGISTRY_USER` and `CI_REGISTRY_PASSWORD`. For images on other registries the runner adds +no credentials. See [Extending the sandbox image](../guides/user/customizing-agents.md#extending-the-sandbox-image). Every mint sets `GH_TOKEN`, `GITHUB_TOKEN`, `GH_ENTERPRISE_TOKEN` and diff --git a/docs/contributing/ci-workflows.md b/docs/contributing/ci-workflows.md index 07854e867b..bba5e3f3a8 100644 --- a/docs/contributing/ci-workflows.md +++ b/docs/contributing/ci-workflows.md @@ -189,6 +189,14 @@ When all five components are present, any code the PR author controls can read a **ADR-0009 and the shim distinction:** ADR-0009 documents why `pull_request_target` was safe for the shim workflow — the shim never checks out PR code, so components 2–3 are absent. The shim has since moved to `pull_request` for same-repo PRs ([ADR 0164](../ADRs/0164-run-the-shim-on-pull-request-for-same-repo-prs.md)); `reusable-dispatch.yml` still accepts `pull_request_target` from shims that have not upgraded. This safety reasoning does **not** transfer to jobs that check out and execute PR-head code (e.g., the behaviour and playback jobs in `e2e.yml`). +**`workflow_run` and the fork PR stub:** `workflow_run` has the same component 1 as `pull_request_target`: the triggered workflow runs from the default branch with secrets, after a run that a fork controls. The shim's `workflow_run` trigger on the `fullsend-fork-pr.yaml` stub stays safe only while components 2 and 3 stay absent: + +- never download the triggering run's artifacts or read its logs or run name, and never check out its head SHA; +- treat the run's `head_repository`, `head_branch`, `head_sha`, `path` and `created_at` as lookup metadata a fork can influence, not as provenance; look the PR up through the API and re-check its head repository id and head SHA; +- authorize the actor the API reports (PR author, closer) before any token mint. Labels do not route a fork PR: the fork's stub copy can run on any label event, so no trusted record ties a label to the head it was added on. + +A `branches:` filter (github/gh-aw's CTR-021 check) does not help here: for a fork PR the run's `head_branch` is a name the fork chose. + ### Credential blast radius Not all credentials carry the same risk on exfiltration: @@ -202,13 +210,14 @@ Prefer short-lived narrowly-scoped credentials whenever possible. When long-live ### Gate job mitigation -Pull requests run the behaviour and playback scenarios on a GitHub emulator ([`behaviour-github-emulator.yml`](../../.github/workflows/behaviour-github-emulator.yml)) with no secrets, no environment and no cloud OIDC, so fork pull requests run them on `pull_request` with no authorization step. `e2e.yml` runs the `behaviour` and `playback` suites, with secrets, only in the merge queue and on push to `main`; on a pull request those jobs skip, which their required checks accept. +Pull requests run the behaviour and playback scenarios on a GitHub emulator ([`behaviour-github-emulator.yml`](../../.github/workflows/behaviour-github-emulator.yml)) with no secrets, no environment and no cloud OIDC, so fork pull requests run them on `pull_request` with no authorization step. `e2e.yml` runs the `behaviour` and `playback` suites, with secrets, in the merge queue and on push to `main`; on a pull request those jobs skip, which their required checks accept, unless a maintainer comments `/ok-to-test live` (below). -The `check-e2e-authorization` gate job (`gate` in `e2e.yml`) mitigates the risk by requiring authorization before the `forgejo-behaviour` job, the only `e2e.yml` suite that runs on pull requests, checks out PR-head code. `e2e.yml` and `e2e-ok-to-test.yml` no longer use `pull_request_target` ([#9245](https://github.com/fullsend-ai/fullsend/issues/9245)): same-repository PRs run on `pull_request`, and fork PRs run only after a `/ok-to-test ` comment (`issue_comment`): +The `check-e2e-authorization` gate job (`gate` in `e2e.yml`) mitigates the risk by requiring authorization before the `forgejo-behaviour` job, or the live `behaviour` and `playback` jobs after `/ok-to-test live`, checks out PR-head code. `e2e.yml` and `e2e-ok-to-test.yml` no longer use `pull_request_target` ([#9245](https://github.com/fullsend-ai/fullsend/issues/9245)): same-repository PRs run on `pull_request`, and fork PRs run only after a `/ok-to-test ` comment (`issue_comment`): - **Same-repository PRs** — the gate authorizes authors with write access (collaborator permission API) and trusted bots. Fork `pull_request` runs get no secrets, so `forgejo-behaviour` skips them. - **Fork PRs** — require a user with write access (Write role or above) to review the PR diff and comment `/ok-to-test `, naming the reviewed commit, including when the fork author has write access. The gate reads the comment from the API, checks the commenter's permission, and authorizes the PR head only when it is the named sha. Another head is refused (`stale_ok_to_test`), and a comment with no sha is refused (`missing_sha`). The gate uses no timing. The `ok-to-test` label no longer starts e2e. -- **Separation of concerns** — the gate (authorize/report) job runs on the base-branch checkout and is the only job with `pull-requests: write` and `checks: write`; it reports only the `forgejo-behaviour` check run on the authorized sha. The `forgejo-behaviour` job runs on the PR-head checkout with `contents: read` only. +- **Live runs on any PR** — `/ok-to-test live` passes the same gate, with no new rules, and also runs the live `behaviour` and `playback` jobs on PR-head code: the authorized sha, in the `dev` environment, with the same steps as the merge queue. The gate writes `live=true` only when it authorizes the run (`reason=ok_to_test`) and the first line ends in a lowercase `live`; any other word after the sha is refused as `missing_sha`. +- **Separation of concerns** — the gate (authorize/report) job runs on the base-branch checkout and is the only job with `pull-requests: write` and `checks: write`; it reports the `forgejo-behaviour` check run on the authorized sha, plus the non-required `behaviour-live` and `playback-live` check runs when `live` is true. It never reports the required `behaviour` and `playback` checks on a PR. The `forgejo-behaviour` job runs on the PR-head checkout with `contents: read` only. The live jobs add only the `id-token: write` permission (for GCP WIF and the mint) and use the same secrets as in the merge queue. **Limitations of the gate:** diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index 59c7bcb612..b3f96eccbe 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -132,7 +132,7 @@ re-renders that template. | `REVIEW_FINDING_SEVERITY_THRESHOLD` | Lowest review finding severity to post | Agent environment variable (`docs/agents/review.md`) | The variable. No YAML field in this repo | Review agent | Stays a harness variable. Set it per repo through the agent entry's `harness:` block ([ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md)) | Yes, the block merges across both files. | | `CODE_AUTO_MERGE`, `CODE_AUTO_MERGE_METHOD` | Whether the code agent enables GitHub auto-merge, and the method | Agent environment variables (`docs/guides/user/adoption.md`) | The variables. No YAML field | Code agent | Leave as variables. The code harness does not declare them, so a `harness:` block ([ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md)) rejects them; declaring them in the harness comes first | Same as the review threshold once declared. | | `OTEL_EXPORTER_OTLP_*`, `OTEL_RESOURCE_ATTRIBUTES`, `OTEL_SDK_DISABLED`, `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` | Trace export | Repository variables. Header values are secrets | The variables. Unset means export stays off | CLI tracer, from the workflow environment | Leave as variables. Endpoints differ per environment, and headers are secrets | No. | -| `FULLSEND_SANDBOX_IMAGE`, `FULLSEND_SANDBOX_ARCH` | Sandbox image and CPU architecture for a run | Process environment | The variables, when set | `fullsend run` | Leave as variables. They are per-machine or per-job overrides | No. | +| `FULLSEND_SANDBOX_IMAGE`, `FULLSEND_SANDBOX_ARCH` | Sandbox image and CPU architecture for a run | Process environment | The variables, when set | `fullsend run`, `fullsend prepare` | Leave as variables. They are per-machine or per-job overrides | No. | | `FULLSEND_REVIEW_CLIENT_ID` | Review app client id, used to check prior review comments | Repository variable written by `github setup` | The variable | Review pre-fetch script | Leave as a variable. Setup derives it from the installed app. It is not a preset input | No. | ## Left out on purpose diff --git a/docs/contributing/documentation.md b/docs/contributing/documentation.md index e158637d52..138408ef9f 100644 --- a/docs/contributing/documentation.md +++ b/docs/contributing/documentation.md @@ -281,6 +281,14 @@ The `admin` command group's `uninstall`/`analyze`/`enable`/`disable` subcommands | Contributing | `docs/contributing/sandbox-topology.md` | | Go source | `internal/cli/run.go` | +### `prepare` + +| Category | Files | +|----------|-------| +| CLI reference | `docs/cli/prepare.md`, `docs/cli/run.md` (GitHub Packages credentials) | +| Guides | `docs/guides/user/running-agents-locally.md`, `docs/guides/dev/cli-internals.md` | +| Go source | `internal/cli/prepare.go`, `internal/cli/run_compose.go`, `internal/cli/run_image_pull.go` | + ### `issues` | Category | Files | diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 2554445879..10e4fa0d38 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -504,8 +504,18 @@ Record every applicable item in the PR description as `verified`, `blocked`, or The inference profiles (`profiles/fullsend-vertex-ai.yaml` in this repo and in fullsend-ai/agents; `profiles/fullsend-openai.yaml`, which has no fleet copy — the runner imports the embedded scaffold) carry a `binaries:` list. OpenShell's OPA (`sandbox-policy.rego`, `binary_allowed`) matches each glob against the kernel-resolved `/proc//exe` of the process that opens the connection **or of any of its ancestors**. That gives two kinds of runtime: -- **Wrapped by node** (pi, codex): `**/node` admits them through the ancestor, so a pin bump cannot take them off the allowlist unless the wrapper disappears. -- **Exec'd directly** (Claude Code, OpenCode): `claude` on PATH is a symlink to the npm package's `bin/claude.exe`, while OpenCode is the native `/usr/local/bin/opencode` binary. Neither has a wrapper ancestor, so only a glob on the real file name admits it. A renamed native binary breaks every run of that runtime on its first model call with `API Error: Error code policy_denied`, 0 tokens, and the only explanation is the gateway's `NET:OPEN … DENIED … binary '…' not allowed in policy '_provider_'` line (#6971). +- **Wrapped by node** (pi): `**/node` admits it, so a pin bump cannot take it + off the allowlist unless the wrapper disappears. +- **Exec'd directly** (Claude Code, OpenCode, Codex): `claude` on PATH is a + symlink to the npm package's `bin/claude.exe`, OpenCode is the native + `/usr/local/bin/opencode` binary, and Codex's npm launcher `bin/codex.js` + replaces node with the native binary (`process.execve`). None has a wrapper + ancestor, so only a glob on the real file name admits it. A renamed native + binary breaks every run of that runtime on its first model call (Claude Code + reports `API Error: Error code policy_denied`, 0 tokens), and the only + explanation is the gateway's + `NET:OPEN … DENIED … binary '…' not allowed in policy '_provider_'` + line (#6971). `TestScaffoldProfilesAllowRuntimeBinaries` (`internal/cli/runtime_binaries_test.go`) fails for any selectable runtime without a mapping and pins the ones below. @@ -513,7 +523,7 @@ The inference profiles (`profiles/fullsend-vertex-ai.yaml` in this repo and in f |---------|-----------------------------------|-----------------|----------| | Claude Code | `bin/claude.exe` in the npm package — 2.1.2xx's `install.cjs` places the native binary there ("Always write to bin/claude.exe"); the Containerfile installs it *with* scripts so that runs | `**/claude`, `**/claude.exe` | gateway deny log in #6971; `npm view @anthropic-ai/claude-code@ bin` | | pi | `node` (`bin = dist/bundle/cli.js`; no native network path in the package) | `**/node` | `images/sandbox/Containerfile`, `npm view @earendil-works/pi-coding-agent@ bin` | -| Codex | `vendor//bin/codex`, spawned by the npm launcher `bin/codex.js` under node; codex also spawns `codex-code-mode-host` (default-enabled in 0.152.1), covered by ancestor matching, not by name | `**/node` (ancestor), `**/codex` (the process) | `npm pack --dry-run "@openai/codex@-linux-x64"` | +| Codex | `vendor//bin/codex`, which the npm launcher `bin/codex.js` execs in place of node (`process.execve`); codex also spawns `codex-code-mode-host` (default-enabled in 0.152.1), covered by ancestor matching, not by name | `**/codex` (the process) | `npm pack --dry-run "@openai/codex@-linux-x64"`, `bin/codex.js` in `@openai/codex@` | | OpenCode | `/usr/local/bin/opencode`, the per-architecture glibc release binary installed directly by the Containerfile | `**/opencode` | `images/sandbox/Containerfile`; `internal/cli/runtime_binaries_test.go` | ## Sandbox workspace layout @@ -1250,7 +1260,8 @@ re-checked on a `CODEX_VERSION` bump. The decisions are Everything below was read at tag `rust-v0.152.1`; the rows of [Re-check on a `CODEX_VERSION` bump](#re-check-on-a-codex_version-bump) were -re-verified at `rust-v0.157.0`, at `rust-v0.159.3` and again at `rust-v0.166.0`. +re-verified at `rust-v0.157.0`, at `rust-v0.159.3`, at `rust-v0.166.0` and +again at `rust-v0.170.0`. Two of the findings are the reason the hook adapter exists at all, because forwarding the scripts' own convention would fail **open**. @@ -1287,8 +1298,8 @@ flowchart TB - **The project is pinned untrusted.** `config.toml` carries `[projects.""] trust_level = "untrusted"` for the target repo, so its own `.codex/` layer — settings, instructions and repo-authored hooks — is never loaded. The entry has to be written: - codex records a trust level for a git checkout it starts in when none is set, and only skips - that when one already is. This is codex's equivalent of pi's `defaultProjectTrust: "never"`. + an unset trust level is not untrusted, and codex skips a project's own `AGENTS.md` only for an + explicit untrusted entry. This is codex's equivalent of pi's `defaultProjectTrust: "never"`. - **Config layering.** The sandbox image bakes a root-owned managed `/etc/codex/config.toml`; the runner's `$CODEX_HOME/config.toml` layers above it, and the `-c` SessionFlags above that. Only the `-c` layer is beyond an agent's reach between iterations, which is why the security-relevant @@ -1303,8 +1314,8 @@ flowchart TB `Read`, `Glob`, `Grep`, `WebFetch` and `WebSearch` have no codex tool — codex does that work through the shell, so the `Bash` groups already cover it. - **Skills** come from `$CODEX_HOME/skills`, which `Bootstrap` populates. Codex also discovers a - repo's `.agents/skills`, and (verified live at 0.157.0; discovery source unchanged through - 0.166.0) its `.codex/skills` even with the project untrusted; both are covered by the host-side + repo's `.agents/skills`, and (verified live at 0.157.0; the same skill roots through + 0.170.0) its `.codex/skills` even with the project untrusted; both are covered by the host-side and in-sandbox context scans, which match `SKILL.md` anywhere in the repo. The agent reads those files through the shell, and Codex 0.157.0 truncates a single exec at 10,000 tokens (head and tail), so both runtime notes (`codexChunkedReadNote`) tell it to count lines with `awk 'END { print NR }'` (`wc -l` @@ -1324,7 +1335,9 @@ flowchart TB - `Run` executes `codex exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox [--dangerously-bypass-hook-trust] -C --model -c model_provider=fullsend-openai -c approval_policy=never -c sandbox_mode=danger-full-access [-c model_reasoning_effort=] - -o /output/last-message.txt -` with the prompt piped to stdin. + -` with the prompt piped to stdin. It passes no `-o` (`--output-last-message`): nothing in the + runner reads that file, and at 0.170.0 a failed open or write of it ends exec with exit 1, even + after a completed turn. - **The prompt is never on argv.** On a retry iteration it carries the previous failure's text (#1050/#6494), and argv is world-readable in the sandbox. `-` is codex's explicit read-from-stdin sentinel; the pipe closes when `printf` finishes, so there is none of the @@ -1369,12 +1382,15 @@ cannot be overridden, so it cannot follow the mid-run refresh a short-lived WIF `auth.command` is an absolute path to the runner-written `openai-token.sh`. - Codex runs that command, uses its trimmed stdout verbatim as the bearer token, caches it for `refresh_interval_ms` (30 s here; codex's default is 300 s) and re-runs it on expiry and on the - 401 retry path. A non-zero exit or empty stdout **fails the request with no fallback to the - environment**, which is what makes the path fail closed. + 401 retry path. A non-zero exit, empty stdout or timeout gives codex no token from that run, + with **no fallback to the environment**: with no earlier token the request fails, and after a + success codex (0.170.0) keeps sending the last token the script printed until one of those + re-runs succeeds. Codex never sends a value the script refused, which is what makes the path + fail closed. - The script prints the placeholder from `$CODEX_HOME/openai-token`, which `CodexRuntime`'s `OpenAICredentialSeeder` implementation seeds at iteration start and the runner re-seeds through - `sandbox exec` after every refresh. Anything that is not a gateway placeholder fails the run - rather than being forwarded, and the script never echoes the value it rejects. + `sandbox exec` after every refresh. Anything that is not a gateway placeholder is refused + with a non-zero exit rather than forwarded, and the script never echoes the value it rejects. - `supports_websockets` is left unset: custom providers default to false, which keeps codex on HTTP/SSE `POST /v1/responses` — the only thing the `fullsend-openai` egress profile allows. - **Inference gateway route (ADR 0137, #8295).** `CodexRuntime` implements @@ -1687,8 +1703,16 @@ Two artefacts of the run are worth knowing about: and local smoke runs. - The rollout session files are archived as transcripts but not error-classified: only the tee'd `exec --json` capture yields a verdict, which is what the runner's exit-code override reads. -- Native sub-agents (ADR 0126) have not completed a fleet-shaped run; `review`/`retro` stay on - Claude Code in the docs until one does. +- Native sub-agents (ADR 0126) have run fleet-shaped only locally on macOS Apple Silicon, + natively and in a Fedora CoreOS (aarch64) podman VM + ([#6970](https://github.com/fullsend-ai/fullsend/issues/6970)), not through the fleet + workflows. In two of the three `review` runs on #6970 a persona the skill selects did not run, + and neither result said so ([#9073](https://github.com/fullsend-ai/fullsend/issues/9073), + [#9657](https://github.com/fullsend-ai/fullsend/issues/9657)). On collaboration V2 (ADR 0159), + `review` and `retro` have run natively on macOS only + ([#9085](https://github.com/fullsend-ai/fullsend/issues/9085#issuecomment-6920231259)), and there the + `review` parent dropped the challenger's kept findings after its own check of the repository + ([#9657](https://github.com/fullsend-ai/fullsend/issues/9657)). ### Re-check on a `CODEX_VERSION` bump @@ -1698,22 +1722,22 @@ Two artefacts of the run are worth knowing about: | `async` and `can_apply_control_effects` | a synchronous-only rule that changed would alter what the wiring must omit | `codex-rs/hooks/src/engine/mod.rs` | | `PostToolUse` output fields | if `updatedToolOutput` ever lands, the sanitizers can start redacting again | `codex-rs/hooks/src/schema.rs` | | Hook payload shape (`tool_name`, `tool_input.command` as a string, `tool_response`, and `cwd`, which since 0.166.0 is the shell call's own `workdir` when it passes one and the session cwd otherwise) | the scripts read these keys directly; the secret redactor derives the checkout root from `cwd`, so a `workdir` inside a submodule narrows it, as its docstring already allows | `codex-rs/core/src/{hook_runtime.rs,tools/context.rs}`, `codex-rs/hooks/src/events/common.rs` (`command_input_cwd`) | -| `auth.command` semantics (trimmed stdout, non-zero exit fails, no env fallback) | the whole credential path | `codex-rs/login/src/auth/external_bearer.rs` | +| `auth.command` semantics (trimmed stdout; a non-zero exit, empty stdout or timeout fails that run, with no env fallback; after a success, a failed run keeps the last token until a later re-run, on expiry or on a 401, succeeds) | the whole credential path | `codex-rs/login/src/auth/external_bearer.rs`, `codex-rs/login/src/auth/manager.rs` (`AuthManager::load_auth`, `AuthManager::auth`) | | `supports_websockets` default for custom providers | a true default would take traffic off `POST /v1/responses` and break the egress profile | `codex-rs/model-provider-info/src/lib.rs` | | `[skills.bundled]` and skill discovery | the bundled skills are disabled by the runner-owned config; a renamed key would silently bring `skill-installer` and friends back into the agent's roster | `codex-rs/config/src/skills_config.rs` | -| Exec output truncation (`DEFAULT_MAX_OUTPUT_TOKENS`, head+tail) | the runtime note's 200-line window is sized to stay under this cap; on bump, confirm 200 lines of a dense `SKILL.md` still fits under the new cap and that a truncated exec still emits a warning the split rule can detect | `codex-rs/core/src/unified_exec/mod.rs`, `codex-rs/core/src/tools/context.rs`, `codex-rs/utils/string/src/truncate.rs` | +| Exec output truncation (`DEFAULT_MAX_OUTPUT_TOKENS`, and for a `code_mode_only` model such as `gpt-5.6-luna` the code-mode host's `DEFAULT_MAX_OUTPUT_TOKENS_PER_EXEC_CALL`; both 10,000 tokens at 0.170.0, head+tail) | the runtime note's 200-line window is sized to stay under this cap; on bump, confirm 200 lines of a dense `SKILL.md` still fits under the new cap and that a truncated exec still emits a warning the split rule can detect | `codex-rs/core/src/unified_exec/mod.rs`, `codex-rs/core/src/tools/context.rs`, `codex-rs/utils/string/src/truncate.rs`, `codex-rs/code-mode-protocol/src/runtime.rs`, `codex-rs/code-mode-runtime/src/output/output_render.rs`, `codex-rs/utils/output-truncation/src/lib.rs` | | The `plugins` feature and what it gates | `[features] plugins = false` is what stops the startup fetch of `github.com/openai/plugins.git`; a renamed key, or a sync no longer gated on it, would bring the fetch back | `codex-rs/features/src/lib.rs`, `codex-rs/core-plugins/src/manager.rs` (`maybe_start_plugin_startup_tasks_for_config`) | -| The native binary's path inside the platform package (`vendor//bin/codex` at 0.166.0) | the `fullsend-openai` profile names it as `**/codex`; the node ancestor still admits a renamed file, but the pin in `runtimeEgressBinaries` should follow the rename | `npm pack --dry-run "@openai/codex@-linux-x64"` | -| Whether a custom provider still issues `GET /v1/models` at startup | the `fullsend-openai` egress profile denies it; if the request ever became fatal or retried, it would delay or fail every first turn | `codex-rs/models-manager/` | +| The native binary's path inside the platform package (`vendor//bin/codex` at 0.170.0), and the launcher's `process.execve` | the `fullsend-openai` and `fullsend-inference-gateway` profiles name it as `**/codex`; with no node ancestor, a renamed file is denied on every model call until the profiles and `runtimeEgressBinaries` follow the rename | `npm pack --dry-run "@openai/codex@-linux-x64"`, `codex-cli/bin/codex.js` | +| Whether a custom provider still issues `GET /v1/models` at startup, every 4.5 minutes from the in-process models refresh and, at 0.170.0, before each sub-agent starts, and whether each denial stays non-fatal, unretried on a 403 and capped at 5 s | the `fullsend-openai` egress profile denies it; if the request ever became fatal or retried, it would delay or fail every first turn and every child start | `codex-rs/models-manager/` (`ensure_initialized`), `codex-rs/core/src/thread_manager/model_catalog.rs`, `codex-rs/app-server/src/models_refresh_worker.rs`, `codex-rs/model-provider/src/models_endpoint.rs` (`MODELS_REFRESH_TIMEOUT`) | | `models_cache.json` name and location, its TTL and the version/identity checks that decide whether it is used | `buildCodexRunCommand` deletes `$CODEX_HOME/models_cache.json` before launch so every run starts from the bundled catalog; a renamed or relocated file would need the deletion to follow it | `codex-rs/models-manager/src/manager.rs` (`MODEL_CACHE_FILE`, `DEFAULT_MODEL_CACHE_TTL`, `try_load_cache`), `codex-rs/models-manager/src/cache.rs` (`load_fresh_file`) | | `ConfigToml` keys and the `ReasoningEffort` enum | a renamed or removed key silently changes behaviour; `--strict-config` reports it | `codex-rs/config/src/config_toml.rs`, `codex-rs/protocol/src/openai_models.rs` | -| Project trust and `AGENTS.md` | the pinned untrusted entry must still stop codex recording its own trust level, the repo's `.codex/` layer must stay unloaded, and `$CODEX_HOME/AGENTS.md` must still load while the project is untrusted, or the bridge stops reaching the agent | `codex-rs/app-server/src/request_processors/thread_processor.rs` (trust write), `codex-rs/config/src/loader/mod.rs`, `codex-rs/core/src/agents_md.rs`, `codex-rs/codex-home/src/instructions/mod.rs` | +| Project trust and `AGENTS.md` | the pinned untrusted entry must keep the repo's `.codex/` layer and its own `AGENTS.md` unloaded, and `$CODEX_HOME/AGENTS.md` must still load while the project is untrusted, or the bridge stops reaching the agent; at 0.170.0 exec also prints a stderr warning naming `codex exec --trust` whenever it disables the repo's `.codex/` layer, and the runner must never pass that flag | `codex-rs/exec/src/lib.rs` (`--trust`), `codex-rs/config/src/loader/mod.rs`, `codex-rs/core/src/agents_md.rs`, `codex-rs/codex-home/src/instructions/mod.rs` | | JSONL event structs, rollout line types and rollout file naming | the stream parser and transcript extraction; a rollout line type missing from `codexRolloutEnvelopes` discards the whole transcript | `codex-rs/exec/src/exec_events.rs`, `codex-rs/history/src/rollout_payload.rs` (`RolloutItemWire`), `codex-rs/thread-store/src/local/helpers.rs` | -| Stderr warning markers (`dropping in-process server notification (queue full)`, `thread/items/list failed during turn completion`, `thread/items/list returned a repeated cursor during turn completion`, and the prefix `thread/read failed while backfilling turn items`), their log targets and levels, and the `RUST_LOG` filter (`error,opentelemetry_sdk=off,opentelemetry_otlp=off,codex_exec=warn,codex_app_server::in_process=warn`; `info` with debug) | `codexStderrDrops` and the debug-log counts match these literals; changed text, targets, levels or filter semantics can silently stop the dropped-notification and failed-backfill warnings | `codex-rs/exec/src/lib.rs` (backfill `warn!` calls, `EXEC_DEFAULT_LOG_FILTER`), `codex-rs/app-server/src/in_process.rs` (drop `warn!` call) | +| Stderr warning markers (`dropping in-process server notification (queue full)`, `thread/items/list failed during turn completion`, `thread/items/list returned a repeated cursor during turn completion`, `thread/items/list returned an incomplete item during turn completion`, and the prefix `thread/read failed while backfilling turn items`), their log targets and levels, and the `RUST_LOG` filter (`error,opentelemetry_sdk=off,opentelemetry_otlp=off,codex_exec=warn,codex_app_server::in_process=warn`; `info` with debug) | `codexStderrDrops` and the debug-log counts match these literals; changed text, targets, levels or filter semantics can silently stop the dropped-notification and failed-backfill warnings | `codex-rs/exec/src/lib.rs` (backfill `warn!` calls, `EXEC_DEFAULT_LOG_FILTER`), `codex-rs/app-server/src/in_process.rs` (drop `warn!` call) | | The multi-agent tool names (`multi_agent_v1*`, `collaboration*`, the bare V1 `spawn_agent`), the block contract (exit 2 with non-empty stderr blocks; a timeout kills the handler and lets the call through), `agent_id` and `agent_type` in a child's payload, the spawn arguments, and what a child start rereads (`hooks.json` and the role file) | the spawn guard's matcher, pass-through set, policy, digest set and deadline rest on them; a renamed tool is denied (loud), but a payload without `agent_id` or `agent_type`, a new model or effort argument, a changed `fork_turns` reading, a changed block contract or a child that rereads another file turns a deny into a pass | `codex-rs/core/src/tools/handlers/multi_agents_spec.rs`, `codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs` (`SpawnAgentArgs::fork_mode`, which the hook's `_is_none_fork` mirrors), `codex-rs/core/src/tools/registry.rs` (`function_hook_tool_name`), `codex-rs/hooks/src/engine/command_runner.rs` (the timeout branch), `codex-rs/core/src/agent/role.rs` (the role file, read at spawn) | -| The bundled catalog's `multi_agent_version`, `default_reasoning_level` and `supported_reasoning_levels` entries, the version codex supplies to an entry that carries none, and the floor model (`codex debug models --bundled`; at 0.166.0 `gpt-5.6-luna` is the listed model that selects `v1` and defaults to `medium`, and `gpt-5.5` carries no version, which the `multi_agent` feature, on by default, resolves to V1, and lists `low` to `xhigh`) | part two of the delegation gate, the child-model floor and the child-effort check rest on them: the floor must stay listed, or every delegating agent without `subagents.default` or `FULLSEND_CODEX_SUBAGENT_MODEL` fails Bootstrap, while the floor's own collaboration version matters only under a V2 parent, which delegates only while no child model selects V2 (moving luna to V2 would stop every V2 parent on the default child model from delegating); a bump that turns `multi_agent` off by default, or gives the null entry a version, changes which parents delegate; a changed level set changes which run efforts Bootstrap accepts; and the fixture `internal/runtime/testdata/codex/models-bundled-0.166.0.json` must be regenerated, never edited | `codex-rs/models-manager/models.json` in the bumped tag; regenerate the fixture with the one-liner in `codex_personas_test.go`'s `TestCodexCatalog` comment and run `go test ./internal/runtime/ -run 'TestCodexCatalog\|TestCodexParentCollabVersion\|TestCodexV2ChildModelReason\|TestResolveCodexChildModels_Effort'` | +| The bundled catalog's `multi_agent_version`, `default_reasoning_level` and `supported_reasoning_levels` entries, the version codex supplies to an entry that carries none, and the floor model (`codex debug models --bundled`; at 0.170.0 `gpt-5.6-luna` is the listed model that selects `v1` and defaults to `medium`, and `gpt-5.5` carries no version, which the `multi_agent` feature, on by default (deprecated at 0.170.0, still on), resolves to V1, and lists `low` to `xhigh`) | part two of the delegation gate, the child-model floor and the child-effort check rest on them: the floor must stay listed, or every delegating agent without `subagents.default` or `FULLSEND_CODEX_SUBAGENT_MODEL` fails Bootstrap, while the floor's own collaboration version matters only under a V2 parent, which delegates only while no child model selects V2 (moving luna to V2 would stop every V2 parent on the default child model from delegating); a bump that turns `multi_agent` off by default, or gives the null entry a version, changes which parents delegate; a changed level set changes which run efforts Bootstrap accepts; and the fixture `internal/runtime/testdata/codex/models-bundled-0.170.0.json` must be regenerated, never edited | `codex-rs/models-manager/models.json` in the bumped tag; regenerate the fixture with the one-liner in `codex_personas_test.go`'s `TestCodexCatalog` comment and run `go test ./internal/runtime/ -run 'TestCodexCatalog\|TestCodexParentCollabVersion\|TestCodexV2ChildModelReason\|TestResolveCodexChildModels_Effort'` | | The `[agents]` keys codex reads (`enabled`, `max_concurrent_threads_per_session`, `max_depth`, `default_subagent_model`, `default_subagent_reasoning_effort`, and `[agents.]` `description` and `config_file`) and the order of the child path: with no model argument a child takes `default_subagent_model` and, with no effort argument, `default_subagent_reasoning_effort`, else that model's catalog default; a role file applies after and its effort is checked against its own model | `codexAgentsBlock` writes the keys and Bootstrap checks the child efforts on that order; a renamed key or a changed order silently changes every child's model or effort | `codex-rs/config/src/config_toml.rs` (`AgentsToml`), `codex-rs/core/src/config/mod.rs`, `codex-rs/core/src/agent/child_config.rs` (`apply_requested_spawn_agent_model_overrides`, `apply_spawn_agent_role`), `codex-rs/core/src/agent/role.rs` | | What writes a rollout under the sessions directory in an exec run, rollout naming and the date layout, creation at a child's first recorded item, a PreToolUse block returning before the tool handler, and spawn-slot reservation before thread creation | the disk side of the admission cross-check (the four facts are in `internal/runtime/testdata/codex/README.md`) | `codex-rs/core/src/tools/registry.rs`, `codex-rs/core/src/agent/control/spawn.rs`, `codex-rs/rollout/src/rollout_file_name.rs`, `codex-rs/features/src/lib.rs` (the memories default) | -| The `enabled`, `disable_direct_message`, `max_wait_timeout_ms`, `expose_spawn_agent_model_overrides` and `max_concurrent_threads_per_session` keys of the `[features.multi_agent_v2]` table (codex parses it with `deny_unknown_fields`) and how codex derives the V2 child cap: the table's own key, else `[agents] max_concurrent_threads_per_session + 1`, else 4, minus one at reservation | ADR 0159 keeps the four-child cap under `[agents]`; a changed derivation silently gives a V2 parent three or five children, and the runner renders the table on every run (`enabled`, plus `disable_direct_message`, `max_wait_timeout_ms` and `expose_spawn_agent_model_overrides` for an admitted V2 parent), so a renamed key fails the config of every run that renders it; a changed `collab_tools_enabled` changes which children of a V2 parent get the multi-agent tools (at 0.166.0 only a child whose own model selects V2), and the V2 spawn's backstop, a V2 parent delegating only while no child model selects V2 (`codexV2ChildModelReason`), rests on it | `codex-rs/core/src/config/mod.rs` (`resolve_multi_agent_v2_config`, `effective_agent_max_threads`), `codex-rs/features/src/feature_configs.rs` (`MultiAgentV2ConfigToml`), `codex-rs/core/src/tools/spec_plan.rs` (`collab_tools_enabled`), codex's test `multi_agent_v2_uses_agents_max_concurrent_threads_per_session` in `codex-rs/core/src/config/config_tests.rs` | -| The wait cap (`codexWaitTimeoutMaxMS`, 120000, #9657): the `max_wait_timeout_ms` key of `[features.multi_agent_v2]` (the table is `deny_unknown_fields`, so a renamed key fails config parsing), the V2 wait's check of `timeout_ms` against that max and the schema max it feeds, and V1's wait limits, which are constants with a max of 3600000 | on V2 the cap is Codex's own: the wait schema the parent reads carries the configured max and the wait returns an error to the model for a longer `timeout_ms`, so the parent waits again; the spawn guard passes a wait through unread (ADR 0126, ADR 0159). A renamed key fails the config of every run that renders the table with `disable_direct_message`; a V2 wait that stopped checking the max leaves only the dispatch note. V1 has no setting, its schema asks for longer waits, and the dispatch note's rule is the only cap there, so a changed V1 limit or wait default changes nothing the runner enforces | `codex-rs/core/src/config/mod.rs` (`max_wait_timeout_ms`, validated in `resolve_multi_agent_v2_config`), `codex-rs/core/src/tools/spec_plan.rs` (the V2 wait schema's max), `codex-rs/core/src/tools/handlers/multi_agents_v2/wait.rs` (the `timeout_ms` max check), `codex-rs/core/src/tools/handlers/multi_agents_common.rs` (V1's wait constants) | +| The `enabled`, `disable_direct_message`, `max_wait_timeout_ms`, `expose_spawn_agent_model_overrides` and `max_concurrent_threads_per_session` keys of the `[features.multi_agent_v2]` table (codex parses it with `deny_unknown_fields`) and how codex derives the V2 child cap: the table's own key, else `[agents] max_concurrent_threads_per_session + 1`, else 4, minus one at reservation | ADR 0159 keeps the four-child cap under `[agents]`; a changed derivation silently gives a V2 parent three or five children, and the runner renders the table on every run (`enabled`, plus `disable_direct_message`, `max_wait_timeout_ms` and `expose_spawn_agent_model_overrides` for an admitted V2 parent), so a renamed key fails the config of every run that renders it; a changed `collab_tools_enabled` changes which children of a V2 parent get the multi-agent tools (at 0.170.0 only a child whose own model selects V2), and the V2 spawn's backstop, a V2 parent delegating only while no child model selects V2 (`codexV2ChildModelReason`), rests on it | `codex-rs/core/src/config/mod.rs` (`resolve_multi_agent_v2_config`, `effective_agent_max_threads`), `codex-rs/features/src/feature_configs.rs` (`MultiAgentV2ConfigToml`), `codex-rs/core/src/tools/spec_plan.rs` (`collab_tools_enabled`), codex's test `multi_agent_v2_uses_agents_max_concurrent_threads_per_session` in `codex-rs/core/src/config/config_tests.rs` | +| The wait cap (`codexWaitTimeoutMaxMS`, 120000, #9657): the `max_wait_timeout_ms` key of `[features.multi_agent_v2]` (the table is `deny_unknown_fields`, so a renamed key fails config parsing), the V2 wait's check of `timeout_ms` against that max and the schema max it feeds, and V1's wait limits, which are constants with a max of 3600000 | on V2 the cap is Codex's own: the wait schema the parent reads carries the configured max and the wait returns an error to the model for a longer `timeout_ms`, so the parent waits again; the spawn guard passes a wait through unread (ADR 0126, ADR 0159). A renamed key fails the config of every run that renders the table with `disable_direct_message`; a V2 wait that stopped checking the max leaves only the dispatch note. V1 has no setting, its schema asks for longer waits, and the dispatch note's rule is the only cap there, so a changed V1 limit or wait default changes nothing the runner enforces | `codex-rs/core/src/config/mod.rs` (`max_wait_timeout_ms`, read in `resolve_multi_agent_v2_config` and validated in `load_config_with_layer_stack`), `codex-rs/core/src/tools/spec_plan.rs` (the V2 wait schema's max), `codex-rs/core/src/tools/handlers/multi_agents_v2/wait.rs` (the `timeout_ms` max check), `codex-rs/core/src/tools/handlers/multi_agents_common.rs` (V1's wait constants) | | The V2 child-result path: `SubagentStop` runs in a thread-spawned child with `last_assistant_message`, the text that becomes its result, before the turn completes and `notify_parent_of_terminal_turn` queues the result to the parent; exit 2 with a non-empty stderr makes the child continue with that stderr as its prompt (an empty one is ignored and the message delivered), `continue: false` ends the child and delivers the message, and the result reaches the parent's next model request as an `agent_message` item, which codex sends only from a thread on V2: the feature table must keep putting every thread of the run on V2, whatever the child's model | the child-result gate (ADR 0159 decision 4) rests on it: re-check on every bump that `SubagentStop` still runs before the result is delivered, that a block still continues the child, and that the hook runs after a block still carry `stop_hook_active: true` for the rest of the turn; if either of the first two changes, a flagged result reaches the parent unchecked, and if the third does, a blocked child can retry through the chain | `codex-rs/core/src/session/turn.rs` (the stop-hook block), `codex-rs/core/src/hook_runtime.rs` (`run_turn_stop_hooks`), `codex-rs/hooks/src/events/stop.rs`, `codex-rs/core/src/agent/control/completion.rs`, `codex-rs/core/src/session/mod.rs` (`record_inter_agent_communication`); run `go test ./internal/runtime/ -run 'TestCodexAdapter_SubagentStopGate'` | diff --git a/docs/guides/dev/behaviour-drivers.md b/docs/guides/dev/behaviour-drivers.md index d7150e420c..f3fac49d7b 100644 --- a/docs/guides/dev/behaviour-drivers.md +++ b/docs/guides/dev/behaviour-drivers.md @@ -20,11 +20,11 @@ v1 reference implementations: - `pkg/behaviourtest/drivers/scm/gitlab/` - `pkg/behaviourtest/drivers/ci/githubactions/` - `pkg/behaviourtest/drivers/ci/gitlabci/` -- `pkg/behaviourtest/drivers/scm/forgejo/` and `pkg/behaviourtest/drivers/ci/forgejoactions/` (minimal stubs; see [Forgejo driver stubs](#forgejo-driver-stubs)) +- `pkg/behaviourtest/drivers/scm/forgejo/` (minimal stub) and `pkg/behaviourtest/drivers/ci/forgejoactions/` (Forgejo Actions); see [Forgejo drivers](#forgejo-drivers) - `pkg/behaviourtest/drivers/install/repopool_cfmint_previews.go` (RepoPoolCFMintPreviews) - `pkg/behaviourtest/drivers/install/repopool_cfmint_stage.go` (RepoPoolCFMintStage) - `pkg/behaviourtest/drivers/install/repopool_external_mint.go` (RepoPoolExternalMint) -- `pkg/behaviourtest/drivers/install/forgejo_dev.go` (NewForgejoDev, minimal stub) +- `pkg/behaviourtest/drivers/install/forgejo_dev.go` (NewForgejoDev: managed Forgejo stack lifecycle in `pkg/behaviourtest/drivers/install/forgejostack/`; repository allocation not implemented yet) - `pkg/behaviourtest/drivers/install/common/setup.go` (shared helpers: `RunGitHubSetup`, `ResolveInferenceWIFProvider`, `InferenceStatusWIFProvider`, `ProvisionInference`) ## Runner configuration @@ -50,7 +50,7 @@ The suite uses a single unified `install.Driver` constructed via `install.Factor |-------------|---------|------|-----|-------------| | `dev` (default) | `NewRepoPoolCFMintPreviews` | One public CF Worker preview per mint group leased in the run (four at 12 slots per org) | Pool orgs `halfsend-01` … `halfsend-22` | Vendored binary | | `stage` | `NewRepoPoolCFMintStage` | Durable CF Worker at `stage-mint.fullsend.sh` | `halfsend` (single unsuffixed org) | Non-vendored, `--fullsend-ref=main` | -| `forgejo-dev` | `NewForgejoDev` | None | None (stub; see [Forgejo driver stubs](#forgejo-driver-stubs)) | Not implemented | +| `forgejo-dev` | `NewForgejoDev` | None | Managed local Forgejo + Runner stack (see [Managed forgejo-dev stack](#managed-forgejo-dev-stack)) | Not implemented | Any other `ENVIRONMENT` value fails at suite startup; it never falls back to a GitHub factory. @@ -76,19 +76,44 @@ When the [job-scoped trace collector](behaviour-testing.md#job-scoped-trace-coll `Finalize` (RepoPoolCFMintPreviews) abandons every org's preview alias via `fullsend mint delete --platform=cloudflare` and reclaims any outstanding leases with an error. The RepoPoolCFMintStage driver's teardown is a no-op (the durable Worker persists across runs). The RepoPoolExternalMint driver's teardown is a no-op. -### Forgejo driver stubs +### Forgejo drivers `ENVIRONMENT=forgejo-dev` selects the Forgejo drivers. When `BEHAVIOUR_SCM` and `BEHAVIOUR_CI` are unset, they default to `forgejo` and `forgejoactions`. The Forgejo drivers only run together and only in `forgejo-dev`. If you mix them, for example `forgejo-dev` with `BEHAVIOUR_SCM=github`, or `BEHAVIOUR_SCM=forgejo` with `ENVIRONMENT=dev`, the suite fails at startup with an error that names the conflicting variables. It does not fall back to the GitHub or GitLab drivers. -The drivers are minimal stubs for now: +The SCM driver is still a minimal stub, and the install driver only manages the Forgejo stack. Forgejo scenarios therefore cannot run end to end yet, so no scenario is tagged `@forgejo` for the CI driver alone: -- `scm/forgejo` and `ci/forgejoactions` implement `scm.Driver` and `ci.Driver`. Every method returns an error. The CI stub implements none of the optional CI extensions. -- `install.NewForgejoDev` returns an `install.Driver` that provisions nothing. `AllocateRepo` and `DeallocateRepo` return an error, `Finalize` is a no-op, and `Capacity` is `install.ForgejoDevCapacity` (2). It is not an `install.LeaseDriver`. -- In `forgejo-dev`, the runner's `PoolConfig` has no layout, `TokenFor` or `NewClient`. The stub driver does not implement `install.SuiteBootstrap`, so the runner's concurrency defaults to `Capacity` and the template `World` has no default org. The run never enumerates the GitHub pool, mints GitHub tokens or builds GitHub clients. +- `scm/forgejo` implements `scm.Driver`. Every method returns an error. +- `ci/forgejoactions` implements `ci.Driver` and the optional `ci.RunLister`, `ci.EmptyMatrixWaiter`, and `ci.AgentArtifactDownloader` extensions. Every API call goes through the Forgejo adapter's read-only Actions operations in `internal/forge/forgejo` (run list and get, jobs, per-run artifacts, artifact download, and job logs), which take the base URL with any path prefix. The driver only observes runs; it never dispatches, cancels, or reruns one. See [Forgejo Actions CI driver](#forgejo-actions-ci-driver). +- `install.NewForgejoDev` starts the [managed forgejo-dev stack](#managed-forgejo-dev-stack) and returns an `install.Driver` whose `Finalize` tears it down and whose `AgentSourceEnv` (`install.AgentSourceEnvReporter`) points `fullsend` at the stack's agent-definition fixture. `AllocateRepo` and `DeallocateRepo` return an error, and `Capacity` is `install.ForgejoDevCapacity` (2, the runner's capacity). It is not an `install.LeaseDriver`. +- In `forgejo-dev`, the runner's `PoolConfig` has no layout, `TokenFor` or `NewClient`. The driver does not implement `install.SuiteBootstrap`, so the runner's concurrency defaults to `Capacity` and the template `World` has no default org. The run never enumerates the GitHub pool, mints GitHub tokens or builds GitHub clients. - The GitHub token check lives in the install drivers that need GitHub access (`NewRepoPoolCFMintPreviews`, `NewRepoPoolCFMintStage`, `NewRepoPoolExternalMint`), not in the runner's general env loading (`e2etest.LoadEnvConfig`). They fail with `e2etest.ErrNoLocalGitHubToken` when a local run has no token, and the suite runner skips the run on that error. `NewForgejoDev` does not need a GitHub token. Each stub error is a `*drivers.NotImplementedError` (package `pkg/behaviourtest/drivers`) that names the driver and the operation, for example `forgejo SCM driver: CreateIssue: not implemented`. It satisfies `errors.Is(err, drivers.ErrNotImplemented)`. Use the same sentinel for any other driver operation that is not supported yet. +#### Forgejo Actions CI driver + +`ci/forgejoactions` keeps the `ci.Driver` contract of the GitHub Actions driver, with these Forgejo specifics: + +- **Run matching:** a run matches by workflow file name, event, and creation time, truncated to whole seconds. Forgejo identifies a workflow by its file name only, so the directory of the workflow path does not matter. The event is the run's `trigger_event` (the workflow's `on` key, for example `pull_request_target`) when Forgejo reports it, and the webhook event otherwise. When no matching run appears, `WaitForWorkflow` returns a `*ci.NotDispatchedError`, so steps retry once with the clock-skew buffer and the failure diagnostics list the repository's runs. `ListRecentRuns` sets `forge.WorkflowRun.Path` to the workflow file name. +- **Status:** Forgejo's `success`, `failure`, `cancelled`, and `skipped` become a `completed` run with that conclusion, `running` becomes `in_progress`, `waiting` becomes `queued`, and `blocked` becomes `waiting`. +- **Artifacts:** every artifact comes from the run that uploaded it, by the existing names (`fullsend-`, optionally with `.matrix-`). The `...After` downloads scan the runs created since the trigger, newest first, and download from the newest run whose own listing has a match. Agent downloads only use completed runs. The driver never uses a repository-wide artifact listing. An instance that serves artifacts directly from object storage answers the download with a redirect, which the adapter refuses like every redirect of an authenticated request. +- **Agent jobs:** harness agents are recognised by the GitHub Actions job names (`Harness run ()`, or the stage name such as `Triage` for a built-in stage), matched by suffix, or by the agent's artifact in a completed run. +- **Empty matrix:** a harness run settles as an empty matrix when it completed, its `Harness dispatch` job succeeded, and no `Harness run ()` job was scheduled. The unexpanded matrix job may be skipped or absent: Forgejo replaces a matrix job with its expanded jobs once the matrix is known. + +#### Managed forgejo-dev stack + +`make behaviour-test` with `ENVIRONMENT=forgejo-dev` owns the stack's whole lifecycle; CI runs no separate provisioning step. Package `pkg/behaviourtest/drivers/install/forgejostack` implements it: + +- **Pinned versions:** Forgejo 17.0.1 (rootless server image) and Forgejo Runner 13.2.1. `forgejostack/versions.go` is the only place that names them. Bump them there, together, along with the job image that the runner labels `docker` and `ubuntu-latest` map to. +- **Engine:** the stack runs on the host's Docker or Podman engine. It talks to the engine through its Unix socket using the Docker Engine API, which Podman also serves. `DOCKER_HOST`, then `CONTAINER_HOST`, select the socket and must be `unix://` URLs. With neither set, the first existing default is used: `/var/run/docker.sock`, then `$XDG_RUNTIME_DIR/podman/podman.sock`, then `/run/podman/podman.sock`. The socket is mounted into the runner, which starts job containers on the same engine. It is not mounted into the job containers. +- **Canonical URL:** `http://127.0.0.1:/`, on a free loopback port picked per run. Forgejo, the runner, and every job container share the host network namespace, and Forgejo listens on loopback only. The one URL therefore reaches the same server from the behaviour-test process, the runner, and job containers. This holds under rootful Docker and under Podman, rootful or rootless, and Forgejo is not exposed beyond the host. Rootless Docker is not supported: its host network is the daemon's own namespace, not the test process's, so startup detects it and fails fast with an infrastructure error. The trade-off is that job containers share the host's network namespace. That is acceptable for a disposable test stack running Fullsend's own workflows, but this profile needs a Linux host engine. +- **Startup and readiness:** the factory pulls the images and starts Forgejo with SQLite, Actions enabled, and registration and SSH disabled. It waits for `api/healthz` at the canonical URL, then creates a local-only admin user, seeds the agent-definition fixture (see below) and registers a runner with capacity 2. Finally it pushes a readiness workflow whose job runs in a job container and fetches the canonical URL. The factory returns only after that run succeeds. A successful run shows that the runner picks up jobs at the canonical URL and that job containers can reach it. It then logs the Forgejo and Runner versions. Startup is bounded at 20 minutes, the health check at 3, and the readiness job at 10. +- **Agent-definition fixture:** the stack creates a public `fullsend-ai/agents` repository and commits a minimal fixture to it in one commit: a triage harness and the agent prompt and policy it references (`forgejostack.AgentFixtureFiles`). `Stack.AgentsRef` is that commit. The driver implements the optional `install.AgentSourceEnvReporter` interface: `AgentSourceEnv` returns `FULLSEND_FORGEJO_URL`, `FULLSEND_FORGEJO_AGENTS_REPO` and `FULLSEND_FORGEJO_AGENTS_REF` for the stack. With them set, `fullsend` resolves built-in agents from the stack at that commit and never from GitHub (see [Agent definitions from a Forgejo instance](../../cli/run.md#agent-definitions-from-a-forgejo-instance)). Repository configs must also allow `fullsend-ai/agents/raw/` in `allowed_remote_resources`. +- **Teardown:** `Finalize` (registered as test cleanup, so it runs at the end of the CI job) stops the runner. It then removes every container labelled `ai.fullsend.behaviour.forgejo-stack=`: leftover job containers, the runner, and Forgejo, with their anonymous volumes. The stack keeps no other engine resources. +- **Diagnostics:** startup, readiness, and teardown failures are infrastructure-classified (`behaviourfail.Mark`). A factory failure fails the run at bootstrap through the normal completion report, so it is eligible for the one infrastructure retry. The error names the failed phase and includes the last 50 log lines of each started container. A failed startup removes what it started. A teardown error is logged as `driver finalize: …` like other drivers' teardown errors. + +`TestStack_Integration` in `forgejostack` runs the real stack when `FULLSEND_FORGEJO_STACK_TEST=1`. It checks the canonical URL from the test process and from the runner container (startup already checked it from a job container), that the agent-definition fixture is served at its pinned commit, and that teardown leaves no stack container behind. Run it once per engine by pointing `DOCKER_HOST` or `CONTAINER_HOST` at each engine's socket. + ## Adding an SCM driver 1. Implement `scm.Driver` in `pkg/behaviourtest/drivers/scm//`. @@ -166,6 +191,6 @@ Prefer unit tests with `httptest` for REST helpers. Optional smoke scenarios aga - [x] GitLab SCM driver (implemented; `@skip:gitlab` tag removal pending) - [x] GitLab CI driver (implemented; suite wiring currently uses a GitHub-backed `forge.Client` — not yet live-testable against real GitLab backends) -- [ ] Forgejo SCM, Forgejo Actions CI, and `forgejo-dev` install drivers (selection and not-implemented stubs only; see [Forgejo driver stubs](#forgejo-driver-stubs)) +- [ ] Forgejo SCM, Forgejo Actions CI, and `forgejo-dev` install drivers (selection, not-implemented SCM/CI stubs, and the managed stack lifecycle; see [Forgejo drivers](#forgejo-drivers)) - [ ] Tekton CI driver - [ ] Non-GitHub install backends diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index 72b25f9f02..0d3d7a1fe2 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -6,12 +6,154 @@ End-to-end Gherkin tests under `e2e/behaviour/` validate **deterministic platfor |---|-----------------|-----------|------------| | **Target** | Platform workflows, sandbox, SCM | Prompts, models | Go functions | | **Inference** | Dummy runtime | Real LLM | N/A | -| **Infrastructure** | Live GitHub + GHA | Varies | None | +| **Infrastructure** | GitHub emulator on pull requests; live GitHub + GHA in the merge queue and on `main` | Varies | None | ## When to add a behaviour test Add one when a **user-visible workflow** must be verified end-to-end (dispatch → workflow → post-script → SCM state) and the assertion is **binary**. Prefer unit tests for pure Go logic. +Pull requests run the scenarios on a GitHub emulator, and the merge queue and +`main` run them on live GitHub. Write the scenario so it runs on the emulator, +which lets every pull request run it; see +[Adding a scenario](#adding-a-scenario). + +## On a pull request + +Every pull request runs the behaviour scenarios against the +[GitHub emulator](#running-against-a-github-emulator), from +[`behaviour-github-emulator.yml`](../../../.github/workflows/behaviour-github-emulator.yml). +The run needs no repository secrets. + +### What runs, and what you see in Checks + +- **`behaviour-github-emulator`** is the required check. It passes only when + the 16 shard jobs, `behaviour-github-emulator (a)` to + `behaviour-github-emulator (p)`, and the `behaviour-github-emulator + (playback)` job all pass. +- **`behaviour-github-emulator (agents)`** runs the agents repository's suite + against your change. It is advisory, not required: it shows whether a fullsend + change breaks the agents suite. +- **`behaviour`** and **`playback`**, from `e2e.yml`, show as skipped. This is + expected, and a skipped job still satisfies these required checks. + +The live `behaviour` and `playback` suites run in the merge queue and on push +to `main`. The merge queue runs `behaviour-github-emulator` as well. To run the +live suites on a pull request before it is enqueued, see +[Run the live suites on a pull request](e2e-testing.md#run-the-live-suites-on-a-pull-request). + +### When the check fails + +1. Open the failed job. Find the failing scenario in the log of its main step: + `Run behaviour features` for a shard, `Run the playback suite` or + `Run the agents suite`. +2. Download the job's artifact from the **Artifacts** list on the run's + summary page. Every job uploads it, whether it passed or failed. + + | Job | Artifact | + |-----|----------| + | A shard | `behaviour-github-emulator-logs-` (`a` to `p`, or `custom` for a [dispatch with features](#running-chosen-scenarios-in-ci)) | + | Playback | `behaviour-github-emulator-logs-playback` | + | Agents | `behaviour-github-emulator-logs-agents` | + + The `Upload logs` step in `behaviour-github-emulator.yml` lists the paths. + Each artifact holds: + + - the run's `*.log` files: `bt-run.log` (the suite output), + `stack/emulator.log` (the emulator) and `stack/runner-.log` (one per + emulator runner); + - `phases.tsv`, with the time each phase of the job took; + - `emulator-profile.json`, a profile of the emulator process. Only the + shard artifacts hold it; + - `bt-artifacts/`, the per-scenario output, such as + `debug-scenario--/failure-summary.txt` for a failed + scenario; + - `openshell-logs/`, the OpenShell logs of each agent run. +3. Decide whether the failure comes from your change or from the emulator. + - It is likely an **emulator failure** when the emulator returns HTTP 4xx + or 5xx for an API call that GitHub supports, or when a workflow job never + starts because no emulator runner picks it up. Look for the call in + `bt-run.log` and `stack/emulator.log`, and for the job in + `stack/runner-.log`. + - Otherwise, treat it as a failure in the code under test. A scenario + that fails on an assertion, or a fullsend command that exits with an + error, usually points at the change. +4. Re-run the failed jobs once, with **Re-run failed jobs** on the run's + summary page. + Re-running needs write access to the repository. Without it, ask a + maintainer to re-run the jobs, or push a new commit. +5. If the job fails again and the failure looks like an emulator bug, file an issue + at . Include the + run link, the scenario and the emulator log lines. + +#### Troubleshooting + +Each row is error text a failed run prints. `N.N` stands for the elapsed time in seconds. + +| Error text | What it means | What to do | +|------------|---------------|------------| +| `behaviour suite failed with status 1: scenario failure (0 infrastructure, 1 scenario); report: .../failure-class.json` | A summary line. The counts say how many failed scenarios were classified as infrastructure and how many as scenario failures. | Scroll up to the `Error:` line under `Failed steps:` for the cause. | +| `harness agent "retro": workflow run 5 concluded with "failure" before producing artifact (url=https://ghemu.localhost/...)` | The agent's workflow ran on the emulator and failed. | Find the run's job in `stack/runner-.log` and read the failing step. In past runs, the cause was in the change under test. | +| `harness agent "pr-ping" did not complete successfully; no recent workflow runs found after trigger time; no repository artifacts listed` | The trigger started no workflow run. | Look in `stack/emulator.log` for the event and the run. If the emulator answered HTTP 4xx or 5xx to an API that GitHub supports, the bug is likely in the emulator. | +| `"review" agent was not dispatched since