diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index 40f990727e..f50f5b4dff 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -135,6 +135,7 @@ jobs: allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' }} sparse-checkout: | .fullsend/config.yaml + .fullsend/config.base.yaml /OWNERS /OWNERS_ALIASES sparse-checkout-cone-mode: false @@ -496,14 +497,45 @@ jobs: if: steps.route.outputs.stage != '' run: | set -euo pipefail + # Mirrors internal/config's IsKillSwitchActive(): if + # config.yaml sets kill_switch at all, that value is final + # and config.base.yaml is ignored; config.base.yaml is only + # consulted when config.yaml is silent on the key. + # -o=json normalizes every YAML null spelling (bare key, ~, + # Null, NULL) to the literal "null", and the true/false + # case variants (True, FALSE, ...) to lowercase. It does not + # normalize the YAML 1.1 word booleans yq treats as plain + # strings (yes/no/on/off print as quoted JSON strings, e.g. + # "yes"), so yes is matched explicitly below, where + # go-yaml's lenient *bool decoding also treats it as active. + # on/off and the single-letter y/n forms are deliberately + # not matched. -o=json also keeps surrounding quotes on any + # scalar that was itself quoted in the source YAML (e.g. + # kill_switch: "true" prints as the JSON string "true", not + # the JSON boolean true), so those quotes are stripped below + # before comparing, matching go-yaml's lenient *bool + # decoding of a quoted "true"/"yes" scalar. + KILL_SWITCH="false" + OVERLAY_KS="null" if [[ -f .fullsend/config.yaml ]]; then - KILL_SWITCH=$(yq '.kill_switch // false' .fullsend/config.yaml) - if [[ "$KILL_SWITCH" == "true" ]]; then - echo "::error::Kill switch is active — all agent dispatch halted" - echo "::error::Set kill_switch: false in .fullsend/config.yaml to resume" - exit 1 + OVERLAY_KS=$(yq -o=json '.kill_switch' .fullsend/config.yaml) + fi + if [[ "$OVERLAY_KS" != "null" ]]; then + KILL_SWITCH="$OVERLAY_KS" + elif [[ -f .fullsend/config.base.yaml ]]; then + BASE_KS=$(yq -o=json '.kill_switch' .fullsend/config.base.yaml) + if [[ "$BASE_KS" != "null" ]]; then + KILL_SWITCH="$BASE_KS" fi fi + KILL_SWITCH="${KILL_SWITCH,,}" + KILL_SWITCH="${KILL_SWITCH#\"}" + KILL_SWITCH="${KILL_SWITCH%\"}" + if [[ "$KILL_SWITCH" == "true" || "$KILL_SWITCH" == "yes" ]]; then + echo "::error::Kill switch is active — all agent dispatch halted" + echo "::error::Set kill_switch: false in .fullsend/config.yaml or .fullsend/config.base.yaml to resume" + exit 1 + fi - name: Validate agents config if: steps.route.outputs.stage != '' diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index d9046dd0b3..8b577b8e28 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -81,6 +81,7 @@ These fields live on `perRepoConfig` in `internal/config/config.go`. Unset means | `status_notifications` | Start and completion comments and reactions | Overlay, base, compiled unset | Whole object replaces the parent when set | Status posting | Already layered | Yes, when a fleet wants one notification policy. | | `models.aliases` | Remap of `opus`, `sonnet`, `haiku`, `fable` | Overlay, base, compiled alias table | Per-key merge, then the compiled table | Model resolution | Already layered | Yes. Fleet model pins belong here. | | `inference.provider` | Inference backend id | Overlay, base, compiled `vertex` | Overlay, then base, then `vertex`. No workflow variable found | Accessor at install and run setup | Already layered | Yes. | +| `kill_switch` | Stop all agent dispatch | Overlay, base, compiled `false` | Overlay, then base, then `false`. Both direct reads — GitHub's "Check kill switch" bash step and GitLab's `run-agent-job.sh` — now consult `config.base.yaml` when `config.yaml` is silent on the key, matching the Go accessor | `internal/harnessdispatch`, `reusable-dispatch.yml`, and GitLab's `run-agent-job.sh` | Already layered | Yes. A central stop belongs in the base file. | `authorization` (extra permission sources, today `owners_file`) is overlay-only by design, not an accessor gap: a base-file value under this @@ -97,7 +98,6 @@ The Go accessor layers these. The bash steps in `.github/workflows/reusable-disp | Setting | Controls | Set from | Wins today | Read by | Decision | Base file? | |---|---|---|---|---|---|---| -| `kill_switch` | Stop all agent dispatch | Overlay, base, compiled `false` | Go accessor: overlay, then base, then `false`. Bash "Check kill switch": `yq '.kill_switch'` on `config.yaml` only. A missing file does not halt dispatch | `internal/harnessdispatch` and `reusable-dispatch.yml` | Layer the direct read so a base-file `true` halts dispatch | Yes. A central stop belongs in the base file. | | `roles` | Which agent roles are enabled | Overlay, base, compiled default role list | Go accessor: replace-if-set, so an explicit empty `roles: []` denies every role. Bash "Check role is enabled": `yq '.roles[]'` on `config.yaml` only, piped through `\|\| echo ""`. An omitted key, a missing file, an explicit `roles: []`, or any `yq` error all leave `$ROLES` empty, and the script only skips the stage when `$ROLES` is non-empty — so all four cases fail open and let the stage run, the opposite of the Go accessor's deny-all | Go accessor and `reusable-dispatch.yml` | Layer the direct read, and make the bash script fail closed on an explicit empty list, not just add the base file | Yes, for the shared role set. An overlay list replaces it. | | `agents` | Registered agents and per-agent `runtime`, `model`, `effort`, `subagents` | Overlay, base, compiled none | Go accessor: keyed merge by agent name. Bash validates the shape of `config.yaml` only | Go run path and `reusable-dispatch.yml` | Layer the direct read for enablement and role checks. Per-agent runtime, model, and effort still lose to flags and environment variables; those rows are below | Yes, for the shared agent baseline. | diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index 05a210acad..e258a6a048 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -409,7 +409,7 @@ The `fork-dispatch.feature` file defines the canonical fork-PR behaviour contrac | CEL `is_fork` exclusion (`!event.state.change_proposal.is_fork`) | Empty matrix, exit 0 | Harness with `is_fork` guard in positive scenario; assert agent did not run | | Fork PR matches CEL `trigger` on `pull_request_target`; unauthorized actor ([ADR 0054](../../ADRs/0054-require-authorization-on-all-agent-dispatch-paths.md)) | Empty matrix, exit 0 — no agent run | `platform/trigger-auth.feature`. The outsider opens a PR from its own fork; assert the harness dispatch completed with an empty matrix, the agent did not run, and it was dispatched exactly 0 times, then a label as the positive control | -**Kill switch vs disabled harness:** These are distinct mechanisms. The **kill switch** (`kill_switch: true` in `config.yaml`) is a global emergency stop that blocks *all* harness dispatch for the repo — tested in its own scenario because no positive harness can run alongside it. A **disabled harness** (`enabled: false` per agent entry) only prevents that single agent from running — tested as a piggyback negative assertion in the positive-path scenario. +**Kill switch vs disabled harness:** These are distinct mechanisms. The **kill switch** (`kill_switch: true`, settable in either `config.yaml` or `config.base.yaml`) is a global emergency stop that blocks *all* harness dispatch for the repo — tested in its own scenario because no positive harness can run alongside it. A **disabled harness** (`enabled: false` per agent entry) only prevents that single agent from running — tested as a piggyback negative assertion in the positive-path scenario. **Consolidation pattern:** To conserve parallel execution slots, add negative-path harnesses (disabled agent, CEL exclusion) alongside the positive-path harness in a single scenario rather than creating separate scenarios. The positive harness wait acts as the settle window for negative assertions (piggyback pattern — see `negativeSettleDuration` in `dispatch.go`). The kill switch scenario cannot be consolidated because it blocks all harnesses. @@ -424,7 +424,9 @@ The `fork-dispatch.feature` file defines the canonical fork-PR behaviour contrac **`the harness dispatch completes with an empty matrix`** — Waits for the harness workflow run(s) created since the last trigger step, then requires every run that was not cancelled to have completed with its `Harness dispatch` job succeeded and no `Harness run ()` job scheduled. It fails if the dispatch job failed or an agent was scheduled, and keeps waiting while no run exists yet or a run is still in progress, so a denial is never inferred from a missing or failed run. Pair it with `agent did not run` and `dispatched exactly 0 times` for denial scenarios. It needs a CI driver that implements the optional `ci.EmptyMatrixWaiter`; the GitHub Actions driver does. -**`the kill switch is active`** — Sets `kill_switch: true` in the repo's `config.yaml`, causing `Dispatch` to return an empty matrix for *all* agents. Use this step in a dedicated scenario where no harness should run. Because the kill switch blocks everything, it cannot share a scenario with a positive-path harness. +**`the kill switch is active`** — Sets `kill_switch: true` in the repo's `config.yaml` (the overlay), causing `Dispatch` to return an empty matrix for *all* agents. Use this step in a dedicated scenario where no harness should run. Because the kill switch blocks everything, it cannot share a scenario with a positive-path harness. + +**`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. ## Forge operational constraints diff --git a/e2e/behaviour/features/dispatch/fork-dispatch.feature b/e2e/behaviour/features/dispatch/fork-dispatch.feature index cd2914a969..7d3008ce2c 100644 --- a/e2e/behaviour/features/dispatch/fork-dispatch.feature +++ b/e2e/behaviour/features/dispatch/fork-dispatch.feature @@ -89,6 +89,25 @@ Feature: Fork PR dispatch And the fork pull request is labeled "ready-for-fork-killswitch" Then the harness "fork-pr-killswitch" agent did not run + Scenario: Fork PR kill switch in config.base.yaml blocks all harnesses + Given a custom harness "fork-pr-killswitch-base" with: + """ + agent: agents/triage.md + role: triage + slug: fullsend-ai-fork-pr-killswitch-base + model: opus + image: ghcr.io/fullsend-ai/fullsend-sandbox:latest + policy: policies/base.yaml + trigger: | + event.entity.kind == "change_proposal" + && event.transition.kind == "label_changed" + && event.transition.label.name == "ready-for-fork-killswitch-base" + """ + And the kill switch is active in config.base.yaml + When a fork pull request is opened + And the fork pull request is labeled "ready-for-fork-killswitch-base" + Then the harness "fork-pr-killswitch-base" agent did not run + Scenario: Fork PR sync + label dispatches harness Given a custom harness "fork-pr-sync" with: """ diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh index 64fd345d0c..63ec8f4f15 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-agent-job.sh @@ -310,16 +310,41 @@ if ! git fetch origin "${FULLSEND_PINNED_REF}" --depth=1; then fi DEFAULT_BRANCH_SHA=$(git rev-parse FETCH_HEAD) CONFIG_YAML=$(git show "${DEFAULT_BRANCH_SHA}:.fullsend/config.yaml" 2>/dev/null || echo "") - -# Kill switch — halt all agent dispatch when active -if [ -n "${CONFIG_YAML}" ]; then - if ! KILL_SWITCH=$(echo "${CONFIG_YAML}" | python3 -c "import sys,yaml; print('true' if str((yaml.safe_load(sys.stdin) or {}).get('kill_switch', False)).lower() in ('true','yes','1','on') else 'false')"); then - echo "WARNING: invalid .fullsend/config.yaml — treating as unconfigured (no kill-switch)" +CONFIG_BASE_YAML=$(git show "${DEFAULT_BRANCH_SHA}:.fullsend/config.base.yaml" 2>/dev/null || echo "") + +# Kill switch — halt all agent dispatch when active. Mirrors +# internal/config's IsKillSwitchActive(): if config.yaml sets +# kill_switch at all, that value is final and config.base.yaml is +# ignored; config.base.yaml is only consulted when config.yaml is +# silent on the key. +if [ -n "${CONFIG_YAML}" ] || [ -n "${CONFIG_BASE_YAML}" ]; then + if ! KILL_SWITCH=$(OVERLAY_YAML="${CONFIG_YAML}" BASE_YAML="${CONFIG_BASE_YAML}" python3 -c " +import os, sys, yaml + +def load(text): + return (yaml.safe_load(text) or {}) if text else {} + +# Resolve the overlay first, and only parse the base file when the +# overlay is silent on kill_switch. This keeps a malformed base.yaml +# from ever being able to suppress an explicit overlay value (it is +# never parsed in that case), and treats overlay 'kill_switch: null' +# (or a bare 'kill_switch:') the same as a fully omitted key — both +# decode to None, matching Go's *bool nil-falls-through-to-parent +# semantics — rather than as an explicit false that shadows the base. +overlay = load(os.environ.get('OVERLAY_YAML', '')) +active = overlay.get('kill_switch') +if active is None: + base = load(os.environ.get('BASE_YAML', '')) + active = base.get('kill_switch') + +print('true' if str(active).lower() in ('true', 'yes', '1', 'on') else 'false') +"); then + echo "WARNING: invalid .fullsend/config.yaml or .fullsend/config.base.yaml — treating as unconfigured (no kill-switch)" KILL_SWITCH="false" fi if [ "${KILL_SWITCH}" = "true" ]; then echo "ERROR: Kill switch is active — all agent dispatch halted" >&2 - echo "Set kill_switch: false in .fullsend/config.yaml to resume" >&2 + echo "Set kill_switch: false in .fullsend/config.yaml or .fullsend/config.base.yaml to resume" >&2 exit 1 fi fi diff --git a/internal/scaffold/github_kill_switch_test.go b/internal/scaffold/github_kill_switch_test.go new file mode 100644 index 0000000000..46c8e98c31 --- /dev/null +++ b/internal/scaffold/github_kill_switch_test.go @@ -0,0 +1,228 @@ +package scaffold + +import ( + "os" + "os/exec" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" +) + +// ghWorkflowStep and friends mirror just enough of +// .github/workflows/reusable-dispatch.yml's shape to extract a single +// step's `run:` script for isolated execution. Unknown fields (if, +// env, uses, with, permissions, outputs, ...) are ignored by +// yaml.Unmarshal. +type ghWorkflowStep struct { + Name string `yaml:"name"` + Run string `yaml:"run"` +} + +type ghWorkflowJob struct { + Steps []ghWorkflowStep `yaml:"steps"` +} + +type ghWorkflowFile struct { + Jobs map[string]ghWorkflowJob `yaml:"jobs"` +} + +// extractReusableDispatchStepScript reads reusable-dispatch.yml from +// the repo root and returns the `run:` script text of the named step +// in the named job, so it can be executed in isolation against +// fixture .fullsend/config.yaml files without spinning up a real +// Actions run. +func extractReusableDispatchStepScript(t *testing.T, jobName, stepName string) string { + t.Helper() + path := filepath.Join("..", "..", ".github", "workflows", "reusable-dispatch.yml") + content, err := os.ReadFile(path) + require.NoError(t, err) + + var wf ghWorkflowFile + require.NoError(t, yaml.Unmarshal(content, &wf)) + + job, ok := wf.Jobs[jobName] + require.True(t, ok, "job %q not found in reusable-dispatch.yml", jobName) + for _, step := range job.Steps { + if step.Name == stepName { + require.NotEmpty(t, step.Run, "step %q has no run script", stepName) + return step.Run + } + } + t.Fatalf("step %q not found in job %q", stepName, jobName) + return "" +} + +func TestCheckKillSwitchStep_ConsultsConfigBaseYAML(t *testing.T) { + if _, err := exec.LookPath("yq"); err != nil { + t.Skip("yq not found in PATH") + } + + script := extractReusableDispatchStepScript(t, "route", "Check kill switch") + + cases := []struct { + name string + configYAML string + configBaseYAML string + wantHalt bool + }{ + { + name: "overlay true halts dispatch", + configYAML: "kill_switch: true\n", + wantHalt: true, + }, + { + name: "overlay silent, base active halts dispatch", + configBaseYAML: "kill_switch: true\n", + wantHalt: true, + }, + { + name: "overlay explicit false overrides base active", + configYAML: "kill_switch: false\n", + configBaseYAML: "kill_switch: true\n", + wantHalt: false, + }, + { + name: "neither file sets kill_switch", + wantHalt: false, + }, + { + name: "overlay True (capital) halts dispatch", + configYAML: "kill_switch: True\n", + wantHalt: true, + }, + { + name: "base True (capital) halts dispatch when overlay is silent", + configBaseYAML: "kill_switch: True\n", + wantHalt: true, + }, + { + name: "overlay kill_switch: null falls through to base", + configYAML: "kill_switch: null\n", + configBaseYAML: "kill_switch: true\n", + wantHalt: true, + }, + { + name: "overlay true survives a malformed base file", + configYAML: "kill_switch: true\n", + configBaseYAML: "kill_switch: [unterminated\n", + wantHalt: true, + }, + { + name: "overlay bare kill_switch: falls through to base", + configYAML: "kill_switch:\n", + configBaseYAML: "kill_switch: true\n", + wantHalt: true, + }, + { + name: "overlay kill_switch: ~ falls through to base", + configYAML: "kill_switch: ~\n", + configBaseYAML: "kill_switch: true\n", + wantHalt: true, + }, + { + name: "overlay kill_switch: Null falls through to base", + configYAML: "kill_switch: Null\n", + configBaseYAML: "kill_switch: true\n", + wantHalt: true, + }, + { + name: "overlay present but silent on kill_switch falls through to base", + configYAML: "# no kill_switch key here\n", + configBaseYAML: "kill_switch: true\n", + wantHalt: true, + }, + { + name: "overlay yes (bare) halts dispatch", + configYAML: "kill_switch: yes\n", + wantHalt: true, + }, + { + name: "overlay Yes (capital) halts dispatch", + configYAML: "kill_switch: Yes\n", + wantHalt: true, + }, + { + name: `overlay "yes" (quoted) halts dispatch`, + configYAML: "kill_switch: \"yes\"\n", + wantHalt: true, + }, + { + name: "base yes halts dispatch when overlay is silent", + configBaseYAML: "kill_switch: yes\n", + wantHalt: true, + }, + { + name: "overlay no does not halt dispatch", + configYAML: "kill_switch: no\n", + wantHalt: false, + }, + { + name: `overlay "no" (quoted) does not halt dispatch`, + configYAML: "kill_switch: \"no\"\n", + wantHalt: false, + }, + { + name: "overlay on does not halt dispatch (on/off intentionally unsupported)", + configYAML: "kill_switch: on\n", + wantHalt: false, + }, + { + name: "overlay off does not halt dispatch (on/off intentionally unsupported)", + configYAML: "kill_switch: off\n", + wantHalt: false, + }, + { + name: "overlay y does not halt dispatch (y/n intentionally unsupported)", + configYAML: "kill_switch: y\n", + wantHalt: false, + }, + { + name: "overlay n does not halt dispatch (y/n intentionally unsupported)", + configYAML: "kill_switch: n\n", + wantHalt: false, + }, + { + name: `overlay kill_switch: "true" (double-quoted) halts dispatch`, + configYAML: "kill_switch: \"true\"\n", + wantHalt: true, + }, + { + name: "overlay kill_switch: 'true' (single-quoted) halts dispatch", + configYAML: "kill_switch: 'true'\n", + wantHalt: true, + }, + { + name: `base kill_switch: "true" (double-quoted) halts dispatch when overlay is silent`, + configBaseYAML: "kill_switch: \"true\"\n", + wantHalt: true, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(root, ".fullsend"), 0o755)) + if tc.configYAML != "" { + require.NoError(t, os.WriteFile(filepath.Join(root, ".fullsend", "config.yaml"), []byte(tc.configYAML), 0o644)) + } + if tc.configBaseYAML != "" { + require.NoError(t, os.WriteFile(filepath.Join(root, ".fullsend", "config.base.yaml"), []byte(tc.configBaseYAML), 0o644)) + } + + scriptPath := filepath.Join(root, "check-kill-switch.sh") + require.NoError(t, os.WriteFile(scriptPath, []byte(script), 0o755)) + + cmd := exec.Command("bash", scriptPath) + cmd.Dir = root + out, err := cmd.CombinedOutput() + + if tc.wantHalt { + require.Error(t, err, "stdout/stderr: %s", out) + } else { + require.NoError(t, err, "stdout/stderr: %s", out) + } + }) + } +} diff --git a/internal/scaffold/gitlab_kill_switch_test.go b/internal/scaffold/gitlab_kill_switch_test.go new file mode 100644 index 0000000000..4a2edad695 --- /dev/null +++ b/internal/scaffold/gitlab_kill_switch_test.go @@ -0,0 +1,191 @@ +package scaffold + +import ( + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// setupConfigOrigin is like setupPinnedConfigOrigin but lets the caller +// control the content of .fullsend/config.yaml (the overlay) and +// .fullsend/config.base.yaml (the base) committed to the origin +// remote's main branch independently. Pass "" for either argument to +// omit that file entirely (as opposed to committing it with empty +// content), so tests can exercise the "key/file absent" fallback path +// distinctly from "file present but doesn't set the key". +func setupConfigOrigin(t *testing.T, root, configYAML, configBaseYAML string) { + t.Helper() + upstream := t.TempDir() + initGitRepo(t, upstream) + if configYAML != "" { + require.NoError(t, os.MkdirAll(filepath.Join(upstream, ".fullsend"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(upstream, ".fullsend/config.yaml"), []byte(configYAML), 0o644)) + gitCmd(t, upstream, "add", ".fullsend/config.yaml") + } + if configBaseYAML != "" { + require.NoError(t, os.MkdirAll(filepath.Join(upstream, ".fullsend"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(upstream, ".fullsend/config.base.yaml"), []byte(configBaseYAML), 0o644)) + gitCmd(t, upstream, "add", ".fullsend/config.base.yaml") + } + // A placeholder file guarantees there is always at least one + // tracked file to commit, even in the "neither config file + // exists" case. + require.NoError(t, os.WriteFile(filepath.Join(upstream, "README.md"), []byte("placeholder\n"), 0o644)) + gitCmd(t, upstream, "add", "README.md") + gitCmd(t, upstream, "commit", "-m", "trusted config") + + initGitRepo(t, root) + gitCmd(t, root, "remote", "add", "origin", upstream) +} + +func TestRunAgentJobScript_KillSwitchConsultsConfigBaseYAML(t *testing.T) { + const secret = "test-hmac-secret" + hmacHex := computeDispatchHMAC(secret, "5", "", "", "", "", "", "", "", "test-key", "triage", "") + + cases := []struct { + name string + configYAML string + configBaseYAML string + wantHalt bool + wantOutput string + }{ + { + name: "overlay silent, base active halts dispatch", + configBaseYAML: "kill_switch: true\n", + wantHalt: true, + wantOutput: "Kill switch is active", + }, + { + name: "overlay explicit false overrides base active", + configYAML: "kill_switch: false\n", + configBaseYAML: "kill_switch: true\n", + wantHalt: false, + }, + { + name: "neither file sets kill_switch", + wantHalt: false, + }, + { + name: "malformed overlay logs a warning and falls through", + configYAML: "kill_switch: [unterminated\n", + wantHalt: false, + wantOutput: "WARNING: invalid .fullsend/config.yaml or .fullsend/config.base.yaml — treating as unconfigured", + }, + { + name: "overlay kill_switch: null falls through to base", + configYAML: "kill_switch: null\n", + configBaseYAML: "kill_switch: true\n", + wantHalt: true, + wantOutput: "Kill switch is active", + }, + { + name: "overlay true survives a malformed base file", + configYAML: "kill_switch: true\n", + configBaseYAML: "kill_switch: [unterminated\n", + wantHalt: true, + wantOutput: "Kill switch is active", + }, + { + name: "overlay yes (bare) halts dispatch", + configYAML: "kill_switch: yes\n", + wantHalt: true, + wantOutput: "Kill switch is active", + }, + { + name: `overlay "yes" (quoted) halts dispatch`, + configYAML: "kill_switch: \"yes\"\n", + wantHalt: true, + wantOutput: "Kill switch is active", + }, + { + name: "overlay no does not halt dispatch", + configYAML: "kill_switch: no\n", + wantHalt: false, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") + writeGitLabScript(t, root, gitlabPinCIJobIdentityScriptPath) + writeGitLabScript(t, root, ".gitlab/ci/scripts/select-gitlab-role-token.sh") + script := writeGitLabScript(t, root, gitlabRunAgentJobScriptPath) + + mux := http.NewServeMux() + mux.HandleFunc("/api/v4/job", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(pinJobJSON("42", "100", "main"))) + }) + mux.HandleFunc("/api/v4/user", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":7,"username":"fullsend-bot"}`)) + }) + mux.HandleFunc("/api/v4/projects/", func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + switch { + case strings.Contains(path, "/repository/branches/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"name":"main","protected":true}`)) + case strings.Contains(path, "/pipelines/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":100,"source":"api","user":{"id":7}}`)) + case strings.Contains(path, "/resource_groups/"): + w.WriteHeader(http.StatusOK) + case strings.Contains(path, "/members/all/"): + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"access_level":40}`)) + default: + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`)) + } + }) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + + bin := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte("#!/bin/sh\nexit 0\n"), 0o755)) + + setupConfigOrigin(t, root, tc.configYAML, tc.configBaseYAML) + + cmd := exec.Command("bash", "-c", "set -euo pipefail; . \"$SCRIPT\"") + cmd.Dir = root + cmd.Env = append([]string{ + "SCRIPT=" + script, + "PATH=" + bin + ":" + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=poller-pat", + "FULLSEND_GITLAB_ANALYST_TOKEN=analyst-pat", + "STAGE=triage", + "RESOURCE_KEY=test-key", + "ACTOR_ID=5", + "FULLSEND_DISPATCH_SECRET=" + secret, + "FULLSEND_DISPATCH_HMAC=" + hmacHex, + "CI_PROJECT_PATH=group/project", + "CI_SERVER_URL=https://gitlab.example", + "CI_PIPELINE_URL=https://gitlab.example/group/project/-/pipelines/100", + "CI_PROJECT_ID=1", + }, pinTLSEnv(t, srv)...) + out, err := cmd.CombinedOutput() + + if tc.wantHalt { + require.Error(t, err, "stdout/stderr: %s", out) + } else { + require.NoError(t, err, "stdout/stderr: %s", out) + } + if tc.wantOutput != "" { + assert.Contains(t, string(out), tc.wantOutput) + } + }) + } +} diff --git a/pkg/behaviourtest/steps/cleanup.go b/pkg/behaviourtest/steps/cleanup.go index 888da23332..930239309d 100644 --- a/pkg/behaviourtest/steps/cleanup.go +++ b/pkg/behaviourtest/steps/cleanup.go @@ -64,9 +64,31 @@ func ValidateSlotClean(w *world.World) error { if err != nil { return nil } - cfg, err := config.ParsePerRepoConfigWriter(cfgData) + // config.base.yaml is not part of the standard scaffold and is + // absent on most slots; a missing-file error just means there is + // no base layer to check, not a validation failure. + baseData, err := w.SCM.GetFileContent(context.Background(), + w.Org, w.RepoName, filepath.Join(".fullsend", "config.base.yaml")) if err != nil { - return nil + baseData = nil + } + cfg, err := config.ParsePerRepoConfigWriterLayered(cfgData, baseData) + if err != nil { + // Fall back to an overlay-only parse so the + // overlay is still checked, and flag the malformed base + // itself as stale state worth reporting. + overlayCfg, overlayErr := config.ParsePerRepoConfigWriter(cfgData) + if overlayErr != nil { + return nil + } + stale := []string{fmt.Sprintf("config.base.yaml is malformed: %v", err)} + if overlayCfg.IsKillSwitchActive() { + stale = append(stale, "kill_switch is active") + } + if overlayCfg.IsOwnersFileAuthEnabled() { + stale = append(stale, "owners_file authorization is enabled") + } + return fmt.Errorf("repo slot has stale state from a previous scenario (cleanup likely failed): %s", strings.Join(stale, ", ")) } var stale []string if cfg.IsKillSwitchActive() { @@ -295,6 +317,13 @@ func CleanupScenario(w *world.World) { worldLogf(w, "behaviour cleanup: deactivate kill switch: %v", err) } } + if w.KillSwitchBaseActivated { + if err := cleanupRetry(w.Logf, "deactivate kill switch in config.base.yaml", func() error { + return DeactivateKillSwitchBase(w) + }); err != nil { + worldLogf(w, "behaviour cleanup: deactivate kill switch in config.base.yaml: %v", err) + } + } // --- Runtime override cleanup --- // Restore the install-time runtime so a later scenario on this slot diff --git a/pkg/behaviourtest/steps/cleanup_test.go b/pkg/behaviourtest/steps/cleanup_test.go index b71dd597d7..8cef48b76c 100644 --- a/pkg/behaviourtest/steps/cleanup_test.go +++ b/pkg/behaviourtest/steps/cleanup_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "path/filepath" + "strings" "testing" "time" @@ -521,7 +522,16 @@ type fakeCleanupSCM struct { commits []committedFileRecord fileContent []byte getFileErr error - openPRs []forge.ChangeProposal + // baseFileConfigured, when true, makes GetFileContent answer + // config.base.yaml requests with baseFileContent/baseFileErr + // instead of the config.yaml-oriented fileContent/getFileErr + // above. Tests that don't care about config.base.yaml leave this + // false, so GetFileContent keeps its original path-agnostic + // behavior (returning fileContent/getFileErr for every path). + baseFileConfigured bool + baseFileContent []byte + baseFileErr error + openPRs []forge.ChangeProposal } type committedFileRecord struct { @@ -590,7 +600,10 @@ func (f *fakeCleanupSCM) GetIssue(context.Context, string, string, int) (*forge. return nil, nil } -func (f *fakeCleanupSCM) GetFileContent(context.Context, string, string, string) ([]byte, error) { +func (f *fakeCleanupSCM) GetFileContent(_ context.Context, _, _, path string) ([]byte, error) { + if f.baseFileConfigured && strings.Contains(path, "config.base.yaml") { + return f.baseFileContent, f.baseFileErr + } return f.fileContent, f.getFileErr } @@ -838,6 +851,58 @@ func TestCleanupScenario_DeactivateKillSwitch_Error(t *testing.T) { assert.Contains(t, logged[0], "deactivate kill switch") } +func TestCleanupScenario_DeactivatesKillSwitchBase(t *testing.T) { + t.Parallel() + + scmDriver := &fakeCleanupSCM{ + fileContent: []byte("version: \"1\"\nkill_switch: true\n"), + } + w := &world.World{ + Org: "org", + RepoOwner: "org", + RepoName: "repo", + KillSwitchBaseActivated: true, + SCM: scmDriver, + } + CleanupScenario(w) + assert.True(t, scmDriver.commitFileCalled, "should commit config.base.yaml to deactivate kill switch") +} + +func TestCleanupScenario_SkipsKillSwitchBaseWhenNotActivated(t *testing.T) { + t.Parallel() + + scmDriver := &fakeCleanupSCM{} + w := &world.World{ + RepoOwner: "org", + RepoName: "repo", + KillSwitchBaseActivated: false, + SCM: scmDriver, + } + CleanupScenario(w) + assert.False(t, scmDriver.commitFileCalled, "should not commit when config.base.yaml kill switch was not activated") +} + +func TestCleanupScenario_DeactivateKillSwitchBase_Error(t *testing.T) { + t.Parallel() + + var logged []string + scmDriver := &fakeCleanupSCM{ + fileContent: []byte("version: \"1\"\nkill_switch: true\n"), + commitFileErr: fmt.Errorf("commit failed"), + } + w := &world.World{ + Org: "org", + RepoOwner: "org", + RepoName: "repo", + KillSwitchBaseActivated: true, + SCM: scmDriver, + Logf: func(format string, args ...any) { logged = append(logged, fmt.Sprintf(format, args...)) }, + } + CleanupScenario(w) + require.Len(t, logged, 1) + assert.Contains(t, logged[0], "deactivate kill switch in config.base.yaml") +} + // --- Allowed remote resources cleanup tests --- func TestCleanupScenario_RestoresAllowedResources(t *testing.T) { @@ -1336,6 +1401,45 @@ func TestValidateSlotClean(t *testing.T) { require.ErrorContains(t, err, "kill_switch is active") }) + // config.yaml is silent on kill_switch here (the "clean slot" + // baseline); only ValidateSlotClean consulting config.base.yaml + // too catches this. + t.Run("kill switch left on in config.base.yaml only", func(t *testing.T) { + t.Parallel() + w := leased(slotConfig(t, nil)) + w.SCM.(*fakeCleanupSCM).baseFileConfigured = true + w.SCM.(*fakeCleanupSCM).baseFileContent = slotConfig(t, func(c config.PerRepoConfigWriter) { c.SetKillSwitch(true) }) + err := ValidateSlotClean(w) + require.ErrorContains(t, err, "kill_switch is active") + }) + + t.Run("config.base.yaml missing is not an error", func(t *testing.T) { + t.Parallel() + w := leased(slotConfig(t, nil)) + w.SCM.(*fakeCleanupSCM).baseFileConfigured = true + w.SCM.(*fakeCleanupSCM).baseFileErr = forge.ErrNotFound + require.NoError(t, ValidateSlotClean(w)) + }) + + t.Run("malformed config.base.yaml does not mask an overlay kill switch left on", func(t *testing.T) { + t.Parallel() + w := leased(slotConfig(t, func(c config.PerRepoConfigWriter) { c.SetKillSwitch(true) })) + w.SCM.(*fakeCleanupSCM).baseFileConfigured = true + w.SCM.(*fakeCleanupSCM).baseFileContent = []byte("kill_switch: [unterminated\n") + err := ValidateSlotClean(w) + require.ErrorContains(t, err, "config.base.yaml is malformed") + require.ErrorContains(t, err, "kill_switch is active") + }) + + t.Run("malformed config.base.yaml alone is reported as stale", func(t *testing.T) { + t.Parallel() + w := leased(slotConfig(t, nil)) + w.SCM.(*fakeCleanupSCM).baseFileConfigured = true + w.SCM.(*fakeCleanupSCM).baseFileContent = []byte("kill_switch: [unterminated\n") + err := ValidateSlotClean(w) + require.ErrorContains(t, err, "config.base.yaml is malformed") + }) + t.Run("no leased repo", func(t *testing.T) { t.Parallel() require.NoError(t, ValidateSlotClean(&world.World{Org: "org", SCM: &fakeCleanupSCM{}})) diff --git a/pkg/behaviourtest/steps/dispatch.go b/pkg/behaviourtest/steps/dispatch.go index 452ccbd7fb..f6b6f9008d 100644 --- a/pkg/behaviourtest/steps/dispatch.go +++ b/pkg/behaviourtest/steps/dispatch.go @@ -13,6 +13,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/agentnew" "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/forge" "github.com/fullsend-ai/fullsend/internal/scaffold" "github.com/fullsend-ai/fullsend/pkg/behaviourtest/drivers/ci" "github.com/fullsend-ai/fullsend/pkg/behaviourtest/world" @@ -46,6 +47,9 @@ func registerDispatchSteps(sc *godog.ScenarioContext) { sc.Step(`^the kill switch is active$`, func(ctx context.Context) (context.Context, error) { return ctx, givenKillSwitchActive(world.FromContext(ctx)) }) + sc.Step(`^the kill switch is active in config\.base\.yaml$`, func(ctx context.Context) (context.Context, error) { + return ctx, givenKillSwitchActiveViaConfigBase(world.FromContext(ctx)) + }) } // givenKillSwitchActive sets kill_switch: true in the enrolled repo's @@ -104,6 +108,75 @@ func DeactivateKillSwitch(w *world.World) error { return nil } +// givenKillSwitchActiveViaConfigBase sets kill_switch: true in the +// enrolled repo's config.base.yaml (the central/base config layer), +// deliberately leaving config.yaml untouched/silent on the key. +// config.base.yaml is not part of the standard per-repo scaffold, so it +// may not exist yet; a missing file is treated as an empty starting +// point rather than an error. It also marks w.KillSwitchBaseActivated +// so CleanupScenario deactivates it before the slot is reused by +// another scenario. +func givenKillSwitchActiveViaConfigBase(w *world.World) error { + if w.Org == "" || w.RepoName == "" { + return fmt.Errorf("no repo configured; call 'Given the enrolled test repository' before kill-switch operations") + } + cfgPath := filepath.Join(".fullsend", "config.base.yaml") + cfgData, err := w.SCM.GetFileContent(context.Background(), w.Org, w.RepoName, cfgPath) + if err != nil { + if !forge.IsNotFound(err) { + return fmt.Errorf("reading base config: %w", err) + } + cfgData = nil + } + cfg, err := config.ParsePerRepoConfigWriter(cfgData) + if err != nil { + return fmt.Errorf("parsing base config: %w", err) + } + cfg.SetKillSwitch(true) + merged, err := cfg.Marshal() + if err != nil { + return err + } + if err := w.SCM.CommitFile(context.Background(), w.Org, w.RepoName, cfgPath, "behaviour: activate kill switch via config.base.yaml", merged); err != nil { + return fmt.Errorf("updating base config: %w", err) + } + w.KillSwitchBaseActivated = true + return nil +} + +// DeactivateKillSwitchBase sets kill_switch: false in the enrolled +// repo's config.base.yaml. Exported so CleanupScenario (in package +// steps) can call it during scenario teardown. The SCM driver has no +// delete-file operation, so this resets the key to false rather than +// removing the file — matching DeactivateKillSwitch's approach for +// config.yaml. +func DeactivateKillSwitchBase(w *world.World) error { + if w.Org == "" || w.RepoName == "" { + return fmt.Errorf("no repo configured; call 'Given the enrolled test repository' before kill-switch operations") + } + cfgPath := filepath.Join(".fullsend", "config.base.yaml") + cfgData, err := w.SCM.GetFileContent(context.Background(), w.Org, w.RepoName, cfgPath) + if err != nil { + if !forge.IsNotFound(err) { + return fmt.Errorf("reading base config: %w", err) + } + cfgData = nil + } + cfg, err := config.ParsePerRepoConfigWriter(cfgData) + if err != nil { + return fmt.Errorf("parsing base config: %w", err) + } + cfg.SetKillSwitch(false) + merged, err := cfg.Marshal() + if err != nil { + return err + } + if err := w.SCM.CommitFile(context.Background(), w.Org, w.RepoName, cfgPath, "behaviour: deactivate kill switch in config.base.yaml", merged); err != nil { + return fmt.Errorf("updating base config: %w", err) + } + return nil +} + func givenDisabledCustomHarness(w *world.World, name, doc string) error { if w.Org == "" || w.RepoName == "" { return fmt.Errorf("no repo configured; call 'Given the enrolled test repository' before harness operations") diff --git a/pkg/behaviourtest/steps/dispatch_test.go b/pkg/behaviourtest/steps/dispatch_test.go index 8fddb304bb..c6967324fa 100644 --- a/pkg/behaviourtest/steps/dispatch_test.go +++ b/pkg/behaviourtest/steps/dispatch_test.go @@ -129,6 +129,150 @@ func TestGivenKillSwitchActive_CommitFileError(t *testing.T) { assert.Contains(t, err.Error(), "updating config") } +// --- givenKillSwitchActiveViaConfigBase / DeactivateKillSwitchBase tests --- +// +// These mirror the givenKillSwitchActive/DeactivateKillSwitch tests +// above, but target .fullsend/config.base.yaml instead of config.yaml. +// config.base.yaml is not part of the standard scaffold, so these also +// cover the "file does not exist yet" path that config.yaml's +// equivalents never need to (config.yaml always exists once a repo is +// enrolled). + +func TestGivenKillSwitchActiveViaConfigBase_SetsKillSwitch(t *testing.T) { + scm := &fakeDispatchSCM{ + fileContent: []byte("version: \"1\"\nroles:\n - triage\n"), + } + w := &world.World{ + SCM: scm, + Org: "org", + RepoName: "repo", + } + err := givenKillSwitchActiveViaConfigBase(w) + require.NoError(t, err) + assert.True(t, scm.commitCalled, "CommitFile should have been called") + assert.Contains(t, string(scm.committedContent), "kill_switch: true") + assert.True(t, w.KillSwitchBaseActivated, "KillSwitchBaseActivated should be set for cleanup") +} + +func TestGivenKillSwitchActiveViaConfigBase_MissingFileTreatedAsEmpty(t *testing.T) { + scm := &fakeDispatchSCM{ + getFileErr: forge.ErrNotFound, + } + w := &world.World{ + SCM: scm, + Org: "org", + RepoName: "repo", + } + err := givenKillSwitchActiveViaConfigBase(w) + require.NoError(t, err, "a missing config.base.yaml should be treated as an empty starting point, not an error") + assert.True(t, scm.commitCalled, "CommitFile should have been called") + assert.Contains(t, string(scm.committedContent), "kill_switch: true") +} + +func TestGivenKillSwitchActiveViaConfigBase_GetFileContentError(t *testing.T) { + scm := &fakeDispatchSCM{ + getFileErr: fmt.Errorf("server error"), + } + w := &world.World{ + SCM: scm, + Org: "org", + RepoName: "repo", + } + err := givenKillSwitchActiveViaConfigBase(w) + require.Error(t, err) + assert.Contains(t, err.Error(), "reading base config") +} + +func TestGivenKillSwitchActiveViaConfigBase_CommitFileError(t *testing.T) { + scm := &fakeDispatchSCM{ + fileContent: []byte("version: \"1\"\nroles:\n - triage\n"), + commitErr: fmt.Errorf("commit failed"), + } + w := &world.World{ + SCM: scm, + Org: "org", + RepoName: "repo", + } + err := givenKillSwitchActiveViaConfigBase(w) + require.Error(t, err) + assert.Contains(t, err.Error(), "updating base config") +} + +func TestGivenKillSwitchActiveViaConfigBase_EmptyIdentity(t *testing.T) { + t.Parallel() + w := &world.World{SCM: &fakeDispatchSCM{}} + err := givenKillSwitchActiveViaConfigBase(w) + require.Error(t, err) + assert.Contains(t, err.Error(), "no repo configured") +} + +func TestDeactivateKillSwitchBase_ClearsKillSwitch(t *testing.T) { + scm := &fakeDispatchSCM{ + fileContent: []byte("version: \"1\"\nkill_switch: true\n"), + } + w := &world.World{ + SCM: scm, + Org: "org", + RepoName: "repo", + } + err := DeactivateKillSwitchBase(w) + require.NoError(t, err) + assert.True(t, scm.commitCalled, "CommitFile should have been called") + assert.Contains(t, string(scm.committedContent), "kill_switch: false") +} + +func TestDeactivateKillSwitchBase_MissingFileTreatedAsEmpty(t *testing.T) { + scm := &fakeDispatchSCM{ + getFileErr: forge.ErrNotFound, + } + w := &world.World{ + SCM: scm, + Org: "org", + RepoName: "repo", + } + err := DeactivateKillSwitchBase(w) + require.NoError(t, err, "a missing config.base.yaml should be treated as an empty starting point, not an error") + assert.True(t, scm.commitCalled, "CommitFile should have been called") + assert.Contains(t, string(scm.committedContent), "kill_switch: false") +} + +func TestDeactivateKillSwitchBase_GetFileContentError(t *testing.T) { + scm := &fakeDispatchSCM{ + getFileErr: fmt.Errorf("server error"), + } + w := &world.World{ + SCM: scm, + Org: "org", + RepoName: "repo", + } + err := DeactivateKillSwitchBase(w) + require.Error(t, err) + assert.Contains(t, err.Error(), "reading base config") +} + +func TestDeactivateKillSwitchBase_CommitFileError(t *testing.T) { + scm := &fakeDispatchSCM{ + fileContent: []byte("version: \"1\"\nkill_switch: true\n"), + commitErr: fmt.Errorf("commit failed"), + } + w := &world.World{ + SCM: scm, + Org: "org", + RepoName: "repo", + } + err := DeactivateKillSwitchBase(w) + require.Error(t, err) + assert.Contains(t, err.Error(), "updating base config") +} + +func TestDeactivateKillSwitchBase_EmptyIdentity(t *testing.T) { + t.Parallel() + w := &world.World{SCM: &fakeDispatchSCM{}} + err := DeactivateKillSwitchBase(w) + require.Error(t, err) + assert.Contains(t, err.Error(), "no repo configured") +} + // --- empty identity guard tests --- func TestGivenKillSwitchActive_EmptyIdentity(t *testing.T) { diff --git a/pkg/behaviourtest/world/world.go b/pkg/behaviourtest/world/world.go index b6cc4b8155..2d91323552 100644 --- a/pkg/behaviourtest/world/world.go +++ b/pkg/behaviourtest/world/world.go @@ -129,6 +129,14 @@ type World struct { // the switch so the next scenario on this slot is not affected. KillSwitchActivated bool + // KillSwitchBaseActivated records whether this scenario activated + // the kill switch via .fullsend/config.base.yaml (the central/base + // layer) rather than config.yaml. CleanupScenario uses this to + // deactivate it so the next scenario on this slot is not affected. + // Tracked separately from KillSwitchActivated because the two + // files are independent. + KillSwitchBaseActivated bool + // RuntimeOverridden records that this scenario changed the repo's // `runtime:` in .fullsend/config.yaml; RuntimeOriginal is the value // to restore. CleanupScenario reverts it so the slot's next scenario