diff --git a/.github/workflows/reusable-dispatch.yml b/.github/workflows/reusable-dispatch.yml index c63945eaa7..cf6ac2b02a 100644 --- a/.github/workflows/reusable-dispatch.yml +++ b/.github/workflows/reusable-dispatch.yml @@ -1322,13 +1322,48 @@ jobs: fi # An enabled entry may omit source when it only tunes a built-in # agent by name (runtime/model/effort/subagents, ADR 0091; trigger, - # #8726), the settings config.AgentEntry.HasSettings counts. A blank - # trigger counts as unset, as on the Go side. trigger is checked for - # null explicitly: `//` would also replace an unquoted false, which - # Go reads as the CEL expression "false". - BAD_SOURCE=$(yq '.agents[] | select(type == "!!map" and .enabled != false and (.source == null or .source == "") and (.runtime == null and .model == null and .effort == null and .subagents == null and ((.trigger == null) or (.trigger | tostring | test("^\\s*$"))))) | line' .fullsend/config.yaml 2>/dev/null || echo "") - if [[ -n "$BAD_SOURCE" ]]; then - echo "::error::config.yaml: enabled agent entry without a source field (an entry with only a name must set runtime, model, effort, subagents or trigger to tune a built-in agent)" + # #8726; a non-empty harness: block, ADR 0162), the settings + # config.AgentEntry.HasSettings counts. A blank trigger counts as + # unset, as on the Go side. trigger is checked for null explicitly: + # `//` would also replace an unquoted false, which Go reads as the + # CEL expression "false". explode(.) resolves each entry's YAML + # aliases, as the Go side does; without it `harness: *anchor` + # counts as unset. It runs per entry, so a bad merge key elsewhere + # in the file does not fail this check. A yq failure is reported; + # fullsend run validates the entries again. + YQ_ERR=$(mktemp) + BAD_SOURCE=$(yq '.agents[] | explode(.) | select(type == "!!map" and .enabled != false and (.source == null or .source == "") and (.runtime == null and .model == null and .effort == null and .subagents == null and ((.trigger == null) or (.trigger | tostring | test("^\\s*$"))) and (((.harness | type) != "!!map") or ((.harness | length) == 0)))) | ((.enabled // "unset") | tostring) + " " + ((.name // "") | downcase)' .fullsend/config.yaml 2>"$YQ_ERR") || { + echo "::warning::yq failed checking agent entries without a source — see logs" + cat "$YQ_ERR" >&2 + BAD_SOURCE="" + } + # The Go keyed merge (perRepoConfig.AgentEntries) completes such an + # entry from the config.base.yaml entry of the same name: one with + # a source or a setting, or one that turns the agent off when this + # entry does not turn it on. Names compare without case, and a base + # entry without a name is named after its source file. + BASE_ENTRIES="" + if [[ -n "$BAD_SOURCE" && -f .fullsend/config.base.yaml ]]; then + BASE_ENTRIES=$(yq '.agents[] | explode(.) | ((select(type == "!!str") | "complete " + (sub("#[^#]*$", "") | sub("^.*/", "") | sub("\\.[^.]*$", "") | downcase)), (select(type == "!!map") | select(((.source // "") != "") or .runtime != null or .model != null or .effort != null or .subagents != null or ((.trigger != null) and ((.trigger | tostring | test("^\\s*$")) | not)) or (((.harness | type) == "!!map") and ((.harness | length) > 0))) | "complete " + ((.name // .source) | sub("#[^#]*$", "") | sub("^.*/", "") | sub("\\.[^.]*$", "") | downcase)), (select(type == "!!map") | select(.enabled == false) | "off " + ((.name // "") | downcase)))' .fullsend/config.base.yaml 2>"$YQ_ERR") || { + echo "::warning::yq failed reading agent entries from config.base.yaml — see logs" + cat "$YQ_ERR" >&2 + BAD_SOURCE="" + } + fi + rm -f "$YQ_ERR" + UNRESOLVED="" + while read -r enabled name; do + [[ -z "$enabled" ]] && continue + if [[ -n "$name" ]] && grep -qxF -- "complete $name" <<<"$BASE_ENTRIES"; then + continue + fi + if [[ -n "$name" && "$enabled" == "unset" ]] && grep -qxF -- "off $name" <<<"$BASE_ENTRIES"; then + continue + fi + UNRESOLVED=1 + done <<<"$BAD_SOURCE" + if [[ -n "$UNRESOLVED" ]]; then + echo "::error::config.yaml: enabled agent entry without a source field (an entry with only a name must set runtime, model, effort, subagents, trigger or harness to tune a built-in agent)" exit 1 fi DUPES_ENABLED=$(yq '.agents[] | select(type == "!!map" and .enabled != false) | (.name // "") | select(. != "") | downcase' .fullsend/config.yaml 2>/dev/null | sort | uniq -d) diff --git a/docs/agents/review.md b/docs/agents/review.md index 2db00d5d53..7f7645df19 100644 --- a/docs/agents/review.md +++ b/docs/agents/review.md @@ -145,11 +145,25 @@ See [Configuring with AGENTS.md](../guides/user/customizing-with-agents-md.md). |----------|-------------|---------|--------------| | `REVIEW_FINDING_SEVERITY_THRESHOLD` | Minimum severity for findings to include in the review. Findings below this level are omitted from both the narrative body and the posted inline comments. | `low` | `info`, `low`, `medium`, `high`, `critical` | -Set this in the harness's `env.sandbox` (the upstream default lives in -`harness/review.yaml`). To override per repo or org, use `base:` -composition rather than the CI workflow `env:` block — workflow `env:` -is reserved for infrastructure plumbing (see [Architecture](../architecture.md#agent-harness) -for details on harness composition and workflow-env conventions). +The upstream default lives in `harness/review.yaml`, in both `env.runner` +and `env.sandbox`. To override it per repo or org, set it in the review +entry's `harness:` block in `config.yaml` (or `config.base.yaml`), which +keeps the agent on upstream updates +([ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md)): + +```yaml +agents: + - name: review + harness: + env: + runner: { REVIEW_FINDING_SEVERITY_THRESHOLD: medium } + sandbox: { REVIEW_FINDING_SEVERITY_THRESHOLD: medium } +``` + +`base:` composition also works. Do not use the CI workflow `env:` block — +workflow `env:` is reserved for infrastructure plumbing (see +[Architecture](../architecture.md#agent-harness) for details on harness +composition and workflow-env conventions). The post-script reads the value from the runner environment directly — no separate configuration is needed. diff --git a/docs/cli/README.md b/docs/cli/README.md index c31d3fdc04..3d36da979d 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 poll` | Discover forge events and dispatch agent pipelines. `--forge gitlab` runs the cron poller ([ADR 0067](../ADRs/0067-gitlab-cron-polling-event-dispatch.md)); events-mode polling also recovers issue opens whose webhook delivery was missed. `--input-driver jira-poll` polls Jira (see [Jira integration](../guides/user/jira-integration.md)). It reads the Jira site, API gateway, project, and query only from the effective `tracker.jira` config (`base_url` and `project` required; the removed `--jira-url`, `--jira-project`, and `--jql` flags are rejected), authenticates with `FULLSEND_JIRA_TOKEN` (plus `FULLSEND_JIRA_EMAIL` for a bot user) or with OAuth 2.0 client credentials via `FULLSEND_JIRA_CLIENT_ID` and `FULLSEND_JIRA_CLIENT_SECRET`, and skips the cycle unless `tracker.jira.poll.enabled` is `true`; by default it writes dispatch records (`--output`) for a GitHub repository (`--target-repo`, an `owner/repo` slug; one that contains `..` is refused), and with `--target-forge gitlab` it starts the protected agent pipelines of the GitLab project named by `--project` (full path, nested groups allowed; default `CI_PROJECT_PATH`) on the https `--gitlab-url` instance, through the same signed, typed-input dispatch route and Poller credential as the GitLab poller, advancing a Jira issue's checkpoint only once its pipelines are created ([GitLab runtime](../guides/user/jira-integration.md#gitlab-runtime)). `--input-driver gitlab-webhook` is the GitLab dispatcher job's webhook fast-path ([ADR 0125](../ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). It reads the native webhook body from the file-type `TRIGGER_PAYLOAD` variable, re-validates it against the GitLab API, and creates each routed stage's pipeline (typed inputs, `FULLSEND_DISPATCH_SECRET` HMAC) with the poller-role credential (the `api` route, the default). Scheduled cron polling and the webhook fast path run as the trigger-only service account: once its dispatch activation is recorded, the managed webhook carries the account's pipeline trigger token ([#8509](https://github.com/fullsend-ai/fullsend/issues/8509)), the scaffold sets `FULLSEND_GITLAB_DISPATCH_ROUTE=child-pipeline`, and the command instead starts each pipeline with the job's own `CI_JOB_TOKEN` through the pipeline trigger API (`source=pipeline`); an unknown route, or `child-pipeline` without `CI_JOB_TOKEN`, fails closed. `fullsend poll --forge gitlab --print-dispatch-routes` prints the routes the CLI supports (`api` and `child-pipeline`) and exits; the scaffold runs it before selecting `child-pipeline`, and a CLI that predates the route rejects the flag, so the job stops before any dispatch. It requires `--project`, which has no `CI_PROJECT_PATH` fallback. It deduplicates against the poller's per-mode state on the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches, so an event the webhook dispatched is not dispatched again by the poller, and the reverse. Shared poller state is occurrence-aware (label additions are keyed on the resource label event ID, dispatched keys are retained for the webhook freshness window, and a failed label dispatch is handed back to the poller as a pending retry); legacy persisted keys keep working. Older pollers do not recognise the new label keys, so before a rollback or mixed-version run, follow the [ADR 0132](../ADRs/0132-occurrence-aware-shared-poller-state.md) guidance to drain in-flight poll jobs or pin every poller to one version. Both GitLab drivers dispatch the fix stage only for a changes-requested marker note authored by the registered Analyst, whose numeric user ID the scaffold exports as the job-local `FULLSEND_GITLAB_ANALYST_USER_ID`. | | `fullsend dispatch` | Evaluate harness CEL triggers for one forge event and print the dispatch matrix (`--output-driver gha-matrix` or `json`); used by the dispatch workflow's `Harness dispatch` job. `--route ` (`review`, `retro`, `triage` or `prioritize`) instead decides routing for that built-in agent and prints one JSON line, `{"agent":"","decision":"run\|skip\|bash","reason":"…","harness":"config:\|agents@"}` (`harness` is optional: it is omitted when the harness cannot be resolved or the decision did not need it, as for `bash`): `run` or `skip` when the repository set `agents[].trigger` on the agent's entry ([Choosing when review runs](../guides/user/customizing-agents.md#choosing-when-review-runs), [Choosing when retro runs](../guides/user/customizing-agents.md#choosing-when-retro-runs), [Choosing when triage and prioritize run](../guides/user/customizing-agents.md#choosing-when-triage-and-prioritize-run)), `bash` to leave the decision to the workflow's built-in rules. The dispatch workflow's `Route` job runs it. With `--input-driver gha-event`, a GitHub bot actor's registered fullsend role is looked up first through the mint (a layered `mint_url`, else `FULLSEND_MINT_URL`) with the job's Actions OIDC token, so the job needs `id-token: write` ([ADR 0107](../ADRs/0107-bot-identity-resolution-for-dispatch-authorization.md)); label-added events skip the lookup, and an unregistered bot or a failed lookup is denied (an empty matrix, or a `skip` decision) rather than failing the command. An absent config falls back to `FULLSEND_MINT_URL`, but a config that fails to load or parse is a failed lookup, not a fallback. | -| `fullsend 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. 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. | +| `fullsend lock [agent-name]` | Pin remote dependencies to `lock.yaml`. If `lock.yaml` exists but cannot be parsed or declares an unsupported version, the command exits without writing and leaves the file unchanged. An entry is stale when the harness file or the `harness:` block of the agent's `agents:` entry has changed. When it composes a harness (a new or stale entry, or `--update`), it also prints the harness diagnostics, including [reserved `env.sandbox` keys](run.md#reserved-envsandbox-keys). A current entry is not composed, so its keys are not checked, and `lock` composes without event context, so keys from event-guarded overlays are reported only by `fullsend run`. A harness whose runtime fetch service can start (`allow_runtime_fetch: true`, URL-sourced skill or plugin directories, or a bare, deprecated `allowed_remote_resources` declaration) must have every harness-level `allowed_remote_resources` prefix covered by the config-level allowlist — `config.yaml`'s `allowed_remote_resources` plus the built-in default prefixes (the defaults are included when the list is omitted or non-empty; an explicit `allowed_remote_resources: []` stays deny-all and excludes them); `lock` fails naming an uncovered prefix, and fails closed when no repository config (`config.yaml` or `config.base.yaml`) exists. With a `harness:` block on the agent's entry, the prefixes checked are the ones the block sets. | | `fullsend lint` | Lint `config.yaml` and agent harness definitions — deprecations, misconfigurations, and file checks, with diagnostics for each enabled agent, or for one agent with `fullsend lint `. See [`fullsend lint`](lint.md), and [Checking a trigger before you merge](../guides/user/cel-triggers-reference.md#checking-a-trigger-before-you-merge) for a walkthrough. | | `fullsend scan` | Run security scanners on agent input/output | | [`fullsend self-update`](self-update.md) | Update the local `fullsend` binary to the latest release, or to `--version`, after verifying the release's Sigstore signature and checksum. | diff --git a/docs/cli/agent.md b/docs/cli/agent.md index 987fa34f68..882b82db8c 100644 --- a/docs/cli/agent.md +++ b/docs/cli/agent.md @@ -384,7 +384,8 @@ the `#sha256=...` integrity hash suffix is stripped from the displayed source for readability. Disabled agents (`enabled: false`) are included in the listing. A built-in agent tuned by an entry without `source:` shows `(built-in)`. An entry's settings follow in brackets, for example `[model=sonnet effort=high]`; -an entry with an `agents[].trigger` shows `trigger` there. +an entry with an `agents[].trigger` shows `trigger` there, and one with a +`harness:` block shows `harness`. Example output: ``` @@ -445,6 +446,10 @@ dispatch on each runtime. Remove an agent from config. If the removed agent was the last one using a given `allowed_remote_resources` prefix, that prefix is cleaned from the config's own list only. Entries the parent chain resolves (fullsend's defaults, `GITHUB_SERVER_URL`-derived prefixes, `config.base.yaml` entries) are never carried into the cleaned list, and a prefix the base owns is left to the base. When the cleaned local list becomes empty, the local `allowed_remote_resources` key is dropped so the parent chain resolves again. Over a chain that resolves to deny-all (a base `[]`), the command instead writes the fullsend default prefixes a remaining agent still uses. Those can be host-specific when `GITHUB_SERVER_URL` names a GitHub Enterprise host. +The command edits `config.yaml` only. For an agent that `config.base.yaml` +registers, it fails and writes nothing. To turn that agent off, add an entry +with its `name` and `enabled: false` to `config.yaml`. + ```bash fullsend agent remove triage ``` diff --git a/docs/cli/lint.md b/docs/cli/lint.md index 5b39d7c93a..45a87d70f9 100644 --- a/docs/cli/lint.md +++ b/docs/cli/lint.md @@ -47,13 +47,18 @@ Each enabled `agents:` entry is resolved and composed through the same machinery directory. Run that online run with the same forge (`--forge` or CI auto-detection) as the offline run; otherwise the forge-specific files are not cached and the offline run fails. -- Harnesses are composed with `base:` chains, CEL-guarded overlays, and the forge - section for the effective platform, so diagnostics see the harness as it would - execute. Without a platform (`--forge` omitted, none in config, no CI env), the forge - section is left unconsumed and its fields are linted in place. - -Diagnostics for an override-only entry come from the upstream harness, not from your -`config.yaml`, so you cannot fix them in this repository. +- Harnesses are composed with `base:` chains, CEL-guarded overlays, the forge + section for the effective platform, and the `harness:` block of the agent's + `agents:` entry, so diagnostics see the harness as it would execute. Without a + platform (`--forge` omitted, none in config, no CI env), the forge section is left + unconsumed and its fields are linted in place. + +Diagnostics for an override-only entry come from the upstream harness, so you cannot +fix them in this repository. The entry's `harness:` block is the exception. A +diagnostic on a field that the block sets comes from your `config.yaml`. It +carries the same field label as one from the upstream harness, so compare the +field with your block. A diagnostic that names the block or a `harness.` field +always comes from the block. Disabled agents (`enabled: false`) are skipped. Overlay `when` expressions evaluate against an empty event with `runtime.forge` and `config` available, like other CLI @@ -194,6 +199,9 @@ Codes appear only in `--format json`. | `trigger-invalid` | `trigger` fails CEL validation | | `preflight-check-path` | `preflight_check` looks like a bare script path | | `github-issue-url-deprecated` | `GITHUB_ISSUE_URL` is set or referenced | +| `block-drops-runtime-fetch` | an `agents:` entry's `harness:` block leaves out a runtime fetch field that a layer below it sets, unless the block sets `allow_runtime_fetch: false` | +| `block-drops-ci-variable-credential` | an `agents:` entry's `harness:` block leaves out `allow_ci_variable_credential` when a layer below it sets it to `true`, unless the block sets it to `false`; not reported when the forge is known and is not GitLab | +| `block-trigger-ignored` | an `agents:` entry's `harness:` block sets `trigger` on a built-in agent | | `reserved-sandbox-env` | `env.sandbox` keys the sandbox will drop | | `config-invalid` | `config.yaml` semantic validation failed, including an invalid `forge:` | | `agents-siblings-invalid` | scoped lint: other agents' `agents[]` entries are invalid | diff --git a/docs/cli/repos.md b/docs/cli/repos.md index e628bc07d5..c5d95574dc 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -104,8 +104,12 @@ declared in a more specific layer than an explicit empty one (for example `defaults.config` `[]` with a non-empty `github.config` or repository list) unless the most specific declared list is itself empty, which denies every remote resource whatever the earlier layers say; declare the full list in a -single layer instead. Omitted values inherit and are not written into the -managed file. Every repository selected from the manifest has a managed +single layer instead. Validation also rejects an agent's `harness:` block that +is set in more than one of these three layers, because they render into one +`config.yaml`. Set the block in one layer (see the +[config reference](../reference/config-reference.md#agents)). Omitted values +inherit and are not written into the managed file. Every repository selected +from the manifest has a managed `.fullsend/config.yaml`; no `config` key is required. With no `config` declared, install renders the canonical sparse file carrying only the ownership marker (omitted values still inherit from a declared preset and the code defaults). @@ -216,9 +220,15 @@ key plus `create_issues.allow_targets`. A setting that schema cannot express repository with an error that names the setting. The ownership marker is the same in every schema. +An agent entry's `harness:` block needs a ref that declares schema version 3 +or later. For a ref on an older schema, install fails that repository with an +error that names the entry, and `repos status` reports a block that is already +in the installed file as `incompatible`. + The pinned ref is looked up only when the managed configuration or the -installed file declares `tracker` or `create_issues`, the only keys whose shape -differs between known schemas. Looking it up needs the upstream GitHub client. +installed file declares `tracker`, `create_issues` or a `harness:` block on an +agent entry, the only settings that known schemas read differently. Looking it +up needs the upstream GitHub client. When the ref or its schema cannot be determined (the ref does not resolve, no upstream client is available, or the ref declares a schema version this CLI does not know), install leaves `.fullsend/config.yaml` unchanged and fails that diff --git a/docs/cli/run.md b/docs/cli/run.md index 4b00e32f78..c44dbda772 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -14,6 +14,16 @@ fullsend run [flags] 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); `fullsend run` fails naming an uncovered prefix, and fails closed when no repository config (`config.yaml` or `config.base.yaml`) exists. See the [`allow_runtime_fetch` entry](../reference/harness-reference.md) in the harness reference. +When the agent's `agents:` entry in `config.yaml` carries a `harness:` block, +`fullsend run` composes the block on the agent's harness as a child layer +([Config Reference — `agents`](../reference/config-reference.md#agents)). The +block does not inherit the runtime fetch fields of the harness below it, so the +rule above then applies to the `allowed_remote_resources` list that the block +sets. A change to the block makes the agent's `lock.yaml` entry stale, like a +change to the harness file. The block is read from the `config.yaml` at the +root of `--fullsend-dir`. A run that finds it only in a sibling +`.fullsend/config.yaml` fails and names the directory to pass. + ## Flags | Flag | Description | @@ -63,6 +73,11 @@ The **Runtime** line shows which runtime was selected and the config source it w The runtime for a run is resolved once, in this order: `--runtime` flag, `FULLSEND_RUNTIME`, `runtime:` on the agent's `agents:` entry in `config.yaml` / `.fullsend/config.yaml`, the repo-wide `runtime:` there, then the built-in `claude`. The same order applies to the model (`--model`, `FULLSEND_MODEL`, `model:` on the agent's `agents:` entry, harness `model:`, agent frontmatter; `FULLSEND_PI_MODEL` on pi and `FULLSEND_CODEX_MODEL` on codex are lower-precedence aliases, each read only when that runtime is the one selected) and to effort (`--effort`, `FULLSEND_EFFORT`, `effort:` on the agent's `agents:` entry, harness `effort:`). `` is the name given to `fullsend run` (`triage`, `code`, …); see [Runtimes — per-agent settings](../runtimes.md#per-agent-runtime-model-and-effort). `FULLSEND_FALLBACK_MODELS=a,b` becomes Claude Code's `--fallback-model`; pi uses it for aliased models on the top-level run when Vertex does not serve the model (two specific 404/403 messages, same provider only; sub-agent children get none); codex ignores it with a warning. +A `model` or `effort` set in the `harness:` block of the agent's `agents:` +entry is a harness value. It ranks where harness `model:` and `effort:` do in +the order above, and `override_source` reports the model as `harness`. Setting +either one both on the entry and in its block fails validation. + The plan block prints `Runtime: (from )` and, when an override applied, `Model: (from )`; stderr carries `runtime: selected "" from ` (and `model: requested "" from `) for scripts. A value from the config file is labelled with the file path, suffixed ` agents.` when the agent's entry decided. When `models.aliases` in `.fullsend/config.yaml` remaps the alias, the line keeps the alias and its source and adds the remap: `Model: sonnet (from ) → claude-sonnet-5 (from models.aliases)`, with `model: alias "sonnet" remapped to "claude-sonnet-5" from models.aliases` on stderr. An alias that is not remapped shows the id it resolves to through the runtime's built-in table instead: `Model: haiku (from FULLSEND_MODEL) → claude-haiku-5-5 (built-in default)` on `claude` (`opus`, `sonnet`, `haiku`) and `pi` (those three plus `fable`). Aliased entries in the `Fallback models` line show as `alias → id` (`sonnet → claude-sonnet-5, claude-opus-4-6 (from FULLSEND_FALLBACK_MODELS)`); literal ids print as written; Claude Code and pi use the chain for aliased models when Vertex does not serve the model and ignore it for pinned ids. With no `FULLSEND_FALLBACK_MODELS`, a `claude` or `pi` run on `opus`, `sonnet` or `haiku` (not retargeted) prints the alias's built-in chain instead: `Fallback models: claude-opus-4-6 (built-in for opus, when not served)`. An invalid override — unknown runtime, unknown effort level, an `agents:` entry that names no agent, or a `models.aliases` key or value the block does not accept — fails before the sandbox is created. Each run then selects its inference provider from the resolved runtime and model, so different @@ -604,6 +619,9 @@ them into the sandbox. Matching is case-insensitive. It warns twice: - As it writes the sandbox environment, one stderr line per key: `WARNING: env.sandbox key "NAME" is reserved (runner infrastructure or security deny-list); skipping` +A reserved name in the `harness:` block of an `agents:` entry fails the run +instead, in `env.runner` as well as in `env.sandbox`. + `fullsend lint` also reports the load-time warning, and `fullsend lint --strict` exits non-zero on it. `fullsend lock` prints the load-time warning when it composes a harness. A current lock entry is not diff --git a/docs/contributing/config-source-inventory.md b/docs/contributing/config-source-inventory.md index 4e932c1d1c..59c7bcb612 100644 --- a/docs/contributing/config-source-inventory.md +++ b/docs/contributing/config-source-inventory.md @@ -99,7 +99,7 @@ The Go accessor layers these. The bash steps in `.github/workflows/reusable-disp | Setting | Controls | Set from | Wins today | Read by | Decision | Base file? | |---|---|---|---|---|---|---| -| `agents` | Registered agents and per-agent `runtime`, `model`, `effort`, `subagents`, and a `harness:` block once [ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md) is implemented | Overlay, base, compiled none | Go accessor: keyed merge by agent name. Bash validates the shape of `config.yaml` only | Go run path and `reusable-dispatch.yml` | Layer the direct read for enablement and role checks. Per-agent runtime, model, and effort still lose to flags and environment variables; those rows are below | Yes, for the shared agent baseline. | +| `agents` | Registered agents and per-agent `runtime`, `model`, `effort`, `subagents`, and a `harness:` block ([ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md)) | Overlay, base, compiled none | Go accessor: keyed merge by agent name. Bash validates the shape of `config.yaml`; its check for an entry without a source also reads the `config.base.yaml` entry of the same name | Go run path and `reusable-dispatch.yml` | Layer the direct read for enablement and role checks. Per-agent runtime, model, and effort still lose to flags and environment variables; those rows are below | Yes, for the shared agent baseline. | ## File fields that lose to a variable or a flag @@ -129,7 +129,7 @@ re-renders that template. | `FULLSEND_FALLBACK_MODELS` | Extra models to try when the first alias is unavailable | Repository variable, copied by `setup-agent-env.sh` | The environment variable. No YAML field | `fullsend run` for Claude and pi | Add a file field if a fleet should share the chain. Until then the variable is the only source | Yes, once a field exists. | | `FULLSEND_PI_PROVIDER` | pi backend (`anthropic-vertex`, `openai`, `xai-vertex`, …) | Repository variable, copied by `setup-agent-env.sh` | The environment variable. No YAML field | pi runtime | Add a file field. The variable stays as the fallback | Yes, once a field exists. | | `FULLSEND_PI_MODEL`, `FULLSEND_CODEX_MODEL` | Runtime-scoped aliases of the model override | Repository variables, copied by `setup-agent-env.sh` | After `FULLSEND_MODEL`, before the agent entry, and only when that runtime is selected | `fullsend run` | No separate file field. They are compatibility names for `agents[].model` | No. | -| `REVIEW_FINDING_SEVERITY_THRESHOLD` | Lowest review finding severity to post | Agent environment variable (`docs/agents/review.md`) | The variable. No YAML field in this repo | Review agent | Stays a harness variable. Set it per repo through the agent entry's `harness:` block once [ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md) is implemented | Yes, the block merges across both files. | +| `REVIEW_FINDING_SEVERITY_THRESHOLD` | Lowest review finding severity to post | Agent environment variable (`docs/agents/review.md`) | The variable. No YAML field in this repo | Review agent | Stays a harness variable. Set it per repo through the agent entry's `harness:` block ([ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md)) | Yes, the block merges across both files. | | `CODE_AUTO_MERGE`, `CODE_AUTO_MERGE_METHOD` | Whether the code agent enables GitHub auto-merge, and the method | Agent environment variables (`docs/guides/user/adoption.md`) | The variables. No YAML field | Code agent | Leave as variables. The code harness does not declare them, so a `harness:` block ([ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md)) rejects them; declaring them in the harness comes first | Same as the review threshold once declared. | | `OTEL_EXPORTER_OTLP_*`, `OTEL_RESOURCE_ATTRIBUTES`, `OTEL_SDK_DISABLED`, `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` | Trace export | Repository variables. Header values are secrets | The variables. Unset means export stays off | CLI tracer, from the workflow environment | Leave as variables. Endpoints differ per environment, and headers are secrets | No. | | `FULLSEND_SANDBOX_IMAGE`, `FULLSEND_SANDBOX_ARCH` | Sandbox image and CPU architecture for a run | Process environment | The variables, when set | `fullsend run` | Leave as variables. They are per-machine or per-job overrides | No. | diff --git a/docs/contributing/harness-composition.md b/docs/contributing/harness-composition.md index 33fc1daf98..d042413d71 100644 --- a/docs/contributing/harness-composition.md +++ b/docs/contributing/harness-composition.md @@ -46,6 +46,22 @@ and update the others as needed. > (specificity). Across layers, child values override inherited base > values (derivation). +> **Note — `harness:` blocks.** The `harness:` block of an `agents:` entry +> ([ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md)) is +> one more child layer. `composeAgentBlocks` +> (`internal/harness/agent_block.go`) resolves the agent's harness with +> `resolveLayerForgeAndOverlays`, the function behind +> `resolveBaseForgeAndOverlays`. It then merges the harness into each block +> with `mergeBaseIntoChild`, so a change to a merge function applies to +> blocks too. With no forge selected, the harness's `forge:` sections are set +> aside for those merges, and `restoreUnresolvedForge` puts them back on the +> result, where a load without a block leaves them. Two block checks depend +> on the field set. A field that `mergeBaseIntoChild` does not inherit needs +> a check in `composeAgentBlocks`, so that lint warns when a block drops it: +> `runtimeFetchFields` lists the runtime fetch fields, and +> `allow_ci_variable_credential` has its own check. `recordDeclaredEnv` +> lists every place where a layer can set `env`. + ### Validation and resolution side | Function | File | Purpose | diff --git a/docs/contributing/harness-fields.md b/docs/contributing/harness-fields.md index 77d6a8c603..2199fcc06f 100644 --- a/docs/contributing/harness-fields.md +++ b/docs/contributing/harness-fields.md @@ -22,10 +22,14 @@ > `human_min_role` field at the top level and in guarded overlays, with its > overlay selected before actor admission and pinned through the run. Legacy > `forge:` blocks cannot set it; the tables below remain current behavior. -> [ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md) lets an -> `agents:` entry in `config.yaml` carry a `harness:` block, a harness layer -> built on the agent's harness and merged by the `base:` composition rules -> below. The ADR lists the few fields it does not take. + +An `agents:` entry in `config.yaml` may carry a `harness:` block +([ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md)). The +block is a harness layer built on the agent's harness. It merges by the +`base:` composition rules below. It takes every field except `base`, `forge` +and `runner_env`. It cannot add an `env` variable that the harness does not +declare. See the [config reference](../reference/config-reference.md#agents) +for the details. ## Field classification diff --git a/docs/guides/getting-started/repo-management.md b/docs/guides/getting-started/repo-management.md index aef1fc1957..f9f6b77244 100644 --- a/docs/guides/getting-started/repo-management.md +++ b/docs/guides/getting-started/repo-management.md @@ -388,7 +388,11 @@ non-empty `allowed_remote_resources` list is unioned with the inherited prefixes, and an explicit empty list replaces the inherited value. The managed file is sparse and cannot record that reset, so validation rejects a non-empty `allowed_remote_resources` list declared in a more specific layer -than an explicit empty one; declare the full list in a single layer. A +than an explicit empty one; declare the full list in a single layer. +Validation also rejects an agent's `harness:` block that is set in more than +one of the `defaults`, forge section and repository `config` layers, because +they render into one `config.yaml`. Set the block in one layer (see the +[config reference](../../reference/config-reference.md#agents)). A forge section's `config` never affects repositories of the other forge. The managed configuration contains only explicitly supplied values — code defaults and `config.base.yaml` are not baked into the file. diff --git a/docs/guides/infrastructure/layered-config-reference.md b/docs/guides/infrastructure/layered-config-reference.md index 060ab8f69b..1af9a7da8f 100644 --- a/docs/guides/infrastructure/layered-config-reference.md +++ b/docs/guides/infrastructure/layered-config-reference.md @@ -173,13 +173,13 @@ repository's concrete `repos.yaml` entry is the only managed layer that may declare it, and install renders the whole block into the managed overlay. See [Config Reference — `trace_context`](../../reference/config-reference.md#trace_context). -### Per-agent `runtime`, `model`, `effort`, `subagents`, `trigger` on `agents:` entries +### Per-agent `runtime`, `model`, `effort`, `subagents`, `trigger`, `harness` on `agents:` entries -An `agents:` entry may set `runtime`, `model`, `effort`, `subagents` and -`trigger` for that agent. The `ref` field records the branch or tag that was resolved when -the agent was adopted via `agent add`; `agent update` re-resolves against -this ref instead of the default branch when it is present (empty for -SHA-pinned or legacy entries). +An `agents:` entry may set `runtime`, `model`, `effort`, `subagents`, +`trigger` and a `harness:` block for that agent. The `ref` field records the +branch or tag that was resolved when the agent was adopted via `agent add`; +`agent update` re-resolves against this ref instead of the default branch +when it is present (empty for SHA-pinned or legacy entries). An enabled entry without `source:` is an *override-only* entry that tunes a built-in agent by name (or, in an overlay, a custom agent registered in the @@ -191,6 +191,17 @@ per-key merge: overlay entries override or tombstone (`~`) individual persona keys while unstated keys inherit from the parent. There is no way to unset a parent's scalar value from the overlay short of restating the entry. +The `harness:` block does not merge field by field like the other settings. +Each layer's block stays a layer of the harness chain. The chain is the +agent's harness, then the `config.base.yaml` block, then the `config.yaml` +block, composed by the `base:` rules. The overlay can replace a base value +but not remove it. An overlay entry with no block, an empty one +(`harness: {}`) or a null one keeps the base block +([ADR 0162](../../ADRs/0162-agent-entries-may-carry-harness-overrides.md); +see the [`harness` field](../../reference/config-reference.md#agents)). +`repos.yaml` managed blocks render into one `config.yaml`, so only one of the +`defaults`, forge and repository `config` layers may set an agent's block. + ```yaml # config.base.yaml (preset) agents: diff --git a/docs/guides/user/bring-your-own-agent.md b/docs/guides/user/bring-your-own-agent.md index 4bcdfe1c9a..84ef8bc716 100644 --- a/docs/guides/user/bring-your-own-agent.md +++ b/docs/guides/user/bring-your-own-agent.md @@ -233,6 +233,7 @@ you would add or change it by hand. | `config.yaml` `agents:` entry | `name:`, `source:` | always, unless `--no-register` | `` / `harness/.yaml` | — | | `config.yaml` `agents:` entry | `runtime:` | only when a runtime is given | `--runtime` / spec `runtime` | — | | `config.yaml` `agents:` entry | `model:`, `effort:`, `subagents:` | never — `agent set` writes these, not `agent new` | `fullsend agent set` | per-agent tuning after generation | +| `config.yaml` `agents:` entry | `harness:` | never | edit `config.yaml` | changes harness fields without a `base:` harness ([ADR 0162](../../ADRs/0162-agent-entries-may-carry-harness-overrides.md)) | ## Troubleshooting diff --git a/docs/guides/user/cel-triggers-reference.md b/docs/guides/user/cel-triggers-reference.md index 97bbd98c4f..c853eff552 100644 --- a/docs/guides/user/cel-triggers-reference.md +++ b/docs/guides/user/cel-triggers-reference.md @@ -346,12 +346,13 @@ to CEL: | Your configuration | Who decides | |---|---| -| No `review` entry, or one with only `runtime`, `model`, `effort` or `subagents` | The dispatch workflow, as before | +| No `review` entry, or one with only `runtime`, `model`, `effort`, `subagents` or a `harness:` block | The dispatch workflow, as before | | `trigger` on the `review` entry | The trigger | | A `review` entry with `source:` whose harness sets or inherits `trigger:` | The dispatch workflow, as before | A harness `trigger:` field never changes when a built-in agent runs, whether -your own harness writes it or inherits it through `base:`. To route review by +your own harness writes it, inherits it through `base:`, or the entry's +`harness:` block sets it. To route review by a trigger you keep in a harness, copy the expression into the `review` entry's `trigger` in `config.yaml`. The kill switch and `enabled: false` on the review entry keep working as before. The `Route` diff --git a/docs/guides/user/customizing-agents.md b/docs/guides/user/customizing-agents.md index 0c61695488..e1a2834be8 100644 --- a/docs/guides/user/customizing-agents.md +++ b/docs/guides/user/customizing-agents.md @@ -18,7 +18,8 @@ Common configuration goals: | Goal | How | |------|-----| -| Change model, timeout, or image | Override scalar fields via `base:` composition | +| Change a setting of an agent's harness, such as a timeout or a variable it declares (for example `REVIEW_FINDING_SEVERITY_THRESHOLD`) | Set it in the agent entry's [`harness:` block](../../reference/config-reference.md#agents) in `config.yaml`; no `base:` harness needed, and the agent keeps getting updates | +| Change model, timeout, or image in a harness file of your own | Override scalar fields via `base:` composition | | Add org-specific skills | Add entries to the `skills:` list | | Add environment variables | Add entries under `env.runner` or `env.sandbox` | | Install GitHub Packages npm dependencies | Add a repo-level GitHub Packages provider (see [Private registries and GitHub Packages](#private-registries-and-github-packages)) | diff --git a/docs/guides/user/customizing-overview.md b/docs/guides/user/customizing-overview.md index f2e095e74f..5bf2861e65 100644 --- a/docs/guides/user/customizing-overview.md +++ b/docs/guides/user/customizing-overview.md @@ -11,7 +11,8 @@ so you can pick the right one. |------|----------|--------| | Teach agents your coding style, test commands, or architecture rules | [AGENTS.md](#agentsmd) | Low | | Give an agent domain-specific knowledge or a new capability | [Skills](#skills) | Low | -| Change model, timeout, image, or add env vars to an existing agent | [Harness configuration](#harness-configuration) | Medium | +| Change a setting of an existing agent's harness, such as a timeout, the image or a variable it declares | [The `harness:` block](#harness-configuration) | Low | +| Add env vars to an existing agent, or keep its changes in a harness file | [Harness configuration](#harness-configuration) | Medium | | Build a completely new agent with its own trigger, scripts, and schema | [Bring Your Own Agent](#bring-your-own-agent) | Medium with `fullsend agent new`, high by hand | Start at the top and move down only when a lighter option doesn't cover your @@ -42,9 +43,28 @@ points, replacing built-in skills. ## Harness configuration -To change how an existing agent runs — its model, timeout, sandbox image, -environment variables, or skills — use `base:` harness composition. Create -a thin harness that inherits from the upstream agent and overrides only what +To change a setting of an existing agent's harness, such as its timeout, +sandbox image, skills or a variable it declares, set it in the `harness:` +block of the agent's entry in `config.yaml`. The agent keeps getting +upstream updates. See the +[config reference](../../reference/config-reference.md#agents). + +```yaml +agents: + - name: code + harness: + timeout_minutes: 90 + env: + sandbox: + TIMEOUT_SECONDS: "5400" +``` + +The code, fix and review skills read their time limit from +`TIMEOUT_SECONDS`, in seconds. Change it together with `timeout_minutes`. + +The block cannot add an environment variable. For that, or to keep the +changes in a harness file, use `base:` harness composition. Create a thin +harness that inherits from the upstream agent and overrides only what differs: ```yaml diff --git a/docs/guides/user/escalation-ladder.md b/docs/guides/user/escalation-ladder.md index 1b95ed9ca2..0245420315 100644 --- a/docs/guides/user/escalation-ladder.md +++ b/docs/guides/user/escalation-ladder.md @@ -35,7 +35,8 @@ must be replicated independently. Use the extension points the default agent was designed for. These keep you in [configured-default territory](default-vs-custom.md) and require no -changes to the agent's identity-defining fields. Some rows need a thin +changes to the agent's identity-defining fields. Some rows need the +`harness:` block of the agent's `config.yaml` entry or a thin `base`-composed harness (still Level 1); others need no harness at all. | Extension point | What it does | Guide | @@ -44,10 +45,10 @@ changes to the agent's identity-defining fields. Some rows need a thin | Repo skills (`.agents/skills/`) | Domain-specific knowledge for individual agents — linting rules, deployment checklists, label glossaries. No harness required. | [Customizing with Skills](customizing-with-skills.md) | | Documented env vars | Per-agent tuning knobs (e.g., `REVIEW_FINDING_SEVERITY_THRESHOLD`). No harness required. | Each agent's [reference page](../../agents/) | | `env:` in harness | Add environment variables without changing the agent's identity. Needs a thin `base` harness. | [Harness Field Reference](../../reference/harness-reference.md) | -| `skills:` in harness | Add skills via `base` composition — concatenated with the base agent's skill list. Needs a thin `base` harness. | [Configuring Agent Behavior](customizing-agents.md#configuration-with-base-composition) | -| `plugins:` in harness | Add language-server plugins. Needs a thin `base` harness. | [Harness Field Reference](../../reference/harness-reference.md) | -| `host_files:` in harness | Inject additional files into the sandbox. Needs a thin `base` harness. | [Harness Field Reference](../../reference/harness-reference.md) | -| Sandbox image layers | Base your image on the default, add tools; point the harness `image:` field at it. Needs a thin `base` harness. | [Extending the sandbox image](customizing-agents.md#extending-the-sandbox-image) | +| `skills:` in harness | Add skills — concatenated with the base agent's skill list. Needs the `harness:` block of the agent's `config.yaml` entry, or a thin `base` harness. | [Configuring Agent Behavior](customizing-agents.md#configuration-with-base-composition) | +| `plugins:` in harness | Add language-server plugins. Needs the `harness:` block of the agent's `config.yaml` entry, or a thin `base` harness. | [Harness Field Reference](../../reference/harness-reference.md) | +| `host_files:` in harness | Inject additional files into the sandbox. Needs the `harness:` block of the agent's `config.yaml` entry, or a thin `base` harness. | [Harness Field Reference](../../reference/harness-reference.md) | +| Sandbox image layers | Base your image on the default, add tools; point the harness `image:` field at it. Needs the `harness:` block of the agent's `config.yaml` entry, or a thin `base` harness. | [Extending the sandbox image](customizing-agents.md#extending-the-sandbox-image) | **Evidence to escalate:** show that no combination of these extension points produces the behavior you need. Concrete evidence includes: diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 5643fb6837..16201c9d38 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -96,8 +96,11 @@ Connect fullsend to a Jira project so that Jira issue activity — comments, lab use the built-in triggers instead, move to the release listed above. Re-pin a harness registered with `source:` or composed with `base:` with `fullsend agent update `. The - poller reads only the harness `trigger:`. A `trigger` on an `agents:` entry - in `config.yaml` does not affect it: that field decides routing for the + poller reads only the harness `trigger:`. For a custom agent, that includes + a `trigger` in the `harness:` block of its `agents:` entry. On a built-in + agent the block's trigger is not evaluated. A `trigger` set directly on an + `agents:` entry in `config.yaml` does not affect the poller: that field + decides routing for the built-in review, retro, triage and prioritize agents on GitHub only ([Choosing when review runs](customizing-agents.md#choosing-when-review-runs), [Choosing when retro runs](customizing-agents.md#choosing-when-retro-runs), diff --git a/docs/guides/user/running-agents-locally.md b/docs/guides/user/running-agents-locally.md index 668d7a22c7..93cbb3b3b8 100644 --- a/docs/guides/user/running-agents-locally.md +++ b/docs/guides/user/running-agents-locally.md @@ -417,7 +417,8 @@ you can tune resolution limits: If a `lock.yaml` file exists in the fullsend directory, `fullsend run` uses it to skip re-resolution when the harness has not changed since the lock was -generated. Generate or update a lock file with: +generated. A `harness:` block on the agent's `config.yaml` entry counts as +part of the harness. Generate or update a lock file with: ```bash fullsend lock code --fullsend-dir /path/to/.fullsend @@ -441,10 +442,11 @@ dependencies is locked. If your agent's forge-specific files come only from a for example `--forge github`, so `fullsend lock` pins them. Without it, the run warns that the lock entry does not pin them. -When the lock entry is current (harness SHA256 matches), dependencies are -resolved from the local cache without network access. If the harness has changed -or a cached artifact is missing, `fullsend run` falls back to normal network -resolution and prints a warning suggesting you re-run `fullsend lock`. +When the lock entry is current (the SHA256 of the harness and its `harness:` +block matches), dependencies are resolved from the local cache without network +access. If the harness or the block has changed, or a cached artifact is +missing, `fullsend run` falls back to normal network resolution and prints a +warning suggesting you re-run `fullsend lock`. A current lock entry also pins the files a URL `base:` (or an agent fetched from a URL) names by relative path: agent, policy, skills, skill file overrides, diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 4d3f7ac9db..a937ef8efa 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -52,6 +52,8 @@ agents: # Registered agent sources and per-agent tu default: sonnet # Fallback model for personas without an explicit entry code-reviewer: opus # Model for a specific persona # trigger: # When the built-in review agent runs (review entry only) + # harness: # Changes harness settings without a base: harness + # timeout_minutes: 90 # ── Remote resources ───────────────────────────────────────── allowed_remote_resources: # URL prefixes allowed for remote resources (agents, policies, skills, plugins, profiles, providers, and base composition) @@ -221,7 +223,7 @@ Omitting the key inherits the parent's roles. See Registered agent sources and per-agent tuning. Each entry identifies an agent by source URL or local path, with optional overrides for runtime, model, -effort, sub-agent models and the trigger. +effort, sub-agent models, the trigger and harness settings. - **`source`** — URL (must include `#sha256=<64-hex-char>` integrity hash) or local path. URL sources must be covered by `allowed_remote_resources`. @@ -261,10 +263,100 @@ effort, sub-agent models and the trigger. invalid `model` or `effort`, an invalid `trigger` makes every agent run in the repository fail with `invalid agent config`, not only built-in routing, so check the expression before you merge the change. -- **`harness`** — Decided, not yet implemented: - [ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md) adds a - block that overrides the agent's harness fields without a `base:` - harness. +- **`harness`** — A partial harness composed on the agent's harness as a + child layer, as if it named that harness in `base:`, with nothing pinned + ([ADR 0162](../ADRs/0162-agent-entries-may-carry-harness-overrides.md)). + It changes harness settings without a `base:` harness, so the agent keeps + getting agent updates. It merges by the `base:` composition rules of the + [harness field reference](../contributing/harness-fields.md#merge-and-inheritance-rules). + A scalar replaces the harness value. A list adds to it. Each `env` + variable replaces the harness value, and `~` sets it empty. + + ```yaml + agents: + - name: review + harness: + env: + runner: { REVIEW_FINDING_SEVERITY_THRESHOLD: medium } + sandbox: { REVIEW_FINDING_SEVERITY_THRESHOLD: medium } + - name: code + harness: + timeout_minutes: 90 + env: + runner: { GITHUB_SIGNED_COMMITS: "true" } + sandbox: { TIMEOUT_SECONDS: "5400" } + - name: fix + harness: + env: + runner: { GITHUB_SIGNED_COMMITS: "true" } + ``` + + `GITHUB_SIGNED_COMMITS: "true"` turns on signed commits for the code and + fix agents on GitHub. The post-script publishes the agent's commits through + the Git Data API, and GitHub signs them (see + [Signed commits](https://github.com/fullsend-ai/agents/blob/main/docs/code.md#signed-commits)). + + `TIMEOUT_SECONDS` is `timeout_minutes` in seconds. The code, fix and review + skills read their time limit from it, so change both together. + + - **Fields.** The block takes every harness field except `base`, `forge` + and `runner_env`; an overlay in the block cannot set `runner_env` + either. An unknown key fails. So does a value that no harness accepts, + such as an unknown `effort`. + - **`env` names.** The block cannot add a variable. A name that the + agent's harness does not declare in that section fails. The error names + the agent and the variable. A name counts as declared when any layer of + the harness sets it at top level, in a `forge:` block or in an overlay. A name + fullsend reserves in the sandbox fails in either section. Adding a + variable still takes a `base:` harness. + - **`schema_version`.** Absent means `1`. A block whose version differs + from the agent's harness fails to load + ([ADR 0127](../ADRs/0127-harness-schema-versioning-and-field-types.md)). + - **Runtime fetch.** Like a `base:` child, the block does not inherit + `allowed_remote_resources`, `allow_runtime_fetch` or + `max_runtime_fetches`. `fullsend lint` warns when a block leaves out + one that the harness or the `config.base.yaml` block sets. The warning + names the field. To keep it, set it in the block. When both files have + a block, set it in the `config.yaml` one. To drop the fields on purpose, + set `allow_runtime_fetch: false` in the block; lint then does not warn. + - **`allow_ci_variable_credential`.** The block does not inherit this + field either. `fullsend lint` warns when a block leaves it out and the + harness or the `config.base.yaml` block sets it to `true`. To keep it, + set it in the block. When both files have a block, set it in the + `config.yaml` one. To drop it on purpose, set it to `false` in the + block; lint then does not warn. Only GitLab runs read the field, so + lint does not warn when the forge is known and is not GitLab. + - **Paths.** Relative paths in the block resolve against the `.fullsend` + directory, like a local harness file's, and a path that escapes it is + rejected. + - **Layers.** The `config.base.yaml` block composes first, then the + `config.yaml` block, so `config.yaml` can replace a value from + `config.base.yaml` but not remove it. An entry in `config.yaml` with no + block, an empty one or a null one keeps the `config.base.yaml` block. + In `repos.yaml`, only one of the + `defaults`, forge and repository `config` layers may set an agent's + block, since they render into one `config.yaml`. A repository pinned to + a `fullsend_ref` from before blocks cannot take one: `repos install` + fails that repository and names the entry (see + [Configuration schema of a pinned ref](../cli/repos.md#configuration-schema-of-a-pinned-ref)). + - **Fields the entry already has.** Setting `model`, `effort` or + `trigger` both on the entry and in the block fails, checked on the + entry merged from both files. The built-in agents are `review`, + `retro`, `triage`, `prioritize`, `code` and `fix`, whether or not the + entry has a `source`. On a built-in agent, a `harness.trigger` is not + evaluated. The configuration loads with a warning that names the agent. + The entry's `trigger` keeps deciding routing as described above. This + lasts until built-in agents are routed by CEL alone + ([#2902](https://github.com/fullsend-ai/fullsend/issues/2902)). + - **Who reads it.** `fullsend run`, `fullsend lint`, `fullsend lock` and + dispatch, CEL dispatch and the Jira poller included, all compose the + block. A change to it makes the agent's lock entry stale. `fullsend lock` + composes the block on the entry's harness only. It locks a local + `harness/.yaml` that the entry does not name without the block, + because `fullsend run` does not use that file for the entry. A non-empty + block alone makes a valid override-only entry. On a disabled entry the + block is not composed. It is still validated when the entry has a + `source`. In the layered config system, agents use keyed merge by `DerivedName()` — see [Layered Config Reference](../guides/infrastructure/layered-config-reference.md). diff --git a/docs/runtimes.md b/docs/runtimes.md index 82f6703fff..57a0f67292 100644 --- a/docs/runtimes.md +++ b/docs/runtimes.md @@ -108,7 +108,8 @@ the agent's `agents:` entry in `.fullsend/config.yaml` instead. Harness `env.run ### Per-agent runtime, model and effort The `agents:` list is the per-agent place in `config.yaml`: an entry names an -agent and can set its `runtime`, `model`, `effort`, `subagents` and `trigger` +agent and can set its `runtime`, `model`, `effort`, `subagents`, a `harness:` +block of harness settings and `trigger` (on `review`, `retro`, `triage` and `prioritize`, decides routing for that agent; see [Choosing when review runs](guides/user/customizing-agents.md#choosing-when-review-runs), @@ -161,10 +162,12 @@ agent gets its settings on its own entry. Precedence: flag > env var > the agent's `agents:` entry > repo-wide `runtime:` / harness `model:` `effort:` > default. Entries merge per field across the layered config (`config.yaml` -over `config.base.yaml`), so a preset base can tune agents too. `fullsend run` validates the -whole `agents:` list in every layer (names, runtime, model syntax, effort) and fails the run with -an error naming the file and entry rather than silently skipping a mistyped entry or handing a -bad value to the runtime. +over `config.base.yaml`), so a preset base can tune agents too. The `harness:` block is the +exception: each file's block stays a layer of its own (see the +[layered config reference](guides/infrastructure/layered-config-reference.md)). +`fullsend run` validates the whole `agents:` list in every layer (names, runtime, model +syntax, effort) and fails the run with an error naming the file and entry rather than +silently skipping a mistyped entry or handing a bad value to the runtime. A value that came from here shows up as ` agents.` wherever the selection is surfaced (plan block, stderr, `metrics.json` — see below); the path is the effective config file. diff --git a/docs/runtimes/pi.md b/docs/runtimes/pi.md index b4921bf2e1..20ccaeaf79 100644 --- a/docs/runtimes/pi.md +++ b/docs/runtimes/pi.md @@ -666,8 +666,9 @@ subagents: challenger → openai/gpt-5.6-luna (from subagents.challenger) If you route a persona with `--subagent` and the agent's harness is a local file that does not declare `openai`, `agent set` warns. The config is still written, so you can edit the harness -afterwards. A harness fetched by URL, one with `base:`, `overlays:` or `forge:` blocks, and a -persona from a skill fetched by URL are not checked here; the run checks them. +afterwards. A harness fetched by URL, one with `base:`, `overlays:` or `forge:` blocks, an +entry with a `harness:` block, and a persona from a skill fetched by URL are not checked here; +the run checks them. ```console ✓ Set agent "my-review": runtime="pi" model="opus" effort="" (empty = inherit) subagents: challenger=openai/gpt-5.6-luna diff --git a/internal/cli/agent.go b/internal/cli/agent.go index dc2306d4f7..2c0bb2058a 100644 --- a/internal/cli/agent.go +++ b/internal/cli/agent.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "sort" "strings" @@ -431,7 +432,9 @@ func runAgentAdd(ctx context.Context, source, name, fullsendDir string, forgeCli return fmt.Errorf("agent %q already exists in config", derivedName) } - cfg.SetAgents(append(agents, entry)) + // Write only this layer's own entries, as runAgentSet does: the merged + // list would copy the parent layer's entries into config.yaml. + cfg.SetAgents(append(append([]config.AgentEntry(nil), localAgentEntries(cfg)...), entry)) if err := validateAgentConfig(cfg); err != nil { return fmt.Errorf("config validation failed: %w", err) @@ -502,6 +505,9 @@ func runAgentList(fullsendDir string, printer *ui.Printer) error { if strings.TrimSpace(a.Trigger) != "" { settings = append(settings, "trigger") } + if len(a.HarnessBlocks()) > 0 { + settings = append(settings, "harness") + } displaySource += " [" + strings.Join(settings, " ") + "]" } printer.Raw(fmt.Sprintf("%-*s %s\n", maxName, a.DerivedName(), displaySource)) @@ -737,8 +743,21 @@ func runAgentRemove(fullsendDir, agentName string, printer *ui.Printer) error { } removedEntry := agents[idx] - agents = append(agents[:idx], agents[idx+1:]...) - cfg.SetAgents(agents) + // Write only this layer's own entries, as runAgentSet does: the merged + // list would copy the parent layer's entries into config.yaml. + local := slices.Clone(localAgentEntries(cfg)) + if i, ok := findAgentByName(local, agentName); ok { + local = slices.Delete(local, i, i+1) + } + cfg.SetAgents(local) + // An agent that config.base.yaml registers is still there, and this + // command edits config.yaml only. + agents = cfg.AgentEntries() + if _, inLocal := findAgentByName(local, agentName); !inLocal { + if _, inBase := findAgentByName(agents, agentName); inBase { + return fmt.Errorf("agent %q is registered in config.base.yaml, which this command does not edit; to turn it off, add an entry with `name: %s` and `enabled: false` to config.yaml", agentName, agentName) + } + } if urlutil.IsURL(removedEntry.Source) { prefix := allowlistPrefixForURL(removedEntry.Source) diff --git a/internal/cli/agent_harness_block_test.go b/internal/cli/agent_harness_block_test.go new file mode 100644 index 0000000000..fc0cdb295c --- /dev/null +++ b/internal/cli/agent_harness_block_test.go @@ -0,0 +1,193 @@ +package cli + +import ( + "bytes" + "context" + "fmt" + "io" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/fetch" + "github.com/fullsend-ai/fullsend/internal/lock" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// newHarnessBlockRunDir builds a code agent whose entry carries block; the pre-script records MY_KNOB. +func newHarnessBlockRunDir(t *testing.T, marker, block string) string { + t.Helper() + dir := newSkipHarnessDir(t, "") + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "code.yaml"), []byte( + "agent: agents/code.md\nrole: test\npolicy: policies/base.yaml\nenv:\n runner:\n MY_KNOB: low\npre_script: "+ + writePreScript(t, "printf '%s' \"$MY_KNOB\" > "+marker+"\n")+"\n"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte( + "version: \"1\"\nagents:\n - name: code\n source: harness/code.yaml\n"+block), 0o644)) + return dir +} + +// The run composes the entry's block, so the pre-script sees the block's value. +func TestRunAgent_HarnessBlockReachesTheRun(t *testing.T) { + usePreScriptStub(t) + marker := filepath.Join(t.TempDir(), "knob") + dir := newHarnessBlockRunDir(t, marker, " harness:\n env:\n runner:\n MY_KNOB: high\n") + + var out bytes.Buffer + err := runRunnerSecretAgentTo(t, dir, &out) + require.Error(t, err) + assert.Contains(t, err.Error(), "creating sandbox", "the run passed composition and validation") + + got, readErr := os.ReadFile(marker) + require.NoError(t, readErr, out.String()) + assert.Equal(t, "high", string(got)) +} + +// An undeclared name fails the run at composition, before the pre-script. +func TestRunAgent_HarnessBlockUndeclaredNameFails(t *testing.T) { + usePreScriptStub(t) + marker := filepath.Join(t.TempDir(), "knob") + dir := newHarnessBlockRunDir(t, marker, " harness:\n env:\n runner:\n NOT_DECLARED: x\n") + + err := runRunnerSecretAgentTo(t, dir, io.Discard) + require.Error(t, err) + assert.Contains(t, err.Error(), `agents entry "code": harness.env.runner.NOT_DECLARED`) + assert.NoFileExists(t, marker, "the pre-script did not run") +} + +// A reserved sandbox name fails in either env section (ADR 0162 Decision 5). +func TestRunAgent_HarnessBlockReservedNameFails(t *testing.T) { + usePreScriptStub(t) + marker := filepath.Join(t.TempDir(), "knob") + dir := newHarnessBlockRunDir(t, marker, " harness:\n env:\n runner:\n LD_PRELOAD: x\n") + + err := runRunnerSecretAgentTo(t, dir, io.Discard) + require.Error(t, err) + assert.Contains(t, err.Error(), "harness.env.runner.LD_PRELOAD: fullsend reserves this name in the sandbox") + assert.NoFileExists(t, marker) +} + +// A block in the sibling .fullsend/config.yaml fails the run instead of being dropped. +func TestRunAgent_HarnessBlockInSiblingConfigFails(t *testing.T) { + // The root has no config, or only a config.base.yaml: both read the sibling config.yaml. + for _, rootBase := range []bool{false, true} { + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, ".fullsend"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".fullsend", "config.yaml"), []byte( + "version: \"1\"\nagents:\n - name: code\n model: sonnet\n harness: { timeout_minutes: 90 }\n"), 0o644)) + if rootBase { + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte("version: \"1\"\n"), 0o644)) + } + + err := runAgent(context.Background(), "code", dir, "", t.TempDir(), "", nil, false, "", "", "", resolveFlags{maxDepth: 10, maxResources: 50}, statusOpts{}, ui.New(io.Discard), false, runOverrideFlags{}) + require.Error(t, err) + assert.Contains(t, err.Error(), `the "code" agents entry has a harness: block`) + assert.Contains(t, err.Error(), "--fullsend-dir "+filepath.Join(dir, ".fullsend")) + } +} + +func harnessBlocks(t *testing.T, docs ...string) []*config.AgentHarness { + t.Helper() + var out []*config.AgentHarness + for _, d := range docs { + var b config.AgentHarness + require.NoError(t, yaml.Unmarshal([]byte(d), &b)) + out = append(out, &b) + } + return out +} + +// lock hashes the entry's block, so the run finds the lock entry current until the block changes. +func TestRunLock_HarnessBlock(t *testing.T) { + agent, sandbox, strict := []byte("You are a coding agent."), []byte("sandbox: default"), []byte("sandbox: strict") + srv, policy := newLockTestServer(t, map[string][]byte{ + "/agents/code.md": agent, + "/policies/sandbox.yaml": sandbox, + "/policies/strict.yaml": strict, + }) + dir := setupLockTestDir(t, srv, fetch.ComputeSHA256(agent), fetch.ComputeSHA256(sandbox)) + origPolicy := fetch.DefaultPolicy + fetch.DefaultPolicy = policy + defer func() { fetch.DefaultPolicy = origPolicy }() + + strictURL := srv.URL + "/policies/strict.yaml" + // writeConfig gives the code entry a block and returns it as the run reads it. + writeConfig := func(timeout int) []*config.AgentHarness { + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(fmt.Sprintf(`version: "1" +allowed_remote_resources: + - "%s/" +agents: + - name: code + source: harness/code.yaml + harness: + timeout_minutes: %d + policy: "%s#sha256=%s" +`, srv.URL, timeout, strictURL, fetch.ComputeSHA256(strict))), 0o644)) + cfg, err := loadLockConfig(filepath.Join(dir, "config.yaml")) + require.NoError(t, err) + return config.HarnessBlocksFor(cfg.AgentEntries(), "code") + } + harnessPath := filepath.Join(dir, "harness", "code.yaml") + printer := ui.New(&bytes.Buffer{}) + + blocks := writeConfig(30) + require.NoError(t, runLock(context.Background(), "code", dir, "", false, resolveFlags{}, printer)) + st, err := readRunLock(dir, "code", harnessPath, blocks) + require.NoError(t, err) + require.NotNil(t, st.entry) + assert.False(t, st.stale, "lock and run hash the block the same way") + assert.NotNil(t, st.entry.LookupDep(strictURL), "lock pins a URL the block adds") + + require.NoError(t, runLockAll(context.Background(), dir, "", false, resolveFlags{}, printer)) + lf, err := lock.Load(filepath.Join(dir, "lock.yaml")) + require.NoError(t, err) + assert.NotNil(t, lf.Lookup("code"), "lock --all keeps an entry whose block did not change") + + st, err = readRunLock(dir, "code", harnessPath, writeConfig(90)) + require.NoError(t, err) + assert.True(t, st.stale) + + st, err = readRunLock(dir, "code", harnessPath, nil) + require.NoError(t, err) + assert.True(t, st.stale, "removing the block also changes what was locked") +} + +// fullsend lock pairs a block with the harness fullsend run composes it on. +func TestRunLock_HarnessBlockFollowsTheRun(t *testing.T) { + const plain = "agent: agents/review.md\nrole: review\n" + const outside = "allowed_remote_resources:\n - \"https://disallowed.example.com/\"\n" + const sourced = " - name: review\n source: harness/review.yaml\n" + for _, tc := range []struct { + name, harness, entry, wantErr string + }{ + {"the block's fetch list is held to the allowlist", plain, + sourced + " harness:\n allow_runtime_fetch: true\n allowed_remote_resources: [\"https://disallowed.example.com/\"]\n", + `"https://disallowed.example.com/" is not covered by the org allowlist`}, + {"a list the block drops is not checked", plain + outside, + sourced + " harness: { timeout_minutes: 5 }\n", ""}, + {"a local file the built-in's entry does not name locks without the block", plain, + " - name: review\n harness: { env: { sandbox: { NOT_DECLARED: x } } }\n", ""}, + {"so does a local file when the entry names another", plain, + " - name: review\n source: harness/other.yaml\n harness: { env: { sandbox: { NOT_DECLARED: x } } }\n", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "review.yaml"), []byte(tc.harness), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "other.yaml"), []byte(plain), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte( + "version: \"1\"\nallowed_remote_resources:\n - \"https://allowed.example.com/\"\nagents:\n"+tc.entry), 0o644)) + + err := runLock(context.Background(), "review", dir, "", false, resolveFlags{}, ui.New(io.Discard)) + if tc.wantErr == "" { + require.NoError(t, err) + return + } + assert.ErrorContains(t, err, tc.wantErr) + }) + } +} diff --git a/internal/cli/agent_openai.go b/internal/cli/agent_openai.go index 831d9bdba6..7ff2892c9c 100644 --- a/internal/cli/agent_openai.go +++ b/internal/cli/agent_openai.go @@ -24,7 +24,7 @@ import ( // It stays silent whenever it cannot tell: a runtime other than pi, an // agent whose harness is a URL (fleet harnesses declare openai) or is not // in this config, a harness that does not load or has overlays: or forge: -// blocks, or a provider entry that is a URL. +// blocks, an entry with a harness: block, or a provider entry that is a URL. func warnOpenAISubagentWithoutProvider(cfg config.ConfigReader, absDir, agentName, runtimeName string, subagents map[string]*string, printer *ui.Printer) { pr, ok := cfg.(config.PerRepoConfigReader) if !ok { @@ -40,6 +40,10 @@ func warnOpenAISubagentWithoutProvider(cfg config.ConfigReader, absDir, agentNam if source == "" || urlutil.IsURL(source) { return } + // A harness: block may add providers too (ADR 0162). + if len(config.HarnessBlocksFor(cfg.AgentEntries(), agentName)) > 0 { + return + } h, err := harness.Load(underDir(absDir, source)) if err != nil || len(h.Overlays) > 0 || len(h.Forge) > 0 { // A base: harness does not load here; an overlay or a forge: diff --git a/internal/cli/agent_test.go b/internal/cli/agent_test.go index 99aba71255..8ba14593fe 100644 --- a/internal/cli/agent_test.go +++ b/internal/cli/agent_test.go @@ -1867,6 +1867,44 @@ agents: assert.Equal(t, "medium", lint.Effort) } +// agent add and agent remove write only the overlay's own entries, not the base layer's. +func TestRunAgentAddRemove_BaseLayerEntriesStayInBase(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + for _, name := range []string{"lint", "other"} { + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", name+".yaml"), []byte("agent: agents/"+name+".md\nrole: test\n"), 0o644)) + } + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.base.yaml"), []byte(`version: "1" +agents: + - source: harness/lint.yaml + harness: + timeout_minutes: 30 +`), 0o644)) + writePerRepoConfig(t, dir, "") + overlay := func() string { + data, err := os.ReadFile(filepath.Join(dir, "config.yaml")) + require.NoError(t, err) + return string(data) + } + + require.NoError(t, runAgentAdd(context.Background(), "harness/other.yaml", "", dir, nil, ui.New(os.Stdout))) + assert.Contains(t, overlay(), "harness/other.yaml") + assert.NotContains(t, overlay(), "lint") + + require.NoError(t, runAgentRemove(dir, "other", ui.New(os.Stdout))) + assert.NotContains(t, overlay(), "other") + assert.NotContains(t, overlay(), "lint") + + // With or without an entry of its own in config.yaml, a base-layer agent is not reported as removed. + for _, own := range []string{"", "agents:\n - name: lint\n enabled: false\n"} { + writePerRepoConfig(t, dir, own) + before := overlay() + err := runAgentRemove(dir, "lint", ui.New(os.Stdout)) + assert.ErrorContains(t, err, `agent "lint" is registered in config.base.yaml`) + assert.Equal(t, before, overlay(), "nothing is written") + } +} + func TestAgentSetCmd_ExecutesAndTracksChangedFlags(t *testing.T) { dir := t.TempDir() writePerRepoConfig(t, dir, "") @@ -2155,6 +2193,8 @@ func TestRunAgentList_BuiltInAndSettings(t *testing.T) { effort: high subagents: default: haiku + harness: + timeout_minutes: 30 - source: harness/lint.yaml model: opus `) @@ -2166,7 +2206,7 @@ func TestRunAgentList_BuiltInAndSettings(t *testing.T) { assert.Contains(t, out, "runtime=claude") assert.Contains(t, out, "model=sonnet") assert.Contains(t, out, "effort=high") - assert.Contains(t, out, "subagents: default=haiku") + assert.Contains(t, out, "subagents: default=haiku harness]") assert.Contains(t, out, "harness/lint.yaml") assert.Contains(t, out, "model=opus") } @@ -2352,6 +2392,7 @@ func TestRunAgentSet_OpenAISubagentWarningAbsolutePaths(t *testing.T) { name string absAgent bool providers func(dir string) string + block string warn bool }{ {name: "absolute openai provider path counts", providers: func(dir string) string { @@ -2359,6 +2400,8 @@ func TestRunAgentSet_OpenAISubagentWarningAbsolutePaths(t *testing.T) { }}, {name: "absolute agent path still finds the persona", absAgent: true, providers: func(string) string { return " - vertex-ai\n" }, warn: true}, + {name: "a harness: block may add the provider", + providers: func(string) string { return " - vertex-ai\n" }, block: " harness: { providers: [openai] }\n"}, } { t.Run(tc.name, func(t *testing.T) { dir := t.TempDir() @@ -2378,7 +2421,7 @@ func TestRunAgentSet_OpenAISubagentWarningAbsolutePaths(t *testing.T) { []byte("name: my-oai\ntype: fullsend-openai\ncredentials:\n OPENAI_API_KEY: \"\"\n"), 0o644)) require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "mix.yaml"), []byte("agent: "+agentPath+"\nrole: test\nmodel: opus\nskills:\n - skills/probe\nproviders:\n"+tc.providers(dir)), 0o644)) - writePerRepoConfig(t, dir, "agents:\n - name: mix\n source: harness/mix.yaml\n") + writePerRepoConfig(t, dir, "agents:\n - name: mix\n source: harness/mix.yaml\n"+tc.block) var out bytes.Buffer require.NoError(t, runAgentSet(dir, "mix", agentSetFlags{ @@ -2390,6 +2433,11 @@ func TestRunAgentSet_OpenAISubagentWarningAbsolutePaths(t *testing.T) { } else { assert.NotContains(t, out.String(), warnText) } + if tc.block != "" { + written, err := os.ReadFile(filepath.Join(dir, "config.yaml")) + require.NoError(t, err) + assert.Contains(t, string(written), "openai", "agent set keeps the entry's harness: block") + } }) } } diff --git a/internal/cli/dispatch_route.go b/internal/cli/dispatch_route.go index 670a7f4096..bd2c2500dc 100644 --- a/internal/cli/dispatch_route.go +++ b/internal/cli/dispatch_route.go @@ -275,6 +275,9 @@ func routeBuiltinAgent(ctx context.Context, o routeOpts) (routeDecision, error) // fails and the route's threshold wrongly fails closed. useAgentsRepoHostFetch(&composeOpts, forgeClient) } + // A harness: block may set role (ADR 0162). + composeOpts.Blocks = config.HarnessBlocksFor(cfg.AgentEntries(), o.agent) + composeOpts.Agent = o.agent if h, _, err := harness.LoadWithBase(ctx, path, composeOpts); err == nil { harnessRole = h.Role } else { diff --git a/internal/cli/dispatch_route_test.go b/internal/cli/dispatch_route_test.go index 97d3ccc554..6d746bed9c 100644 --- a/internal/cli/dispatch_route_test.go +++ b/internal/cli/dispatch_route_test.go @@ -846,6 +846,22 @@ func TestRouteBuiltinAgent_HarnessRoleThreshold(t *testing.T) { assert.Equal(t, routeRun, got.Decision, "reason: %s", got.Reason) }) + t.Run("a harness: block's role sets the threshold", func(t *testing.T) { + // The block composes for dispatch too, and role is a field it may set. + client, policy, agentsURL := routeAgentsRepo(t, routeTestHarnessBody) + dir := writeRouteFixture(t, routeFixture{ + allowlist: []string{agentsURL}, + agents: []config.AgentEntry{{Name: "review", Trigger: commentOnly, Harness: harnessBlocks(t, "role: code")[0]}}, + }) + got, err := routeBuiltinAgent(context.Background(), routeOpts{ + agent: "review", configDir: dir, event: routeEvent(t, routeTriageReviewComment), + forgeClient: client, fetchPolicy: policy, printer: ui.New(io.Discard), + }) + require.NoError(t, err) + assert.Equal(t, routeSkip, got.Decision) + assert.Equal(t, "actor not authorized", got.Reason) + }) + t.Run("triage user is denied a sourced harness with a write role", func(t *testing.T) { dir := writeRouteFixture(t, sourcedReview(config.AgentEntry{Trigger: commentOnly}, map[string]string{ "harness/review.yaml": strings.Replace(routeTestHarnessBody, "role: review", "role: code", 1), diff --git a/internal/cli/lint.go b/internal/cli/lint.go index 936a2e84b7..372d364d33 100644 --- a/internal/cli/lint.go +++ b/internal/cli/lint.go @@ -340,6 +340,8 @@ func runLint(cmd *cobra.Command, fullsendDir, forgeFlag, only string, strict, of if len(fetchDeps) > 0 && fetchDeps[0].URL != "" { agentOpts.SourceURL = fetchDeps[0].URL } + agentOpts.Blocks = config.HarnessBlocksFor(entries, agentName) + agentOpts.Agent = agentName h, _, err := harness.LoadWithBase(cmd.Context(), harnessPath, agentOpts) if err != nil { wrapped := fmt.Errorf("loading harness for agent %q: %w", agentName, err) diff --git a/internal/cli/lint_test.go b/internal/cli/lint_test.go index 5be006ce5b..038f438987 100644 --- a/internal/cli/lint_test.go +++ b/internal/cli/lint_test.go @@ -1328,6 +1328,9 @@ func TestLintDiagnosticCodesMatchPattern(t *testing.T) { harness.CodeTriggerInvalid, harness.CodePreflightCheckPath, harness.CodeGithubIssueURLDeprecated, + harness.CodeBlockDropsRuntimeFetch, + harness.CodeBlockDropsCIVariableCred, + harness.CodeBlockTriggerIgnored, } seen := map[string]struct{}{} for _, c := range codes { @@ -1695,3 +1698,41 @@ func TestLintCommand_ScopedJSONLintsOnlySelectedAgent(t *testing.T) { assert.Equal(t, "warning", report.Diagnostics[0].Severity) assert.Equal(t, harness.CodeGithubIssueURLDeprecated, report.Diagnostics[0].Code) } + +// lint composes an entry's harness: block as run does, with the same name and path checks. +func TestLintCommand_LintsHarnessBlock(t *testing.T) { + stubLintGitHubToken(t, "test-token") + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + writeLintAgentFixture(t, dir, "my-agent") + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "my-agent.yaml"), []byte(`role: triage +agent: agents/my-agent.md +policy: policies/base.yaml +env: + sandbox: + MY_KNOB: low +`), 0o644)) + writeConfig := func(block string) { + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" +agents: + - name: my-agent + source: harness/my-agent.yaml + harness: +`+block), 0o644)) + } + + writeConfig(" env: { sandbox: { MY_KNOB: high } }\n policy: policies/base.yaml\n") + out, err := executeCmd(newLintCmd(), []string{"--fullsend-dir", dir}) + require.NoError(t, err, out) + assert.NotContains(t, out, "error:") + + writeConfig(" env: { sandbox: { NOT_DECLARED: x } }\n") + out, err = executeCmd(newLintCmd(), []string{"--fullsend-dir", dir}) + require.Error(t, err) + assert.Contains(t, out+err.Error(), `harness.env.sandbox.NOT_DECLARED`) + + writeConfig(" policy: ../outside.yaml\n") + out, err = executeCmd(newLintCmd(), []string{"--fullsend-dir", dir}) + require.Error(t, err, "a block path escaping the config directory is rejected, as in a local harness file") + assert.Contains(t, out+err.Error(), "resolving paths for agent") +} diff --git a/internal/cli/lock.go b/internal/cli/lock.go index 9da9488f9b..f85bd408ad 100644 --- a/internal/cli/lock.go +++ b/internal/cli/lock.go @@ -1,6 +1,7 @@ package cli import ( + "bytes" "context" "errors" "fmt" @@ -227,7 +228,11 @@ func lockOneAgent(ctx context.Context, agentName, absFullsendDir, forgeFlag stri if err != nil { return nil, fmt.Errorf("reading harness file: %w", err) } - harnessHash := fetch.ComputeSHA256(harnessData) + blocks := lockHarnessBlocks(orgCfg, absFullsendDir, agentName, harnessPath) + harnessHash, err := lockHarnessHash(harnessData, blocks) + if err != nil { + return nil, err + } // The subset check also covers the cached path: a fetch-capable harness // whose lock entry is current returns below before the harness is ever @@ -235,8 +240,9 @@ func lockOneAgent(ctx context.Context, agentName, absFullsendDir, forgeFlag stri // the raw declaration here, before the up-to-date return — // allowed_remote_resources and allow_runtime_fetch are not inherited // from base:, so the child's own declaration is the complete list - // (#9291). - if rawH, rawErr := harness.LoadRaw(harnessPath); rawErr == nil && shouldStartFetchService(rawH) { + // (#9291). A harness: block is one more child layer, so with blocks the + // last block's declaration is the complete list. + if rawH, rawErr := harness.RuntimeFetchLayer(harnessPath, agentName, blocks); rawErr == nil && shouldStartFetchService(rawH) { if orgCfg == nil { var cfgErr error if rawH.HasURLReferences() { @@ -324,6 +330,8 @@ func lockOneAgent(ctx context.Context, agentName, absFullsendDir, forgeFlag stri GitHubURL: forge.ConfiguredGitHubURL(), Config: harness.BuildConfigMap(orgCfg), SourceURL: sourceURL, + Blocks: blocks, + Agent: agentName, }) if loadErr != nil { printer.StepFail(fmt.Sprintf("Failed to load harness (forge: %s)", platform)) @@ -602,7 +610,7 @@ func runLockAll(ctx context.Context, fullsendDir, forgeFlag string, update bool, lf.SetHarness(name, result.harnessLock) locked = append(locked, name) } else if entry := lf.Lookup(name); entry != nil { - if isHarnessUpToDate(absFullsendDir, name, entry, printer) { + if isHarnessUpToDate(absFullsendDir, name, entry, orgCfg, printer) { upToDate++ } else { delete(lf.Harnesses, name) @@ -653,15 +661,20 @@ func runLockAll(ctx context.Context, fullsendDir, forgeFlag string, update bool, // .yaml nor .yml exists in the harness directory. var errHarnessNotFound = errors.New("harness file not found") +// localHarnessPaths returns where agentName's harness file may live in the +// local harness directory: the .yaml path, which wins, and the .yml path. +func localHarnessPaths(dir, agentName string) (yamlPath, ymlPath string) { + return filepath.Join(dir, "harness", agentName+".yaml"), filepath.Join(dir, "harness", agentName+".yml") +} + // resolveHarnessPath finds the harness file for agentName, preferring .yaml // over .yml. Warns via printer when both extensions exist. func resolveHarnessPath(dir, agentName string, printer *ui.Printer) (string, error) { - yamlPath := filepath.Join(dir, "harness", agentName+".yaml") + yamlPath, ymlPath := localHarnessPaths(dir, agentName) if _, err := os.Stat(yamlPath); err != nil { if !os.IsNotExist(err) { return "", fmt.Errorf("checking harness file: %w", err) } - ymlPath := filepath.Join(dir, "harness", agentName+".yml") if _, ymlErr := os.Stat(ymlPath); ymlErr != nil { if !os.IsNotExist(ymlErr) { return "", fmt.Errorf("checking harness file: %w", ymlErr) @@ -670,7 +683,7 @@ func resolveHarnessPath(dir, agentName string, printer *ui.Printer) (string, err } return ymlPath, nil } - if _, ymlErr := os.Stat(filepath.Join(dir, "harness", agentName+".yml")); ymlErr == nil { + if _, ymlErr := os.Stat(ymlPath); ymlErr == nil { printer.StepWarn(fmt.Sprintf("Both %s.yaml and %s.yml exist; using .yaml", agentName, agentName)) } return yamlPath, nil @@ -777,9 +790,10 @@ func discoverHarnessNames(dir string) ([]string, error) { } // isHarnessUpToDate checks whether a lock entry's hash matches the current -// harness file on disk. Used by runLockAll to distinguish "already locked" -// from "re-evaluated with no remote deps" when lockOneAgent returns nil. -func isHarnessUpToDate(absFullsendDir, name string, entry *lock.HarnessLock, printer *ui.Printer) bool { +// harness file on disk and the agent's harness: blocks. Used by runLockAll +// to distinguish "already locked" from "re-evaluated with no remote deps" +// when lockOneAgent returns nil. +func isHarnessUpToDate(absFullsendDir, name string, entry *lock.HarnessLock, orgCfg config.ConfigReader, printer *ui.Printer) bool { harnessPath, err := resolveHarnessPath(absFullsendDir, name, printer) if err != nil { printer.StepWarn(fmt.Sprintf("Cannot stat harness for %s: %v; preserving lock entry", name, err)) @@ -790,7 +804,68 @@ func isHarnessUpToDate(absFullsendDir, name string, entry *lock.HarnessLock, pri printer.StepWarn(fmt.Sprintf("Cannot read %s: %v; preserving lock entry", harnessPath, err)) return true } - return !entry.IsStale(fetch.ComputeSHA256(data)) + hash, err := lockHarnessHash(data, lockHarnessBlocks(orgCfg, absFullsendDir, name, harnessPath)) + if err != nil { + printer.StepWarn(fmt.Sprintf("Cannot hash the harness: blocks of %s: %v; preserving lock entry", name, err)) + return true + } + return !entry.IsStale(hash) +} + +// lockHarnessBlocks returns the harness: blocks lock composes on harnessPath: +// those of agentName's agents: entry when harnessPath is that entry's +// harness. lock prefers a local harness/ file, but fullsend run +// composes the blocks on the entry's source or on the built-in agent, so a +// local file the entry does not name is locked without them. +func lockHarnessBlocks(orgCfg config.ConfigReader, absFullsendDir, agentName, harnessPath string) []*config.AgentHarness { + if orgCfg == nil { + return nil + } + entries := orgCfg.AgentEntries() + entry, ok := config.AgentSettingsFor(entries, agentName) + if !ok { + return nil + } + if entry.Source == "" || harness.IsURL(entry.Source) { + // lock resolved this entry's harness unless a local file took its place. + if yamlPath, ymlPath := localHarnessPaths(absFullsendDir, agentName); harnessPath == yamlPath || harnessPath == ymlPath { + return nil + } + } else if !sameFile(filepath.Join(absFullsendDir, entry.Source), harnessPath) { + return nil + } + return config.HarnessBlocksFor(entries, agentName) +} + +// sameFile reports whether two paths name one existing file. +func sameFile(a, b string) bool { + ai, err := os.Stat(a) + if err != nil { + return false + } + bi, err := os.Stat(b) + return err == nil && os.SameFile(ai, bi) +} + +// lockHarnessHash is the hash a lock entry records for an agent's harness: +// the harness file's, or, when the agent's agents: entry carries harness: +// blocks (ADR 0162), the hash of the file followed by each block, so a +// change to a block makes the entry stale like a change to the file. An +// agent without blocks keeps the file hash existing entries record. +func lockHarnessHash(harnessData []byte, blocks []*config.AgentHarness) (string, error) { + if len(blocks) == 0 { + return fetch.ComputeSHA256(harnessData), nil + } + buf := bytes.NewBuffer(slices.Clone(harnessData)) + for _, b := range blocks { + data, err := yaml.Marshal(b) + if err != nil { + return "", fmt.Errorf("serializing harness: block: %w", err) + } + buf.WriteString("\n--- agents entry harness: block\n") + buf.Write(data) + } + return fetch.ComputeSHA256(buf.Bytes()), nil } // lockForgePlatforms determines which forge platform(s) to lock. When a @@ -879,7 +954,7 @@ func planSkillOverrideReplay(h *harness.Harness, deps []resolve.Dependency) ([]s type runLockState struct { loadErr error // lock.yaml exists but cannot be loaded entry *lock.HarnessLock // agentName's entry; nil if none - stale bool // entry does not match the harness file + stale bool // entry does not match the harness file and blocks // pins are the current entry's pins for harness.LoadWithBase, which // resolves a URL base's relative files to them instead of the cache URL // index (#8979). Nil when there is no current entry. @@ -887,8 +962,9 @@ type runLockState struct { } // readRunLock reads agentName's entry in /lock.yaml and -// checks it against the harness at harnessPath. -func readRunLock(absFullsendDir, agentName, harnessPath string) (runLockState, error) { +// checks it against the harness at harnessPath and the agent's harness: +// blocks. +func readRunLock(absFullsendDir, agentName, harnessPath string, blocks []*config.AgentHarness) (runLockState, error) { lf, err := lock.Load(filepath.Join(absFullsendDir, "lock.yaml")) if err != nil { return runLockState{loadErr: err}, nil @@ -901,7 +977,11 @@ func readRunLock(absFullsendDir, agentName, harnessPath string) (runLockState, e if err != nil { return runLockState{}, fmt.Errorf("reading harness file for lock check: %w", err) } - st := runLockState{entry: entry, stale: entry.IsStale(fetch.ComputeSHA256(data))} + hash, err := lockHarnessHash(data, blocks) + if err != nil { + return runLockState{}, err + } + st := runLockState{entry: entry, stale: entry.IsStale(hash)} if st.stale { return st, nil } diff --git a/internal/cli/lock_pins_test.go b/internal/cli/lock_pins_test.go index d39888a7f8..b2b594bb98 100644 --- a/internal/cli/lock_pins_test.go +++ b/internal/cli/lock_pins_test.go @@ -78,7 +78,7 @@ func TestReadRunLock_PinsURLBaseFiles(t *testing.T) { // runLockPins returns the pins readRunLock builds for agentName. func runLockPins(t *testing.T, dir, agentName, harnessPath string) map[string]harness.LockedPin { t.Helper() - st, err := readRunLock(dir, agentName, harnessPath) + st, err := readRunLock(dir, agentName, harnessPath, nil) require.NoError(t, err) return st.pins } @@ -125,7 +125,7 @@ func TestReadRunLock_NoPins(t *testing.T) { t.Run("no lock file", func(t *testing.T) { dir, harnessPath := setup(t, nil) - st, err := readRunLock(dir, "code", harnessPath) + st, err := readRunLock(dir, "code", harnessPath, nil) require.NoError(t, err) assert.Equal(t, runLockState{}, st) }) @@ -133,7 +133,7 @@ func TestReadRunLock_NoPins(t *testing.T) { t.Run("unreadable lock file", func(t *testing.T) { dir, harnessPath := setup(t, nil) require.NoError(t, os.WriteFile(filepath.Join(dir, "lock.yaml"), []byte("version: [\n"), 0o644)) - st, err := readRunLock(dir, "code", harnessPath) + st, err := readRunLock(dir, "code", harnessPath, nil) require.NoError(t, err) assert.Error(t, st.loadErr) assert.Nil(t, st.pins) @@ -141,14 +141,14 @@ func TestReadRunLock_NoPins(t *testing.T) { t.Run("no entry for the agent", func(t *testing.T) { dir, harnessPath := setup(t, entry(harnessHash)) - st, err := readRunLock(dir, "other", harnessPath) + st, err := readRunLock(dir, "other", harnessPath, nil) require.NoError(t, err) assert.Equal(t, runLockState{}, st) }) t.Run("stale entry", func(t *testing.T) { dir, harnessPath := setup(t, entry(fetch.ComputeSHA256([]byte("older harness")))) - st, err := readRunLock(dir, "code", harnessPath) + st, err := readRunLock(dir, "code", harnessPath, nil) require.NoError(t, err) assert.True(t, st.stale) assert.NotNil(t, st.entry) @@ -157,7 +157,7 @@ func TestReadRunLock_NoPins(t *testing.T) { t.Run("missing harness file", func(t *testing.T) { dir, _ := setup(t, entry(harnessHash)) - _, err := readRunLock(dir, "code", filepath.Join(dir, "harness", "missing.yaml")) + _, err := readRunLock(dir, "code", filepath.Join(dir, "harness", "missing.yaml"), nil) assert.ErrorContains(t, err, "reading harness file for lock check") }) diff --git a/internal/cli/run.go b/internal/cli/run.go index 8a772514be..ea2f08329d 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -359,6 +359,25 @@ func loadRunConfig(path string) (runConfig, error) { return runConfig{source: source, perRepo: perRepoCfg}, nil } +// siblingConfigBlockError fails a run whose agents: entry has a harness: +// block in the sibling .fullsend/config.yaml that loadRunConfig falls back +// to. The entry's runtime, model and effort are read from there, but a block +// composes only from the config at the root of --fullsend-dir, and dropping +// it would run the agent without its settings. +func siblingConfigBlockError(path, agentName string) error { + rc, err := loadRunConfig(path) + if err != nil || rc.perRepo == nil { + return nil // reported where the run loads this config + } + if filepath.Dir(rc.source) == filepath.Dir(path) { + return nil // the config blocks compose from + } + if len(config.HarnessBlocksFor(rc.perRepo.AgentEntries(), agentName)) == 0 { + return nil + } + return fmt.Errorf("%s: the %q agents entry has a harness: block, which applies only when --fullsend-dir is the directory that holds config.yaml; pass --fullsend-dir %s", rc.source, agentName, filepath.Dir(rc.source)) +} + // backendFromConfigFile selects the runtime for agentName from the config // file at path (see loadRunConfig for which file and layering). The // returned source names the file, suffixed with agents. @@ -556,6 +575,11 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep return err } + if err := siblingConfigBlockError(orgConfigPath, agentName); err != nil { + printer.StepFail("Failed to load fullsend config") + return err + } + // Detect forge platform after config is loaded so config.forge can be consulted (ADR 0088). forgePlatform, err := detectForgePlatform(forgeFlag, orgCfg) if err != nil { @@ -715,9 +739,16 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } } + // The agent's agents: entry may carry harness: blocks, composed on the + // harness as child layers (ADR 0162). + if orgCfg != nil { + composeOpts.Blocks = config.HarnessBlocksFor(orgCfg.AgentEntries(), agentName) + composeOpts.Agent = agentName + } + // A current lock entry pins the relative files of a URL base, so pass // its pins in before composition fetches them (#8979). - lockState, err := readRunLock(absFullsendDir, agentName, harnessPath) + lockState, err := readRunLock(absFullsendDir, agentName, harnessPath, composeOpts.Blocks) if err != nil { return err } @@ -3945,6 +3976,9 @@ func init() { // keys there; only credential values (child env) may expand them. sandbox.CredentialOnlyExpansionKeys(k) } + // An agents: entry's harness: block may not set a reserved name in + // either env section (ADR 0162 Decision 5). + harness.SetReservedSandboxKeyCheck(isReservedSandboxKey) } // isReservedSandboxKey reports whether an env.sandbox key is blocked by name: @@ -8170,13 +8204,13 @@ func resolveAgentSource(ctx context.Context, fullsendDir, agentName string, forg return "", nil, fmt.Errorf("resolving agent %q: not in config and agents-repo fallback unavailable", agentName) } if entry.Source == "" { - // An override-only entry tunes a built-in agent (runtime/model/ - // effort) but registers no harness: the built-in still comes from - // the agents repo, exactly as if the entry were absent. + // An override-only entry tunes a built-in agent (any setting + // HasSettings counts) but registers no harness: the built-in still + // comes from the agents repo, exactly as if the entry were absent. if path, deps, ok := tryAgentsRepoFallback(ctx, agentName, forgeClient, composeOpts, printer); ok { return path, deps, nil } - return "", nil, fmt.Errorf("resolving agent %q: config entry has no source (it only sets runtime/model/effort) and agents-repo fallback unavailable", agentName) + return "", nil, fmt.Errorf("resolving agent %q: config entry has no source (it only tunes the built-in agent) and agents-repo fallback unavailable", agentName) } if harness.IsURL(entry.Source) { diff --git a/internal/config/agent_harness.go b/internal/config/agent_harness.go new file mode 100644 index 0000000000..1b00edf2f6 --- /dev/null +++ b/internal/config/agent_harness.go @@ -0,0 +1,273 @@ +package config + +import ( + "fmt" + "slices" + "strings" + "unicode" + + "gopkg.in/yaml.v3" +) + +// AgentHarness is an agents: entry's harness: block (ADR 0162): a partial +// harness composed on the agent's harness as a child layer, with nothing +// pinned, so a repository can change harness settings without writing a +// base: harness. The config package keeps the block as YAML; the harness +// package decodes it and composes it. +type AgentHarness struct { + node *yaml.Node +} + +// excludedAgentHarnessKeys are the harness fields a block may not set +// (ADR 0162 Decision 2): base, since the entry's source already names the +// harness, and the deprecated forge and runner_env. runner_env would add +// runner variables the agent's harness does not declare, so an overlay in +// the block may not set it either. +var excludedAgentHarnessKeys = map[string]string{ + "base": "the entry's source names the harness the block builds on", + "forge": "deprecated by ADR 0088; use overlays that test runtime.forge", + "runner_env": "deprecated by ADR 0055; use env.runner", +} + +// agentHarnessCheck is the harness package's check of a block's content: +// unknown keys, value types and values, schema_version and reserved env +// names. This package cannot import internal/harness, which registers the +// check with SetAgentHarnessCheck; until then Validate checks the excluded +// fields only. +var agentHarnessCheck func(*AgentHarness) error + +// SetAgentHarnessCheck registers the check Validate runs on a block's +// content, so config and manifest validation reject what is wrong with a +// block by itself (ADR 0162 Decision 2). +func SetAgentHarnessCheck(f func(*AgentHarness) error) { + agentHarnessCheck = f +} + +// maxAgentHarnessNodes bounds a block once its YAML aliases are expanded, +// so nested aliases cannot grow it without limit. +const maxAgentHarnessNodes = 10000 + +// UnmarshalYAML keeps the block's mapping node, with its YAML aliases and +// merge keys resolved (plainYAML). A null block decodes to a nil +// *AgentHarness without calling this method. +func (h *AgentHarness) UnmarshalYAML(value *yaml.Node) error { + budget := maxAgentHarnessNodes + plain, err := plainYAML(value, map[*yaml.Node]bool{}, &budget) + if err != nil { + return err + } + if plain.Kind != yaml.MappingNode { + return fmt.Errorf("harness: must be a mapping of harness fields") + } + h.node = plain + return nil +} + +// plainYAML returns a copy of n with every alias replaced by a copy of its +// target and every merge key (<<) folded into its mapping, so the block +// stands on its own and the checks on its keys see everything it sets. As +// in yaml.v3, a mapping's own keys win over merged ones and the first merged +// mapping wins. A key repeated inside one merged mapping fails: folding +// would hide the duplicate from the strict decode. +func plainYAML(n *yaml.Node, expanding map[*yaml.Node]bool, budget *int) (*yaml.Node, error) { + n = resolveAlias(n) + if expanding[n] { + return nil, fmt.Errorf("harness: a YAML anchor contains itself") + } + if *budget--; *budget < 0 { + return nil, fmt.Errorf("harness: block is too large once its YAML aliases are expanded") + } + cp := *n + cp.Anchor, cp.Content = "", nil + expanding[n] = true + defer delete(expanding, n) + + if n.Kind != yaml.MappingNode { + for _, c := range n.Content { + child, err := plainYAML(c, expanding, budget) + if err != nil { + return nil, err + } + cp.Content = append(cp.Content, child) + } + return &cp, nil + } + + own := map[string]bool{} + var merged []*yaml.Node + for i := 0; i+1 < len(n.Content); i += 2 { + key, val := n.Content[i], n.Content[i+1] + if key.Kind == yaml.ScalarNode && key.Value == "<<" && key.ShortTag() == "!!merge" { + sources := []*yaml.Node{val} + if val = resolveAlias(val); val.Kind == yaml.SequenceNode { + sources = val.Content + } + for _, src := range sources { + if resolveAlias(src).Kind != yaml.MappingNode { + return nil, fmt.Errorf("harness: a merge key (<<) takes a mapping or a list of mappings") + } + m, err := plainYAML(src, expanding, budget) + if err != nil { + return nil, err + } + seen := map[string]bool{} + for j := 0; j+1 < len(m.Content); j += 2 { + if k := m.Content[j]; k.Kind == yaml.ScalarNode { + if seen[k.Value] { + return nil, fmt.Errorf("harness: a merged mapping repeats the key %q", k.Value) + } + seen[k.Value] = true + } + } + merged = append(merged, m.Content...) + } + continue + } + k, err := plainYAML(key, expanding, budget) + if err != nil { + return nil, err + } + v, err := plainYAML(val, expanding, budget) + if err != nil { + return nil, err + } + cp.Content = append(cp.Content, k, v) + own[k.Value] = true + } + for i := 0; i+1 < len(merged); i += 2 { + if k := merged[i]; !own[k.Value] { + cp.Content = append(cp.Content, k, merged[i+1]) + own[k.Value] = true + } + } + return &cp, nil +} + +// MarshalYAML writes the block back as it was read. +func (h AgentHarness) MarshalYAML() (any, error) { + if h.node == nil { + return map[string]any{}, nil + } + return h.node, nil +} + +// IsEmpty reports whether the block sets nothing. Nil-safe. +func (h *AgentHarness) IsEmpty() bool { + return h == nil || h.node == nil || len(h.node.Content) == 0 +} + +// DecodeStrict decodes the block into out, failing on a key out does not +// define (ADR 0162 Decision 2: an unknown key fails). +func (h *AgentHarness) DecodeStrict(out any) error { + if h.IsEmpty() { + return nil + } + return decodeKnownFields(h.node, out) +} + +// Validate checks the block's keys (CheckKeys), then runs the harness +// package's check of the block's content (SetAgentHarnessCheck). +func (h *AgentHarness) Validate() error { + if err := h.CheckKeys(); err != nil { + return err + } + if h.IsEmpty() || agentHarnessCheck == nil { + return nil + } + return agentHarnessCheck(h) +} + +// CheckKeys rejects the fields a block may not set, at its top level and, +// for runner_env, in its overlays, and a key with a control character. +func (h *AgentHarness) CheckKeys() error { + if h.IsEmpty() { + return nil + } + if err := checkScalarKeys(h.node, "harness"); err != nil { + return err + } + if err := checkPrintableKeys(h.node); err != nil { + return err + } + for i := 0; i+1 < len(h.node.Content); i += 2 { + if key := h.node.Content[i].Value; excludedAgentHarnessKeys[key] != "" { + return fmt.Errorf("harness.%s is not allowed in an agents entry: %s", key, excludedAgentHarnessKeys[key]) + } + } + for j, overlay := range h.overlays() { + if mappingNode(overlay, "runner_env") != nil { + return fmt.Errorf("harness.overlays[%d].runner_env is not allowed in an agents entry: %s", j, excludedAgentHarnessKeys["runner_env"]) + } + } + return nil +} + +// checkPrintableKeys rejects a key with a control character anywhere in n. +// Errors and diagnostics name a block's keys, and dispatch prints them in +// workflow command lines, where a newline would start a new command. +func checkPrintableKeys(n *yaml.Node) error { + if n.Kind == yaml.MappingNode { + for i := 0; i+1 < len(n.Content); i += 2 { + if k := n.Content[i]; strings.ContainsFunc(k.Value, unicode.IsControl) { + return fmt.Errorf("harness: key %q has a control character", k.Value) + } + } + } + for _, c := range n.Content { + if err := checkPrintableKeys(c); err != nil { + return err + } + } + return nil +} + +// Sets reports whether the block sets key at its top level. Nil-safe. +func (h *AgentHarness) Sets(key string) bool { + return !h.IsEmpty() && mappingNode(h.node, key) != nil +} + +// overlays returns the block's overlays entries that are mappings. +func (h *AgentHarness) overlays() []*yaml.Node { + seq := mappingNode(h.node, "overlays") + if seq == nil || seq.Kind != yaml.SequenceNode { + return nil + } + var out []*yaml.Node + for _, o := range seq.Content { + if o = resolveAlias(o); o.Kind == yaml.MappingNode { + out = append(out, o) + } + } + return out +} + +// clone returns a deep copy. Nil-safe. +func (h *AgentHarness) clone() *AgentHarness { + if h == nil { + return nil + } + return &AgentHarness{node: cloneYAMLNode(h.node)} +} + +func cloneAgentHarnesses(in []*AgentHarness) []*AgentHarness { + if in == nil { + return nil + } + out := make([]*AgentHarness, len(in)) + for i, h := range in { + out[i] = h.clone() + } + return out +} + +func cloneYAMLNode(n *yaml.Node) *yaml.Node { + if n == nil { + return nil + } + cp := *n + cp.Content = slices.Clone(n.Content) + for i, c := range cp.Content { + cp.Content[i] = cloneYAMLNode(c) + } + return &cp +} diff --git a/internal/config/agent_harness_test.go b/internal/config/agent_harness_test.go new file mode 100644 index 0000000000..40d05aed89 --- /dev/null +++ b/internal/config/agent_harness_test.go @@ -0,0 +1,209 @@ +package config + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" +) + +func parseAgents(t *testing.T, doc string) []AgentEntry { + t.Helper() + return parseAgentSettingsConfig(t, doc).AgentEntries() +} + +func TestAgentHarness_DecodeAndSettings(t *testing.T) { + agents := parseAgents(t, ` +agents: + - name: review + harness: + env: + sandbox: { REVIEW_FINDING_SEVERITY_THRESHOLD: medium } + - name: code + harness: {} + - name: triage + harness: ~ +`) + require.Len(t, agents, 3) + assert.False(t, agents[0].Harness.IsEmpty()) + assert.True(t, agents[0].HasSettings(), "a non-empty block counts as a setting (ADR 0162 Decision 8)") + assert.True(t, agents[0].IsOverrideOnly()) + assert.True(t, agents[1].Harness.IsEmpty()) + assert.False(t, agents[1].HasSettings(), "an empty block sets nothing") + assert.Nil(t, agents[2].Harness) + + // Ten aliases to a list of ten aliases, four levels deep, expand past the node limit. + bomb := "agents:\n - name: review\n harness:\n a: &a [" + strings.Repeat("s,", 10) + "]\n" + for _, level := range []string{"b: &b [" + strings.Repeat("*a,", 10), "c: &c [" + strings.Repeat("*b,", 10), "d: [" + strings.Repeat("*c,", 10)} { + bomb += " " + level + "]\n" + } + for doc, want := range map[string]string{ + "agents:\n - name: review\n harness: [env]\n": "harness: must be a mapping", + "agents:\n - name: review\n harness: &h { overlays: [ *h ] }\n": "a YAML anchor contains itself", + "agents:\n - name: review\n harness: { <<: [ a ] }\n": "a merge key (<<) takes a mapping", + "x: &a { image: a, image: b }\nagents:\n - name: review\n harness: { <<: *a }\n": `a merged mapping repeats the key "image"`, + bomb: "too large once its YAML aliases are expanded", + } { + assert.ErrorContains(t, yaml.Unmarshal([]byte(doc), &perRepoConfig{}), want) + } +} + +func TestAgentHarness_RoundTrip(t *testing.T) { + agents := parseAgents(t, ` +agents: + - name: code + harness: + timeout_minutes: 90 + env: + sandbox: { TIMEOUT_SECONDS: "5400" } +`) + out, err := yaml.Marshal(perRepoConfig{Agents: agents}) + require.NoError(t, err) + again := parseAgents(t, string(out)) + require.Len(t, again, 1) + data, err := yaml.Marshal(again[0].Harness) + require.NoError(t, err) + assert.Contains(t, string(data), "timeout_minutes: 90") + assert.Contains(t, string(data), `TIMEOUT_SECONDS: "5400"`) +} + +func TestAgentHarness_DecodeStrict(t *testing.T) { + agents := parseAgents(t, "agents:\n - name: code\n harness: { timeout_minutes: 90, timeout_minute: 5 }\n") + var out struct { + TimeoutMinutes int `yaml:"timeout_minutes"` + Model string `yaml:"model"` + } + assert.ErrorContains(t, agents[0].Harness.DecodeStrict(&out), "timeout_minute") + + // A merge key from an anchor outside the block resolves when the file is read; the block's own key wins. + agents = parseAgents(t, "x-shared: &s { timeout_minutes: 30, model: opus }\nagents:\n - name: code\n harness:\n <<: *s\n timeout_minutes: 90\n") + require.NoError(t, agents[0].Harness.DecodeStrict(&out)) + assert.Equal(t, 90, out.TimeoutMinutes) + assert.Equal(t, "opus", out.Model) + + var empty *AgentHarness + assert.NoError(t, empty.DecodeStrict(&out), "an absent block decodes to nothing") +} + +func TestAgentHarness_ValidateExcludedFields(t *testing.T) { + for _, tc := range []struct { + name, block, want string + }{ + {"base", "{ base: harness/review.yaml }", "harness.base is not allowed"}, + {"forge", "{ forge: { github: {} } }", "harness.forge is not allowed"}, + {"runner_env", "{ runner_env: { A: b } }", "harness.runner_env is not allowed"}, + {"overlay runner_env", "{ overlays: [ { when: \"true\" }, { when: \"true\", runner_env: { A: b } } ] }", "harness.overlays[1].runner_env is not allowed"}, + {"runner_env through a merge key", "{ skills: [ &m { runner_env: { A: b } } ], <<: *m }", "harness.runner_env is not allowed"}, + {"key with a control character", "{ env: { runner: { \"A\\n::warning::x\": b } } }", `harness: key "A\n::warning::x" has a control character`}, + } { + t.Run(tc.name, func(t *testing.T) { + agents := parseAgents(t, "agents:\n - name: review\n harness: "+tc.block+"\n") + assert.ErrorContains(t, ValidateAgentEntries(agents, nil), tc.want) + }) + } + + agents := parseAgents(t, "agents:\n - name: review\n harness: { schema_version: 1, overlays: [ { when: \"true\", env: { sandbox: { A: b } } } ] }\n") + assert.NoError(t, agents[0].Harness.Validate()) +} + +// Validate runs the content check the harness package registers. +func TestAgentHarness_ValidateRunsRegisteredCheck(t *testing.T) { + SetAgentHarnessCheck(func(*AgentHarness) error { return fmt.Errorf("content check ran") }) + t.Cleanup(func() { SetAgentHarnessCheck(nil) }) + agents := parseAgents(t, "agents:\n - name: review\n harness: { timeout_minutes: 30 }\n") + assert.ErrorContains(t, ValidateAgentEntries(agents, nil), "content check ran") +} + +func TestAgentHarness_Sets(t *testing.T) { + agents := parseAgents(t, ` +agents: + - name: review + harness: + timeout_minutes: 30 +`) + h := agents[0].Harness + assert.True(t, h.Sets("timeout_minutes")) + assert.False(t, h.Sets("model")) + var none *AgentHarness + assert.False(t, none.Sets("model")) +} + +func TestHarnessBlocksFor(t *testing.T) { + agents := parseAgents(t, ` +agents: + - name: review + harness: { timeout_minutes: 30 } + - name: code + enabled: false + harness: { timeout_minutes: 90 } +`) + assert.Len(t, HarnessBlocksFor(agents, "Review"), 1) + assert.Nil(t, HarnessBlocksFor(agents, "code"), "a disabled entry's block has no effect") + assert.Nil(t, HarnessBlocksFor(agents, "triage")) + assert.NoError(t, ValidateAgentEntries(agents, nil), "a block on a disabled entry is not an error") +} + +func TestValidateAgentEntries_OneControlPerSetting(t *testing.T) { + const custom = "harness/custom.yaml" + for _, tc := range []struct { + name, doc, want string + }{ + {"model both", "agents:\n - name: review\n model: opus\n harness: { model: sonnet }\n", "model is set both on the entry and in its harness: block"}, + {"effort both", "agents:\n - name: review\n effort: high\n harness: { effort: low }\n", "effort is set both on the entry and in its harness: block"}, + {"model both through a merge key", "x-shared: &s { model: sonnet }\nagents:\n - name: review\n model: opus\n harness: { <<: *s }\n", "model is set both on the entry and in its harness: block"}, + {"trigger both on a built-in agent", "agents:\n - name: review\n trigger: \"true\"\n harness: { trigger: \"true\" }\n", "trigger is set both on the entry and in its harness: block"}, + } { + t.Run(tc.name, func(t *testing.T) { + assert.ErrorContains(t, ValidateAgentEntries(parseAgents(t, tc.doc), nil), tc.want) + }) + } + + for _, doc := range []string{ + "agents:\n - name: review\n model: opus\n harness: { effort: high }\n", + "agents:\n - name: review\n trigger: \"true\"\n harness: { timeout_minutes: 30 }\n", + "agents:\n - source: " + custom + "\n harness: { trigger: \"true\" }\n", + // On a built-in agent the block's trigger loads; composition ignores it with a warning. + "agents:\n - name: review\n harness: { trigger: \"true\" }\n", + } { + assert.NoError(t, ValidateAgentEntries(parseAgents(t, doc), nil), doc) + } +} + +func TestValidateAgentEntries_ModelBothAcrossLayers(t *testing.T) { + // The check runs on the merged entry, so a base entry's model conflicts with an overlay block's. + w, err := ParsePerRepoConfigWriterLayered( + []byte("agents:\n - name: review\n harness: { model: sonnet }\n"), + []byte("agents:\n - name: review\n model: opus\n")) + require.NoError(t, err) + assert.ErrorContains(t, w.Validate(), "model is set both on the entry and in its harness: block") +} + +func TestValidateMergedManaged_HarnessInOneLayerOnly(t *testing.T) { + var defaults, repo ManagedConfig + require.NoError(t, yaml.Unmarshal([]byte("agents:\n - name: review\n harness: { timeout_minutes: 30 }\n"), &defaults)) + require.NoError(t, yaml.Unmarshal([]byte("agents:\n - name: review\n model: opus\n"), &repo)) + assert.NoError(t, ValidateMergedManaged(MergeManaged(defaults.Writer(), repo.Writer())), "one layer may set the block") + + require.NoError(t, yaml.Unmarshal([]byte("agents:\n - name: review\n harness: { env: { sandbox: { A: b } } }\n"), &repo)) + err := ValidateMergedManaged(MergeManaged(defaults.Writer(), repo.Writer())) + assert.ErrorContains(t, err, `agents entry "review": harness: is set in more than one repos.yaml config layer`) + + require.NoError(t, yaml.Unmarshal([]byte("agents:\n - name: review\n model: opus\n harness: {}\n"), &repo)) + assert.NoError(t, ValidateMergedManaged(MergeManaged(defaults.Writer(), repo.Writer())), "an empty block is not a second layer") + + var emptyParent, child ManagedConfig + require.NoError(t, yaml.Unmarshal([]byte("agents:\n - name: review\n model: opus\n harness: {}\n"), &emptyParent)) + require.NoError(t, yaml.Unmarshal([]byte("agents:\n - name: review\n harness: { timeout_minutes: 30 }\n"), &child)) + assert.NoError(t, ValidateMergedManaged(MergeManaged(emptyParent.Writer(), child.Writer())), "nor is an empty block in the parent layer") +} + +func TestAgentHarness_EmptyBlock(t *testing.T) { + var h AgentHarness + out, err := yaml.Marshal(h) + require.NoError(t, err) + assert.Equal(t, "{}\n", string(out), "a block with no node writes an empty mapping") + assert.NoError(t, (&h).Validate()) +} diff --git a/internal/config/config.go b/internal/config/config.go index 6a78445bf0..2e0a7b4ea7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -56,6 +56,10 @@ var validConfigAgentName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]*$`) // tombstones an inherited entry (per-key layered merge, like // ConfigModelAliases). Values are ValidModelRef through the repo alias // table. Keys must match ValidSubagentKey. +// +// Harness is a partial harness composed on the agent's harness as a child +// layer (ADR 0162); see AgentHarness. The keyed merge keeps a parent +// layer's block as a layer of its own beneath the overlay's. type AgentEntry struct { Name string `yaml:"name,omitempty"` Source string `yaml:"source,omitempty"` @@ -66,12 +70,47 @@ type AgentEntry struct { Effort string `yaml:"effort,omitempty"` Subagents map[string]*string `yaml:"subagents,omitempty"` Trigger string `yaml:"trigger,omitempty"` + Harness *AgentHarness `yaml:"harness,omitempty"` + + // inheritedHarness holds the harness: blocks of parent config layers, + // outermost first, below Harness. Set only by the keyed merge. + inheritedHarness []*AgentHarness `yaml:"-"` } // HasSettings reports whether the entry tunes runtime, model, effort, -// subagents or trigger. +// subagents, trigger or harness fields. func (a AgentEntry) HasSettings() bool { - return a.Runtime != "" || a.Model != "" || a.Effort != "" || len(a.Subagents) > 0 || strings.TrimSpace(a.Trigger) != "" + return a.Runtime != "" || a.Model != "" || a.Effort != "" || len(a.Subagents) > 0 || strings.TrimSpace(a.Trigger) != "" || len(a.HarnessBlocks()) > 0 +} + +// HarnessBlocks returns the entry's non-empty harness: blocks in +// composition order: the blocks of parent config layers (config.base.yaml +// first), then the entry's own. +func (a AgentEntry) HarnessBlocks() []*AgentHarness { + var blocks []*AgentHarness + for _, h := range append(slices.Clone(a.inheritedHarness), a.Harness) { + if !h.IsEmpty() { + blocks = append(blocks, h) + } + } + return blocks +} + +// HarnessBlocksFor returns the harness: blocks of name's entry in an +// effective (merged) agent list, the entry AgentSettingsFor reads: nil +// when there is none or it is disabled, since a disabled agent does not +// run (ADR 0162). +func HarnessBlocksFor(agents []AgentEntry, name string) []*AgentHarness { + entry, ok := AgentSettingsFor(agents, name) + if !ok || !entry.IsEnabled() { + return nil + } + return entry.HarnessBlocks() +} + +// harnessSets reports whether any of the entry's harness: blocks sets key. +func (a AgentEntry) harnessSets(key string) bool { + return slices.ContainsFunc(a.HarnessBlocks(), func(h *AgentHarness) bool { return h.Sets(key) }) } // IsOverrideOnly reports whether the entry only tunes an agent defined @@ -730,8 +769,8 @@ func EnsureDefaultAllowedRemoteResources(existing []string) []string { return result } -// validateAgentSettings checks an entry's runtime, model, effort and -// subagents values. +// validateAgentSettings checks an entry's runtime, model, effort, +// subagents and trigger values and its harness: blocks. func validateAgentSettings(i int, entry AgentEntry) error { label := entry.Name if label == "" { @@ -749,6 +788,21 @@ func validateAgentSettings(i int, entry AgentEntry) error { if err := celtrigger.Validate(entry.Trigger); err != nil { return fmt.Errorf("agents[%d] (%s): invalid trigger: %w", i, label, err) } + for _, h := range entry.HarnessBlocks() { + if err := h.Validate(); err != nil { + return fmt.Errorf("agents[%d] (%s): %w", i, label, err) + } + } + // One setting, one control (ADR 0162 Decision 6): setting model, effort + // or trigger both on the entry and in a harness: block fails rather + // than letting one silently win. + for _, field := range []struct{ key, value string }{ + {"model", entry.Model}, {"effort", entry.Effort}, {"trigger", strings.TrimSpace(entry.Trigger)}, + } { + if field.value != "" && entry.harnessSets(field.key) { + return fmt.Errorf("agents[%d] (%s): %s is set both on the entry and in its harness: block; set it in one place", i, label, field.key) + } + } for key, val := range entry.Subagents { if !ValidSubagentKey(key) { return fmt.Errorf("agents[%d] (%s): invalid subagent key %q: must be lowercase alphanumeric segments joined by hyphens (max 64 chars), or \"default\"", i, label, key) @@ -855,7 +909,7 @@ func validateAgentEntriesAt(agents []AgentEntry, positions []int, allowlist []st // merge (the merged entry carries the parent's source), so by the // time an entry reaches validation without one it must be built in. if !entry.HasSettings() { - return fmt.Errorf("agents[%d]: enabled agent entry must have a source (or, to tune a built-in agent, a name plus runtime, model, effort, subagents or trigger)", i) + return fmt.Errorf("agents[%d]: enabled agent entry must have a source (or, to tune a built-in agent, a name plus runtime, model, effort, subagents, trigger or harness)", i) } if entry.Name == "" { return fmt.Errorf("agents[%d]: agent entry without a source must name the agent it tunes", i) @@ -1415,6 +1469,16 @@ func ValidateMergedManaged(w PerRepoConfigWriter) error { if err := c.validateLocalFields(); err != nil { return err } + // The merged layers are written as one config.yaml, which holds one + // harness: block per entry. Two blocks cannot be folded into one + // without changing how they compose (a parent block's overlays would + // apply above the child's top-level values), so only one managed layer + // may set an agent's block. + for _, a := range c.Agents { + if len(a.inheritedHarness) > 0 { + return fmt.Errorf("agents entry %q: harness: is set in more than one repos.yaml config layer (defaults, forge section, repository); set it in one of them", a.DerivedName()) + } + } return validateAgentEntries(c.AgentEntries(), EffectiveAllowedResources(c), true, false) } diff --git a/internal/config/effective.go b/internal/config/effective.go index 5bdc8cabef..857d605852 100644 --- a/internal/config/effective.go +++ b/internal/config/effective.go @@ -43,7 +43,11 @@ func EffectiveYAML(r PerRepoConfigReader) ([]byte, error) { out["tracker"] = t } if agents := r.AgentEntries(); len(agents) > 0 { - out["agents"] = agents + rendered, err := effectiveAgents(agents) + if err != nil { + return nil, err + } + out["agents"] = rendered } if n := r.StatusNotifications(); n != nil { out["status_notifications"] = n @@ -115,3 +119,32 @@ func EffectiveYAML(r PerRepoConfigReader) ([]byte, error) { } return yaml.Marshal(out) } + +// effectiveAgents returns agents as the effective view renders them. An +// entry that inherits a harness: block lists every block under harness, +// outermost layer first: the blocks compose as separate layers (ADR 0162), +// so showing only the entry's own would hide a parent's. +func effectiveAgents(agents []AgentEntry) ([]any, error) { + out := make([]any, len(agents)) + for i, a := range agents { + out[i] = a + if len(a.inheritedHarness) == 0 { + continue + } + var entry yaml.Node + if err := entry.Encode(a); err != nil { + return nil, err + } + layers := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq"} + for _, h := range a.HarnessBlocks() { + layers.Content = append(layers.Content, cloneYAMLNode(h.node)) + } + for j := 0; j+1 < len(entry.Content); j += 2 { + if entry.Content[j].Value == "harness" { + entry.Content[j+1] = layers + } + } + out[i] = &entry + } + return out, nil +} diff --git a/internal/config/effective_test.go b/internal/config/effective_test.go index bff7d1dc8d..3607b65415 100644 --- a/internal/config/effective_test.go +++ b/internal/config/effective_test.go @@ -9,7 +9,8 @@ import ( ) func TestEffectiveYAML_LayersOverlayBaseAndDefaults(t *testing.T) { - overlay, err := ParsePerRepoConfigWriter([]byte("kill_switch: true\nruntime: pi\nauthorization:\n - provider: owners_file\n")) + overlay, err := ParsePerRepoConfigWriter([]byte("kill_switch: true\nruntime: pi\nauthorization:\n - provider: owners_file\n" + + "agents:\n - name: review\n harness: { timeout_minutes: 90 }\n - name: code\n effort: high\n")) require.NoError(t, err) base := []byte(`version: "1" keep_history: false @@ -34,6 +35,11 @@ inference: models: aliases: fast: some-model +agents: + - name: review + harness: { timeout_minutes: 30 } + - name: code + harness: { timeout_minutes: 60 } `) layered, err := LayerOnBase(overlay, base) require.NoError(t, err) @@ -59,6 +65,11 @@ models: assert.Equal(t, "us-east5", inference["region"]) assert.Contains(t, inference, "wif_provider") assert.Contains(t, inference, "openai") + // Blocks set in both layers compose as two layers, so both are shown, base first. + assert.Equal(t, []any{ + map[string]any{"name": "review", "harness": []any{map[string]any{"timeout_minutes": 30}, map[string]any{"timeout_minutes": 90}}}, + map[string]any{"name": "code", "effort": "high", "harness": map[string]any{"timeout_minutes": 60}}, + }, got["agents"]) } func TestEffectiveYAML_InheritsInferenceGateway(t *testing.T) { diff --git a/internal/config/interfaces.go b/internal/config/interfaces.go index bcc24303d9..b203d03415 100644 --- a/internal/config/interfaces.go +++ b/internal/config/interfaces.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "strings" "gopkg.in/yaml.v3" @@ -261,6 +262,16 @@ func (c *perRepoConfig) AgentEntries() []AgentEntry { } merged.Subagents = cloned } + // harness: blocks layer like harness inheritance (ADR 0162): + // the parent's block stays a layer of its own beneath the + // overlay's, and the harness package composes them in order. An + // empty block sets nothing, like no block, in either layer. + if !oi.entry.Harness.IsEmpty() { + if !merged.Harness.IsEmpty() { + merged.inheritedHarness = append(slices.Clone(merged.inheritedHarness), merged.Harness) + } + merged.Harness = oi.entry.Harness + } } result = append(result, merged) } diff --git a/internal/config/interfaces_test.go b/internal/config/interfaces_test.go index a8a8751b11..838865a3b2 100644 --- a/internal/config/interfaces_test.go +++ b/internal/config/interfaces_test.go @@ -69,6 +69,47 @@ func TestPerRepoConfig_AgentEntries_TriggerLayeredMerge(t *testing.T) { assert.Equal(t, parentTrigger, merged[0].Trigger, "a blank trigger inherits the parent's") } +func TestPerRepoConfig_AgentEntries_HarnessLayeredMerge(t *testing.T) { + w, err := ParsePerRepoConfigWriterLayered([]byte(` +agents: + - name: review + harness: { env: { sandbox: { REVIEW_FINDING_SEVERITY_THRESHOLD: high } } } + - name: code + model: opus + - name: retro + harness: {} +`), []byte(` +agents: + - name: review + harness: { timeout_minutes: 30 } + - name: code + harness: { timeout_minutes: 90 } + - name: triage + harness: { timeout_minutes: 10 } + - name: retro + harness: { timeout_minutes: 20 } +`)) + require.NoError(t, err) + + byName := map[string]AgentEntry{} + for _, a := range w.AgentEntries() { + byName[a.DerivedName()] = a + } + review := byName["review"].HarnessBlocks() + require.Len(t, review, 2, "each config layer's block stays a layer of its own") + assert.True(t, review[0].Sets("timeout_minutes"), "config.base.yaml's block comes first") + assert.True(t, review[1].Sets("env"), "config.yaml's block comes last") + + code := byName["code"].HarnessBlocks() + require.Len(t, code, 1, "an overlay entry without a block keeps the parent's") + assert.True(t, code[0].Sets("timeout_minutes")) + assert.Equal(t, "opus", byName["code"].Model) + + assert.Len(t, byName["triage"].HarnessBlocks(), 1) + assert.True(t, byName["retro"].Harness.Sets("timeout_minutes"), "an empty overlay block keeps the parent's, like no block") + assert.Empty(t, asPerRepo(w).Agents[0].inheritedHarness, "the merge must not write to a layer's own entries") +} + func TestPerRepoConfig_IsKillSwitchActive(t *testing.T) { tr := true cfg := &perRepoConfig{KillSwitch: &tr} diff --git a/internal/config/managed-config-schema b/internal/config/managed-config-schema index 931a9f7a10..5b721307dd 100644 --- a/internal/config/managed-config-schema +++ b/internal/config/managed-config-schema @@ -3,4 +3,4 @@ # render .fullsend/config.yaml in the shape that ref reads. Increment it, and # config.ManagedConfigSchemaVersion with a renderer for the previous version, # whenever a per-repo configuration change is not readable by older releases. -2 +3 diff --git a/internal/config/managed.go b/internal/config/managed.go index ee126067a1..814bd88174 100644 --- a/internal/config/managed.go +++ b/internal/config/managed.go @@ -633,6 +633,8 @@ func cloneAgentEntries(in []AgentEntry) []AgentEntry { } out[i].Subagents = m } + out[i].Harness = a.Harness.clone() + out[i].inheritedHarness = cloneAgentHarnesses(a.inheritedHarness) } return out } diff --git a/internal/config/managed_safety.go b/internal/config/managed_safety.go index dab6237b31..925bd90294 100644 --- a/internal/config/managed_safety.go +++ b/internal/config/managed_safety.go @@ -188,7 +188,7 @@ func CheckManagedSafetyGate(current PerRepoConfigReader, candidate PerRepoConfig if IsAgentExplicitlyDisabled(candidateAgents, name) { continue } - } else if !isBuiltinAgentName(name) { + } else if !IsBuiltinAgentName(name) { // A custom (source-declared, non-built-in) agent that is // entirely absent from the candidate was removed, not // re-enabled. Built-in agents keep resolving through the @@ -320,11 +320,12 @@ func agentEntryPresent(agents []AgentEntry, name string) bool { return false } -// isBuiltinAgentName reports whether name is one of the built-in agents -// fullsend dispatches by name (ValidAgentNames). Built-in agents keep -// resolving through the agents-repo fallback even without a config entry, -// so their absence from a candidate's agent list is not a removal. -func isBuiltinAgentName(name string) bool { +// IsBuiltinAgentName reports whether name is one of the built-in agents +// fullsend dispatches by name (ValidAgentNames), whether or not its entry +// has a source. Built-in agents keep resolving through the agents-repo +// fallback even without a config entry, so their absence from a +// candidate's agent list is not a removal. +func IsBuiltinAgentName(name string) bool { return slices.Contains(ValidAgentNames(), strings.ToLower(name)) } diff --git a/internal/config/managed_schema.go b/internal/config/managed_schema.go index c48be5a300..f264ed8826 100644 --- a/internal/config/managed_schema.go +++ b/internal/config/managed_schema.go @@ -23,10 +23,13 @@ const ( // A ref that declares no schema is treated as legacy unless it contains // the commit that introduced the tracker mapping. ManagedConfigSchemaLegacy = 1 + // ManagedConfigSchemaTrackerMapping is the schema with the tracker + // mapping (#9082) that predates the harness: block of an agents: entry. + ManagedConfigSchemaTrackerMapping = 2 // ManagedConfigSchemaVersion is the schema this binary reads and - // renders: issue tracking is the tracker mapping. It must equal the - // value declared in ManagedConfigSchemaDeclarationPath. - ManagedConfigSchemaVersion = 2 + // renders: an agents: entry may carry a harness: block (ADR 0162). It + // must equal the value declared in ManagedConfigSchemaDeclarationPath. + ManagedConfigSchemaVersion = 3 ) // ManagedConfigSchemaDeclarationPath is the path, in the fullsend-ai/fullsend @@ -71,17 +74,25 @@ type legacyCreateIssuesOut struct { // RenderManagedConfigSchema converts data, a per-repo configuration document // rendered in the current schema (ManagedConfigSchemaVersion), into the shape -// schema version reads. The current schema returns data unchanged. For the -// legacy schema the tracker mapping is rewritten to the scalar tracker key -// plus create_issues.allow_targets; settings that schema cannot express -// (GitLab groups, any Jira setting) return an error rather than being dropped. -// An unknown version returns an error. +// schema version reads. The current schema returns data unchanged. An older +// schema cannot express an agents: entry's harness: block. For the legacy +// schema the tracker mapping is also rewritten to the scalar tracker key +// plus create_issues.allow_targets. Settings a schema cannot express (a +// harness: block, GitLab groups, any Jira setting) return an error rather +// than being dropped. An unknown version returns an error. func RenderManagedConfigSchema(data []byte, version int) ([]byte, error) { switch version { case ManagedConfigSchemaVersion: return data, nil - case ManagedConfigSchemaLegacy: - return downgradeTrackingYAML(data) + case ManagedConfigSchemaTrackerMapping, ManagedConfigSchemaLegacy: + if name, ok := harnessBlockEntry(data); ok { + return nil, fmt.Errorf("agents entry %q: a harness: block cannot be expressed in the configuration schema of the repository's fullsend_ref: "+ + "upgrade fullsend_ref to a release that reads harness: blocks, or remove the block", name) + } + if version == ManagedConfigSchemaLegacy { + return downgradeTrackingYAML(data) + } + return data, nil } return nil, fmt.Errorf("unknown managed configuration schema version %d (this fullsend knows versions %d to %d)", version, ManagedConfigSchemaLegacy, ManagedConfigSchemaVersion) @@ -161,26 +172,49 @@ func legacyTrackingFor(t *TrackingConfig) (provider string, orgs, repos []string return "", nil, nil, errors.New("tracker must select exactly one provider to be expressed in the legacy configuration schema") } +// harnessBlockEntry returns the name of the first agents: entry in data, a +// per-repo configuration document, that carries a non-empty harness: block +// (ADR 0162), and whether there is one. Unparseable content has none; the +// regular parser reports it. +func harnessBlockEntry(data []byte) (string, bool) { + var doc struct { + Agents []AgentEntry `yaml:"agents"` + } + if err := yaml.Unmarshal(data, &doc); err != nil { + return "", false + } + for _, a := range doc.Agents { + if !a.Harness.IsEmpty() { + return a.DerivedName(), true + } + } + return "", false +} + // ManagedConfigSchemaDependent reports whether data, a per-repo -// configuration document, declares any key whose shape differs between the -// known schema versions (tracker or create_issues). A document without such -// keys renders identically, and is read identically, under every known -// schema. Blank or unparseable content is not schema-dependent. +// configuration document, declares anything the known schema versions do +// not all read the same way: tracker, create_issues, or a harness: block on +// an agents: entry. A document without them renders identically, and is +// read identically, under every known schema. Blank or unparseable content +// is not schema-dependent. func ManagedConfigSchemaDependent(data []byte) bool { var doc yaml.Node if err := yaml.Unmarshal(data, &doc); err != nil || doc.Kind != yaml.DocumentNode || len(doc.Content) != 1 { return false } + if _, ok := harnessBlockEntry(data); ok { + return true + } _, kind, _ := ReadLegacyTracking(doc.Content[0], LegacyTracking{}) return kind != TrackingLayerUnset } // CheckManagedConfigSchemaCompat reports whether data, an installed per-repo -// configuration document, uses the issue-tracking shape schema version -// reads: the legacy schema rejects the tracker mapping, and the current -// schema rejects the scalar tracker key and the removed create_issues block. -// Blank or unparseable content is not judged here; the regular parser -// reports it. +// configuration document, uses only shapes schema version reads: the legacy +// schema rejects the tracker mapping, later schemas reject the scalar +// tracker key and the removed create_issues block, and schemas before the +// current one do not read an agents: entry's harness: block. Blank or +// unparseable content is not judged here; the regular parser reports it. func CheckManagedConfigSchemaCompat(data []byte, version int) error { var doc yaml.Node if err := yaml.Unmarshal(data, &doc); err != nil || doc.Kind != yaml.DocumentNode || len(doc.Content) != 1 { @@ -190,8 +224,11 @@ func CheckManagedConfigSchemaCompat(data []byte, version int) error { switch { case version == ManagedConfigSchemaLegacy && kind == TrackingLayerMapping: return errors.New("uses the tracker mapping, which the legacy configuration schema cannot read") - case version == ManagedConfigSchemaVersion && kind == TrackingLayerLegacy: + case version > ManagedConfigSchemaLegacy && kind == TrackingLayerLegacy: return errors.New("uses the legacy tracker scalar or create_issues keys, which the current configuration schema cannot read") } + if name, ok := harnessBlockEntry(data); ok && version < ManagedConfigSchemaVersion { + return fmt.Errorf("has a harness: block on the agents entry %q, which this configuration schema cannot read", name) + } return nil } diff --git a/internal/config/managed_schema_test.go b/internal/config/managed_schema_test.go index 9dcedfaa33..ebedc1ba4a 100644 --- a/internal/config/managed_schema_test.go +++ b/internal/config/managed_schema_test.go @@ -36,6 +36,19 @@ func TestRenderManagedConfigSchemaCurrentUnchanged(t *testing.T) { assert.Equal(t, in, out) } +// A schema before the harness: block fails on an entry that carries one. +func TestRenderManagedConfigSchemaHarnessBlock(t *testing.T) { + block := []byte("agents:\n - name: review\n harness:\n timeout_minutes: 30\n") + plain := []byte("agents:\n - name: review\n model: opus\n harness: {}\n") + for _, v := range []int{ManagedConfigSchemaTrackerMapping, ManagedConfigSchemaLegacy} { + _, err := RenderManagedConfigSchema(block, v) + require.ErrorContains(t, err, `agents entry "review": a harness: block cannot be expressed`) + out, err := RenderManagedConfigSchema(plain, v) + require.NoError(t, err) + assert.Equal(t, plain, out, "an empty block sets nothing") + } +} + func TestRenderManagedConfigSchemaUnknownVersion(t *testing.T) { _, err := RenderManagedConfigSchema([]byte("runtime: claude\n"), ManagedConfigSchemaVersion+1) require.ErrorContains(t, err, "unknown managed configuration schema version") @@ -168,6 +181,8 @@ func TestManagedConfigSchemaDependent(t *testing.T) { assert.True(t, ManagedConfigSchemaDependent([]byte("tracker:\n github: {}\n"))) assert.True(t, ManagedConfigSchemaDependent([]byte("tracker: github\n"))) assert.True(t, ManagedConfigSchemaDependent([]byte("create_issues:\n allow_targets: {}\n"))) + assert.True(t, ManagedConfigSchemaDependent([]byte("agents:\n - name: review\n harness: { timeout_minutes: 30 }\n"))) + assert.False(t, ManagedConfigSchemaDependent([]byte("agents:\n - name: review\n model: opus\n harness: {}\n"))) assert.False(t, ManagedConfigSchemaDependent([]byte("runtime: claude\n"))) assert.False(t, ManagedConfigSchemaDependent(nil)) assert.False(t, ManagedConfigSchemaDependent([]byte("a: [\n"))) @@ -185,4 +200,11 @@ func TestCheckManagedConfigSchemaCompat(t *testing.T) { require.NoError(t, CheckManagedConfigSchemaCompat(neutral, ManagedConfigSchemaLegacy)) require.NoError(t, CheckManagedConfigSchemaCompat(neutral, ManagedConfigSchemaVersion)) require.NoError(t, CheckManagedConfigSchemaCompat([]byte("a: [\n"), ManagedConfigSchemaLegacy)) + + require.NoError(t, CheckManagedConfigSchemaCompat(mapping, ManagedConfigSchemaTrackerMapping)) + require.Error(t, CheckManagedConfigSchemaCompat(legacy, ManagedConfigSchemaTrackerMapping)) + block := []byte("agents:\n - name: review\n harness: { timeout_minutes: 30 }\n") + require.NoError(t, CheckManagedConfigSchemaCompat(block, ManagedConfigSchemaVersion)) + require.ErrorContains(t, CheckManagedConfigSchemaCompat(block, ManagedConfigSchemaTrackerMapping), `harness: block on the agents entry "review"`) + require.Error(t, CheckManagedConfigSchemaCompat(block, ManagedConfigSchemaLegacy)) } diff --git a/internal/forge/fake.go b/internal/forge/fake.go index 8022395211..ac74f9dcec 100644 --- a/internal/forge/fake.go +++ b/internal/forge/fake.go @@ -24,7 +24,7 @@ var _ ProjectLeaser = (*FakeClient)(nil) // config.ManagedConfigSchemaVersion by a test in internal/repos. func fakeUpstreamAnyRefFiles() map[string][]byte { return map[string][]byte{ - "fullsend-ai/fullsend/internal/config/managed-config-schema": []byte("2\n"), + "fullsend-ai/fullsend/internal/config/managed-config-schema": []byte("3\n"), } } diff --git a/internal/harness/agent_block.go b/internal/harness/agent_block.go new file mode 100644 index 0000000000..4e222a9948 --- /dev/null +++ b/internal/harness/agent_block.go @@ -0,0 +1,312 @@ +package harness + +import ( + "fmt" + "slices" + "strings" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/maputil" +) + +// Config and manifest validation run the same content check composition +// does, through config.AgentHarness.Validate. +func init() { + config.SetAgentHarnessCheck(checkAgentBlock) +} + +// reservedSandboxKey reports whether fullsend reserves an env name in the +// sandbox (ADR 0146). The runner registers its check through +// SetReservedSandboxKeyCheck; until then no name is reserved here. +var reservedSandboxKey = func(string) bool { return false } + +// SetReservedSandboxKeyCheck registers the runner's check of reserved +// sandbox names. A harness: block may not set one in either env section +// (ADR 0162 Decision 5). +func SetReservedSandboxKeyCheck(f func(string) bool) { + reservedSandboxKey = f +} + +// declaredEnvNames are the env names a harness declares per section, in any +// layer, forge: block or overlay. They are recorded before forge: blocks and +// overlays are resolved, so a name only one forge or overlay declares counts +// for every command. +type declaredEnvNames struct { + runner map[string]bool + sandbox map[string]bool +} + +// recordDeclaredEnv adds the env names h declares at top level, in its +// forge: blocks and in its overlays. Only env.runner and env.sandbox +// declare a name; runner_env does not. +func (h *Harness) recordDeclaredEnv() { + h.addDeclaredEnv(h.Env) + for _, fc := range h.Forge { + if fc != nil { + h.addDeclaredEnv(fc.Env) + } + } + for _, o := range h.Overlays { + h.addDeclaredEnv(o.Env) + } +} + +func (h *Harness) addDeclaredEnv(env *EnvConfig) { + if h.declaredEnv.runner == nil { + h.declaredEnv.runner = make(map[string]bool) + h.declaredEnv.sandbox = make(map[string]bool) + } + if env == nil { + return + } + for k := range env.Runner { + h.declaredEnv.runner[k] = true + } + for k := range env.Sandbox { + h.declaredEnv.sandbox[k] = true + } +} + +// mergeDeclaredEnv adds the names base declares to h's. +func (h *Harness) mergeDeclaredEnv(base *Harness) { + h.addDeclaredEnv(nil) + for k := range base.declaredEnv.runner { + h.declaredEnv.runner[k] = true + } + for k := range base.declaredEnv.sandbox { + h.declaredEnv.sandbox[k] = true + } +} + +// composeAgentBlocks composes opts.Blocks on h, the agent's composed +// harness, whose forge: blocks and overlays are not resolved yet. As in a +// base: chain, h is the base of the first block and each block the base of +// the next. It returns the last block, merged, with its own overlays left +// for the caller to resolve. +func composeAgentBlocks(h *Harness, opts ComposeOpts) (*Harness, error) { + if len(opts.Blocks) == 0 { + return h, nil + } + // The runtime fetch fields a layer below the last block sets. + fetchBelow := h.runtimeFetchFields() + // allow_ci_variable_credential as the layers below the last block leave it. + ciCredentialBelow := h.AllowCIVariableCredential + // With no forge selected nothing resolves h's forge: sections. A layer + // that blocks merge onto cannot keep them, so they are set aside here. + var unresolved map[string]*ForgeConfig + if opts.ForgePlatform == "" { + unresolved = h.Forge + } + if err := resolveLayerForgeAndOverlays(h, opts, false); err != nil { + return nil, err + } + declared := h.declaredEnv + base := h + triggerIgnored := false + for i, b := range opts.Blocks { + block, err := parseAgentBlock(opts.Agent, b) + if err != nil { + return nil, err + } + // allow_runtime_fetch: false turns runtime fetch off on purpose, so + // nothing below that block counts as dropped. + if b.Sets("allow_runtime_fetch") && !block.AllowRuntimeFetch { + fetchBelow = nil + } + // A harness.trigger on a built-in agent is not evaluated until + // built-in agents are routed by CEL alone (ADR 0162 Decision 6, + // #2902). Dropping it here gives every command the same harness; + // Lint warns about it. + if block.Trigger != "" && config.IsBuiltinAgentName(opts.Agent) { + block.Trigger = "" + triggerIgnored = true + } + if opts.WorkspaceRoot != "" { + if err := block.resolveSkillSourcesWithin(opts.WorkspaceRoot); err != nil { + return nil, fmt.Errorf("agents entry %q: harness: %w", opts.Agent, err) + } + } + if baseVer, blockVer := base.EffectiveSchemaVersion(), block.EffectiveSchemaVersion(); !schemaVersionsCompose(baseVer, blockVer) { + return nil, fmt.Errorf("agents entry %q: harness: block declares schema_version %d, which is incompatible with schema_version %d of the harness it builds on (ADR 0127); set the block's schema_version to match", opts.Agent, blockVer, baseVer) + } + if err := block.checkBlockEnv(opts.Agent, declared); err != nil { + return nil, err + } + block.captureDeprecatedIssueURL() + own := len(block.issueURLDiags) + if err := mergeBaseIntoChild(base, block); err != nil { + return nil, fmt.Errorf("agents entry %q: harness: %w", opts.Agent, err) + } + // mergeBaseIntoChild labels the base's GITHUB_ISSUE_URL diagnostics + // "base."; the agent's harness is not a base: harness to its user, + // so Lint labels its fields as it does without a block. + for j := own; j < len(block.issueURLDiags); j++ { + block.issueURLDiags[j].Field = strings.TrimPrefix(block.issueURLDiags[j].Field, "base.") + } + if i < len(opts.Blocks)-1 { + if err := resolveLayerForgeAndOverlays(block, opts, false); err != nil { + return nil, fmt.Errorf("agents entry %q: harness: %w", opts.Agent, err) + } + fetchBelow = append(fetchBelow, block.runtimeFetchFields()...) + if b.Sets("allow_ci_variable_credential") { + ciCredentialBelow = block.AllowCIVariableCredential + } + } + base = block + } + // base: composition does not carry the runtime fetch fields to a child, + // so a base cannot widen the child's fetch grants (ADR 0158). The block + // follows the same rule; Lint names each field a layer below set and the + // last block leaves out. + last := opts.Blocks[len(opts.Blocks)-1] + for _, f := range fetchBelow { + if !last.Sets(f) { + base.blockDroppedFetch = append(base.blockDroppedFetch, f) + } + } + slices.Sort(base.blockDroppedFetch) + base.blockDroppedFetch = slices.Compact(base.blockDroppedFetch) + // base: composition does not carry allow_ci_variable_credential either, + // so a base cannot silence the warning for its children (#9511). Only a + // GitLab run reads the field, so nothing is lost on another forge. + if opts.ForgePlatform == "" || opts.ForgePlatform == "gitlab" { + base.blockDroppedCIVariableCredential = ciCredentialBelow && !last.Sets("allow_ci_variable_credential") + } + if triggerIgnored { + base.blockTriggerIgnored = opts.Agent + } + base.unresolvedForge = unresolved + return base, nil +} + +// restoreUnresolvedForge puts the forge: sections composeAgentBlocks set +// aside back on the loaded harness, where a load without a block leaves them +// when no forge is selected. It runs after the block's own overlays are +// resolved, since forge and overlays cannot coexist in one harness. +func (h *Harness) restoreUnresolvedForge() { + if h.unresolvedForge != nil { + h.Forge, h.unresolvedForge = h.unresolvedForge, nil + } +} + +// RuntimeFetchLayer returns, without composing the harness, the layer whose +// runtime fetch fields the composed harness keeps: the last of blocks, or +// the harness file at path when the agent's entry has none. Composition +// carries those fields from no layer below (composeAgentBlocks). +func RuntimeFetchLayer(path, agent string, blocks []*config.AgentHarness) (*Harness, error) { + if len(blocks) == 0 { + return LoadRaw(path) + } + return parseAgentBlock(agent, blocks[len(blocks)-1]) +} + +// runtimeFetchFields names the runtime fetch fields h sets. +func (h *Harness) runtimeFetchFields() []string { + var set []string + if len(h.AllowedRemoteResources) > 0 { + set = append(set, "allowed_remote_resources") + } + if h.AllowRuntimeFetch { + set = append(set, "allow_runtime_fetch") + } + if h.MaxRuntimeFetches != nil { + set = append(set, "max_runtime_fetches") + } + return set +} + +// parseAgentBlock decodes an agents: entry's harness: block, failing on +// the fields a block may not set and on content decodeAgentBlock rejects +// (ADR 0162 Decision 2). +func parseAgentBlock(agent string, b *config.AgentHarness) (*Harness, error) { + if err := b.CheckKeys(); err != nil { + return nil, fmt.Errorf("agents entry %q: %w", agent, err) + } + h, err := decodeAgentBlock(b) + if err != nil { + return nil, fmt.Errorf("agents entry %q: %w", agent, err) + } + return h, nil +} + +// checkAgentBlock is the content check config.AgentHarness.Validate runs. +func checkAgentBlock(b *config.AgentHarness) error { + _, err := decodeAgentBlock(b) + return err +} + +// decodeAgentBlock decodes a block and checks what needs no harness to +// check: unknown keys, value types, schema_version, env names fullsend +// reserves in the sandbox (ADR 0146, either env section) and field values +// no harness accepts, such as an unknown effort. The trigger is left to +// composition, which ignores it on a built-in agent. +func decodeAgentBlock(b *config.AgentHarness) (*Harness, error) { + var h Harness + if err := b.DecodeStrict(&h); err != nil { + return nil, fmt.Errorf("harness: %w", err) + } + if err := validateSchemaVersion(h.SchemaVersion); err != nil { + return nil, fmt.Errorf("harness: %w", err) + } + err := h.blockEnvNames(func(field, section, name string) error { + if reservedSandboxKey(name) { + return fmt.Errorf("%s.%s.%s: fullsend reserves this name in the sandbox (ADR 0146)", field, section, name) + } + return nil + }) + if err != nil { + return nil, err + } + if err := h.validate(false); err != nil { + return nil, fmt.Errorf("harness: %w", err) + } + return &h, nil +} + +// blockEnvNames calls f for each env name a block sets, at top level and +// in its overlays, in a stable order. +func (h *Harness) blockEnvNames(f func(field, section, name string) error) error { + envs := []struct { + field string + env *EnvConfig + }{{"harness.env", h.Env}} + for i, o := range h.Overlays { + envs = append(envs, struct { + field string + env *EnvConfig + }{fmt.Sprintf("harness.overlays[%d].env", i), o.Env}) + } + for _, e := range envs { + if e.env == nil { + continue + } + for _, s := range []struct { + name string + values map[string]string + }{{"runner", e.env.Runner}, {"sandbox", e.env.Sandbox}} { + for _, k := range maputil.SortedKeys(s.values) { + if err := f(e.field, s.name, k); err != nil { + return err + } + } + } + } + return nil +} + +// checkBlockEnv checks the env names a block sets (ADR 0162 Decision 5): +// each must be declared in that section by some layer of the agent's +// harness, since the block changes harness variables and adding one still +// takes a base: harness. +func (h *Harness) checkBlockEnv(agent string, declared declaredEnvNames) error { + return h.blockEnvNames(func(field, section, name string) error { + names := declared.runner + if section == "sandbox" { + names = declared.sandbox + } + if !names[name] { + return fmt.Errorf("agents entry %q: %s.%s.%s: the %q harness does not declare this variable in env.%s; a harness: block only changes declared variables (ADR 0162), so add it with a base: harness", agent, field, section, name, agent, section) + } + return nil + }) +} diff --git a/internal/harness/agent_block_test.go b/internal/harness/agent_block_test.go new file mode 100644 index 0000000000..7c9f982e4f --- /dev/null +++ b/internal/harness/agent_block_test.go @@ -0,0 +1,414 @@ +package harness + +import ( + "context" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" + + "github.com/fullsend-ai/fullsend/internal/config" +) + +func agentBlock(t *testing.T, doc string) *config.AgentHarness { + t.Helper() + var b config.AgentHarness + require.NoError(t, yaml.Unmarshal([]byte(doc), &b)) + return &b +} + +func loadWithBlocks(t *testing.T, path string, opts ComposeOpts, blocks ...string) (*Harness, error) { + t.Helper() + for _, b := range blocks { + opts.Blocks = append(opts.Blocks, agentBlock(t, b)) + } + if opts.Agent == "" { + opts.Agent = "review" + } + h, _, err := LoadWithBase(context.Background(), path, opts) + return h, err +} + +const blockTestHarness = ` +agent: agents/review.md +role: review +readonly_repo: true +timeout_minutes: 45 +skills: + - skills/pr-review +env: + runner: { REVIEW_FINDING_SEVERITY_THRESHOLD: low } + sandbox: { REVIEW_FINDING_SEVERITY_THRESHOLD: low, TIMEOUT_SECONDS: "2700" } +overlays: + - when: 'runtime.forge == "gitlab"' + env: + runner: { OVERLAY_ONLY: "1" } +` + +func TestAgentBlock_OverridesDeclaredValues(t *testing.T) { + dir := t.TempDir() + path := writeTestHarness(t, dir, "review.yaml", blockTestHarness) + + h, err := loadWithBlocks(t, path, ComposeOpts{ForgePlatform: "gitlab"}, ` +timeout_minutes: 90 +skills: [skills/extra] +env: + runner: { REVIEW_FINDING_SEVERITY_THRESHOLD: medium } + sandbox: { REVIEW_FINDING_SEVERITY_THRESHOLD: medium, TIMEOUT_SECONDS: "5400" } +`) + require.NoError(t, err) + assert.Equal(t, 90, h.TimeoutMinutes) + assert.Equal(t, "medium", h.Env.Runner["REVIEW_FINDING_SEVERITY_THRESHOLD"]) + assert.Equal(t, "medium", h.Env.Sandbox["REVIEW_FINDING_SEVERITY_THRESHOLD"]) + assert.Equal(t, "5400", h.Env.Sandbox["TIMEOUT_SECONDS"]) + assert.Equal(t, "1", h.Env.Runner["OVERLAY_ONLY"], "the harness's matching overlay still applies") + assert.Equal(t, "agents/review.md", h.Agent, "fields the block does not set keep the harness value") + assert.Equal(t, "review", h.Role) + assert.True(t, h.RepoReadonly(), "the read-only checkout survives the block (#7360)") + require.Len(t, h.Skills, 2, "lists concatenate as in base: composition") + assert.Equal(t, "skills/extra", h.Skills[1].Source) +} + +// A URL-sourced harness fetches its own paths from that URL; a block's paths stay local. +func TestAgentBlock_URLSourcedHarness(t *testing.T) { + harnessContent := "agent: agents/triage.md\nrole: triage\npolicy: policies/triage.yaml\npre_script: scripts/pre-triage.sh\n" + server, policy := setupScriptTestServer(t, []byte(harnessContent), map[string][]byte{ + "/scripts/pre-triage.sh": []byte("#!/bin/sh\n"), + "/scripts/mine.sh": []byte("#!/bin/sh\n"), + }) + dir := t.TempDir() + path := writeTestHarness(t, dir, "triage.yaml", harnessContent) + + h, err := loadWithBlocks(t, path, ComposeOpts{ + WorkspaceRoot: filepath.Join(dir, "cache"), + FetchPolicy: policy, + OrgAllowlist: []string{server.URL + "/"}, + SourceURL: server.URL + "/harness/triage.yaml", + }, "pre_script: scripts/mine.sh") + require.NoError(t, err) + assert.True(t, filepath.IsAbs(h.Policy), "the harness's own path is fetched: %s", h.Policy) + assert.Equal(t, "scripts/mine.sh", h.PreScript) +} + +func TestAgentBlock_TildeSetsEmpty(t *testing.T) { + dir := t.TempDir() + path := writeTestHarness(t, dir, "review.yaml", blockTestHarness) + + h, err := loadWithBlocks(t, path, ComposeOpts{}, "env: { sandbox: { REVIEW_FINDING_SEVERITY_THRESHOLD: ~ } }") + require.NoError(t, err) + v, ok := h.Env.Sandbox["REVIEW_FINDING_SEVERITY_THRESHOLD"] + assert.True(t, ok, "~ does not remove the variable") + assert.Empty(t, v, "~ sets it empty (ADR 0162 Decision 3)") +} + +func TestAgentBlock_LayersInOrder(t *testing.T) { + dir := t.TempDir() + path := writeTestHarness(t, dir, "review.yaml", blockTestHarness) + + h, err := loadWithBlocks(t, path, ComposeOpts{}, + "timeout_minutes: 60\nenv: { sandbox: { REVIEW_FINDING_SEVERITY_THRESHOLD: high } }", + "timeout_minutes: 90") + require.NoError(t, err) + assert.Equal(t, 90, h.TimeoutMinutes, "config.yaml's block wins over config.base.yaml's") + assert.Equal(t, "high", h.Env.Sandbox["REVIEW_FINDING_SEVERITY_THRESHOLD"], "config.base.yaml's value stays when config.yaml does not replace it") +} + +func TestAgentBlock_DeclaredNames(t *testing.T) { + dir := t.TempDir() + writeTestHarness(t, dir, "ancestor.yaml", ` +agent: agents/review.md +role: review +env: + sandbox: { ANCESTOR_ONLY: "1" } +forge: + github: {} + gitlab: + env: + sandbox: { GITLAB_ONLY: "1" } +`) + path := writeTestHarness(t, dir, "review.yaml", "base: ancestor.yaml\n"+blockTestHarness) + + for _, tc := range []struct { + name, block string + }{ + {"a name only a base: ancestor declares", "env: { sandbox: { ANCESTOR_ONLY: \"2\" } }"}, + {"a name only another forge's block declares", "env: { sandbox: { GITLAB_ONLY: \"2\" } }"}, + {"a name only a non-matching overlay declares", "env: { runner: { OVERLAY_ONLY: \"2\" } }"}, + {"a declared name in the block's own overlay", "overlays: [ { when: 'true', env: { sandbox: { REVIEW_FINDING_SEVERITY_THRESHOLD: high } } } ]"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := loadWithBlocks(t, path, ComposeOpts{ForgePlatform: "github"}, tc.block) + assert.NoError(t, err) + }) + } + + for _, tc := range []struct { + name, block, want string + }{ + {"an undeclared name", "env: { sandbox: { REVIEW_UX_ENABLED: \"false\" } }", `agents entry "review": harness.env.sandbox.REVIEW_UX_ENABLED: the "review" harness does not declare this variable in env.sandbox`}, + {"a name declared in the other section", "env: { runner: { TIMEOUT_SECONDS: \"1\" } }", `harness.env.runner.TIMEOUT_SECONDS: the "review" harness does not declare this variable in env.runner`}, + {"an undeclared name in the block's overlay", "overlays: [ { when: 'true', env: { runner: { NEW: x } } } ]", `harness.overlays[0].env.runner.NEW: the "review" harness does not declare`}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := loadWithBlocks(t, path, ComposeOpts{ForgePlatform: "github"}, tc.block) + assert.ErrorContains(t, err, tc.want) + }) + } +} + +func TestAgentBlock_ReservedName(t *testing.T) { + saved := reservedSandboxKey + t.Cleanup(func() { SetReservedSandboxKeyCheck(saved) }) + SetReservedSandboxKeyCheck(func(k string) bool { return strings.EqualFold(k, "PATH") }) + + dir := t.TempDir() + path := writeTestHarness(t, dir, "review.yaml", ` +agent: agents/review.md +role: review +env: + runner: { PATH: /usr/bin } +`) + _, err := loadWithBlocks(t, path, ComposeOpts{}, "env: { runner: { PATH: /tmp } }") + assert.ErrorContains(t, err, "harness.env.runner.PATH: fullsend reserves this name in the sandbox") +} + +func TestAgentBlock_RejectsKeys(t *testing.T) { + dir := t.TempDir() + path := writeTestHarness(t, dir, "review.yaml", blockTestHarness) + + for _, tc := range []struct { + name, block, want string + }{ + {"unknown nested key", "env: { sandbx: { A: b } }", "sandbx"}, + {"base", "base: other.yaml", "harness.base is not allowed"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := loadWithBlocks(t, path, ComposeOpts{}, tc.block) + assert.ErrorContains(t, err, tc.want) + }) + } + + _, err := loadWithBlocks(t, path, ComposeOpts{}, "schema_version: 1\ntimeout_minutes: 30") + assert.NoError(t, err, "a block may declare the version of the harness it builds on") +} + +// Config validation rejects a malformed block before any harness loads. +func TestAgentBlock_ConfigValidationChecksContent(t *testing.T) { + for block, want := range map[string]string{ + "{ timeout_minute: 90 }": "timeout_minute", + "{ timeout_minutes: [a, b] }": "cannot unmarshal", + "{ schema_version: 2 }": "schema_version 2 is not supported", + "{ effort: ultra }": `harness: effort "ultra" is not valid`, + "{ overlays: [ { when: 'this is not CEL' } ] }": "harness: overlays[0].when", + } { + var entries []config.AgentEntry + require.NoError(t, yaml.Unmarshal([]byte("- name: review\n harness: "+block+"\n"), &entries)) + assert.ErrorContains(t, config.ValidateAgentEntries(entries, nil), want, block) + } + + var entries []config.AgentEntry + require.NoError(t, yaml.Unmarshal([]byte("- name: review\n harness: { validation_loop: { schema: a.json }, overlays: [ { when: \"true\", validation_loop: { schema: b.json } } ] }\n"), &entries)) + assert.NoError(t, config.ValidateAgentEntries(entries, nil), "the harness below supplies what a block leaves out, here the loop's script") +} + +func TestAgentBlock_TriggerOverride(t *testing.T) { + dir := t.TempDir() + path := writeTestHarness(t, dir, "custom.yaml", ` +agent: agents/custom.md +role: custom +trigger: 'event.transition.kind == "opened"' +`) + const blockTrigger = `trigger: 'event.transition.kind == "label_changed"'` + h, err := loadWithBlocks(t, path, ComposeOpts{Agent: "custom"}, blockTrigger) + require.NoError(t, err) + assert.Equal(t, `event.transition.kind == "label_changed"`, h.Trigger) + assert.NotContains(t, diagnosticCodes(h.Lint()), CodeBlockTriggerIgnored) + + // On a built-in agent name the block's trigger is not evaluated (ADR 0162 Decision 6). + h, err = loadWithBlocks(t, path, ComposeOpts{Agent: "Triage"}, "timeout_minutes: 30", blockTrigger) + require.NoError(t, err) + assert.Equal(t, `event.transition.kind == "opened"`, h.Trigger) + var warning string + for _, d := range h.Lint() { + if d.Code == CodeBlockTriggerIgnored { + warning = d.Message + } + } + assert.Contains(t, warning, `agents entry "Triage"`) +} + +func TestAgentBlock_ForgePlatformStillRequired(t *testing.T) { + for name, forge := range map[string]string{ + "platform not configured": "gitlab", + "unrecognized forge key": "bitbucket", + } { + t.Run(name, func(t *testing.T) { + path := writeTestHarness(t, t.TempDir(), "review.yaml", "agent: agents/review.md\nrole: review\nforge:\n "+forge+":\n env:\n sandbox: { A: b }\n") + _, plain := loadWithBlocks(t, path, ComposeOpts{ForgePlatform: "github"}) + _, withBlock := loadWithBlocks(t, path, ComposeOpts{ForgePlatform: "github"}, "timeout_minutes: 30") + require.Error(t, plain) + require.EqualError(t, withBlock, plain.Error()) + }) + } +} + +func TestAgentBlock_HarnessErrorsReadAsWithoutBlock(t *testing.T) { + dir := t.TempDir() + path := writeTestHarness(t, dir, "review.yaml", ` +agent: agents/review.md +role: review +overlays: + - when: 'this is not CEL' + env: { sandbox: { A: b } } +`) + _, err := loadWithBlocks(t, path, ComposeOpts{}, "timeout_minutes: 30") + require.Error(t, err) + assert.NotContains(t, err.Error(), "base", "the agent's own harness is not a base: harness to its user") +} + +// A block does not inherit the runtime fetch fields (ADR 0158); Lint names the ones it leaves out. +func TestAgentBlock_DropsRuntimeFetchWarns(t *testing.T) { + const plain = "agent: agents/custom.md\nrole: custom\n" + const fetch = "allowed_remote_resources: [https://raw.githubusercontent.com/org/skills/]\nallow_runtime_fetch: true\n" + tests := []struct { + name string + harness string + blocks []string + fetchOn bool + dropped string // fields the warning names; empty for no warning + }{ + {"no block", plain + fetch, nil, true, ""}, + {"block without the fields", plain + fetch, []string{"timeout_minutes: 30"}, false, "allow_runtime_fetch, allowed_remote_resources"}, + {"block sets them again", plain + fetch, []string{fetch}, true, ""}, + {"only the cap is lost", plain + fetch + "max_runtime_fetches: 50\n", []string{fetch}, true, "max_runtime_fetches"}, + {"second block drops what the first set", plain, []string{fetch, "timeout_minutes: 30"}, false, "allow_runtime_fetch, allowed_remote_resources"}, + {"block turns fetch off on purpose", plain + fetch, []string{"allow_runtime_fetch: false"}, false, ""}, + {"a later block does not undo that", plain + fetch, []string{"allow_runtime_fetch: false", "timeout_minutes: 30"}, false, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := writeTestHarness(t, t.TempDir(), "custom.yaml", tt.harness) + h, err := loadWithBlocks(t, path, ComposeOpts{}, tt.blocks...) + require.NoError(t, err) + assert.Equal(t, tt.fetchOn, h.AllowRuntimeFetch) + var messages []string + for _, d := range h.Lint() { + if d.Code == CodeBlockDropsRuntimeFetch { + messages = append(messages, d.Message) + } + } + if tt.dropped == "" { + assert.Empty(t, messages) + return + } + require.Len(t, messages, 1) + assert.Contains(t, messages[0], "leaves out "+tt.dropped+",") + }) + } +} + +// base: composition does not carry allow_ci_variable_credential either; lint warns when the last block drops it. +func TestAgentBlock_DropsCIVariableCredentialWarns(t *testing.T) { + const plain = "agent: agents/custom.md\nrole: custom\n" + const allow = "allow_ci_variable_credential: true\n" + tests := []struct { + name string + forge string + harness string + blocks []string + allowed bool + warns bool + }{ + {"block without the field", "gitlab", plain + allow, []string{"timeout_minutes: 30"}, false, true}, + {"no forge selected", "", plain + allow, []string{"timeout_minutes: 30"}, false, true}, + {"another forge does not read the field", "github", plain + allow, []string{"timeout_minutes: 30"}, false, false}, + {"block sets it again", "gitlab", plain + allow, []string{allow}, true, false}, + {"second block drops what the first set", "gitlab", plain, []string{allow, "timeout_minutes: 30"}, false, true}, + {"two blocks drop what the harness set", "gitlab", plain + allow, []string{"timeout_minutes: 30", "timeout_minutes: 40"}, false, true}, + {"block turns it off on purpose", "gitlab", plain + allow, []string{"allow_ci_variable_credential: false"}, false, false}, + {"a later block does not undo that", "gitlab", plain + allow, []string{"allow_ci_variable_credential: false", "timeout_minutes: 30"}, false, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := writeTestHarness(t, t.TempDir(), "custom.yaml", tt.harness) + h, err := loadWithBlocks(t, path, ComposeOpts{ForgePlatform: tt.forge}, tt.blocks...) + require.NoError(t, err) + assert.Equal(t, tt.allowed, h.AllowCIVariableCredential) + assert.Equal(t, tt.warns, slices.Contains(diagnosticCodes(h.Lint()), CodeBlockDropsCIVariableCred)) + }) + } +} + +func diagnosticCodes(diags []Diagnostic) []string { + codes := make([]string, 0, len(diags)) + for _, d := range diags { + codes = append(codes, d.Code) + } + return codes +} + +// A block that leaves a field alone does not change what lint reports for the +// agent's own harness, or the forge sections lint can read, whether or not a +// forge is selected. +func TestAgentBlock_LintFieldsUnchanged(t *testing.T) { + // One of everything lint flags in a forge section or an overlay. + const section = ` + runner_env: { OLD: "1" } + env: + runner: { ISSUE: "${GITHUB_ISSUE_URL}" } + sandbox: { S: x } + host_files: + - { src: "${GITHUB_ISSUE_URL}/x.env", dest: /sandbox/.env.d/x.env, expand: true } + validation_loop: { script: scripts/v.sh, max_iterations: 2, preflight_check: scripts/check.sh } +` + harnesses := map[string]string{ + "top level": "env:\n runner: { GITHUB_ISSUE_URL: \"${GITHUB_ISSUE_URL}\", X: a }\n", + "forge section": "env:\n runner: { X: a }\nforge:\n github:" + section, + "with a base": "base: base.yaml\nenv:\n runner: { X: a }\nforge:\n github:" + section, + "overlay": "env:\n runner: { X: a }\noverlays:\n - when: runtime.forge == \"github\"" + section, + } + for name, body := range harnesses { + dir := t.TempDir() + writeTestHarness(t, dir, "base.yaml", "agent: agents/review.md\nrole: review\n") + path := writeTestHarness(t, dir, "review.yaml", "agent: agents/review.md\nrole: review\n"+body) + for _, forge := range []string{"", "github"} { + opts := ComposeOpts{ForgePlatform: forge} + plain, err := loadWithBlocks(t, path, opts) + require.NoError(t, err) + want := plain.Lint() + require.NotEmpty(t, want) + for _, blocks := range [][]string{ + {"env: { runner: { X: b } }"}, + {"env: { runner: { X: b } }", "env: { runner: { X: c } }"}, + // Its overlay cannot coexist with the harness's forge section. + {"overlays:\n - when: runtime.forge == \"github\"\n env:\n runner: { X: b }\n"}, + } { + h, err := loadWithBlocks(t, path, opts, blocks...) + require.NoError(t, err, "%s, forge %q, blocks %q", name, forge, blocks) + assert.Equal(t, want, h.Lint(), "%s, forge %q, blocks %q", name, forge, blocks) + assert.Equal(t, plain.Forge, h.Forge, "%s, forge %q, blocks %q", name, forge, blocks) + } + } + } +} + +// With blocks, the last block's runtime fetch declaration is the one kept. +func TestRuntimeFetchLayer(t *testing.T) { + path := writeTestHarness(t, t.TempDir(), "custom.yaml", "agent: agents/custom.md\nrole: custom\nallow_runtime_fetch: true\nallowed_remote_resources: [https://example.com/a/]\n") + + h, err := RuntimeFetchLayer(path, "custom", nil) + require.NoError(t, err) + assert.Equal(t, []string{"https://example.com/a/"}, h.AllowedRemoteResources) + + h, err = RuntimeFetchLayer(path, "custom", []*config.AgentHarness{ + agentBlock(t, "allowed_remote_resources: [https://example.com/b/]"), + agentBlock(t, "timeout_minutes: 30"), + }) + require.NoError(t, err) + assert.Empty(t, h.AllowedRemoteResources) + assert.False(t, h.AllowRuntimeFetch) +} diff --git a/internal/harness/compose.go b/internal/harness/compose.go index 74a1660907..5f47de301f 100644 --- a/internal/harness/compose.go +++ b/internal/harness/compose.go @@ -15,6 +15,7 @@ import ( "strings" "time" + "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/gitfetch" @@ -129,6 +130,13 @@ type ComposeOpts struct { // records them, never cache paths. Nil disables pinning. LockedPins map[string]LockedPin + // Blocks are the harness: blocks of the agent's agents: entry, outermost + // config layer first (config.AgentEntry.HarnessBlocks). LoadWithBase + // composes them on the agent's harness as child layers (ADR 0162). + Blocks []*config.AgentHarness + // Agent names the agent in errors about Blocks. + Agent string + // allowSelfAllowlist permits using the child harness's own AllowedRemoteResources // when OrgAllowlist is empty. This is for testing only; production callers should // always provide OrgAllowlist from config.yaml. Unexported to prevent misuse. @@ -216,15 +224,19 @@ func checkLockedHash(field, rawURL, pin, got string) error { // // Pipeline: // 1. LoadRaw(path) — preserves forge map -// 2. If base absent: resolve URL-sourced resources → ResolveForge → ResolveOverlays → Validate → return +// 2. If base absent: resolve URL-sourced resources → compose opts.Blocks +// (step 5) → ResolveForge → ResolveOverlays → Validate → return // 3. If base present: loadBaseChain recursively (each base layer resolves its // own forge/overlays via resolveBaseForgeAndOverlays before merging into // the next layer), then mergeBaseIntoChild with the flat base // 4. Resolve remaining URL-sourced resources and scripts (child's own relative paths) -// 5. ResolveForge and ResolveOverlays on child's own forge/overlay blocks -// 6. Validate +// 5. Compose opts.Blocks, the harness: blocks of the agent's agents: entry, +// as further child layers (composeAgentBlocks, ADR 0162) +// 6. ResolveForge and ResolveOverlays on the result's own forge/overlay blocks +// 7. Validate // -// When base is absent, this behaves identically to LoadWithOpts. +// When base is absent and opts.Blocks is empty, this behaves identically to +// LoadWithOpts. func LoadWithBase(ctx context.Context, path string, opts ComposeOpts) (*Harness, []Dependency, error) { childDir := filepath.Dir(path) @@ -232,7 +244,6 @@ func LoadWithBase(ctx context.Context, path string, opts ComposeOpts) (*Harness, if err != nil { return nil, nil, err } - // A local harness's relative skill paths are resolved against the // workspace root now, so every merge below compares declared names; // ResolveRelativeTo later finds them absolute. The root comes from the @@ -288,6 +299,10 @@ func LoadWithBase(ctx context.Context, path string, opts ComposeOpts) (*Harness, deps = append(deps, pluginDeps...) } + child, err = composeAgentBlocks(child, opts) + if err != nil { + return nil, nil, err + } if err := child.validateForge(); err != nil { return nil, nil, fmt.Errorf("invalid harness: %w", err) } @@ -299,7 +314,11 @@ func LoadWithBase(ctx context.Context, path string, opts ComposeOpts) (*Harness, } // Capture forge presence before ResolveForge nils the map so Lint() // can emit the forge deprecation warning; LoadWithOpts does the same. - child.hadForgeBeforeResolve = child.Forge != nil + // OR semantics: composeAgentBlocks may have carried the marker from + // the agent's harness to a block. + if child.Forge != nil { + child.hadForgeBeforeResolve = true + } if err := child.ResolveForge(opts.ForgePlatform); err != nil { return nil, nil, fmt.Errorf("resolving forge config: %w", err) } @@ -309,6 +328,7 @@ func LoadWithBase(ctx context.Context, path string, opts ComposeOpts) (*Harness, if err := child.Validate(); err != nil { return nil, nil, fmt.Errorf("invalid harness: %w", err) } + child.restoreUnresolvedForge() return child, deps, nil } @@ -421,6 +441,11 @@ func LoadWithBase(ctx context.Context, path string, opts ComposeOpts) (*Harness, deps = append(deps, pluginDeps...) } + child, err = composeAgentBlocks(child, opts) + if err != nil { + return nil, nil, err + } + // ResolveForge and ResolveOverlays once on the merged result if err := child.validateForge(); err != nil { return nil, nil, fmt.Errorf("invalid harness: %w", err) @@ -445,6 +470,7 @@ func LoadWithBase(ctx context.Context, path string, opts ComposeOpts) (*Harness, if err := child.Validate(); err != nil { return nil, nil, fmt.Errorf("invalid harness: %w", err) } + child.restoreUnresolvedForge() return child, deps, nil } @@ -683,6 +709,21 @@ func loadBaseChain( // used by a child that runs on github only). The non-matching platform's // config is simply discarded when the forge map is niled. func resolveBaseForgeAndOverlays(base *Harness, opts ComposeOpts) error { + return resolveLayerForgeAndOverlays(base, opts, true) +} + +// resolveLayerForgeAndOverlays is resolveBaseForgeAndOverlays for any +// layer a child composes on: a base: ancestor (isBase), or the agent's own +// harness beneath an agents: entry's harness: block (ADR 0162), whose +// errors read as they do without a block. +func resolveLayerForgeAndOverlays(base *Harness, opts ComposeOpts, isBase bool) error { + invalid, resolving, forge := "invalid harness", "resolving overlays", "resolving forge config" + if isBase { + invalid, resolving, forge = "invalid base harness", "resolving base overlays", "invalid base harness" + } + // Record this layer's declared env names before its non-matching + // forge: blocks and overlays are discarded below (ADR 0162). + base.recordDeclaredEnv() // Capture forge presence before the map is niled below so the // deprecation marker survives for Lint(); mergeBaseIntoChild propagates // it up the chain. OR semantics: an ancestor's marker may already be @@ -698,12 +739,12 @@ func resolveBaseForgeAndOverlays(base *Harness, opts ComposeOpts) error { // while both are still present so mutual-exclusion checks fire. if base.Forge != nil { if err := base.validateForge(); err != nil { - return fmt.Errorf("invalid base harness: %w", err) + return fmt.Errorf("%s: %w", invalid, err) } } if len(base.Overlays) > 0 { if err := base.validateOverlays(); err != nil { - return fmt.Errorf("invalid base harness: %w", err) + return fmt.Errorf("%s: %w", invalid, err) } } @@ -717,9 +758,16 @@ func resolveBaseForgeAndOverlays(base *Harness, opts ComposeOpts) error { // ResolveForge("") would also be a no-op, and keeping the base's // forge map around would violate the mergeBaseIntoChild precondition. if base.Forge != nil && opts.ForgePlatform != "" { + // Unlike a base, the agent's own harness must configure the + // platform, as ResolveForge requires of it without a block. + if !isBase { + if _, err := base.forgeConfigFor(opts.ForgePlatform); err != nil { + return fmt.Errorf("%s: %w", forge, err) + } + } if fc, ok := base.Forge[opts.ForgePlatform]; ok && fc != nil { if err := mergeForgeConfig(base, fc); err != nil { - return fmt.Errorf("invalid base harness: forge.%s: %w", opts.ForgePlatform, err) + return fmt.Errorf("%s: forge.%s: %w", forge, opts.ForgePlatform, err) } } } @@ -729,10 +777,10 @@ func resolveBaseForgeAndOverlays(base *Harness, opts ComposeOpts) error { // entries into top-level fields. if len(base.Overlays) > 0 { if err := ValidateOverlayRunnerSecretRefs(base.Overlays, opts.RunnerSecretNames); err != nil { - return fmt.Errorf("invalid base harness: %w", err) + return fmt.Errorf("%s: %w", invalid, err) } if err := base.ResolveOverlays(opts.Event, opts.ForgePlatform, opts.Config); err != nil { - return fmt.Errorf("resolving base overlays: %w", err) + return fmt.Errorf("%s: %w", resolving, err) } } base.Overlays = nil @@ -872,6 +920,7 @@ func mergeBaseIntoChild(base, child *Harness) error { if base.hadForgeBeforeResolve { child.hadForgeBeforeResolve = true } + child.mergeDeclaredEnv(base) // GITHUB_ISSUE_URL diagnostics (#8742): record the child's own before // base fields are merged into its top level, then append the base's diff --git a/internal/harness/forge.go b/internal/harness/forge.go index d9c1ca6477..c45ba8ec02 100644 --- a/internal/harness/forge.go +++ b/internal/harness/forge.go @@ -236,6 +236,12 @@ func validateValidationLoop(prefix string, vl *ValidationLoop, inheritScript boo // mutual exclusion with forge, CEL expression compilation, and // ForgeConfig field validation per entry. func (h *Harness) validateOverlays() error { + return h.validateOverlayEntries(h.ValidationLoop != nil && h.ValidationLoop.Script != "") +} + +// validateOverlayEntries is validateOverlays with the caller saying whether +// an overlay's validation loop may leave its script to the top-level one. +func (h *Harness) validateOverlayEntries(inheritScript bool) error { if len(h.Overlays) == 0 { return nil } @@ -264,7 +270,6 @@ func (h *Harness) validateOverlays() error { return fmt.Errorf("overlays[%d].when must evaluate to bool, got %v", i, ast.OutputType()) } fc := entry.ForgeConfig - inheritScript := h.ValidationLoop != nil && h.ValidationLoop.Script != "" if err := validateOverlayForgeConfigInherit(i, &fc, inheritScript); err != nil { return err } @@ -345,12 +350,9 @@ func (h *Harness) ResolveForge(platform string) error { if platform == "" || h.Forge == nil { return nil } - if !validForgeKeys[platform] { - return fmt.Errorf("forge platform %q is not valid (valid: %s)", platform, ForgeKeyList()) - } - fc, ok := h.Forge[platform] - if !ok { - return fmt.Errorf("forge platform %q not configured (available: %s)", platform, forgeKeyList(h.Forge)) + fc, err := h.forgeConfigFor(platform) + if err != nil { + return err } if fc != nil { if err := mergeForgeConfig(h, fc); err != nil { @@ -361,6 +363,19 @@ func (h *Harness) ResolveForge(platform string) error { return nil } +// forgeConfigFor returns the forge: block for platform. The harness a run +// uses must configure the platform it runs on. +func (h *Harness) forgeConfigFor(platform string) (*ForgeConfig, error) { + if !validForgeKeys[platform] { + return nil, fmt.Errorf("forge platform %q is not valid (valid: %s)", platform, ForgeKeyList()) + } + fc, ok := h.Forge[platform] + if !ok { + return nil, fmt.Errorf("forge platform %q not configured (available: %s)", platform, forgeKeyList(h.Forge)) + } + return fc, nil +} + // mergeForgeConfig applies forge-specific overrides to the harness. // // Merge rules per ADR-0045: diff --git a/internal/harness/harness.go b/internal/harness/harness.go index 31136a14e3..60a11cda06 100644 --- a/internal/harness/harness.go +++ b/internal/harness/harness.go @@ -431,6 +431,24 @@ type Harness struct { // issueURLDiagsCaptured is true. issueURLDiags []Diagnostic `yaml:"-"` issueURLDiagsCaptured bool `yaml:"-"` + + // declaredEnv holds the env names any layer declares, checked against + // an agents: entry's harness: block (ADR 0162). + declaredEnv declaredEnvNames `yaml:"-"` + // blockDroppedFetch names the runtime fetch fields a layer below the + // last harness: block set and that block did not; Lint() warns about it. + blockDroppedFetch []string `yaml:"-"` + // blockDroppedCIVariableCredential is true when a layer below the last + // harness: block set allow_ci_variable_credential and that block did + // not; Lint() warns about it. + blockDroppedCIVariableCredential bool `yaml:"-"` + // blockTriggerIgnored names the built-in agent whose harness: block set + // a trigger that composition dropped; Lint() warns about it. + blockTriggerIgnored string `yaml:"-"` + // unresolvedForge holds the forge: sections of the harness under a + // harness: block while the block is composed with no forge selected; + // restoreUnresolvedForge puts them back. + unresolvedForge map[string]*ForgeConfig `yaml:"-"` } // Load reads a harness YAML file from path, unmarshals it, and validates it. @@ -531,19 +549,28 @@ func LoadRaw(path string) (*Harness, error) { // Validate checks that required fields are present. func (h *Harness) Validate() error { + return h.validate(true) +} + +// validate checks h's field values. With whole it also checks what only a +// composed harness can be held to: the required fields, consistent runtime +// fetch fields and the trigger. Without it h is one layer, such as an +// agents: entry's harness: block (ADR 0162), and only the values no +// composition can make valid fail. +func (h *Harness) validate(whole bool) error { // Base field must be consumed by LoadWithBase before validation. // If it's still set, the harness was loaded via Load/LoadWithOpts which // don't process base composition — a silent misconfiguration. if h.Base != "" { return fmt.Errorf("base field is set but harness was not loaded with LoadWithBase; use LoadWithBase to enable base composition") } - if h.Agent == "" { + if whole && h.Agent == "" { return fmt.Errorf("agent field is required") } // Agent name (filename without .md) must be safe for shell interpolation. // Skip name validation when agent is a URL — the resolver will replace it // with a local cache path before it reaches the shell. - if !IsURL(h.Agent) { + if h.Agent != "" && !IsURL(h.Agent) { agentBase := strings.TrimSuffix(filepath.Base(h.Agent), ".md") if !validAgentName.MatchString(agentBase) { return fmt.Errorf("agent name %q contains invalid characters (allowed: a-z, A-Z, 0-9, _, -)", agentBase) @@ -555,10 +582,10 @@ func (h *Harness) Validate() error { if h.Effort != "" && !validEffortLevel(h.Effort) { return fmt.Errorf("effort %q is not valid (allowed: %s)", h.Effort, strings.Join(validEffortLevels, ", ")) } - if h.Role == "" { + if whole && h.Role == "" { return fmt.Errorf("role field is required") } - if !validRoleName.MatchString(h.Role) { + if h.Role != "" && !validRoleName.MatchString(h.Role) { return fmt.Errorf("role %q contains invalid characters (allowed: a-z, 0-9, _, -; must start with a lowercase letter)", h.Role) } if strings.Contains(h.Role, "--") { @@ -598,7 +625,7 @@ func (h *Harness) Validate() error { return fmt.Errorf("host_files[%d]: %w", i, err) } } - if h.ValidationLoop != nil && h.ValidationLoop.Script == "" { + if whole && h.ValidationLoop != nil && h.ValidationLoop.Script == "" { return fmt.Errorf("validation_loop.script is required when validation_loop is set") } if h.ValidationLoop != nil { @@ -615,11 +642,11 @@ func (h *Harness) Validate() error { if err := h.ValidateResourceTypes(); err != nil { return err } - if h.AllowRuntimeFetch && len(h.AllowedRemoteResources) == 0 { + if whole && h.AllowRuntimeFetch && len(h.AllowedRemoteResources) == 0 { return fmt.Errorf("allow_runtime_fetch requires at least one entry in allowed_remote_resources") } if h.MaxRuntimeFetches != nil { - if !h.AllowRuntimeFetch { + if whole && !h.AllowRuntimeFetch { return fmt.Errorf("max_runtime_fetches requires allow_runtime_fetch to be true") } if *h.MaxRuntimeFetches <= 0 || *h.MaxRuntimeFetches > 1000 { @@ -629,11 +656,14 @@ func (h *Harness) Validate() error { if err := h.validateForge(); err != nil { return err } - if err := h.validateOverlays(); err != nil { + // A layer's overlay may leave its loop's script to a layer below. + if err := h.validateOverlayEntries(!whole || (h.ValidationLoop != nil && h.ValidationLoop.Script != "")); err != nil { return err } - if err := ValidateTriggerExpression(h.Trigger); err != nil { - return fmt.Errorf("trigger: %w", err) + if whole { + if err := ValidateTriggerExpression(h.Trigger); err != nil { + return fmt.Errorf("trigger: %w", err) + } } // ValidateAllowedRemoteResources requires the org allowlist and is called // by the integration layer, not here. diff --git a/internal/harness/lint.go b/internal/harness/lint.go index 6b35f60fab..e166cfe832 100644 --- a/internal/harness/lint.go +++ b/internal/harness/lint.go @@ -62,6 +62,9 @@ const ( CodeTriggerInvalid = "trigger-invalid" CodePreflightCheckPath = "preflight-check-path" CodeGithubIssueURLDeprecated = "github-issue-url-deprecated" + CodeBlockDropsRuntimeFetch = "block-drops-runtime-fetch" + CodeBlockDropsCIVariableCred = "block-drops-ci-variable-credential" + CodeBlockTriggerIgnored = "block-trigger-ignored" ) // Diagnostic represents a non-fatal issue found by Lint. @@ -85,6 +88,33 @@ func (d Diagnostic) String() string { func (h *Harness) Lint() []Diagnostic { var diags []Diagnostic + if len(h.blockDroppedFetch) > 0 { + diags = append(diags, Diagnostic{ + Code: CodeBlockDropsRuntimeFetch, + Severity: SeverityWarning, + Field: "harness", + Message: fmt.Sprintf("the agents entry's harness: block leaves out %s, set by a layer below it: like a base: child, a block does not inherit the runtime fetch fields (ADR 0158); set them in the block to keep them (in the config.yaml block when config.base.yaml has one too), or set allow_runtime_fetch: false to drop them on purpose", strings.Join(h.blockDroppedFetch, ", ")), + }) + } + + if h.blockDroppedCIVariableCredential { + diags = append(diags, Diagnostic{ + Code: CodeBlockDropsCIVariableCred, + Severity: SeverityWarning, + Field: "harness", + Message: "the agents entry's harness: block leaves out allow_ci_variable_credential, set by a layer below it: like a base: child, a block does not inherit it; set it in the block to keep it (in the config.yaml block when config.base.yaml has one too), or set it to false there to drop it on purpose", + }) + } + + if h.blockTriggerIgnored != "" { + diags = append(diags, Diagnostic{ + Code: CodeBlockTriggerIgnored, + Severity: SeverityWarning, + Field: "harness.trigger", + Message: fmt.Sprintf("agents entry %q: harness.trigger is not evaluated for a built-in agent until built-in agents are routed by CEL alone (ADR 0162, #2902)", h.blockTriggerIgnored), + }) + } + if len(h.RunnerEnv) > 0 { msg := "runner_env is deprecated; use env.runner instead (see ADR 0055)" if h.Env != nil && len(h.Env.Runner) > 0 { diff --git a/internal/harness/lint_test.go b/internal/harness/lint_test.go index d8a0f58a9d..672a6580e1 100644 --- a/internal/harness/lint_test.go +++ b/internal/harness/lint_test.go @@ -611,6 +611,9 @@ func TestDiagnosticCodeConstantsMatchPattern(t *testing.T) { CodeTriggerInvalid, CodePreflightCheckPath, CodeGithubIssueURLDeprecated, + CodeBlockDropsRuntimeFetch, + CodeBlockDropsCIVariableCred, + CodeBlockTriggerIgnored, } seen := map[string]struct{}{} for _, c := range codes { diff --git a/internal/harness/registry.go b/internal/harness/registry.go index eab194fd1d..7eb9f59f92 100644 --- a/internal/harness/registry.go +++ b/internal/harness/registry.go @@ -42,9 +42,10 @@ func RegisteredAgents(cfg config.ConfigReader) ([]RegisteredAgent, error) { if !entry.IsEnabled() { continue } - // An override-only entry tunes a built-in agent (runtime/model/ - // effort) but registers no harness of its own: the built-in stage - // runs it, so it is not a custom harness to enumerate or lock. + // An override-only entry tunes a built-in agent (any setting + // HasSettings counts) but registers no harness of its own: the + // built-in stage runs it, so it is not a custom harness to + // enumerate or lock. if entry.IsOverrideOnly() { continue } diff --git a/internal/harnessdispatch/enumerate.go b/internal/harnessdispatch/enumerate.go index 7c464a5203..e68a072659 100644 --- a/internal/harnessdispatch/enumerate.go +++ b/internal/harnessdispatch/enumerate.go @@ -56,6 +56,7 @@ 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 @@ -74,6 +75,9 @@ 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) diff --git a/internal/harnessdispatch/enumerate_test.go b/internal/harnessdispatch/enumerate_test.go index 4dac379838..4322ec78bd 100644 --- a/internal/harnessdispatch/enumerate_test.go +++ b/internal/harnessdispatch/enumerate_test.go @@ -684,3 +684,35 @@ func TestNewComposeOpts_ConfiguredGitHubHost(t *testing.T) { t.Setenv(forge.GitHubServerURLEnv, "") assert.Empty(t, newComposeOpts(configDir, cfg, nil, fetch.DefaultPolicy).GitHubURL) } + +// A block's trigger replaces a custom agent's; on a built-in agent name it is not evaluated. +func TestListTriggeredHarnesses_HarnessBlockTrigger(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, "harness"), 0o755)) + const body = `agent: agents/triage.md +role: triage +model: opus +image: ghcr.io/fullsend-ai/fullsend-sandbox:latest +` + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "issue-ping.yaml"), []byte(body), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "harness", "triage.yaml"), + []byte(body+`trigger: 'event.transition.kind == "closed"'`+"\n"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" +agents: + - source: harness/issue-ping.yaml + harness: + trigger: 'event.transition.kind == "opened"' + - source: harness/triage.yaml + harness: + trigger: 'event.transition.kind == "label_changed"' +`), 0o644)) + + dirCfg, err := config.LoadConfig(dir, config.LoadOpts{MissingOK: false}) + require.NoError(t, err) + + out, err := ListTriggeredHarnesses(context.Background(), dir, dirCfg, nil) + require.NoError(t, err) + require.Len(t, out, 2) + assert.Equal(t, `event.transition.kind == "opened"`, out[0].Harness.Trigger) + assert.Equal(t, `event.transition.kind == "closed"`, out[1].Harness.Trigger, "triage keeps its harness file's trigger") +} diff --git a/internal/lock/lock.go b/internal/lock/lock.go index 0bbcf2b0e1..c52a203bcc 100644 --- a/internal/lock/lock.go +++ b/internal/lock/lock.go @@ -171,10 +171,11 @@ func (lf *LockFile) Lookup(harnessName string) *HarnessLock { return &hl } -// IsStale returns true if the harness source file has changed since the -// lock entry was generated. It compares the harness file's SHA256 against -// the stored hash. sourceHash is the SHA256 of the current harness file -// content. Returns true for a nil receiver. +// IsStale returns true if the harness has changed since the lock entry was +// generated. It compares sourceHash against the stored hash. sourceHash is +// the SHA256 of the current harness file content, or, for an agent whose +// agents: entry carries harness: blocks, of that content followed by the +// blocks (ADR 0162). Returns true for a nil receiver. func (hl *HarnessLock) IsStale(sourceHash string) bool { if hl == nil { return true diff --git a/internal/repos/managed_config_schema.go b/internal/repos/managed_config_schema.go index 46fa577205..afda5c0032 100644 --- a/internal/repos/managed_config_schema.go +++ b/internal/repos/managed_config_schema.go @@ -126,7 +126,7 @@ func resolveManagedConfigSchema(ctx context.Context, fullsendRef, upstreamRef, u return s } if hasMapping { - s.Version = config.ManagedConfigSchemaVersion + s.Version = config.ManagedConfigSchemaTrackerMapping } else { s.Version = config.ManagedConfigSchemaLegacy } diff --git a/internal/repos/managed_config_schema_test.go b/internal/repos/managed_config_schema_test.go index 2d2228ee1a..4a5e9cbd16 100644 --- a/internal/repos/managed_config_schema_test.go +++ b/internal/repos/managed_config_schema_test.go @@ -27,7 +27,7 @@ func schemaAncestryKey(sha string) string { // schemaTestClient returns a fake upstream client where v0.1.0 is a legacy // release predating the schema declaration and the tracker mapping, and -// v0.9.0 declares the current schema. +// v0.9.0 declares the tracker-mapping schema. func schemaTestClient() *forge.FakeClient { fc := forge.NewFakeClient() fc.FileContentsAnyRef = nil @@ -59,12 +59,17 @@ func TestResolveManagedConfigSchema(t *testing.T) { fc.CommitAncestry[schemaAncestryKey(schemaTestCurrentSHA)] = "ahead" delete(fc.FileContentsRef, schemaDeclKey(schemaTestCurrentSHA)) s := resolveManagedConfigSchema(ctx, "v0.9.0", "", "", NewRefResolver(fc)) - assert.Equal(t, config.ManagedConfigSchemaVersion, s.Version) + assert.Equal(t, config.ManagedConfigSchemaTrackerMapping, s.Version) assert.Empty(t, s.Unknown) }) - t.Run("declared current schema", func(t *testing.T) { - s := resolveManagedConfigSchema(ctx, "v0.9.0", "", "", NewRefResolver(schemaTestClient())) + t.Run("declared schema", func(t *testing.T) { + fc := schemaTestClient() + s := resolveManagedConfigSchema(ctx, "v0.9.0", "", "", NewRefResolver(fc)) + assert.Equal(t, managedConfigSchema{Ref: "v0.9.0", Version: config.ManagedConfigSchemaTrackerMapping}, s) + + fc.FileContentsRef[schemaDeclKey(schemaTestCurrentSHA)] = []byte("3\n") + s = resolveManagedConfigSchema(ctx, "v0.9.0", "", "", NewRefResolver(fc)) assert.Equal(t, managedConfigSchema{Ref: "v0.9.0", Version: config.ManagedConfigSchemaVersion}, s) }) @@ -137,6 +142,23 @@ func TestSelectManagedConfigSchema(t *testing.T) { tcfg.FullsendRef = "v0.1.0" s = selectManagedConfigSchema(ctx, tcfg, nil, "", "", nil) assert.Contains(t, s.Unknown, "upstream GitHub client") + + // So does a harness: block, in the desired body or in the installed overlay. + bcfg, ok := blockManifest(t).ResolveConfig("acme", "api") + require.True(t, ok) + bcfg.FullsendRef = "v0.9.0" + s = selectManagedConfigSchema(ctx, bcfg, nil, "", "", NewRefResolver(schemaTestClient())) + assert.Equal(t, config.ManagedConfigSchemaTrackerMapping, s.Version) + cfg.FullsendRef = "v0.9.0" + s = selectManagedConfigSchema(ctx, cfg, []byte("agents:\n - name: review\n harness: { timeout_minutes: 30 }\n"), "", "", NewRefResolver(schemaTestClient())) + assert.Equal(t, config.ManagedConfigSchemaTrackerMapping, s.Version) +} + +func blockManifest(t *testing.T) *Manifest { + t.Helper() + m := newConvergeManifest("acme/api") + m.Defaults.Config = mustManagedConfig(t, "agents:\n - name: review\n harness:\n timeout_minutes: 30\n") + return m } func trackerManifest(t *testing.T) *Manifest { @@ -179,6 +201,21 @@ func TestDesiredManagedConfig_LegacyUnsupportedSetting(t *testing.T) { require.ErrorContains(t, err, "legacy configuration schema") } +// A harness: block is rendered for a ref that reads it and refused for an older one. +func TestDesiredManagedConfig_HarnessBlockNeedsCurrentSchema(t *testing.T) { + cfg, ok := blockManifest(t).ResolveConfig("acme", "api") + require.True(t, ok) + + current, _, err := desiredManagedConfig(cfg) + require.NoError(t, err) + assert.Contains(t, string(current), "timeout_minutes: 30") + + cfg.ConfigSchema = managedConfigSchema{Ref: "v0.9.0", Version: config.ManagedConfigSchemaTrackerMapping} + _, managed, err := desiredManagedConfig(cfg) + assert.True(t, managed) + require.ErrorContains(t, err, `fullsend_ref "v0.9.0": agents entry "review": a harness: block cannot be expressed`) +} + func TestCheckManagedConfigDrift_RefSchema(t *testing.T) { ctx := context.Background() m := trackerManifest(t) @@ -221,6 +258,29 @@ func TestCheckManagedConfigDrift_RefSchema(t *testing.T) { assert.Equal(t, preset.OverlayPath, status.Drifts[0].Field) }) + t.Run("installed harness: block at an older ref is incompatible", func(t *testing.T) { + fc := forge.NewFakeClient() + installed, _, err := desiredManagedConfig(managedResolved(t, fc, blockManifest(t), "acme", "api")) + require.NoError(t, err) + fc.FileContents[overlayKey] = installed + cfg := legacyCfg(fc) + cfg.ConfigSchema = managedConfigSchema{Ref: "v0.9.0", Version: config.ManagedConfigSchemaTrackerMapping} + status := RepoStatus{Installed: true} + checkManagedConfigDrift(ctx, cfg, &status) + assert.Empty(t, status.Error) + assert.Equal(t, ConfigIncompatible, status.ConfigCompatibility) + assert.Contains(t, status.ConfigCompatibilityReason, "harness: block") + }) + + t.Run("desired harness: block at an older ref is an error naming the entry", func(t *testing.T) { + fc := forge.NewFakeClient() + cfg := managedResolved(t, fc, blockManifest(t), "acme", "api") + cfg.ConfigSchema = managedConfigSchema{Ref: "v0.9.0", Version: config.ManagedConfigSchemaTrackerMapping} + status := RepoStatus{Installed: true} + checkManagedConfigDrift(ctx, cfg, &status) + assert.Contains(t, status.Error, `agents entry "review": a harness: block cannot be expressed`) + }) + t.Run("unknown schema is reported, file not judged current", func(t *testing.T) { fc := forge.NewFakeClient() cfg := managedResolved(t, fc, m, "acme", "api") diff --git a/internal/scaffold/cel_route_test.go b/internal/scaffold/cel_route_test.go index 208905bf37..f57ebe8e9c 100644 --- a/internal/scaffold/cel_route_test.go +++ b/internal/scaffold/cel_route_test.go @@ -673,24 +673,76 @@ func TestValidateAgentsConfigStep_AcceptsOverrideOnlySettings(t *testing.T) { {"unquoted boolean trigger", "agents:\n - name: review\n trigger: false\n", false}, {"blank trigger", "agents:\n - name: review\n trigger: \" \"\n", true}, {"empty trigger", "agents:\n - name: review\n trigger: \"\"\n", true}, + {"harness block only", "agents:\n - name: review\n harness:\n timeout_minutes: 30\n", false}, + {"harness block as an alias", "agents:\n - name: code\n harness: &blk\n timeout_minutes: 90\n - name: fix\n harness: *blk\n", false}, + {"empty harness block", "agents:\n - name: review\n harness: {}\n", true}, + {"null harness block", "agents:\n - name: review\n harness: ~\n", true}, + {"name only beside a bad merge key", "x: &s hello\nother:\n <<: *s\nagents:\n - name: review\n", true}, + } + run := func(t *testing.T, base, config string) (string, error) { + t.Helper() + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, ".fullsend"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".fullsend", "config.yaml"), []byte(config), 0o644)) + if base != "" { + require.NoError(t, os.WriteFile(filepath.Join(dir, ".fullsend", "config.base.yaml"), []byte(base), 0o644)) + } + cmd := exec.Command("bash", "-c", script) + cmd.Dir = dir + cmd.Env = []string{"PATH=" + os.Getenv("PATH")} + out, err := cmd.CombinedOutput() + return string(out), err } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - dir := t.TempDir() - require.NoError(t, os.MkdirAll(filepath.Join(dir, ".fullsend"), 0o755)) - require.NoError(t, os.WriteFile(filepath.Join(dir, ".fullsend", "config.yaml"), []byte(tc.config), 0o644)) - cmd := exec.Command("bash", "-c", script) - cmd.Dir = dir - cmd.Env = []string{"PATH=" + os.Getenv("PATH")} - out, err := cmd.CombinedOutput() + out, err := run(t, "", tc.config) if tc.wantErr { require.Error(t, err, "%s", out) - assert.Contains(t, string(out), "without a source field") + assert.Contains(t, out, "without a source field") return } require.NoError(t, err, "%s", out) }) } + + // The config.base.yaml entry of the same name completes a name-only entry, as the Go keyed merge does. + nameOnly := "agents:\n - name: lint\n" + layered := []struct { + name string + base string + config string + wantErr bool + }{ + {"base block", "agents:\n - name: lint\n harness:\n timeout_minutes: 30\n", nameOnly, false}, + {"base source as a string", "agents:\n - harness/lint.yaml\n", nameOnly, false}, + {"base source in a map", "agents:\n - source: https://example.com/harness/Lint.yaml#sha256=abc\n", nameOnly, false}, + {"base turns the agent off", "agents:\n - name: lint\n enabled: false\n", nameOnly, false}, + {"base turns the agent off, entry turns it on", "agents:\n - name: lint\n enabled: false\n", "agents:\n - name: lint\n enabled: true\n", true}, + {"base has no such agent", "agents:\n - name: other\n model: opus\n", nameOnly, true}, + } + for _, tc := range layered { + t.Run(tc.name, func(t *testing.T) { + out, err := run(t, tc.base, tc.config) + if tc.wantErr { + require.Error(t, err, "%s", out) + assert.Contains(t, out, "without a source field") + return + } + require.NoError(t, err, "%s", out) + }) + } + + // A yq failure is reported; fullsend run validates the entries again. + t.Run("a bad merge key in an entry is reported", func(t *testing.T) { + out, err := run(t, "", "x: &s hello\nagents:\n - name: review\n model: opus\n <<: *s\n") + require.NoError(t, err, "%s", out) + assert.Contains(t, out, "::warning::yq failed checking agent entries") + }) + t.Run("an unreadable config.base.yaml is reported", func(t *testing.T) { + out, err := run(t, "agents:\n - name: lint\n model: *nope\n", nameOnly) + require.NoError(t, err, "%s", out) + assert.Contains(t, out, "::warning::yq failed reading agent entries from config.base.yaml") + }) } // TestCELRouteSanitizerCopiesMatch keeps the gha_text copies in the CEL