From 26fd08d9a7fee24439eee4855fc92f5a3a3db128 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 22 Oct 2026 17:08:55 -0400 Subject: [PATCH] feat(#8726): let a CEL trigger decide review routing Add `fullsend dispatch --route review`, which resolves the review harness the way `fullsend run` does (a config entry with source:, else the agents-repo fallback at the lockstep ref) and prints one JSON line: run, skip, or bash when the resolved harness has no trigger. The route job evaluates it when the repository or organization variable FULLSEND_CEL_ROUTING_REVIEW is shadow or on, for pull request and comment events. shadow logs the CEL decision next to the bash stage; on lets it set or clear STAGE=review. The review job still runs the review. With the variable off or unset every new step is skipped and the bash stage is unchanged. Move the OWNERS-aware authorization gate out of Dispatch into AuthorizeEvent so both paths share it. Add a parity test of the default review trigger against the bash router, a test that runs the Determine stage script per mode, and a behaviour step that sets a repository variable and restores it at cleanup. Closes #8726 Assisted-by: Claude Signed-off-by: Wayne Sun --- .github/workflows/reusable-dispatch.yml | 196 +++++++++ docs/contributing/workflow-contracts.md | 2 +- docs/guides/dev/behaviour-testing.md | 2 + .../infrastructure-reference.md | 1 + docs/guides/user/cel-triggers-reference.md | 2 + docs/guides/user/customizing-agents.md | 84 ++++ internal/cli/dispatch.go | 32 ++ internal/cli/dispatch_route.go | 166 ++++++++ internal/cli/dispatch_route_test.go | 376 ++++++++++++++++++ internal/harnessdispatch/authorize.go | 39 ++ internal/harnessdispatch/core.go | 25 +- .../review_route_parity_test.go | 236 +++++++++++ .../testdata/review-trigger.cel | 15 + internal/scaffold/cel_review_route_test.go | 283 +++++++++++++ pkg/behaviourtest/steps/cleanup.go | 10 + pkg/behaviourtest/steps/registry.go | 1 + pkg/behaviourtest/steps/repo_variable.go | 90 +++++ pkg/behaviourtest/steps/repo_variable_test.go | 73 ++++ pkg/behaviourtest/suite/init.go | 1 + pkg/behaviourtest/world/world.go | 5 + 20 files changed, 1614 insertions(+), 25 deletions(-) create mode 100644 internal/cli/dispatch_route.go create mode 100644 internal/cli/dispatch_route_test.go create mode 100644 internal/harnessdispatch/authorize.go create mode 100644 internal/harnessdispatch/review_route_parity_test.go create mode 100644 internal/harnessdispatch/testdata/review-trigger.cel create mode 100644 internal/scaffold/cel_review_route_test.go create mode 100644 pkg/behaviourtest/steps/repo_variable.go create mode 100644 pkg/behaviourtest/steps/repo_variable_test.go diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index d8415c8caa..8fb0bb5f34 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -147,6 +147,154 @@ jobs: /OWNERS_ALIASES sparse-checkout-cone-mode: false + # CEL review routing (#8726). FULLSEND_CEL_ROUTING_REVIEW = off (default), + # shadow (log the CEL decision next to the bash stage) or on (the CEL + # decision sets STAGE=review). When it is off or unset every cel-* step + # is skipped and "Determine stage" routes exactly as before. Only PR and + # comment events are evaluated; other events keep the bash stage. + - name: Checkout config for CEL review route + id: cel-config + if: ${{ (vars.FULLSEND_CEL_ROUTING_REVIEW == 'shadow' || vars.FULLSEND_CEL_ROUTING_REVIEW == 'on') && (github.event_name == 'pull_request_target' || github.event_name == 'issue_comment') }} + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # Same trusted ref as the checkout above: the base branch for PR events. + ref: ${{ (github.event_name == 'pull_request_target' || github.event_name == 'pull_request_review') && github.event.pull_request.base.sha || github.sha }} + path: cel-route + persist-credentials: false + allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' }} + sparse-checkout: | + .fullsend/ + /OWNERS + /OWNERS_ALIASES + .defaults/action.yml + .defaults/.github/actions/install-fullsend-cli/ + .fullsend/.defaults/action.yml + sparse-checkout-cone-mode: false + + - name: Detect CLI install mode for CEL review route + id: cel-cli-mode + if: steps.cel-config.outcome == 'success' + shell: bash + run: | + set -euo pipefail + if [[ -f cel-route/.defaults/action.yml || -f cel-route/.fullsend/.defaults/action.yml ]]; then + echo "mode=vendored" >> "${GITHUB_OUTPUT}" + else + echo "mode=upstream" >> "${GITHUB_OUTPUT}" + fi + + - name: Guard vendored install for CEL review route + if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'vendored' + shell: bash + run: | + set -euo pipefail + if [[ ! -f cel-route/.fullsend/bin/fullsend ]]; then + echo "::error::broken --vendor install: vendored marker present but .fullsend/bin/fullsend is missing" + exit 1 + fi + + # Shares the harness-dispatch cache key, so whichever job installs first + # serves the other. + - name: Restore fullsend CLI cache for CEL review route + id: cel-cli-cache + if: steps.cel-config.outcome == 'success' + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/fullsend-cache + key: fullsend-cli-${{ steps.cel-cli-mode.outputs.mode }}-${{ job.workflow_sha }} + + - name: Install fullsend CLI for CEL review route (vendored defaults) + if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'vendored' && steps.cel-cli-cache.outputs.cache-hit != 'true' + uses: ./cel-route/.defaults/.github/actions/install-fullsend-cli + with: + mode: vendored + vendored_path: cel-route/.fullsend/bin/fullsend + github_token: ${{ github.token }} + + - name: Checkout upstream install action for CEL review route + if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'upstream' && steps.cel-cli-cache.outputs.cache-hit != 'true' + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: .workflow-actions + fetch-depth: 1 + sparse-checkout: | + .github/actions/install-fullsend-cli/ + sparse-checkout-cone-mode: false + + - name: Install fullsend CLI for CEL review route (upstream workflow) + if: steps.cel-config.outcome == 'success' && steps.cel-cli-mode.outputs.mode == 'upstream' && steps.cel-cli-cache.outputs.cache-hit != 'true' + uses: ./.workflow-actions/.github/actions/install-fullsend-cli + with: + mode: upstream + workflow_repository: ${{ job.workflow_repository }} + workflow_sha: ${{ job.workflow_sha }} + github_token: ${{ github.token }} + + - name: Expose cached fullsend CLI for CEL review route + if: steps.cel-config.outcome == 'success' && steps.cel-cli-cache.outputs.cache-hit == 'true' + shell: bash + run: | + set -euo pipefail + install_dir="${RUNNER_TEMP}/fullsend" + 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 review route + if: steps.cel-config.outcome == 'success' && steps.cel-cli-cache.outputs.cache-hit != 'true' + shell: bash + run: | + set -euo pipefail + mkdir -p "${RUNNER_TEMP}/fullsend-cache" + cp "${RUNNER_TEMP}/fullsend/fullsend" "${RUNNER_TEMP}/fullsend-cache/fullsend" + + - name: Save fullsend CLI cache for CEL review route + if: steps.cel-config.outcome == 'success' && steps.cel-cli-cache.outputs.cache-hit != 'true' + 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 }}-${{ job.workflow_sha }} + + # A failure here never fails the route job: "Determine stage" keeps the + # bash stage and reports the failure (::error:: when on, ::warning:: when + # shadow). + - name: Evaluate CEL review route + id: cel-review + if: steps.cel-config.outcome == 'success' + continue-on-error: true + shell: bash + env: + GH_TOKEN: ${{ github.token }} + GITHUB_EVENT_NAME: ${{ github.event_name }} + EVENT_ACTION: ${{ inputs.event_action }} + run: | + set -euo pipefail + DECISION_JSON=$(fullsend dispatch \ + --input-driver gha-event \ + --config-dir cel-route/.fullsend \ + --event-action "${EVENT_ACTION}" \ + --route review) + printf '%s\n' "${DECISION_JSON}" + DECISION=$(jq -r '.decision // ""' <<<"${DECISION_JSON}") + case "${DECISION}" in + run|skip|bash) ;; + *) + echo "::error::Unexpected CEL review route decision: ${DECISION}" + exit 1 + ;; + esac + REASON=$(jq -r '.reason // ""' <<<"${DECISION_JSON}" | tr -d '\r\n') + HARNESS=$(jq -r '.harness // ""' <<<"${DECISION_JSON}" | tr -d '\r\n') + { + echo "decision=${DECISION}" + echo "reason=${REASON}" + echo "harness=${HARNESS}" + } >> "${GITHUB_OUTPUT}" + - name: Determine stage id: route env: @@ -170,6 +318,11 @@ jobs: ORG_NAME: ${{ github.repository_owner }} FULLSEND_APP_SET: ${{ vars.FULLSEND_APP_SET || 'fullsend-ai' }} GH_TOKEN: ${{ github.token }} + CEL_REVIEW_MODE: ${{ vars.FULLSEND_CEL_ROUTING_REVIEW }} + CEL_REVIEW_OUTCOME: ${{ steps.cel-review.outcome }} + CEL_REVIEW_DECISION: ${{ steps.cel-review.outputs.decision }} + CEL_REVIEW_REASON: ${{ steps.cel-review.outputs.reason }} + CEL_REVIEW_HARNESS: ${{ steps.cel-review.outputs.harness }} run: | set -euo pipefail @@ -421,6 +574,49 @@ jobs: ;; esac + # CEL review routing (#8726). off or unset leaves STAGE exactly as + # the bash rules above set it. shadow only logs. on lets the CEL + # decision set or clear STAGE=review, but never replaces another + # bash stage; decision=bash (the resolved review harness has no + # trigger) keeps the bash stage. + case "${CEL_REVIEW_MODE:-off}" in + off) ;; + shadow|on) + if [[ "${CEL_REVIEW_OUTCOME}" == "skipped" || -z "${CEL_REVIEW_OUTCOME}" ]]; then + : # Event type not evaluated by CEL: keep the bash stage. + elif [[ "${CEL_REVIEW_OUTCOME}" != "success" ]]; then + if [[ "${CEL_REVIEW_MODE}" == "on" ]]; then + echo "::error::CEL review route failed; keeping the bash stage '${STAGE}'. See the 'Evaluate CEL review route' step." + else + echo "::warning::CEL review route (shadow) failed. See the 'Evaluate CEL review route' step." + fi + elif [[ -n "${STAGE}" && "${STAGE}" != "review" ]]; then + echo "::notice::CEL review route: keeping bash stage '${STAGE}' (CEL decision ${CEL_REVIEW_DECISION})" + else + CEL_BASH_STAGE="${STAGE:-none}" + echo "::notice::CEL review route (${CEL_REVIEW_MODE}): bash=${CEL_BASH_STAGE} cel=${CEL_REVIEW_DECISION} reason=${CEL_REVIEW_REASON} harness=${CEL_REVIEW_HARNESS}" + if [[ "${CEL_REVIEW_MODE}" == "shadow" ]]; then + if [[ "${CEL_REVIEW_DECISION}" == "run" && "${STAGE}" != "review" ]] \ + || [[ "${CEL_REVIEW_DECISION}" == "skip" && "${STAGE}" == "review" ]]; then + echo "::warning::CEL review route mismatch: bash=${CEL_BASH_STAGE} cel=${CEL_REVIEW_DECISION} (${CEL_REVIEW_REASON})" + fi + echo "CEL review route (shadow): bash=${CEL_BASH_STAGE} cel=${CEL_REVIEW_DECISION}" >> "${GITHUB_STEP_SUMMARY:-/dev/null}" + else + CEL_ROUTE_SOURCE="cel" + case "${CEL_REVIEW_DECISION}" in + run) STAGE="review" ;; + skip) STAGE="" ;; + *) CEL_ROUTE_SOURCE="bash" ;; + esac + echo "review_route=${CEL_ROUTE_SOURCE}" >> "${GITHUB_STEP_SUMMARY:-/dev/null}" + fi + fi + ;; + *) + echo "::warning::FULLSEND_CEL_ROUTING_REVIEW='${CEL_REVIEW_MODE}' is not off, shadow or on; using bash routing" + ;; + esac + if [[ -z "${STAGE}" ]]; then echo "No stage matched — skipping dispatch" echo "stage=" >> "${GITHUB_OUTPUT}" diff --git a/docs/contributing/workflow-contracts.md b/docs/contributing/workflow-contracts.md index 5150a0f84b..77d9b12c3b 100644 --- a/docs/contributing/workflow-contracts.md +++ b/docs/contributing/workflow-contracts.md @@ -8,7 +8,7 @@ **Silent failures and required-flag consistency:** Omitting a secret that is `required: true` at every hop in the chain fails loudly at workflow-call validation time and self-enforces. However, a secret whose `required` flag is `false` at any upstream hop can still arrive as an empty string at a downstream `required: true` consumer — GitHub Actions' required-secret validation only checks key presence, not that the resolved value is non-empty. The standalone prioritize workflow also passes optional GCP inputs to the Fullsend action and leaves credential preparation to `fullsend run`, matching dispatch. An explicit `fullsend_version` override with both GCP credentials supplied also runs the compatibility GCP preparation step, so older CLIs continue to support Vertex. Per-repo GCP inputs are optional because an OpenAI-only repository does not use them; for the fleet harnesses' optional GCP mount, `fullsend run` rejects missing credentials before the pre-script on Vertex. Treat a missing forwarding hop as a correctness bug, not a cosmetic issue. -**OWNERS-file authorization:** `has_repo_permission` in `reusable-dispatch.yml` supports an opt-in OWNERS-file path gated by `owners_file` in the `authorization` providers list in `.fullsend/config.yaml`. When enabled, the function checks the repo-root `OWNERS` (and `OWNERS_ALIASES` if present) before falling back to the collaborator API. Approvers get write-equivalent access; reviewers get triage-equivalent. `TestDispatchPerStageAuthorization` checks `has_repo_permission` including OWNERS role-mapping invariants. The Go harness-dispatch path (`internal/harnessdispatch/core.go`) has equivalent OWNERS resolution via `internal/owners`; changes to the OWNERS schema or role mapping must be kept in sync across both implementations. +**OWNERS-file authorization:** `has_repo_permission` in `reusable-dispatch.yml` supports an opt-in OWNERS-file path gated by `owners_file` in the `authorization` providers list in `.fullsend/config.yaml`. When enabled, the function checks the repo-root `OWNERS` (and `OWNERS_ALIASES` if present) before falling back to the collaborator API. Approvers get write-equivalent access; reviewers get triage-equivalent. `TestDispatchPerStageAuthorization` checks `has_repo_permission` including OWNERS role-mapping invariants. The Go harness-dispatch path (`AuthorizeEvent` in `internal/harnessdispatch/authorize.go`, shared by `fullsend dispatch` and its `--route` mode) has equivalent OWNERS resolution via `internal/owners`; changes to the OWNERS schema or role mapping must be kept in sync across both implementations. **Security — consuming threaded inputs:** When a newly-threaded entry carries user- or event-controlled data, consume it via `env:` in the final `run:` step — never interpolate `${{ ... }}` directly into a shell block (see the Security note atop `reusable-dispatch.yml`). This prevents the GHA script-injection class of bugs the project defends against elsewhere. diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index faf09c46a9..fd0eeb512b 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -600,6 +600,8 @@ The `fork-dispatch.feature` file defines the canonical fork-PR behaviour contrac **`the kill switch is active in config.base.yaml`** — Sets `kill_switch: true` in `config.base.yaml` (the central/base layer) instead, leaving `config.yaml` unset. Use this step to verify that a base-file kill switch halts dispatch the same way an overlay one does, since the two files are read independently. +**`the repository variable "" is ""`** — Sets a repository variable on the enrolled repo, for example `FULLSEND_CEL_ROUTING_REVIEW` to `shadow` or `on`. The first time a scenario sets a name, the step records the previous value (or that the variable did not exist), and scenario cleanup restores it, so the slot's next scenario runs with the install defaults. Requires the GitHub SCM driver. + ## Forge operational constraints When modifying behaviour test repo provisioning, fork handling, or workflow dispatch, be aware of these constraints. They are not enforced by the compiler or linter — violations surface as cryptic API errors or silently dropped events in CI. diff --git a/docs/guides/infrastructure/infrastructure-reference.md b/docs/guides/infrastructure/infrastructure-reference.md index 107fbdac71..a4da5db6a0 100644 --- a/docs/guides/infrastructure/infrastructure-reference.md +++ b/docs/guides/infrastructure/infrastructure-reference.md @@ -349,6 +349,7 @@ Repos whose `inference.auth` is `openai-wif` need no Fullsend-managed inference - `FULLSEND_GCP_REGION` (value drift is detected and repaired by convergence) - `FULLSEND_REVIEW_CLIENT_ID` — OAuth client ID of the review agent's GitHub App (best-effort, conditional on successful lookup) - `FULLSEND_APP_SET` — GitHub App set prefix (apps named `{app-set}-{role}`); auto-set by the installer and repaired on convergence +- `FULLSEND_CEL_ROUTING_REVIEW` — optional, set by you: `off` (default), `shadow` or `on`; lets the review harness `trigger` decide when review runs ([Choosing when review runs](../user/customizing-agents.md#choosing-when-review-runs)); not set by `github setup` #### GitLab diff --git a/docs/guides/user/cel-triggers-reference.md b/docs/guides/user/cel-triggers-reference.md index 994798768b..fea17c7f37 100644 --- a/docs/guides/user/cel-triggers-reference.md +++ b/docs/guides/user/cel-triggers-reference.md @@ -33,6 +33,8 @@ When you register a custom agent and give it a `trigger` expression, fullsend ha Built-in agents (triage, code, review, fix, retro, prioritize) are routed by the dispatch workflow's stage-based routing logic. Custom agents with CEL triggers run alongside them — the two mechanisms coexist. A single event can trigger both a built-in agent via stage routing and one or more custom agents via CEL matching. +The review agent can opt in to CEL routing: with the variable `FULLSEND_CEL_ROUTING_REVIEW` set to `on`, the trigger on the resolved review harness decides whether the `Review` job starts, and `shadow` only logs that decision. A resolved review harness without a `trigger` keeps the stage-based routing, and an empty `trigger` in a harness with `base:` inherits the base trigger. See [Choosing when review runs](customizing-agents.md#choosing-when-review-runs). + You can also keep a hand-written workflow that invokes `fullsend run` with a fixed harness path. CEL-based dispatch and explicit harness invocation may run side by side in the same installation. ## Writing CEL triggers diff --git a/docs/guides/user/customizing-agents.md b/docs/guides/user/customizing-agents.md index fbbfc08e80..de44441aac 100644 --- a/docs/guides/user/customizing-agents.md +++ b/docs/guides/user/customizing-agents.md @@ -729,6 +729,90 @@ role name. The built-in agent names are: `code`, `triage`, `review`, agent named `code` — writing `name: coder` passes validation but disables nothing because no agent has that harness name. +## Choosing when review runs + +By default, the dispatch workflow decides when the review agent runs: when a +pull request is opened, pushed to or marked ready, when the +`ready-for-review` label is added, and on a `/fs-review` comment. To change +that, set the repository or organization variable +`FULLSEND_CEL_ROUTING_REVIEW` and give the review harness a `trigger` +expression. The review still runs in the same `Review` job; the trigger only +decides whether that job starts. + +| `FULLSEND_CEL_ROUTING_REVIEW` | What happens | +|---|---| +| unset or `off` | The dispatch workflow decides, as before. | +| `shadow` | The dispatch workflow still decides. The `Route` job also evaluates the review trigger and logs both decisions, with a warning when they differ. Use this to check a trigger before you switch to `on`. | +| `on` | The review trigger decides for pull request and comment events. | + +The review harness is the one `fullsend run review` resolves: your +`agents:` entry named `review` with a `source:`, otherwise the default review +harness from the agents repository. **If the resolved harness has no +`trigger`, the dispatch workflow keeps deciding even when the variable is +`on`.** A review override whose `base:` pins an agents commit from before the +default review trigger existed therefore keeps today's behaviour. + +### Example: review only on `/fs-review` + +To stop automatic reviews on every pull request but keep `/fs-review`, +override the review harness with a narrower trigger: + +```yaml +# .fullsend/harness/review.yaml +base: https://raw.githubusercontent.com/fullsend-ai/agents//harness/review.yaml#sha256=abc... + +trigger: > + event.transition.kind == "comment_added" + && has(event.transition.comment.command) + && event.transition.comment.command == "/fs-review" + && event.actor.kind == "human" +``` + +```yaml +# .fullsend/config.yaml +agents: + - name: review + source: harness/review.yaml +``` + +Then turn routing on: + +```bash +gh variable set FULLSEND_CEL_ROUTING_REVIEW --repo / --body shadow +# after the shadow log looks right: +gh variable set FULLSEND_CEL_ROUTING_REVIEW --repo / --body on +``` + +You cannot remove an inherited trigger by leaving `trigger` empty: an empty +`trigger` inherits the one from `base:`. Write the narrower expression +instead, or `trigger: "false"` to never start a review automatically. + +### Checking the decision + +The `Route` job's "Determine stage" step logs one line per pull request or +comment event: + +```text +CEL review route (on): bash=review cel=skip reason=trigger did not match harness=config:harness/review.yaml +``` + +With `on`, the job summary also shows `review_route=cel` (the trigger +decided) or `review_route=bash` (the resolved harness has no trigger). + +| Log text | Meaning | Action | +|---|---|---| +| `CEL review route mismatch: bash=review cel=skip` | `shadow`: the trigger would skip a review the workflow runs | Expected for events your trigger leaves out; otherwise fix the trigger before switching to `on` | +| `CEL review route failed; keeping the bash stage` | `on`: the trigger could not be evaluated, so the workflow decided | Open the "Evaluate CEL review route" step for the error (for example a harness that fails to load) | +| `bash=... cel=bash reason=resolved harness has no trigger` | The review harness has no trigger | Add a `trigger` to your review harness, or remove the override to use the default | +| `is not off, shadow or on; using bash routing` | The variable holds another value | Set it to `off`, `shadow` or `on` | + +Two cases are not yet authorized on the trigger path, so with `on` they do +not start a review: pull requests and `/fs-review` comments from triage-role +users ([#8724](https://github.com/fullsend-ai/fullsend/issues/8724)), and pull +requests opened or pushed by a bot without a `write` collaborator role, +including fullsend's own agent bots. Check both in `shadow` before you switch +to `on`. + ## Agent dispatch authorization By default, fullsend checks the forge's permission API to decide who can diff --git a/internal/cli/dispatch.go b/internal/cli/dispatch.go index 26be77fe5d..7b70f36a62 100644 --- a/internal/cli/dispatch.go +++ b/internal/cli/dispatch.go @@ -2,6 +2,7 @@ package cli import ( "context" + "encoding/json" "fmt" "os" "strings" @@ -13,6 +14,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/harnessdispatch/input" "github.com/fullsend-ai/fullsend/internal/harnessdispatch/output" "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/internal/ui" ) func newDispatchCmd() *cobra.Command { @@ -25,6 +27,7 @@ func newDispatchCmd() *cobra.Command { eventName string eventAction string forgeToken string + route string ) cmd := &cobra.Command{ @@ -40,6 +43,7 @@ func newDispatchCmd() *cobra.Command { eventName: eventName, eventAction: eventAction, forgeToken: forgeToken, + route: route, }) }, } @@ -52,6 +56,7 @@ func newDispatchCmd() *cobra.Command { cmd.Flags().StringVar(&eventName, "event-name", "", "GitHub event name (default: GITHUB_EVENT_NAME)") cmd.Flags().StringVar(&eventAction, "event-action", "", "GitHub event action") cmd.Flags().StringVar(&forgeToken, "forge-token", "", "Forge API token (default: GH_TOKEN, GITHUB_TOKEN, or gh auth token)") + cmd.Flags().StringVar(&route, "route", "", "Decide routing for one built-in agent (review) and print one JSON line with decision run, skip or bash; --output-driver is ignored") return cmd } @@ -65,9 +70,17 @@ type dispatchOpts struct { eventName string eventAction string forgeToken string + // route, when set, names a built-in agent (routableAgents) to decide + // routing for instead of producing a dispatch matrix. + route string } func runDispatch(ctx context.Context, opts dispatchOpts) error { + route := strings.ToLower(strings.TrimSpace(opts.route)) + if opts.route != "" && !routableAgents[route] { + return fmt.Errorf("unsupported --route agent %q (supported: review)", opts.route) + } + inDriver := opts.inputDriver if inDriver == "" { if os.Getenv("GITHUB_EVENT_PATH") != "" { @@ -103,6 +116,25 @@ func runDispatch(ctx context.Context, opts dispatchOpts) error { return err } + if route != "" { + decision, err := routeBuiltinAgent(ctx, routeOpts{ + agent: route, + configDir: opts.configDir, + event: event, + forgeClient: client, + printer: ui.New(os.Stderr), + }) + if err != nil { + return err + } + data, err := json.Marshal(decision) + if err != nil { + return err + } + _, err = fmt.Fprintln(os.Stdout, string(data)) + return err + } + refs, err := harnessdispatch.Dispatch(ctx, harnessdispatch.Options{ ConfigDir: opts.configDir, Event: event, diff --git a/internal/cli/dispatch_route.go b/internal/cli/dispatch_route.go new file mode 100644 index 0000000000..ccb6037fdb --- /dev/null +++ b/internal/cli/dispatch_route.go @@ -0,0 +1,166 @@ +package cli + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/fetch" + "github.com/fullsend-ai/fullsend/internal/forge" + gh "github.com/fullsend-ai/fullsend/internal/forge/github" + "github.com/fullsend-ai/fullsend/internal/harness" + "github.com/fullsend-ai/fullsend/internal/harnessdispatch" + "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// Route decisions printed by `fullsend dispatch --route `. +const ( + // routeRun: the resolved harness trigger matched an authorized event. + routeRun = "run" + // routeSkip: the agent must not run for this event. + routeSkip = "skip" + // routeBash: the resolved harness has no trigger, so the bash router in + // reusable-dispatch.yml keeps deciding (compatibility guard). + routeBash = "bash" +) + +// routableAgents lists the built-in agents whose routing a CEL trigger may +// decide through --route. Each one still runs in its own reusable-dispatch.yml +// job; --route only answers whether that job runs. +var routableAgents = map[string]bool{"review": true} + +// routeDecision is the one-line JSON answer of `fullsend dispatch --route`. +type routeDecision struct { + Agent string `json:"agent"` + Decision string `json:"decision"` + Reason string `json:"reason"` + // Harness names the harness the decision used: "config:" for a + // config-registered harness, "agents@" for the agents-repo fallback. + Harness string `json:"harness,omitempty"` +} + +type routeOpts struct { + agent string + configDir string + event *normevent.Event + // forgeClient resolves the agents-repo ref for the fallback. When nil, + // an unauthenticated GitHub client is used (fullsend-ai/agents is public). + forgeClient forge.Client + // fetchPolicy overrides fetch.DefaultPolicy (tests). + fetchPolicy *fetch.FetchPolicy + printer *ui.Printer +} + +// routeBuiltinAgent decides whether a built-in agent runs for an event. It +// resolves the agent harness the way `fullsend run` does (a config entry with +// source:, else the agents-repo fallback at the lockstep ref), and returns +// routeBash when that harness has no trigger. Otherwise the event must pass +// the dispatch authorization gate and the trigger must match. +func routeBuiltinAgent(ctx context.Context, o routeOpts) (routeDecision, error) { + d := routeDecision{Agent: o.agent} + if o.event == nil { + return d, fmt.Errorf("event is required") + } + + cfg, err := config.LoadConfig(o.configDir, config.LoadOpts{MissingOK: true}) + if err != nil { + return d, err + } + if cfg.IsKillSwitchActive() { + return withDecision(d, routeSkip, "kill switch active"), nil + } + if config.IsAgentExplicitlyDisabled(cfg.AgentEntries(), o.agent) { + return withDecision(d, routeSkip, "agent disabled in config"), nil + } + + absConfigDir, err := filepath.Abs(o.configDir) + if err != nil { + return d, fmt.Errorf("resolving config dir: %w", err) + } + allowlist := cfg.AllowedResources() + if allowlist == nil { + allowlist = config.DefaultAllowedRemoteResources() + } + policy := fetch.DefaultPolicy + if o.fetchPolicy != nil { + policy = *o.fetchPolicy + } + eventMap, err := o.event.ToMap() + if err != nil { + return d, err + } + composeOpts := harness.ComposeOpts{ + WorkspaceRoot: absConfigDir, + OrgAllowlist: allowlist, + FetchPolicy: policy, + Config: harness.BuildConfigMap(cfg), + Event: eventMap, + } + // Resolve forge: blocks for the event's forge, as `fullsend run` does. + switch o.event.Source.System { + case normevent.SystemGitHub, normevent.SystemGitLab: + composeOpts.ForgePlatform = string(o.event.Source.System) + } + + forgeClient := o.forgeClient + if forgeClient == nil { + forgeClient = gh.New("") + } + printer := o.printer + if printer == nil { + printer = ui.New(os.Stderr) + } + harnessPath, deps, err := resolveAgentSource(ctx, absConfigDir, o.agent, forgeClient, cfg, composeOpts, printer) + if err != nil { + return d, err + } + if len(deps) > 0 && deps[0].URL != "" { + composeOpts.SourceURL = deps[0].URL + } + d.Harness = routeHarnessLabel(cfg, o.agent, deps) + + h, _, err := harness.LoadWithBase(ctx, harnessPath, composeOpts) + if err != nil { + return d, fmt.Errorf("loading %s harness: %w", o.agent, err) + } + if strings.TrimSpace(h.Trigger) == "" { + return withDecision(d, routeBash, "resolved harness has no trigger"), nil + } + + if !harnessdispatch.AuthorizeEvent(o.configDir, cfg, o.event) { + return withDecision(d, routeSkip, "actor not authorized"), nil + } + ok, err := harness.EvaluateTrigger(h.Trigger, eventMap) + if err != nil { + return d, fmt.Errorf("evaluating %s trigger: %w", o.agent, err) + } + if !ok { + return withDecision(d, routeSkip, "trigger did not match"), nil + } + return withDecision(d, routeRun, "trigger matched"), nil +} + +func withDecision(d routeDecision, decision, reason string) routeDecision { + d.Decision = decision + d.Reason = reason + return d +} + +// routeHarnessLabel names the harness source for the decision log. +func routeHarnessLabel(cfg config.ConfigReader, agent string, deps []harness.Dependency) string { + if entry := findConfigAgentEntry(cfg.AgentEntries(), agent); entry != nil && entry.Source != "" { + return "config:" + entry.Source + } + if len(deps) > 0 && strings.HasPrefix(deps[0].URL, defaultAgentsRepoURLPrefix) { + sha, _, _ := strings.Cut(strings.TrimPrefix(deps[0].URL, defaultAgentsRepoURLPrefix), "/") + if len(sha) > 12 { + sha = sha[:12] + } + return "agents@" + sha + } + return "" +} diff --git a/internal/cli/dispatch_route_test.go b/internal/cli/dispatch_route_test.go new file mode 100644 index 0000000000..08edb39e24 --- /dev/null +++ b/internal/cli/dispatch_route_test.go @@ -0,0 +1,376 @@ +package cli + +import ( + "context" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/fetch" + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// routeTestTrigger mirrors the default review trigger shape: PR opened, +// synchronized or marked ready, the ready-for-review label, and a human +// /fs-review comment. +const routeTestTrigger = `trigger: > + (event.entity.kind == "change_proposal" + && event.transition.kind in ["opened", "synchronized", "marked_ready"]) + || (event.entity.kind == "change_proposal" + && event.transition.kind == "label_changed" + && event.transition.label.name == "ready-for-review" + && event.transition.label.action == "added") + || (event.transition.kind == "comment_added" + && has(event.transition.comment.command) + && event.transition.comment.command == "/fs-review" + && event.actor.kind == "human") +` + +// routeTestCommentOnlyTrigger is a narrowed override: /fs-review only. +const routeTestCommentOnlyTrigger = `trigger: > + event.transition.kind == "comment_added" + && has(event.transition.comment.command) + && event.transition.comment.command == "/fs-review" +` + +const routeTestHarnessBody = `agent: agents/review.md +role: review +slug: fullsend-ai-review +model: opus +image: ghcr.io/fullsend-ai/fullsend-sandbox:latest +` + +const routeTestSHA = "abcdef1234567890abcdef1234567890abcdef12" + +// routeAgentsRepo serves harness/review.yaml at routeTestSHA from a TLS test +// server standing in for the agents repo, and returns a forge client whose +// main ref resolves to that SHA plus the matching fetch policy. +func routeAgentsRepo(t *testing.T, harnessYAML string) (forge.Client, *fetch.FetchPolicy, string) { + t.Helper() + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/" + routeTestSHA + "/harness/review.yaml": + _, _ = w.Write([]byte(harnessYAML)) + case "/" + routeTestSHA + "/agents/review.md": + _, _ = w.Write([]byte("# review\n")) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + + hostname, port, err := net.SplitHostPort(strings.TrimPrefix(srv.URL, "https://")) + require.NoError(t, err) + tlsCfg := srv.TLS.Clone() + tlsCfg.InsecureSkipVerify = true + policy := fetch.NewTestPolicy(tlsCfg, []string{hostname}, []string{port}) + + orig := defaultAgentsRepoURLPrefix + defaultAgentsRepoURLPrefix = srv.URL + "/" + t.Cleanup(func() { defaultAgentsRepoURLPrefix = orig }) + + client := forge.NewFakeClient() + client.Refs["fullsend-ai/agents/heads/main"] = routeTestSHA + return client, &policy, srv.URL + "/" +} + +type routeFixture struct { + agents []config.AgentEntry + allowlist []string + killSwitch bool + files map[string]string // relative to the config dir +} + +func writeRouteFixture(t *testing.T, f routeFixture) string { + t.Helper() + dir := filepath.Join(t.TempDir(), ".fullsend") + require.NoError(t, os.MkdirAll(dir, 0o755)) + for rel, content := range f.files { + path := filepath.Join(dir, rel) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) + } + cfg := config.NewPerRepoConfig(nil, "fullsend-ai/demo") + cfg.SetAgents(f.agents) + if f.allowlist != nil { + cfg.SetAllowedRemoteResources(f.allowlist) + } + if f.killSwitch { + cfg.SetKillSwitch(true) + } + data, err := yaml.Marshal(cfg) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), data, 0o644)) + return dir +} + +func routeEvent(t *testing.T, raw string) *normevent.Event { + t.Helper() + ev, err := normevent.ParseJSON([]byte(raw)) + require.NoError(t, err) + return ev +} + +const ( + routePROpened = `{ + "repo": "fullsend-ai/demo", + "entity": {"kind": "change_proposal", "id": 7, "url": "https://github.com/fullsend-ai/demo/pull/7"}, + "transition": {"kind": "opened"}, + "actor": {"id": "alice", "kind": "human", "role": "write", "is_entity_author": true}, + "state": {"labels": []}, + "source": {"system": "github", "raw_type": "pull_request_target", "raw_action": "opened"} +}` + routeReviewComment = `{ + "repo": "fullsend-ai/demo", + "entity": {"kind": "change_proposal", "id": 7, "url": "https://github.com/fullsend-ai/demo/pull/7"}, + "transition": {"kind": "comment_added", "comment": {"id": "1", "command": "/fs-review", "body": "/fs-review"}}, + "actor": {"id": "alice", "kind": "human", "role": "write", "is_entity_author": false}, + "state": {"labels": []}, + "source": {"system": "github", "raw_type": "issue_comment", "raw_action": "created"} +}` + routePROpenedNoRole = `{ + "repo": "fullsend-ai/demo", + "entity": {"kind": "change_proposal", "id": 7, "url": "https://github.com/fullsend-ai/demo/pull/7"}, + "transition": {"kind": "opened"}, + "actor": {"id": "mallory", "kind": "human", "role": "none", "is_entity_author": true}, + "state": {"labels": []}, + "source": {"system": "github", "raw_type": "pull_request_target", "raw_action": "opened"} +}` +) + +func TestRouteBuiltinAgent(t *testing.T) { + disabled := false + cases := []struct { + name string + fixture func(t *testing.T, agentsURL string) routeFixture + agentsYAML string // served as the agents-repo review harness + event string + wantDecision string + wantReason string + wantHarness string + }{ + { + name: "no review entry uses the agents-repo harness and matches", + fixture: func(t *testing.T, u string) routeFixture { return routeFixture{allowlist: []string{u}} }, + agentsYAML: routeTestHarnessBody + routeTestTrigger, + event: routePROpened, + wantDecision: routeRun, + wantReason: "trigger matched", + wantHarness: "agents@" + routeTestSHA[:12], + }, + { + name: "override-only entry still uses the agents-repo harness", + fixture: func(t *testing.T, u string) routeFixture { + return routeFixture{ + allowlist: []string{u}, + agents: []config.AgentEntry{{Name: "review", Model: "sonnet"}}, + } + }, + agentsYAML: routeTestHarnessBody + routeTestTrigger, + event: routeReviewComment, + wantDecision: routeRun, + wantHarness: "agents@" + routeTestSHA[:12], + }, + { + name: "agents-repo harness without a trigger stays on bash", + fixture: func(t *testing.T, u string) routeFixture { return routeFixture{allowlist: []string{u}} }, + agentsYAML: routeTestHarnessBody, + event: routePROpened, + wantDecision: routeBash, + wantReason: "resolved harness has no trigger", + }, + { + name: "override on a base without a trigger stays on bash", + fixture: func(t *testing.T, u string) routeFixture { + return routeFixture{ + agents: []config.AgentEntry{{Name: "review", Source: "harness/review.yaml"}}, + files: map[string]string{ + "harness/base-old.yaml": routeTestHarnessBody, + "harness/review.yaml": `base: base-old.yaml +model: sonnet +pre_script: scripts/pre-review.sh +post_script: scripts/post-review.sh +forge: + github: + runner_env: + REVIEW_MODE: strict +`, + "harness/scripts/pre-review.sh": "#!/bin/sh\n", + "harness/scripts/post-review.sh": "#!/bin/sh\n", + }, + } + }, + event: routePROpened, + wantDecision: routeBash, + wantHarness: "config:harness/review.yaml", + }, + { + name: "override inherits the trigger of its base", + fixture: func(t *testing.T, u string) routeFixture { + return routeFixture{ + agents: []config.AgentEntry{{Name: "review", Source: "harness/review.yaml"}}, + files: map[string]string{ + "harness/base-new.yaml": routeTestHarnessBody + routeTestTrigger, + "harness/review.yaml": "base: base-new.yaml\nmodel: sonnet\n", + }, + } + }, + event: routePROpened, + wantDecision: routeRun, + }, + { + name: "narrowed override skips automatic review", + fixture: func(t *testing.T, u string) routeFixture { + return routeFixture{ + agents: []config.AgentEntry{{Name: "review", Source: "harness/review.yaml"}}, + files: map[string]string{ + "harness/review.yaml": routeTestHarnessBody + routeTestCommentOnlyTrigger, + }, + } + }, + event: routePROpened, + wantDecision: routeSkip, + wantReason: "trigger did not match", + }, + { + name: "narrowed override keeps /fs-review", + fixture: func(t *testing.T, u string) routeFixture { + return routeFixture{ + agents: []config.AgentEntry{{Name: "review", Source: "harness/review.yaml"}}, + files: map[string]string{ + "harness/review.yaml": routeTestHarnessBody + routeTestCommentOnlyTrigger, + }, + } + }, + event: routeReviewComment, + wantDecision: routeRun, + }, + { + name: "disabled agent is skipped", + fixture: func(t *testing.T, u string) routeFixture { + return routeFixture{agents: []config.AgentEntry{{Name: "review", Enabled: &disabled}}} + }, + event: routePROpened, + wantDecision: routeSkip, + wantReason: "agent disabled in config", + }, + { + name: "kill switch skips", + fixture: func(t *testing.T, u string) routeFixture { return routeFixture{killSwitch: true} }, + event: routePROpened, + wantDecision: routeSkip, + wantReason: "kill switch active", + }, + { + name: "unauthorized actor is skipped", + fixture: func(t *testing.T, u string) routeFixture { return routeFixture{allowlist: []string{u}} }, + agentsYAML: routeTestHarnessBody + routeTestTrigger, + event: routePROpenedNoRole, + wantDecision: routeSkip, + wantReason: "actor not authorized", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + agentsYAML := tc.agentsYAML + if agentsYAML == "" { + agentsYAML = routeTestHarnessBody + routeTestTrigger + } + client, policy, agentsURL := routeAgentsRepo(t, agentsYAML) + dir := writeRouteFixture(t, tc.fixture(t, agentsURL)) + + got, err := routeBuiltinAgent(context.Background(), routeOpts{ + agent: "review", + configDir: dir, + event: routeEvent(t, tc.event), + forgeClient: client, + fetchPolicy: policy, + printer: ui.New(io.Discard), + }) + require.NoError(t, err) + assert.Equal(t, "review", got.Agent) + assert.Equal(t, tc.wantDecision, got.Decision, "reason: %s", got.Reason) + if tc.wantReason != "" { + assert.Equal(t, tc.wantReason, got.Reason) + } + if tc.wantHarness != "" { + assert.Equal(t, tc.wantHarness, got.Harness) + } + }) + } +} + +func TestRouteBuiltinAgent_FallbackUnavailableIsAnError(t *testing.T) { + neutralizeAgentsRepoFallback(t) + dir := writeRouteFixture(t, routeFixture{}) + + _, err := routeBuiltinAgent(context.Background(), routeOpts{ + agent: "review", + configDir: dir, + event: routeEvent(t, routePROpened), + forgeClient: forge.NewFakeClient(), + printer: ui.New(io.Discard), + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "agents-repo fallback unavailable") +} + +func TestRunDispatch_RouteRejectsUnsupportedAgent(t *testing.T) { + err := runDispatch(context.Background(), dispatchOpts{route: "code", inputDriver: "json"}) + require.Error(t, err) + assert.Contains(t, err.Error(), `unsupported --route agent "code"`) +} + +func TestRunDispatch_RoutePrintsOneJSONLine(t *testing.T) { + dir := writeRouteFixture(t, routeFixture{ + agents: []config.AgentEntry{{Name: "review", Source: "harness/review.yaml"}}, + files: map[string]string{ + "harness/review.yaml": routeTestHarnessBody + routeTestCommentOnlyTrigger, + }, + }) + eventPath := filepath.Join(t.TempDir(), "event.json") + require.NoError(t, os.WriteFile(eventPath, []byte(routeReviewComment), 0o644)) + + old := os.Stdout + r, w, err := os.Pipe() + require.NoError(t, err) + os.Stdout = w + errCh := make(chan error, 1) + go func() { + defer w.Close() + errCh <- runDispatch(context.Background(), dispatchOpts{ + inputDriver: "json", + inputFile: eventPath, + configDir: dir, + route: "Review", + }) + }() + out, _ := io.ReadAll(r) + os.Stdout = old + require.NoError(t, <-errCh) + + lines := strings.Split(strings.TrimRight(string(out), "\n"), "\n") + require.Len(t, lines, 1, "stdout must hold exactly one JSON line: %q", out) + var got routeDecision + require.NoError(t, json.Unmarshal([]byte(lines[0]), &got)) + assert.Equal(t, routeDecision{ + Agent: "review", + Decision: routeRun, + Reason: "trigger matched", + Harness: "config:harness/review.yaml", + }, got) +} diff --git a/internal/harnessdispatch/authorize.go b/internal/harnessdispatch/authorize.go new file mode 100644 index 0000000000..5c68cc6766 --- /dev/null +++ b/internal/harnessdispatch/authorize.go @@ -0,0 +1,39 @@ +package harnessdispatch + +import ( + "log" + "path/filepath" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/internal/owners" +) + +// AuthorizeEvent applies the dispatch authorization gate (IsAuthorized) to +// event. When the per-repo config enables OWNERS-file authorization, the +// actor role is first upgraded from the OWNERS and OWNERS_ALIASES files in +// the parent of configDir. The caller's event is not mutated: the upgraded +// role is used only for the gate, and CEL evaluation keeps seeing the +// collaborator-API role. +func AuthorizeEvent(configDir string, cfg config.ConfigReader, event *normevent.Event) bool { + if event == nil { + return false + } + repoRoot := filepath.Dir(configDir) + effectiveRole := event.Actor.Role + if pr, ok := cfg.(config.PerRepoConfigReader); ok && pr.IsOwnersFileAuthEnabled() && event.Actor.ID != "" { + ownersPath := filepath.Join(repoRoot, "OWNERS") + aliasesPath := filepath.Join(repoRoot, "OWNERS_ALIASES") + role, err := owners.Resolve(ownersPath, aliasesPath, event.Actor.ID) + if err != nil { + log.Printf("harness dispatch: OWNERS resolution failed for %s: %v", event.Actor.ID, err) + } else if role != owners.RoleNone { + effectiveRole = owners.MapToActorRole(role, effectiveRole) + log.Printf("harness dispatch: OWNERS file resolved user %s as %s", event.Actor.ID, role) + } + } + + authCheck := *event + authCheck.Actor.Role = effectiveRole + return IsAuthorized(&authCheck) +} diff --git a/internal/harnessdispatch/core.go b/internal/harnessdispatch/core.go index f28d86bda8..09216cf93e 100644 --- a/internal/harnessdispatch/core.go +++ b/internal/harnessdispatch/core.go @@ -3,13 +3,10 @@ package harnessdispatch import ( "context" "fmt" - "log" - "path/filepath" "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/fetch" "github.com/fullsend-ai/fullsend/internal/normevent" - "github.com/fullsend-ai/fullsend/internal/owners" ) // Options configures a dispatch run. @@ -45,27 +42,7 @@ func Dispatch(ctx context.Context, opts Options) ([]ExecutionRef, error) { return nil, nil } - // Compute the effective role for the auth gate without mutating the - // caller's event. The OWNERS-upgraded role is used only for - // IsAuthorized; downstream CEL evaluation sees the original - // collaborator-API role. - repoRoot := filepath.Dir(opts.ConfigDir) - effectiveRole := opts.Event.Actor.Role - if pr, ok := dirCfg.(config.PerRepoConfigReader); ok && pr.IsOwnersFileAuthEnabled() && opts.Event.Actor.ID != "" { - ownersPath := filepath.Join(repoRoot, "OWNERS") - aliasesPath := filepath.Join(repoRoot, "OWNERS_ALIASES") - role, err := owners.Resolve(ownersPath, aliasesPath, opts.Event.Actor.ID) - if err != nil { - log.Printf("harness dispatch: OWNERS resolution failed for %s: %v", opts.Event.Actor.ID, err) - } else if role != owners.RoleNone { - effectiveRole = owners.MapToActorRole(role, effectiveRole) - log.Printf("harness dispatch: OWNERS file resolved user %s as %s", opts.Event.Actor.ID, role) - } - } - - authCheck := *opts.Event - authCheck.Actor.Role = effectiveRole - if !IsAuthorized(&authCheck) { + if !AuthorizeEvent(opts.ConfigDir, dirCfg, opts.Event) { return nil, nil } diff --git a/internal/harnessdispatch/review_route_parity_test.go b/internal/harnessdispatch/review_route_parity_test.go new file mode 100644 index 0000000000..f1a50edd1f --- /dev/null +++ b/internal/harnessdispatch/review_route_parity_test.go @@ -0,0 +1,236 @@ +package harnessdispatch_test + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/harness" + "github.com/fullsend-ai/fullsend/internal/harnessdispatch" + "github.com/fullsend-ai/fullsend/internal/harnessdispatch/input" +) + +// TestReviewRouteParity runs raw GitHub webhook payloads through the same +// steps `fullsend dispatch --route review` uses (gha-event input, the dispatch +// authorization gate, the review trigger) and compares the result with the +// decision the bash router in reusable-dispatch.yml makes for the same event. +// +// A row whose CEL result differs from bash must name the known difference in +// diff; any other mismatch is a parity regression. The trigger under test is +// testdata/review-trigger.cel, a copy of the trigger: field in the agents +// repository harness/review.yaml. +func TestReviewRouteParity(t *testing.T) { + triggerData, err := os.ReadFile(filepath.Join("testdata", "review-trigger.cel")) + require.NoError(t, err) + trigger := string(triggerData) + require.NoError(t, harness.ValidateTriggerExpression(trigger)) + + const repo = "acme/widgets" + permissions := map[string]string{ + repo + "/writer": "write", + repo + "/triager": "triage", + repo + "/reader": "read", + } + + cases := []struct { + name string + eventName string + action string + payload string + bash bool // reusable-dispatch.yml routes STAGE=review + cel bool // CEL route decision is run + diff string // known, accepted difference; empty when cel == bash + }{ + { + name: "PR opened by a write author", + eventName: "pull_request_target", action: "opened", + payload: prPayload("opened", "writer", "writer", ""), + bash: true, cel: true, + }, + { + name: "PR synchronized by its write author", + eventName: "pull_request_target", action: "synchronize", + payload: prPayload("synchronize", "writer", "writer", ""), + bash: true, cel: true, + }, + { + name: "PR marked ready by its write author", + eventName: "pull_request_target", action: "ready_for_review", + payload: prPayload("ready_for_review", "writer", "writer", ""), + bash: true, cel: true, + }, + { + name: "PR opened by a read-only author", + eventName: "pull_request_target", action: "opened", + payload: prPayload("opened", "reader", "reader", ""), + bash: false, cel: false, + }, + { + name: "PR opened by a triage author", + eventName: "pull_request_target", action: "opened", + payload: prPayload("opened", "triager", "triager", ""), + bash: true, cel: false, + diff: "the dispatch gate requires write until the per-harness threshold (#8724)", + }, + { + name: "PR opened by a bot without a collaborator role", + eventName: "pull_request_target", action: "opened", + payload: prPayload("opened", "dep-updater[bot]", "dep-updater[bot]", ""), + bash: true, cel: false, + diff: "bash reviews every [bot] author; the gha-event input does not run the ADR 0107 bot-role lookup yet, so a bot needs a write collaborator role", + }, + { + name: "PR from a read-only author synchronized by a write maintainer", + eventName: "pull_request_target", action: "synchronize", + payload: prPayload("synchronize", "reader", "writer", ""), + bash: false, cel: true, + diff: "bash checks the PR author; the dispatch gate checks the event sender", + }, + { + name: "ready-for-review label added by a triage user", + eventName: "pull_request_target", action: "labeled", + payload: prPayload("labeled", "reader", "triager", "ready-for-review"), + bash: true, cel: true, + }, + { + name: "another label added", + eventName: "pull_request_target", action: "labeled", + payload: prPayload("labeled", "writer", "writer", "documentation"), + bash: false, cel: false, + }, + { + name: "PR closed", + eventName: "pull_request_target", action: "closed", + payload: prPayload("closed", "writer", "writer", ""), + bash: false, cel: false, + }, + { + name: "/fs-review on a PR by a write user", + eventName: "issue_comment", action: "created", + payload: commentPayload(true, "writer", "User", "/fs-review"), + bash: true, cel: true, + }, + { + name: "/fs-review on a PR with trailing punctuation", + eventName: "issue_comment", action: "created", + payload: commentPayload(true, "writer", "User", "/fs-review."), + bash: true, cel: true, + }, + { + name: "/fs-review on a PR by a triage user", + eventName: "issue_comment", action: "created", + payload: commentPayload(true, "triager", "User", "/fs-review"), + bash: true, cel: false, + diff: "the dispatch gate requires write until the per-harness threshold (#8724)", + }, + { + name: "/fs-review on a PR by a read-only user", + eventName: "issue_comment", action: "created", + payload: commentPayload(true, "reader", "User", "/fs-review"), + bash: false, cel: false, + }, + { + name: "/fs-review on a PR by a bot", + eventName: "issue_comment", action: "created", + payload: commentPayload(true, "helper[bot]", "Bot", "/fs-review"), + bash: false, cel: false, + }, + { + name: "/fs-review on an issue", + eventName: "issue_comment", action: "created", + payload: commentPayload(false, "writer", "User", "/fs-review"), + bash: false, cel: false, + }, + { + name: "/fs-fix on a PR", + eventName: "issue_comment", action: "created", + payload: commentPayload(true, "writer", "User", "/fs-fix"), + bash: false, cel: false, + }, + } + + cfg, err := config.LoadConfig(t.TempDir(), config.LoadOpts{MissingOK: true}) + require.NoError(t, err) + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + eventPath := filepath.Join(t.TempDir(), "event.json") + require.NoError(t, os.WriteFile(eventPath, []byte(tc.payload), 0o644)) + + client := forge.NewFakeClient() + client.CollaboratorPermissions = permissions + ev, err := input.LoadGHAEvent(context.Background(), input.GHAEventOptions{ + EventPath: eventPath, + EventName: tc.eventName, + EventAction: tc.action, + Repository: repo, + Forge: client, + }) + require.NoError(t, err) + + got := false + if harnessdispatch.AuthorizeEvent(filepath.Join(t.TempDir(), ".fullsend"), cfg, ev) { + eventMap, err := ev.ToMap() + require.NoError(t, err) + got, err = harness.EvaluateTrigger(trigger, eventMap) + require.NoError(t, err) + } + + assert.Equal(t, tc.cel, got, "CEL route decision") + if tc.diff == "" { + assert.Equal(t, tc.bash, got, "CEL differs from bash without a documented difference") + } else { + assert.NotEqual(t, tc.bash, tc.cel, "row documents a difference but bash and CEL agree") + } + }) + } +} + +func prPayload(action, author, sender, label string) string { + labelField := "" + if label != "" { + labelField = `"label": {"name": "` + label + `"},` + } + senderType := "User" + if len(sender) > 5 && sender[len(sender)-5:] == "[bot]" { + senderType = "Bot" + } + return `{ + "action": "` + action + `", + ` + labelField + ` + "pull_request": { + "number": 7, + "html_url": "https://github.com/acme/widgets/pull/7", + "user": {"login": "` + author + `"}, + "labels": [], + "head": {"ref": "topic", "sha": "1111111111111111111111111111111111111111", "repo": {"full_name": "acme/widgets"}}, + "base": {"ref": "main", "repo": {"full_name": "acme/widgets"}} + }, + "sender": {"login": "` + sender + `", "type": "` + senderType + `"} +}` +} + +func commentPayload(onPR bool, commenter, userType, body string) string { + prField := "" + if onPR { + prField = `"pull_request": {"url": "https://api.github.com/repos/acme/widgets/pulls/7"},` + } + return `{ + "action": "created", + "issue": { + "number": 7, + "html_url": "https://github.com/acme/widgets/issues/7", + ` + prField + ` + "user": {"login": "someone"}, + "labels": [] + }, + "comment": {"id": 1, "body": "` + body + `", "user": {"login": "` + commenter + `", "type": "` + userType + `"}}, + "sender": {"login": "` + commenter + `", "type": "` + userType + `"} +}` +} diff --git a/internal/harnessdispatch/testdata/review-trigger.cel b/internal/harnessdispatch/testdata/review-trigger.cel new file mode 100644 index 0000000000..c5adb1a1b5 --- /dev/null +++ b/internal/harnessdispatch/testdata/review-trigger.cel @@ -0,0 +1,15 @@ +// Copy of the trigger: field in fullsend-ai/agents harness/review.yaml +// (added by fullsend-ai/agents#1755). Update both together; the parity test in +// review_route_parity_test.go compares it with the bash router. +(event.entity.kind == "change_proposal" + && event.transition.kind in ["opened", "synchronized", "marked_ready"]) +|| (event.entity.kind == "change_proposal" + && event.transition.kind == "label_changed" + && event.transition.label.name == "ready-for-review" + && event.transition.label.action == "added") +|| (event.transition.kind == "comment_added" + && has(event.transition.comment.command) + && event.transition.comment.command == "/fs-review" + && event.actor.kind == "human" + && (event.entity.kind == "change_proposal" + || has(event.entity.linked_change_proposal))) diff --git a/internal/scaffold/cel_review_route_test.go b/internal/scaffold/cel_review_route_test.go new file mode 100644 index 0000000000..62c00bb534 --- /dev/null +++ b/internal/scaffold/cel_review_route_test.go @@ -0,0 +1,283 @@ +package scaffold + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" +) + +type routeStepRun struct { + output string // GITHUB_OUTPUT contents + stdout string + summary string // GITHUB_STEP_SUMMARY contents +} + +// runDetermineStage executes the route job's "Determine stage" script under +// bash with event env that needs no GitHub API call, plus extra env. +func runDetermineStage(t *testing.T, event map[string]string, extra map[string]string) routeStepRun { + t.Helper() + script := extractReusableDispatchStepScript(t, "route", "Determine stage") + dir := t.TempDir() + outPath := filepath.Join(dir, "output") + summaryPath := filepath.Join(dir, "summary") + require.NoError(t, os.WriteFile(outPath, nil, 0o644)) + require.NoError(t, os.WriteFile(summaryPath, nil, 0o644)) + + cmd := exec.Command("bash", "-c", script) + cmd.Dir = dir + cmd.Env = []string{ + "PATH=" + os.Getenv("PATH"), + "GITHUB_OUTPUT=" + outPath, + "GITHUB_STEP_SUMMARY=" + summaryPath, + } + for k, v := range event { + cmd.Env = append(cmd.Env, k+"="+v) + } + for k, v := range extra { + cmd.Env = append(cmd.Env, k+"="+v) + } + out, err := cmd.CombinedOutput() + require.NoError(t, err, "Determine stage failed:\n%s", out) + + output, err := os.ReadFile(outPath) + require.NoError(t, err) + summary, err := os.ReadFile(summaryPath) + require.NoError(t, err) + return routeStepRun{output: string(output), stdout: string(out), summary: string(summary)} +} + +func stageOf(t *testing.T, r routeStepRun) string { + t.Helper() + for _, line := range strings.Split(r.output, "\n") { + if v, ok := strings.CutPrefix(line, "stage="); ok { + return v + } + } + t.Fatalf("no stage= line in GITHUB_OUTPUT:\n%s", r.output) + return "" +} + +// Events the bash router decides without calling the GitHub API. +var ( + celRouteReviewLabel = map[string]string{ + "EVENT_NAME": "pull_request_target", "EVENT_ACTION": "labeled", + "TRIGGERING_LABEL": "ready-for-review", "PR_USER_LOGIN": "someone", + } + celRouteOtherLabel = map[string]string{ + "EVENT_NAME": "pull_request_target", "EVENT_ACTION": "labeled", + "TRIGGERING_LABEL": "documentation", "PR_USER_LOGIN": "someone", + } + celRouteClosed = map[string]string{ + "EVENT_NAME": "pull_request_target", "EVENT_ACTION": "closed", + "PR_USER_LOGIN": "someone", + } +) + +func celEnv(mode, outcome, decision string) map[string]string { + return map[string]string{ + "CEL_REVIEW_MODE": mode, + "CEL_REVIEW_OUTCOME": outcome, + "CEL_REVIEW_DECISION": decision, + "CEL_REVIEW_REASON": "test reason", + "CEL_REVIEW_HARNESS": "agents@abc", + } +} + +// TestDetermineStage_CELReviewRouteOffIsNoOp checks that with the variable +// off or unset the step's output, log and summary are byte-for-byte the same +// as with no CEL env at all, whatever the CEL step outputs would say. +func TestDetermineStage_CELReviewRouteOffIsNoOp(t *testing.T) { + for name, event := range map[string]map[string]string{ + "review label": celRouteReviewLabel, + "other label": celRouteOtherLabel, + "closed": celRouteClosed, + } { + t.Run(name, func(t *testing.T) { + baseline := runDetermineStage(t, event, nil) + for _, mode := range []string{"", "off"} { + for _, decision := range []string{"run", "skip", "bash"} { + got := runDetermineStage(t, event, celEnv(mode, "success", decision)) + assert.Equal(t, baseline, got, "mode=%q decision=%s", mode, decision) + } + } + }) + } +} + +func TestDetermineStage_CELReviewRoute(t *testing.T) { + cases := []struct { + name string + event map[string]string + cel map[string]string + wantStage string + wantLog string + wantSummary string + }{ + { + name: "on: run sets review where bash chose nothing", + event: celRouteOtherLabel, cel: celEnv("on", "success", "run"), + wantStage: "review", wantSummary: "review_route=cel", + }, + { + name: "on: skip clears a bash review", + event: celRouteReviewLabel, cel: celEnv("on", "success", "skip"), + wantStage: "", wantSummary: "review_route=cel", + }, + { + name: "on: bash decision keeps the bash review", + event: celRouteReviewLabel, cel: celEnv("on", "success", "bash"), + wantStage: "review", wantSummary: "review_route=bash", + }, + { + name: "on: bash decision keeps no stage", + event: celRouteOtherLabel, cel: celEnv("on", "success", "bash"), + wantStage: "", wantSummary: "review_route=bash", + }, + { + name: "on: another bash stage is never replaced", + event: celRouteClosed, cel: celEnv("on", "success", "run"), + wantStage: "retro", wantLog: "keeping bash stage 'retro'", + }, + { + name: "on: a failed CEL step keeps the bash stage and reports an error", + event: celRouteReviewLabel, cel: celEnv("on", "failure", ""), + wantStage: "review", wantLog: "::error::CEL review route failed", + }, + { + name: "on: a skipped CEL step keeps the bash stage", + event: celRouteReviewLabel, cel: celEnv("on", "skipped", ""), + wantStage: "review", + }, + { + name: "shadow: mismatch is logged and the bash stage kept", + event: celRouteReviewLabel, cel: celEnv("shadow", "success", "skip"), + wantStage: "review", wantLog: "::warning::CEL review route mismatch: bash=review cel=skip", + wantSummary: "CEL review route (shadow): bash=review cel=skip", + }, + { + name: "shadow: agreement logs no mismatch", + event: celRouteReviewLabel, cel: celEnv("shadow", "success", "run"), + wantStage: "review", wantLog: "::notice::CEL review route (shadow): bash=review cel=run", + }, + { + name: "shadow: a failed CEL step only warns", + event: celRouteOtherLabel, cel: celEnv("shadow", "failure", ""), + wantStage: "", wantLog: "::warning::CEL review route (shadow) failed", + }, + { + name: "unknown mode warns and keeps bash", + event: celRouteOtherLabel, cel: celEnv("yes", "success", "run"), + wantStage: "", wantLog: "is not off, shadow or on", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := runDetermineStage(t, tc.event, tc.cel) + assert.Equal(t, tc.wantStage, stageOf(t, got)) + if tc.wantLog != "" { + assert.Contains(t, got.stdout, tc.wantLog) + } + if tc.wantSummary != "" { + assert.Contains(t, got.summary, tc.wantSummary) + } + if strings.Contains(tc.name, "agreement") { + assert.NotContains(t, got.stdout, "mismatch") + } + }) + } +} + +// TestCELReviewRouteStepsGatedOnVariable checks that every CEL review route +// step in the route job is skipped unless FULLSEND_CEL_ROUTING_REVIEW is +// shadow or on: the first step carries the variable check and the rest +// depend on its outcome. +func TestCELReviewRouteStepsGatedOnVariable(t *testing.T) { + content, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "reusable-dispatch.yml")) + require.NoError(t, err) + var wf struct { + Jobs map[string]struct { + Steps []struct { + Name string `yaml:"name"` + ID string `yaml:"id"` + If string `yaml:"if"` + } `yaml:"steps"` + } `yaml:"jobs"` + } + require.NoError(t, yaml.Unmarshal(content, &wf)) + + seen := 0 + for _, step := range wf.Jobs["route"].Steps { + if !strings.Contains(step.Name, "CEL review route") { + continue + } + seen++ + if step.ID == "cel-config" { + assert.Contains(t, step.If, "vars.FULLSEND_CEL_ROUTING_REVIEW == 'shadow'") + assert.Contains(t, step.If, "vars.FULLSEND_CEL_ROUTING_REVIEW == 'on'") + continue + } + assert.True(t, strings.HasPrefix(step.If, "steps.cel-config.outcome == 'success'"), + "step %q must be gated on the cel-config step, got if: %q", step.Name, step.If) + } + assert.GreaterOrEqual(t, seen, 3, "expected the CEL review route steps in the route job") +} + +// TestEvaluateCELReviewRouteStep runs the "Evaluate CEL review route" script +// against a stub fullsend binary and checks the step outputs it writes. +func TestEvaluateCELReviewRouteStep(t *testing.T) { + script := extractReusableDispatchStepScript(t, "route", "Evaluate CEL review route") + cases := []struct { + name string + cliOutput string + cliExit int + wantErr bool + wantOutput string + }{ + { + name: "decision is written to the step outputs", + cliOutput: `{"agent":"review","decision":"run","reason":"trigger matched","harness":"agents@abc"}`, + wantOutput: "decision=run\nreason=trigger matched\nharness=agents@abc\n", + }, + { + name: "missing harness is written empty", + cliOutput: `{"agent":"review","decision":"bash","reason":"resolved harness has no trigger"}`, + wantOutput: "decision=bash\nreason=resolved harness has no trigger\nharness=\n", + }, + {name: "unknown decision fails the step", cliOutput: `{"decision":"maybe"}`, wantErr: true}, + {name: "CLI failure fails the step", cliExit: 1, wantErr: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "bin") + require.NoError(t, os.MkdirAll(bin, 0o755)) + stub := "#!/bin/sh\nprintf '%s\\n' '" + tc.cliOutput + "'\nexit " + map[bool]string{true: "1", false: "0"}[tc.cliExit != 0] + "\n" + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte(stub), 0o755)) + outPath := filepath.Join(dir, "output") + require.NoError(t, os.WriteFile(outPath, nil, 0o644)) + + cmd := exec.Command("bash", "-c", script) + cmd.Dir = dir + cmd.Env = []string{ + "PATH=" + bin + ":" + os.Getenv("PATH"), + "GITHUB_OUTPUT=" + outPath, + "EVENT_ACTION=opened", + } + out, err := cmd.CombinedOutput() + if tc.wantErr { + require.Error(t, err, "step should fail:\n%s", out) + return + } + require.NoError(t, err, "step failed:\n%s", out) + got, err := os.ReadFile(outPath) + require.NoError(t, err) + assert.Equal(t, tc.wantOutput, string(got)) + }) + } +} diff --git a/pkg/behaviourtest/steps/cleanup.go b/pkg/behaviourtest/steps/cleanup.go index 6513393252..7f93b28045 100644 --- a/pkg/behaviourtest/steps/cleanup.go +++ b/pkg/behaviourtest/steps/cleanup.go @@ -130,6 +130,16 @@ func CleanupScenario(w *world.World) { worldLogf(w, "behaviour cleanup: delete inference gateway api-key secret: %v", err) } + // --- Repository variable cleanup --- + // Restore the variables a scenario set (for example + // FULLSEND_CEL_ROUTING_REVIEW) so the slot's next scenario routes with + // the install defaults. + if err := guardedCleanupRetry(w, "restore repository variables", func() error { + return RestoreRepoVariables(w) + }); err != nil { + worldLogf(w, "behaviour cleanup: restore repository variables: %v", err) + } + // --- Issue / PR cleanup --- if w.IssueNumber > 0 { desc := fmt.Sprintf("close issue #%d", w.IssueNumber) diff --git a/pkg/behaviourtest/steps/registry.go b/pkg/behaviourtest/steps/registry.go index 3761a5d615..4bcba6fc23 100644 --- a/pkg/behaviourtest/steps/registry.go +++ b/pkg/behaviourtest/steps/registry.go @@ -25,4 +25,5 @@ func Register(sc *godog.ScenarioContext) { registerMintProbeSteps(sc) registerMintStatusSteps(sc) registerBotRoleProbeSteps(sc) + registerRepoVariableSteps(sc) } diff --git a/pkg/behaviourtest/steps/repo_variable.go b/pkg/behaviourtest/steps/repo_variable.go new file mode 100644 index 0000000000..50088c4749 --- /dev/null +++ b/pkg/behaviourtest/steps/repo_variable.go @@ -0,0 +1,90 @@ +package steps + +import ( + "context" + "fmt" + "sort" + + "github.com/cucumber/godog" + + "github.com/fullsend-ai/fullsend/internal/forge" + scmgh "github.com/fullsend-ai/fullsend/pkg/behaviourtest/drivers/scm/github" + "github.com/fullsend-ai/fullsend/pkg/behaviourtest/world" +) + +func registerRepoVariableSteps(sc *godog.ScenarioContext) { + sc.Step(`^the repository variable "([A-Z][A-Z0-9_]*)" is "([^"]*)"$`, func(ctx context.Context, name, value string) (context.Context, error) { + return ctx, givenRepoVariable(world.FromContext(ctx), name, value) + }) +} + +// repoVariableClient returns the forge client of the GitHub SCM driver. +func repoVariableClient(w *world.World) (forge.Client, error) { + ghDriver, ok := w.SCM.(*scmgh.Driver) + if !ok { + return nil, fmt.Errorf("repository variable steps require the GitHub SCM driver") + } + return ghDriver.Client, nil +} + +// givenRepoVariable sets a repository variable on the enrolled repo. The +// first time a scenario sets a name, the pre-scenario value (or its absence) +// is recorded so RestoreRepoVariables can put it back during cleanup. +func givenRepoVariable(w *world.World, name, value string) error { + if w.Org == "" || w.RepoName == "" { + return fmt.Errorf("no repo configured; call 'Given the enrolled test repository' before setting repository variables") + } + client, err := repoVariableClient(w) + if err != nil { + return err + } + if _, recorded := w.RepoVariablesOriginal[name]; !recorded { + original, exists, err := client.GetRepoVariable(context.Background(), w.Org, w.RepoName, name) + if err != nil { + return fmt.Errorf("reading repository variable %s: %w", name, err) + } + if w.RepoVariablesOriginal == nil { + w.RepoVariablesOriginal = map[string]*string{} + } + if exists { + w.RepoVariablesOriginal[name] = &original + } else { + w.RepoVariablesOriginal[name] = nil + } + } + if err := client.CreateOrUpdateRepoVariable(mutationCtx(w), w.Org, w.RepoName, name, value); err != nil { + return fmt.Errorf("setting repository variable %s: %w", name, err) + } + return nil +} + +// RestoreRepoVariables puts back every repository variable a scenario set: +// the recorded value, or a delete when the variable did not exist. A name is +// forgotten only once it is restored, so a failed restore is retried. +func RestoreRepoVariables(w *world.World) error { + if len(w.RepoVariablesOriginal) == 0 { + return nil + } + client, err := repoVariableClient(w) + if err != nil { + return err + } + names := make([]string, 0, len(w.RepoVariablesOriginal)) + for name := range w.RepoVariablesOriginal { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + original := w.RepoVariablesOriginal[name] + if original == nil { + err = client.DeleteRepoVariable(mutationCtx(w), w.Org, w.RepoName, name) + if err != nil && !forge.IsNotFound(err) { + return fmt.Errorf("deleting repository variable %s: %w", name, err) + } + } else if err := client.CreateOrUpdateRepoVariable(mutationCtx(w), w.Org, w.RepoName, name, *original); err != nil { + return fmt.Errorf("restoring repository variable %s: %w", name, err) + } + delete(w.RepoVariablesOriginal, name) + } + return nil +} diff --git a/pkg/behaviourtest/steps/repo_variable_test.go b/pkg/behaviourtest/steps/repo_variable_test.go new file mode 100644 index 0000000000..a8af0d09ee --- /dev/null +++ b/pkg/behaviourtest/steps/repo_variable_test.go @@ -0,0 +1,73 @@ +package steps + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/forge" + scmgh "github.com/fullsend-ai/fullsend/pkg/behaviourtest/drivers/scm/github" + "github.com/fullsend-ai/fullsend/pkg/behaviourtest/world" +) + +const celVar = "FULLSEND_CEL_ROUTING_REVIEW" + +func TestGivenRepoVariable_SetsAndRestoresAbsentVariable(t *testing.T) { + fc := forge.NewFakeClient() + w := &world.World{Org: "org", RepoName: "repo", SCM: scmgh.New(fc)} + + require.NoError(t, givenRepoVariable(w, celVar, "shadow")) + require.NoError(t, givenRepoVariable(w, celVar, "on")) + assert.Equal(t, "on", fc.VariableValues["org/repo/"+celVar]) + + require.NoError(t, RestoreRepoVariables(w)) + _, exists := fc.VariableValues["org/repo/"+celVar] + assert.False(t, exists, "a variable that did not exist is deleted") + assert.Empty(t, w.RepoVariablesOriginal) +} + +func TestGivenRepoVariable_RestoresPreviousValue(t *testing.T) { + fc := forge.NewFakeClient() + fc.VariableValues = map[string]string{"org/repo/" + celVar: "off"} + w := &world.World{Org: "org", RepoName: "repo", SCM: scmgh.New(fc)} + + require.NoError(t, givenRepoVariable(w, celVar, "on")) + require.NoError(t, RestoreRepoVariables(w)) + assert.Equal(t, "off", fc.VariableValues["org/repo/"+celVar]) +} + +func TestGivenRepoVariable_RequiresRepo(t *testing.T) { + err := givenRepoVariable(&world.World{}, celVar, "on") + require.ErrorContains(t, err, "enrolled test repository") +} + +func TestGivenRepoVariable_ReadErrorDoesNotSet(t *testing.T) { + fc := forge.NewFakeClient() + fc.Errors = map[string]error{"GetRepoVariable": errors.New("boom")} + w := &world.World{Org: "org", RepoName: "repo", SCM: scmgh.New(fc)} + + require.ErrorContains(t, givenRepoVariable(w, celVar, "on"), "boom") + assert.Empty(t, fc.VariableValues) + assert.Empty(t, w.RepoVariablesOriginal) +} + +func TestRestoreRepoVariables_NotFoundIsFine(t *testing.T) { + fc := forge.NewFakeClient() + fc.Errors = map[string]error{"DeleteRepoVariable": fmt.Errorf("%w: variable", forge.ErrNotFound)} + w := &world.World{Org: "org", RepoName: "repo", SCM: scmgh.New(fc), + RepoVariablesOriginal: map[string]*string{celVar: nil}} + require.NoError(t, RestoreRepoVariables(w)) + assert.Empty(t, w.RepoVariablesOriginal) +} + +func TestRestoreRepoVariables_ErrorKeepsEntryForRetry(t *testing.T) { + fc := forge.NewFakeClient() + fc.Errors = map[string]error{"DeleteRepoVariable": errors.New("boom")} + w := &world.World{Org: "org", RepoName: "repo", SCM: scmgh.New(fc), + RepoVariablesOriginal: map[string]*string{celVar: nil}} + require.ErrorContains(t, RestoreRepoVariables(w), "boom") + assert.Contains(t, w.RepoVariablesOriginal, celVar, "a failed restore is retried by cleanupRetry") +} diff --git a/pkg/behaviourtest/suite/init.go b/pkg/behaviourtest/suite/init.go index 834ba0d344..4301d144e3 100644 --- a/pkg/behaviourtest/suite/init.go +++ b/pkg/behaviourtest/suite/init.go @@ -188,6 +188,7 @@ func resetScenarioWorld(w *world.World) { w.GatewayConfigOverridden = false w.GatewayConfigOriginal = nil w.GatewayAPIKeySecretSet = false + w.RepoVariablesOriginal = nil w.OwnersAuthActivated = false w.JiraMockServer = nil w.JiraMockState = nil diff --git a/pkg/behaviourtest/world/world.go b/pkg/behaviourtest/world/world.go index 375d7c1e22..3e52cbdfc0 100644 --- a/pkg/behaviourtest/world/world.go +++ b/pkg/behaviourtest/world/world.go @@ -224,6 +224,11 @@ type World struct { // CleanupScenario deletes it before the leased repo is deallocated. GatewayAPIKeySecretSet bool + // RepoVariablesOriginal maps each repository variable a scenario set + // to its pre-scenario value (nil when it did not exist). + // CleanupScenario restores them before the leased repo is deallocated. + RepoVariablesOriginal map[string]*string + // OwnersAuthActivated records whether this scenario committed an // OWNERS file and/or added owners_file to the authorization providers in config.yaml. // CleanupScenario removes both.