diff --git a/.github/workflows/reusable-poll-jira.yml b/.github/workflows/reusable-poll-jira.yml index 91252c17dd..e585d5d668 100644 --- a/.github/workflows/reusable-poll-jira.yml +++ b/.github/workflows/reusable-poll-jira.yml @@ -115,6 +115,7 @@ jobs: - name: Poll Jira env: + GH_TOKEN: ${{ github.token }} FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }} FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} diff --git a/docs/cli/README.md b/docs/cli/README.md index 4b6dcbb52b..fb61d6122c 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -29,7 +29,7 @@ To update an installed binary later, run [`fullsend self-update`](self-update.md | [`fullsend run`](run.md) | Execute an agent locally in a sandbox. See [running agents locally](../guides/user/running-agents-locally.md). | | `fullsend review-dedup` | Decide whether an unchanged synchronize event can skip review, publish the skip note, or supersede an earlier skip note. | | [`fullsend prepare`](prepare.md) | Resolve an agent's sandbox image as `fullsend run` does, pre-pull a private image with the CI job's registry credential (`ghcr.io` on GitHub Actions, `CI_REGISTRY` on GitLab CI) as `run` does, and create and delete a restrictive preflight sandbox, which makes the gateway pull the image. Run it once before many parallel runs. `--json` prints the resolved image, architecture, and result. | -| `fullsend poll` | Discover forge events and dispatch agent pipelines. `--forge gitlab` runs the cron poller ([ADR 0067](../ADRs/0067-gitlab-cron-polling-event-dispatch.md)); events-mode polling also recovers issue opens whose webhook delivery was missed. `--input-driver jira-poll` polls Jira (see [Jira integration](../guides/user/jira-integration.md)). It reads the Jira site, API gateway, projects, and query only from the effective entity-source configuration: the source translated from `tracker.jira` (`base_url` and `project` required), which becomes `connections.jira` and the `jira` source; explicit Jira `entity_sources` entries cannot be polled until explicit connections get their own credential binding (the removed `--jira-url`, `--jira-project`, and `--jql` flags are rejected). It authenticates with `FULLSEND_JIRA_TOKEN` (plus `FULLSEND_JIRA_EMAIL` for a bot user) or with OAuth 2.0 client credentials via `FULLSEND_JIRA_CLIENT_ID` and `FULLSEND_JIRA_CLIENT_SECRET`. Those credentials are reused only for the connection translated from `tracker.jira`; a source on an explicit Jira connection is refused until a separately provisioned credential binding exists, and explicit sources are refused when enabled agents bind different `entities.source` lists. It skips the cycle unless a selected source permits discovery (`tracker.jira.poll.enabled` is `true` for the translated source); by default it writes dispatch records (`--output`) for a GitHub repository (`--target-repo`, an `owner/repo` slug; one that contains `..` is refused), and with `--target-forge gitlab` it starts the protected agent pipelines of the GitLab project named by `--project` (full path, nested groups allowed; default `CI_PROJECT_PATH`) on the https `--gitlab-url` instance, through the same signed, typed-input dispatch route and Poller credential as the GitLab poller, advancing a Jira issue's checkpoint only once its pipelines are created ([GitLab runtime](../guides/user/jira-integration.md#gitlab-runtime)). `--input-driver gitlab-webhook` is the GitLab dispatcher job's webhook fast-path ([ADR 0125](../ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). It reads the native webhook body from the file-type `TRIGGER_PAYLOAD` variable, re-validates it against the GitLab API, and creates each routed stage's pipeline (typed inputs, `FULLSEND_DISPATCH_SECRET` HMAC) with the poller-role credential (the `api` route, the default). Scheduled cron polling and the webhook fast path run as the trigger-only service account: once its dispatch activation is recorded, the managed webhook carries the account's pipeline trigger token ([#8509](https://github.com/fullsend-ai/fullsend/issues/8509)), the scaffold sets `FULLSEND_GITLAB_DISPATCH_ROUTE=child-pipeline`, and the command instead starts each pipeline with the job's own `CI_JOB_TOKEN` through the pipeline trigger API (`source=pipeline`); an unknown route, or `child-pipeline` without `CI_JOB_TOKEN`, fails closed. `fullsend poll --forge gitlab --print-dispatch-routes` prints the routes the CLI supports (`api` and `child-pipeline`) and exits; the scaffold runs it before selecting `child-pipeline`, and a CLI that predates the route rejects the flag, so the job stops before any dispatch. It requires `--project`, which has no `CI_PROJECT_PATH` fallback. It deduplicates against the poller's per-mode state on the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches, so an event the webhook dispatched is not dispatched again by the poller, and the reverse. Shared poller state is occurrence-aware (label additions are keyed on the resource label event ID, dispatched keys are retained for the webhook freshness window, and a failed label dispatch is handed back to the poller as a pending retry); legacy persisted keys keep working. Older pollers do not recognise the new label keys, so before a rollback or mixed-version run, follow the [ADR 0132](../ADRs/0132-occurrence-aware-shared-poller-state.md) guidance to drain in-flight poll jobs or pin every poller to one version. Both GitLab drivers dispatch the fix stage only for a changes-requested marker note authored by the registered Analyst, whose numeric user ID the scaffold exports as the job-local `FULLSEND_GITLAB_ANALYST_USER_ID`. | +| `fullsend poll` | Discover forge events and dispatch agent pipelines. `--forge gitlab` runs the cron poller ([ADR 0067](../ADRs/0067-gitlab-cron-polling-event-dispatch.md)); events-mode polling also recovers issue opens whose webhook delivery was missed. `--input-driver jira-poll` polls Jira (see [Jira integration](../guides/user/jira-integration.md)). It matches each Jira event against the harness triggers of the agents that config makes effective. These are the built-in triage and code agents (review, fix, retro and prioritize are never dispatched from Jira) selected by the effective `roles:` setting and not disabled by `agents:`: omitting `roles`, setting it to null, or leaving a bare `roles:` key all inherit the parent/default selection, while an explicit `roles: []` selects none. Built-ins are resolved from the `fullsend-ai/agents` release that matches the CLI version as `fullsend run` resolves them, with the GitHub token `fullsend run` uses when one is available; agents registered with a `source:` are also included ([Check which agents handle Jira events](../guides/user/jira-integration.md#setup-overview)). It reads the Jira site, API gateway, projects, and query only from the effective entity-source configuration: the source translated from `tracker.jira` (`base_url` and `project` required), which becomes `connections.jira` and the `jira` source; explicit Jira `entity_sources` entries cannot be polled until explicit connections get their own credential binding (the removed `--jira-url`, `--jira-project`, and `--jql` flags are rejected). It authenticates with `FULLSEND_JIRA_TOKEN` (plus `FULLSEND_JIRA_EMAIL` for a bot user) or with OAuth 2.0 client credentials via `FULLSEND_JIRA_CLIENT_ID` and `FULLSEND_JIRA_CLIENT_SECRET`. Those credentials are reused only for the connection translated from `tracker.jira`; a source on an explicit Jira connection is refused until a separately provisioned credential binding exists, and explicit sources are refused when enabled agents bind different `entities.source` lists. It skips the cycle unless a selected source permits discovery (`tracker.jira.poll.enabled` is `true` for the translated source); by default it writes dispatch records (`--output`) for a GitHub repository (`--target-repo`, an `owner/repo` slug; one that contains `..` is refused), and with `--target-forge gitlab` it starts the protected agent pipelines of the GitLab project named by `--project` (full path, nested groups allowed; default `CI_PROJECT_PATH`) on the https `--gitlab-url` instance, through the same signed, typed-input dispatch route and Poller credential as the GitLab poller, advancing a Jira issue's checkpoint only once its pipelines are created ([GitLab runtime](../guides/user/jira-integration.md#gitlab-runtime)). `--input-driver gitlab-webhook` is the GitLab dispatcher job's webhook fast-path ([ADR 0125](../ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). It reads the native webhook body from the file-type `TRIGGER_PAYLOAD` variable, re-validates it against the GitLab API, and creates each routed stage's pipeline (typed inputs, `FULLSEND_DISPATCH_SECRET` HMAC) with the poller-role credential (the `api` route, the default). Scheduled cron polling and the webhook fast path run as the trigger-only service account: once its dispatch activation is recorded, the managed webhook carries the account's pipeline trigger token ([#8509](https://github.com/fullsend-ai/fullsend/issues/8509)), the scaffold sets `FULLSEND_GITLAB_DISPATCH_ROUTE=child-pipeline`, and the command instead starts each pipeline with the job's own `CI_JOB_TOKEN` through the pipeline trigger API (`source=pipeline`); an unknown route, or `child-pipeline` without `CI_JOB_TOKEN`, fails closed. `fullsend poll --forge gitlab --print-dispatch-routes` prints the routes the CLI supports (`api` and `child-pipeline`) and exits; the scaffold runs it before selecting `child-pipeline`, and a CLI that predates the route rejects the flag, so the job stops before any dispatch. It requires `--project`, which has no `CI_PROJECT_PATH` fallback. It deduplicates against the poller's per-mode state on the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches, so an event the webhook dispatched is not dispatched again by the poller, and the reverse. Shared poller state is occurrence-aware (label additions are keyed on the resource label event ID, dispatched keys are retained for the webhook freshness window, and a failed label dispatch is handed back to the poller as a pending retry); legacy persisted keys keep working. Older pollers do not recognise the new label keys, so before a rollback or mixed-version run, follow the [ADR 0132](../ADRs/0132-occurrence-aware-shared-poller-state.md) guidance to drain in-flight poll jobs or pin every poller to one version. Both GitLab drivers dispatch the fix stage only for a changes-requested marker note authored by the registered Analyst, whose numeric user ID the scaffold exports as the job-local `FULLSEND_GITLAB_ANALYST_USER_ID`. | | `fullsend dispatch` | Evaluate harness CEL triggers for one forge event and print the dispatch matrix (`--output-driver gha-matrix` or `json`); used by the dispatch workflow's `Harness dispatch` job. `--route ` (`review`, `retro`, `triage` or `prioritize`) instead decides routing for that built-in agent and prints one JSON line, `{"agent":"","decision":"run\|skip\|bash","reason":"…","harness":"config:\|agents@"}` (`harness` is optional: it is omitted when the harness cannot be resolved or the decision did not need it, as for `bash`): `run` or `skip` when the repository set `agents[].trigger` on the agent's entry ([Choosing when review runs](../guides/user/customizing-agents.md#choosing-when-review-runs), [Choosing when retro runs](../guides/user/customizing-agents.md#choosing-when-retro-runs), [Choosing when triage and prioritize run](../guides/user/customizing-agents.md#choosing-when-triage-and-prioritize-run)), `bash` to leave the decision to the workflow's built-in rules. Built-in agents resolve from a configured Forgejo instance when `FULLSEND_FORGEJO_URL` is set, as in [`fullsend run`](run.md#agent-definitions-from-a-forgejo-instance). The dispatch workflow's `Route` job runs it. With `--input-driver gha-event`, a GitHub bot actor's registered fullsend role is looked up first through the mint (a layered `mint_url`, else `FULLSEND_MINT_URL`) with the job's Actions OIDC token, so the job needs `id-token: write` ([ADR 0107](../ADRs/0107-bot-identity-resolution-for-dispatch-authorization.md)); label-added events skip the lookup, and an unregistered bot or a failed lookup is denied (an empty matrix, or a `skip` decision) rather than failing the command. An absent config falls back to `FULLSEND_MINT_URL`, but a config that fails to load or parse is a failed lookup, not a fallback. `--input-driver forgejo-event` maps a Forgejo Actions event payload (`FORGEJO_EVENT_PATH`, bound to `FORGEJO_SERVER_URL` and the repository); it is the default when `FORGEJO_ACTIONS` or `GITEA_ACTIONS` is `true`, even when `GITHUB_EVENT_PATH` is also set. This changes the default for pipelines on Forgejo or Gitea runners that relied on the implicit `gha-event` driver; pass `--input-driver gha-event` to restore the previous behavior. No Forgejo permission lookup is wired yet, so its events are denied by the authorization gate ([Forgejo adapter notes](../normative/normalized-event/v1/README.md#forgejo-adapter-notes)). | | `fullsend bot-role` | Resolve the registered Fullsend role ([ADR 0107](../ADRs/0107-bot-identity-resolution-for-dispatch-authorization.md)) of the actor that produced a comment on the entity the run handles (`--entity --comment `) — a harness pre-/post-script helper: `fullsend run` starts the loopback bot-role helper and hands the scripts `FULLSEND_BOT_ROLE_URL`/`FULLSEND_BOT_ROLE_TOKEN` and the entity's canonical ID as `FULLSEND_ENTITY_ID`, so scripts learn a comment's bot role without touching the OIDC token. The answer is for the comment's current-revision actor (the last editor of an edited comment). Prints the registered role or `no_match` and exits 0; a lookup that cannot be completed, a comment on another entity, or a run with no trusted lookup (GitLab and Jira today, and any run with no mint URL, no Actions OIDC environment, or no resolvable GitHub entity) exits non-zero with empty stdout, so callers fail closed. See [Bring your own agent](../guides/user/bring-your-own-agent.md#resolving-a-comments-bot-role). | | `fullsend lock [agent-name]` | Pin remote dependencies to `lock.yaml`. If `lock.yaml` exists but cannot be parsed or declares an unsupported version, the command exits without writing and leaves the file unchanged. An entry is stale when the harness file or the `harness:` block of the agent's `agents:` entry has changed. When it composes a harness (a new or stale entry, or `--update`), it also prints the harness diagnostics, including [reserved `env.sandbox` keys](run.md#reserved-envsandbox-keys). A current entry is not composed, so its keys are not checked, and `lock` composes without event context, so keys from event-guarded overlays are reported only by `fullsend run`. A harness whose runtime fetch service can start (`allow_runtime_fetch: true`, URL-sourced skill or plugin directories, or a bare, deprecated `allowed_remote_resources` declaration) must have every harness-level `allowed_remote_resources` prefix covered by the config-level allowlist — `config.yaml`'s `allowed_remote_resources` plus the built-in default prefixes (the defaults are included when the list is omitted or non-empty; an explicit `allowed_remote_resources: []` stays deny-all and excludes them); `lock` fails naming an uncovered prefix, and fails closed when no repository config (`config.yaml` or `config.base.yaml`) exists. With a `harness:` block on the agent's entry, the prefixes checked are the ones the block sets. | @@ -44,4 +44,10 @@ To update an installed binary later, run [`fullsend self-update`](self-update.md All commands that interact with GitHub resolve authentication via `GH_TOKEN`, `GITHUB_TOKEN`, or `gh auth token` (in that order). Explicit token flags such as `--token` and `--forge-token` override the chain. For GitLab, set `GITLAB_TOKEN` or pass `--gitlab-token` to `repos` subcommands. The CLI runs preflight checks and tells you exactly which OAuth scopes are missing before making any changes. +For built-in agent lookup during Jira polling, the shipped GitHub workflow +passes its read-only job token as `GH_TOKEN`. On GitLab, configure a masked, +protected `GITHUB_TOKEN` CI/CD variable. Without a GitHub token, the lookup +shares the anonymous API rate limit with other jobs using the same public IP +address. See [GitLab Jira polling requirements](../guides/user/jira-integration.md#requirements). + For the complete command tree with implementation details, see [CLI internals](../guides/dev/cli-internals.md). diff --git a/docs/guides/user/custom-poller-example.md b/docs/guides/user/custom-poller-example.md index 574cd33730..8c95f5130b 100644 --- a/docs/guides/user/custom-poller-example.md +++ b/docs/guides/user/custom-poller-example.md @@ -49,6 +49,7 @@ jobs: - name: Poll Jira and build dispatch matrix id: dispatch env: + GH_TOKEN: ${{ github.token }} FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }} FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 636dfb5774..b41e135f7d 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -79,11 +79,44 @@ Connect fullsend to a Jira project so that Jira issue activity — comments, lab install writes the scheduled workflow; on GitLab, it creates the pipeline schedule. See [Scheduled workflow](#scheduled-workflow) and [GitLab runtime](#gitlab-runtime). -6. **Check which agents handle Jira events.** The poller dispatches an agent - only when its harness `trigger:` CEL expression matches the Jira event, and - produces zero dispatches for a harness with no trigger, its own or - inherited. The built-in triage and code harnesses ship triggers that match - Jira events, so they need no extra configuration: +6. **Check which agents handle Jira events.** A fresh install needs no + `agents:` entries. Each poll run considers the following agents: + + - The built-in triage and code agents, unless `agents:` in + `.fullsend/config.yaml` disables one with `enabled: false`. Review, fix, + retro and prioritize are never dispatched from Jira, so the poller does + not fetch them and one that is unavailable cannot fail a poll run. When + the config sets `roles:` (or setup ran with `--agents`), only the + built-in agents those roles select are considered: for example + `roles: [triage]` leaves out code, `coder` selects code, and an explicit + `roles: []` selects no built-in agent. An agent a role does not select is + never fetched. + The poller resolves it the same way + `fullsend run` does: from the `fullsend-ai/agents` release tag that + matches the fullsend release you run, or from `main` for a development + build. It reads the commit that ref points to at the start of the run. + Authentication uses the same token sources as `fullsend run`, in order: + `GH_TOKEN`, `GITHUB_TOKEN`, then `gh auth`. The shipped GitHub workflow + passes its read-only job token to the poll step as `GH_TOKEN`. On GitLab, + supply `GITHUB_TOKEN` as a CI/CD variable (see + [GitLab requirements](#requirements)). With no token, the lookup is + anonymous and shares GitHub's unauthenticated API rate limit with other + jobs using the same public IP address. A refused lookup fails the poll + before checkpoints advance. + - Every agent registered under `agents:` with a `source:` harness. An + entry with a `source:` that has a built-in agent's name replaces that + built-in. + + An `agents:` entry without a `source:` only tunes a built-in agent. Two + examples are `- name: triage` with `runtime: claude`, and an entry with a + `harness:` block. The built-in agent still dispatches from Jira, and the + entry's settings apply. Each agent is considered once. + + The poller dispatches an agent only when its harness `trigger:` CEL + expression matches the Jira event, and produces zero dispatches for a + harness with no trigger, its own or inherited. The built-in triage and + code harnesses ship triggers that match Jira events, so they need no + extra configuration: | Built-in agent | Jira events its trigger matches | From | |---|---|---| @@ -91,11 +124,31 @@ Connect fullsend to a Jira project so that Jira issue activity — comments, lab | code | A `/fs-code` comment from a human, or the `ready-to-code` label being added | The agents release that follows v0.52.0 ([agents#1842](https://github.com/fullsend-ai/agents/pull/1842)) | The actor still needs the role the agent requires. See - [Actor role resolution](#actor-role-resolution). The default prioritize - trigger also matches a `/fs-prioritize` comment on a Jira issue, but - prioritize has no Jira support yet + [Actor role resolution](#actor-role-resolution). The built-in prioritize + agent is not dispatched from Jira: a `/fs-prioritize` comment on a Jira + issue produces no dispatch, because prioritize has no Jira support yet ([#2266](https://github.com/fullsend-ai/fullsend/issues/2266)). Review, - fix and retro do not run from Jira events: see [How it works](#how-it-works). + fix and retro do not run from Jira events either: see + [How it works](#how-it-works). An agent you register with a `source:` is + considered whatever its name, so a custom harness with a valid Jira + `trigger:` still dispatches. + + To stop a built-in agent from dispatching, add an `agents:` entry with + its name and `enabled: false`. This disables the agent on the code host + as well, not only for Jira. If the poller cannot fetch the triage or code + built-in harness, for example because `allowed_remote_resources` leaves out + the agents repository or the lookup is refused, it logs an error for that + agent and the poll run fails. To poll with no access to the agents + repository, register triage and code with a `source:` (a custom source + replaces the built-in, which is then not fetched). The + same holds when it cannot resolve or load any other selected, enabled + agent. The failure happens before any checkpoint advances, so the next + run tries again. When a cycle selects issues but no agent matches a + `/fs-*` command or a label change on them, it logs a + `jira-poll: selected N issue(s) but no agent matched` warning. Ordinary + comments never trigger it. That + warning names each event and the agents considered. See + [Troubleshooting](#troubleshooting). If your built-in agents are pinned to an earlier agents release, or for a custom agent, add a `trigger:` to a harness YAML file registered via @@ -1067,6 +1120,20 @@ for issues and merge requests. dispatches. - The effective config sets `tracker.jira.base_url`, `tracker.jira.project`, and `tracker.jira.poll.enabled: true` (see [Custom JQL](#custom-jql)). +- When using built-in agents, the poll job needs HTTPS access to github.com, + including `api.github.com` and `raw.githubusercontent.com`, to resolve and + fetch `fullsend-ai/agents`. Set a GitHub token as a **masked, protected + `GITHUB_TOKEN` CI/CD variable** in the GitLab project. This is the same + variable `install-fullsend-cli.sh` accepts; the poll job inherits it and + the CLI uses it for the ref lookup. GitLab does not supply a GitHub token + automatically. `GH_TOKEN`, if also set, takes precedence for the poller. + GitLab job/role tokens and Jira credentials cannot replace this token. + Without a GitHub token or `gh auth`, the lookup is anonymous: GitHub allows + [60 unauthenticated API requests per hour](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api#primary-rate-limit-for-unauthenticated-users) + per public IP address, shared by every repository polling from that address. + Five repositories polling every five minutes can consume all 60 requests + with one ref lookup per cycle, before retries or other API calls. A + rate-limited lookup fails the poll without advancing checkpoints. - The poll job receives `FULLSEND_JIRA_TOKEN` and, for a bot user, `FULLSEND_JIRA_EMAIL`. A service account can use `FULLSEND_JIRA_CLIENT_ID` and `FULLSEND_JIRA_CLIENT_SECRET` instead (see @@ -1730,6 +1797,8 @@ However, more pollers against the same Jira project means more API calls per cyc | `jira: OAuth token request to "https://auth.atlassian.com/oauth/token" with FULLSEND_JIRA_CLIENT_ID and FULLSEND_JIRA_CLIENT_SECRET: unexpected status 401 (invalid_client)` | The service account's OAuth 2.0 client ID or secret is wrong, expired, or revoked | Create a new OAuth 2.0 credential for the service account and update `FULLSEND_JIRA_CLIENT_ID` and `FULLSEND_JIRA_CLIENT_SECRET` with `repos install --jira-client-id --jira-client-secret` | | `jira: set either FULLSEND_JIRA_TOKEN or FULLSEND_JIRA_CLIENT_ID and FULLSEND_JIRA_CLIENT_SECRET, not both` | Both credential types are set | Keep one. `repos install` removes the other set when you supply new credentials | | 200 on `/myself` but 403 on issue search | Org restricts personal API tokens for project data | Ask your Atlassian org admin to allow API token access for project data | +| `::warning::jira-poll: selected N issue(s) but no agent matched any of their events` | The poller evaluated a `/fs-*` command or label change on the selected issues, but none matched an agent (ordinary comments are not counted). The warning lists each issue key and event, for example `PROJ-1 (comment_added /fs-code)`, and the agents considered | If the agent is missing from the list, check that it is not disabled under `agents:`. Otherwise, compare the event with the agent's harness `trigger:`, and check that the actor has the role the agent requires. See [Actor role resolution](#actor-role-resolution) | +| `list triggered harnesses: no agents could be loaded` or `list triggered harnesses: some agents could not be loaded` | The poller could not fetch or load the harness of every agent it considers (`no agents`) or of at least one of them (`some agents`). The poller fails in both cases, so an event only the unavailable agent could match is not dropped. One cause is a network failure reaching the `fullsend-ai/agents` repository. Another is an `allowed_remote_resources` list that leaves it out | Check the `::error::harness dispatch: skipping` lines for each agent. No checkpoint advances, so the next poll run retries the same events | | No dispatches produced | No changes since last poll | Check the `lastCheck` entity property on the issue — the poller only dispatches for changes newer than this timestamp | | Agent comments or label changes re-dispatch in a loop | A different Jira account posted the agent output than the one the poller authenticates as | The poller classifies its own `/myself` account as `actor.kind: bot` and filters those events. The built-in agents post with the poller's own `FULLSEND_JIRA_TOKEN` and `FULLSEND_JIRA_EMAIL`. Confirm that a custom agent which posts comments or labels uses the same credential, not another account's token. Human follow-up, including `/fs-triage`, still dispatches | | Your own comments or label changes never dispatch | The poller's `FULLSEND_JIRA_TOKEN` belongs to your own Jira account | The poller classifies its own `/myself` account as `actor.kind: bot`, so that account's comments (including `/fs-triage`) and label changes are filtered with no error. Give the poller a dedicated account; see [Use a dedicated account for the poller](#use-a-dedicated-account-for-the-poller) | diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index dcddfa8a04..b2c4de3b1d 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -248,6 +248,18 @@ overlay that sets `roles` replaces the parent list entirely (no union). Omitting the key inherits the parent's roles. See [Layered Config Reference](../guides/infrastructure/layered-config-reference.md). +Roles also select which built-in agents the Jira poller considers (see +[Jira integration](../guides/user/jira-integration.md)). The poller considers +only the built-in triage and code agents: `triage` enables triage and `coder` +enables code. Review, fix, retro and prioritize are never fetched or +dispatched from Jira, whatever the roles. A built-in agent that no configured +role enables is never fetched or dispatched from Jira. Omitting `roles` falls +back to the parent's roles or the default roles, which select every built-in +agent, while an explicit empty list (`roles: []`) selects none, including over +a parent that lists roles. `roles: null` and a bare `roles:` behave like +omitting the key, as for other list settings that inherit from the parent. +Roles do not scope agents registered with a `source`. + ### `agents` Registered agent sources and per-agent tuning. Each entry identifies an agent @@ -264,7 +276,10 @@ effort, sub-agent models, the trigger and harness settings. against this ref. Empty for SHA-pinned or legacy entries. - **`enabled`** — Toggle the agent without removing its entry. A suppression-only entry (`enabled: false`, no source) disables a built-in or - parent-layer agent by name. + parent-layer agent by name. The Jira poller evaluates the enabled, + role-selected built-in triage and code agents without an `agents:` + registration, so `- name: ` with `enabled: false` is how you opt one + of them out of Jira dispatch (see [`roles`](#roles) for role selection). - **`runtime`**, **`model`**, **`effort`** — Per-agent overrides. An override-only entry (no source, at least one setting) tunes a built-in agent by name. @@ -289,7 +304,9 @@ effort, sub-agent models, the trigger and harness settings. and [Choosing when triage and prioritize run](../guides/user/customizing-agents.md#choosing-when-triage-and-prioritize-run)). It does not change CEL dispatch: the harness `trigger:` keeps deciding when - custom agents run and what the Jira poller dispatches. A trigger alone + custom agents run and what the Jira poller dispatches for each agent it + considers (every enabled, role-selected built-in triage and code agent and + every registered agent). A trigger alone makes a valid override-only entry for a built-in agent. Validated when the agent list is validated: it must compile and return a boolean. Like an invalid `model` or `effort`, an invalid `trigger` makes every agent run in diff --git a/internal/cli/jira_lifecycle_test.go b/internal/cli/jira_lifecycle_test.go index 6f3a3cd603..6f23eeb9b2 100644 --- a/internal/cli/jira_lifecycle_test.go +++ b/internal/cli/jira_lifecycle_test.go @@ -211,6 +211,9 @@ func newJiraLifecycle(t *testing.T, host string) *jiraLifecycle { require.NoError(t, err) configDir := writeLifecycleConfig(t) + // The config registers triage, code, review and retro; the remaining + // built-ins resolve with no trigger, so they dispatch nothing. + stubJiraBuiltins(t, nil) matcher, err := newCELMatcher(context.Background(), configDir) require.NoError(t, err) diff --git a/internal/cli/poll.go b/internal/cli/poll.go index 06015bbfc5..19ded85bae 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -16,6 +16,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/forge" "github.com/fullsend-ai/fullsend/internal/forge/gitlab" "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/harness" "github.com/fullsend-ai/fullsend/internal/harnessdispatch" "github.com/fullsend-ai/fullsend/internal/jiradispatch" "github.com/fullsend-ai/fullsend/internal/jirapoll" @@ -537,6 +538,9 @@ type celMatcher struct { // nil when none is listed. It configures the poller's actor role // resolution and the gate's Jira label rule. jiraAuth *config.AuthorizationProvider + // killSwitch records that the matcher has no candidates because the + // kill switch is active, rather than because no agent is dispatchable. + killSwitch bool } // Match applies the dispatch gate policy the configured jira @@ -566,15 +570,94 @@ func newCELMatcher(ctx context.Context, fullsendDir string) (*celMatcher, error) if cfg.IsKillSwitchActive() { // Kill switch active: return a matcher with no candidates so all // events are silently dropped (no dispatches). - return &celMatcher{Matcher: &jiradispatch.Matcher{Auth: jiraAuthOptions(jiraAuth)}, jiraAuth: jiraAuth}, nil + return &celMatcher{Matcher: &jiradispatch.Matcher{Auth: jiraAuthOptions(jiraAuth)}, jiraAuth: jiraAuth, killSwitch: true}, nil } - candidates, err := harnessdispatch.ListTriggeredHarnesses(ctx, fullsendDir, cfg, nil) + // The effective agents: those registered with a source, plus the + // built-in agents the config does not disable or replace, resolved + // from the agents repository as fullsend run resolves them (#9503). + candidates, err := harnessdispatch.ListEffectiveTriggeredHarnesses(ctx, fullsendDir, cfg, nil, newJiraBuiltinResolverFn()) if err != nil { return nil, fmt.Errorf("list triggered harnesses: %w", err) } return &celMatcher{Matcher: &jiradispatch.Matcher{Candidates: candidates, Auth: jiraAuthOptions(jiraAuth)}, jiraAuth: jiraAuth}, nil } +// DispatchCandidates names the agents the matcher evaluates events +// against, for the poller's no-match warning (jirapoll.CandidateReporter). +// An active kill switch drops every event on purpose, so it suppresses the +// warning. +func (m *celMatcher) DispatchCandidates() ([]string, bool) { + if m.killSwitch { + return nil, true + } + var names []string + if m.Matcher != nil { + for _, c := range m.Candidates { + names = append(names, c.Name) + } + } + return names, false +} + +// newJiraBuiltinResolverFn returns the resolver the Jira matcher loads +// built-in agents with. Override in tests to resolve built-in harnesses +// from local files without the network. +var newJiraBuiltinResolverFn = func() harnessdispatch.BuiltinResolver { + // Authenticated with the token fullsend run composes with + // (GH_TOKEN, GITHUB_TOKEN or gh auth), so the ref lookup does not + // depend on the anonymous API rate limit. Without a token it falls back + // to anonymous access, as the agents repository is public. The client + // is on the configured host when GITHUB_SERVER_URL and GITHUB_API_URL + // agree, as for fullsend run, so the token never follows GITHUB_API_URL + // alone. + printer := ui.New(os.Stderr) + token, err := resolveToken() + if err != nil { + printer.StepWarn("Git token not available; resolving built-in agents anonymously, which the API rate limit may refuse") + } + return agentsRepoBuiltinResolver(newConfiguredHostGitHubClient(token), printer) +} + +// agentsRepoBuiltinResolver resolves built-in agents from the agents +// repository with the version-aware fallback fullsend run uses +// (tryAgentsRepoFallback): a release build reads its own release tag and +// other builds main, pinned to the commit the ref resolves to. The ref is +// resolved once, on first use, and every built-in is read from that commit, +// so a poll cycle makes one ref lookup however many built-ins it loads. +// The resolver is not safe for concurrent use. +func agentsRepoBuiltinResolver(forgeClient forge.Client, printer *ui.Printer) harnessdispatch.BuiltinResolver { + var ( + pin agentsRepoPin + pinned bool + resolved bool + ) + return func(ctx context.Context, name string, opts harness.ComposeOpts) (string, harness.ComposeOpts, bool) { + normalized := strings.ToLower(name) + if !defaultAgentsRepoKnownAgents[normalized] || forgeClient == nil { + return "", opts, false + } + if !resolved { + resolved = true + pin, pinned = resolveAgentsRepoPin(ctx, forgeClient, printer) + } + if !pinned { + return "", opts, false + } + // The configured host serves raw content from itself, so allow it + // in the fetch policy, as fullsend run does. + opts.FetchPolicy = withAgentsRepoHostAllowed(opts.FetchPolicy, forgeClient) + path, dep, ok := fetchAgentsRepoFileAtPin(ctx, "harness/"+normalized+".yaml", pin, forgeClient, opts, printer, "agent "+name) + if !ok { + return "", opts, false + } + // Relative resources resolve against the harness URL, through the + // configured host's API when the harness came from there. + opts.SourceURL = dep.URL + useAgentsRepoHostFetch(&opts, forgeClient) + return path, opts, true + } +} + // jiraAuthOptions returns the dispatch gate policy for the configured // jira provider: with no jira entry, Jira label-added events take the // per-harness role threshold as before; with an entry, they are authorized diff --git a/internal/cli/poll_jira_builtin_production_test.go b/internal/cli/poll_jira_builtin_production_test.go new file mode 100644 index 0000000000..d03dae48a5 --- /dev/null +++ b/internal/cli/poll_jira_builtin_production_test.go @@ -0,0 +1,320 @@ +package cli + +import ( + "context" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/fetch" + "github.com/fullsend-ai/fullsend/internal/jirapoll" +) + +// These tests drive newCELMatcher through the production built-in resolver +// (newJiraBuiltinResolverFn is NOT replaced). Only the external GitHub +// boundary is faked: an httptest server that answers the agents-repo ref +// lookup and contents reads, reached through GITHUB_SERVER_URL and +// GITHUB_API_URL as on a GitHub Enterprise Server host. The coverage is +// fixture-based; it is not a live Jira or live GitHub validation. + +const ( + jiraProdMainSHA = "1111111111111111111111111111111111111111" + jiraProdTagSHA = "2222222222222222222222222222222222222222" +) + +// jiraProdGitHub emulates the GitHub API for fullsend-ai/agents: refs maps +// a ref path (heads/main, tags/v0.85.0) to a commit SHA, and files maps a +// commit SHA to its files. Every request path is recorded; anything it does +// not serve is a 404. +type jiraProdGitHub struct { + *httptest.Server + mu sync.Mutex + paths []string +} + +func newJiraProdGitHub(t *testing.T, refs map[string]string, files map[string]map[string][]byte) *jiraProdGitHub { + t.Helper() + s := &jiraProdGitHub{} + s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + s.paths = append(s.paths, r.URL.RequestURI()) + s.mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + const apiRepo = "/api/v3/repos/fullsend-ai/agents/" + if ref, ok := strings.CutPrefix(r.URL.Path, apiRepo+"git/ref/"); ok { + if sha, found := refs[ref]; found { + _ = json.NewEncoder(w).Encode(map[string]any{"object": map[string]string{"sha": sha, "type": "commit"}}) + return + } + } + if rel, ok := strings.CutPrefix(r.URL.Path, apiRepo+"contents/"); ok { + if content, found := files[r.URL.Query().Get("ref")][rel]; found { + _ = json.NewEncoder(w).Encode(map[string]string{ + "type": "file", + "path": rel, + "sha": fetch.ComputeSHA256(content), + "content": base64.StdEncoding.EncodeToString(content), + "encoding": "base64", + }) + return + } + } + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"message":"Not Found"}`)) + })) + t.Cleanup(s.Close) + useConfiguredGitHubHost(t, s.URL) + useProductionFetchPolicy(t) + return s +} + +func (s *jiraProdGitHub) requests() []string { + s.mu.Lock() + defer s.mu.Unlock() + return append([]string(nil), s.paths...) +} + +// jiraProdAgentsFiles returns the built-in harness and agent files of one +// agents-repo commit, as the agents release ships them: triage and code +// carry Jira command triggers, the rest carry none. model tells commits +// apart. +func jiraProdAgentsFiles(model string) map[string][]byte { + triggers := defaultJiraBuiltinTriggers() + files := map[string][]byte{} + for name := range jiraBuiltinTestRoles { + harnessYAML := strings.Replace(jiraBuiltinTestHarness(name, triggers[name]), "model: opus", "model: "+model, 1) + files["harness/"+name+".yaml"] = []byte(harnessYAML) + files["agents/"+name+".md"] = []byte("# " + name + "\n") + } + return files +} + +// jiraProdAllowlist is the allowed_remote_resources entry for the fixture +// host's agents-repo raw-content URLs, which the default list does not name. +func jiraProdAllowlist(s *jiraProdGitHub) string { + return "allowed_remote_resources:\n - " + s.URL + "/fullsend-ai/agents/raw/\n" +} + +// jiraProdRecords matches a Jira comment with command and returns the +// dispatch records. +func jiraProdRecords(t *testing.T, m *celMatcher, command string) []jirapoll.DispatchRecord { + t.Helper() + records, err := m.Match(context.Background(), jiraCommandEvent(t, command)) + require.NoError(t, err) + return records +} + +// useProductionFetchPolicy restores the production default fetch policy +// for the test. Other tests in the package overwrite fetch.DefaultPolicy +// and leave it zeroed, and newCELMatcher reads the global, so a zero size +// bound would otherwise fail every fixture read. +func useProductionFetchPolicy(t *testing.T) { + t.Helper() + orig := fetch.DefaultPolicy + fetch.DefaultPolicy = fetch.FetchPolicy{ + AllowedDomains: []string{"github.com", "raw.githubusercontent.com"}, + MaxSizeBytes: 10 * 1024 * 1024, + Timeout: 30 * time.Second, + } + t.Cleanup(func() { fetch.DefaultPolicy = orig }) +} + +func jiraProdSetVersion(t *testing.T, ver, commit string) { + t.Helper() + origVersion, origSHA := version, commitSHA + version, commitSHA = ver, commit + t.Cleanup(func() { version, commitSHA = origVersion, origSHA }) +} + +func TestNewCELMatcher_ProductionResolver(t *testing.T) { + const ( + mainRef = "heads/main" + tagRef = "tags/v0.85.0" + ) + refs := map[string]string{mainRef: jiraProdMainSHA, tagRef: jiraProdTagSHA} + files := map[string]map[string][]byte{ + jiraProdMainSHA: jiraProdAgentsFiles("haiku"), + jiraProdTagSHA: jiraProdAgentsFiles("opus"), + } + + // A dev build reads main. No agents: configuration and shorthand + // runtime overrides (no source) both dispatch /fs-triage and /fs-code + // from the built-in harnesses. + for name, agents := range map[string]string{ + "no agents configuration": "", + "shorthand overrides without source": `agents: + - name: triage + runtime: claude + - name: code + effort: low +`, + } { + t.Run(name, func(t *testing.T) { + jiraProdSetVersion(t, "dev", "") + srv := newJiraProdGitHub(t, refs, files) + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n"+jiraProdAllowlist(srv)+agents) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"triage", "code"}, jiraCandidateNames(m)) + for _, c := range m.Candidates { + assert.Equal(t, "haiku", c.Harness.Model, "dev build reads the main commit") + } + + triage := jiraProdRecords(t, m, "/fs-triage") + require.Len(t, triage, 1) + assert.Equal(t, "triage", triage[0].Agent) + assert.Equal(t, "triage", triage[0].Role) + code := jiraProdRecords(t, m, "/fs-code") + require.Len(t, code, 1) + assert.Equal(t, "code", code[0].Agent) + assert.Equal(t, "coder", code[0].Role) + assert.Empty(t, jiraProdRecords(t, m, "/fs-unknown")) + + paths := srv.requests() + require.NotEmpty(t, paths) + assert.Equal(t, "/api/v3/repos/fullsend-ai/agents/git/ref/"+mainRef, paths[0]) + assert.Equal(t, 1, countPrefix(paths, "/api/v3/repos/fullsend-ai/agents/git/ref/"), "the agents ref is resolved once per matcher") + for _, p := range paths { + assert.Contains(t, p, "/api/v3/repos/fullsend-ai/agents/", "only the agents repository is read") + if strings.Contains(p, "/contents/") { + assert.Contains(t, p, "ref="+jiraProdMainSHA, "every file is read from the one pinned commit") + } + } + }) + } + + t.Run("release build pins to its release tag", func(t *testing.T) { + jiraProdSetVersion(t, "0.85.0", "abc123def456") + srv := newJiraProdGitHub(t, refs, files) + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n"+jiraProdAllowlist(srv)) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"triage", "code"}, jiraCandidateNames(m)) + for _, c := range m.Candidates { + assert.Equal(t, "opus", c.Harness.Model, "a release build reads the commit its tag points at") + } + assert.Len(t, jiraProdRecords(t, m, "/fs-triage"), 1) + assert.Len(t, jiraProdRecords(t, m, "/fs-code"), 1) + + paths := srv.requests() + assert.Equal(t, "/api/v3/repos/fullsend-ai/agents/git/ref/"+tagRef, paths[0]) + assert.NotContains(t, strings.Join(paths, "\n"), mainRef, "the main ref is never read by a release build") + assert.NotContains(t, strings.Join(paths, "\n"), jiraProdMainSHA) + }) + + t.Run("custom source replaces the built-in harness", func(t *testing.T) { + jiraProdSetVersion(t, "dev", "") + srv := newJiraProdGitHub(t, refs, files) + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n"+jiraProdAllowlist(srv)+"agents:\n - name: code\n source: harness/code.yaml\n") + customHarness := strings.Replace(jiraBuiltinTestHarness("code", jiraCommandTrigger("/fs-implement")), "model: opus", "model: sonnet", 1) + writeHarnessFile(t, dir, "harness/code.yaml", customHarness) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"code", "triage"}, jiraCandidateNames(m)) + assert.Equal(t, "sonnet", m.Candidates[0].Harness.Model) + assert.Empty(t, jiraProdRecords(t, m, "/fs-code"), "the built-in code trigger is replaced") + code := jiraProdRecords(t, m, "/fs-implement") + require.Len(t, code, 1) + assert.Equal(t, "code", code[0].Agent) + assert.Len(t, jiraProdRecords(t, m, "/fs-triage"), 1) + assert.NotContains(t, strings.Join(srv.requests(), "\n"), "contents/harness/code.yaml", "the built-in code harness is not fetched") + }) + + t.Run("authorization still gates dispatch", func(t *testing.T) { + jiraProdSetVersion(t, "dev", "") + srv := newJiraProdGitHub(t, refs, files) + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n"+jiraProdAllowlist(srv)) + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + + event := jiraCommandEvent(t, "/fs-code") + event.Actor.Role = "read" + records, err := m.Match(context.Background(), event) + require.NoError(t, err) + assert.Empty(t, records, "an actor below the role threshold dispatches nothing") + + event = jiraCommandEvent(t, "/fs-code") + event.Actor.Kind = "bot" + records, err = m.Match(context.Background(), event) + require.NoError(t, err) + assert.Empty(t, records, "the built-in triggers match human actors only") + }) + + t.Run("allowed_remote_resources still restricts the fetch", func(t *testing.T) { + jiraProdSetVersion(t, "dev", "") + srv := newJiraProdGitHub(t, refs, files) + dir := t.TempDir() + // The fixture host is not allowlisted, so no harness is fetched and + // the poll fails rather than matching against nothing. + writeMatcherConfig(t, dir, "version: \"1\"\nallowed_remote_resources:\n - https://raw.githubusercontent.com/fullsend-ai/agents/\n") + + _, err := newCELMatcher(context.Background(), dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "no agents could be loaded") + for _, p := range srv.requests() { + assert.NotContains(t, p, "/contents/", "no file is read from a host the allowlist excludes") + } + }) + + t.Run("an unavailable agents ref fails the poll", func(t *testing.T) { + jiraProdSetVersion(t, "dev", "") + srv := newJiraProdGitHub(t, nil, nil) + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n"+jiraProdAllowlist(srv)) + + _, err := newCELMatcher(context.Background(), dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "no agents could be loaded") + assert.Equal(t, 1, countPrefix(srv.requests(), "/api/v3/repos/fullsend-ai/agents/git/ref/"), "the failed lookup is not retried per built-in") + }) + + t.Run("kill switch reads nothing", func(t *testing.T) { + jiraProdSetVersion(t, "dev", "") + srv := newJiraProdGitHub(t, refs, files) + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\nkill_switch: true\n"+jiraProdAllowlist(srv)) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + names, suppressed := m.DispatchCandidates() + assert.Empty(t, names) + assert.True(t, suppressed) + assert.Empty(t, jiraProdRecords(t, m, "/fs-triage")) + assert.Empty(t, srv.requests(), "the kill switch makes no GitHub request") + }) +} + +func countPrefix(paths []string, prefix string) int { + n := 0 + for _, p := range paths { + if strings.HasPrefix(p, prefix) { + n++ + } + } + return n +} + +func writeHarnessFile(t *testing.T, dir, rel, content string) { + t.Helper() + path := filepath.Join(dir, filepath.FromSlash(rel)) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) +} diff --git a/internal/cli/poll_jira_builtin_test.go b/internal/cli/poll_jira_builtin_test.go new file mode 100644 index 0000000000..3202250d74 --- /dev/null +++ b/internal/cli/poll_jira_builtin_test.go @@ -0,0 +1,647 @@ +package cli + +import ( + "context" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "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/harness" + "github.com/fullsend-ai/fullsend/internal/harnessdispatch" + "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// jiraBuiltinTestRoles are the harness roles of the built-in agents. +var jiraBuiltinTestRoles = map[string]string{ + "triage": "triage", "code": "coder", "review": "review", + "fix": "coder", "retro": "retro", "prioritize": "prioritize", +} + +// jiraCommandTrigger matches a Jira / comment from a human, the +// shape of the built-in triage and code triggers. +func jiraCommandTrigger(command string) string { + return `trigger: > + event.entity.kind == "work_item" + && event.source.system == "jira" + && event.transition.kind == "comment_added" + && has(event.transition.comment.command) + && event.transition.comment.command == "` + command + `" + && event.actor.kind == "human" +` +} + +// jiraBuiltinTestHarness is a built-in agent harness with an optional +// trigger: block. +func jiraBuiltinTestHarness(name, trigger string) string { + return "agent: agents/" + name + ".md\nrole: " + jiraBuiltinTestRoles[name] + "\nslug: fullsend-ai-" + name + + "\nmodel: opus\nimage: ghcr.io/fullsend-ai/fullsend-sandbox:latest\n" + trigger +} + +// defaultJiraBuiltinTriggers gives triage and code their Jira command +// triggers, as the agents release does. +func defaultJiraBuiltinTriggers() map[string]string { + return map[string]string{ + "triage": jiraCommandTrigger("/fs-triage"), + "code": jiraCommandTrigger("/fs-code"), + } +} + +// stubJiraBuiltins makes newCELMatcher resolve built-in agents from local +// harness files instead of the agents repository. triggers maps a built-in +// name to its trigger: block (a nil map means defaultJiraBuiltinTriggers); +// a built-in it does not name gets a harness with no trigger, and one in +// unavailable fails to resolve. It returns the names the resolver was +// asked for. +func stubJiraBuiltins(t *testing.T, triggers map[string]string, unavailable ...string) *[]string { + t.Helper() + if triggers == nil { + triggers = defaultJiraBuiltinTriggers() + } + dir := t.TempDir() + requested := &[]string{} + orig := newJiraBuiltinResolverFn + newJiraBuiltinResolverFn = func() harnessdispatch.BuiltinResolver { + return func(_ context.Context, name string, opts harness.ComposeOpts) (string, harness.ComposeOpts, bool) { + *requested = append(*requested, name) + if slices.Contains(unavailable, name) { + return "", opts, false + } + path := filepath.Join(dir, name+".yaml") + if err := os.WriteFile(path, []byte(jiraBuiltinTestHarness(name, triggers[name])), 0o644); err != nil { + t.Errorf("write %s: %v", path, err) + return "", opts, false + } + return path, opts, true + } + } + t.Cleanup(func() { newJiraBuiltinResolverFn = orig }) + return requested +} + +// jiraCommandEvent returns the normative Jira /fs-triage comment example +// with its command replaced by command. +func jiraCommandEvent(t *testing.T, command string) *normevent.Event { + t.Helper() + raw, err := os.ReadFile(filepath.Join("..", "..", "docs", "normative", "normalized-event", "v1", "examples", "jira-fs-triage-comment.json")) + require.NoError(t, err) + ev, err := normevent.ParseJSON(raw) + require.NoError(t, err) + require.NotNil(t, ev.Transition.Comment) + ev.Transition.Comment.Command = command + ev.Transition.Comment.Body = command + return ev +} + +// matchedAgents returns the agents m dispatches for a Jira comment with +// command. +func matchedAgents(t *testing.T, m *celMatcher, command string) []string { + t.Helper() + records, err := m.Match(context.Background(), jiraCommandEvent(t, command)) + require.NoError(t, err) + var agents []string + for _, r := range records { + agents = append(agents, r.Agent) + } + return agents +} + +func writeMatcherConfig(t *testing.T, dir, yamlText string) { + t.Helper() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(yamlText), 0o644)) +} + +func jiraCandidateNames(m *celMatcher) []string { + names, _ := m.DispatchCandidates() + return names +} + +// TestNewCELMatcher_FreshInstallDispatchesBuiltins is the #9503 +// regression: a config written by setup (roles:, no agents:), or no config +// at all, dispatches the built-in triage and code agents from Jira. +func TestNewCELMatcher_FreshInstallDispatchesBuiltins(t *testing.T) { + for name, configYAML := range map[string]string{ + "roles only": "version: \"1\"\nroles: [triage, coder, review, fix, retro, prioritize]\n", + "roles absent": "version: \"1\"\n", + "no config file": "", + } { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + if configYAML != "" { + writeMatcherConfig(t, dir, configYAML) + } + requested := stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"triage", "code"}, *requested, "only the Jira-capable built-ins are considered, once each") + assert.Equal(t, []string{"triage", "code"}, jiraCandidateNames(m)) + assert.Equal(t, []string{"triage"}, matchedAgents(t, m, "/fs-triage")) + assert.Equal(t, []string{"code"}, matchedAgents(t, m, "/fs-code")) + }) + } +} + +// TestNewCELMatcher_HonorsConfiguredRoles covers the roles: subset: only +// the built-in agents the roles select are fetched and dispatched, so an +// unselected built-in that cannot load does not fail the poll. +func TestNewCELMatcher_HonorsConfiguredRoles(t *testing.T) { + t.Run("roles triage dispatches triage but not code", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\nroles: [triage]\n") + requested := stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"triage"}, *requested, "an unselected built-in is not fetched") + assert.Equal(t, []string{"triage"}, jiraCandidateNames(m)) + assert.Equal(t, []string{"triage"}, matchedAgents(t, m, "/fs-triage")) + assert.Empty(t, matchedAgents(t, m, "/fs-code")) + }) + + t.Run("roles coder dispatches code", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\nroles: [coder]\n") + stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"code"}, jiraCandidateNames(m)) + assert.Equal(t, []string{"code"}, matchedAgents(t, m, "/fs-code")) + assert.Empty(t, matchedAgents(t, m, "/fs-triage")) + }) + + t.Run("an explicitly disabled agent stays disabled", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\nroles: [triage, coder]\nagents:\n - name: code\n enabled: false\n") + requested := stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.NotContains(t, *requested, "code") + assert.Equal(t, []string{"triage"}, jiraCandidateNames(m)) + }) +} + +// TestNewCELMatcher_ShorthandOverrideEntries covers agents: entries with +// no source (ADR 0091, ADR 0162): they tune the built-in agent and keep it +// dispatchable, with harness: blocks composed on the built-in harness. +func TestNewCELMatcher_ShorthandOverrideEntries(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, `version: "1" +agents: + - name: triage + runtime: claude + - name: code + effort: low + harness: + model: sonnet +`) + requested := stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"triage", "code"}, *requested) + require.Equal(t, []string{"triage", "code"}, jiraCandidateNames(m)) + assert.Equal(t, "sonnet", m.Candidates[1].Harness.Model, "harness: block override applies") + assert.Equal(t, []string{"triage"}, matchedAgents(t, m, "/fs-triage")) + assert.Equal(t, []string{"code"}, matchedAgents(t, m, "/fs-code")) +} + +// TestNewCELMatcher_CustomSourcesTakePrecedence covers a source entry +// named after a built-in, which replaces it, and an additional custom +// agent, which is dispatchable beside the built-ins. +func TestNewCELMatcher_CustomSourcesTakePrecedence(t *testing.T) { + dir := t.TempDir() + harnessDir := filepath.Join(dir, "harness") + require.NoError(t, os.MkdirAll(harnessDir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, "code.yaml"), + []byte(strings.Replace(jiraBuiltinTestHarness("code", jiraCommandTrigger("/fs-implement")), "model: opus", "model: haiku", 1)), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, "docs-bot.yaml"), + []byte("agent: agents/docs.md\nrole: triage\nslug: docs-bot\nmodel: opus\nimage: ghcr.io/fullsend-ai/fullsend-sandbox:latest\n"+jiraCommandTrigger("/fs-docs")), 0o644)) + writeMatcherConfig(t, dir, `version: "1" +agents: + - name: code + source: harness/code.yaml + - name: docs-bot + source: harness/docs-bot.yaml +`) + requested := stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.NotContains(t, *requested, "code", "the built-in code harness is not resolved when a source entry replaces it") + assert.Equal(t, []string{"code", "docs-bot", "triage"}, jiraCandidateNames(m)) + assert.Equal(t, "haiku", m.Candidates[0].Harness.Model, "the custom harness is used") + + assert.Empty(t, matchedAgents(t, m, "/fs-code"), "the built-in code trigger is replaced") + assert.Equal(t, []string{"code"}, matchedAgents(t, m, "/fs-implement")) + assert.Equal(t, []string{"docs-bot"}, matchedAgents(t, m, "/fs-docs")) + assert.Equal(t, []string{"triage"}, matchedAgents(t, m, "/fs-triage")) +} + +func TestNewCELMatcher_DisabledAgentsStayDisabled(t *testing.T) { + t.Run("disabled built-in", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\nagents:\n - name: code\n enabled: false\n") + requested := stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.NotContains(t, *requested, "code") + assert.Equal(t, []string{"triage"}, jiraCandidateNames(m)) + assert.Empty(t, matchedAgents(t, m, "/fs-code")) + }) + + t.Run("every candidate disabled", func(t *testing.T) { + dir := t.TempDir() + yamlText := "version: \"1\"\nagents:\n" + for _, name := range config.ValidAgentNames() { + yamlText += " - name: " + name + "\n enabled: false\n" + } + writeMatcherConfig(t, dir, yamlText) + requested := stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Empty(t, *requested, "the fallback does not reintroduce disabled built-ins") + assert.Empty(t, jiraCandidateNames(m)) + assert.Empty(t, matchedAgents(t, m, "/fs-triage")) + assert.Empty(t, matchedAgents(t, m, "/fs-code")) + }) +} + +func TestNewCELMatcher_BuiltinResolutionFailures(t *testing.T) { + t.Run("one built-in unavailable", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n") + stubJiraBuiltins(t, nil, "code") + + // An incomplete matcher would advance the checkpoints past events + // only the unavailable built-in could match, so the poll fails. + _, err := newCELMatcher(context.Background(), dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "some agents could not be loaded") + assert.Contains(t, err.Error(), "built-in agent code") + + // Once the built-in resolves again, its command dispatches. + stubJiraBuiltins(t, nil) + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"triage", "code"}, jiraCandidateNames(m)) + }) + + t.Run("every built-in unavailable", func(t *testing.T) { + // Matching nothing would advance every checkpoint past the + // cycle's events, so the poll fails and retries next cycle. + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n") + stubJiraBuiltins(t, nil, config.ValidAgentNames()...) + + _, err := newCELMatcher(context.Background(), dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "no agents could be loaded") + }) + + t.Run("kill switch resolves nothing", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\nkill_switch: true\n") + requested := stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Empty(t, *requested) + names, suppressed := m.DispatchCandidates() + assert.Empty(t, names) + assert.True(t, suppressed) + }) +} + +// countingRefClient counts GetRef calls on a fake forge client. +type countingRefClient struct { + *forge.FakeClient + getRef atomic.Int32 +} + +func (c *countingRefClient) GetRef(ctx context.Context, owner, repo, refPath string) (string, error) { + c.getRef.Add(1) + return c.FakeClient.GetRef(ctx, owner, repo, refPath) +} + +// TestAgentsRepoBuiltinResolver_VersionPinned resolves built-in agents +// through the agents-repo fallback fullsend run uses: a release build reads +// its own release tag, other builds main, and every built-in is read from +// the one commit the ref resolves to. +func TestAgentsRepoBuiltinResolver_VersionPinned(t *testing.T) { + const sha = "abcdef1234567890abcdef1234567890abcdef12" + var served atomic.Int32 + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + served.Add(1) + switch r.URL.Path { + case "/" + sha + "/harness/triage.yaml": + _, _ = w.Write([]byte(jiraBuiltinTestHarness("triage", jiraCommandTrigger("/fs-triage")))) + case "/" + sha + "/harness/code.yaml": + _, _ = w.Write([]byte(jiraBuiltinTestHarness("code", jiraCommandTrigger("/fs-code")))) + case "/" + sha + "/agents/triage.md", "/" + sha + "/agents/code.md": + _, _ = w.Write([]byte("# agent\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}) + origPrefix := defaultAgentsRepoURLPrefix + defaultAgentsRepoURLPrefix = srv.URL + "/" + t.Cleanup(func() { defaultAgentsRepoURLPrefix = origPrefix }) + + tests := map[string]struct { + version, commit, ref string + }{ + "release build reads its tag": {version: "0.85.0", commit: "abc123def456", ref: "fullsend-ai/agents/tags/v0.85.0"}, + "dev build reads main": {version: "dev", commit: "", ref: "fullsend-ai/agents/heads/main"}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + origVersion, origSHA := version, commitSHA + version, commitSHA = tt.version, tt.commit + t.Cleanup(func() { version, commitSHA = origVersion, origSHA }) + + dir := filepath.Join(t.TempDir(), ".fullsend") + require.NoError(t, os.MkdirAll(dir, 0o755)) + // The server serves only the triage and code harnesses; the + // other built-ins are not Jira dispatch targets, so they are never + // requested and need no disabling. + writeMatcherConfig(t, dir, "version: \"1\"\nallowed_remote_resources:\n - "+srv.URL+"/\n") + cfg, err := config.LoadConfig(dir, config.LoadOpts{MissingOK: true}) + require.NoError(t, err) + + client := &countingRefClient{FakeClient: forge.NewFakeClient()} + client.Refs[tt.ref] = sha + resolver := agentsRepoBuiltinResolver(client, ui.New(io.Discard)) + + candidates, err := harnessdispatch.ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, &policy, resolver) + require.NoError(t, err) + var names []string + for _, c := range candidates { + names = append(names, c.Name) + } + assert.Equal(t, []string{"triage", "code"}, names) + assert.Equal(t, int32(1), client.getRef.Load(), "the agents ref is resolved once per matcher") + }) + } +} + +func TestAgentsRepoBuiltinResolver_Unresolvable(t *testing.T) { + opts := harness.ComposeOpts{WorkspaceRoot: t.TempDir()} + + t.Run("unknown agent or no client", func(t *testing.T) { + client := &countingRefClient{FakeClient: forge.NewFakeClient()} + _, _, ok := agentsRepoBuiltinResolver(client, ui.New(io.Discard))(context.Background(), "custom", opts) + assert.False(t, ok) + assert.Zero(t, client.getRef.Load()) + _, _, ok = agentsRepoBuiltinResolver(nil, ui.New(io.Discard))(context.Background(), "triage", opts) + assert.False(t, ok) + }) + + t.Run("ref lookup fails once for every built-in", func(t *testing.T) { + client := &countingRefClient{FakeClient: forge.NewFakeClient()} + resolve := agentsRepoBuiltinResolver(client, ui.New(io.Discard)) + for _, name := range []string{"triage", "code"} { + _, _, ok := resolve(context.Background(), name, opts) + assert.False(t, ok) + } + assert.Equal(t, int32(1), client.getRef.Load()) + }) +} + +func TestNewJiraBuiltinResolver_Default(t *testing.T) { + assert.NotNil(t, newJiraBuiltinResolverFn()) +} + +// allJiraBuiltinTriggers gives every built-in a Jira command trigger, so a +// test shows which of them the matcher leaves out on purpose. +func allJiraBuiltinTriggers() map[string]string { + triggers := defaultJiraBuiltinTriggers() + for _, name := range []string{"review", "fix", "retro", "prioritize"} { + triggers[name] = jiraCommandTrigger("/fs-" + name) + } + return triggers +} + +// TestNewCELMatcher_UnsupportedBuiltinsNotDispatched covers the built-ins +// the Jira matcher never dispatches: review, fix and retro only act on a +// proposed change and prioritize has no supported Jira path. Their +// harnesses are not fetched, even when they carry a Jira trigger. +func TestNewCELMatcher_UnsupportedBuiltinsNotDispatched(t *testing.T) { + for name, configYAML := range map[string]string{ + "default roles": "version: \"1\"\n", + "every role": "version: \"1\"\nroles: [triage, coder, review, fix, retro, prioritize]\n", + "override-only entries": "version: \"1\"\nagents:\n - name: prioritize\n runtime: claude\n - name: review\n runtime: claude\n", + } { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, configYAML) + requested := stubJiraBuiltins(t, allJiraBuiltinTriggers()) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"triage", "code"}, *requested) + assert.Equal(t, []string{"triage", "code"}, jiraCandidateNames(m)) + assert.Empty(t, matchedAgents(t, m, "/fs-prioritize"), "prioritize has no Jira support yet") + for _, command := range []string{"/fs-review", "/fs-fix", "/fs-retro"} { + assert.Empty(t, matchedAgents(t, m, command), command) + } + assert.Equal(t, []string{"triage"}, matchedAgents(t, m, "/fs-triage")) + assert.Equal(t, []string{"code"}, matchedAgents(t, m, "/fs-code")) + }) + } + + t.Run("an explicitly registered custom agent is still dispatched", func(t *testing.T) { + dir := t.TempDir() + harnessDir := filepath.Join(dir, "harness") + require.NoError(t, os.MkdirAll(harnessDir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, "prioritize.yaml"), + []byte(jiraBuiltinTestHarness("prioritize", jiraCommandTrigger("/fs-prioritize"))), 0o644)) + writeMatcherConfig(t, dir, "version: \"1\"\nagents:\n - name: prioritize\n source: harness/prioritize.yaml\n") + stubJiraBuiltins(t, nil) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"prioritize"}, matchedAgents(t, m, "/fs-prioritize")) + assert.Equal(t, []string{"triage"}, matchedAgents(t, m, "/fs-triage")) + }) +} + +// TestNewCELMatcher_UnrelatedBuiltinsCannotBlockPoll shows an unavailable +// built-in that is not a Jira dispatch target does not fail the poll, while +// an unavailable Jira-capable built-in still does (and a custom source +// needs no fetch for the built-in it replaces). +func TestNewCELMatcher_UnrelatedBuiltinsCannotBlockPoll(t *testing.T) { + t.Run("unsupported built-ins unavailable", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n") + stubJiraBuiltins(t, allJiraBuiltinTriggers(), "review", "fix", "retro", "prioritize") + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Equal(t, []string{"triage"}, matchedAgents(t, m, "/fs-triage")) + assert.Equal(t, []string{"code"}, matchedAgents(t, m, "/fs-code")) + }) + + t.Run("a Jira-capable built-in unavailable still fails the poll", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n") + stubJiraBuiltins(t, allJiraBuiltinTriggers(), "triage") + + _, err := newCELMatcher(context.Background(), dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "built-in agent triage: harness could not be resolved") + assert.Contains(t, err.Error(), "allowed_remote_resources", "the error says where to look") + }) + + t.Run("custom sources need no built-in fetch", func(t *testing.T) { + dir := t.TempDir() + harnessDir := filepath.Join(dir, "harness") + require.NoError(t, os.MkdirAll(harnessDir, 0o755)) + for _, name := range []string{"triage", "code"} { + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, name+".yaml"), + []byte(jiraBuiltinTestHarness(name, jiraCommandTrigger("/fs-"+name))), 0o644)) + } + writeMatcherConfig(t, dir, "version: \"1\"\nagents:\n - name: triage\n source: harness/triage.yaml\n - name: code\n source: harness/code.yaml\n") + requested := stubJiraBuiltins(t, nil, config.ValidAgentNames()...) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Empty(t, *requested) + assert.Equal(t, []string{"triage"}, matchedAgents(t, m, "/fs-triage")) + assert.Equal(t, []string{"code"}, matchedAgents(t, m, "/fs-code")) + }) +} + +// TestNewCELMatcher_RestrictedAgentSourceAccess runs the production +// resolver against a forge client with no access to the agents repository, +// and with allowed_remote_resources: [], using a controlled fixture instead +// of the network. +func TestNewCELMatcher_RestrictedAgentSourceAccess(t *testing.T) { + const sha = "abcdef1234567890abcdef1234567890abcdef12" + useResolver := func(t *testing.T, client forge.Client) { + t.Helper() + orig := newJiraBuiltinResolverFn + newJiraBuiltinResolverFn = func() harnessdispatch.BuiltinResolver { + return agentsRepoBuiltinResolver(client, ui.New(io.Discard)) + } + t.Cleanup(func() { newJiraBuiltinResolverFn = orig }) + } + writeCustomHarnesses := func(t *testing.T, dir string) { + t.Helper() + harnessDir := filepath.Join(dir, "harness") + require.NoError(t, os.MkdirAll(harnessDir, 0o755)) + for _, name := range []string{"triage", "code"} { + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, name+".yaml"), + []byte(jiraBuiltinTestHarness(name, jiraCommandTrigger("/fs-"+name))), 0o644)) + } + } + const customSources = "agents:\n - name: triage\n source: harness/triage.yaml\n - name: code\n source: harness/code.yaml\n" + + t.Run("custom sources poll with no agents repository access", func(t *testing.T) { + dir := t.TempDir() + writeCustomHarnesses(t, dir) + writeMatcherConfig(t, dir, "version: \"1\"\nallowed_remote_resources: []\n"+customSources) + client := &countingRefClient{FakeClient: forge.NewFakeClient()} + useResolver(t, client) + + m, err := newCELMatcher(context.Background(), dir) + require.NoError(t, err) + assert.Zero(t, client.getRef.Load(), "no built-in is looked up") + assert.Equal(t, []string{"triage"}, matchedAgents(t, m, "/fs-triage")) + assert.Equal(t, []string{"code"}, matchedAgents(t, m, "/fs-code")) + }) + + t.Run("a built-in with the agents repository not allowed fails the poll", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\nallowed_remote_resources: []\n") + client := &countingRefClient{FakeClient: forge.NewFakeClient()} + client.Refs["fullsend-ai/agents/heads/main"] = sha + client.Refs["fullsend-ai/agents/tags/v0.85.0"] = sha + useResolver(t, client) + + _, err := newCELMatcher(context.Background(), dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "harness could not be resolved") + }) + + t.Run("an unreachable agents repository fails the poll", func(t *testing.T) { + dir := t.TempDir() + writeMatcherConfig(t, dir, "version: \"1\"\n") + useResolver(t, forge.NewFakeClient()) + + _, err := newCELMatcher(context.Background(), dir) + require.Error(t, err) + assert.Contains(t, err.Error(), "no agents could be loaded") + }) +} + +// TestNewJiraBuiltinResolver_TokenAuth shows the default resolver sends the +// configured GitHub token on the agents-ref lookup, and falls back to an +// anonymous lookup only when no token is available. +func TestNewJiraBuiltinResolver_TokenAuth(t *testing.T) { + var auth atomic.Value + var requests atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + auth.Store(r.Header.Get("Authorization")) + w.WriteHeader(http.StatusNotFound) + })) + t.Cleanup(srv.Close) + origServer := githubServerBaseURLFn + githubServerBaseURLFn = func() string { return srv.URL } + t.Cleanup(func() { githubServerBaseURLFn = origServer }) + t.Setenv("GITHUB_API_URL", srv.URL+"/api/v3") + origAuth := ghAuthTokenFn + ghAuthTokenFn = func() ([]byte, error) { return nil, errGitHubTokenMissing } + t.Cleanup(func() { ghAuthTokenFn = origAuth }) + + lookup := func(t *testing.T) string { + t.Helper() + auth.Store("") + requests.Store(0) + opts := harness.ComposeOpts{WorkspaceRoot: t.TempDir()} + _, _, ok := newJiraBuiltinResolverFn()(context.Background(), "triage", opts) + assert.False(t, ok, "the fixture server has no agents repository") + assert.Positive(t, requests.Load(), "the resolver must attempt the ref lookup") + got, _ := auth.Load().(string) + return got + } + + for _, tt := range []struct { + name, ghToken, githubToken, want string + }{ + {name: "GH_TOKEN", ghToken: "poll-token", want: "Bearer poll-token"}, + {name: "GITHUB_TOKEN", githubToken: "operator-token", want: "Bearer operator-token"}, + {name: "GH_TOKEN takes precedence", ghToken: "poll-token", githubToken: "operator-token", want: "Bearer poll-token"}, + {name: "no token"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("GH_TOKEN", tt.ghToken) + t.Setenv("GITHUB_TOKEN", tt.githubToken) + assert.Equal(t, tt.want, lookup(t)) + }) + } +} diff --git a/internal/cli/poll_jira_gitlab_test.go b/internal/cli/poll_jira_gitlab_test.go index 36ac5869ca..725b6ab1ae 100644 --- a/internal/cli/poll_jira_gitlab_test.go +++ b/internal/cli/poll_jira_gitlab_test.go @@ -158,6 +158,7 @@ func TestPollCmd_JiraPollGitLabAuthFailure(t *testing.T) { require.NoError(t, os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}), 0o600)) clearPollEnv(t) + stubJiraBuiltins(t, nil) t.Setenv("CI_SERVER_TLS_CA_FILE", caFile) t.Setenv(forge.SecretGitLabPollerToken, "bad-tok") t.Setenv("CI_COMMIT_REF_NAME", "main") diff --git a/internal/cli/poll_test.go b/internal/cli/poll_test.go index 81c1675543..f9bc9c6ca3 100644 --- a/internal/cli/poll_test.go +++ b/internal/cli/poll_test.go @@ -147,6 +147,8 @@ trigger: | require.NoError(t, err) require.Equal(t, normevent.SystemJira, ev.Source.System) + // The other built-ins resolve with no trigger, so only code matches. + stubJiraBuiltins(t, map[string]string{}) m, err := newCELMatcher(context.Background(), dir) require.NoError(t, err) records, err := m.Match(context.Background(), ev) @@ -718,6 +720,7 @@ func TestCELMatcher_JiraLabelRule(t *testing.T) { } func TestNewCELMatcher_LoadsJiraAuthorization(t *testing.T) { + stubJiraBuiltins(t, nil) dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" authorization: @@ -769,6 +772,7 @@ authorization: func noJiraEnv(string) string { return "" } func TestJiraPollOptions_ForwardsAuthorization(t *testing.T) { + stubJiraBuiltins(t, nil) dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" authorization: @@ -846,6 +850,7 @@ authorization: } func TestNewCELMatcher_RejectsInvalidAuthorization(t *testing.T) { + stubJiraBuiltins(t, nil) tests := map[string]struct { yaml string wantErr string @@ -887,6 +892,7 @@ func TestJiraPollAuthorization_EmptyListsStayConfigured(t *testing.T) { } func TestNewCELMatcher_NullListKeysStayConfigured(t *testing.T) { + stubJiraBuiltins(t, nil) for name, key := range map[string]string{ "bare write": "write:", "null write": "write: null", @@ -908,6 +914,7 @@ func TestNewCELMatcher_NullListKeysStayConfigured(t *testing.T) { } func TestNewCELMatcher_RejectsAliasedMisspelledJiraKey(t *testing.T) { + stubJiraBuiltins(t, nil) dir := t.TempDir() yamlText := "version: \"1\"\njira_provider: &jp jira\nauthorization:\n - provider: *jp\n lables: allowlist\n" require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(yamlText), 0o644)) diff --git a/internal/cli/run.go b/internal/cli/run.go index 7f54159e75..63da4594fa 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -8481,19 +8481,50 @@ func fetchPinnedAgentsRepoFile(ctx context.Context, relPath string, forgeClient if forgeClient == nil { return "", none, false } + pin, ok := resolveAgentsRepoPin(ctx, forgeClient, printer) + if !ok { + return "", none, false + } + return fetchAgentsRepoFileAtPin(ctx, relPath, pin, forgeClient, composeOpts, printer, noun) +} - allowlist := composeOpts.OrgAllowlist +// agentsRepoPin is the fullsend-ai/agents commit a fallback fetch reads +// from: the commit SHA resolveAgentsRef's ref pointed at, and that ref for +// messages. +type agentsRepoPin struct { + displayRef string + sha string +} +// resolveAgentsRepoPin resolves the agents ref (resolveAgentsRef: the +// release tag of a release build, main otherwise) to a commit SHA. A caller +// that fetches several files resolves the pin once and passes it to +// fetchAgentsRepoFileAtPin for each. Errors are non-fatal and reported as +// warnings. +func resolveAgentsRepoPin(ctx context.Context, forgeClient forge.Client, printer *ui.Printer) (agentsRepoPin, bool) { displayRef, gitRef := resolveAgentsRef() resolvedSHA, err := forgeClient.GetRef(ctx, defaultAgentsRepoOwner, defaultAgentsRepoName, gitRef) if err != nil { printer.StepWarn(fmt.Sprintf("Could not resolve %s/%s@%s: %v", defaultAgentsRepoOwner, defaultAgentsRepoName, displayRef, err)) - return "", none, false + return agentsRepoPin{}, false } if !commitSHAPattern.MatchString(resolvedSHA) { printer.StepWarn(fmt.Sprintf("Invalid SHA from %s/%s@%s: %q", defaultAgentsRepoOwner, defaultAgentsRepoName, displayRef, resolvedSHA)) + return agentsRepoPin{}, false + } + return agentsRepoPin{displayRef: displayRef, sha: resolvedSHA}, true +} + +// fetchAgentsRepoFileAtPin fetches relPath from fullsend-ai/agents at the +// pinned commit, subject to the allowlist in composeOpts. All errors are +// non-fatal. +func fetchAgentsRepoFileAtPin(ctx context.Context, relPath string, pin agentsRepoPin, forgeClient forge.Client, composeOpts harness.ComposeOpts, printer *ui.Printer, noun string) (string, harness.Dependency, bool) { + var none harness.Dependency + if strings.Contains(relPath, "..") || strings.HasPrefix(relPath, "/") { return "", none, false } + allowlist := composeOpts.OrgAllowlist + displayRef, resolvedSHA := pin.displayRef, pin.sha hostPrefix := agentsRepoHostURLPrefix(forgeClient) rawURL := defaultAgentsRepoURLPrefix + resolvedSHA + "/" + relPath @@ -8513,6 +8544,7 @@ func fetchPinnedAgentsRepoFile(ctx context.Context, relPath string, forgeClient printer.StepStart(fmt.Sprintf("Fetching %s from %s/%s@%s", noun, defaultAgentsRepoOwner, defaultAgentsRepoName, shortSHA)) var content []byte + var err error if hostPrefix != "" { // A host other than github.com has no raw.githubusercontent.com, // so read the file through the same client that resolved the ref. diff --git a/internal/config/config.go b/internal/config/config.go index 273bd70e05..f18de9229b 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -744,6 +744,38 @@ func ValidAgentNames() []string { return []string{"triage", "code", "review", "fix", "retro", "prioritize"} } +// builtinAgentRoles maps each built-in agent (ValidAgentNames) to the roles: +// values that enable it. Agent names and roles differ for code (role coder), +// and the fix stage reuses the coder app, so either fix or coder enables it +// (see DefaultAgentRoles). +var builtinAgentRoles = map[string][]string{ + "triage": {"triage"}, + "code": {"coder"}, + "review": {"review"}, + "fix": {"fix", "coder"}, + "retro": {"retro"}, + "prioritize": {"prioritize"}, +} + +// BuiltinAgentSelected reports whether the configured roles (ConfigRoles, +// the roles: key or `--agents` at setup) select the built-in agent name. +// Only nil roles (the key omitted) means roles are not configured, and every +// built-in agent is selected. A non-nil empty list is an explicit +// `roles: []` and selects no built-in agent. A name that is not a built-in +// agent is always selected, since roles do not scope custom agents. +func BuiltinAgentSelected(name string, roles []string) bool { + if roles == nil { + return true + } + enabling, ok := builtinAgentRoles[strings.ToLower(name)] + if !ok { + return true + } + return slices.ContainsFunc(roles, func(r string) bool { + return slices.Contains(enabling, strings.TrimSpace(r)) + }) +} + // validEffortLevels are the reasoning effort levels accepted by the claude // CLI's --effort flag (the version pinned by CLAUDE_CODE_VERSION in // images/sandbox/Containerfile). The CLI also documents an "ultracode" diff --git a/internal/config/config_test.go b/internal/config/config_test.go index dcc34b380c..a43ee8041c 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -2383,3 +2383,35 @@ func TestPerRepoConfig_LocalAgentEntries(t *testing.T) { assert.Equal(t, []AgentEntry{{Name: "code", Model: "sonnet"}}, local, "only the overlay's own entries") assert.Len(t, cfg.AgentEntries(), 2, "merged view includes the base") } + +func TestBuiltinAgentSelected(t *testing.T) { + cases := []struct { + name string + agent string + roles []string + want bool + }{ + {"no roles selects every built-in", "code", nil, true}, + {"empty roles selects no built-in", "code", []string{}, false}, + {"empty roles selects no triage", "triage", []string{}, false}, + {"empty roles still selects a custom agent", "my-agent", []string{}, true}, + {"triage role selects triage", "triage", []string{"triage"}, true}, + {"triage role does not select code", "code", []string{"triage"}, false}, + {"coder role selects code", "code", []string{"coder"}, true}, + {"code is not a role", "code", []string{"code"}, false}, + {"coder role selects fix", "fix", []string{"coder"}, true}, + {"fix role selects fix", "fix", []string{"fix"}, true}, + {"fix role does not select code", "code", []string{"fix"}, false}, + {"agent name is case-insensitive", "Code", []string{"coder"}, true}, + {"custom agent is not scoped by roles", "my-agent", []string{"triage"}, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, BuiltinAgentSelected(tc.agent, tc.roles)) + }) + } + for _, agent := range ValidAgentNames() { + _, ok := builtinAgentRoles[agent] + assert.True(t, ok, "built-in agent %q has a role mapping", agent) + } +} diff --git a/internal/harnessdispatch/enumerate.go b/internal/harnessdispatch/enumerate.go index e68a072659..675228e46c 100644 --- a/internal/harnessdispatch/enumerate.go +++ b/internal/harnessdispatch/enumerate.go @@ -7,6 +7,7 @@ import ( "io" "os" "path/filepath" + "slices" "strings" "github.com/fullsend-ai/fullsend/internal/config" @@ -14,6 +15,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/forge" "github.com/fullsend-ai/fullsend/internal/harness" "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/internal/workflowcmd" ) // annotationWriter is the destination for GitHub Actions workflow command @@ -39,11 +41,111 @@ type TriggeredHarness struct { // returned so a fully-unreadable harness set is not indistinguishable from // "no trigger matched". func ListTriggeredHarnesses(ctx context.Context, configDir string, cfg config.ConfigReader, fetchPolicy *fetch.FetchPolicy) ([]TriggeredHarness, error) { + return listTriggeredHarnesses(ctx, configDir, cfg, fetchPolicy, nil) +} + +// BuiltinResolver resolves a built-in agent (config.ValidAgentNames) to a +// local harness path when no agents: entry registers it with a source. It +// receives the compose options ListEffectiveTriggeredHarnesses loads +// harnesses with and returns the options to load this harness with (for +// example with SourceURL set when it was fetched from a URL). ok is false +// when the harness could not be resolved; the resolver reports why. +type BuiltinResolver func(ctx context.Context, name string, opts harness.ComposeOpts) (path string, loadOpts harness.ComposeOpts, ok bool) + +// ListEffectiveTriggeredHarnesses returns the triggered harnesses of every +// agent the config makes effective, for a dispatcher with no stage routing +// of its own, such as the Jira poller: the agents registered with a source, +// as ListTriggeredHarnesses lists them, plus each built-in agent that no +// such entry registers, resolved with builtin. An entry with no source (it +// only tunes the agent, ADR 0091) does not replace the built-in harness, so +// the built-in is listed with the entry's harness: blocks applied. An agent +// whose last agents: entry disables it is not listed, whether registered +// or built-in, and each agent is listed at most once. Only the built-in +// agents in effectiveDispatchBuiltinAgents (triage and code) are listed; +// review, fix, retro and prioritize are never dispatched this way. When the +// config sets roles:, only the built-in agents those roles select are listed +// (code is selected by coder); agents registered with a source are not +// scoped by roles or by that set. +// +// Unlike ListTriggeredHarnesses, any failure is an error: an agent that +// cannot be resolved or loaded (registered or built-in) is also logged as an +// error annotation, but the list is not returned incomplete. A dispatcher +// that advances its checkpoints past events no agent matched, such as the +// Jira poller, would otherwise lose the events only the unavailable agent +// could match. Failing the run lets the next run retry them. +func ListEffectiveTriggeredHarnesses(ctx context.Context, configDir string, cfg config.ConfigReader, fetchPolicy *fetch.FetchPolicy, builtin BuiltinResolver) ([]TriggeredHarness, error) { + if builtin == nil { + return nil, fmt.Errorf("built-in agent resolver is required") + } + return listTriggeredHarnesses(ctx, configDir, cfg, fetchPolicy, builtin) +} + +// effectiveDispatchBuiltinAgents are the built-in agents (a subset of +// config.ValidAgentNames) a dispatcher with no stage routing, such as the +// Jira poller, dispatches without an agents: registration. The others are +// not Jira dispatch targets: review, fix and retro only act on a proposed +// change, and prioritize has no supported Jira path yet. They are never +// resolved or fetched, so one that cannot load cannot fail the poll. An +// agent registered with a source: is not restricted by this list. +var effectiveDispatchBuiltinAgents = []string{"triage", "code"} + +// EffectiveDispatchBuiltinAgents returns the built-in agent names +// ListEffectiveTriggeredHarnesses may list without an agents: source entry. +func EffectiveDispatchBuiltinAgents() []string { + return slices.Clone(effectiveDispatchBuiltinAgents) +} + +// effectiveBuiltinAgents returns the built-in agents +// (effectiveDispatchBuiltinAgents) that registered does not already list, +// that the configured roles select (config.BuiltinAgentSelected) and that no +// agents: entry disables, in ValidAgentNames order. An unsupported or +// unselected built-in is dropped here, before anything resolves or fetches +// its harness. +func effectiveBuiltinAgents(entries []config.AgentEntry, registered []harness.RegisteredAgent, roles []string) []string { + var out []string + for _, name := range config.ValidAgentNames() { + if !slices.Contains(effectiveDispatchBuiltinAgents, name) { + continue + } + if !config.BuiltinAgentSelected(name, roles) { + continue + } + if config.IsAgentExplicitlyDisabled(entries, name) { + continue + } + if slices.ContainsFunc(registered, func(a harness.RegisteredAgent) bool { + return strings.EqualFold(a.Name, name) + }) { + continue + } + out = append(out, name) + } + return out +} + +// listTriggeredHarnesses implements ListTriggeredHarnesses and, with a +// non-nil builtin, ListEffectiveTriggeredHarnesses. +func listTriggeredHarnesses(ctx context.Context, configDir string, cfg config.ConfigReader, fetchPolicy *fetch.FetchPolicy, builtin BuiltinResolver) ([]TriggeredHarness, error) { registered, err := harness.RegisteredAgents(cfg) if err != nil { return nil, err } - if len(registered) == 0 { + entries := cfg.AgentEntries() + var builtins []string + if builtin != nil { + // RegisteredAgents keeps every enabled entry with a source, even + // one a later entry disables; the effective list honors the last + // entry for the name. + registered = slices.DeleteFunc(registered, func(a harness.RegisteredAgent) bool { + return config.IsAgentExplicitlyDisabled(entries, a.Name) + }) + var roles []string + if pr, ok := cfg.(config.PerRepoConfigReader); ok { + roles = pr.ConfigRoles() + } + builtins = effectiveBuiltinAgents(entries, registered, roles) + } + if len(registered) == 0 && len(builtins) == 0 { return nil, nil } @@ -56,14 +158,30 @@ func ListTriggeredHarnesses(ctx context.Context, configDir string, cfg config.Co composeOpts := newComposeOpts(configDir, cfg, allowlist, policy) - entries := cfg.AgentEntries() var out []TriggeredHarness var loadErrs []error loaded := 0 + // load composes one agent's harness with its entry's harness: blocks + // (ADR 0162), which may override the trigger, and records the result. + load := func(name, path string, loadOpts harness.ComposeOpts) { + loadOpts.Blocks = config.HarnessBlocksFor(entries, name) + loadOpts.Agent = name + h, _, err := harness.LoadWithBase(ctx, path, loadOpts) + if err != nil { + fmt.Fprintf(annotationWriter, "::error::harness dispatch: skipping agent %s: load failed: %s\n", workflowcmd.SanitizeAnnotation(name), workflowcmd.SanitizeAnnotation(err.Error())) + loadErrs = append(loadErrs, fmt.Errorf("agent %s: load failed: %w", name, err)) + return + } + loaded++ + if strings.TrimSpace(h.Trigger) == "" { + return + } + out = append(out, TriggeredHarness{Name: name, Harness: h, Path: path}) + } for _, agent := range registered { resolved, err := harness.ResolveRegisteredPath(ctx, configDir, agent.Entry, allowlist, composeOpts) if err != nil { - fmt.Fprintf(annotationWriter, "::error::harness dispatch: skipping agent %s: resolve failed: %v\n", agent.Name, err) + fmt.Fprintf(annotationWriter, "::error::harness dispatch: skipping agent %s: resolve failed: %s\n", workflowcmd.SanitizeAnnotation(agent.Name), workflowcmd.SanitizeAnnotation(err.Error())) loadErrs = append(loadErrs, fmt.Errorf("agent %s: resolve failed: %w", agent.Name, err)) continue } @@ -75,20 +193,16 @@ func ListTriggeredHarnesses(ctx context.Context, configDir string, cfg config.Co if harness.IsURL(agent.Entry.Source) { loadOpts.SourceURL = agent.Entry.Source } - // The entry's harness: blocks may override the trigger (ADR 0162). - loadOpts.Blocks = config.HarnessBlocksFor(entries, agent.Name) - loadOpts.Agent = agent.Name - h, _, err := harness.LoadWithBase(ctx, resolved.Path, loadOpts) - if err != nil { - fmt.Fprintf(annotationWriter, "::error::harness dispatch: skipping agent %s: load failed: %v\n", agent.Name, err) - loadErrs = append(loadErrs, fmt.Errorf("agent %s: load failed: %w", agent.Name, err)) - continue - } - loaded++ - if strings.TrimSpace(h.Trigger) == "" { + load(agent.Name, resolved.Path, loadOpts) + } + for _, name := range builtins { + path, loadOpts, ok := builtin(ctx, name, composeOpts) + if !ok { + fmt.Fprintf(annotationWriter, "::error::harness dispatch: skipping built-in agent %s: its harness could not be resolved\n", workflowcmd.SanitizeAnnotation(name)) + loadErrs = append(loadErrs, fmt.Errorf("built-in agent %s: harness could not be resolved (check access to fullsend-ai/agents and allowed_remote_resources, or register the agent with a source:)", name)) continue } - out = append(out, TriggeredHarness{Name: agent.Name, Harness: h, Path: resolved.Path}) + load(name, path, loadOpts) } // Each failure above was already written as a ::error:: annotation, and // its text is also folded into the aggregated error returned here. That @@ -96,10 +210,16 @@ func ListTriggeredHarnesses(ctx context.Context, configDir string, cfg config.Co // annotations surface inline in the GitHub Actions UI next to the step // that produced them, while the aggregated error drives dispatch's // non-zero exit and appears in the plain-text CI log/exit trace. Partial - // failures (loaded > 0) keep the annotation-only behavior unchanged. + // failures (loaded > 0) keep the annotation-only behavior unchanged, + // except for the effective list below. if loaded == 0 && len(loadErrs) > 0 { return nil, fmt.Errorf("no agents could be loaded: %w", errors.Join(loadErrs...)) } + // With a built-in resolver (the effective list) a partial failure is + // also an error, so the caller never matches against an incomplete list. + if builtin != nil && len(loadErrs) > 0 { + return nil, fmt.Errorf("some agents could not be loaded: %w", errors.Join(loadErrs...)) + } return out, nil } @@ -127,7 +247,7 @@ func MatchHarnesses(candidates []TriggeredHarness, event *normevent.Event) ([]Tr for _, c := range candidates { ok, err := harness.EvaluateTrigger(c.Harness.Trigger, eventMap) if err != nil { - fmt.Fprintf(annotationWriter, "::error::harness dispatch: skipping agent %s: trigger eval failed: %v\n", c.Name, err) + fmt.Fprintf(annotationWriter, "::error::harness dispatch: skipping agent %s: trigger eval failed: %s\n", workflowcmd.SanitizeAnnotation(c.Name), workflowcmd.SanitizeAnnotation(err.Error())) continue } if ok { diff --git a/internal/harnessdispatch/enumerate_effective_test.go b/internal/harnessdispatch/enumerate_effective_test.go new file mode 100644 index 0000000000..636aa7b19b --- /dev/null +++ b/internal/harnessdispatch/enumerate_effective_test.go @@ -0,0 +1,369 @@ +package harnessdispatch + +import ( + "context" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/harness" +) + +// builtinStub resolves built-in agents to local harness files with the +// given triggers (a built-in missing from triggers gets no trigger) and +// records each name it is asked for. A name in unavailable fails to +// resolve. +type builtinStub struct { + t *testing.T + dir string + triggers map[string]string + unavailable []string + requested []string +} + +func newBuiltinStub(t *testing.T, triggers map[string]string, unavailable ...string) *builtinStub { + return &builtinStub{t: t, dir: t.TempDir(), triggers: triggers, unavailable: unavailable} +} + +func (s *builtinStub) resolve(_ context.Context, name string, opts harness.ComposeOpts) (string, harness.ComposeOpts, bool) { + s.requested = append(s.requested, name) + if slices.Contains(s.unavailable, name) { + return "", opts, false + } + body := "agent: agents/" + name + ".md\nrole: " + name + "\nslug: fullsend-ai-" + name + + "\nmodel: opus\nimage: ghcr.io/fullsend-ai/fullsend-sandbox:latest\n" + if trig := s.triggers[name]; trig != "" { + body += "trigger: " + trig + "\n" + } + path := filepath.Join(s.dir, name+".yaml") + require.NoError(s.t, os.WriteFile(path, []byte(body), 0o644)) + return path, opts, true +} + +func loadYAMLConfig(t *testing.T, dir, yamlText string) config.ConfigReader { + t.Helper() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(yamlText), 0o644)) + cfg, err := config.LoadConfig(dir, config.LoadOpts{MissingOK: true}) + require.NoError(t, err) + return cfg +} + +func candidateNames(c []TriggeredHarness) []string { + var names []string + for _, h := range c { + names = append(names, h.Name) + } + return names +} + +const effectiveTestTrigger = `"event.source.system == 'jira'"` + +func TestListEffectiveTriggeredHarnesses_NoAgentsListsBuiltins(t *testing.T) { + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\n") + stub := newBuiltinStub(t, map[string]string{"triage": effectiveTestTrigger, "code": effectiveTestTrigger}) + + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"triage", "code"}, candidateNames(out)) + assert.Equal(t, EffectiveDispatchBuiltinAgents(), stub.requested, "without roles every dispatchable built-in is considered once") + assert.Equal(t, []string{"triage", "code"}, EffectiveDispatchBuiltinAgents()) + + // The GitHub dispatch path keeps listing only source-registered agents. + gh, err := ListTriggeredHarnesses(context.Background(), dir, cfg, nil) + require.NoError(t, err) + assert.Empty(t, gh) +} + +func TestListEffectiveTriggeredHarnesses_OverrideOnlyEntryAppliesBlocks(t *testing.T) { + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, `version: "1" +agents: + - name: triage + runtime: claude + - name: code + harness: + model: sonnet +`) + stub := newBuiltinStub(t, map[string]string{"triage": effectiveTestTrigger, "code": effectiveTestTrigger}) + + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + require.Equal(t, []string{"triage", "code"}, candidateNames(out)) + assert.Equal(t, "opus", out[0].Harness.Model) + assert.Equal(t, "sonnet", out[1].Harness.Model, "the entry's harness: block composes on the built-in harness") +} + +func TestListEffectiveTriggeredHarnesses_SourceEntryReplacesBuiltin(t *testing.T) { + dir := t.TempDir() + harnessDir := filepath.Join(dir, "harness") + require.NoError(t, os.MkdirAll(harnessDir, 0o755)) + custom := "agent: agents/x.md\nrole: coder\nslug: custom\nmodel: haiku\nimage: ghcr.io/fullsend-ai/fullsend-sandbox:latest\ntrigger: " + effectiveTestTrigger + "\n" + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, "code.yaml"), []byte(custom), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, "extra.yaml"), []byte(custom), 0o644)) + cfg := loadYAMLConfig(t, dir, `version: "1" +agents: + - name: Code + source: harness/code.yaml + - name: extra + source: harness/extra.yaml +`) + stub := newBuiltinStub(t, map[string]string{"triage": effectiveTestTrigger, "code": effectiveTestTrigger}) + + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"Code", "extra", "triage"}, candidateNames(out)) + assert.NotContains(t, stub.requested, "code", "a source entry replaces the built-in, case-insensitively") + assert.Equal(t, "haiku", out[0].Harness.Model) +} + +func TestListEffectiveTriggeredHarnesses_DisabledAgents(t *testing.T) { + t.Run("disabled built-in", func(t *testing.T) { + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\nagents:\n - name: code\n enabled: false\n") + stub := newBuiltinStub(t, map[string]string{"triage": effectiveTestTrigger, "code": effectiveTestTrigger}) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"triage"}, candidateNames(out)) + assert.NotContains(t, stub.requested, "code") + }) + + t.Run("source entry disabled by a later entry", func(t *testing.T) { + dir := t.TempDir() + harnessDir := filepath.Join(dir, "harness") + require.NoError(t, os.MkdirAll(harnessDir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, "code.yaml"), []byte("agent: agents/x.md\nrole: coder\nslug: custom\nmodel: haiku\nimage: ghcr.io/fullsend-ai/fullsend-sandbox:latest\ntrigger: "+effectiveTestTrigger+"\n"), 0o644)) + cfg := loadYAMLConfig(t, dir, `version: "1" +agents: + - name: code + source: harness/code.yaml + - name: code + enabled: false +`) + stub := newBuiltinStub(t, map[string]string{"code": effectiveTestTrigger}) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Empty(t, out) + assert.NotContains(t, stub.requested, "code") + }) + + t.Run("every built-in disabled", func(t *testing.T) { + dir := t.TempDir() + yamlText := "version: \"1\"\nagents:\n" + for _, name := range config.ValidAgentNames() { + yamlText += " - name: " + name + "\n enabled: false\n" + } + cfg := loadYAMLConfig(t, dir, yamlText) + stub := newBuiltinStub(t, map[string]string{"triage": effectiveTestTrigger}) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Empty(t, out) + assert.Empty(t, stub.requested, "no disabled built-in is resolved") + }) +} + +func TestListEffectiveTriggeredHarnesses_ResolveFailures(t *testing.T) { + t.Run("partial failure is annotated and an error", func(t *testing.T) { + buf := captureAnnotations(t) + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\n") + stub := newBuiltinStub(t, map[string]string{"triage": effectiveTestTrigger, "code": effectiveTestTrigger}, "code") + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.Error(t, err) + assert.Nil(t, out, "an incomplete list is never returned") + assert.Contains(t, err.Error(), "some agents could not be loaded") + assert.Contains(t, err.Error(), "built-in agent code: harness could not be resolved") + assert.Contains(t, buf.String(), "::error::harness dispatch: skipping built-in agent code: its harness could not be resolved") + }) + + t.Run("total failure is an error", func(t *testing.T) { + captureAnnotations(t) + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\n") + stub := newBuiltinStub(t, nil, config.ValidAgentNames()...) + _, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.Error(t, err) + assert.Contains(t, err.Error(), "no agents could be loaded") + assert.Contains(t, err.Error(), "built-in agent triage: harness could not be resolved") + }) + + t.Run("built-in load failure is annotated", func(t *testing.T) { + buf := captureAnnotations(t) + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\n") + stub := newBuiltinStub(t, map[string]string{"triage": effectiveTestTrigger}) + resolve := func(ctx context.Context, name string, opts harness.ComposeOpts) (string, harness.ComposeOpts, bool) { + if name == "code" { + return filepath.Join(dir, "missing.yaml"), opts, true + } + return stub.resolve(ctx, name, opts) + } + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, resolve) + require.Error(t, err) + assert.Nil(t, out) + assert.Contains(t, err.Error(), "some agents could not be loaded") + assert.Contains(t, buf.String(), "::error::harness dispatch: skipping agent code: load failed") + }) +} + +func TestListEffectiveTriggeredHarnesses_UnsupportedBuiltinsNeverListed(t *testing.T) { + captureAnnotations(t) + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\n") + triggers := map[string]string{} + for _, name := range config.ValidAgentNames() { + triggers[name] = effectiveTestTrigger + } + // Every built-in outside the dispatchable set is unavailable; none of + // them is requested, so none can fail the listing. + stub := newBuiltinStub(t, triggers, "review", "fix", "retro", "prioritize") + + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"triage", "code"}, candidateNames(out)) + assert.Equal(t, []string{"triage", "code"}, stub.requested) +} + +func TestListEffectiveTriggeredHarnesses_RequiresResolver(t *testing.T) { + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\n") + _, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, nil) + require.Error(t, err) +} + +func TestListEffectiveTriggeredHarnesses_Roles(t *testing.T) { + triggers := map[string]string{"triage": effectiveTestTrigger, "code": effectiveTestTrigger} + + t.Run("roles triage selects triage but not code", func(t *testing.T) { + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\nroles: [triage]\n") + stub := newBuiltinStub(t, triggers) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"triage"}, candidateNames(out)) + assert.Equal(t, []string{"triage"}, stub.requested, "an unselected built-in is never resolved") + }) + + t.Run("empty roles selects and fetches no built-in", func(t *testing.T) { + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\nroles: []\n") + stub := newBuiltinStub(t, triggers) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Empty(t, out) + assert.Empty(t, stub.requested, "no built-in is resolved when roles is explicitly empty") + }) + + t.Run("overlay roles [] over a base that selects roles selects no built-in", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte("version: \"1\"\nroles: [triage, coder]\n"), 0o644)) + cfg := loadYAMLConfig(t, dir, "version: \"1\"\nroles: []\n") + stub := newBuiltinStub(t, triggers) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Empty(t, out) + assert.Empty(t, stub.requested) + }) + + // Omitted, `roles: null` and a bare `roles:` all decode to a nil slice, + // which means "inherit"; only an explicit `roles: []` selects nothing. + // The null forms are intentionally not treated as an empty selection. + inheritForms := []struct { + name string + yaml string + }{ + {"omitted roles", "version: \"1\"\n"}, + {"roles null", "version: \"1\"\nroles: null\n"}, + {"bare roles", "version: \"1\"\nroles:\n"}, + } + for _, form := range inheritForms { + t.Run(form.name+" inherits the parent selection", func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte("version: \"1\"\nroles: [triage]\n"), 0o644)) + cfg := loadYAMLConfig(t, dir, form.yaml) + stub := newBuiltinStub(t, triggers) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"triage"}, candidateNames(out)) + assert.Equal(t, []string{"triage"}, stub.requested, "the parent's roles still scope the built-ins") + }) + + t.Run(form.name+" without a parent selects every built-in", func(t *testing.T) { + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, form.yaml) + stub := newBuiltinStub(t, triggers) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"triage", "code"}, candidateNames(out)) + assert.Equal(t, []string{"triage", "code"}, stub.requested, "no roles means the default selection") + }) + } + + t.Run("roles coder selects code", func(t *testing.T) { + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\nroles: [coder]\n") + stub := newBuiltinStub(t, triggers) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"code"}, candidateNames(out)) + assert.Equal(t, []string{"code"}, stub.requested, "coder also selects fix, but fix is not a dispatchable built-in") + }) + + t.Run("an unselected built-in that cannot load does not fail the poll", func(t *testing.T) { + captureAnnotations(t) + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\nroles: [triage]\n") + stub := newBuiltinStub(t, triggers, "code", "review", "fix", "retro", "prioritize") + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"triage"}, candidateNames(out)) + assert.NotContains(t, stub.requested, "code") + }) + + t.Run("a selected built-in that cannot load still fails the poll", func(t *testing.T) { + captureAnnotations(t) + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\nroles: [triage, coder]\n") + stub := newBuiltinStub(t, triggers, "code") + _, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.Error(t, err) + assert.Contains(t, err.Error(), "built-in agent code: harness could not be resolved") + }) + + t.Run("an explicitly disabled agent stays disabled", func(t *testing.T) { + dir := t.TempDir() + cfg := loadYAMLConfig(t, dir, "version: \"1\"\nroles: [triage, coder]\nagents:\n - name: code\n enabled: false\n") + stub := newBuiltinStub(t, triggers) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"triage"}, candidateNames(out)) + assert.NotContains(t, stub.requested, "code") + }) + + t.Run("custom-source agents are not scoped by roles", func(t *testing.T) { + dir := t.TempDir() + harnessDir := filepath.Join(dir, "harness") + require.NoError(t, os.MkdirAll(harnessDir, 0o755)) + custom := "agent: agents/x.md\nrole: coder\nslug: custom\nmodel: haiku\nimage: ghcr.io/fullsend-ai/fullsend-sandbox:latest\ntrigger: " + effectiveTestTrigger + "\n" + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, "code.yaml"), []byte(custom), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(harnessDir, "extra.yaml"), []byte(custom), 0o644)) + cfg := loadYAMLConfig(t, dir, `version: "1" +roles: [triage] +agents: + - name: code + source: harness/code.yaml + - name: extra + source: harness/extra.yaml +`) + stub := newBuiltinStub(t, triggers) + out, err := ListEffectiveTriggeredHarnesses(context.Background(), dir, cfg, nil, stub.resolve) + require.NoError(t, err) + assert.Equal(t, []string{"code", "extra", "triage"}, candidateNames(out)) + assert.Equal(t, []string{"triage"}, stub.requested) + }) +} diff --git a/internal/harnessdispatch/enumerate_test.go b/internal/harnessdispatch/enumerate_test.go index 4322ec78bd..03be4d2eb0 100644 --- a/internal/harnessdispatch/enumerate_test.go +++ b/internal/harnessdispatch/enumerate_test.go @@ -611,6 +611,27 @@ func TestMatchHarnesses_TriggerEvalFailureAnnotation(t *testing.T) { assert.Contains(t, annotation, "trigger eval failed") } +// Dynamic text in an ::error:: annotation (agent name and error text) must +// not be able to end the line and start another workflow command. +func TestMatchHarnesses_TriggerEvalFailureAnnotationSanitized(t *testing.T) { + buf := captureAnnotations(t) + + ev := mustEvent(t, "issue-opened.json") + matched, err := MatchHarnesses([]TriggeredHarness{{ + Name: "evil\n::error::spoofed", + Harness: &harness.Harness{Trigger: "!!!\n::set-output name=a::b"}, + }}, ev) + require.NoError(t, err) + assert.Empty(t, matched) + + annotation := buf.String() + assert.Equal(t, 1, strings.Count(annotation, "\n"), "annotation must be a single line: %q", annotation) + assert.True(t, strings.HasSuffix(annotation, "\n")) + assert.NotContains(t, annotation, "::spoofed") + assert.NotContains(t, annotation, "::set-output") + assert.Contains(t, annotation, "%0A") +} + func TestDispatch_PRMatch(t *testing.T) { dir := t.TempDir() harnessDir := filepath.Join(dir, "harness") diff --git a/internal/jirapoll/nomatch.go b/internal/jirapoll/nomatch.go new file mode 100644 index 0000000000..845250f042 --- /dev/null +++ b/internal/jirapoll/nomatch.go @@ -0,0 +1,99 @@ +package jirapoll + +import ( + "fmt" + "io" + "os" + "strings" + + "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/internal/workflowcmd" +) + +// annotationWriter is where the poller writes GitHub Actions workflow +// command annotations (::warning::). It defaults to os.Stderr; tests +// replace it to capture output. An annotation must start a line, so it is +// written directly rather than through the log package's prefixed output. +var annotationWriter io.Writer = os.Stderr + +// maxNoMatchEvents bounds how many unmatched events the no-match warning +// lists, keeping the single-line annotation readable on a busy cycle. +const maxNoMatchEvents = 10 + +// CandidateReporter is optionally implemented by an EventMatcher so the +// poller can name the agents it considered in its no-match warning. +type CandidateReporter interface { + // DispatchCandidates returns the names of the agents the matcher + // evaluates events against, and whether it drops every event on + // purpose (an active kill switch), in which case no warning is due. + DispatchCandidates() (agents []string, suppressed bool) +} + +// unmatchedEvent is a validated event of the cycle for which the matcher +// returned no dispatch record. +type unmatchedEvent struct { + issueKey string + event string +} + +// describeEvent summarizes a normalized event for the no-match warning: its +// transition kind and, where present, the comment's slash command or the +// label change. +func describeEvent(ne *normevent.Event) string { + desc := string(ne.Transition.Kind) + switch { + case ne.Transition.Comment != nil && ne.Transition.Comment.Command != "": + desc += " " + ne.Transition.Comment.Command + case ne.Transition.Label != nil: + desc += " " + ne.Transition.Label.Name + " " + ne.Transition.Label.Action + } + return desc +} + +// looksLikeRequest reports whether an event reads as a request for an agent: +// a comment carrying a /fs-* slash command, or a label change (a trigger +// label). Other events, such as an ordinary comment, are expected to match +// no agent, so they are not counted toward the no-match warning. +func looksLikeRequest(ne *normevent.Event) bool { + if ne.Transition.Comment != nil && ne.Transition.Comment.Command != "" { + return true + } + return ne.Transition.Label != nil +} + +// warnNoMatch writes a ::warning:: annotation when the cycle selected +// issues and evaluated events on them, but no agent matched any event, so +// nothing was dispatched (#9503). It names each unmatched event (bounded by +// maxNoMatchEvents), the agents the matcher considered, and what to check. +// It writes nothing when the cycle dispatched work, when no event was +// evaluated (the selected issues had no new activity), or when the matcher +// drops every event on purpose. +func (p *Poller) warnNoMatch(selected int) { + if selected == 0 || len(p.dispatches) > 0 || len(p.unmatched) == 0 { + return + } + agentsClause := "" + if r, ok := p.matcher.(CandidateReporter); ok { + agents, suppressed := r.DispatchCandidates() + if suppressed { + return + } + considered := "none" + if len(agents) > 0 { + considered = workflowcmd.SanitizeAnnotation(strings.Join(agents, ", ")) + } + agentsClause = " Agents considered: " + considered + "." + } + events := make([]string, 0, min(len(p.unmatched), maxNoMatchEvents)) + for i, u := range p.unmatched { + if i == maxNoMatchEvents { + events = append(events, fmt.Sprintf("and %d more", len(p.unmatched)-maxNoMatchEvents)) + break + } + events = append(events, workflowcmd.SanitizeAnnotation(u.issueKey+" ("+u.event+")")) + } + fmt.Fprintf(annotationWriter, "::warning::jira-poll: selected %d issue(s) but no agent matched any of their events, so nothing was dispatched: %s.%s "+ + "Check that the agent is not disabled under agents: in .fullsend/config.yaml, that its harness trigger matches the event, "+ + "and that the actor has the role the agent requires (see Actor role resolution in the Jira integration guide).\n", + selected, strings.Join(events, ", "), agentsClause) +} diff --git a/internal/jirapoll/nomatch_test.go b/internal/jirapoll/nomatch_test.go new file mode 100644 index 0000000000..fefc2494f3 --- /dev/null +++ b/internal/jirapoll/nomatch_test.go @@ -0,0 +1,278 @@ +package jirapoll + +import ( + "bytes" + "context" + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/normevent" +) + +// reportingMatcher is a stubMatcher that also reports its candidates, as +// the CLI's CEL matcher does. +type reportingMatcher struct { + stubMatcher + candidates []string + suppressed bool +} + +func (m *reportingMatcher) DispatchCandidates() ([]string, bool) { + return m.candidates, m.suppressed +} + +// discardDispatcher accepts every record, standing in for the GitLab +// output driver. +type discardDispatcher struct{ records []DispatchRecord } + +func (d *discardDispatcher) Dispatch(_ context.Context, r DispatchRecord) error { + d.records = append(d.records, r) + return nil +} + +func captureAnnotations(t *testing.T) *bytes.Buffer { + t.Helper() + var buf bytes.Buffer + prev := annotationWriter + annotationWriter = &buf + t.Cleanup(func() { annotationWriter = prev }) + return &buf +} + +// noMatchClient returns a mock client with one issue, PROJ-123, carrying +// a /fs-code comment by a project member. +func noMatchClient(body string) *mockClient { + now := time.Now().Truncate(time.Second) + mc := newMockClient() + mc.roleMembership = map[string]string{"557058:abc123def456": "Developers"} + mc.searchResult = []jira.Issue{{ + ID: "10042", + Key: "PROJ-123", + Self: "https://acme.atlassian.net/rest/api/3/issue/10042", + Fields: jira.IssueFields{ + Summary: "Test issue", + Labels: []string{"bug"}, + Status: jira.Status{Name: "Open", StatusCategory: jira.StatusCategory{Key: "new"}}, + Reporter: jira.User{AccountID: "reporter-id", AccountType: "atlassian"}, + Created: now.Add(-1 * time.Hour).Format("2006-01-02T15:04:05.000-0700"), + Updated: now.Format("2006-01-02T15:04:05.000-0700"), + }, + }} + mc.comments["PROJ-123"] = []jira.Comment{{ + ID: "50001", + Body: body, + Created: now.Format("2006-01-02T15:04:05.000-0700"), + Author: jira.User{AccountID: "557058:abc123def456", AccountType: "atlassian"}, + }} + return mc +} + +// TestRun_WarnsWhenSelectedWorkMatchesNoAgent covers the per-cycle +// diagnostic for #9503 on both target forges: a cycle that selects an +// issue whose events match no agent writes a ::warning:: naming the issue +// key, the event and the agents considered. +func TestRun_WarnsWhenSelectedWorkMatchesNoAgent(t *testing.T) { + for _, target := range []string{TargetForgeGitHub, TargetForgeGitLab} { + t.Run(target, func(t *testing.T) { + out := captureAnnotations(t) + captureLog(t) + opts := Options{ + TargetRepo: "acme/platform", + TargetForge: target, + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + } + if target == TargetForgeGitLab { + opts.GitLabURL = "https://gitlab.example.com" + opts.Dispatcher = &discardDispatcher{} + } else { + opts.OutputPath = filepath.Join(t.TempDir(), "dispatches.json") + } + m := &reportingMatcher{candidates: []string{"triage", "review"}} + p := newTestPoller(noMatchClient("/fs-code please"), m, opts) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + got := out.String() + if !strings.HasPrefix(got, "::warning::jira-poll: selected 1 issue(s) but no agent matched") { + t.Fatalf("expected a no-match warning annotation, got %q", got) + } + for _, want := range []string{ + "PROJ-123 (comment_added /fs-code)", + "Agents considered: triage, review.", + "agents: in .fullsend/config.yaml", + "harness trigger matches the event", + "Actor role resolution", + } { + if !strings.Contains(got, want) { + t.Errorf("warning missing %q: %q", want, got) + } + } + if strings.Count(got, "\n") != 1 { + t.Errorf("expected a single annotation line, got %q", got) + } + }) + } +} + +func TestRun_NoMatchWarningSkipped(t *testing.T) { + tests := map[string]struct { + matcher EventMatcher + body string + }{ + "an agent matched": { + matcher: &reportingMatcher{stubMatcher: stubMatcher{agents: []string{"code"}}, candidates: []string{"code"}}, + body: "/fs-code", + }, + "kill switch suppresses": { + matcher: &reportingMatcher{suppressed: true}, + body: "/fs-code", + }, + "ordinary comment is not a request": { + matcher: &reportingMatcher{candidates: []string{"triage"}}, + body: "thanks, that makes sense", + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + out := captureAnnotations(t) + captureLog(t) + p := newTestPoller(noMatchClient(tt.body), tt.matcher, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + }) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + if out.Len() != 0 { + t.Errorf("expected no annotation, got %q", out.String()) + } + }) + } + + t.Run("no events on the selected issue", func(t *testing.T) { + out := captureAnnotations(t) + captureLog(t) + // lastCheck is newer than all of the issue's activity, so the + // cycle selects the issue but evaluates no event. + mc := noMatchClient("/fs-code") + mc.comments = map[string][]jira.Comment{} + setLastCheck(mc, "PROJ-123", "acme", "platform", time.Now().Truncate(time.Second)) + p := newTestPoller(mc, &reportingMatcher{}, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + }) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + if out.Len() != 0 { + t.Errorf("expected no annotation, got %q", out.String()) + } + }) +} + +// A matcher that does not report its candidates still gets the warning, +// without the agents clause. +func TestWarnNoMatch_MatcherWithoutCandidates(t *testing.T) { + out := captureAnnotations(t) + p := New(nil, &stubMatcher{}, Options{}) + p.unmatched = []unmatchedEvent{{issueKey: "PROJ-1", event: "label_changed ready-to-code added"}} + p.warnNoMatch(1) + got := out.String() + if !strings.Contains(got, "PROJ-1 (label_changed ready-to-code added)") { + t.Errorf("warning missing event: %q", got) + } + if strings.Contains(got, "Agents considered") { + t.Errorf("warning names agents without a CandidateReporter: %q", got) + } +} + +func TestWarnNoMatch_SanitizesDynamicStrings(t *testing.T) { + out := captureAnnotations(t) + p := New(nil, &reportingMatcher{}, Options{}) + p.unmatched = []unmatchedEvent{{ + issueKey: "PROJ-1", + event: "comment_added /fs-x%0A::error::spoofed\n::set-output name=a::b\x1b[31m", + }} + p.warnNoMatch(1) + got := out.String() + if strings.Count(got, "\n") != 1 || !strings.HasSuffix(got, "\n") { + t.Errorf("annotation is not a single line: %q", got) + } + if strings.Contains(got, "\x1b") { + t.Errorf("annotation keeps a control character: %q", got) + } + if strings.Contains(got[len("::warning::"):], "::error::") || strings.Contains(got[len("::warning::"):], "::set-output") { + t.Errorf("annotation embeds a workflow command: %q", got) + } + if !strings.Contains(got, "%250A") || !strings.Contains(got, "%0A") { + t.Errorf("annotation does not encode %% and LF: %q", got) + } +} + +func TestWarnNoMatch_BoundsEventList(t *testing.T) { + out := captureAnnotations(t) + p := New(nil, &reportingMatcher{}, Options{}) + for i := range maxNoMatchEvents + 3 { + p.unmatched = append(p.unmatched, unmatchedEvent{issueKey: fmt.Sprintf("PROJ-%d", i+1), event: "comment_added"}) + } + p.warnNoMatch(5) + got := out.String() + if !strings.Contains(got, fmt.Sprintf("PROJ-%d (comment_added)", maxNoMatchEvents)) { + t.Errorf("warning missing the last listed event: %q", got) + } + if strings.Contains(got, fmt.Sprintf("PROJ-%d ", maxNoMatchEvents+1)) { + t.Errorf("warning lists more than %d events: %q", maxNoMatchEvents, got) + } + if !strings.Contains(got, "and 3 more") { + t.Errorf("warning missing the overflow count: %q", got) + } + if !strings.Contains(got, "Agents considered: none.") { + t.Errorf("warning missing the empty candidate list: %q", got) + } +} + +func TestLooksLikeRequest(t *testing.T) { + tests := []struct { + name string + ne normevent.Event + want bool + }{ + {"slash command", normevent.Event{Transition: normevent.Transition{Kind: normevent.TransitionCommentAdded, Comment: &normevent.Comment{Command: "/fs-code"}}}, true}, + {"ordinary comment", normevent.Event{Transition: normevent.Transition{Kind: normevent.TransitionCommentAdded, Comment: &normevent.Comment{Body: "thanks"}}}, false}, + {"label change", normevent.Event{Transition: normevent.Transition{Kind: normevent.TransitionLabelChanged, Label: &normevent.LabelChange{Name: "ready-to-code", Action: "added"}}}, true}, + {"opened", normevent.Event{Transition: normevent.Transition{Kind: normevent.TransitionOpened}}, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := looksLikeRequest(&tt.ne); got != tt.want { + t.Errorf("looksLikeRequest() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestDescribeEvent(t *testing.T) { + tests := []struct { + ne normevent.Event + want string + }{ + {normevent.Event{Transition: normevent.Transition{Kind: normevent.TransitionCommentAdded, Comment: &normevent.Comment{Command: "/fs-triage"}}}, "comment_added /fs-triage"}, + {normevent.Event{Transition: normevent.Transition{Kind: normevent.TransitionCommentAdded, Comment: &normevent.Comment{Body: "hello"}}}, "comment_added"}, + {normevent.Event{Transition: normevent.Transition{Kind: normevent.TransitionLabelChanged, Label: &normevent.LabelChange{Name: "ready-to-code", Action: "added"}}}, "label_changed ready-to-code added"}, + {normevent.Event{Transition: normevent.Transition{Kind: normevent.TransitionOpened}}, "opened"}, + } + for _, tt := range tests { + if got := describeEvent(&tt.ne); got != tt.want { + t.Errorf("describeEvent() = %q, want %q", got, tt.want) + } + } +} diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 95a5cb85b5..32c2b70f53 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -63,6 +63,7 @@ type Poller struct { eventsSeen int // events converted this cycle eventsInvalid int // events skipped this cycle because they failed validation eventsMatchErrors int // events dropped this cycle because matcher.Match errored + unmatched []unmatchedEvent // validated events this cycle that matched no agent } // ctxSleep sleeps for d or until ctx is cancelled, whichever comes first, @@ -103,6 +104,7 @@ func (p *Poller) Run(ctx context.Context) error { cycleID := uuid.New().String() p.dispatches = nil p.eventsSeen, p.eventsInvalid, p.eventsMatchErrors = 0, 0, 0 + p.unmatched = nil p.statusCategoryCache = make(map[string]string) p.rosters = make(map[string]*projectRoster) p.userGroups = make(map[string][]jira.UserGroupInfo) @@ -293,6 +295,7 @@ func (p *Poller) Run(ctx context.Context) error { log.Printf("poll complete: %d candidates, %d unlocked, %d selected, %d dispatches", len(candidates), len(unlocked), len(selected), len(p.dispatches)) + p.warnNoMatch(len(selected)) if dispatchErrors > 0 { return fmt.Errorf("failed to dispatch records for %d issue(s); their lastCheck was not advanced, so they are retried next cycle: %w", dispatchErrors, firstDispatchErr) } @@ -682,6 +685,12 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue, cycleID str p.eventsMatchErrors++ continue } + // Only an event that looks like a request (a /fs-* command + // or a label change) feeds the no-match warning; an ordinary + // comment is expected to match no agent. + if len(records) == 0 && looksLikeRequest(&ne) { + p.unmatched = append(p.unmatched, unmatchedEvent{issueKey: event.IssueKey, event: describeEvent(&ne)}) + } p.dispatches = append(p.dispatches, records...) } } diff --git a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-poll-job.sh b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-poll-job.sh index 539bdd0c7f..042bf32ffe 100644 --- a/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-poll-job.sh +++ b/internal/scaffold/fullsend-repo-gitlab/.gitlab/ci/scripts/run-poll-job.sh @@ -152,6 +152,10 @@ if [ "${FULLSEND_POLL_MODE:-events}" = "jira" ]; then # tracker.jira in .fullsend/config.yaml; the credentials from # FULLSEND_JIRA_TOKEN and the optional FULLSEND_JIRA_EMAIL, or from a # service account's FULLSEND_JIRA_CLIENT_ID and FULLSEND_JIRA_CLIENT_SECRET. + # Built-in agent lookup also inherits the operator's GITHUB_TOKEN CI/CD + # variable, as install-fullsend-cli.sh does. The CLI prefers GH_TOKEN when + # both are set; without either or gh auth, it uses anonymous GitHub access. + # GitLab job/role tokens are separate and cannot authenticate this lookup. fullsend poll \ --input-driver jira-poll \ --target-forge gitlab \ diff --git a/internal/scaffold/gitlab_job_scripts_test.go b/internal/scaffold/gitlab_job_scripts_test.go index 5e5a142e76..8a57dabf33 100644 --- a/internal/scaffold/gitlab_job_scripts_test.go +++ b/internal/scaffold/gitlab_job_scripts_test.go @@ -235,8 +235,8 @@ func TestRunPollJobScript_BlanksSiblingSecretsBeforePoll(t *testing.T) { // TestRunPollJobScript_JiraModeRunsJiraPoller covers the Jira poll mode the // job rules select for the "fullsend jira poll" schedule (#9108): the Jira // credentials reach `fullsend poll --input-driver jira-poll` alone, with no -// Jira site, project or query argument, while every other credential is -// still blanked. +// Jira site, project or query argument, while sibling role and webhook +// credentials are still blanked. func TestRunPollJobScript_JiraModeRunsJiraPoller(t *testing.T) { root := t.TempDir() writeGitLabScript(t, root, ".gitlab/ci/scripts/trust-ci-server-ca.sh") @@ -300,6 +300,98 @@ func TestRunPollJobScript_JiraModeRunsJiraPoller(t *testing.T) { assert.Contains(t, got, "WEBHOOK_SECRET=unset") } +// The same operator-supplied GitHub token used by the installer must survive +// both shipped scripts and reach the Jira poll command. No GitLab credential +// may be substituted when the operator leaves the GitHub token unset. +func TestRunPollJobScript_JiraBuiltinToken(t *testing.T) { + var jobs map[string]struct { + BeforeScript []string `yaml:"before_script"` + Script []string `yaml:"script"` + } + gitlabLastYAMLDocument(t, ".gitlab/ci/fullsend-poll.yml", &jobs) + require.Len(t, jobs, 1) + job, ok := jobs["$[[ inputs.schedule_name | expand_vars ]]"] + require.True(t, ok, "the scheduled poll job must exist") + commands := append([]string{"set -euo pipefail"}, job.BeforeScript...) + commands = append(commands, job.Script...) + + for _, tt := range []struct { + name, ghToken, githubToken string + }{ + {name: "GITHUB_TOKEN", githubToken: "test-operator-token"}, + {name: "GH_TOKEN", ghToken: "test-gh-token"}, + {name: "both tokens preserved", ghToken: "test-gh-token", githubToken: "test-operator-token"}, + {name: "no GitHub token"}, + } { + t.Run(tt.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") + writeGitLabScript(t, root, gitlabRunPollJobScriptPath) + install := writeGitLabScript(t, root, gitlabInstallCLIScriptPath) + content, err := os.ReadFile(install) + require.NoError(t, err) + require.NoError(t, os.WriteFile(install, []byte(strings.Replace(string(content), "__FULLSEND_VERSION__", "v0.55.0", 1)), 0o644)) + + st := &pinAPIState{ + jobJSON: pinJobJSON("42", "100", "main"), + projectJSON: `{"id":42,"default_branch":"main","path_with_namespace":"group/project"}`, + branchJSON: `{"name":"main","protected":true}`, + pipelineJSON: `{"id":100,"source":"schedule"}`, + } + srv := startPinAPI(t, st) + t.Cleanup(srv.Close) + + bin := t.TempDir() + stub := `#!/bin/sh +set -eu +if [ "$1" = --version ]; then + echo 'fullsend version 0.55.0' + exit 0 +fi +test "$1" = poll +test "$2" = --input-driver +test "$3" = jira-poll +test "${GH_TOKEN:-}" = "$EXPECTED_GH_TOKEN" +test "${GITHUB_TOKEN:-}" = "$EXPECTED_GITHUB_TOKEN" +printf 'poll received expected tokens\n' > "$POLL_CALLED" +` + require.NoError(t, os.WriteFile(filepath.Join(bin, "fullsend"), []byte(stub), 0o755)) + called := filepath.Join(root, "poll-called") + cmd := exec.Command("bash", "-c", strings.Join(commands, "\n")) + cmd.Dir = root + cmd.Env = append([]string{ + "PATH=" + bin + string(os.PathListSeparator) + os.Getenv("PATH"), + "HOME=" + t.TempDir(), + "CI_PROJECT_DIR=" + root, + "RUNNER_TEMP=" + t.TempDir(), + "CI_JOB_TOKEN=test-gitlab-job-token", + "FULLSEND_GITLAB_POLLER_TOKEN=test-poller-pat", + "FULLSEND_JIRA_TOKEN=test-jira-token", + "FULLSEND_POLL_MODE=jira", + "EXPECTED_GH_TOKEN=" + tt.ghToken, + "EXPECTED_GITHUB_TOKEN=" + tt.githubToken, + "POLL_CALLED=" + called, + }, pinTLSEnv(t, srv)...) + if tt.ghToken != "" { + cmd.Env = append(cmd.Env, "GH_TOKEN="+tt.ghToken) + } + if tt.githubToken != "" { + cmd.Env = append(cmd.Env, "GITHUB_TOKEN="+tt.githubToken) + } + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + assert.Contains(t, string(out), "skipping download", "the real installer ran") + assert.NotContains(t, string(out), "test-operator-token") + assert.NotContains(t, string(out), "test-gh-token") + got, err := os.ReadFile(called) + require.NoError(t, err) + assert.Equal(t, "poll received expected tokens\n", string(got)) + }) + } +} + // TestRunPollJobScript_AnalystUserIDLookupFailureIsNonFatal covers the // Analyst ID export when the Analyst identity cannot be resolved (#8807): // an inherited FULLSEND_GITLAB_ANALYST_USER_ID is never passed through, and diff --git a/internal/scaffold/jira_poll_test.go b/internal/scaffold/jira_poll_test.go index 74281264a6..f4693ff6f5 100644 --- a/internal/scaffold/jira_poll_test.go +++ b/internal/scaffold/jira_poll_test.go @@ -226,6 +226,67 @@ func TestJiraPollCallerPollAlignment(t *testing.T) { assert.NotContains(t, string(matrixJob), "secrets.") } +// The install action's token does not persist into later steps. Exercise the +// actual poll step with its own token binding so missing wiring cannot be +// hidden by resolver tests that supply a token themselves. +func TestJiraPollWorkflowBuiltinToken(t *testing.T) { + content, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", "reusable-poll-jira.yml")) + require.NoError(t, err) + var workflow struct { + Jobs map[string]struct { + Permissions map[string]string `yaml:"permissions"` + Steps []struct { + Name string `yaml:"name"` + Env map[string]string `yaml:"env"` + Run string `yaml:"run"` + } `yaml:"steps"` + } `yaml:"jobs"` + } + require.NoError(t, yaml.Unmarshal(content, &workflow)) + job, ok := workflow.Jobs["poll"] + require.True(t, ok, "the poll job must exist") + assert.Equal(t, map[string]string{"contents": "read"}, job.Permissions) + for _, step := range job.Steps { + if step.Name != "Poll Jira" { + continue + } + require.Equal(t, "${{ github.token }}", step.Env["GH_TOKEN"]) + root := t.TempDir() + const token = "test-job-token" + stub := `#!/bin/sh +set -eu +test "$1" = poll +test "$2" = --input-driver +test "$3" = jira-poll +test "${GH_TOKEN:-}" = "test-job-token" +printf 'authenticated poll\n' > "$POLL_CALLED" +` + require.NoError(t, os.WriteFile(filepath.Join(root, "fullsend"), []byte(stub), 0o755)) + called := filepath.Join(root, "poll-called") + cmd := exec.Command("bash", "-c", step.Run) + cmd.Dir = root + cmd.Env = []string{ + "PATH=" + root + string(os.PathListSeparator) + os.Getenv("PATH"), + "HOME=" + root, + "TARGET_REPO=example/repo", + "POLL_CALLED=" + called, + } + for name, value := range step.Env { + if value == "${{ github.token }}" { + cmd.Env = append(cmd.Env, name+"="+token) + } + } + out, err := cmd.CombinedOutput() + require.NoError(t, err, "stdout/stderr: %s", out) + assert.NotContains(t, string(out), token) + got, err := os.ReadFile(called) + require.NoError(t, err) + assert.Equal(t, "authenticated poll\n", string(got)) + return + } + t.Fatal("Poll Jira step not found") +} + // The check step must find a Jira credential that JSON escaped inside // event_payload, an object as the poller writes it. func TestJiraPollWorkflowCheckDispatches(t *testing.T) { diff --git a/internal/workflowcmd/workflowcmd.go b/internal/workflowcmd/workflowcmd.go new file mode 100644 index 0000000000..0d1ee16b23 --- /dev/null +++ b/internal/workflowcmd/workflowcmd.go @@ -0,0 +1,37 @@ +// Package workflowcmd makes dynamic strings safe to embed in GitHub Actions +// workflow command annotations (::error::, ::warning::). +package workflowcmd + +import ( + "strings" + "unicode" +) + +// annotationEscaper encodes the characters GitHub Actions treats specially +// in a workflow command message: '%' first (so a literal "%0A" in a value +// stays visible as text), then CR and LF. Breaking up "::" is done separately +// in SanitizeAnnotation, because a non-overlapping replacer leaves "::" in +// runs of three or more colons. +var annotationEscaper = strings.NewReplacer("%", "%25", "\r", "%0D", "\n", "%0A") + +// SanitizeAnnotation makes a dynamic string safe to embed in a workflow +// command annotation: control characters (including ANSI escape +// sequences' ESC) are dropped, the characters annotationEscaper names are +// encoded, and "::" is broken up until none remains so a value cannot read +// as the start of another workflow command. +func SanitizeAnnotation(s string) string { + s = strings.Map(func(r rune) rune { + if r == '\r' || r == '\n' { + return r + } + if unicode.IsControl(r) { + return -1 + } + return r + }, s) + s = annotationEscaper.Replace(s) + for strings.Contains(s, "::") { + s = strings.ReplaceAll(s, "::", ": :") + } + return s +} diff --git a/internal/workflowcmd/workflowcmd_test.go b/internal/workflowcmd/workflowcmd_test.go new file mode 100644 index 0000000000..55305c8e48 --- /dev/null +++ b/internal/workflowcmd/workflowcmd_test.go @@ -0,0 +1,25 @@ +package workflowcmd + +import ( + "strings" + "testing" +) + +func TestSanitizeAnnotation_NoDoubleColon(t *testing.T) { + for _, in := range []string{"::", ":::", "::::", ":::::", "a:::error:::b", ":%0A::", "::\n::"} { + got := SanitizeAnnotation(in) + if strings.Contains(got, "::") { + t.Errorf("SanitizeAnnotation(%q) = %q, still contains %q", in, got, "::") + } + } +} + +func TestSanitizeAnnotation_EncodesAndStripsControl(t *testing.T) { + got := SanitizeAnnotation("a%b\r\nc\x1b[31m") + if strings.ContainsAny(got, "\r\n\x1b") { + t.Errorf("SanitizeAnnotation kept a raw control character: %q", got) + } + if got != "a%25b%0D%0Ac[31m" { + t.Errorf("SanitizeAnnotation = %q", got) + } +}