From 86409f1f9f1e6f77ddc3c17e3c8eebd5da19a0c9 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Mon, 2 Nov 2026 14:56:39 +0200 Subject: [PATCH 001/208] docs(adr): share GitHub caching with read-only mint tokens Record ghproxy routing through layered configuration and read-only mint token reuse across equivalent roles and processes. Signed-off-by: Barak Korren Assisted-by: Codex --- docs/ADRs/0007-per-role-github-apps.md | 6 + ...ub-api-cache-with-read-only-mint-tokens.md | 135 ++++++++++++++++++ docs/architecture.md | 11 ++ docs/problems/agent-architecture.md | 4 + docs/problems/agent-infrastructure.md | 5 + docs/problems/security-threat-model.md | 5 + 6 files changed, 166 insertions(+) create mode 100644 docs/ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md diff --git a/docs/ADRs/0007-per-role-github-apps.md b/docs/ADRs/0007-per-role-github-apps.md index 17d0eba9e1..5611a9ada3 100644 --- a/docs/ADRs/0007-per-role-github-apps.md +++ b/docs/ADRs/0007-per-role-github-apps.md @@ -18,6 +18,12 @@ Date: 2026-04-02 Accepted +**Read-only token sharing:** +[ADR 0071](0071-share-github-api-cache-with-read-only-mint-tokens.md) +introduces a limited exception: roles authorized for identical read +permissions and scope may share a minted token; write credentials remain +per-role. + ## Context Agents need forge credentials to act on repos. A single shared credential for all agent roles violates least-privilege: a review agent would hold write permissions it should never use. The identity model must scope permissions per role while keeping setup automatable. See [agent-architecture.md](../problems/agent-architecture.md) and [security-threat-model.md](../problems/security-threat-model.md). diff --git a/docs/ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md b/docs/ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md new file mode 100644 index 0000000000..1d34511753 --- /dev/null +++ b/docs/ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md @@ -0,0 +1,135 @@ +--- +title: "71. Share GitHub API caching through ghproxy and read-only mint tokens" +status: Accepted +relates_to: + - agent-infrastructure + - agent-architecture + - security-threat-model +topics: + - github + - caching + - mint + - least-privilege +--- + +# 71. Share GitHub API caching through ghproxy and read-only mint tokens + +Date: 2026-11-02 + +## Status + +Accepted + +## Context + +Different agents and processes fetch the same GitHub entities, spending API +quota repeatedly (see [agent infrastructure](../problems/agent-infrastructure.md)). +Fullsend already keeps an ETag cache for selected GETs within each +[`LiveClient`][client-code], but separate clients cannot share it. +[ghproxy][ghproxy] shares an HTTP response cache across clients; +[ghcache][ghcache] revalidates cached responses with conditional requests and +coalesces concurrent reads. Authenticated, unchanged responses returning +`304` do not consume GitHub's [primary REST rate limit][github-limits]. + +ghproxy [partitions caches by the authorization header][ghcache-code], so +independently minted tokens fragment the cache even when they grant identical +access. The current [`mintToken`][mint-code] selects the requested role's App +and creates a token per request. This builds on the named permission levels +in [ADR 0073](0073-named-mint-privilege-levels.md) and introduces a narrow +read-only sharing exception to the per-role identities in +[ADR 0007](0007-per-role-github-apps.md). It complements the discovery-query +coalescing in [ADR 0149](0149-coalesce-entity-source-discovery-queries.md). +Sharing credentials must preserve the authorization boundaries described in +[agent architecture](../problems/agent-architecture.md) and the +[security threat model](../problems/security-threat-model.md). + +This ADR aims to conserve GitHub API quota across agents and processes by +sharing response caches and equivalent read-only credentials without widening +any caller's authorized access. + +## Options + +### Process-level caching + +Keep cached responses within each Fullsend process, extending the existing +client cache where useful. This avoids another service and keeps credential +lifetimes unchanged, but separate agents and processes still fetch and cache +the same entities independently; restarting a process also loses its cache. +It saves quota within a process without addressing reuse across processes. + +### ghproxy without further Fullsend changes + +Route existing clients through an externally deployed ghproxy while leaving +Fullsend's token issuance unchanged. This adds shared cache infrastructure +without changing the mint, and requests using the same token can benefit. +However, independently minted tokens still select different cache partitions, +so agents and processes with equivalent access cannot reliably share cached +responses. Deployment-specific routing also leaves consistent client and +agent-tool configuration to each operator. + +### ghproxy with a mint-level read-token cache + +Configure ghproxy routing in Fullsend and reuse mint-issued read-only tokens +by effective permission set and authorized scope. Equivalent requests from +different roles and processes use the same token and cache partition. This +addresses both response-cache sharing and token fragmentation, at the cost of +credential-cache storage, shared token lifecycle management, and explicit +audit attribution for cross-role reuse. + +## Decision + +We adopt optional ghproxy routing with a permission-keyed, read-only token +cache in the mint to make repeated GitHub reads share cached responses. +Configure the proxy through Fullsend's usual +[layered configuration](../guides/infrastructure/layered-config-reference.md), +following [ADR 0080](0080-config-yaml-vs-agent-env-var-scope.md), with no +separate environment-variable configuration surface. The resolved settings +apply to Fullsend's GitHub clients and supported agent API tools. With no +configured endpoint, retain direct GitHub access. + +Cache only tokens whose **actual granted permissions are all read-only**; +role and level names do not establish eligibility. Key entries by the +order-independent set of effective permission name/value pairs, within the +mint trust domain, GitHub host, target organization, and exact repository +scope. Equivalent roles and separate processes may receive the **same token +value**; tokens granting write or admin access remain unshared. + +Authorize each request, including the requested role's installation access, +before reusing a token, and never return broader access than that caller is +authorized to receive. A shared token may come from another authorized role's +App: this is the read-only exception to ADR 0007. Record the requesting role +and actual issuer separately, and use unshared credentials for operations +that require a particular App identity. Reuse must honor expiry, revocation, +and changes to the issuer's access or the authorized scope. + +Treat the proxy and mint cache as trusted credential-handling infrastructure. +Preserve credential isolation, authorization boundaries, and ghproxy's +authenticated cache partitions and conditional revalidation; a cache failure +must not broaden access or substitute stale data for successful revalidation. +Storage, replica coordination, transport wiring, and telemetry remain +implementation concerns. + +## Forge scope + +GitHub only, including GitHub Enterprise Server where the configured ghproxy +supports that API origin; hosts have separate cache namespaces. GitLab and +Forgejo are excluded because ghproxy and GitHub App installation tokens are +GitHub-specific; their credential and API routing contracts are unchanged. + +## Consequences + +- Equivalent reads across agents and processes can save primary REST quota, + but cache misses, changed resources, and secondary limits still matter. +- Read-only roles can share a token without sharing write authority, while + mint audit records preserve attribution that the shared GitHub identity loses. +- The proxy and token cache become credential-handling infrastructure whose + access controls and availability need operational ownership. +- Expiry and revocation affect all users of a shared token, so refresh and + cleanup must respect shared ownership and preserve authorization checks. + +[client-code]: https://github.com/fullsend-ai/fullsend/blob/93ff87e845f898f4d344ad90433bc30f5bddbfa1/internal/forge/github/github.go#L60-L80 +[mint-code]: https://github.com/fullsend-ai/fullsend/blob/93ff87e845f898f4d344ad90433bc30f5bddbfa1/internal/mintcore/handler.go#L517-L553 +[ghproxy]: https://docs.prow.k8s.io/docs/ghproxy/ +[ghcache]: https://docs.prow.k8s.io/docs/ghproxy/ghcache/ +[ghcache-code]: https://github.com/kubernetes-sigs/prow/blob/c06373a3e2cdcf0de2a087b4ed1db426366694b8/pkg/ghcache/ghcache.go#L390-L437 +[github-limits]: https://docs.github.com/en/rest/guides/best-practices-for-using-the-rest-api#use-conditional-requests diff --git a/docs/architecture.md b/docs/architecture.md index 19b5cbc5ab..e1372661b3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -356,6 +356,17 @@ Identity is not the same as trust. An agent's identity lets it authenticate to e **Decided:** +- Shared GitHub reads: optional ghproxy routing through the usual layered + configuration will let agents and processes reuse HTTP responses, backed + by a mint cache of tokens whose granted permissions are exclusively + read-only. Cache keys use the effective permission set within an exact host, + target organization, repository scope, and mint trust domain; equivalent + roles may share a token + after independent authorization, with the actual issuer recorded separately + from the requesting role. Write tokens stay unshared + ([ADR 0071](ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md)). + Decided, not yet implemented. + - Credential delivery model: four tiers — (1) prefetch + post-process for agents with enumerable inputs (zero credential access), (2) OpenShell providers + L7 egress policies for static token auth (credentials never enter sandbox), (3) host-side REST server for operations providers cannot handle — long-running operations, sandbox capability gaps, credentials in request bodies, response transformation, and multi-step atomic operations (see [ADR 0046](ADRs/0046-host-side-api-server-design.md)), (4) host files + L7 policies for complex auth requiring in-sandbox credential files. L7 policies enforce both method + path and binary-level restrictions. Providers are preferred over REST servers when viable ([ADR 0017](ADRs/0017-credential-isolation-for-sandboxed-agents.md), extended by [ADR 0025](ADRs/0025-provider-credential-delivery-for-sandboxed-agents.md)). OpenAI inference on the pi runtime is the first tier-2 use: the runner exchanges the job's GitHub OIDC token for a short-lived OpenAI access token and hands it to a run-scoped OpenShell provider, so no OpenAI credential enters the sandbox ([ADR 0092](ADRs/0092-openai-wif-credential-delivery.md)); the codex runtime reuses that provider and follows its refreshes by re-reading a runner-seeded token file through codex's `auth.command`, since its process environment cannot carry a placeholder that survives a refresh ([ADR 0099](ADRs/0099-codex-agent-runtime.md)). - Inference gateway route: a committed `inference.gateway` block in `.fullsend/config.yaml` names an LLM gateway (`url` and `audience`) that trusts the forge's OIDC issuer directly. The route is runtime-neutral: the credential is re-seeded through a route-aware seeder (the OpenAI seeder generalised, with independent handoffs when a run uses both routes), and each runtime keeps the gateway URL runner-owned. pi, codex and Claude Code use it, and on each the `gateway/` model prefix opts a model in: pi through the pi-inference-gateway extension, codex through a runner-owned `fullsend-gateway` provider in its digest-guarded `config.toml`, on the Responses API only, and Claude Code through a runner-owned `ANTHROPIC_BASE_URL`, cleared and re-exported after `.env`, with its credential from an `apiKeyHelper` that re-reads the re-seeded token file. The runner seeds the job's OIDC token, fetched with the gateway's audience, into a run-scoped OpenShell provider as an endpoint-bound placeholder and re-seeds it before `exp`, scheduled from each token's own `exp` and `iat`. The gateway holds the upstream provider key, so the forge stores no reusable provider key. The route is selected per model by provider prefix, with no precedence order against WIF or the static key: `openai/` and other providers keep their routes, one run can mix them, and a gateway that fails never falls back. The runner owns the route only when a complete block applies; without one, the plugin-carried setup for local runs is unchanged. On pi the route is a separate `gateway` provider served by pi-inference-gateway, with a runner-rendered, digest-guarded model list taken from inline `models` or a validated `models_file` ([ADR 0137](ADRs/0137-inference-gateway-credential-route.md)). The block's `auth` field selects the credential: `oidc` (the default, as above) or `api-key`, a supported mode for gateways that cannot trust forge OIDC. In `api-key` mode the runner reads a gateway key from `FULLSEND_INFERENCE_GATEWAY_API_KEY` and puts it behind the same placeholder, egress profile and guards, with no re-seed loop. The block then applies on local runs too. There is no fallback between modes, and because the mode relies on a long-lived secret, setup and status warn about it ([ADR 0138](ADRs/0138-inference-gateway-api-key-credential-mode.md)). An opt-in setting on the block, `messages_auth_header: x-api-key`, sends the gateway credential as `x-api-key` instead of `Authorization: Bearer` for Messages-dialect models (pi `anthropic-messages` models and Claude Code), for gateways that read the key where Anthropic documents it for that API. It is valid only with `auth: api-key`; an `oidc` block that sets it is a config error. The default stays `authorization`, the other dialects and codex keep Bearer, and an `x-api-key` gateway must replace the caller's key with its own on the upstream hop ([ADR 0142](ADRs/0142-inference-gateway-x-api-key-header-for-messages-models.md); implementation in [#8370](https://github.com/fullsend-ai/fullsend/issues/8370)). - GitHub Packages for sandboxed installs: the job's Actions workflow token is preserved as `GH_WORKFLOW_TOKEN`, readable only by provider credential expansion, and a repo-level provider binds it to `npm.pkg.github.com` (read-only, enforced) and the tarball CDN (which serves pre-signed URLs); forge identity stays the minted App token, which cannot read public packages owned by another org ([ADR 0114](ADRs/0114-github-packages-via-host-bound-workflow-token-provider.md)). diff --git a/docs/problems/agent-architecture.md b/docs/problems/agent-architecture.md index e905b26184..524dccd300 100644 --- a/docs/problems/agent-architecture.md +++ b/docs/problems/agent-architecture.md @@ -231,6 +231,10 @@ The multi-agent framework space is expanding rapidly, with new entries appearing - Should agents be stateless (fresh context per task) or stateful (accumulated knowledge of the codebase)? Stateless is safer (no poisoned state persists) but less efficient. - Should there be one instance of each agent type per repo, per org, or shared? Per-repo is simpler but more expensive. Shared agents need careful isolation. [ADR 0106](../ADRs/0106-serialize-agent-runs-and-coalesce-subsequent-events.md) fixes the per-harness, repository, and entity serialization scope; [ADR 0144](../ADRs/0144-reuse-poll-and-entity-bound-run-processes.md) permits a bound process to remain resident. If a centrally managed service is offered, its per-tenant repository configuration will use the existing `repos.yaml` v1 format; source of truth, execution topology, and isolation remain open ([ADR 0123](../ADRs/0123-tenant-configuration-from-repos-yaml.md); infrastructure constrains this — see [agent-infrastructure.md](agent-infrastructure.md).) - ~~What's the right model for agent identity? Agents need GitHub accounts to post comments and status checks. Separate bot accounts per agent role? A single bot account with role indicated in the comment? GitHub App installations?~~ Decided in [ADR 0007](../ADRs/0007-per-role-github-apps.md): per-role GitHub Apps with manifest-based creation. + [ADR 0071](../ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md) + permits equivalent read-only roles to share a minted token for the same + authorized scope, with each request independently authorized and attributed; + write identities remain per-role. - How do we test the interaction model? Can we simulate adversarial scenarios (injection attempts, unauthorized changes, agent disagreements) in a sandbox repo? - How does the two-phase review model work in practice? Does the code agent run all six sub-agents locally, or a subset? Is the pre-PR review a lighter version? (Depends on [agent-infrastructure.md](agent-infrastructure.md) — what compute is available where.) - What's the iteration limit before human escalation? Too low and humans get pulled in constantly. Too high and the system wastes resources on unresolvable conflicts. diff --git a/docs/problems/agent-infrastructure.md b/docs/problems/agent-infrastructure.md index 731bb5a68f..d947010346 100644 --- a/docs/problems/agent-infrastructure.md +++ b/docs/problems/agent-infrastructure.md @@ -122,6 +122,11 @@ Many fullsend scenarios skew toward **ephemeral, task-scoped** execution (triage ## Open questions +- How can agents and separate processes avoid repeatedly spending GitHub API + quota on the same entities? (Shared HTTP caching through ghproxy and + permission-equivalent read-only mint tokens decided in + [ADR 0071](../ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md); + deployment ownership and cache storage remain implementation work.) - What is the right level of isolation per agent (process, container, microVM, separate cluster)? - How do we provide agents with “resources to do their work” (clone, tools, APIs) without over-privileging them or creating a single high-value target? (Credential access decided in [ADR 0017](../ADRs/0017-credential-isolation-for-sandboxed-agents.md), with [ADR 0092](../ADRs/0092-openai-wif-credential-delivery.md) as the first inference credential delivered entirely through a gateway provider, and [ADR 0137](../ADRs/0137-inference-gateway-credential-route.md) routing inference through an LLM gateway that accepts the job's OIDC token so the forge stores no reusable provider key ([ADR 0138](../ADRs/0138-inference-gateway-api-key-credential-mode.md) adds an opt-in API-key mode for gateways that cannot trust forge OIDC, at the cost of a long-lived secret); tool access restrictions decided in [ADR 0027](../ADRs/0027-allowed-and-disallowed-tools-for-agents.md); cross-org public GitHub Packages access decided in [ADR 0114](../ADRs/0114-github-packages-via-host-bound-workflow-token-provider.md); user secrets for host-side scripts on GitHub decided in [ADR 0136](../ADRs/0136-runner-secrets-through-one-stored-secret.md); other resource access remains open.) - Do we need a dedicated “agent runner” image or environment with a known, auditable tool set? diff --git a/docs/problems/security-threat-model.md b/docs/problems/security-threat-model.md index fa7546288a..5379fcd95c 100644 --- a/docs/problems/security-threat-model.md +++ b/docs/problems/security-threat-model.md @@ -133,6 +133,11 @@ Agents amplify authority. If a compromised account can trigger agent actions, th verified platform invocation and human-reviewed policy and harness revisions that authorized it (see [ADR 0098](../ADRs/0098-entity-first-harness-evaluation.md)) +- **Shared read credentials retain scope boundaries** — + [ADR 0071](../ADRs/0071-share-github-api-cache-with-read-only-mint-tokens.md) + permits token reuse only for identical read permissions and repository + scope after independently authorizing each caller; the mint records both + the requesting role and actual issuer, and write tokens remain unshared. - **Human input admission and harness scope** — the target platform requires verified `triage` authority for ordinary human event actors, decision-relevant entity facts, and model-bound records, then enforces each From 78e66dd0b6cec0f3faace8d91334a8b31f55b119 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 09:29:16 -0500 Subject: [PATCH 002/208] fix(#6970): stop advising claude for review and retro on codex Review and retro run their sub-agents as native Codex children since v0.53.0 when the parent model resolves to collaboration V1 on the direct route. Both completed fleet-shaped runs that way on macOS and on Fedora, recorded on fullsend #6970. The setup prompt and four docs pages still told readers to keep the two agents on Claude Code. Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 5 +++-- .../getting-started/choosing-a-runtime.md | 4 ++-- docs/runtimes.md | 2 +- docs/runtimes/codex.md | 21 +++++++++---------- internal/cli/runtime_prompt.go | 2 +- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 2d8c95e421..7f9fcea8c9 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1578,8 +1578,9 @@ Two artefacts of the run are worth knowing about: and local smoke runs. - The rollout session files are archived as transcripts but not error-classified: only the tee'd `exec --json` capture yields a verdict, which is what the runner's exit-code override reads. -- Native sub-agents (ADR 0126) have not completed a fleet-shaped run; `review`/`retro` stay on - Claude Code in the docs until one does. +- Native sub-agents (ADR 0126) have completed fleet-shaped runs only locally, on macOS and on + Fedora ([#6970](https://github.com/fullsend-ai/fullsend/issues/6970)), not through the fleet + workflows. ### Re-check on a `CODEX_VERSION` bump diff --git a/docs/guides/getting-started/choosing-a-runtime.md b/docs/guides/getting-started/choosing-a-runtime.md index 8b1a94c3a9..5a9a8a29f8 100644 --- a/docs/guides/getting-started/choosing-a-runtime.md +++ b/docs/guides/getting-started/choosing-a-runtime.md @@ -4,7 +4,7 @@ sidebar_label: Choose a Runtime # Choose an agent runtime -> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`; codex runs OpenAI models through the same secretless credential path; `review`/`retro` are best left on Claude Code there. Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. +> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`; codex runs OpenAI models through the same secretless credential path. Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. This page explains what the choice means and where it is made. **You do not select anything on this page** — the selection happens in the next step. On GitHub, [Configuring GitHub](configuring-github.md) asks when you run `fullsend github setup` (press Enter for `claude`) or you pass `--runtime`. On GitLab, set `runtime:` in `defaults.config`, `gitlab.config`, or the repository entry's `config` in `repos.yaml` before running `fullsend repos install` (there is no install flag) — see [Configuring GitLab](configuring-gitlab.md). @@ -16,7 +16,7 @@ Fullsend supports multiple agent runtimes. A runtime is the program that runs in |---------|--------|-------------|-------------| | `claude` | **Stable (default)** | Claude Code on Vertex AI | Every production deployment — mature, full sub-agent support for `review`/`retro` | | `pi` | Experimental (enablement phase) | [Pi](https://github.com/earendil-works/pi) — Claude on Vertex by default; any provider pi supports by model name (e.g. Gemini on Vertex with the same credentials) | Opt-in pilots only; see [Runtimes](../../runtimes.md) for known constraints | -| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. Sub-agents run as [native Codex children](../../runtimes/codex.md#sub-agents), not yet verified fleet-wide, so keeping `review`/`retro` on Claude Code is recommended; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | +| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. Sub-agents run as [native Codex children](../../runtimes/codex.md#sub-agents) on OpenAI parent models that support them, such as `gpt-5.6-luna`, and in one context otherwise, including on every `gateway/` model; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | | `opencode` | Experimental | [OpenCode](https://opencode.ai/) — reads `AGENTS.md` natively | Opt-in read-only agents (`triage`, `prioritize`) until the security-hook adapter lands; see [OpenCode](../../runtimes/opencode.md) | ## When and how the runtime is selected diff --git a/docs/runtimes.md b/docs/runtimes.md index 5236117037..bd71bcc73a 100644 --- a/docs/runtimes.md +++ b/docs/runtimes.md @@ -58,7 +58,7 @@ sequenceDiagram | Sub-agents | Native (`Agent` tool) | `Agent`/`Task` via a fullsend extension | Native Codex children under a runner-owned policy, for an agent whose tools include `Agent` (or that declares no `tools:`), with harness security on, on a parent model Codex resolves to collaboration V1 on the direct route ([Sub-agents](runtimes/codex.md#sub-agents)) | | Default alias models | `opus`/`sonnet`/`haiku` → `claude-*-5-5`, passed as the id; `fable` by Claude Code's own table; sub-agent frontmatter resolved by Claude Code | `opus`/`sonnet`/`haiku` → `claude-*-5-5`, `fable` → `claude-fable-5-1`, children included | Not applicable — OpenAI models only | | Fallback model chain | Alias requests retried by the runner when Vertex does not serve the model (Claude Code's own "model not available" result naming the model, or Vertex's [two 404/403 messages](runtimes/claude.md#models)): `FULLSEND_FALLBACK_MODELS`, else the alias's built-in chain (`opus` → `claude-opus-4-6`, `sonnet` → `claude-sonnet-4-6`, `haiku` → `claude-haiku-4-5`); only an explicit `FULLSEND_FALLBACK_MODELS` is also passed as `--fallback-model`, never the built-in chain; pinned ids, retargets and sub-agents fail loudly | The same chain, same provider only; sub-agent children asking for an alias use its built-in chain; pinned ids and retargets fail loudly | Ignored with a warning | -| Roles | All | All; `review`/`retro` at `--thinking medium` by default | Same recommendation as before until a fleet-shaped run completes ([Sub-agents](runtimes/codex.md#sub-agents)) | +| Roles | All | All; `review`/`retro` at `--thinking medium` by default | All | | Effort | `--effort low..max` | `--thinking`, same levels (`high` when unset) | `model_reasoning_effort`, same levels | | Tools | Native Claude permission syntax | `--tools` (strict) + a first-token Bash allowlist | Shell + `apply_patch` only; `tools:` is recorded, not enforced (the allowlist hook is opt-in) | | Security controls | Full matrix | Full matrix; stricter on failed-call sanitizing | Full matrix; post-tool hooks detect and block but cannot rewrite output | diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index 7071615ff3..c25495d4dc 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -203,7 +203,9 @@ role's instructions and the message its parent sends. At most four are open at o is one. A runner-owned hook admits a spawn only for a registered role with `fork_context: false` and no model or effort override; it denies resume, Codex's built-in `explorer` and `worker`, and any spawn from a child. A denied spawn is final for that role: the parent runs that -sub-agent definition itself. A spawn the hook did not admit fails the run after the fact, within +sub-agent definition itself. In one live run the parent dropped it instead, and its result did not +say so ([#9073](https://github.com/fullsend-ai/fullsend/issues/9073)). +A spawn the hook did not admit fails the run after the fact, within the limits named in [Troubleshooting](#troubleshooting): per iteration the runner counts the spawns seen in the event stream or in the children's rollouts on disk, each child once, and compares the run's total with the admissions the hook recorded. Every child's rollout is saved and redacted like the @@ -398,16 +400,13 @@ has no default behaviour-test coverage; its scenario is gated. What was run, and is recorded in [codex runtime internals](../contributing/runtime-implementation.md#codex-runtime-internals-6920). -**Keep `review` and `retro` on Claude Code.** Their sub-agents run as native Codex children -([Sub-agents](#sub-agents)), but that path has not completed a fleet-shaped run yet. Nothing -prevents a repo-wide `runtime: codex` from applying to them — they will run — so pin them with -`runtime: claude` on their `agents:` entries until it has: - -```yaml -agents: - - name: review - runtime: claude -``` +**`review` and `retro` delegate.** On a V1 parent on the direct route with +harness security on, `review` runs its skill's personas and `retro` its +investigation tasks as native Codex children ([Sub-agents](#sub-agents)); +otherwise they run in one context. Both completed fleet-shaped runs +that way on `gpt-5.6-luna`, on macOS and on Fedora, locally rather than +through the fleet workflows +([#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). **`code` and `fix` delegate too.** They declare no `tools:`, so on a V1 parent on the direct route with harness security on they get the `default` and `explore` roles, children with the parent's shell and `apply_patch`, diff --git a/internal/cli/runtime_prompt.go b/internal/cli/runtime_prompt.go index 04246f6512..a7ef9d9e7e 100644 --- a/internal/cli/runtime_prompt.go +++ b/internal/cli/runtime_prompt.go @@ -32,7 +32,7 @@ func promptRuntime(printer *ui.Printer, in io.Reader, interactive bool) (string, printer.StepInfo("Choose the agent runtime for this repository:") printer.StepInfo(" [claude] Claude Code — stable default, recommended; all fleet agents, concurrent sub-agents") printer.StepInfo(" [pi] pi — experimental (enablement phase); any provider pi supports, no sub-agent tool yet") - printer.StepInfo(" [codex] Codex — experimental; OpenAI models, or gateway/ through an inference gateway. Recommended: keep review and retro on claude") + printer.StepInfo(" [codex] Codex — experimental; OpenAI models, or gateway/ through an inference gateway") printer.StepInfo(" [opencode] OpenCode — experimental; read-only agents only until the security-hook adapter lands (unbound-force#515)") printer.StepInfo(" Keep the default unless you are taking part in a runtime pilot. Change later with `runtime:`") printer.StepInfo(" in .fullsend/config.yaml or `fullsend github setup --runtime`; see docs/runtimes.md.") From ddf5a2c338a21a932412520ccfbf8a4ee258ab99 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 3 Nov 2026 11:37:53 -0500 Subject: [PATCH 003/208] docs(#6970): reword the codex row, update a stale comment The getting-started row said "in one context", which the page never defines, and implied every model that can spawn children delegates; it now names the allowed parents and says the parent otherwise does the sub-agents' work itself. The comment on codexSubagentNote still said the agents pr-review wording had not landed; it landed, with retro's, in fullsend-ai/agents#1849. Signed-off-by: Dharit Shah --- docs/guides/getting-started/choosing-a-runtime.md | 2 +- internal/runtime/codex_bootstrap.go | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/guides/getting-started/choosing-a-runtime.md b/docs/guides/getting-started/choosing-a-runtime.md index 5a9a8a29f8..a68016e663 100644 --- a/docs/guides/getting-started/choosing-a-runtime.md +++ b/docs/guides/getting-started/choosing-a-runtime.md @@ -16,7 +16,7 @@ Fullsend supports multiple agent runtimes. A runtime is the program that runs in |---------|--------|-------------|-------------| | `claude` | **Stable (default)** | Claude Code on Vertex AI | Every production deployment — mature, full sub-agent support for `review`/`retro` | | `pi` | Experimental (enablement phase) | [Pi](https://github.com/earendil-works/pi) — Claude on Vertex by default; any provider pi supports by model name (e.g. Gemini on Vertex with the same credentials) | Opt-in pilots only; see [Runtimes](../../runtimes.md) for known constraints | -| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. Sub-agents run as [native Codex children](../../runtimes/codex.md#sub-agents) on OpenAI parent models that support them, such as `gpt-5.6-luna`, and in one context otherwise, including on every `gateway/` model; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | +| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. Sub-agents run as [native Codex children](../../runtimes/codex.md#sub-agents) on the OpenAI parent models fullsend allows, such as `gpt-5.6-luna` but not the `gpt-6` ones; on any other model, `gateway/` ones included, the parent does the sub-agents' work itself; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | | `opencode` | Experimental | [OpenCode](https://opencode.ai/) — reads `AGENTS.md` natively | Opt-in read-only agents (`triage`, `prioritize`) until the security-hook adapter lands; see [OpenCode](../../runtimes/opencode.md) | ## When and how the runtime is selected diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index 78cb178ac4..9acaa3c5ee 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -407,10 +407,10 @@ const codexChunkedReadNote = "When reading a SKILL.md or other instruction file, // tools and states the policy the spawn guard enforces, so the parent passes // the arguments the guard admits and handles a denial without retrying. The // first two sentences and the denied-spawn sentence are what the agents -// repository's pr-review skill will key on once its codex wording lands; -// change them only together with that skill. roles is the registered -// roster, sorted by name (codexRoles). The child contract is in every role -// file (codexChildNote), not here. +// repository's pr-review skill and retro agent key on +// (fullsend-ai/agents#1849); change them only together with those. roles is +// the registered roster, sorted by name (codexRoles). The child contract is in +// every role file (codexChildNote), not here. func codexSubagentNote(roles []codexRole) string { names := make([]string, len(roles)) for i, role := range roles { From 427c80b8e2d4d63164a8e6a93b54f17fe4ca2247 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 8 Nov 2026 22:13:58 +0200 Subject: [PATCH 004/208] docs(adr): define entity source bindings and execution integration Record named connections, entity sources, typed harness slots, and provider filters as the configuration model for entity-driven execution. Explain native source resolution, CI integration, run modes, destination policy, and compatible migration from tracker. Add the versioned configuration contract and update the architecture, problem documents, and configuration reference. Signed-off-by: Barak Korren Assisted-by: Codex --- ...-entity-execution-through-named-sources.md | 459 +++++++++++ .../0098-entity-first-harness-evaluation.md | 5 + ...oalesce-entity-source-discovery-queries.md | 7 + docs/architecture.md | 59 +- .../entity-source-configuration/v1/README.md | 755 ++++++++++++++++++ docs/problems/agent-architecture.md | 14 + docs/problems/agent-infrastructure.md | 1 + docs/reference/config-reference.md | 14 + 8 files changed, 1305 insertions(+), 9 deletions(-) create mode 100644 docs/ADRs/0079-bind-entity-execution-through-named-sources.md create mode 100644 docs/normative/entity-source-configuration/v1/README.md diff --git a/docs/ADRs/0079-bind-entity-execution-through-named-sources.md b/docs/ADRs/0079-bind-entity-execution-through-named-sources.md new file mode 100644 index 0000000000..041456527f --- /dev/null +++ b/docs/ADRs/0079-bind-entity-execution-through-named-sources.md @@ -0,0 +1,459 @@ +--- +title: "79. Bind entity-driven execution through named connections and sources" +status: Accepted +relates_to: + - agent-architecture + - agent-infrastructure +topics: + - configuration + - entities + - dispatch + - polling +--- + +# 79. Bind entity-driven execution through named connections and sources + +Date: 2026-11-08 + +## Status + +Accepted + +Refines [ADR 0098](0098-entity-first-harness-evaluation.md): harnesses declare +named entity slots and their kinds; repository configuration binds those slots +to concrete sources. +Partially supersedes [ADR 0149](0149-coalesce-entity-source-discovery-queries.md): +source membership uses native provider semantics and may be checked remotely, +rather than requiring local reproduction over actor-filtered data. Its combined +search, current-membership, coverage, and retry requirements remain. The +lifecycles in [ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md) +remain unchanged. + +## Context + +The current `tracker` mapping selects one issue backend and its issue-creation +policy. [PR #9091](https://github.com/fullsend-ai/fullsend/pull/9091) added the +Jira connection and polling configuration contract. The +[review proposal](https://github.com/fullsend-ai/fullsend/pull/9091#discussion_r4465261777) +separates reusable connections, named entity sources, and agent bindings: one +connection can supply several entity kinds, and one agent can process equivalent +work from several systems. + +ADRs 0098, 0144, and 0149 define entity evaluation, reusable run processes, and +combined discovery, but leave the configuration and CI integration incomplete. +This ADR aims to connect those decisions through one repository-owned binding +model, while keeping agent coordination in entity state and predicates. + +## Options + +### Keep the current `tracker` syntax + +The existing syntax is compact and already understood by the issue commands, +Jira poller, and configuration tooling. For example: + +```yaml +tracker: + jira: + base_url: https://example.atlassian.net + project: PROJ1 + allowed_targets: + projects: [PROJ2] + poll: + enabled: true + query: 'statusCategory != Done ORDER BY updated DESC' +``` + +This selects Jira for issue commands, supplies one primary project and polling +query, and permits issue creation in the additional project. It works for a +single tracker, including Jira used from a repository hosted on GitHub or GitLab. +Keeping it avoids a configuration migration. + +The mapping accepts at most one provider block. It has no names for multiple +instances of a provider, no per-agent source bindings, and no source/target +entity-kind declarations. The example cannot express a triage agent reading +both native and Jira work items while a code agent reads only Jira and produces +native change proposals. Those concepts would have to be added to or alongside +`tracker`; the current shape is insufficient as the shared entity-execution +configuration model. It remains useful as a compatibility input. + +### Separate connections, sources, and harness bindings + +Named connections describe service instances, sources describe what to select, +and harness bindings connect those sources to an agent's needs. This supports +multiple providers and instances without putting repository-specific names in +reusable harnesses. It introduces more configuration concepts and requires a +compatibility adapter, but each concept has one role and can be shared across +agents. This is the selected option. + +## Decision + +Adopt named connections and entity sources as the binding between portable +agent harnesses and the shared discovery, dispatch, and run path. The +[entity-source configuration v1 contract](../normative/entity-source-configuration/v1/README.md) +defines the fields, defaults, layering, destination policy, and compatibility +translation. The sections below describe the target design; existing +deployments use `tracker` until their consumers migrate. + +### Configuration responsibilities + +The model separates four concepts: + +- A **connection** identifies a service instance, such as a Jira site or GitHub + Enterprise host. Repository configuration defines it under `connections`. +- An **entity source** identifies a connection, repository or project scope, and + selection query. Repository configuration defines it under `entity_sources`. +- A **slot** names an entity requirement of a harness. The harness's + `entity_kinds` map declares each slot's kind, such as `work_item` (an issue) + or `change_proposal` (a pull or merge request). +- A **binding** assigns a list of entity sources to a slot. Repository + configuration defines it under `agents[].entities`. + +Connections share the registry proposed for Vault in +[PR #9097](https://github.com/fullsend-ai/fullsend/pull/9097); a connection's +`kind` selects its service type. Sources do not have a `kind` field. Fullsend +checks that each source's provider and query support the consuming slot's kind. +Bindings select where an agent can look for entities; credentials and permission +checks remain separate. + +### Harness slots and defaults + +Only the `source` slot drives automatic discovery and scheduling. Its binding +list is a union of possible inputs: each run processes one source entity. +`target` gives the run its default destinations for new entities. Additional +slots give it other named scopes to query or use. Those slots do not start +polling loops, fetch every entity in advance, or create combinations of inputs. +Every slot accepts a list. When several output destinations are possible, the +operation must choose one explicitly; a list does not broadcast writes. + +Apply defaults after all configuration layers have been combined: + +- In the harness, the `source` kind defaults to `work_item`; the `target` kind + defaults to the effective source kind. Additional slots require a kind. +- In `agents[].entities`, `source` defaults to `[native]`; an omitted `target` + copies the effective source list. An explicit target, including an inherited + one, takes precedence. Additional slots require explicit nonempty bindings. +- Omitted slot values inherit. An explicit binding list replaces that slot's + inherited list. `source: []` disables source-based execution; `target: []` + removes the default output scope. + +Copying a source list to `target` copies names, not entities or kinds. For +example, a Jira work-item source cannot supply a `change_proposal` target; that +agent must bind its target to a compatible source, such as `[native]`. Unknown +slots and incompatible bindings fail validation. An old event-only harness +stays on its existing path until it is explicitly migrated; these defaults do +not opt it into entity execution. + +### Repository and harness examples + +The following YAML illustrates the target contract, not fields supported by the +current CLI. Repository configuration supplies connections, scopes, and bindings: + +```yaml +# .fullsend/config.yaml +connections: + jira1: + kind: jira + base_url: https://example.atlassian.net + api_url: https://api.atlassian.com + +entity_sources: + github: + # Customizes native selection when the configuration was cloned from GitHub. + query: 'is:open -label:blocked' + jira_work: + connection: jira1 + projects: [PROJ1] + query: 'statusCategory != Done' + discovery: true + jira_related: + connection: jira1 + projects: [PROJ1, PROJ2] + query: '' # No additional filter within these projects. + +agents: + - name: code + entities: + source: [jira_work] + target: [native] + related_work: [jira_related] + - name: triage + entities: + source: [native, jira_work] + # target is omitted, so it defaults to [native, jira_work]. +``` + +The same body can live in a preset installed as `.fullsend/config.base.yaml`, +or under `defaults.config`, `github.config`, `gitlab.config`, or a repository +entry's `config` in `repos.yaml` +([layered configuration](../guides/infrastructure/layered-config-reference.md)). +An overlay can replace one slot's list while inheriting the other slots. + +The corresponding code harness declares the kinds of its slots and its +predicate over the primary source entity: + +```yaml +# Harness YAML; other agent, policy, and runtime fields omitted. +entity_kinds: + source: work_item + target: change_proposal + related_work: work_item +entity_filters: + source: + github: 'is:open label:"needs-code" no:assignee' + gitlab: open + jira: 'statusCategory != Done' +trigger: >- + entity.kind == "work_item" && + entity.state == "open" && + "needs-code" in entity.labels +``` + +With the code binding above, this harness receives Jira work items, targets +native change proposals, and can query `related_work` when needed. `entity` in +CEL is the one source entity for the run. The example predicate works without +an event. After successful processing, the agent must remove the request signal +or use a predicate that checks whether it has already handled the work. A +predicate that reads event fields must first check `event != null`. Labels used +by CEL remain subject to the actor-authorization rules. + +Harness `entity_filters` maps slot names to provider-specific queries. Each +filter narrows the bound source's query and trusted scope; it cannot widen them. +Missing provider entries add no restriction. Only source filters participate in +automatic discovery and dispatch; other slot filters constrain explicit searches. +Filters do not inherit from source to target. They filter searches, not creation +destinations or lookups by an explicit entity identity. Matching a filter is +required for source-based execution, but the full harness CEL predicate must +also pass. + +For a work-item agent using the default kinds, the declaration can be: + +```yaml +# Harness YAML; source defaults to work_item and target defaults to source. +entity_kinds: {} +``` + +Together with the triage binding above, this means native and Jira work-item +inputs and the same native/Jira choices for new work-item targets. Creating in +Jira still needs an independent connection policy grant. If both binding keys +are omitted, they resolve to `source: [native]` and `target: [native]`. +Additional named slots require explicit bindings. The agent names in these +examples illustrate roles; they do not define a fixed inventory. + +### Resolving native sources + +`native` is an entity-source selector. Resolve it in three steps: + +1. The repository from which Fullsend configuration was cloned selects the + provider: GitHub, GitLab, or Forgejo. The platform running Fullsend does not + select it. +2. The corresponding reserved source name (`github`, `gitlab`, or `forgejo`) + selects a connection. It defaults to the connection with the same name. +3. That connection selects the instance. The source selects repository paths + on that instance. The clone host and path provide defaults; explicit + connection and source settings override them after layering. + +Reserved connection names imply their provider kind; an explicit `kind` must +agree. For example, a GitHub.com configuration clone can use a GitHub Enterprise +instance as its native forge: + +```yaml +# Configuration cloned from https://github.com/example/project. +connections: + github: + kind: github + base_url: https://github.example.com +entity_sources: + github: + query: 'is:open -label:blocked' +agents: + - name: triage + entities: + source: [native] +``` + +Here `[native]` and `[github]` both select `example/project` on +`github.example.com`, including when Fullsend runs on standalone Kubernetes or +in GitLab CI. Set `entity_sources.github.repositories` if the repository path +differs. The override selects an instance; access still requires credentials and +permissions for that instance. + +Provider source names can also be bound explicitly for external systems. A +GitHub-origin configuration can use `[gitlab]` when a GitLab connection and +repository scope are configured, without changing its native provider. The +contract includes a complete cross-provider example. A matching provider name +and `native` are aliases for the same effective source and do not duplicate +runs. Without a native-source override, selection includes all lifecycle states. +Defining `entity_sources.native` is forbidden. Additional names may be reserved +in future revisions, with validation of existing definitions. + +### Candidate selection and CEL evaluation + +Source queries and harness provider filters use the same language for each +provider: + +- Jira uses native JQL. Fullsend combines selection conditions with `OR` inside + the configured project scope and manages traversal order separately. +- GitHub uses the contract's subset of UI filters: state, labels, + author/assignee, milestone, issue type, missing metadata, dates, and PR + draft/branch fields, with Boolean combinations and exclusions. Full-text and + history/review search filters are outside the initial subset. Lifecycle + filters use `is:open` or `is:closed`; an empty query adds no restriction. +- GitLab initially uses `open`, `closed`, and `all` presets. Adapter support may + expand without requiring the same query language on every provider. + +For each source binding, require both the repository's source query and the +harness filter, within the configured repository or project scope. Combine +those effective selections across enabled harnesses so discovery retrieves +candidates needed by any of them. A provider adapter may retrieve a broader +shared set if it can then check each harness's selection exactly. It must still +account for pagination, provider limits, and missed or incomplete results. + +Source membership means that an entity currently matches this effective +selection. Use the provider's semantics. Reuse fetched data only when a local +check can prove the same answer; otherwise batch the remaining membership +checks through the provider, including Jira's +[JQL match API](https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issue-search/#api-rest-api-3-jql-match-post). +Equivalent queries and repeated references to the same entity share work when +their credential and authorization scopes are compatible. Unknown membership +remains unresolved and retryable; it is not evidence that no work exists. + +For GitHub, prefer GraphQL advanced search and request fields based on the +enabled harnesses' compiled CEL expressions. Fetch inexpensive shared fields +first, then additional fields and history only where evaluation remains +unresolved. Include the authorship and coverage evidence needed for +authorization, even when CEL does not reference those fields directly. +[ADR 0147](0147-evaluate-entity-cel-over-selectively-acquired-data.md) governs +these partial-data checks. Selecting fewer fields does not remove search caps +or pagination requirements. + +An entity matching a provider query is only a candidate. Before execution, +Fullsend must establish authorized invocation, a current source match, and a +true harness predicate over actor-filtered data. It must also prepare filtered +model context under [ADR 0141](0141-deterministic-filtered-entity-context-staging.md). +Provider-native fields may include changes that CEL is not allowed to use, so +query membership can select or suppress candidates but never proves an actor's +authority. This is the explicit change to ADR 0149's source-membership rule. + +### CI coordination and run modes + +Webhooks and polling supply candidates to the same Fullsend selection and +authorization path. Each dispatch identifies the agent, target repository, +canonical source entity, and resolved configuration revision. A resolved plan +contains the connections, source queries, slot bindings, and harness requirements +for that revision. Source aliases are not entity identities. + +Fullsend decides whether an agent should act. CI provides trusted invocation, +capacity, job deadlines, execution serialization, and result publication. +Existing jobs may remain as execution wrappers during migration; migrated jobs +use Fullsend's decisions rather than separate stage-routing conditions. + +Agents coordinate by changing entity state and recording completed work, which +other agents' predicates can observe. For example, triage can make a work item +eligible for a code agent, and a resulting change proposal can become eligible +for review. This introduces no workflow graph or automatic next-agent step. + +This binding model supplies the entities and eligibility checks needed by +[ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md). Its run modes remain: + +- `once`: one discovery cycle for `fullsend poll`, or one eligibility check and + at most one sandbox cycle for an entity-bound `fullsend run`, then exit. +- `poll`: repeat checks while waiting for work. An entity-bound run exits after + a finite idle period; the discovery process may stay alive until stopped. +- `timed`: repeat checks within a hard deadline, with the same idle exit for an + entity-bound run and enough budget reserved for each sandbox cycle it starts. + +An entity-bound run stays associated with one canonical entity and rechecks its +current source membership and predicate before each sandbox cycle. Reusing the +host process does not reuse the sandbox or model session. `fullsend poll` still +defaults to `once`. Bound runs default to `once` outside CI; the automatic CI +choice of `timed` also requires a usable deadline, sufficient initial-cycle +budget, permission for eventless checks, and working recurring discovery. + +Installation sets up recurring discovery for enabled source bindings. Before a +run can repeat checks without events, Fullsend must verify that discovery is +operational for its current plan and can recover work after the run exits. An +installed workflow file alone is insufficient. Missing or stale discovery +evidence keeps the automatic `once` fallback or rejects an explicit request to +repeat eventless checks. A configuration change invalidates old readiness; an +existing process stops starting new cycles under the obsolete plan. ADR 0144's +pending-work, cancellation, and rediscovery rules continue to preserve unfinished +work. + +### Destinations and standalone commands + +Inside a run, new entity creation defaults to the `target` slot. Updates to an +existing entity use that entity's canonical origin; a native target does not +redirect comments on a Jira source issue. Connection-scoped +`allowed_targets` remains an independent policy for work-item creation. A source +binding or query match does not grant write access. The contract defines the +destination checks and explicit cross-project creation rules. No separate +`issue_commands` configuration block is introduced. + +Standalone issue commands select one named source with the proposed +`--entity-source ` flag, or explicitly select `native` after resolving the +origin's provider and configured connection/source overrides. The command +supplies the `work_item` kind; no harness or agent binding is needed. Infer the +project or repository only when the selected scope has one choice; otherwise +require explicit selection. For example, using `jira_work` from the repository +example: + +```sh +fullsend issues get --fullsend-dir .fullsend --entity-source jira_work --number 123 +fullsend issues get --fullsend-dir .fullsend --entity-source native --number 123 +``` + +The first command retrieves PROJ1-123 from Jira; the second retrieves issue 123 +from the effective native source, including any instance override. Operations +with an explicit entity identity use the connection and lookup scope without +applying discovery filters, so the first command also works for a closed issue. +Creation remains subject to independent permissions. These flags describe the +target CLI, not current functionality. Omitting the selector is an error unless +the compatibility adapter can preserve legacy command selection. An explicit +source overrides legacy defaults; combining `--entity-source` and `--tracker` +is an error. + +### Migration and activation + +Accept deprecated `tracker` mappings by translating them in memory, with +actionable warnings and no automatic file rewrite. Preserve connection settings, +queries, polling enablement, command defaults, credentials, and creation +permissions. The old syntax remains usable while its consumers migrate. + +Scripts that read raw tracker YAML must migrate to effective configuration before +new-only configurations are enabled. Syntax translation alone does not move an +agent from event reconstruction to entity-state execution. + +First make configuration loading and existing consumers understand both forms. +Then deliver the provider adapters, CI integration, and entity-capable harnesses. +Switch each agent/source binding once; its old and new dispatch paths must not +run in parallel. Activation requires the normalized-entity contract, a provider +query protocol with coverage guarantees, the new major authorization contract +required by ADR 0149, and model-context support for the provider and entity kind. +That authorization contract must account for native source-membership semantics. +This configuration contract does not replace those prerequisites. +Implementation is tracked under +[#8418](https://github.com/fullsend-ai/fullsend/issues/8418), with entity and +discovery contracts in [#8420](https://github.com/fullsend-ai/fullsend/issues/8420) +and [#8421](https://github.com/fullsend-ai/fullsend/issues/8421). + +## Forge scope + +The initial entity-adapter targets are GitHub and GitLab work items and change +proposals, plus Jira work items. A Jira project remains distinct from the code +repository where the agent works. Forgejo and additional kinds such as +conversations use the same binding model, but remain disabled until the required +entity, discovery, context, and execution support is available and validated. + +GitHub Actions and GitLab CI are the first CI integrations. Source providers are +independent of execution platforms; the same configuration-resolution rules +apply to standalone runtimes, including Kubernetes. Each combination activates +only when its adapters satisfy the relevant contracts. Existing event-only paths +remain available. + +## Consequences + +- Agents can process equivalent entities from several systems without knowing deployment-specific connection names. +- Explicit connections, sources, and bindings add configuration concepts that the single-tracker model did not require. +- Provider queries remain expressive, and shared discovery and selective reads can reduce API work, subject to exact membership and coverage checks. +- Existing tracker configurations continue working, but raw-YAML consumers and CI require a coordinated migration. +- Coverage readiness and adapter conformance become explicit activation requirements for resident runs. diff --git a/docs/ADRs/0098-entity-first-harness-evaluation.md b/docs/ADRs/0098-entity-first-harness-evaluation.md index 22166a48c5..7ffcb02040 100644 --- a/docs/ADRs/0098-entity-first-harness-evaluation.md +++ b/docs/ADRs/0098-entity-first-harness-evaluation.md @@ -62,6 +62,11 @@ one combined logical search per source scope and local per-harness routing. For source-backed harnesses, even an event-supplied candidate must pass a current local source-query membership check before sandbox admission. +[ADR 0079](0079-bind-entity-execution-through-named-sources.md) refines source +declarations into named, typed harness slots and repository-owned binding lists. +It also permits native provider membership checks as a separate selection gate; +actor-filtered CEL and model-context admission remain required. + ## Context [ADR 0061](0061-harness-cel-dispatch.md) made a `NormalizedEvent` the sole CEL diff --git a/docs/ADRs/0149-coalesce-entity-source-discovery-queries.md b/docs/ADRs/0149-coalesce-entity-source-discovery-queries.md index a7c9f3a44f..15b5e87bcc 100644 --- a/docs/ADRs/0149-coalesce-entity-source-discovery-queries.md +++ b/docs/ADRs/0149-coalesce-entity-source-discovery-queries.md @@ -25,6 +25,13 @@ candidate and to let a harness act on it. poll and bound-run lifecycles. This ADR adds a local source check before each sandbox cycle for an entity-driven harness. +[ADR 0079](0079-bind-entity-execution-through-named-sources.md) partially +supersedes the local-reproduction and actor-filtered source-query requirements: +membership follows native provider semantics, with exact local checks where +possible and batched provider checks otherwise. Combined enumeration, current +membership, coverage, and retry remain required; actor-filtered harness CEL +and model-context admission are independent gates. + ## Context ADR 0098 lets harnesses declare entity sources, but allows sharing only when diff --git a/docs/architecture.md b/docs/architecture.md index c52b43a73e..c7b9c3df9d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -496,6 +496,39 @@ The existing design principle is that [the repo is the coordinator](problems/age or explicit receipts to decide whether work has already been handled ([ADR 0098](ADRs/0098-entity-first-harness-evaluation.md), partially superseding [ADR 0063](ADRs/0063-polling-based-work-discovery.md)). +- Entity binding and CI integration (target state): harness `entity_kinds` maps + named slots to kinds, with source defaulting to work item and target to the + source kind. Repository `agents[].entities` maps those slots to lists of + scopes. Source defaults to `[native]`; omitted target copies the effective + source list, while additional slots require explicit bindings. + The configuration clone selects the native provider independently of the + runtime or CI platform. Its host and repository path supply defaults; + provider-default connections (`github`, `gitlab`, `forgejo`) can override the + instance, including GitHub.com to GitHub Enterprise. Reserved source names + default to those connections and can override queries and repository scopes. + The matching provider source and `native` resolve identically. Other provider names + require explicit external connections and scopes when bound. A source named + `native` is forbidden. Only source schedules work. + Harness `entity_filters` narrows each slot's source queries + by provider; primary selections combine for discovery and are checked before + full CEL admission. Other slot filters apply to explicit searches only. + GitHub source queries and harness filters share a bounded subset of native + UI metadata filters and Boolean combinations; unsupported syntax is rejected. + GitHub prefers GraphQL discovery with selective projections derived from + compiled CEL dependencies, progressively acquiring further decision and actor + evidence under ADR 0147. + The same resolved plan drives event + dispatch, broad polling, and bound-run checks, with CI providing trusted + invocation and execution rather than separate agent-routing decisions. + Installation verifies recurring discovery coverage for the effective plan + before resident eventless cycles can run. Target and additional slots make + typed scopes available to the run without implicit joins or broadcast writes. + Creation policy stays on connections independently of discovery; standalone + commands without context require explicit scope selection. Deprecated + `tracker` mappings translate in memory with warnings and preserved legacy + command defaults + ([ADR 0079](ADRs/0079-bind-entity-execution-through-named-sources.md), + [configuration contract](normative/entity-source-configuration/v1/)). - GitLab dispatch uses a native webhook fast-path for low-latency candidates and the cron-poller as the authoritative reconciliation backstop ([ADR 0125](ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). Native `merge_request_event` dispatch stays removed ([#7322](https://github.com/fullsend-ai/fullsend/issues/7322)). No external webhook bridge (see [ADR 0067](ADRs/0067-gitlab-cron-polling-event-dispatch.md) for the poller, credentials, and in-job gate). - Conversation participation: GitHub Discussions (and future chat systems) enter dispatch as resolved entities with `entity.kind: conversation`; when a @@ -599,11 +632,17 @@ The existing design principle is that [the repo is the coordinator](problems/age [ADR 0151](ADRs/0151-harness-human-role-minimums.md), [Authorization Contract v2](normative/authorization/v2/)). -- Entity-source discovery (target state): `fullsend poll` combines admissible - harness queries into one logical candidate search per source scope and routes - possible matches locally. A bound `run` rechecks source-query membership - before event-backed or eventless sandbox cycles - ([ADR 0149](ADRs/0149-coalesce-entity-source-discovery-queries.md)). +- Entity-source discovery (target state): `fullsend poll` combines source + queries into one logical candidate search per source scope. Source membership + follows native provider semantics, with exact checks over already-fetched + data or batched provider checks; Jira accepts native JQL, GitHub accepts a + bounded subset of UI metadata filters and Boolean combinations, and GitLab + starts with open/closed/all state selections. A bound `run` rechecks current + membership before event-backed or eventless sandbox cycles. Provider-native + selection can reflect changes excluded from the actor-filtered CEL view; it + grants no authority and does not admit content to the model + ([ADR 0149](ADRs/0149-coalesce-entity-source-discovery-queries.md), partially + superseded by [ADR 0079](ADRs/0079-bind-entity-execution-through-named-sources.md)). Implementation and the normative query protocol are tracked in [#8418](https://github.com/fullsend-ai/fullsend/issues/8418) and [#8421](https://github.com/fullsend-ai/fullsend/issues/8421). @@ -616,10 +655,12 @@ The existing design principle is that [the repo is the coordinator](problems/age [ADR 0147](ADRs/0147-evaluate-entity-cel-over-selectively-acquired-data.md) for selective acquisition and its authorization rules, and [ADR 0149](ADRs/0149-coalesce-entity-source-discovery-queries.md) - for query combination and local routing. The normative discovery protocol, - including query syntax, adapter mappings, and discovery coverage evidence, - remains open, as do the normalized entity-history and handled-state - contracts. + for query combination and coverage. Configuration, provider-specific query + selection, native membership, and CI binding are decided in + [ADR 0079](ADRs/0079-bind-entity-execution-through-named-sources.md). + Detailed provider query/consistency mappings and coverage evidence remain in + the pending discovery protocol, alongside the normalized entity-history, + handled-state, authorization, and model-context contracts needed for activation. - Is GitHub's event system sufficient for forge-native duplicate protection, or do we need additional coordination beyond label/state conventions and agent idempotency? (Jira polling per ADR 0063 uses entity-property locks and runner diff --git a/docs/normative/entity-source-configuration/v1/README.md b/docs/normative/entity-source-configuration/v1/README.md new file mode 100644 index 0000000000..62a9fd3730 --- /dev/null +++ b/docs/normative/entity-source-configuration/v1/README.md @@ -0,0 +1,755 @@ +# Entity-source configuration v1 + +This contract defines the configuration binding chosen by +[ADR 0079](../../../ADRs/0079-bind-entity-execution-through-named-sources.md). +It applies to effective per-repository configuration, including managed +`repos.yaml` layers. MUST, SHOULD, and MAY express requirements for conforming +implementations. + +**Target contract, not implemented:** existing configuration continues to use +`tracker`. This document is not the complete discovery/query wire protocol, +normalized-entity specification, or authorization contract. Those contracts, +provider conformance, and context support are prerequisites for entity-driven +execution, as required by ADR 0079. + +## Configuration shape + +Repository configuration binds named harness slots to entity-source scopes: + +```yaml +# .fullsend/config.yaml +connections: + jira1: + kind: jira + base_url: https://example.atlassian.net + api_url: https://api.atlassian.com + +entity_sources: + github: + # Customizes native selection when the configuration was cloned from GitHub. + query: 'is:open -label:blocked' + jira_work: + connection: jira1 + projects: [PROJ1] + query: 'statusCategory != Done' + discovery: true + jira_related: + connection: jira1 + projects: [PROJ1, PROJ2] + query: '' # No additional filter within these projects. + +agents: + - name: code + entities: + source: [jira_work] + target: [native] + related_work: [jira_related] + - name: triage + entities: + source: [native, jira_work] + # target is omitted, so it defaults to [native, jira_work]. +``` + +The example code harness declares +`entity_kinds: {source: work_item, target: change_proposal, related_work: work_item}`. +A triage harness can declare `entity_kinds: {}` to use the default work-item +source and target kinds. Agent names are illustrative, not a fixed inventory. +Concrete connection names and repository/project scopes belong to repository +configuration. The `entities` map is configuration, not a map of already-fetched +entity values exposed to CEL. + +Unknown fields, unknown names, incompatible provider/kind pairs, and empty +required scope lists MUST fail validation. Unsupported capabilities cannot be +treated as empty discovery results. Compatibility placeholders for existing +incomplete tracker declarations are limited to the migration rules below. + +### Connections + +`connections` is a map of names to service-specific settings. Each ordinary +entry MUST specify `kind`; arbitrary names do not imply a provider. The reserved +names `github`, `gitlab`, and `forgejo` are provider-default connections: their +kind is implied, and an explicit `kind` MUST agree. Initial enabled entity +connection kinds are `github`, `gitlab`, and `jira`; reserving `forgejo` does not +enable an unsupported adapter. Non-entity connection kinds, +such as Vault under [PR #9097](https://github.com/fullsend-ai/fullsend/pull/9097), +share the registry but MUST NOT be accepted by an entity source. + +Record the repository from which this invocation's Fullsend configuration was +cloned as trusted origin metadata: provider, host, and canonical repository +identity/path. This selects the native provider and supplies connection defaults; +it does not lock native entities to the clone host. For the origin's provider, +synthesize its named connection when absent, using the origin host. A declared +connection of that name replaces the default and MAY set a different `base_url`. +If it omits `base_url`, use the origin host; never fill it from the CI platform. +Other provider-default connections require an explicit endpoint when used. + +For example, a GitHub.com clone selects the `github` provider. Setting +`connections.github.base_url` to a GitHub Enterprise URL makes that instance +the default GitHub connection used by native entities. The same rule applies to +GitLab and Forgejo. The execution platform and imported layer/harness origins do +not change the selected provider, but trusted layered connection settings can +change its instance. Missing origin prevents native-provider inference; it MUST +NOT be guessed from the runner or current Git remote. There is no separate fixed +`repository` connection. Entity `native` is distinct from the Vault proposal's +`native` secret-source selector. + +Forge connections identify their provider instance through `base_url`; +Jira uses `base_url` for the site and optional `api_url` for its API +gateway, preserving the current Jira gateway default. Provider validation MUST +reject endpoints containing embedded credentials. Changing an alias's endpoint +does not transfer grants or cached evidence from the previous instance. An +inherited issue-creation policy MUST NOT authorize a different instance unless +trusted configuration explicitly rebinds that policy to the new instance. + +Connections identify where to connect, not an authorization principal. Host +credential resolution MUST bind each connection to a provisioned credential +scope and keep discovery credentials separate from harness run identities. +Legacy translated connections retain existing credential lookup. Credentials +MUST NOT be written into this configuration or sent in dispatch descriptors. +Additional connections require independently provisioned host bindings; they +MUST NOT inherit credentials merely because their `kind` matches. Concrete +credential-reference formats remain part of the provider credential contracts. + +### Sources and queries + +`entity_sources` is a map of named entries. Each ordinary source MUST have a +`connection` and a provider-valid `query`; it MUST NOT declare a `kind`. Reserved +provider entries can omit the connection as specified below. The +adapter's supported kinds and the query's selection are checked against each +consuming harness slot's kind. The same source may serve differently typed slots. +The planner enumerates only the kinds needed by active primary-source bindings. +A forge source's +`repositories` list scopes it to explicit canonical repository paths; omission +is permitted for the origin provider's default connection and means the clone's +repository path on that effective connection, which may be on a different host. +An explicit list selects other paths; an override does not claim they are the +same canonical repository as the clone. A Jira source MUST specify a nonempty +`projects` list. Source +scopes MUST resolve to canonical provider identities before use. Configuration +authorizes a source scope, not an arbitrary target code repository. + +GitHub accepts the bounded UI filter subset defined below; an explicitly empty +query adds no filter beyond the scope and kind guards. GitLab initially accepts +`open`, `closed`, and `all` presets for `work_item` and `change_proposal`. For change proposals, +`closed` includes both merged and closed-unmerged entities; CEL can distinguish +them. Jira work-item sources accept native JQL; an explicitly empty string +adds no filter beyond the project guard. Their project guard is independent of +the query: +`OR` terms MUST NOT widen it. When scopes overlap, adapters plan per canonical +provider/tenant/project-or-repository/kind/credential scope, so each scope has +one combined logical enumeration under ADR 0149, not one search per alias. + +GitLab's presets are an initial Fullsend subset, not a claim that the provider +supports only lifecycle filters. Its [REST issue filters](https://docs.gitlab.com/api/issues/#list-all-project-issues) +also include labels, assignees, and dates. Its +[GLQL operators](https://docs.gitlab.com/user/glql/#operators) support conjunction +and some same-field alternatives through `in`, but not arbitrary disjunctions +of whole queries. GitHub supports +[Boolean and nested issue filters](https://docs.github.com/en/issues/tracking-your-work-with-issues/using-issues/filtering-and-searching-issues-and-pull-requests#building-advanced-filters-for-issues) +and an advanced-search option in its +[search API](https://docs.github.com/en/rest/search/search#search-issues-and-pull-requests). +Query support requires adapter conformance for the deployed provider +version, exact membership, and complete discovery under provider limits. + +For Jira, combine parenthesized selection predicates and use one adapter-owned +traversal order. Individual `ORDER BY` clauses do not alter set membership and +MUST be separated before combination. Any batching or partitioning required by +provider limits remains part of that combined logical enumeration and MUST +preserve coverage. Unsupported queries or capabilities MUST fail explicitly; +they cannot silently become unrestricted, disappear from the plan, or cause a full +search per agent. Time-dependent queries require periodic rediscovery even +without entity updates. Provider-side filter changes and other dependencies +must likewise be reconciled rather than assumed immutable. + +Native provider semantics determine membership. Local evaluation MAY avoid a +provider membership request only when it proves the same result from current, +sufficiently complete data under the same provider scope, credential identity, +and relevant query context. The adapter MUST NOT substitute the actor-filtered +CEL view. For example, `currentUser()` cannot be reinterpreted using the agent's +run identity. Batch unresolved membership checks across entities and distinct +queries in one credential scope. Query errors or uncertain freshness produce +an unresolved candidate with retry/rediscovery, never a false result. A proven +false harness predicate MAY avoid membership reads for that harness; a true +predicate cannot bypass membership. A prior discovery result does not prove +membership at a later sandbox cycle. + +`discovery` is a boolean, defaulting to `true`, that permits broad enumeration +and eventless rechecks when this scope is bound to the primary `source` slot. +Binding it only to another slot adds no scheduled work. It does not authorize execution or +set the clock frequency. `false` permits event-backed candidates subject to +current membership and admission, but excludes this source from broad polling +and eventless execution. Effective platform eligibility and operational polling +coverage remain required even when it is `true`. + +### Native sources and reserved names + +`native` is an entity binding selector, not a definable source name. +`entity_sources.native` MUST fail validation in every configuration layer. +Resolve `native` in order: the configuration origin selects the provider's +reserved source name (`github`, `gitlab`, or `forgejo`); that source selects its +connection; the effective connection selects the instance. Resolve the source's +repository scope and consuming slot's kind on that instance. The clone host and +path are defaults, not immutable native destinations. Execution platform never +selects the provider or overrides these configured values. + +The reserved provider names customize native selection. A declared reserved +entry MUST contain a provider-valid `query`. Its connection defaults to the +same-named provider-default connection; an explicit connection must have the +same provider kind. If the origin's matching source entry is absent, +synthesize it on that provider-default connection with an +all-state query and `discovery: true`: an empty query for GitHub, or `all` for +GitLab. If present, its `query` and optional +`discovery` override those defaults under ordinary whole-entry layering. Its +repository scope defaults to the clone's path on the selected instance; an +explicit `repositories` list overrides that path. Source connection overrides +and provider-default connection overrides therefore both affect native +resolution. Other named sources can select additional instances or scopes. + +Provider names MAY also appear explicitly in `agents[].entities` lists and in +standalone source selection. For the origin's provider, `[github]` (for example) +and `[native]` resolve to the same customized source even if its definition was +omitted. For a different provider, such as `[gitlab]` with a GitHub origin, an +explicit binding is allowed when that entry resolves a configured external +connection and an explicit repository scope. Its connection can be omitted when +the same-named provider-default connection is configured. Any connection +referenced by a reserved provider source +MUST have a kind matching that source name. Do not infer that external connection +from the execution platform. Such a source +does not change native resolution or acquire credentials or creation grants. + +An unbound reserved entry for another provider may contain just its query and +discovery settings so a preset can customize several native providers. It does +not activate that provider. Binding it explicitly on a nonmatching origin +requires the missing external connection and scope to be supplied; otherwise +validation fails. Reservation alone does not enable a Forgejo adapter: provider, +kind, query, and admission support are still required before a source is used. +Additional names may be reserved in future contract revisions; adding a +reservation must diagnose existing incompatible definitions rather than silently +reinterpret them. + +```yaml +# Configuration cloned from GitHub.com; runtime may be Kubernetes or GitLab CI. +# Native entities use the configured GitHub Enterprise instance. +connections: + github: + kind: github + base_url: https://github.example.com + gitlab: + kind: gitlab + base_url: https://gitlab.example.com +entity_sources: + github: + repositories: [example/project] + query: 'is:open -label:blocked' + gitlab: + repositories: [example/related-work] + query: open +agents: + - name: triage + entities: + source: [native, gitlab] + target: [github] +``` + +Here `native` and `github` select `example/project` on `github.example.com`, +even though the configuration was cloned from GitHub.com. `gitlab` selects the +configured external scope. Omitting `repositories` from the `github` source +would reuse the clone's owner/repository path on the enterprise instance. +Binding both `native` and `github` +does not duplicate discovery or executions. Native customization applies to all +uses of that native source, including omitted source bindings and targets that +inherit them; query filters still do not constrain creation or explicit identity +operations. Source and target kind defaults are unchanged. + +### GitHub query subset + +GitHub source `query` values and harness `entity_filters..github` accept +the same subset of native issue/PR search syntax. The initial supported +qualifiers are: + +- Lifecycle: `is:open`, `is:closed`, and their `state:` equivalents; for change + proposals, also `is:merged` and `is:unmerged`. +- Metadata: `label:`, `author:`, `assignee:`, and `milestone:` with literal + values; `type:` for issue types on work items. GitHub's `type:issue` and + `type:pr` aliases are kind assertions, like `is:issue` and `is:pr`. +- Missing metadata: `no:label`, `no:assignee`, and `no:milestone`. +- Dates: `created:`, `updated:`, and `closed:`, plus `merged:` for change + proposals. Accept absolute dates or timestamps, comparisons, and inclusive + ranges using GitHub's [date syntax](https://docs.github.com/en/search-github/getting-started-with-searching-on-github/understanding-the-search-syntax#query-for-dates). +- Change-proposal fields: `draft:true`, `draft:false`, `base:`, and `head:`. + +Use native [qualifier semantics](https://docs.github.com/en/search-github/searching-on-github/searching-issues-and-pull-requests), +including quoted values, case handling, and branch matching. Accept explicit +`AND`, whitespace conjunction, `OR`, and parentheses with GitHub's precedence. +Accept `-` exclusion of a single supported qualifier where GitHub permits it; +`-no:...` and negation of groups are not supported. Positive label comma lists +are native alternatives; repeated label terms are conjunctive. Express +exclusions with individual terms, such as `-label:blocked -label:wip`. +Use `is:open` or `is:closed` for lifecycle selection and `query: ''` for no +additional restriction. Bare `open`, `closed`, and `all` are unsupported free +text, not query shorthands. The adapter always retains the scope and kind guards. + +For example, a GitHub repository can provide a named source while a portable +harness further narrows it: + +```yaml +# .fullsend/config.yaml on a GitHub repository +entity_sources: + actionable_work: + connection: github + query: 'is:open (label:bug OR label:enhancement) -label:blocked' +agents: + - name: code + entities: + source: [actionable_work] + target: [native] +``` + +```yaml +# Harness YAML; other fields omitted. +entity_kinds: + source: work_item + target: change_proposal +entity_filters: + source: + github: 'is:open label:"needs-code" no:assignee' +``` + +The effective query requires both expressions inside the configured repository +and work-item guard. A review harness could instead use a change-proposal +source with `is:open draft:false base:main -label:blocked`. + +Parse and validate this subset before provider submission; do not pass unknown +syntax through as free text. Reject bare text, `in:`, general `NOT`, relative +dates, viewer-relative identities such as `@me`, and qualifiers outside the +list above. This excludes review/CI status, involvement or comment-history +filters, interaction counts, and project-board membership in v1. Richer agent +conditions remain in CEL until their native query membership and acquisition +contracts are supported. Sorting and ranking are adapter-owned; user `sort:` +is not accepted. Reject `repo:`, `org:`, and `user:` with a diagnostic pointing +to source scope configuration. Kind assertions MUST agree with the slot and +cannot replace the adapter's independent kind guard. + +Combine parsed expressions, then serialize with explicit grouping and escaped +values; never concatenate unchecked strings. Preserve every condition when +provider query-length or nesting limits require partitioning or broader shared +enumeration. Exact local checks use current provider-view metadata, including +complete relevant collections, and follow the native membership rules above. +Unknown membership remains unresolved; negative filters cannot treat unfetched +labels, assignees, or other metadata as absent. + +### Harness slots and repository bindings + +`entity_kinds` is a harness map from slot names to single normalized kind names. +The reserved slots are `source` and `target`; other names declare additional +requirements. Compose explicit harness declarations first, preserving which +keys were omitted, then apply these defaults: + +- Missing `source` means `work_item`. +- Missing `target` means the effective `source` kind. +- Every additional slot must explicitly name its kind. + +An explicit inherited target kind remains explicit when a child changes the +source kind. A defaulted target follows the final source kind. These defaults +apply to the entity-capable contract; they MUST NOT silently activate an old +event-only harness. `entity_kinds: {}` is an explicit declaration of the default +slots. A legacy harness without the declaration stays on its compatibility +path until coordinated entity-mode cutover. + +`agents[].entities` maps the same slot names to lists of scope names. Every +value MUST be a list, including when it contains one name. Every referenced +scope MUST exist and support the slot's effective kind. Compose bindings by +slot name: omission inherits, and an explicit list replaces that slot's list +rather than extending it. After composition, a missing `source` becomes +`[native]`; a missing `target` copies the effective source list, including an +explicit empty list. Explicit target lists, including inherited lists, win. +Copy scope names, not resolved entities or their kinds: resolve each copied +name against the target kind and reject incompatibility. For example, a Jira +source with a change-proposal target needs an explicit `target: [native]`. +Additional harness slots require explicit, nonempty lists, possibly inherited +from an explicit configuration layer. Unknown slot keys and missing required +bindings are configuration errors. Do not materialize default target lists in +parent layers before child source overrides have been applied. + +An explicit `source: []` disables source-based scheduling, including +source-backed event candidates, without restoring native defaults or inventing +an event-only fallback. An explicit `target: []` provides no default output +scopes; operations needing that slot fail until a valid target is bound. +Use ordinary agent enablement to disable an agent completely. + +Resolve `native` and the reserved provider names using the native-source rules +above, after configuration composition. The same source can resolve differently +for a work-item slot and a change-proposal slot. Missing native origin or +provider/kind support MUST be diagnosed, not replaced by an external connection +or treated as empty. External sources always require explicit bindings. + +Only the `source` slot drives automatic candidate discovery, event routing, +and scheduling. Its list is a union of alternatives; one run binds one +canonical source entity, exposed as `entity` to the existing CEL contract. +`target` and additional slots provide typed scopes available to the run. They +MUST NOT create automatic joins, Cartesian products, eager acquisition, or +independent polling/dispatch merely by being bound. Reading from such a scope +still requires the appropriate acquisition, actor-admission, and context +filtering contracts. A configured scope is not admitted model context. + +Every slot accepts multiple scopes. Output lists are choices, not automatic +broadcast. An operation identifies the slot and, when necessary, a specific +scope and repository/project within it. A single unambiguous destination may +be selected automatically; otherwise the operation MUST require an explicit +selection rather than use list order. Each selected destination must support +the slot's kind and pass independent run and creation policy checks. + +Deduplicate primary-source candidates by target code repository, agent, and +canonical entity identity, independently of aliases. Do not combine evidence +from incompatible credential/admission scopes to manufacture a successful +check. Matching several source aliases does not create several executions. +Replies and status updates on an existing entity use its canonical origin; +`target: [native]` does not redirect a Jira source issue's update to a forge +issue with the same display number. + +### Harness provider filters + +Harnesses MAY declare `entity_filters`, a map from effective entity slot names +to maps of provider kinds and query strings. Filters do not change the shape or +defaults of `entity_kinds`. For example: + +```yaml +entity_kinds: + source: work_item + target: change_proposal +entity_filters: + source: + github: 'is:open label:"needs-code" no:assignee' + gitlab: open + jira: 'statusCategory != Done' +trigger: >- + entity.state == "open" && + "needs-code" in entity.labels +``` + +Choose the provider entry from each bound connection's kind, including the +resolved native provider, not its connection alias. Query values use the same +provider-specific language and kind validation as source queries. Unknown +slots, unknown provider keys, and explicitly unsupported filters MUST fail +validation. An omitted provider entry adds no restriction. Compose filters by +slot and provider: omission inherits, while an explicit query replaces that +slot/provider's inherited query. Use an empty query for GitHub or Jira, or +`all` for GitLab, to explicitly remove an inherited restriction. Target filters +MUST NOT default to source filters, even when kinds and bindings do. + +For each binding, the effective selection is the intersection of the trusted +source scope, source query, and harness filter for that provider. The source's +scope and query remain enforced; a harness cannot broaden either. Combine the +effective selections of enabled primary-source bindings with logical OR in each +compatible discovery scope, deduplicating equivalent expressions. This is a +logical union requirement, not a requirement to serialize a native OR operator. +If the provider cannot express the union, the adapter MAY enumerate a shared +superset within the trusted scope and check the effective selections exactly. +It MUST preserve coverage, provider limits, and retry semantics; it MUST NOT +drop a filter or fall back to separate full searches per harness. When no +conforming plan is possible, report an unsupported combination. + +For `source`, the filter is a required selection condition, not an optional +performance hint. It applies to polling, event-backed candidates, and every +further bound-run cycle. Match the combined source query and harness filter +using native semantics, the exact local fast path, and batched unresolved +provider checks described above. Cheap filter mismatches can skip full CEL +evaluation; execution still requires both a current selection match and full +actor-filtered harness CEL, along with independent authorization and context +admission. A broader discovery result alone proves neither condition. + +Only `source` drives automatic discovery and scheduling. Filters on `target` +or additional named slots constrain explicit searches in those scopes without +adding background enumeration or eager acquisition. As with source queries, +they do not restrict creation destinations or explicit identity operations. +Standalone issue commands do not load a harness's filters. + +### GitHub search and selective acquisition + +The GitHub adapter SHOULD use GraphQL where it can combine discovery with +selective field acquisition. GitHub documents +[advanced search through GraphQL](https://github.blog/changelog/2025-03-06-github-issues-projects-api-support-for-issues-advanced-search-and-more/) +using `search(type: ISSUE_ADVANCED, query: ...)`; the current +[search schema](https://docs.github.com/en/graphql/reference/search) exposes that +type and typed issue/pull-request results. Validate the supported mode for the +deployed host. An unsupported mode MUST NOT silently fall back to interpreting +the same Boolean text with legacy search semantics. Preserve the per-kind +discovery scopes, using `is:issue` or `is:pr` explicitly. Search remains lexical +and set-based; semantic relevance and top-N ranking cannot establish coverage. + +Build two coordinated plans: a candidate-selection query from the effective +source/filter expressions, and a field-acquisition plan from enabled harness +CEL dependencies under [ADR 0147](../../../ADRs/0147-evaluate-entity-cel-over-selectively-acquired-data.md). +Mapping CEL field dependencies to GraphQL projections does not authorize +translating arbitrary actor-filtered CEL conditions into provider search terms. +The initial projection SHOULD share identity, scope, membership-routing facts, +and inexpensive decision-relevant fields across compatible harnesses. After +selection and partial evaluation eliminate harnesses or candidates, batch +further node reads for the dependencies still needed. Do not eagerly project +the union of every harness's complete history requirements onto every result. +Share acquired facts only across compatible credential and admission scopes. + +Projections MUST include or subsequently acquire the provenance, authorization +evidence, and coverage needed to establish a decision, even when those fields +are not named directly in CEL. Derived fields and provider aggregates cannot +substitute for the actor-filtered view. Page nested connections as necessary; +a partial label, comment, review, or timeline page is not a complete collection. +Apply ADR 0147's proven true/false versus unresolved semantics throughout. + +The search API exposes at most 1,000 results for one search, independently of +the selected fields. Partition or reconcile discovery as required by ADR 0149; +reaching that cap cannot establish coverage. GraphQL +[resource limits and partial errors](https://docs.github.com/en/graphql/overview/rate-limits-and-query-limits-for-the-graphql-api) +also apply: selecting fewer fields can reduce work, but does not by itself +guarantee fewer billed points or complete results. Required data affected by an +error remains unresolved, never absent. Full model-context acquisition remains +a separate admitted step after selection and predicate evaluation. + +### Destination policy and issue commands + +There is no `issue_commands` configuration block. Inside an agent run, new +entity creation defaults to the `target` slot; an operation may explicitly +select another declared slot and a destination in its list. Existing-entity +operations use the resolved entity's origin. A slot binding selects a provider, +kind, and scope; it does not grant credentials or mutation authority. Source +queries are neither creation templates nor authorization policies. A new entity +need not already satisfy a discovery query before it can be created. + +`connections..allowed_targets` carries the independent work-item creation +policy formerly under `tracker`: GitHub `orgs`/`repos`, GitLab `groups`/`repos`, +and Jira `projects`. Omission grants no additional destinations. The target +code repository remains implicitly allowed on its own forge and host, subject +to actual run permissions. For Jira, allowed creation projects must be listed +explicitly; the translator includes the legacy primary project to preserve its +implicit grant. Binding a Jira project as an input or output does not itself +grant creation rights there. Policies replace as whole values; grants cannot +move to another instance merely by reusing a connection alias. + +Lookup scope supplies the ordinary destination choices. An explicit work-item +creation destination outside that lookup scope is allowed only when the +connection's separate `allowed_targets` policy covers it, the operation selects +a compatible bound slot/connection, and run permissions allow it. This retains +legacy explicit cross-project issue creation without turning a discovery query +into a write grant. Change-proposal creation retains the execution repository +boundary and the existing forge/run permission checks. + +### Standalone issue commands + +Without agent/entity context, `fullsend issues` commands select one scope using +`--entity-source `, where the name is an effective `entity_sources` entry, +the reserved `native` selector, or its matching provider name. This is target +CLI syntax, not an implemented +flag. The command supplies the `work_item` kind, so the selected source MUST +support that kind. Resolve configuration through the normal layers, selected +with `--fullsend-dir` where needed; no agent or harness is required. The selector +is singular: standalone operations MUST NOT fan out across sources or inspect +an agent's `entities` bindings to choose a default. + +For the configuration above: + +```sh +# Resolve PROJ1-123 through jira1; jira_work has only one project. +fullsend issues get --fullsend-dir .fullsend --entity-source jira_work --number 123 + +# Select a project explicitly when the source contains several projects. +fullsend issues get --fullsend-dir .fullsend --entity-source jira_related --project PROJ2 --number 123 + +# Resolve issue 123 in the effective native source, including connection overrides. +fullsend issues get --fullsend-dir .fullsend --entity-source native --number 123 +``` + +Infer an omitted `--project` only when the selected scope identifies exactly one +project or repository. Otherwise require an explicit project/repository, or an +unambiguous entity identity where the command accepts one. Resolve `native` +only when its provider and effective connection/scope can be resolved from the +configuration origin plus overrides; missing required context MUST produce an +error. Validate explicit entity origins against the selected +connection and lookup scope. Explicit creation destinations remain subject to +the independent creation policy above, including its cross-project allowance. + +An explicit identity operation such as `get`, `post-comment`, or `link` MUST NOT +run the discovery query or require the identified entity to match it. For +example, `jira_work` can retrieve a closed PROJ1 issue by number even though its +discovery query excludes completed work. Queries select candidates for discovery; +they do not prohibit explicit scoped reads or updates. Authentication and +mutation checks still apply, and `create` still requires creation permission. + +Without an explicit source, standalone commands MUST NOT silently select the +first configured source, the first agent, or a native default. The compatibility +adapter alone preserves existing tracker command selection, including the old +`--tracker` selector and default connection/project behavior, with deprecation +warnings. An explicit `--entity-source` overrides legacy command defaults; +supplying it together with `--tracker` MUST fail as conflicting selectors. With +neither a selected source nor a legacy selection, fail with a diagnostic that +requests `--entity-source`. No new repository-wide command-default block is +introduced. Removing legacy tracker configuration therefore requires updating +standalone invocations; agent-context operations obtain their slots from the +plan. + +## Layering and legacy translation + +Named `connections` and `entity_sources` entries replace whole entries by name; +they do not deep-merge. Provider-default connections and reserved provider source +overrides use the same whole-entry replacement. After composition, use the +recorded configuration origin to fill omitted native defaults, then resolve the +effective connection and source. Explicit connection endpoints and repository +scopes win over clone-derived defaults. Omitted maps +inherit; empty maps do not delete unrelated +inherited names. Harness `entity_kinds` and agent `entities` compose by slot +name, with defaults applied only after composition. Each explicit binding list +replaces the inherited list for that slot. Creation allowlists MUST NOT be +unioned across layers. + +Resolve legacy `tracker` using its existing whole-block replacement semantics +across layers, then translate the effective result into a canonical fallback. +Explicit new entries override their translated equivalents, even if legacy +syntax occurs in a later layer; diagnostics MUST identify shadowed settings. +A new explicit slot binding replaces that translated slot's entire list. This +allows mixed-layer migration without changing legacy-only behavior or retaining +write grants from a replaced tracker provider. + +The translator uses `legacy_tracker` for its connection and lookup scope when +connection/polling settings exist. Explicit entries with that name replace the +corresponding generated entries and undergo ordinary validation; independent +new names coexist. Effective-config inspection MUST distinguish translated +entries, explicit replacements, and compatibility-only command defaults. + +Translate existing tracker configuration without guessing missing values: + +- Preserve provider, endpoint, host credential binding, and effective command + default connection/project. Jira's primary project becomes the lookup + scope's `projects` element; native JQL and its legacy default are retained. +- Preserve `poll.enabled`: true permits discovery, while false or omission + does not. A provider-only declaration creates no usable discovery scope; + incomplete Jira declarations retain their existing use-time failure. +- Copy `allowed_targets` to the connection policy, including Jira's implicit + primary-project grant and the existing native-repository grant. Do not add + fresh-install defaults to an existing installation's permissions. +- Legacy drivers and commands consume this resolved configuration through an + internal compatibility projection, including command defaults where there is + no agent context. Translation alone MUST NOT add entity declarations, change + poll checkpoints, switch predicate semantics, or replay historical work. +- At coordinated entity-mode cutover, established external routes become + explicit `entities.source` bindings and established output destinations + become typed slot bindings. Native defaults MUST NOT silently replace them. + An unmappable route or destination prevents that binding's cutover and keeps + its legacy path with a diagnostic. + +Runtime loading and managed installation MUST share normalization and +validation. Warn once per loaded legacy definition per process, with its +location and replacement guidance, on diagnostics rather than machine-readable +stdout. Reads MUST NOT rewrite source files. Raw-YAML consumers must migrate +to effective configuration or a host-generated compatibility projection before +new-only configuration is enabled; the projection is never a second authority +merged back into configuration. + +## Execution readiness and cutover + +The resolved execution plan records the agent/harness revision, trusted target +repository identity, configuration-origin provider/host/repository identity, +effective connection endpoints and canonical source repositories after overrides, +named slot kinds and binding lists, query/configuration revision, +credential-scope identity, and platform eligibility. Dispatch conveys canonical +entity identity and optional verified event context with a reference to this +trusted plan; event payloads MUST NOT supply connection endpoints, credentials, +or self-asserted eligibility. The receiving run revalidates the plan and current +admission before creating a sandbox. A discovery alias is not an execution lock. + +Installers reconcile recurring discovery only for enabled effective `source` +bindings; target and auxiliary lists do not add scheduled work. For GitHub Actions +execution this is a managed workflow; for GitLab CI execution it is a managed +pipeline schedule/job. These are execution adapters, not native-provider +selection rules. A standalone scheduler uses the same readiness and coverage +contract. Each invokes the shared Fullsend discovery path, +with the proper trusted credential scope, rather than reproducing agent routing +in workflow expressions. Event-driven GitHub Actions execution retains synchronous +dispatch correlation; GitLab CI uses its protected-default-branch delivery model. +Concurrency and result publication conform to ADR 0144, including preservation +of pending event-backed work and the latest selected cycle's result. + +Resident eventless execution requires evidence that the discovery mechanism is +enabled, compatible, and making progress for the same effective plan, including +durable retry or reconciliation for uncovered work. A workflow filename or a +historical successful job alone is insufficient. The execution adapter MUST +define a bounded readiness age relative to its configured schedule, retry and +cycle budget, and store/check that evidence in trusted per-repository state. +No new centralized scheduler is required. Missing or stale evidence gives +automatic once behavior; an explicit resident request fails with a diagnostic. + +Before each further cycle, verify current eligibility and plan readiness. A +changed configuration origin, binding, policy, credential scope, or execution +contract invalidates old readiness and cached membership. The resident process MUST stop admitting +new cycles and relinquish its claim through ADR 0144's pending-work protocol; +an already admitted sandbox retains the existing cancellation policy. New +invocations resolve the updated plan. Coverage invalidation MUST trigger a scan +for newly eligible work, not inherit a watermark that could skip it. + +Activate by agent/source binding after its contracts, adapters, context handling, +and harness support are deployed. For that binding, only one of legacy event +reconstruction and entity-driven admission may own dispatch at a time. Keep +legacy paths for unmigrated agents. Generic execution jobs or existing stage +wrappers may deliver admitted work, but all migrated bindings use the same +Fullsend admission logic. Job deadlines and lifecycle choices use ADR 0144; +source queries do not select lifecycle or define an agent sequence. + +## Conformance requirements + +Implementations MUST cover at least these observable cases: + +- Kind defaults and per-slot inheritance resolve correctly; all binding values + are lists, source defaults to `[native]`, and an omitted target copies the + final source list. Explicit targets win, copied names must support the target + kind, and additional named slots require explicit compatible nonempty bindings. +- Native resolution uses the clone's provider independently of Kubernetes, + GitHub Actions, or GitLab CI execution. Matching provider-default connections + can override the instance, including GitHub.com to GitHub Enterprise, and + source scopes can override the cloned path. Explicit matching-provider aliases + deduplicate with `native`; other provider names can bind external sources. + Missing external scope, mismatched provider kinds, and `entity_sources.native` + fail validation. Unbound cross-provider preset overrides start no discovery; + endpoint changes neither reuse old-host credentials/evidence nor transfer grants. +- Only the primary source list schedules work; target/auxiliary lists create + neither implicit joins nor broadcast writes, and ambiguous destinations need + explicit selection. Empty source/target lists suppress their defaults. +- Harness filters resolve by slot and connection provider, inherit by + slot/provider, and only narrow source selection. Missing filters add no + restriction; targets do not inherit source filters. Shared enumeration covers + the union of effective selections, with exact per-harness checks before + admission even when enumeration must use a superset. Event-backed and resident + cycles enforce the same filters. Other slots filter only explicit searches. +- GitHub subset parsing preserves Boolean grouping, quoted values, label + alternatives and exclusions, kind assertions, and native metadata/date + semantics. Unsupported terms and embedded scope/sort qualifiers fail before + provider submission. Negative and missing-metadata tests require complete + relevant facts; combining or partitioning cannot weaken a configured filter. +- GitHub discovery uses a verified advanced-search mode, with a projection + derived from currently relevant CEL and admission dependencies. Irrelevant + history is not eagerly fetched, partial nested collections remain explicit, + and search caps or field errors cannot establish complete coverage or a + negative predicate result. +- One canonical entity matching several aliases/queries admits at most one + execution per agent and target repository, without mixing credential scopes. +- Jira query combination preserves scoped membership; the local fast path + agrees with native evaluation, and unresolved checks batch without per-agent + searches or changing the effective Jira principal. +- A source match alone cannot authorize a sandbox or admit content; uncertain + membership, actor authority, or coverage cannot masquerade as a non-match. +- Legacy translation preserves command defaults, polling enablement, credential + resolution, and creation permissions, including whole-block tracker replacement, + provider-only Jira entries, and shadowing. Standalone invocations without + legacy defaults or agent/entity context require explicit scope selection. +- Standalone `--entity-source` selects one work-item scope independently of + agent bindings. Unique projects are inferred; ambiguous projects require + selection. Explicit identity operations can access entities outside a source's + discovery filter while retaining scope and authorization checks. Conflicting + new and legacy selectors fail, and legacy defaults cannot override an explicit + new selection. +- A new-format configuration works through migrated script consumers without + retaining `tracker` on disk; diagnostics do not corrupt machine-readable output. +- Lost coverage readiness and changed plans prevent new resident cycles while + preserving pending events and rediscovery; closed/merged entities remain + eligible for matching agents, including after webhook loss. + +Provider query pagination/consistency proofs, detailed authorization evidence, +and normalized entity/context schemas are specified and tested in their owning +contracts. Passing configuration conformance alone MUST NOT enable execution. diff --git a/docs/problems/agent-architecture.md b/docs/problems/agent-architecture.md index e905b26184..0dff8d6719 100644 --- a/docs/problems/agent-architecture.md +++ b/docs/problems/agent-architecture.md @@ -160,6 +160,20 @@ The repository's existing infrastructure provides all the coordination needed: combines source queries into one logical candidate search and routes each possible result locally. A bound run rechecks source-query membership, including when an event supplies the candidate. + [ADR 0079](../ADRs/0079-bind-entity-execution-through-named-sources.md) + binds named, typed harness entity slots to repository-owned source lists. + Harness provider filters further narrow those queries before full CEL + evaluation, with effective primary selections combined for discovery. + The configuration clone selects the native provider independently of where + agents execute. Provider-default connections can override its instance; + reserved source names supply queries and repository scopes, including + explicitly configured external providers. + Only the source slot schedules work; other slots supply scopes for the run + without automatic joins or broadcast outputs. It permits provider-native + membership with exact local checks or + batched remote checks; actor-filtered agent predicates remain independent. + CI supplies execution and verified recurring discovery, while coordination + stays in entity state and receipts rather than an agent workflow graph. No agent orchestrates other agents. Each agent independently observes the state of the PR and acts according to its role: diff --git a/docs/problems/agent-infrastructure.md b/docs/problems/agent-infrastructure.md index 03d4b04fc7..71f7bea8f1 100644 --- a/docs/problems/agent-infrastructure.md +++ b/docs/problems/agent-infrastructure.md @@ -126,6 +126,7 @@ Many fullsend scenarios skew toward **ephemeral, task-scoped** execution (triage - How do we provide agents with “resources to do their work” (clone, tools, APIs) without over-privileging them or creating a single high-value target? (Credential access decided in [ADR 0017](../ADRs/0017-credential-isolation-for-sandboxed-agents.md), with [ADR 0092](../ADRs/0092-openai-wif-credential-delivery.md) as the first inference credential delivered entirely through a gateway provider, and [ADR 0137](../ADRs/0137-inference-gateway-credential-route.md) routing inference through an LLM gateway that accepts the job's OIDC token so the forge stores no reusable provider key ([ADR 0138](../ADRs/0138-inference-gateway-api-key-credential-mode.md) adds an opt-in API-key mode for gateways that cannot trust forge OIDC, at the cost of a long-lived secret); tool access restrictions decided in [ADR 0027](../ADRs/0027-allowed-and-disallowed-tools-for-agents.md); cross-org public GitHub Packages access decided in [ADR 0114](../ADRs/0114-github-packages-via-host-bound-workflow-token-provider.md); user secrets for host-side scripts on GitHub decided in [ADR 0136](../ADRs/0136-runner-secrets-through-one-stored-secret.md); the sandbox environment the runner provides — which env vars it injects, per runtime, and which keys it reserves from harness override — is now published as a generated, machine-checkable contract ([ADR 0146](../ADRs/0146-sandbox-environment-contract-manifest.md)); other resource access remains open.) - Do we need a dedicated “agent runner” image or environment with a known, auditable tool set? - ~~How do we preserve end-to-end traceability for event-driven agent dispatch in GitHub Actions?~~ Decided in [ADR 0041](../ADRs/0041-synchronous-workflow-call-event-dispatch.md) (synchronous `workflow_call` dispatch for the event path). +- ~~How do CI wiring and recurring discovery support entity-bound resident runs without introducing a separate agent coordinator?~~ Decided in [ADR 0079](../ADRs/0079-bind-entity-execution-through-named-sources.md): shared binding/admission in Fullsend, execution in CI, and verified discovery readiness for the effective plan under ADR 0144's lifecycle rules. - How do we compare 3rd party vs internal vs build-our-own on concrete criteria: cost, time to first agent, compliance, and alignment with our security and coordination model? - Who in the org would own and operate agent infrastructure, and how does that align with existing platform or CI ownership? [ADR 0123](../ADRs/0123-tenant-configuration-from-repos-yaml.md) establishes the existing `repos.yaml` v1 format for tenant configuration in a possible centralized offering; the source of truth, service, operational ownership, and infrastructure remain open. - For cluster-hosted agents, how do we preserve an acceptable inner loop (fast local or sandboxed tests) without granting dangerous privilege, and how do we avoid paying for idle capacity while work waits on humans? (The poll/run process lifecycle and bound-run idle exit are decided in [ADR 0144](../ADRs/0144-reuse-poll-and-entity-bound-run-processes.md); capacity policy and the inner loop remain open.) diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 64eab0d0e8..1b1f789ad6 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -261,6 +261,20 @@ resources; a non-empty list is unioned with the parent's list. See ### `tracker` +The target replacement is specified in +[ADR 0079](../ADRs/0079-bind-entity-execution-through-named-sources.md) and the +[entity-source configuration contract](../normative/entity-source-configuration/v1/): +named `connections`, `entity_sources`, and `agents[].entities` slot bindings, +with connection-scoped creation policy, in-memory legacy translation, and +deprecation warnings. +The configuration clone selects the native entity provider independently of the +execution platform. Provider-default connections (`github`, `gitlab`, `forgejo`) +can override its instance, including GitHub.com to GitHub Enterprise. Reserved +provider source names select queries and repository scopes and can be explicitly +bound; defining a source named `native` is forbidden. +These fields and the translation are not implemented yet; the current supported +configuration remains the `tracker` mapping documented below. + The issue tracker, as a single provider-discriminated mapping. `tracker` holds at most one provider block — `github`, `gitlab`, or `jira` — and the block that is present selects the provider. It is the default backend for the `--tracker` From 7fd17699a0b38e1b4c931cc06e8d2c2dd99928c8 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Sun, 8 Nov 2026 23:42:45 +0200 Subject: [PATCH 005/208] docs(adr): resolve entity source configuration review Require same-named connection defaults and reserved source connections, and clarify when the origin repository path is inherited. Bind credentials to trusted endpoints, specify GitLab closed-state expansion, and resolve documentation and migration review findings. Signed-off-by: Barak Korren Assisted-by: Codex --- ...-entity-execution-through-named-sources.md | 56 +++-- .../entity-source-configuration/v1/README.md | 203 ++++++++++++------ docs/problems/agent-infrastructure.md | 6 +- 3 files changed, 175 insertions(+), 90 deletions(-) diff --git a/docs/ADRs/0079-bind-entity-execution-through-named-sources.md b/docs/ADRs/0079-bind-entity-execution-through-named-sources.md index 041456527f..f8704d3f59 100644 --- a/docs/ADRs/0079-bind-entity-execution-through-named-sources.md +++ b/docs/ADRs/0079-bind-entity-execution-through-named-sources.md @@ -32,15 +32,19 @@ remain unchanged. ## Context The current `tracker` mapping selects one issue backend and its issue-creation -policy. [PR #9091](https://github.com/fullsend-ai/fullsend/pull/9091) added the +policy, as specified in [issue #9074](https://github.com/fullsend-ai/fullsend/issues/9074). +[PR #9091](https://github.com/fullsend-ai/fullsend/pull/9091) added the Jira connection and polling configuration contract. The [review proposal](https://github.com/fullsend-ai/fullsend/pull/9091#discussion_r4465261777) separates reusable connections, named entity sources, and agent bindings: one connection can supply several entity kinds, and one agent can process equivalent work from several systems. -ADRs 0098, 0144, and 0149 define entity evaluation, reusable run processes, and -combined discovery, but leave the configuration and CI integration incomplete. +[ADR 0098](0098-entity-first-harness-evaluation.md), +[ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md), and +[ADR 0149](0149-coalesce-entity-source-discovery-queries.md) define entity +evaluation, reusable run processes, and combined discovery, but leave the +configuration and CI integration incomplete. This ADR aims to connect those decisions through one repository-owned binding model, while keeping agent coordination in entity state and predicates. @@ -243,14 +247,17 @@ examples illustrate roles; they do not define a fixed inventory. `native` is an entity-source selector. Resolve it in three steps: -1. The repository from which Fullsend configuration was cloned selects the - provider: GitHub, GitLab, or Forgejo. The platform running Fullsend does not +1. The repository from which fullsend configuration was cloned selects the + provider: GitHub, GitLab, or Forgejo. The platform running fullsend does not select it. 2. The corresponding reserved source name (`github`, `gitlab`, or `forgejo`) - selects a connection. It defaults to the connection with the same name. -3. That connection selects the instance. The source selects repository paths - on that instance. The clone host and path provide defaults; explicit - connection and source settings override them after layering. + uses the provider-default connection with the same name. It cannot use a + differently named connection. +3. That connection selects the instance. A trusted override of its `base_url` + can select another instance. For the origin provider, the reserved source's + repository path defaults to the clone path on that instance; its explicit + scope can select another path. Sources for other providers need explicit + repository scopes. Reserved connection names imply their provider kind; an explicit `kind` must agree. For example, a GitHub.com configuration clone can use a GitHub Enterprise @@ -272,7 +279,7 @@ agents: ``` Here `[native]` and `[github]` both select `example/project` on -`github.example.com`, including when Fullsend runs on standalone Kubernetes or +`github.example.com`, including when fullsend runs on standalone Kubernetes or in GitLab CI. Set `entity_sources.github.repositories` if the repository path differs. The override selects an instance; access still requires credentials and permissions for that instance. @@ -298,8 +305,10 @@ provider: draft/branch fields, with Boolean combinations and exclusions. Full-text and history/review search filters are outside the initial subset. Lifecycle filters use `is:open` or `is:closed`; an empty query adds no restriction. -- GitLab initially uses `open`, `closed`, and `all` presets. Adapter support may - expand without requiring the same query language on every provider. +- GitLab initially uses `open`, `closed`, and `all` presets. For change + proposals, `closed` expands to the union of native `state=closed` and + `state=merged` results; work items use native `state=closed`. Adapter support + may expand without requiring the same query language on every provider. For each source binding, require both the repository's source query and the harness filter, within the configured repository or project scope. Combine @@ -327,7 +336,7 @@ these partial-data checks. Selecting fewer fields does not remove search caps or pagination requirements. An entity matching a provider query is only a candidate. Before execution, -Fullsend must establish authorized invocation, a current source match, and a +fullsend must establish authorized invocation, a current source match, and a true harness predicate over actor-filtered data. It must also prepare filtered model context under [ADR 0141](0141-deterministic-filtered-entity-context-staging.md). Provider-native fields may include changes that CEL is not allowed to use, so @@ -336,7 +345,7 @@ authority. This is the explicit change to ADR 0149's source-membership rule. ### CI coordination and run modes -Webhooks and polling supply candidates to the same Fullsend selection and +Webhooks and polling supply candidates to the same fullsend selection and authorization path. Each dispatch identifies the agent, target repository, canonical source entity, and resolved configuration revision. A resolved plan contains the connections, source queries, slot bindings, and harness requirements @@ -345,7 +354,7 @@ for that revision. Source aliases are not entity identities. Fullsend decides whether an agent should act. CI provides trusted invocation, capacity, job deadlines, execution serialization, and result publication. Existing jobs may remain as execution wrappers during migration; migrated jobs -use Fullsend's decisions rather than separate stage-routing conditions. +use fullsend's decisions rather than separate stage-routing conditions. Agents coordinate by changing entity state and recording completed work, which other agents' predicates can observe. For example, triage can make a work item @@ -370,7 +379,7 @@ choice of `timed` also requires a usable deadline, sufficient initial-cycle budget, permission for eventless checks, and working recurring discovery. Installation sets up recurring discovery for enabled source bindings. Before a -run can repeat checks without events, Fullsend must verify that discovery is +run can repeat checks without events, fullsend must verify that discovery is operational for its current plan and can recover work after the run exits. An installed workflow file alone is insufficient. Missing or stale discovery evidence keeps the automatic `once` fallback or rejects an explicit request to @@ -452,8 +461,13 @@ remain available. ## Consequences -- Agents can process equivalent entities from several systems without knowing deployment-specific connection names. -- Explicit connections, sources, and bindings add configuration concepts that the single-tracker model did not require. -- Provider queries remain expressive, and shared discovery and selective reads can reduce API work, subject to exact membership and coverage checks. -- Existing tracker configurations continue working, but raw-YAML consumers and CI require a coordinated migration. -- Coverage readiness and adapter conformance become explicit activation requirements for resident runs. +- Agents can process equivalent entities from several systems without knowing + deployment-specific connection names. +- Explicit connections, sources, and bindings add configuration concepts that + the single-tracker model did not require. +- Provider queries remain expressive, and shared discovery and selective reads + can reduce API work, subject to exact membership and coverage checks. +- Existing tracker configurations continue working, but raw-YAML consumers and + CI require a coordinated migration. +- Coverage readiness and adapter conformance become explicit activation + requirements for resident runs. diff --git a/docs/normative/entity-source-configuration/v1/README.md b/docs/normative/entity-source-configuration/v1/README.md index 62a9fd3730..4c7fbec6d2 100644 --- a/docs/normative/entity-source-configuration/v1/README.md +++ b/docs/normative/entity-source-configuration/v1/README.md @@ -12,6 +12,12 @@ normalized-entity specification, or authorization contract. Those contracts, provider conformance, and context support are prerequisites for entity-driven execution, as required by ADR 0079. +The `v1` label versions this contract; it does not add a version field to +`config.yaml`. Configuration readers remain strict and older binaries may reject +the new fields. Deploy updated readers and managed-config consumers before +writing entity-source fields; mixed-version readers are not supported during +that cutover, and diagnostics MUST identify the unsupported configuration key. + ## Configuration shape Repository configuration binds named harness slots to entity-source scopes: @@ -74,7 +80,7 @@ enable an unsupported adapter. Non-entity connection kinds, such as Vault under [PR #9097](https://github.com/fullsend-ai/fullsend/pull/9097), share the registry but MUST NOT be accepted by an entity source. -Record the repository from which this invocation's Fullsend configuration was +Record the repository from which this invocation's fullsend configuration was cloned as trusted origin metadata: provider, host, and canonical repository identity/path. This selects the native provider and supplies connection defaults; it does not lock native entities to the clone host. For the origin's provider, @@ -82,28 +88,43 @@ synthesize its named connection when absent, using the origin host. A declared connection of that name replaces the default and MAY set a different `base_url`. If it omits `base_url`, use the origin host; never fill it from the CI platform. Other provider-default connections require an explicit endpoint when used. +Connection kinds and endpoints determine where credentials are sent. Only +configuration layers designated trusted by the repository's configuration +policy may set or change them; event data, harnesses, and untrusted overlays +MUST NOT. At minimum, trusted layers include managed `repos.yaml` values and +`.fullsend/` configuration read from the protected default branch under +[ADR 0033](../../../ADRs/0033-per-repo-installation-mode.md). PR-head config, +harness content, and event data cannot designate themselves as trusted endpoint +overrides. Credential bindings MUST be provisioned for the canonical provider +endpoint and tenant, and the resolver MUST refuse to send a credential to any +other endpoint even when the connection name and kind match. Changing an +endpoint requires a separately provisioned credential binding for that host; +the old host's credential, grants, and cached evidence do not transfer. For example, a GitHub.com clone selects the `github` provider. Setting `connections.github.base_url` to a GitHub Enterprise URL makes that instance the default GitHub connection used by native entities. The same rule applies to GitLab and Forgejo. The execution platform and imported layer/harness origins do -not change the selected provider, but trusted layered connection settings can -change its instance. Missing origin prevents native-provider inference; it MUST -NOT be guessed from the runner or current Git remote. There is no separate fixed -`repository` connection. Entity `native` is distinct from the Vault proposal's -`native` secret-source selector. +not change the selected provider, but trusted configuration layers can change the +provider-default connection's instance. Missing origin prevents native-provider +inference; it MUST NOT be guessed from the runner or current Git remote. There +is no separate fixed `repository` connection. Entity `native` is distinct from +the Vault proposal's `native` secret-source selector. Forge connections identify their provider instance through `base_url`; Jira uses `base_url` for the site and optional `api_url` for its API gateway, preserving the current Jira gateway default. Provider validation MUST -reject endpoints containing embedded credentials. Changing an alias's endpoint -does not transfer grants or cached evidence from the previous instance. An -inherited issue-creation policy MUST NOT authorize a different instance unless -trusted configuration explicitly rebinds that policy to the new instance. +reject endpoints containing embedded credentials. An inherited issue-creation +policy MUST NOT authorize a different instance unless trusted configuration +explicitly rebinds that policy to the new instance. Connections identify where to connect, not an authorization principal. Host credential resolution MUST bind each connection to a provisioned credential -scope and keep discovery credentials separate from harness run identities. +scope for the exact canonical endpoint and tenant, and keep discovery +credentials separate from harness run identities. A connection name or kind +alone MUST NOT select or reuse a credential for another host. Changing an +endpoint invalidates the old binding until a credential for the new host is +separately provisioned. Legacy translated connections retain existing credential lookup. Credentials MUST NOT be written into this configuration or sent in dispatch descriptors. Additional connections require independently provisioned host bindings; they @@ -112,36 +133,50 @@ credential-reference formats remain part of the provider credential contracts. ### Sources and queries -`entity_sources` is a map of named entries. Each ordinary source MUST have a -`connection` and a provider-valid `query`; it MUST NOT declare a `kind`. Reserved -provider entries can omit the connection as specified below. The +`entity_sources` is a map of named entries. Each source MUST resolve a +connection and provider-valid `query`; it MUST NOT declare a `kind`. If a source +omits `connection`, use the connection with the same name as the source and +require that connection to exist when the source is active. An unbound reserved +preset may omit its connection as described below. Reserved provider entries +follow the stricter same-name rule below. The adapter's supported kinds and the query's selection are checked against each consuming harness slot's kind. The same source may serve differently typed slots. The planner enumerates only the kinds needed by active primary-source bindings. -A forge source's -`repositories` list scopes it to explicit canonical repository paths; omission -is permitted for the origin provider's default connection and means the clone's -repository path on that effective connection, which may be on a different host. -An explicit list selects other paths; an override does not claim they are the -same canonical repository as the clone. A Jira source MUST specify a nonempty -`projects` list. Source -scopes MUST resolve to canonical provider identities before use. Configuration -authorizes a source scope, not an arbitrary target code repository. +An active forge source's `repositories` list scopes it to explicit canonical +repository paths. Omission is permitted only for the reserved source whose +provider matches the configuration origin. In that case it means the clone's +repository path on the same-named provider-default connection, including when +that connection uses an explicit `base_url` for another instance. All other +active forge sources, including reserved names for non-origin providers, MUST +specify `repositories`. An unbound reserved entry for another provider is an +inert preset and may omit its connection and repository scope until it is bound. +An explicit list selects those paths; it does not claim they are the same +canonical repository as the clone. A Jira source MUST specify a nonempty +`projects` list. +Source scopes MUST resolve to canonical provider identities before use. +Configuration authorizes a source scope, not an arbitrary target code +repository. GitHub accepts the bounded UI filter subset defined below; an explicitly empty query adds no filter beyond the scope and kind guards. GitLab initially accepts -`open`, `closed`, and `all` presets for `work_item` and `change_proposal`. For change proposals, -`closed` includes both merged and closed-unmerged entities; CEL can distinguish -them. Jira work-item sources accept native JQL; an explicitly empty string +`open`, `closed`, and `all` presets for `work_item` and `change_proposal`. These +are fullsend lifecycle predicates translated into native API filters. For change +proposals, `closed` means not open and expands to the union of native +`state=closed` and `state=merged` results; these are separate GitLab API states. +CEL can distinguish merged from closed-unmerged entities. Jira work-item sources +accept native JQL; an explicitly empty string adds no filter beyond the project guard. Their project guard is independent of the query: `OR` terms MUST NOT widen it. When scopes overlap, adapters plan per canonical provider/tenant/project-or-repository/kind/credential scope, so each scope has one combined logical enumeration under ADR 0149, not one search per alias. -GitLab's presets are an initial Fullsend subset, not a claim that the provider +GitLab's presets are an initial fullsend subset, not a claim that the provider supports only lifecycle filters. Its [REST issue filters](https://docs.gitlab.com/api/issues/#list-all-project-issues) -also include labels, assignees, and dates. Its +also include labels, assignees, and dates. The +[merge request API](https://docs.gitlab.com/api/merge_requests/#list-project-merge-requests) +exposes `closed` and `merged` as separate `state` values; the fullsend `closed` +preset therefore combines both native queries. The [GLQL operators](https://docs.gitlab.com/user/glql/#operators) support conjunction and some same-field alternatives through `in`, but not arbitrary disjunctions of whole queries. GitHub supports @@ -193,29 +228,31 @@ path are defaults, not immutable native destinations. Execution platform never selects the provider or overrides these configured values. The reserved provider names customize native selection. A declared reserved -entry MUST contain a provider-valid `query`. Its connection defaults to the -same-named provider-default connection; an explicit connection must have the -same provider kind. If the origin's matching source entry is absent, -synthesize it on that provider-default connection with an -all-state query and `discovery: true`: an empty query for GitHub, or `all` for -GitLab. If present, its `query` and optional -`discovery` override those defaults under ordinary whole-entry layering. Its -repository scope defaults to the clone's path on the selected instance; an -explicit `repositories` list overrides that path. Source connection overrides -and provider-default connection overrides therefore both affect native -resolution. Other named sources can select additional instances or scopes. +entry MUST contain a provider-valid `query`. The reserved source name is also +its connection name: `entity_sources.github` uses `connections.github`, +`entity_sources.gitlab` uses `connections.gitlab`, and `entity_sources.forgejo` +uses `connections.forgejo`. The source may omit `connection`, which defaults to +that same name; if specified, `connection` MUST equal the reserved source name. +A reserved source MUST NOT use a differently named connection, even when its +kind matches. To select a different instance for the native provider, configure +the same-named provider-default connection's `base_url`. If the origin's +matching source entry is absent, synthesize it on that provider-default +connection with an all-state query and `discovery: true`: an empty query for +GitHub, or `all` for GitLab. If present, its `query` and optional `discovery` +override those defaults under ordinary whole-entry layering. Its repository +scope defaults to the clone's path on the same-named connection, including when +that connection's endpoint is overridden; an explicit `repositories` list +selects another path. Other named sources can select additional instances or +scopes. Provider names MAY also appear explicitly in `agents[].entities` lists and in standalone source selection. For the origin's provider, `[github]` (for example) and `[native]` resolve to the same customized source even if its definition was omitted. For a different provider, such as `[gitlab]` with a GitHub origin, an -explicit binding is allowed when that entry resolves a configured external -connection and an explicit repository scope. Its connection can be omitted when -the same-named provider-default connection is configured. Any connection -referenced by a reserved provider source -MUST have a kind matching that source name. Do not infer that external connection -from the execution platform. Such a source -does not change native resolution or acquire credentials or creation grants. +explicit binding is allowed when the same-named provider-default connection and +an explicit repository scope are configured. Do not infer that external +connection from the execution platform. Such a source does not change native +resolution or acquire credentials or creation grants. An unbound reserved entry for another provider may contain just its query and discovery settings so a preset can customize several native providers. It does @@ -239,7 +276,6 @@ connections: base_url: https://gitlab.example.com entity_sources: github: - repositories: [example/project] query: 'is:open -label:blocked' gitlab: repositories: [example/related-work] @@ -252,9 +288,10 @@ agents: ``` Here `native` and `github` select `example/project` on `github.example.com`, -even though the configuration was cloned from GitHub.com. `gitlab` selects the -configured external scope. Omitting `repositories` from the `github` source -would reuse the clone's owner/repository path on the enterprise instance. +even though the configuration was cloned from GitHub.com. The `github` source +omits both `connection` and `repositories`: the same-named connection is used, +and the clone's owner/repository path carries over to that connection's +enterprise endpoint. `gitlab` selects the configured external scope. Binding both `native` and `github` does not duplicate discovery or executions. Native customization applies to all uses of that native source, including omitted source bindings and targets that @@ -608,11 +645,15 @@ A new explicit slot binding replaces that translated slot's entire list. This allows mixed-layer migration without changing legacy-only behavior or retaining write grants from a replaced tracker provider. -The translator uses `legacy_tracker` for its connection and lookup scope when -connection/polling settings exist. Explicit entries with that name replace the -corresponding generated entries and undergo ordinary validation; independent -new names coexist. Effective-config inspection MUST distinguish translated -entries, explicit replacements, and compatibility-only command defaults. +For every present provider block, the translator creates the compatibility +connection `legacy_tracker` using the legacy endpoint and credential-resolution +rules. It attaches that block's `allowed_targets` to this connection, including +for GitHub and GitLab blocks that contain only creation policy; they MUST NOT be +copied to another provider-default connection. A provider-only block still does +not create a discovery scope. Explicit entries with the name `legacy_tracker` +replace the corresponding generated entries and undergo ordinary validation; +independent new names coexist. Effective-config inspection MUST distinguish translated entries, explicit +replacements, and compatibility-only command defaults. Translate existing tracker configuration without guessing missing values: @@ -643,6 +684,13 @@ to effective configuration or a host-generated compatibility projection before new-only configuration is enabled; the projection is never a second authority merged back into configuration. +No release or removal date is set for `tracker` support. Keep the +compatibility translator until every supported reader, command, poller, +installer, and raw-YAML consumer has migrated and no supported execution +path depends on the legacy form. Removing it requires a later ADR and a +published major-release migration window. Until then, deprecation +warnings do not disable the old configuration. + ## Execution readiness and cutover The resolved execution plan records the agent/harness revision, trusted target @@ -660,7 +708,7 @@ bindings; target and auxiliary lists do not add scheduled work. For GitHub Actio execution this is a managed workflow; for GitLab CI execution it is a managed pipeline schedule/job. These are execution adapters, not native-provider selection rules. A standalone scheduler uses the same readiness and coverage -contract. Each invokes the shared Fullsend discovery path, +contract. Each invokes the shared fullsend discovery path, with the proper trusted credential scope, rather than reproducing agent routing in workflow expressions. Event-driven GitHub Actions execution retains synchronous dispatch correlation; GitLab CI uses its protected-default-branch delivery model. @@ -689,25 +737,39 @@ and harness support are deployed. For that binding, only one of legacy event reconstruction and entity-driven admission may own dispatch at a time. Keep legacy paths for unmigrated agents. Generic execution jobs or existing stage wrappers may deliver admitted work, but all migrated bindings use the same -Fullsend admission logic. Job deadlines and lifecycle choices use ADR 0144; +fullsend admission logic. Job deadlines and lifecycle choices use ADR 0144; source queries do not select lifecycle or define an agent sequence. ## Conformance requirements Implementations MUST cover at least these observable cases: +- The v1 contract has no in-band configuration version field. Old strict readers + reject entity-source keys with an actionable key-specific error; managed + rollout does not write those keys until every supported reader is upgraded. +- Connection endpoints can be changed only by trusted layers. Discovery + credentials are bound to the canonical endpoint and tenant; changing the host + requires a separately provisioned binding and never sends the previous host's + credential to the new endpoint. - Kind defaults and per-slot inheritance resolve correctly; all binding values are lists, source defaults to `[native]`, and an omitted target copies the final source list. Explicit targets win, copied names must support the target kind, and additional named slots require explicit compatible nonempty bindings. +- A source that omits `connection` uses the connection with the same name; + validation fails when that connection is absent. Reserved source names may use + only their same-named provider connection. For a GitHub-origin clone, + `entity_sources.github` may omit both `connection` and `repositories`; it uses + `connections.github` and the clone path even when that connection points to + GitHub Enterprise. `entity_sources.github.connection: enterprise` fails + validation. A reserved source for another provider must specify its repository + scope. Untrusted layers cannot change endpoints, and a new endpoint requires a + separately provisioned credential binding. - Native resolution uses the clone's provider independently of Kubernetes, - GitHub Actions, or GitLab CI execution. Matching provider-default connections - can override the instance, including GitHub.com to GitHub Enterprise, and - source scopes can override the cloned path. Explicit matching-provider aliases - deduplicate with `native`; other provider names can bind external sources. - Missing external scope, mismatched provider kinds, and `entity_sources.native` - fail validation. Unbound cross-provider preset overrides start no discovery; - endpoint changes neither reuse old-host credentials/evidence nor transfer grants. + GitHub Actions, or GitLab CI execution. Its provider-default connection can + override the instance. Explicit matching-provider aliases deduplicate with + `native`; external names do not change native resolution. Unbound + cross-provider preset overrides start no discovery, and endpoint changes do + not transfer grants or evidence. - Only the primary source list schedules work; target/auxiliary lists create neither implicit joins nor broadcast writes, and ambiguous destinations need explicit selection. Empty source/target lists suppress their defaults. @@ -731,13 +793,18 @@ Implementations MUST cover at least these observable cases: execution per agent and target repository, without mixing credential scopes. - Jira query combination preserves scoped membership; the local fast path agrees with native evaluation, and unresolved checks batch without per-agent - searches or changing the effective Jira principal. + searches or changing the effective Jira principal. GitLab `closed` for a merge + request combines native `state=closed` and `state=merged` results, while a work + item uses `state=closed`; neither preset mistakes merged for open. - A source match alone cannot authorize a sandbox or admit content; uncertain membership, actor authority, or coverage cannot masquerade as a non-match. - Legacy translation preserves command defaults, polling enablement, credential - resolution, and creation permissions, including whole-block tracker replacement, - provider-only Jira entries, and shadowing. Standalone invocations without - legacy defaults or agent/entity context require explicit scope selection. + resolution, and creation permissions, including whole-block tracker replacement + and shadowing. For provider-only GitHub and GitLab blocks, `allowed_targets` + attaches to the generated `legacy_tracker` connection; it is not lost or + copied to a provider-default connection. Provider-only Jira entries follow the + same rule. Standalone invocations without legacy defaults or agent/entity + context require explicit scope selection. - Standalone `--entity-source` selects one work-item scope independently of agent bindings. Unique projects are inferred; ambiguous projects require selection. Explicit identity operations can access entities outside a source's diff --git a/docs/problems/agent-infrastructure.md b/docs/problems/agent-infrastructure.md index 71f7bea8f1..397fb106be 100644 --- a/docs/problems/agent-infrastructure.md +++ b/docs/problems/agent-infrastructure.md @@ -126,7 +126,11 @@ Many fullsend scenarios skew toward **ephemeral, task-scoped** execution (triage - How do we provide agents with “resources to do their work” (clone, tools, APIs) without over-privileging them or creating a single high-value target? (Credential access decided in [ADR 0017](../ADRs/0017-credential-isolation-for-sandboxed-agents.md), with [ADR 0092](../ADRs/0092-openai-wif-credential-delivery.md) as the first inference credential delivered entirely through a gateway provider, and [ADR 0137](../ADRs/0137-inference-gateway-credential-route.md) routing inference through an LLM gateway that accepts the job's OIDC token so the forge stores no reusable provider key ([ADR 0138](../ADRs/0138-inference-gateway-api-key-credential-mode.md) adds an opt-in API-key mode for gateways that cannot trust forge OIDC, at the cost of a long-lived secret); tool access restrictions decided in [ADR 0027](../ADRs/0027-allowed-and-disallowed-tools-for-agents.md); cross-org public GitHub Packages access decided in [ADR 0114](../ADRs/0114-github-packages-via-host-bound-workflow-token-provider.md); user secrets for host-side scripts on GitHub decided in [ADR 0136](../ADRs/0136-runner-secrets-through-one-stored-secret.md); the sandbox environment the runner provides — which env vars it injects, per runtime, and which keys it reserves from harness override — is now published as a generated, machine-checkable contract ([ADR 0146](../ADRs/0146-sandbox-environment-contract-manifest.md)); other resource access remains open.) - Do we need a dedicated “agent runner” image or environment with a known, auditable tool set? - ~~How do we preserve end-to-end traceability for event-driven agent dispatch in GitHub Actions?~~ Decided in [ADR 0041](../ADRs/0041-synchronous-workflow-call-event-dispatch.md) (synchronous `workflow_call` dispatch for the event path). -- ~~How do CI wiring and recurring discovery support entity-bound resident runs without introducing a separate agent coordinator?~~ Decided in [ADR 0079](../ADRs/0079-bind-entity-execution-through-named-sources.md): shared binding/admission in Fullsend, execution in CI, and verified discovery readiness for the effective plan under ADR 0144's lifecycle rules. +- How do CI wiring and recurring discovery support entity-bound resident runs + without introducing a separate agent coordinator? The design direction is + decided in [ADR 0079](../ADRs/0079-bind-entity-execution-through-named-sources.md): + shared binding/admission in fullsend, execution in CI, and verified discovery + readiness under ADR 0144. Required contracts, adapters, and rollout remain open. - How do we compare 3rd party vs internal vs build-our-own on concrete criteria: cost, time to first agent, compliance, and alignment with our security and coordination model? - Who in the org would own and operate agent infrastructure, and how does that align with existing platform or CI ownership? [ADR 0123](../ADRs/0123-tenant-configuration-from-repos-yaml.md) establishes the existing `repos.yaml` v1 format for tenant configuration in a possible centralized offering; the source of truth, service, operational ownership, and infrastructure remain open. - For cluster-hosted agents, how do we preserve an acceptable inner loop (fast local or sandboxed tests) without granting dangerous privilege, and how do we avoid paying for idle capacity while work waits on humans? (The poll/run process lifecycle and bound-run idle exit are decided in [ADR 0144](../ADRs/0144-reuse-poll-and-entity-bound-run-processes.md); capacity policy and the inner loop remain open.) From 31c0a9fc0073d73bf6b1714f910dba118004d4ad Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Mon, 9 Nov 2026 00:20:25 +0200 Subject: [PATCH 006/208] docs(adr): default native source repository scope Signed-off-by: Barak Korren Assisted-by: Codex --- .../entity-source-configuration/v1/README.md | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/docs/normative/entity-source-configuration/v1/README.md b/docs/normative/entity-source-configuration/v1/README.md index 4c7fbec6d2..8d6af72239 100644 --- a/docs/normative/entity-source-configuration/v1/README.md +++ b/docs/normative/entity-source-configuration/v1/README.md @@ -143,16 +143,16 @@ adapter's supported kinds and the query's selection are checked against each consuming harness slot's kind. The same source may serve differently typed slots. The planner enumerates only the kinds needed by active primary-source bindings. An active forge source's `repositories` list scopes it to explicit canonical -repository paths. Omission is permitted only for the reserved source whose -provider matches the configuration origin. In that case it means the clone's -repository path on the same-named provider-default connection, including when +repository paths. If omitted, the scope defaults to the clone's repository path +when the source resolves to the configuration origin provider's provider-default +connection. This applies to reserved and ordinary source names, including when that connection uses an explicit `base_url` for another instance. All other -active forge sources, including reserved names for non-origin providers, MUST -specify `repositories`. An unbound reserved entry for another provider is an -inert preset and may omit its connection and repository scope until it is bound. -An explicit list selects those paths; it does not claim they are the same -canonical repository as the clone. A Jira source MUST specify a nonempty -`projects` list. +active forge sources, including those using another provider-default or named +connection, MUST specify `repositories`. An unbound reserved entry for another +provider is an inert preset and may omit its connection and repository scope +until it is bound. An explicit list selects those paths; it does not claim they +are the same canonical repository as the clone. A Jira source MUST specify a +nonempty `projects` list. Source scopes MUST resolve to canonical provider identities before use. Configuration authorizes a source scope, not an arbitrary target code repository. @@ -241,9 +241,10 @@ connection with an all-state query and `discovery: true`: an empty query for GitHub, or `all` for GitLab. If present, its `query` and optional `discovery` override those defaults under ordinary whole-entry layering. Its repository scope defaults to the clone's path on the same-named connection, including when -that connection's endpoint is overridden; an explicit `repositories` list -selects another path. Other named sources can select additional instances or -scopes. +that connection's endpoint is overridden. The same repository-path default +applies to any active forge source that resolves to this connection; an explicit +`repositories` list selects another path. Other named sources can select +additional instances or scopes. Provider names MAY also appear explicitly in `agents[].entities` lists and in standalone source selection. For the origin's provider, `[github]` (for example) @@ -353,8 +354,10 @@ entity_filters: ``` The effective query requires both expressions inside the configured repository -and work-item guard. A review harness could instead use a change-proposal -source with `is:open draft:false base:main -label:blocked`. +and work-item guard. `actionable_work` omits `repositories` because it resolves +to the origin's provider-default `github` connection, so its scope is the +configuration repository. A review harness could instead use a +change-proposal source with `is:open draft:false base:main -label:blocked`. Parse and validate this subset before provider submission; do not pass unknown syntax through as free text. Reject bare text, `in:`, general `NOT`, relative @@ -760,10 +763,12 @@ Implementations MUST cover at least these observable cases: only their same-named provider connection. For a GitHub-origin clone, `entity_sources.github` may omit both `connection` and `repositories`; it uses `connections.github` and the clone path even when that connection points to - GitHub Enterprise. `entity_sources.github.connection: enterprise` fails - validation. A reserved source for another provider must specify its repository - scope. Untrusted layers cannot change endpoints, and a new endpoint requires a - separately provisioned credential binding. + GitHub Enterprise. Any other active forge source resolving to + `connections.github`, such as `actionable_work`, may also omit `repositories`. + A source using an external or separately named connection must specify its + repository scope. `entity_sources.github.connection: enterprise` fails + validation. Untrusted layers cannot change endpoints, and a new endpoint + requires a separately provisioned credential binding. - Native resolution uses the clone's provider independently of Kubernetes, GitHub Actions, or GitLab CI execution. Its provider-default connection can override the instance. Explicit matching-provider aliases deduplicate with From 8671194a7bcd37a67cffab0c32be3b148dc53093 Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Tue, 10 Nov 2026 12:06:47 +0200 Subject: [PATCH 007/208] docs(adr): define repository-owned recovery journals Signed-off-by: eshulman2 --- ...ugh-repository-owned-operation-journals.md | 102 ++++++++++++++++++ docs/architecture.md | 9 +- docs/problems/agent-architecture.md | 6 ++ docs/problems/agent-infrastructure.md | 6 ++ docs/problems/cross-run-memory.md | 5 + docs/problems/durable-work-recovery.md | 88 +++++++++++++++ docs/problems/operational-observability.md | 5 + 7 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md create mode 100644 docs/problems/durable-work-recovery.md diff --git a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md new file mode 100644 index 0000000000..159599b9be --- /dev/null +++ b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md @@ -0,0 +1,102 @@ +--- +title: "165. Recover work through repository-owned operation journals" +status: Accepted +relates_to: + - durable-work-recovery + - agent-architecture + - agent-infrastructure +topics: + - coordination + - recovery +--- + +# 165. Recover work through repository-owned operation journals + +Date: 2026-11-10 + +## Status + +Accepted + +## Context + +Per-subject serialization ([ADR 0106](0106-serialize-agent-runs-and-coalesce-subsequent-events.md)) +and occurrence-aware poll state +([ADR 0132](0132-occurrence-aware-shared-poller-state.md)) reduce duplicate +dispatch. They do not reserve an operation across scheduling, worker failure +and external publication. Runtime workflow packaging in +[#8225](https://github.com/fullsend-ai/fullsend/pull/8225) addresses another +boundary: delivering a sequence to an agent runtime. + +[Durable work recovery](../problems/durable-work-recovery.md) describes the +failure cases. This ADR aims to keep admitted work recoverable across hosts +without making a model or a central daemon the coordination authority. + +## Options + +Integration-owned databases offer flexibility but repeat the same recovery +controls. A mandatory workflow service adds an operated dependency. A +repository-owned journal reuses forge state and existing schedulers, at the +cost of conditional writes and explicit reconciliation. + +## Decision + +Fullsend adopts repository-owned operation journals to recover work across +dispatch, execution and publication. + +The trusted host records work before dispatch in repository-scoped forge +storage with integrity checks and compare-and-swap updates. The journal +retains stable operation identities and persistent work bounds. Multi-target +dispatch and collection are tracked separately in +[#9260](https://github.com/fullsend-ai/fullsend/issues/9260). Attempts retain +their own identity, source/input revisions and +scheduler/run identifiers. Scheduling acceptance, worker completion and each +publication effect have separate receipts. Loss of an acknowledgement leaves +recoverable pending work rather than advancing a completion checkpoint. + +Short-lived reconcilers use leases and monotonically increasing ownership +generations. Every result acceptance, state transition and publication +admission checks the current generation and plan. A timed-out or superseded +worker cannot authorize a new effect. A publication admitted before ownership +loss remains an in-flight effect to reconcile; expiry cannot revoke a request +already accepted by an external service. Remote writes remain in trusted host +adapters, outside worker sandboxes. + +Publication adapters persist intent before writing, use a stable external +operation marker, and reconcile ambiguous outcomes before retrying. An +eventually consistent search returning no match is not proof a create failed. +If the adapter cannot establish the outcome, it holds publication for operator +resolution. It can retry publication from retained validated evidence without +rerunning inference, subject to current authorization, source and policy. +Missing, exhausted or unresolved required children remain visible and cannot +imply completion. A configured domain adapter may request investigation after +failure, but cannot turn that request into a successful worker assessment. + +This is a deterministic host capability. It adds neither a coordinator agent +nor authority from journal contents. Existing actor, entity, disclosure and +repository gates still apply. Domain mapping, assessment semantics and ticket +rendering remain adapters. Journal records contain bounded identities, digests +and receipts, not raw private prompts or credentials. Artifact publication +policy still applies. Journal integrity failure stops scheduling and +publication; it does not silently reset state and repeat work. + +## Forge scope + +The contract applies to GitHub, GitLab and Forgejo target repositories. +Each backend must demonstrate conditional updates and the same recovery +tests before enablement. Initial implementation may enable GitHub alone; +GitLab and Forgejo remain disabled until their adapters conform. Jira may be +a source or publication destination; its unconditional issue-property writes +do not satisfy the journal's compare-and-swap requirement. + +## Consequences + +- Recovery can resume scheduling or publication without keeping a host or + model session alive. +- Existing forge storage and CI schedules remain the coordination substrate. +- Backend integrity, ownership and ambiguous-write tests become enablement + gates; delivery is not claimed to be exactly once. +- Adopters must define target identity and completion rules while Fullsend + enforces the shared recovery boundary. +- Journal layout, credentials, retention and adapter implementation require + follow-up work before this capability is available. diff --git a/docs/architecture.md b/docs/architecture.md index b23239a26e..34378bb25a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -618,6 +618,12 @@ The existing design principle is that [the repo is the coordinator](problems/age [#8418](https://github.com/fullsend-ai/fullsend/issues/8418) and [#8421](https://github.com/fullsend-ai/fullsend/issues/8421). +- Decided, not yet implemented: repository-owned operation journals retain + separate dispatch, execution and publication receipts. Conditional state + updates and ownership generations support cross-host recovery while domain + adapters retain operation and completion semantics + ([ADR 0165](ADRs/0165-recover-work-through-repository-owned-operation-journals.md)). + **Open questions:** - What provider query plans can support entity-first evaluation over the @@ -632,7 +638,8 @@ The existing design principle is that [the repo is the coordinator](problems/age - Is GitHub's event system sufficient for forge-native duplicate protection, or do we need additional coordination beyond label/state conventions and agent idempotency? (Jira polling per ADR 0063 uses entity-property locks and runner - lock refresh; ADR 0098 does not resolve this question.) + lock refresh; ADR 0165 chooses an operation journal for recoverable effects, + while adapter implementation and external-system guarantees remain open.) - How does work assignment interact with the backlog/priority agent described in [agent-architecture.md](problems/agent-architecture.md)? - How should explicit cancellation, retry, and reassignment interact with the automatic event-coalescing policy in diff --git a/docs/problems/agent-architecture.md b/docs/problems/agent-architecture.md index 80d7f4d206..6ac93af766 100644 --- a/docs/problems/agent-architecture.md +++ b/docs/problems/agent-architecture.md @@ -178,6 +178,12 @@ This principle aligns with what Yegge's Gas City project calls "Zero Framework C [OpenAI Symphony](../landscape.md#openai-symphony) is the other useful contrast: a long-running central daemon that owns scheduling state, candidate selection, and retry. Where Gas City puts a controller on the path but forbids it from containing judgment, Symphony's orchestrator visibly contains it (priority sort, blocker rules, reconciliation). Fullsend can borrow Symphony's workspace safety invariants and continuation-turn semantics without adopting the daemon. +Cross-host scheduling and partial external writes need deterministic recovery +without adding a coordinator agent; see +[durable work recovery](durable-work-recovery.md). +[ADR 0165](../ADRs/0165-recover-work-through-repository-owned-operation-journals.md) +chooses repository-owned operation journals; implementation remains open. + ### How agents communicate Agents interact through GitHub's existing mechanisms: diff --git a/docs/problems/agent-infrastructure.md b/docs/problems/agent-infrastructure.md index ef5cfc305d..a0f66d41da 100644 --- a/docs/problems/agent-infrastructure.md +++ b/docs/problems/agent-infrastructure.md @@ -120,6 +120,12 @@ Many fullsend scenarios skew toward **ephemeral, task-scoped** execution (triage - **Governance** — Policy may be applied at runtime by agents reading from a policy repo; infrastructure determines where that runtime runs and how it accesses policy. - **Repo readiness** — Repos need reliable CI and signals; agent infrastructure may consume or depend on the same CI (e.g. for “run tests” or “run linters”) and should not conflict with it. Headless runtimes amplify **feedback latency** and **workspace handoff** costs when CI is the only execution path. +Restarting workers also needs durable ownership and reconciliation of external +effects; see [durable work recovery](durable-work-recovery.md). +[ADR 0165](../ADRs/0165-recover-work-through-repository-owned-operation-journals.md) +chooses repository-owned journals and short-lived reconcilers; backend +implementation and operational acceptance remain open. + ## Open questions - What is the right level of isolation per agent (process, container, microVM, separate cluster)? diff --git a/docs/problems/cross-run-memory.md b/docs/problems/cross-run-memory.md index b3bbb803ce..fca00bda6d 100644 --- a/docs/problems/cross-run-memory.md +++ b/docs/problems/cross-run-memory.md @@ -86,6 +86,11 @@ These splits suggest that "memory" may not be one feature. It may be several fee Cross-run memory is one piece of a broader question: what happens when an agent fails? The memory problem asks how agents learn from prior failures. The recovery problem asks what the system does immediately after a failure, before any learning occurs. +Recovering scheduling ownership and ambiguous external writes is a separate +mechanical problem; see [durable work recovery](durable-work-recovery.md). +Its operation journal retains attempts and work bounds without deciding +whether another model approach is likely to succeed. + ### Retry vs. escalate When a run fails (CI failure, merge conflict, model refusal, timeout), the system must decide: retry the same approach, try a different approach, or escalate to a human. Execution limits bound how much work can occur, but reaching a limit does not establish whether another attempt is likely to produce a different outcome. diff --git a/docs/problems/durable-work-recovery.md b/docs/problems/durable-work-recovery.md new file mode 100644 index 0000000000..724fea2f77 --- /dev/null +++ b/docs/problems/durable-work-recovery.md @@ -0,0 +1,88 @@ +--- +title: Durable work recovery +--- + +# Durable work recovery + +A job can disappear after discovery, finish after its caller stops, or publish +an external change before its acknowledgement is saved. A successful model +invocation does not answer whether the requested work was scheduled, which +attempt owns it, or whether publication must be retried. + +The [repository coordination model](agent-architecture.md#interaction-model-the-repo-as-coordinator) +keeps authority in repository-visible controls. Recovery must preserve that +boundary. It needs deterministic bookkeeping, rather than an agent deciding +which other agents should run. The +[infrastructure discussion](agent-infrastructure.md) also separates execution +capacity from waiting for people or external systems. + +## Failure boundaries + +- A dispatcher stops after a remote scheduler accepts a request but before it + records the scheduler's run identifier. +- Two hosts discover the same operation while neither has reserved it. +- A worker's lease expires; its replacement starts while the old worker is + still running. +- A worker saves valid evidence, but its publication request times out after + the external system creates the issue or comment. +- One required child never returns while other children succeed. +- Source, authorization or a target plan changes while work is queued. + +Serialization for a harness and subject reduces overlap. It does not make +dispatch, execution and external writes one transaction. A source checkpoint +or the absence of a running CI job cannot prove completion. Operators need to +distinguish these conditions from ordinary agent failures; see +[operational observability](operational-observability.md#what-just-happened). + +Persistent attempt bounds supply recovery mechanics, while +[cross-run escalation](cross-run-memory.md#error-recovery-and-retry-mechanics) +also needs failure interpretation and policy. A journal does not decide whether +a different model strategy is likely to succeed. + +## Options and trade-offs + +### Let each integration own its recovery + +An adapter can maintain a database and reconcile its own jobs and external +effects. This is flexible and avoids a new platform contract. Each adapter +must also implement authorization rechecks, duplicate prevention, restart +handling and publication recovery. Guarantees can differ across workflows. + +### Extend repository-owned state + +A repository-scoped journal can use conditional forge writes and short-lived +reconcilers. Existing schedulers still run individual workers. This fits the +repository coordination model and avoids a required central service. It needs +explicit trust, retention, conflict, lease and external-effect protocols; +eventual-consistency searches cannot establish that an ambiguous write failed. + +### Delegate to a durable workflow service + +A service can supply timers, retries and ownership. It introduces another +operated component and trust boundary. Its scheduler guarantees still do not +make a remote issue creation atomic or authorize a retry after scope changes. + +## Decision and acceptance + +[ADR 0165](../ADRs/0165-recover-work-through-repository-owned-operation-journals.md) +chooses a repository-owned journal. Its implementation remains separate from +the decision. A local database test is not distributed acceptance. + +Fault tests must stop both sides of each handoff, overlap reconcilers, expire +ownership while a worker is still alive, and supersede a plan before +publication. A remote write that succeeded before its acknowledgement was +lost must be reconciled without rerunning inference or blindly repeating the +write. Every required target remains accounted for, including exhausted or +missing attempts. A domain adapter may publish an investigation request when +analysis fails; that request is not an assessment or permission to remediate. + +## Open questions + +- Which journal layout, signing rules, retention and compaction bounds meet + the conditional-write and integrity requirements on each forge? +- Which existing scheduler APIs can reconcile accepted-but-unacknowledged + requests by stable operation identity? +- Which publication adapters can safely prove a write absent, and which must + retain an ambiguous operation for human reconciliation? +- How should an operator repair corrupted or inaccessible state without + discarding accepted work or permitting stale workers to publish? diff --git a/docs/problems/operational-observability.md b/docs/problems/operational-observability.md index 20f61bd7df..9afb906e1c 100644 --- a/docs/problems/operational-observability.md +++ b/docs/problems/operational-observability.md @@ -47,6 +47,11 @@ When something goes wrong — a bad merge, a missed vulnerability, an unexpected This is the debugging use case. It requires structured traces of individual agent runs that can be correlated into end-to-end workflows. The trace is the unit of debugging — when something goes wrong, you pull the trace and read it. +A trace alone cannot establish whether an external write succeeded after its +acknowledgement was lost. [Durable work recovery](durable-work-recovery.md) +separates scheduling, execution and publication receipts so an operator can +identify which effect still needs reconciliation. + ### Is the system getting better or worse? Beyond individual incidents, operators need trend-level visibility: From b77dc71b1fa85c8aa0f247f3ab22758a5941c508 Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Wed, 11 Nov 2026 16:53:59 +0200 Subject: [PATCH 008/208] docs(adr): place saga journal in the control repository Signed-off-by: eshulman2 --- ...ugh-repository-owned-operation-journals.md | 133 +++++++++++++++--- docs/architecture.md | 11 +- docs/problems/durable-work-recovery.md | 31 +++- 3 files changed, 144 insertions(+), 31 deletions(-) diff --git a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md index 159599b9be..fa332e11cf 100644 --- a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md +++ b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md @@ -41,11 +41,19 @@ cost of conditional writes and explicit reconciliation. ## Decision -Fullsend adopts repository-owned operation journals to recover work across -dispatch, execution and publication. - -The trusted host records work before dispatch in repository-scoped forge -storage with integrity checks and compare-and-swap updates. The journal +Fullsend adopts a durable saga journal stored as versioned JSON files in the +control repository. A saga records progress across separate external actions +and recovers each step without claiming one atomic transaction across services. +It covers admission, target resolution, dispatch, execution, publication and +accounting for every required target. Multi-branch assessment remains in scope. + +The initial deployment stores the journal in the GitLab control repository +that hosts Fullsend execution. That repository may assess and fix code hosted +on GitHub, GitLab or Forgejo, and publish findings to Jira. Source repositories +need no journal branch or journal-write credential. + +The trusted host records work before dispatch in the control repository, +with integrity checks and compare-and-swap updates. The journal retains stable operation identities and persistent work bounds. Multi-target dispatch and collection are tracked separately in [#9260](https://github.com/fullsend-ai/fullsend/issues/9260). Attempts retain @@ -80,23 +88,108 @@ and receipts, not raw private prompts or credentials. Artifact publication policy still applies. Journal integrity failure stops scheduling and publication; it does not silently reset state and repeat work. +## Storage and writer boundary + +Use a dedicated protected journal branch in the control repository, separate +from workflow configuration and source branches. Bounded, schema-versioned +JSON records identify the saga, required targets, plan and input digests, +attempts, ownership generations, effect intents and receipts. Large validated +outputs remain retained artifacts referenced by immutable identity and digest. +Journal commits must not recursively trigger ordinary agent pipelines. + +Only an explicitly authorized trusted host identity writes the journal. +Read-only assessment workers receive admitted context without journal-write +credentials. Source-read, code-publication and journal-write permissions are +separate; a source checkout does not grant control-repository access. The +implementation must define credential routing and protected-branch permissions +before enablement. GitLab writer selection must use the trusted registered-role +contract; an administrator may register a dedicated responsibility identity. +This decision does not expand the built-in Analyst role's repository-write +permissions. Editable tracker properties are not ownership authority. + +A state change commits against the exact journal revision read by the writer. +The backend must reject a competing update. On conflict, reload state and +re-evaluate ownership, inputs and the proposed transition. Automatically +merging JSON, force-pushing, or recreating a missing journal branch cannot +resolve an ownership conflict. The GitLab implementation must demonstrate +conditional updates of the complete transition and integrity under concurrent +writers. A per-file check alone is insufficient for a transition that changes +several records. GitHub and Forgejo storage adapters follow the same contract. + +## Script consumption and recovery + +Expose shared trusted journal operations to pre-scripts, post-scripts and +short-lived scheduled reconcilers. These operations claim work, record intent, +accept input-bound evidence and confirm an effect through the same ownership +and transition checks. Consumers can condition actions on durable saga state +without implementing separate lease or receipt rules in each script. These +are capability requirements, not existing CLI commands or harness fields. + +Persist an intent before each external action and its receipt after verified +acceptance. Retain validated worker evidence before publication. A later +invocation can retry publication without inference, subject to current inputs, +authorization and unresolved-effect checks. Independent publish-only recovery +can be delivered without waiting for the complete saga implementation. + +A CI finalizer, such as GitLab's `after_script`, makes a best-effort final +checkpoint from verified local evidence. It cannot promise a write after runner +loss, hard termination, timeout or journal outage. It must not mark an operation +complete merely because the job exited. Scheduled reconciliation reads pending +intents and receipts even when the finalizer never ran. Missing acknowledgements +remain unresolved until external acceptance can be established. + +Each required branch has independent attempts and receipts. A missing result, +exhausted retry or unresolved publication keeps that target visible. Domain +adapters define cancellation or compensating actions where appropriate, and +forward recovery where an external action cannot safely be undone. Recording a +compensation does not erase its original effect or authorize automatic issue +closure, deletion or code rollback. + +## Entity state and journal state + +[ADR 0098](0098-entity-first-harness-evaluation.md) and +[ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md) keep business and +handled state on the entity. Trackers retain applicability, human workflow +status and validated assessment handoffs. Entity-first discovery remains +responsible for finding eligible work, including a lost trigger that never +admitted an operation. A journal cannot recover work it never recorded. + +The journal records mechanical progress of admitted work: ownership, attempts, +step intents, input bindings and scheduling or publication receipts. It adds +no independent revision-deduplication or business handled-state gate. A bound +receipt must still pass the current entity and policy checks before use. +Tracker-first branch investigations and their assessment semantics remain the +multi-target adapter's decision; journal storage does not require one Jira +issue per journal record. + ## Forge scope -The contract applies to GitHub, GitLab and Forgejo target repositories. -Each backend must demonstrate conditional updates and the same recovery -tests before enablement. Initial implementation may enable GitHub alone; -GitLab and Forgejo remain disabled until their adapters conform. Jira may be -a source or publication destination; its unconditional issue-property writes -do not satisfy the journal's compare-and-swap requirement. +Execution host, journal storage, source forge and tracker are independent +bindings. The initial journal backend is the GitLab control repository; a +GitHub source repository or Jira tracker does not need a matching journal +backend. GitLab storage must pass the recovery acceptance tests before use. +GitHub and Forgejo control-repository storage remain disabled until their +adapters pass the same tests. Source and publication adapters retain their own +authorization and enablement requirements. + +The capability contract covers GitHub, GitLab and Forgejo without requiring +every deployment to use the source forge for storage. Jira may be a source or +publication destination. Its unconditional issue-property updates do not +satisfy this journal's compare-and-swap requirement. ## Consequences -- Recovery can resume scheduling or publication without keeping a host or - model session alive. -- Existing forge storage and CI schedules remain the coordination substrate. -- Backend integrity, ownership and ambiguous-write tests become enablement - gates; delivery is not claimed to be exactly once. -- Adopters must define target identity and completion rules while Fullsend - enforces the shared recovery boundary. -- Journal layout, credentials, retention and adapter implementation require - follow-up work before this capability is available. +- The full saga can recover individual branches and external effects without + keeping a host or model session alive. +- JSON history in the control repository supplies inspectable durable state; + it adds commit volume, retention and compaction responsibilities. +- A GitLab control repository can coordinate GitHub source and Jira trackers + without a journal in each source repository. +- Shared script operations and periodic reconciliation are both required; + best-effort finalization alone cannot provide crash recovery. +- Conditional updates, integrity, ownership and ambiguous-write tests are + enablement gates; delivery is not claimed to be exactly once. +- Domain adapters retain target identity, completion and compensation rules. + Tracker-state reconciliation and publish-only retry can ship independently. +- JSON layout, credential provisioning, retention and adapter implementation + require follow-up work before this capability is available. diff --git a/docs/architecture.md b/docs/architecture.md index 34378bb25a..c498b0758f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -618,10 +618,13 @@ The existing design principle is that [the repo is the coordinator](problems/age [#8418](https://github.com/fullsend-ai/fullsend/issues/8418) and [#8421](https://github.com/fullsend-ai/fullsend/issues/8421). -- Decided, not yet implemented: repository-owned operation journals retain - separate dispatch, execution and publication receipts. Conditional state - updates and ownership generations support cross-host recovery while domain - adapters retain operation and completion semantics +- Decided, not yet implemented: a saga journal stores versioned JSON in the + control repository, initially on GitLab, independently of the source forge + and tracker. Shared pre/post-script operations and scheduled reconciliation + retain separate dispatch, execution and publication receipts for each target. + Conditional updates and ownership generations support cross-host recovery; + CI finalization provides only a best-effort checkpoint. Domain adapters + retain operation, completion and compensation semantics ([ADR 0165](ADRs/0165-recover-work-through-repository-owned-operation-journals.md)). **Open questions:** diff --git a/docs/problems/durable-work-recovery.md b/docs/problems/durable-work-recovery.md index 724fea2f77..567d255217 100644 --- a/docs/problems/durable-work-recovery.md +++ b/docs/problems/durable-work-recovery.md @@ -50,8 +50,9 @@ handling and publication recovery. Guarantees can differ across workflows. ### Extend repository-owned state -A repository-scoped journal can use conditional forge writes and short-lived -reconcilers. Existing schedulers still run individual workers. This fits the +A journal in a control repository can use versioned JSON files, conditional +forge writes and short-lived reconcilers. Storage need not share the forge of +the source code or tracker. Existing schedulers still run individual workers. This fits the repository coordination model and avoids a required central service. It needs explicit trust, retention, conflict, lease and external-effect protocols; eventual-consistency searches cannot establish that an ambiguous write failed. @@ -65,12 +66,24 @@ make a remote issue creation atomic or authorize a retry after scope changes. ## Decision and acceptance [ADR 0165](../ADRs/0165-recover-work-through-repository-owned-operation-journals.md) -chooses a repository-owned journal. Its implementation remains separate from -the decision. A local database test is not distributed acceptance. +chooses JSON journal files in the control repository, initially hosted on +GitLab. The journal covers the full saga and each required branch, while +source repositories and trackers can use other providers. Shared trusted +operations let pre/post scripts and scheduled reconcilers consume the same +state. CI finalization is a best-effort checkpoint, not the recovery guarantee. +Its implementation remains separate from the decision. A local database test is not distributed acceptance. + +Entity-first discovery must also find eligible work whose trigger was lost +before admission. Trackers retain business and handled state; the journal +records mechanical progress after admission. Publish-only retry from retained +validated evidence can be implemented independently of the complete journal. Fault tests must stop both sides of each handoff, overlap reconcilers, expire ownership while a worker is still alive, and supersede a plan before -publication. A remote write that succeeded before its acknowledgement was +publication. Kill a runner before its finalizer, interrupt journal writes and +race multi-record updates; only a valid conditional transition may win. A +GitLab control repository must demonstrate recovery with GitHub source and +Jira publication. Journal writes must not trigger recursive agent runs. A remote write that succeeded before its acknowledgement was lost must be reconciled without rerunning inference or blindly repeating the write. Every required target remains accounted for, including exhausted or missing attempts. A domain adapter may publish an investigation request when @@ -78,8 +91,12 @@ analysis fails; that request is not an assessment or permission to remediate. ## Open questions -- Which journal layout, signing rules, retention and compaction bounds meet - the conditional-write and integrity requirements on each forge? +- Which bounded JSON layout, integrity checks, retention and compaction rules + preserve history and conditional transitions in the control repository? +- Which trusted host identity writes the protected GitLab journal branch, and + how are its credentials kept separate from read-only assessment workers? +- Which shared script interface and reconciliation schedule expose the saga + without making CI finalizers a prerequisite for recovery? - Which existing scheduler APIs can reconcile accepted-but-unacknowledged requests by stable operation identity? - Which publication adapters can safely prove a write absent, and which must From e71d3fee2561d81954d7461ec79bcf9d88d68a39 Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Wed, 11 Nov 2026 18:10:27 +0200 Subject: [PATCH 009/208] docs(adr): separate recovery decision from implementation detail Signed-off-by: eshulman2 --- ...ugh-repository-owned-operation-journals.md | 199 ++++++------------ 1 file changed, 62 insertions(+), 137 deletions(-) diff --git a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md index fa332e11cf..5fdc6ddfbf 100644 --- a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md +++ b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md @@ -43,153 +43,78 @@ cost of conditional writes and explicit reconciliation. Fullsend adopts a durable saga journal stored as versioned JSON files in the control repository. A saga records progress across separate external actions -and recovers each step without claiming one atomic transaction across services. -It covers admission, target resolution, dispatch, execution, publication and -accounting for every required target. Multi-branch assessment remains in scope. - -The initial deployment stores the journal in the GitLab control repository -that hosts Fullsend execution. That repository may assess and fix code hosted -on GitHub, GitLab or Forgejo, and publish findings to Jira. Source repositories -need no journal branch or journal-write credential. - -The trusted host records work before dispatch in the control repository, -with integrity checks and compare-and-swap updates. The journal -retains stable operation identities and persistent work bounds. Multi-target -dispatch and collection are tracked separately in -[#9260](https://github.com/fullsend-ai/fullsend/issues/9260). Attempts retain -their own identity, source/input revisions and -scheduler/run identifiers. Scheduling acceptance, worker completion and each -publication effect have separate receipts. Loss of an acknowledgement leaves -recoverable pending work rather than advancing a completion checkpoint. - -Short-lived reconcilers use leases and monotonically increasing ownership -generations. Every result acceptance, state transition and publication -admission checks the current generation and plan. A timed-out or superseded -worker cannot authorize a new effect. A publication admitted before ownership -loss remains an in-flight effect to reconcile; expiry cannot revoke a request -already accepted by an external service. Remote writes remain in trusted host -adapters, outside worker sandboxes. - -Publication adapters persist intent before writing, use a stable external -operation marker, and reconcile ambiguous outcomes before retrying. An -eventually consistent search returning no match is not proof a create failed. -If the adapter cannot establish the outcome, it holds publication for operator -resolution. It can retry publication from retained validated evidence without -rerunning inference, subject to current authorization, source and policy. -Missing, exhausted or unresolved required children remain visible and cannot -imply completion. A configured domain adapter may request investigation after -failure, but cannot turn that request into a successful worker assessment. - -This is a deterministic host capability. It adds neither a coordinator agent -nor authority from journal contents. Existing actor, entity, disclosure and -repository gates still apply. Domain mapping, assessment semantics and ticket -rendering remain adapters. Journal records contain bounded identities, digests -and receipts, not raw private prompts or credentials. Artifact publication -policy still applies. Journal integrity failure stops scheduling and -publication; it does not silently reset state and repeat work. - -## Storage and writer boundary - -Use a dedicated protected journal branch in the control repository, separate -from workflow configuration and source branches. Bounded, schema-versioned -JSON records identify the saga, required targets, plan and input digests, -attempts, ownership generations, effect intents and receipts. Large validated -outputs remain retained artifacts referenced by immutable identity and digest. -Journal commits must not recursively trigger ordinary agent pipelines. - -Only an explicitly authorized trusted host identity writes the journal. -Read-only assessment workers receive admitted context without journal-write -credentials. Source-read, code-publication and journal-write permissions are -separate; a source checkout does not grant control-repository access. The -implementation must define credential routing and protected-branch permissions -before enablement. GitLab writer selection must use the trusted registered-role -contract; an administrator may register a dedicated responsibility identity. -This decision does not expand the built-in Analyst role's repository-write -permissions. Editable tracker properties are not ownership authority. - -A state change commits against the exact journal revision read by the writer. -The backend must reject a competing update. On conflict, reload state and -re-evaluate ownership, inputs and the proposed transition. Automatically -merging JSON, force-pushing, or recreating a missing journal branch cannot -resolve an ownership conflict. The GitLab implementation must demonstrate -conditional updates of the complete transition and integrity under concurrent -writers. A per-file check alone is insufficient for a transition that changes -several records. GitHub and Forgejo storage adapters follow the same contract. - -## Script consumption and recovery - -Expose shared trusted journal operations to pre-scripts, post-scripts and -short-lived scheduled reconcilers. These operations claim work, record intent, -accept input-bound evidence and confirm an effect through the same ownership -and transition checks. Consumers can condition actions on durable saga state -without implementing separate lease or receipt rules in each script. These -are capability requirements, not existing CLI commands or harness fields. - -Persist an intent before each external action and its receipt after verified -acceptance. Retain validated worker evidence before publication. A later -invocation can retry publication without inference, subject to current inputs, -authorization and unresolved-effect checks. Independent publish-only recovery -can be delivered without waiting for the complete saga implementation. - -A CI finalizer, such as GitLab's `after_script`, makes a best-effort final -checkpoint from verified local evidence. It cannot promise a write after runner -loss, hard termination, timeout or journal outage. It must not mark an operation -complete merely because the job exited. Scheduled reconciliation reads pending -intents and receipts even when the finalizer never ran. Missing acknowledgements -remain unresolved until external acceptance can be established. - -Each required branch has independent attempts and receipts. A missing result, -exhausted retry or unresolved publication keeps that target visible. Domain -adapters define cancellation or compensating actions where appropriate, and -forward recovery where an external action cannot safely be undone. Recording a -compensation does not erase its original effect or authorize automatic issue -closure, deletion or code rollback. +and recovers individual steps without claiming an atomic transaction across +services. It covers admission, target resolution, dispatch, execution, +publication and accounting for every required target, including multiple +branches. Domain dispatch and assessment semantics remain in adapters. + +The journal retains stable operation identities, input bindings, work bounds, +effect intents and separate scheduling, execution and publication receipts. +Conditional updates, integrity checks and ownership fencing prevent competing +or superseded workers from accepting results or admitting new effects. An +external request admitted before ownership loss remains in-flight until its +outcome is reconciled. + +Trusted host adapters persist intent before external actions and confirm +receipts after verified acceptance. They reconcile ambiguous outcomes before +retrying; an empty eventually consistent search does not prove a write failed. +Retained validated evidence permits publication recovery without repeating +inference, subject to current source, authorization and policy checks. Missing, +exhausted or unresolved targets remain visible and cannot imply completion. +Domain adapters define completion and any compensating actions. + +Shared trusted journal operations are consumable from pre/post scripts and +reconcilers. Incremental checkpoints and periodic reconciliation provide +recovery when execution stops. CI cleanup supplies a best-effort checkpoint; +it is not the recovery guarantee. This is a deterministic host capability, +not a coordinator agent. + +Only authorized trusted host code writes the journal. Assessment workers +receive admitted context without journal-write credentials. Journal state +contains bounded identities, digests and receipts; artifact publication policy +still applies. Journal contents grant no authority, and integrity failure +stops scheduling and publication rather than resetting state and repeating work. ## Entity state and journal state [ADR 0098](0098-entity-first-harness-evaluation.md) and -[ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md) keep business and -handled state on the entity. Trackers retain applicability, human workflow -status and validated assessment handoffs. Entity-first discovery remains -responsible for finding eligible work, including a lost trigger that never -admitted an operation. A journal cannot recover work it never recorded. - -The journal records mechanical progress of admitted work: ownership, attempts, -step intents, input bindings and scheduling or publication receipts. It adds -no independent revision-deduplication or business handled-state gate. A bound -receipt must still pass the current entity and policy checks before use. -Tracker-first branch investigations and their assessment semantics remain the -multi-target adapter's decision; journal storage does not require one Jira -issue per journal record. +[ADR 0144](0144-reuse-poll-and-entity-bound-run-processes.md) retain business and +handled state on the entity. Trackers hold applicability, human workflow status +and assessment handoffs. Entity-first discovery must still find eligible work +whose trigger was lost before admission; a journal cannot recover unrecorded work. + +The journal records mechanical progress of admitted work. It adds no separate +business handled-state or revision-deduplication gate. Existing actor, entity, +disclosure and repository checks remain authoritative. Journal storage does +not require one tracker per branch; tracker-first dispatch is a domain decision +tracked separately in [#9260](https://github.com/fullsend-ai/fullsend/issues/9260). ## Forge scope Execution host, journal storage, source forge and tracker are independent -bindings. The initial journal backend is the GitLab control repository; a -GitHub source repository or Jira tracker does not need a matching journal -backend. GitLab storage must pass the recovery acceptance tests before use. -GitHub and Forgejo control-repository storage remain disabled until their -adapters pass the same tests. Source and publication adapters retain their own -authorization and enablement requirements. - -The capability contract covers GitHub, GitLab and Forgejo without requiring -every deployment to use the source forge for storage. Jira may be a source or -publication destination. Its unconditional issue-property updates do not -satisfy this journal's compare-and-swap requirement. +bindings. The initial journal backend is the GitLab control repository, which +can coordinate GitHub, GitLab or Forgejo source repositories and Jira trackers. +Source repositories need no journal or journal-write credential. + +The same journal contract applies to GitHub and Forgejo control repositories; +their storage adapters require conformance before enablement. Source and +publication adapters retain their own authorization and enablement requirements. +Jira issue properties do not satisfy the journal's conditional-update contract. ## Consequences - The full saga can recover individual branches and external effects without keeping a host or model session alive. -- JSON history in the control repository supplies inspectable durable state; - it adds commit volume, retention and compaction responsibilities. -- A GitLab control repository can coordinate GitHub source and Jira trackers - without a journal in each source repository. -- Shared script operations and periodic reconciliation are both required; - best-effort finalization alone cannot provide crash recovery. -- Conditional updates, integrity, ownership and ambiguous-write tests are - enablement gates; delivery is not claimed to be exactly once. -- Domain adapters retain target identity, completion and compensation rules. - Tracker-state reconciliation and publish-only retry can ship independently. -- JSON layout, credential provisioning, retention and adapter implementation - require follow-up work before this capability is available. +- Control-repository history makes state inspectable and avoids a mandatory + central service, at the cost of commit volume, retention and compaction. +- Conditional updates, ownership fencing and ambiguous-effect reconciliation + require backend conformance; delivery is not claimed to be exactly once. +- Shared script operations and periodic reconciliation are both required. + Assessment workers retain their existing source-access boundaries. +- Tracker-state reconciliation and publish-only retry can ship independently + without narrowing the saga's scope. + +Implementation layout, script interfaces, credentials, reconciliation schedules +and detailed acceptance tests belong to +[#9253](https://github.com/fullsend-ai/fullsend/issues/9253). This ADR records +the decision; the journal capability is not yet implemented. From 7b5732ffb41c0a3cf20b7cf3ff0829e6e5afbcab Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Sun, 15 Nov 2026 19:07:30 +0200 Subject: [PATCH 010/208] docs(adr): clarify durable continuation and work reservations Explain the need for durable work state in evidence-driven workflows with bounded retries. Retain concurrency reservations until scheduler termination is reconciled, including after ownership expiry or result acceptance. Signed-off-by: eshulman2 --- ...work-through-repository-owned-operation-journals.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md index 5fdc6ddfbf..e2353b02b3 100644 --- a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md +++ b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md @@ -29,8 +29,10 @@ and external publication. Runtime workflow packaging in boundary: delivering a sequence to an agent runtime. [Durable work recovery](../problems/durable-work-recovery.md) describes the -failure cases. This ADR aims to keep admitted work recoverable across hosts -without making a model or a central daemon the coordination authority. +failure cases. Workflows such as CVE resolution need durable state to track +required work, continue after interruption and retain evidence within bounded +retries. This ADR aims to keep admitted work recoverable across hosts without +making a model or a central daemon the coordination authority. ## Options @@ -53,7 +55,9 @@ effect intents and separate scheduling, execution and publication receipts. Conditional updates, integrity checks and ownership fencing prevent competing or superseded workers from accepting results or admitting new effects. An external request admitted before ownership loss remains in-flight until its -outcome is reconciled. +outcome is reconciled. Ownership expiry, supersession or result acceptance +does not release a running attempt's concurrency reservation. Release requires +reconciled scheduler termination. Trusted host adapters persist intent before external actions and confirm receipts after verified acceptance. They reconcile ambiguous outcomes before From 1f0a3b5f659a1d95f1665e162592d24b29600b21 Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Mon, 16 Nov 2026 19:27:11 +0200 Subject: [PATCH 011/208] docs(adr): clarify workflow opt-in for journal recovery Separate explicit workflow integration from existing webhook and poll dispatch. Preserve the full recovery contract for journal-admitted work. Signed-off-by: eshulman2 --- ...ver-work-through-repository-owned-operation-journals.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md index e2353b02b3..758dbc371c 100644 --- a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md +++ b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md @@ -67,6 +67,13 @@ inference, subject to current source, authorization and policy checks. Missing, exhausted or unresolved targets remain visible and cannot imply completion. Domain adapters define completion and any compensating actions. +Journal-backed recovery is an explicit workflow opt-in. Participating workflows +integrate trusted journal operations through their pre/post scripts, agent or +harness contracts, and reconcilers. Existing webhook and poll dispatch paths do +not automatically journal every run; their selection and dispatch behavior +remains unchanged unless explicitly integrated. Once a workflow admits work to +the journal, the recovery contract covers all its required targets and effects. + Shared trusted journal operations are consumable from pre/post scripts and reconcilers. Incremental checkpoints and periodic reconciliation provide recovery when execution stops. CI cleanup supplies a best-effort checkpoint; From 26babda761a1f6226b1fc84311dc43fd3f008442 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 17 Nov 2026 16:41:36 -0500 Subject: [PATCH 012/208] docs(#6970): state the V1 or V2 gate and what the runs showed The codex row of the runtime guide named the parents fullsend allows, which is not the gate: delegation needs harness security on and a parent Codex resolves to collaboration V1 or V2 on the direct route, and a V2 parent delegates only when no child model selects V2. The row and the review/retro paragraph of the codex page now say that, and the code/fix paragraph points back to the same conditions. The run evidence said more than the runs showed. Every run exited 0, but in two of the three V1 review runs on #6970 a persona the skill selects did not run and neither result said so (#9073, #9657), and in the V2 review run on #9085 the parent dropped the challenger's kept findings after its own check of the repository (#9657). The guide's callout, the Roles row of runtimes.md, the review/retro paragraph and the runtime internals now say so, and the denied-spawn sentence names the run it happened in. The review/retro paragraph and the internals use one wording for where the V1 runs were: locally on macOS Apple Silicon, natively and in a Fedora CoreOS (aarch64) podman VM. The Platforms bullet and the Not yet exercised lead name the same two places, and the lead gives the V1 and V2 runs a sentence each. The comment above codexSubagentNote now names every agents prompt that keys on the note: the pr-review skill, the review agent and the retro agent (fullsend-ai/agents#1849, fullsend-ai/agents#1971). Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 13 +++- .../getting-started/choosing-a-runtime.md | 4 +- docs/runtimes.md | 2 +- docs/runtimes/codex.md | 62 ++++++++++++------- internal/runtime/codex_bootstrap.go | 5 +- 5 files changed, 56 insertions(+), 30 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index ffc11791f8..b58ea1a78d 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1670,9 +1670,16 @@ Two artefacts of the run are worth knowing about: and local smoke runs. - The rollout session files are archived as transcripts but not error-classified: only the tee'd `exec --json` capture yields a verdict, which is what the runner's exit-code override reads. -- Native sub-agents (ADR 0126) have completed fleet-shaped runs only locally, on macOS and on - Fedora ([#6970](https://github.com/fullsend-ai/fullsend/issues/6970)), not through the fleet - workflows. +- Native sub-agents (ADR 0126) have run fleet-shaped only locally on macOS Apple Silicon, + natively and in a Fedora CoreOS (aarch64) podman VM + ([#6970](https://github.com/fullsend-ai/fullsend/issues/6970)), not through the fleet + workflows. In two of the three `review` runs on #6970 a persona the skill selects did not run, + and neither result said so ([#9073](https://github.com/fullsend-ai/fullsend/issues/9073), + [#9657](https://github.com/fullsend-ai/fullsend/issues/9657)). On collaboration V2 (ADR 0159), + `review` and `retro` have run natively on macOS only + ([#9085](https://github.com/fullsend-ai/fullsend/issues/9085#issuecomment-6920231259)), and there the + `review` parent dropped the challenger's kept findings after its own check of the repository + ([#9657](https://github.com/fullsend-ai/fullsend/issues/9657)). ### Re-check on a `CODEX_VERSION` bump diff --git a/docs/guides/getting-started/choosing-a-runtime.md b/docs/guides/getting-started/choosing-a-runtime.md index a68016e663..bd5b56169f 100644 --- a/docs/guides/getting-started/choosing-a-runtime.md +++ b/docs/guides/getting-started/choosing-a-runtime.md @@ -4,7 +4,7 @@ sidebar_label: Choose a Runtime # Choose an agent runtime -> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`; codex runs OpenAI models through the same secretless credential path. Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. +> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`; codex runs OpenAI models through the same secretless credential path, and some of its local `review` runs have skipped one of the review's checks without saying so, or dropped findings the review had confirmed ([details](../../runtimes/codex.md#not-yet-exercised)). Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. This page explains what the choice means and where it is made. **You do not select anything on this page** — the selection happens in the next step. On GitHub, [Configuring GitHub](configuring-github.md) asks when you run `fullsend github setup` (press Enter for `claude`) or you pass `--runtime`. On GitLab, set `runtime:` in `defaults.config`, `gitlab.config`, or the repository entry's `config` in `repos.yaml` before running `fullsend repos install` (there is no install flag) — see [Configuring GitLab](configuring-gitlab.md). @@ -16,7 +16,7 @@ Fullsend supports multiple agent runtimes. A runtime is the program that runs in |---------|--------|-------------|-------------| | `claude` | **Stable (default)** | Claude Code on Vertex AI | Every production deployment — mature, full sub-agent support for `review`/`retro` | | `pi` | Experimental (enablement phase) | [Pi](https://github.com/earendil-works/pi) — Claude on Vertex by default; any provider pi supports by model name (e.g. Gemini on Vertex with the same credentials) | Opt-in pilots only; see [Runtimes](../../runtimes.md) for known constraints | -| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. Sub-agents run as [native Codex children](../../runtimes/codex.md#sub-agents) on the OpenAI parent models fullsend allows, such as `gpt-5.6-luna` but not the `gpt-6` ones; on any other model, `gateway/` ones included, the parent does the sub-agents' work itself; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | +| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. Sub-agents run as [native Codex children](../../runtimes/codex.md#sub-agents) when harness security is on (`security.enabled`, the default) and Codex resolves the parent model to [collaboration V1 or V2](../../runtimes/codex.md#sub-agents) at its pinned version, except on a `gateway/` model or, for a V2 parent, when a child model selects V2; otherwise the parent does the sub-agents' work itself; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | | `opencode` | Experimental | [OpenCode](https://opencode.ai/) — reads `AGENTS.md` natively | Opt-in read-only agents (`triage`, `prioritize`) until the security-hook adapter lands; see [OpenCode](../../runtimes/opencode.md) | ## When and how the runtime is selected diff --git a/docs/runtimes.md b/docs/runtimes.md index 130bfaef80..6de0559c5e 100644 --- a/docs/runtimes.md +++ b/docs/runtimes.md @@ -58,7 +58,7 @@ sequenceDiagram | Sub-agents | Native (`Agent` tool) | `Agent`/`Task` via a fullsend extension | Native Codex children under a runner-owned policy, for an agent whose tools include `Agent` (or that declares no `tools:`), with harness security on, on a parent model Codex resolves to collaboration V1 or V2 on the direct route ([Sub-agents](runtimes/codex.md#sub-agents)) | | Default alias models | `opus`/`sonnet`/`haiku` → `claude-*-5-5`, passed as the id; `fable` by Claude Code's own table; sub-agent frontmatter resolved by Claude Code | `opus`/`sonnet`/`haiku` → `claude-*-5-5`, `fable` → `claude-fable-5-1`, children included | Not applicable — OpenAI models only | | Fallback model chain | Alias requests retried by the runner when Vertex does not serve the model (Claude Code's own "model not available" result naming the model, or Vertex's [two 404/403 messages](runtimes/claude.md#models)): `FULLSEND_FALLBACK_MODELS`, else the alias's built-in chain (`opus` → `claude-opus-4-6`, `sonnet` → `claude-sonnet-4-6`, `haiku` → `claude-haiku-4-5`); only an explicit `FULLSEND_FALLBACK_MODELS` is also passed as `--fallback-model`, never the built-in chain; pinned ids, retargets and sub-agents fail loudly | The same chain, same provider only; sub-agent children asking for an alias use its built-in chain; pinned ids and retargets fail loudly | Ignored with a warning | -| Roles | All | All; `review`/`retro` at `--thinking medium` by default | All | +| Roles | All | All; `review`/`retro` at `--thinking medium` by default | All; some `review` runs have dropped a sub-agent the skill selects without saying so, or findings its challenger kept ([#9073](https://github.com/fullsend-ai/fullsend/issues/9073), [#9657](https://github.com/fullsend-ai/fullsend/issues/9657)) | | Effort | `--effort low..max` | `--thinking`, same levels (`high` when unset) | `model_reasoning_effort`, same levels | | Tools | Native Claude permission syntax | `--tools` (strict) + a first-token Bash allowlist | Shell + `apply_patch` only; `tools:` is recorded, not enforced (the allowlist hook is opt-in) | | Security controls | Full matrix | Full matrix; stricter on failed-call sanitizing | Full matrix; post-tool hooks detect and block but cannot rewrite output | diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index ac7eee2ec3..c2e889ccfd 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -208,8 +208,9 @@ run at once on V2; the depth is one. A runner-owned hook admits a spawn only for role with that fresh context and no model or effort override; it denies resume, V2's message and follow-up calls, Codex's built-in `explorer` and `worker`, and any spawn from a child. A denied spawn is final for that role: the parent runs that -sub-agent definition itself. In one live run the parent dropped it instead, and its result did not -say so ([#9073](https://github.com/fullsend-ai/fullsend/issues/9073)). +sub-agent definition itself. In a fleet-shaped V1 `review` run on +[#6970](https://github.com/fullsend-ai/fullsend/issues/6970) the parent dropped the denied persona +instead, and its result did not say so ([#9073](https://github.com/fullsend-ai/fullsend/issues/9073)). A spawn the hook did not admit fails the run after the fact, within the limits named in [Troubleshooting](#troubleshooting): per iteration the runner counts the spawns seen in the event stream or in the children's rollouts on disk, each child once, and @@ -346,9 +347,10 @@ What a local codex run needs, beyond the guide: - **Debugging** — `--debug='*'` (the `=` is required); sandbox-side failures land in `codex-debug.log` inside the run directory, next to the transcripts, not in the runner's output. -- **Platforms** — the runtime was brought up and smoke-tested on macOS Apple Silicon (podman - machine, Homebrew `openshell`, arm64 image); the local guide's platform notes otherwise apply - unchanged. +- **Platforms** — the runtime was brought up and smoke-tested locally on macOS Apple Silicon + (podman machine, Homebrew `openshell`, arm64 image), and `review` and `retro` also ran with + fullsend and OpenShell 0.1.4 (CI's pin) inside a Fedora CoreOS (aarch64) podman VM on the same + Mac. The local guide's platform notes otherwise apply unchanged. ## Behaviour differences worth knowing @@ -432,25 +434,41 @@ What a local codex run needs, beyond the guide: ## Not yet exercised -**Start on a disposable repo,** with `triage` or `prioritize` before `code` or `fix`. Codex has been -run end to end by hand — the fleet's own `triage` and `review` harnesses, on `openai/gpt-5.6-luna`, -on macOS — but not yet through a full fleet lifecycle, and not yet on the CI credential path: the -Workload Identity route needs an OpenAI organization mapped to the repositories, which does not -exist yet, so local runs use `OPENAI_API_KEY` on the runner. Until that mapping exists codex also -has no default behaviour-test coverage; its scenario is gated. What was run, and on which versions, -is recorded in [codex runtime -internals](../contributing/runtime-implementation.md#codex-runtime-internals-6920). - -**`review` and `retro` delegate.** On a V1 parent on the direct route with +**Start on a disposable repo,** with `triage` or `prioritize` before `code` or `fix`. Codex has +been run end to end by hand, locally on macOS Apple Silicon. On `openai/gpt-5.6-luna`, a V1 +parent, the fleet's own `triage`, `code`, `fix`, `review` and `retro` harnesses ran natively, +and `review` and `retro` also ran in a Fedora CoreOS (aarch64) podman VM. On an +`openai/gpt-6.1-sol` parent, a V2 one, `review` and `retro` ran natively. None of these runs +went through a full fleet lifecycle or the CI credential path: the Workload Identity route needs +an OpenAI organization mapped to the repositories, which does not exist yet, so local runs use +`OPENAI_API_KEY` on the runner. Until that mapping exists codex also has no default +behaviour-test coverage; its scenario is gated. What was run, and on which versions, is recorded +in [codex runtime internals](../contributing/runtime-implementation.md#codex-runtime-internals-6920), +in [#8836](https://github.com/fullsend-ai/fullsend/pull/8836) (`triage`, `code` and `fix`), on +[#6970](https://github.com/fullsend-ai/fullsend/issues/6970) (`review` and `retro` on V1) and on +[#9085](https://github.com/fullsend-ai/fullsend/issues/9085#issuecomment-6920231259) (`review` +and `retro` on V2). + +**`review` and `retro` delegate.** On a V1 or V2 parent on the direct route with harness security on, `review` runs its skill's personas and `retro` its investigation tasks as native Codex children ([Sub-agents](#sub-agents)); -otherwise they run in one context. Both completed fleet-shaped runs -that way on `gpt-5.6-luna`, on macOS and on Fedora, locally rather than -through the fleet workflows -([#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). - -**`code` and `fix` delegate too.** They declare no `tools:`, so on a V1 or V2 parent on the -direct route with harness security on they get the `default` and `explore` roles, children with the parent's shell and `apply_patch`, +otherwise, and on a V2 parent when a child model selects V2, they run in one +context. Both have run fleet-shaped that way on +`gpt-5.6-luna`, a V1 parent, locally on macOS Apple Silicon, natively and in a Fedora +CoreOS (aarch64) podman VM, not through the fleet workflows +([#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). Every run +exited 0, but in two of the three `review` runs on #6970 a persona the skill +selects did not run, and neither result said so +([#9073](https://github.com/fullsend-ai/fullsend/issues/9073), +[#9657](https://github.com/fullsend-ai/fullsend/issues/9657)). On a `gpt-6.1-sol` parent, a V2 +one, with `gpt-5.6-luna` children, `review` ran eight personas and `retro` four tasks natively on +macOS, and each child's result reached the parent once +([#9085](https://github.com/fullsend-ai/fullsend/issues/9085#issuecomment-6920231259)); the `review` +parent then dropped the challenger's kept findings after its own check of the repository +([#9657](https://github.com/fullsend-ai/fullsend/issues/9657)). + +**`code` and `fix` delegate too.** They declare no `tools:`, so under the same conditions they get +the `default` and `explore` roles, children with the parent's shell and `apply_patch`, the spawn guard and the dispatch note, as `review` does. Both have run end to end that way on `gpt-5.6-luna` and chose not to spawn, so neither has run a native child yet. diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index ce2b15cd11..5bb8f740e4 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -453,8 +453,9 @@ const codexV2DispatchMarker = "Dispatch follows collaboration V2." // codex's native tools and states the policy the spawn guard enforces, so // the parent passes the arguments the guard admits and handles a denial // without retrying. The first two sentences and the denied-spawn sentence -// are what the agents repository's pr-review skill and retro agent key on -// (fullsend-ai/agents#1849); change them only together with those. roles is +// are what the agents repository's pr-review skill, review agent and retro +// agent key on (fullsend-ai/agents#1849, fullsend-ai/agents#1971); change +// them only together with those. roles is // the registered roster, sorted by name (codexRoles); version is the // collaboration version the gate admitted. The V2 note keeps the keyed // sentences, puts codexV2DispatchMarker right after its third sentence, From 455ea94a1a81358d3bf966285e9ab860cead2c5e Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 17 Nov 2026 18:31:49 -0500 Subject: [PATCH 013/208] fix(#6970): name the review persona losses in setup and the guide The setup prompt's codex line said nothing about review once the keep-on-claude advice went, so it now says review has skipped one of its sub-agents without saying so (#9073, #9657). The guide's callout says what was lost and how often: a selected review persona in two of the three local review runs on #6970, and in a later run findings the review's challenger persona had kept. The review/retro paragraph of the codex page names the per-agent `runtime: claude` override for keeping either agent on Claude Code. Signed-off-by: Dharit Shah --- docs/guides/getting-started/choosing-a-runtime.md | 2 +- docs/runtimes/codex.md | 4 +++- internal/cli/runtime_prompt.go | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/guides/getting-started/choosing-a-runtime.md b/docs/guides/getting-started/choosing-a-runtime.md index bd5b56169f..60de94d3a4 100644 --- a/docs/guides/getting-started/choosing-a-runtime.md +++ b/docs/guides/getting-started/choosing-a-runtime.md @@ -4,7 +4,7 @@ sidebar_label: Choose a Runtime # Choose an agent runtime -> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`; codex runs OpenAI models through the same secretless credential path, and some of its local `review` runs have skipped one of the review's checks without saying so, or dropped findings the review had confirmed ([details](../../runtimes/codex.md#not-yet-exercised)). Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. +> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`; codex runs OpenAI models through the same secretless credential path, but in two of the three local `review` runs on [#6970](https://github.com/fullsend-ai/fullsend/issues/6970) a selected review persona (a sub-agent that checks one aspect of the change) did not run and the result did not say so, and in a later run the review dropped findings its challenger persona (the one that re-checks the others' findings) had kept ([details](../../runtimes/codex.md#not-yet-exercised)). Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. This page explains what the choice means and where it is made. **You do not select anything on this page** — the selection happens in the next step. On GitHub, [Configuring GitHub](configuring-github.md) asks when you run `fullsend github setup` (press Enter for `claude`) or you pass `--runtime`. On GitLab, set `runtime:` in `defaults.config`, `gitlab.config`, or the repository entry's `config` in `repos.yaml` before running `fullsend repos install` (there is no install flag) — see [Configuring GitLab](configuring-gitlab.md). diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index c2e889ccfd..59e803c72c 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -465,7 +465,9 @@ one, with `gpt-5.6-luna` children, `review` ran eight personas and `retro` four macOS, and each child's result reached the parent once ([#9085](https://github.com/fullsend-ai/fullsend/issues/9085#issuecomment-6920231259)); the `review` parent then dropped the challenger's kept findings after its own check of the repository -([#9657](https://github.com/fullsend-ai/fullsend/issues/9657)). +([#9657](https://github.com/fullsend-ai/fullsend/issues/9657)). To keep either agent on Claude Code, +set `runtime: claude` on its `agents:` entry ([per-agent +settings](../runtimes.md#per-agent-runtime-model-and-effort)). **`code` and `fix` delegate too.** They declare no `tools:`, so under the same conditions they get the `default` and `explore` roles, children with the parent's shell and `apply_patch`, diff --git a/internal/cli/runtime_prompt.go b/internal/cli/runtime_prompt.go index a7ef9d9e7e..7d9cc1ecc1 100644 --- a/internal/cli/runtime_prompt.go +++ b/internal/cli/runtime_prompt.go @@ -32,7 +32,8 @@ func promptRuntime(printer *ui.Printer, in io.Reader, interactive bool) (string, printer.StepInfo("Choose the agent runtime for this repository:") printer.StepInfo(" [claude] Claude Code — stable default, recommended; all fleet agents, concurrent sub-agents") printer.StepInfo(" [pi] pi — experimental (enablement phase); any provider pi supports, no sub-agent tool yet") - printer.StepInfo(" [codex] Codex — experimental; OpenAI models, or gateway/ through an inference gateway") + printer.StepInfo(" [codex] Codex — experimental; OpenAI models, or gateway/ through an inference gateway;") + printer.StepInfo(" review has skipped one of its sub-agents without saying so (#9073, #9657)") printer.StepInfo(" [opencode] OpenCode — experimental; read-only agents only until the security-hook adapter lands (unbound-force#515)") printer.StepInfo(" Keep the default unless you are taking part in a runtime pilot. Change later with `runtime:`") printer.StepInfo(" in .fullsend/config.yaml or `fullsend github setup --runtime`; see docs/runtimes.md.") From ecc1f0702a5a06d47cf6b7fe939c7324d70dcb89 Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Wed, 18 Nov 2026 09:41:58 +0200 Subject: [PATCH 014/208] docs(adr): clarify journal primitives scope Signed-off-by: eshulman2 --- ...k-through-repository-owned-operation-journals.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md index 758dbc371c..55627aea24 100644 --- a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md +++ b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md @@ -1,5 +1,5 @@ --- -title: "165. Recover work through repository-owned operation journals" +title: "165. Primitives for repository-owned operation journals" status: Accepted relates_to: - durable-work-recovery @@ -10,7 +10,7 @@ topics: - recovery --- -# 165. Recover work through repository-owned operation journals +# 165. Primitives for repository-owned operation journals Date: 2026-11-10 @@ -67,10 +67,11 @@ inference, subject to current source, authorization and policy checks. Missing, exhausted or unresolved targets remain visible and cannot imply completion. Domain adapters define completion and any compensating actions. -Journal-backed recovery is an explicit workflow opt-in. Participating workflows -integrate trusted journal operations through their pre/post scripts, agent or -harness contracts, and reconcilers. Existing webhook and poll dispatch paths do -not automatically journal every run; their selection and dispatch behavior +Journal-backed recovery is an explicit workflow opt-in. Workflows installed by +fullsend require explicit integration to use these primitives. Participating +workflows integrate trusted journal operations through their pre/post scripts, +agent or harness contracts, and reconcilers. Existing webhook and poll dispatch +paths do not automatically journal every run; their selection and dispatch behavior remains unchanged unless explicitly integrated. Once a workflow admits work to the journal, the recovery contract covers all its required targets and effects. From ec55c411cc584aff6d5f373d73c781f53a73aa92 Mon Sep 17 00:00:00 2001 From: Barak Korren Date: Wed, 18 Nov 2026 10:18:30 +0200 Subject: [PATCH 015/208] docs(config): bind creation policy to trusted branch config Signed-off-by: Barak Korren Assisted-by: Codex --- .../entity-source-configuration/v1/README.md | 34 ++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/docs/normative/entity-source-configuration/v1/README.md b/docs/normative/entity-source-configuration/v1/README.md index 8d6af72239..7a4ee80b1d 100644 --- a/docs/normative/entity-source-configuration/v1/README.md +++ b/docs/normative/entity-source-configuration/v1/README.md @@ -92,14 +92,16 @@ Connection kinds and endpoints determine where credentials are sent. Only configuration layers designated trusted by the repository's configuration policy may set or change them; event data, harnesses, and untrusted overlays MUST NOT. At minimum, trusted layers include managed `repos.yaml` values and -`.fullsend/` configuration read from the protected default branch under -[ADR 0033](../../../ADRs/0033-per-repo-installation-mode.md). PR-head config, -harness content, and event data cannot designate themselves as trusted endpoint -overrides. Credential bindings MUST be provisioned for the canonical provider -endpoint and tenant, and the resolver MUST refuse to send a credential to any -other endpoint even when the connection name and kind match. Changing an -endpoint requires a separately provisioned credential binding for that host; -the old host's credential, grants, and cached evidence do not transfer. +`.fullsend/` configuration selected by the workflow: for a pull request, the +PR target branch head, as described by +[ADR 0033](../../../ADRs/0033-per-repo-installation-mode.md). The PR source +branch's config, harness content, and event data cannot designate themselves +as trusted endpoint overrides. Credential bindings MUST be provisioned for the +canonical provider endpoint and tenant, and the resolver MUST refuse to send a +credential to any other endpoint even when the connection name and kind match. +Changing an endpoint requires a separately provisioned credential binding for +that host; the old host's credential, grants, and cached evidence do not +transfer. For example, a GitHub.com clone selects the `github` provider. Setting `connections.github.base_url` to a GitHub Enterprise URL makes that instance @@ -565,6 +567,15 @@ implicit grant. Binding a Jira project as an input or output does not itself grant creation rights there. Policies replace as whole values; grants cannot move to another instance merely by reusing a connection alias. +`allowed_targets` is part of trusted repository configuration and uses the +same workflow-selected revision as connection settings. On pull-request runs, +that is the PR target branch head; configuration changes present only on the PR +source branch do not change creation policy. This is the existing repository +configuration trust boundary; it requires no separate per-field trust or layer +mechanism. Untrusted overlays, harness content, and event data MUST NOT add or +replace creation grants or remove an inherited restriction. Legacy `tracker` +`allowed_targets` grants follow the same rule before translation. + Lookup scope supplies the ordinary destination choices. An explicit work-item creation destination outside that lookup scope is allowed only when the connection's separate `allowed_targets` policy covers it, the operation selects @@ -754,6 +765,13 @@ Implementations MUST cover at least these observable cases: credentials are bound to the canonical endpoint and tenant; changing the host requires a separately provisioned binding and never sends the previous host's credential to the new endpoint. +- Pull-request workflows resolve connection and creation-policy configuration + from the PR target branch head. A destination grant present only on the PR + source branch cannot widen a same-endpoint `allowed_targets` policy, replace + or remove an inherited restriction, or affect grants translated from legacy + `tracker` configuration. The existing repository configuration trust + boundary provides this behavior; no additional per-field trust mechanism is + required. - Kind defaults and per-slot inheritance resolve correctly; all binding values are lists, source defaults to `[native]`, and an omitted target copies the final source list. Explicit targets win, copied names must support the target From e643e1bc614665a228fc40908e6fcc0e0beb1b5b Mon Sep 17 00:00:00 2001 From: eshulman2 Date: Thu, 19 Nov 2026 10:07:15 +0200 Subject: [PATCH 016/208] docs(adr): clarify journal privacy and telemetry boundaries Signed-off-by: eshulman2 --- ...-through-repository-owned-operation-journals.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md index 55627aea24..0254b313fd 100644 --- a/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md +++ b/docs/ADRs/0165-recover-work-through-repository-owned-operation-journals.md @@ -52,6 +52,10 @@ branches. Domain dispatch and assessment semantics remain in adapters. The journal retains stable operation identities, input bindings, work bounds, effect intents and separate scheduling, execution and publication receipts. +Execution receipts retain recovery state and references to runs and available +traces; detailed execution history remains in run telemetry. The journal +determines what work needs recovery, while telemetry records what happened +within a run. Correlation mechanisms remain an implementation choice. Conditional updates, integrity checks and ownership fencing prevent competing or superseded workers from accepting results or admitting new effects. An external request admitted before ownership loss remains in-flight until its @@ -83,8 +87,14 @@ not a coordinator agent. Only authorized trusted host code writes the journal. Assessment workers receive admitted context without journal-write credentials. Journal state -contains bounded identities, digests and receipts; artifact publication policy -still applies. Journal contents grant no authority, and integrity failure +contains bounded identities, digests and receipts. Workflow integrators must +ensure journal contents and retained evidence are accessible only to readers +authorized for that data; journal storage may use a separate private repository. +Artifact publication filters do not protect journal commits. With artifact +levels of `metadata` or `none`, evidence needed for recovery requires a separate +store permitted by the source's disclosure and retention policies. Its location +and access controls are integration choices. Journal contents grant no +authority, and integrity failure stops scheduling and publication rather than resetting state and repeating work. ## Entity state and journal state From 079bebf8a134cc0ce6f1d2e24fc42207751a20d8 Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:33:59 +0000 Subject: [PATCH 017/208] chore(#9743): bump pi to 1.6.0 for undici 8.12.4 and Gemini 4 models Bump PI_VERSION in images/sandbox/Containerfile from 1.5.0 to 1.6.0. pi 1.6.0 pins undici 8.12.4, which carries six upstream security fixes, and its google-vertex catalog gains new models. Extension tags are left as they are. check-vertex-catalog.sh against pi-ai 1.6.0's dist/providers/data/google-vertex.json reported four added ids: gemini-4-carbon, gemini-4-hydrogen, gemini-4-neon and gemini-robotics-er-2-preview. All four are added to piGoogleVertexModels, which is documented as a verbatim copy of that catalog; the issue named only the first three, but the script cannot pass without the fourth. It now reports OK (17 ids). Bump checks run against 1.6.0: - jiti-cache-check.sh: all six checks pass; jiti is still 2.7.0, jiti.cjs is byte-identical and the bundled createJiti branch still passes no alias, so the pi.go and pi_run.go notes say re-checked at 1.6.0. - environment-variables.md and json.md are byte-identical to 1.5.0. - anthropic.json adds claude-fable-5-2 and a supportsTemperature compat key; piModelAliases is left unchanged. - A live 1.6.0 --mode json capture parses through parsePiStream with ResultEvent last; basic_run.ndjson is hand-authored and kept. - The usage schema is unchanged; the distributed-tracing link moves to v1.6.0 types.ts#L467-L479. - fullsend-edit-repair.test.mjs passes 13/13 at real pi 1.6.0 and the without-extension control still fails, so the extension stays. Note: pre-commit could not fetch its hook repositories (TLS failure in the sandbox); the hooks were run directly instead. semgrep was skipped because its pinned ruleset could not be downloaded. Closes #9743 --- docs/guides/infrastructure/distributed-tracing.md | 4 ++-- images/sandbox/Containerfile | 2 +- internal/runtime/pi.go | 2 +- internal/runtime/pi_bootstrap.go | 6 +++++- internal/runtime/pi_run.go | 2 +- 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/guides/infrastructure/distributed-tracing.md b/docs/guides/infrastructure/distributed-tracing.md index 61688ecbc4..d3d2bd06eb 100644 --- a/docs/guides/infrastructure/distributed-tracing.md +++ b/docs/guides/infrastructure/distributed-tracing.md @@ -664,8 +664,8 @@ records them, so there the reasoning rule depends on the runtime: - **Claude:** Reasoning is a breakdown of output. Do not add it again. An interrupted iteration may lack the final reasoning count even when streamed output counts were captured. -- **pi:** The pinned pi `1.5.0` - [usage schema](https://github.com/earendil-works/pi/blob/v1.5.0/packages/ai/src/types.ts#L459-L471) +- **pi:** The pinned pi `1.6.0` + [usage schema](https://github.com/earendil-works/pi/blob/v1.6.0/packages/ai/src/types.ts#L467-L479) defines reasoning as a subset of output. Fullsend passes those fields through, so do not add reasoning again. Recheck the schema when pricing artifacts from a different pi version; sibling JSON fields and synthetic diff --git a/images/sandbox/Containerfile b/images/sandbox/Containerfile index b7521eef50..73e0dd5de7 100644 --- a/images/sandbox/Containerfile +++ b/images/sandbox/Containerfile @@ -108,7 +108,7 @@ RUN NPM_CLAUDE="$(npm prefix -g)/bin/claude" \ # rejecting malformed edit arguments (earendil-works/pi#8521, #8962); once # the test's without-extension control stops failing, this pi repairs both # shapes itself — delete the extension and internal/runtime/pi_edit_repair.go. -ARG PI_VERSION=1.5.0 +ARG PI_VERSION=1.6.0 RUN node -e "process.exit(process.versions.node.split('.').map(Number).reduce((a,b,i)=>a!==0?a:(b-[22,19,0][i]),0)>=0?0:1)" \ || (echo "pi ${PI_VERSION} requires Node >=22.19.0, base image has $(node --version)" >&2 && exit 1) \ && npm install -g --ignore-scripts @earendil-works/pi-coding-agent@${PI_VERSION} diff --git a/internal/runtime/pi.go b/internal/runtime/pi.go index 348dccfa9e..d88c6447b7 100644 --- a/internal/runtime/pi.go +++ b/internal/runtime/pi.go @@ -132,7 +132,7 @@ func (PiRuntime) WorkspaceDir() string { return sandbox.SandboxWorkspace } // (piExtensionsGuard) and the hook adapter's SHA-256 check (piHooksGuard), // neither of which can see it. Setting the variable to false makes jiti // ignore any planted entry and create no cache directory at all (verified -// on pi 0.84.4, re-checked on 0.85.0 and 1.5.0, jiti 2.7.0 throughout — +// on pi 0.84.4, re-checked on 0.85.0, 1.5.0 and 1.6.0, jiti 2.7.0 throughout — // internal/runtime/testdata/pi/jiti-cache-check.sh reproduces both // halves). Run re-exports these after the agent-writable // .env is sourced, so the agent cannot switch the cache back on, and diff --git a/internal/runtime/pi_bootstrap.go b/internal/runtime/pi_bootstrap.go index f9bc4ce15a..3e6f7db9d5 100644 --- a/internal/runtime/pi_bootstrap.go +++ b/internal/runtime/pi_bootstrap.go @@ -776,7 +776,7 @@ func piAgentModels(defModel string, configAliases map[string]string) map[string] // piGoogleVertexModels are the model ids pi's built-in google-vertex // provider registers, verbatim from the catalog the pinned pi bundles -// (@earendil-works/pi-ai 1.5.0, dist/providers/data/google-vertex.json). +// (@earendil-works/pi-ai 1.6.0, dist/providers/data/google-vertex.json). // Re-check it on a pi bump, the way the Anthropic ids in pi_run.go are: // diff that data file, not the generated wrapper (0.85.0 changed only the // data file); a missed entry means this table rejects an id the running pi @@ -803,6 +803,10 @@ var piGoogleVertexModels = []string{ "gemini-3.7-flash", "gemini-3.8-flash", "gemini-4-argon", + "gemini-4-carbon", + "gemini-4-hydrogen", + "gemini-4-neon", + "gemini-robotics-er-2-preview", } // piXaiVertexModels are the model ids the vendored xai-vertex extension diff --git a/internal/runtime/pi_run.go b/internal/runtime/pi_run.go index ad12de9039..59a08a76b5 100644 --- a/internal/runtime/pi_run.go +++ b/internal/runtime/pi_run.go @@ -833,7 +833,7 @@ func piChildLaunchExport() string { // different file while the extension source, its tree hash // (piExtensionsGuard) and the hook adapter's SHA-256 (piHooksGuard) all // stay clean, because none of them can see the substitution. Verified on -// pi 0.84.4, re-checked on 0.85.0 and 1.5.0 (jiti 2.7.0 throughout); the +// pi 0.84.4, re-checked on 0.85.0, 1.5.0 and 1.6.0 (jiti 2.7.0 throughout); the // shell half is // internal/runtime/testdata/pi/jiti-cache-check.sh. // From 5359aba3d6e58043b26282bd73dd12390a2a08aa Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:38:57 +0000 Subject: [PATCH 018/208] test(#9754): check shards.txt against the behaviour feature files Nothing checked e2e/behaviour/github-emulator/shards.txt against the feature files, so a scenario silently stopped running on pull requests when it was added without a shard entry, or when lines added above it left its feature:line entry stale. Add e2e/behaviour/shards_test.go, untagged so the plain go test ./... unit run picks it up. It parses every feature with gherkin/go/v42 and collects each Scenario / Scenario Outline header line (an outline counts once, at its own line, including scenarios under a Rule). It then reads shards.txt ( ...) and the new not-sharded.txt ( # reason), where an entry without :line covers the whole feature. It fails, naming each offending entry, when a scenario is in neither list, when an entry names a missing file or matches no scenario header, or when a scenario is listed more than once (two shards, or a shard and not-sharded.txt). not-sharded.txt starts with the 12 scenarios deliberately in no shard: 11 gated on @requires:capability tags and the @playback scenario. Table-driven cases over a temp dir cover each failure mode. The behaviour- and playback-tagged builds still compile. The shards.txt paragraph in docs/guides/dev/behaviour-testing.md now describes the check and not-sharded.txt. pre-commit could not fetch its remote hook repos in the sandbox (TLS error). The applicable hooks were run directly instead: whitespace, end-of-file, line-ending and conflict checks, gofmt, go vet ./..., lint-broken-symlinks, lint-docs-links and lychee all pass, and scan-secrets covered secret detection. Closes #9754 Co-Authored-By: Claude Opus 5.5 --- docs/guides/dev/behaviour-testing.md | 9 + e2e/behaviour/github-emulator/not-sharded.txt | 16 + e2e/behaviour/shards_test.go | 391 ++++++++++++++++++ 3 files changed, 416 insertions(+) create mode 100644 e2e/behaviour/github-emulator/not-sharded.txt create mode 100644 e2e/behaviour/shards_test.go diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index dadd6a9be4..96db233f1a 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -584,6 +584,15 @@ are balanced on measured scenario time, not on scenario count. When you add or move a scenario, update its line. List a Scenario Outline by its own line so all its rows stay on one shard. +`e2e/behaviour/shards_test.go` enforces the list as part of the plain +`go test ./...` unit run. It fails, naming each entry, when a scenario is in no +shard, when an entry does not point at a `Scenario:` or `Scenario Outline:` +header (for example after lines are added above it), or when a scenario is +listed more than once. A scenario that cannot run on the emulator, such as one +gated on a `@requires:capability:` tag, goes in +`e2e/behaviour/github-emulator/not-sharded.txt` instead, one +`` per line with a `#` comment giving the reason. + ### Failure classification and infrastructure retry Behaviour tests run against live infrastructure — the GitHub API, Actions diff --git a/e2e/behaviour/github-emulator/not-sharded.txt b/e2e/behaviour/github-emulator/not-sharded.txt new file mode 100644 index 0000000000..e3e6a785a4 --- /dev/null +++ b/e2e/behaviour/github-emulator/not-sharded.txt @@ -0,0 +1,16 @@ +# Behaviour scenarios deliberately in no shard of shards.txt: # why +# shards_test.go fails when a scenario is in neither shards.txt nor this +# file, so a scenario that cannot run on the emulator in a pull request is +# listed here with the reason. +features/runtime/agent-settings.feature:57 # @requires:capability:runtime-pi +features/runtime/claude-gateway.feature:24 # @requires:capability:runtime-claude-gateway +features/runtime/codex-gateway.feature:27 # @requires:capability:runtime-codex-gateway +features/runtime/codex-openai.feature:26 # @requires:capability:runtime-codex-openai +features/runtime/inference-gateway-api-key.feature:28 # @requires:capability:inference-gateway-api-key +features/runtime/inference-gateway.feature:62 # @requires:capability:inference-gateway +features/runtime/inference-gateway.feature:100 # @requires:capability:inference-gateway-reseed +features/runtime/opencode.feature:19 # @requires:capability:runtime-opencode +features/runtime/pi-gateway.feature:23 # @requires:capability:runtime-pi-gateway +features/runtime/pi-openai.feature:19 # @requires:capability:runtime-pi-openai +features/runtime/pi.feature:17 # @requires:capability:runtime-pi +features/runtime/playback.feature:29 # @playback, run by the playback job diff --git a/e2e/behaviour/shards_test.go b/e2e/behaviour/shards_test.go new file mode 100644 index 0000000000..55bf86c84b --- /dev/null +++ b/e2e/behaviour/shards_test.go @@ -0,0 +1,391 @@ +package behaviour_test + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io/fs" + "os" + "path" + "path/filepath" + "sort" + "strconv" + "strings" + "testing" + + gherkin "github.com/cucumber/gherkin/go/v42" + messages "github.com/cucumber/messages/go/v34" +) + +// The shard files, relative to this directory. Their entries are relative to +// this directory too, e.g. "features/triage/triage.feature:6". +const ( + shardFeaturesDir = "features" + shardsListFile = "github-emulator/shards.txt" + notShardedListFile = "github-emulator/not-sharded.txt" +) + +// TestShardsCoverEveryScenario checks shards.txt, which lists the scenarios +// that run on pull requests, against the feature files: every scenario must +// be in exactly one shard or in not-sharded.txt, and every entry must point +// at a scenario header. +func TestShardsCoverEveryScenario(t *testing.T) { + problems, err := shardListProblems(".") + if err != nil { + t.Fatal(err) + } + for _, p := range problems { + t.Error(p) + } +} + +func TestShardListProblems(t *testing.T) { + base := map[string]string{ + "features/a.feature": "Feature: a\n" + + "\n" + + " Scenario: one\n" + + " Given x\n" + + "\n" + + " Scenario: two\n" + + " Given y\n", + "features/outline.feature": "Feature: outline\n" + + "\n" + + " Scenario Outline: row \n" + + " Given \n" + + "\n" + + " Examples:\n" + + " | n |\n" + + " | 1 |\n" + + " | 2 |\n", + "features/sub/c.feature": "Feature: c\n" + + "\n" + + " Rule: r\n" + + " Scenario: three\n" + + " Given z\n" + + "\n" + + " Scenario: four\n" + + " Given w\n", + shardsListFile: "# ...\n" + + "x 2 4 features/a.feature:3 features/outline.feature:3\n" + + "\n" + + "y 1 1 features/a.feature:6\n", + notShardedListFile: "# not sharded\n" + + "features/sub/c.feature # whole feature, Rule included\n", + } + + tests := []struct { + name string + files map[string]string + want []string // substrings, one per problem, in order + }{ + { + name: "valid layout", + }, + { + name: "unlisted scenario", + files: map[string]string{ + "features/a.feature": base["features/a.feature"] + + "\n" + + " Scenario: new\n" + + " Given n\n", + }, + want: []string{"features/a.feature:9 is in neither shards.txt nor not-sharded.txt"}, + }, + { + name: "unlisted feature file", + files: map[string]string{ + "features/new.feature": "Feature: new\n\n Scenario: new\n Given n\n", + }, + want: []string{"features/new.feature:3 is in neither"}, + }, + { + name: "blank line above sharded scenarios makes entries stale", + files: map[string]string{ + "features/a.feature": strings.Replace(base["features/a.feature"], "Feature: a\n", "Feature: a\n\n", 1), + }, + want: []string{ + "shards.txt:2 (shard x): features/a.feature:3 matches no Scenario or Scenario Outline header (next header: line 4)", + "shards.txt:4 (shard y): features/a.feature:6 matches no Scenario or Scenario Outline header (next header: line 7)", + "features/a.feature:4 is in neither", + "features/a.feature:7 is in neither", + }, + }, + { + name: "scenario in two shards", + files: map[string]string{ + shardsListFile: "x 2 4 features/a.feature:3 features/outline.feature:3\n" + + "y 1 1 features/a.feature:6 features/a.feature:3\n", + }, + want: []string{"features/a.feature:3 is listed more than once: shards.txt:1 (shard x), shards.txt:2 (shard y)"}, + }, + { + name: "scenario in a shard and in not-sharded.txt", + files: map[string]string{ + notShardedListFile: base[notShardedListFile] + "features/a.feature:6 # also sharded\n", + }, + want: []string{"features/a.feature:6 is listed more than once: shards.txt:4 (shard y), not-sharded.txt:3"}, + }, + { + name: "bare feature entry overlaps a line entry", + files: map[string]string{ + notShardedListFile: base[notShardedListFile] + "features/outline.feature\n", + }, + want: []string{"features/outline.feature:3 is listed more than once"}, + }, + { + name: "missing feature file", + files: map[string]string{ + shardsListFile: base[shardsListFile] + "z 1 1 features/gone.feature:1\n", + }, + want: []string{"shards.txt:5 (shard z): features/gone.feature:1 names a missing feature file"}, + }, + { + name: "missing feature file in not-sharded.txt", + files: map[string]string{ + notShardedListFile: base[notShardedListFile] + "features/gone.feature\n", + }, + want: []string{"not-sharded.txt:3: features/gone.feature names a missing feature file"}, + }, + { + name: "Scenario Outline counts once, at its own line", + files: map[string]string{ + shardsListFile: "x 2 4 features/a.feature:3 features/outline.feature:8\n" + + "y 1 1 features/a.feature:6\n", + }, + want: []string{ + "shards.txt:1 (shard x): features/outline.feature:8 matches no Scenario or Scenario Outline header", + "features/outline.feature:3 is in neither", + }, + }, + { + name: "malformed shard line", + files: map[string]string{ + shardsListFile: base[shardsListFile] + "z 1 features/a.feature:3\n", + }, + want: []string{"shards.txt:5: want ..."}, + }, + { + name: "bad line number", + files: map[string]string{ + notShardedListFile: base[notShardedListFile] + "features/a.feature:x\n", + }, + want: []string{"not-sharded.txt:3: features/a.feature:x has a bad line number"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + root := t.TempDir() + for name, content := range base { + if override, ok := tt.files[name]; ok { + content = override + } + writeShardFixture(t, root, name, content) + } + for name, content := range tt.files { + if _, ok := base[name]; !ok { + writeShardFixture(t, root, name, content) + } + } + + got, err := shardListProblems(root) + if err != nil { + t.Fatal(err) + } + if len(got) != len(tt.want) { + t.Fatalf("got %d problems, want %d:\n%s", len(got), len(tt.want), strings.Join(got, "\n")) + } + for i, want := range tt.want { + if !strings.Contains(got[i], want) { + t.Errorf("problem %d = %q, want it to contain %q", i, got[i], want) + } + } + }) + } +} + +func TestShardListProblemsMissingListFile(t *testing.T) { + root := t.TempDir() + writeShardFixture(t, root, "features/a.feature", "Feature: a\n") + writeShardFixture(t, root, shardsListFile, "") + if _, err := shardListProblems(root); err == nil { + t.Fatal("want an error when not-sharded.txt is missing") + } +} + +func writeShardFixture(t *testing.T, root, name, content string) { + t.Helper() + p := filepath.Join(root, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +// shardScenario is one scenario header: a feature path relative to the +// root and the line of its Scenario or Scenario Outline keyword. +type shardScenario struct { + feature string + line int +} + +func (s shardScenario) String() string { return fmt.Sprintf("%s:%d", s.feature, s.line) } + +// shardListProblems checks shards.txt and not-sharded.txt under root against +// the feature files under root/features and returns one message per +// offending entry or scenario. It returns an error only when a file cannot +// be read or parsed. +func shardListProblems(root string) ([]string, error) { + fsys := os.DirFS(root) + headers, err := shardScenarioHeaders(fsys) + if err != nil { + return nil, err + } + + var problems []string + listed := map[shardScenario][]string{} + for _, list := range []struct { + name string + sharded bool + }{{shardsListFile, true}, {notShardedListFile, false}} { + data, err := fs.ReadFile(fsys, list.name) + if err != nil { + return nil, err + } + problems = append(problems, checkShardList(path.Base(list.name), data, list.sharded, headers, listed)...) + } + + var scenarios []shardScenario + for feature, lines := range headers { + for _, line := range lines { + scenarios = append(scenarios, shardScenario{feature, line}) + } + } + sort.Slice(scenarios, func(i, j int) bool { + if scenarios[i].feature != scenarios[j].feature { + return scenarios[i].feature < scenarios[j].feature + } + return scenarios[i].line < scenarios[j].line + }) + for _, s := range scenarios { + switch where := listed[s]; { + case len(where) == 0: + problems = append(problems, fmt.Sprintf("%s is in neither %s nor %s: add it to a shard, or to %s with the reason it cannot run on the emulator", + s, path.Base(shardsListFile), path.Base(notShardedListFile), path.Base(notShardedListFile))) + case len(where) > 1: + problems = append(problems, fmt.Sprintf("%s is listed more than once: %s", s, strings.Join(where, ", "))) + } + } + return problems, nil +} + +// checkShardList records in listed where each scenario named by a shard list +// is listed, and returns the problems with its entries. A sharded list's +// lines are " ..."; the other +// list's lines are "...". "#" starts a comment. An entry +// without ":line" covers every scenario in its feature. +func checkShardList(name string, data []byte, sharded bool, headers map[string][]int, listed map[shardScenario][]string) []string { + var problems []string + scanner := bufio.NewScanner(bytes.NewReader(data)) + for n := 1; scanner.Scan(); n++ { + text := scanner.Text() + if i := strings.IndexByte(text, '#'); i >= 0 { + text = text[:i] + } + fields := strings.Fields(text) + if len(fields) == 0 { + continue + } + where := fmt.Sprintf("%s:%d", name, n) + entries := fields + if sharded { + if len(fields) < 4 { + problems = append(problems, fmt.Sprintf("%s: want ..., got %q", where, strings.TrimSpace(text))) + continue + } + where = fmt.Sprintf("%s (shard %s)", where, fields[0]) + entries = fields[3:] + } + for _, entry := range entries { + feature, line := entry, 0 + if i := strings.LastIndexByte(entry, ':'); i >= 0 { + l, err := strconv.Atoi(entry[i+1:]) + if err != nil || l <= 0 { + problems = append(problems, fmt.Sprintf("%s: %s has a bad line number", where, entry)) + continue + } + feature, line = entry[:i], l + } + lines, ok := headers[feature] + if !ok { + problems = append(problems, fmt.Sprintf("%s: %s names a missing feature file", where, entry)) + continue + } + if line == 0 { + for _, l := range lines { + s := shardScenario{feature, l} + listed[s] = append(listed[s], where) + } + continue + } + i := sort.SearchInts(lines, line) + if i == len(lines) || lines[i] != line { + msg := fmt.Sprintf("%s: %s matches no Scenario or Scenario Outline header", where, entry) + if i < len(lines) { + msg += fmt.Sprintf(" (next header: line %d)", lines[i]) + } + problems = append(problems, msg) + continue + } + s := shardScenario{feature, line} + listed[s] = append(listed[s], where) + } + } + return problems +} + +// shardScenarioHeaders returns the sorted scenario header lines of every +// feature file under features, keyed by its slash path. A Scenario Outline +// is one header, at its own line, whatever its example rows. +func shardScenarioHeaders(fsys fs.FS) (map[string][]int, error) { + headers := map[string][]int{} + err := fs.WalkDir(fsys, shardFeaturesDir, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() || path.Ext(p) != ".feature" { + return nil + } + data, err := fs.ReadFile(fsys, p) + if err != nil { + return err + } + doc, err := gherkin.ParseGherkinDocument(bytes.NewReader(data), (&messages.Incrementing{}).NewId) + if err != nil { + return fmt.Errorf("parsing feature %s: %w", p, err) + } + if doc.Feature == nil { + return errors.New("feature " + p + " has no Feature") + } + lines := []int{} + for _, child := range doc.Feature.Children { + if child.Scenario != nil { + lines = append(lines, int(child.Scenario.Location.Line)) + } + if child.Rule != nil { + for _, rc := range child.Rule.Children { + if rc.Scenario != nil { + lines = append(lines, int(rc.Scenario.Location.Line)) + } + } + } + } + sort.Ints(lines) + headers[p] = lines + return nil + }) + return headers, err +} From b2a0560a39ec9ddf4c6127b530328142d0920c89 Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:39:53 +0000 Subject: [PATCH 019/208] ci(#9757): accept `/ok-to-test live` in the e2e gate Since #9740, pull requests run behaviour and playback only on the GitHub emulator, and there is no way to run the live suites on a PR, even on request. Runtime bumps and gateway changes first meet the real-model scenarios in the merge queue, where a failure drops the entry and rebuilds every entry behind it. check-e2e-authorization.sh now accepts an optional lowercase `live` after the sha on the first line of an /ok-to-test comment. It passes the same gate (write+ commenter, comment read by id, head must be the named sha). A new `live` output is true only when the run is authorized (reason=ok_to_test) and the comment asked for live; every other path, the error path included, writes live=false. Any other word after the sha stays missing_sha. The tests cover live=true (extra spaces, CRLF), LIVE, a word after live, live with no space, live before the sha, a stale sha, a triage commenter and an API error, and every existing case now asserts live=false. e2e-testing.md gains a "Run the live suites on a pull request" walkthrough, a CI authorization row, the live wording for missing_sha, and an updated CI architecture list. ci-workflows.md describes the live jobs under Gate job mitigation. The .github/ wiring (action output, behaviour-live and playback-live check runs, the e2e.yml `live` input) is added during review, as the issue describes. Note: pre-commit could not fetch hook repositories (TLS failure in the sandbox). The applicable hooks were run directly instead and passed: pre-commit-hooks 6.0.0 fixers/checks, shellcheck 0.10.0.1, gitleaks, lint-docs-links, lychee --offline --include-fragments and lint-broken-symlinks. Closes #9757 Co-Authored-By: Claude Opus 5.5 --- docs/contributing/ci-workflows.md | 7 ++- docs/guides/dev/e2e-testing.md | 79 +++++++++++++++++++++---- scripts/check-e2e-authorization-test.sh | 61 ++++++++++++++++--- scripts/check-e2e-authorization.sh | 30 +++++++--- 4 files changed, 148 insertions(+), 29 deletions(-) diff --git a/docs/contributing/ci-workflows.md b/docs/contributing/ci-workflows.md index 07854e867b..ca65dde922 100644 --- a/docs/contributing/ci-workflows.md +++ b/docs/contributing/ci-workflows.md @@ -202,13 +202,14 @@ Prefer short-lived narrowly-scoped credentials whenever possible. When long-live ### Gate job mitigation -Pull requests run the behaviour and playback scenarios on a GitHub emulator ([`behaviour-github-emulator.yml`](../../.github/workflows/behaviour-github-emulator.yml)) with no secrets, no environment and no cloud OIDC, so fork pull requests run them on `pull_request` with no authorization step. `e2e.yml` runs the `behaviour` and `playback` suites, with secrets, only in the merge queue and on push to `main`; on a pull request those jobs skip, which their required checks accept. +Pull requests run the behaviour and playback scenarios on a GitHub emulator ([`behaviour-github-emulator.yml`](../../.github/workflows/behaviour-github-emulator.yml)) with no secrets, no environment and no cloud OIDC, so fork pull requests run them on `pull_request` with no authorization step. `e2e.yml` runs the `behaviour` and `playback` suites, with secrets, in the merge queue and on push to `main`; on a pull request those jobs skip, which their required checks accept, unless a maintainer comments `/ok-to-test live` (below). -The `check-e2e-authorization` gate job (`gate` in `e2e.yml`) mitigates the risk by requiring authorization before the `forgejo-behaviour` job, the only `e2e.yml` suite that runs on pull requests, checks out PR-head code. `e2e.yml` and `e2e-ok-to-test.yml` no longer use `pull_request_target` ([#9245](https://github.com/fullsend-ai/fullsend/issues/9245)): same-repository PRs run on `pull_request`, and fork PRs run only after a `/ok-to-test ` comment (`issue_comment`): +The `check-e2e-authorization` gate job (`gate` in `e2e.yml`) mitigates the risk by requiring authorization before the `forgejo-behaviour` job, or the live `behaviour` and `playback` jobs after `/ok-to-test live`, checks out PR-head code. `e2e.yml` and `e2e-ok-to-test.yml` no longer use `pull_request_target` ([#9245](https://github.com/fullsend-ai/fullsend/issues/9245)): same-repository PRs run on `pull_request`, and fork PRs run only after a `/ok-to-test ` comment (`issue_comment`): - **Same-repository PRs** — the gate authorizes authors with write access (collaborator permission API) and trusted bots. Fork `pull_request` runs get no secrets, so `forgejo-behaviour` skips them. - **Fork PRs** — require a user with write access (Write role or above) to review the PR diff and comment `/ok-to-test `, naming the reviewed commit, including when the fork author has write access. The gate reads the comment from the API, checks the commenter's permission, and authorizes the PR head only when it is the named sha. Another head is refused (`stale_ok_to_test`), and a comment with no sha is refused (`missing_sha`). The gate uses no timing. The `ok-to-test` label no longer starts e2e. -- **Separation of concerns** — the gate (authorize/report) job runs on the base-branch checkout and is the only job with `pull-requests: write` and `checks: write`; it reports only the `forgejo-behaviour` check run on the authorized sha. The `forgejo-behaviour` job runs on the PR-head checkout with `contents: read` only. +- **Live runs on any PR** — `/ok-to-test live` passes the same gate, with no new rules, and also runs the live `behaviour` and `playback` jobs on PR-head code: the authorized sha, in the `dev` environment, with the same steps as the merge queue. The gate writes `live=true` only when it authorizes the run (`reason=ok_to_test`) and the first line ends in a lowercase `live`; any other word after the sha is refused as `missing_sha`. +- **Separation of concerns** — the gate (authorize/report) job runs on the base-branch checkout and is the only job with `pull-requests: write` and `checks: write`; it reports the `forgejo-behaviour` check run on the authorized sha, plus the non-required `behaviour-live` and `playback-live` check runs when `live` is true. It never reports the required `behaviour` and `playback` checks on a PR. The `forgejo-behaviour` job runs on the PR-head checkout with `contents: read` only. The live jobs add only the `id-token: write` permission (for GCP WIF and the mint) and use the same secrets as in the merge queue. **Limitations of the gate:** diff --git a/docs/guides/dev/e2e-testing.md b/docs/guides/dev/e2e-testing.md index 041daf1c0e..e01069a28f 100644 --- a/docs/guides/dev/e2e-testing.md +++ b/docs/guides/dev/e2e-testing.md @@ -112,7 +112,7 @@ Mint URL uses the hosted public endpoint by default (same as `fullsend github se ### Behaviour test GitHub Environments -The behaviour job in `e2e.yml` binds to GitHub Environments `dev` (the merge queue) and `stage` (push to `main`). It skips pull requests, `workflow_dispatch`, and other triggers. The job sets `ENVIRONMENT` to the same value for the suite (`dev` or `stage`). GitHub auto-creates those environments on first use. +The behaviour job in `e2e.yml` binds to GitHub Environments `dev` (the merge queue, and a pull request after `/ok-to-test live`) and `stage` (push to `main`). It skips other pull request runs, `workflow_dispatch`, and other triggers. The job sets `ENVIRONMENT` to the same value for the suite (`dev` or `stage`). GitHub auto-creates those environments on first use. The non-required `forgejo-behaviour` job uses the GitHub Environment `forgejo-stage` on pushes to `main` and `forgejo-dev` for authorized pull requests, the merge queue, and `/ok-to-test` runs for authorized fork pull requests. This separates mainline deployments in the Environments view; the job still sets `ENVIRONMENT=forgejo-dev` for every event because there is only one Forgejo driver target. It also sets `BEHAVIOUR_SCM=forgejo`, `BEHAVIOUR_CI=forgejoactions`, and `GODOG_TAGS=@forgejo`. The current job needs no GCP, Cloudflare, or actor credentials. GitHub creates each environment on first use. If future Forgejo-specific secrets are needed, configure them in both environments (or use appropriately scoped repository secrets) and add them to the artifact-redaction step before passing them to the test process. @@ -828,17 +828,20 @@ Pull requests from any author, forks included, run the behaviour and playback scenarios on the GitHub emulator ([`behaviour-github-emulator.yml`](../../../.github/workflows/behaviour-github-emulator.yml), required check `behaviour-github-emulator`) with no authorization. The live `behaviour` and `playback` jobs in `e2e.yml`, -which use repository secrets, run only in the merge queue and on push to -`main`; on a pull request they skip. The only `e2e.yml` suite that runs PR-head -code on a pull request is the optional `forgejo-behaviour` job, so a -**gate job** authorizes every PR run of it first (see workflow comments for -why it is a separate job). +which use repository secrets, run in the merge queue and on push to +`main`; on a pull request they skip unless a maintainer asks for them with +`/ok-to-test live` (see +[Run the live suites on a pull request](#run-the-live-suites-on-a-pull-request)). +Otherwise the only `e2e.yml` suite that runs PR-head code on a pull request is +the optional `forgejo-behaviour` job. A **gate job** authorizes every PR run of +these suites first (see workflow comments for why it is a separate job). | Path | Trigger | What runs | |---|---|---| | Same-repository PR | `pull_request` (opened, synchronize, reopened) | The gate authorizes the author, then `forgejo-behaviour` runs on the PR head; `behaviour` and `playback` skip | | Fork PR | `pull_request` | Nothing from `e2e.yml`: fork `pull_request` runs get no secrets, so all suites are skipped | | Fork PR after `/ok-to-test ` | `issue_comment` | The gate authorizes the commenter and the sha the comment names, then `forgejo-behaviour` runs on that sha and reports a check named `forgejo-behaviour` on it | +| Any PR after `/ok-to-test live` | `issue_comment` | The same gate as `/ok-to-test `. On that sha, `forgejo-behaviour` runs as above, and the live `behaviour` and `playback` jobs run in the `dev` environment and report the non-required checks `behaviour-live` and `playback-live` | | Merge queue, push to `main`, `workflow_dispatch` | unchanged | No gate; `behaviour` and `playback` run live | A same-repository `pull_request` run takes `e2e.yml` from the PR merge ref, not @@ -857,7 +860,9 @@ automatically. ### Who needs `/ok-to-test` -`/ok-to-test` is needed only for the optional `forgejo-behaviour` suite. Every +`/ok-to-test` is needed only for the optional `forgejo-behaviour` suite, and +`/ok-to-test live` for an optional live run (see +[Run the live suites on a pull request](#run-the-live-suites-on-a-pull-request)). Every PR, forks included, runs the required `behaviour-github-emulator` check without it. @@ -895,6 +900,53 @@ runs. A bare `/ok-to-test` with no sha runs nothing either. Any later push needs a new `/ok-to-test ` from a user with write access after reviewing the new changes. +### Run the live suites on a pull request + +Pull requests run `behaviour` and `playback` on the GitHub emulator only. The +live suites otherwise first run in the merge queue, and a failure there drops +the entry and rebuilds every entry behind it. Ask for a live run before the PR +is enqueued when the change needs something only the live suites cover: + +- the real-model scenarios (Claude, Codex, pi, OpenCode, the inference + gateway), for example a PR that bumps a runtime or changes the gateway; +- the deployed mint and real App installations and permissions; +- anything else that only real GitHub shows. + +A live run takes a `dev` pool org for up to 90 minutes, as a merge queue entry +does. Ask for one only when the PR needs it. + +To ask, a user with write access reviews the latest push and comments, on the +first line: + +```text +/ok-to-test live +``` + +`live` is one lowercase word after the sha. It passes the same gate as +`/ok-to-test `: write access, the command on the first line, and a PR head +that is the named sha. It works on fork and same-repository PRs. Any other +word after the sha (`LIVE`, `live please`, or `live` before the sha) is +refused as `missing_sha`, and nothing runs. + +When the gate authorizes the comment, these checks appear on the named sha. +Wait for them in the PR's **Checks** tab: + +| Check | What runs | +|---|---| +| `forgejo-behaviour` | The Forgejo suite, as for `/ok-to-test ` | +| `behaviour-live` | The live `behaviour` job, in the `dev` environment, with the same steps as the merge queue | +| `playback-live` | The live `playback` job, in the `dev` environment, with the same steps as the merge queue | + +The live checks are **not required**, and they have their own names on +purpose. The PR's required `behaviour` and `playback` checks still report as +skipped, and the merge queue still runs them. A live run adds information +before the PR is enqueued; it never stands in for a required check or blocks +the merge. + +The live jobs keep the behaviour relevance filter: on a PR with no +behaviour-relevant change, `behaviour-live` reports success without running +scenarios. + ### Blocked runs When the gate **runs** and denies authorization, a sticky PR comment (marker @@ -907,7 +959,7 @@ The comment names a reason. What to do next: |---|---| | `untrusted_commenter` | The person who commented `/ok-to-test` does not have write access (for example a Triage user). Do not repeat it yourself. Ask a reviewer on this PR, or a maintainer listed in [MAINTAINERS.md](../../../MAINTAINERS.md), to comment `/ok-to-test ` after reviewing the latest push. | | `stale_ok_to_test` | The comment named a commit that is not the PR head, usually because of a push after the review. A user with write access reviews the changes and comments `/ok-to-test ` with the current head sha. | -| `missing_sha` | The comment did not name a commit on its first line (for example a bare `/ok-to-test`). A user with write access comments `/ok-to-test ` with the full sha of the commit they reviewed. The gate comment shows the current head; review it before naming it. | +| `missing_sha` | The comment did not name a commit on its first line (for example a bare `/ok-to-test`), or had a word after the sha other than a lowercase `live`. A user with write access comments `/ok-to-test `, or `/ok-to-test live` for the live suites, with the full sha of the commit they reviewed. The gate comment shows the current head; review it before naming it. | | `error` | The GitHub API failed during the check. Re-run the workflow. | | `unauthorized` | The author of a same-repository PR does not have write access. Ask a user with write access to review the PR and comment `/ok-to-test `. If you do have write access, the permission lookup may have failed: re-run the workflow first. | @@ -928,10 +980,15 @@ the "How to check" links in [LADDER.md](../../../LADDER.md). that sha. Only the authorize/report job holds `checks: write` and `pull-requests: write`; it creates the `forgejo-behaviour` check run on the head sha and completes it from the suite result. -3. **Gate** — base checkout only; never checks out PR head +3. **`/ok-to-test live` comment** — the same workflow and gate. When + the gate writes `live=true`, the authorize job also creates the + `behaviour-live` and `playback-live` check runs on the head sha, passes + `live` to the suite, and the report job completes both checks from the + `behaviour` and `playback` results. +4. **Gate** — base checkout only; never checks out PR head ([`scripts/check-e2e-authorization.sh`](../../../scripts/check-e2e-authorization.sh)). -4. **Behaviour / playback** — never on a pull request; - `contents: read` and `id-token: write` only; +5. **Behaviour / playback** — on a pull request only after + `/ok-to-test live`; `contents: read` and `id-token: write` only; checkout the commit under test, authenticate to GCP via WIF, mint cross-org tokens per pool org, `make behaviour-test` (or `make playback-test` for the playback job) diff --git a/scripts/check-e2e-authorization-test.sh b/scripts/check-e2e-authorization-test.sh index 4d00be64c6..b82d963903 100755 --- a/scripts/check-e2e-authorization-test.sh +++ b/scripts/check-e2e-authorization-test.sh @@ -169,11 +169,14 @@ run_case() { auth="$(grep -o 'authorized=[^ ]*' <<<"${output}" | cut -d= -f2)" reason="$(grep -o 'reason=[^ ]*' <<<"${output}" | cut -d= -f2)" removed="$(grep -o 'label_removed=[^ ]*' <<<"${output}" | cut -d= -f2)" + local live + live="$(grep -o ' live=[^ ]*' <<<"${output}" | cut -d= -f2)" - if [[ "${auth}" != "${expected_auth}" || "${reason}" != "${expected_reason}" || "${removed}" != "${expected_removed}" ]]; then + # Only an authorized `/ok-to-test live` comment sets live=true. + if [[ "${auth}" != "${expected_auth}" || "${reason}" != "${expected_reason}" || "${removed}" != "${expected_removed}" || "${live}" != "false" ]]; then echo "FAIL: ${name}" - echo " expected authorized=${expected_auth} reason=${expected_reason} label_removed=${expected_removed}" - echo " got authorized=${auth} reason=${reason} label_removed=${removed}" + echo " expected authorized=${expected_auth} reason=${expected_reason} label_removed=${expected_removed} live=false" + echo " got authorized=${auth} reason=${reason} label_removed=${removed} live=${live}" FAILURES=$((FAILURES + 1)) return fi @@ -509,18 +512,21 @@ write_comment() { }' >"${COMMENT_JSON}" } +# run_cmd_case NAME AUTHORIZED REASON HEAD_SHA [LIVE]; LIVE defaults to false. run_cmd_case() { local name="$1" expected_auth="$2" expected_reason="$3" expected_sha="$4" + local expected_live="${5:-false}" : >"${GH_LOG}" - local output auth reason sha + local output auth reason sha live output="$("${AUTH_SCRIPT}" 42 "fullsend-ai/fullsend")" auth="$(grep -o 'authorized=[^ ]*' <<<"${output}" | cut -d= -f2)" reason="$(grep -o 'reason=[^ ]*' <<<"${output}" | cut -d= -f2)" sha="$(grep -o 'head_sha=[^ ]*' <<<"${output}" | cut -d= -f2)" - if [[ "${auth}" != "${expected_auth}" || "${reason}" != "${expected_reason}" || "${sha}" != "${expected_sha}" ]]; then + live="$(grep -o ' live=[^ ]*' <<<"${output}" | cut -d= -f2)" + if [[ "${auth}" != "${expected_auth}" || "${reason}" != "${expected_reason}" || "${sha}" != "${expected_sha}" || "${live}" != "${expected_live}" ]]; then echo "FAIL: ${name}" - echo " expected authorized=${expected_auth} reason=${expected_reason} head_sha=${expected_sha}" - echo " got authorized=${auth} reason=${reason} head_sha=${sha}" + echo " expected authorized=${expected_auth} reason=${expected_reason} head_sha=${expected_sha} live=${expected_live}" + echo " got authorized=${auth} reason=${reason} head_sha=${sha} live=${live}" FAILURES=$((FAILURES + 1)) return fi @@ -620,6 +626,47 @@ run_logged_cmd_case "old head sha after a push to a look-alike commit is stale" write_cmd_pr write_comment "/ok-to-test ${HEAD_SHA}" +# `/ok-to-test live` asks for the live suites; the gate is unchanged. +run_logged_cmd_case "plain /ok-to-test is not live" "true" "ok_to_test" "${HEAD_SHA}" "false" +write_comment "/ok-to-test ${HEAD_SHA} live" +run_logged_cmd_case "/ok-to-test live authorizes live" "true" "ok_to_test" "${HEAD_SHA}" "true" +LIVE_OUTPUT="${TMPDIR}/github-output" +: >"${LIVE_OUTPUT}" +GITHUB_OUTPUT="${LIVE_OUTPUT}" "${AUTH_SCRIPT}" 42 "fullsend-ai/fullsend" >/dev/null +if grep -qx 'live=true' "${LIVE_OUTPUT}" && grep -qx 'authorized=true' "${LIVE_OUTPUT}"; then + echo "PASS: /ok-to-test live writes live=true to GITHUB_OUTPUT" +else + echo "FAIL: /ok-to-test live writes live=true to GITHUB_OUTPUT" + sed 's/^/ /' "${LIVE_OUTPUT}" + FAILURES=$((FAILURES + 1)) +fi +write_comment "/ok-to-test ${HEAD_SHA} live " +run_logged_cmd_case "extra spaces around live authorize live" "true" "ok_to_test" "${HEAD_SHA}" "true" +write_comment "/ok-to-test ${HEAD_SHA} live"$'\r\n'"Reviewed the diff." +run_logged_cmd_case "CRLF line ending after live authorizes live" "true" "ok_to_test" "${HEAD_SHA}" "true" +write_comment "/ok-to-test ${HEAD_SHA}"$'\n'"live" +run_logged_cmd_case "live on the second line is not live" "true" "ok_to_test" "${HEAD_SHA}" "false" +write_comment "/ok-to-test ${HEAD_SHA} LIVE" +run_logged_cmd_case "uppercase LIVE is missing_sha" "false" "missing_sha" "${HEAD_SHA}" "false" +write_comment "/ok-to-test ${HEAD_SHA} live please" +run_logged_cmd_case "a word after live is missing_sha" "false" "missing_sha" "${HEAD_SHA}" "false" +write_comment "/ok-to-test ${HEAD_SHA}live" +run_logged_cmd_case "live without a space before it is missing_sha" "false" "missing_sha" "${HEAD_SHA}" "false" +write_comment "/ok-to-test live ${HEAD_SHA}" +run_logged_cmd_case "live before the sha is missing_sha" "false" "missing_sha" "${HEAD_SHA}" "false" +write_comment "/ok-to-test ${HEAD_SHA:0:7} live" +run_logged_cmd_case "short sha with live is missing_sha" "false" "missing_sha" "${HEAD_SHA}" "false" +write_comment "/ok-to-test ${OTHER_SHA} live" +run_logged_cmd_case "live on a stale sha is not live" "false" "stale_ok_to_test" "${HEAD_SHA}" "false" +write_comment "/ok-to-test ${HEAD_SHA} live" +set_role "maint" "triage" +run_logged_cmd_case "live from triage commenter is not live" "false" "untrusted_commenter" "" "false" +set_role "maint" "write" +export GH_FAIL="pulls" +run_logged_cmd_case "live with PR API failure is not live" "false" "error" "" "false" +export GH_FAIL="false" +write_comment "/ok-to-test ${HEAD_SHA}" + # Comment identity comes from the API by id. write_comment "/ok-to-test ${HEAD_SHA}" "someone-else" run_logged_cmd_case "comment by another user fails closed" "false" "error" "" diff --git a/scripts/check-e2e-authorization.sh b/scripts/check-e2e-authorization.sh index 62cf6c65c7..f21c394b63 100755 --- a/scripts/check-e2e-authorization.sh +++ b/scripts/check-e2e-authorization.sh @@ -29,6 +29,12 @@ # script runs, equals the named sha. Any other head means the # PR changed since the review (reason=stale_ok_to_test). No timing is used. # +# `/ok-to-test live` asks for the live behaviour and playback suites as +# well. The optional lowercase word `live` after the sha passes the same gate; +# any other word after the sha is reason=missing_sha. The live output is true +# only when the run is authorized (reason=ok_to_test) and the comment asked +# for `live`; every other path, the error path included, writes live=false. +# # Usage: check-e2e-authorization.sh PR_NUMBER OWNER/REPO # # Environment (optional, from workflow): @@ -44,10 +50,10 @@ # comment and its body are read from the API; it must belong to # PR_NUMBER and to COMMENTER_LOGIN. # -# Writes authorized, reason, label_removed and head_sha to GITHUB_OUTPUT when -# set. head_sha is the current PR head in /ok-to-test mode once the commenter -# passes the role check, and empty otherwise. Exits 0 always; callers inspect -# outputs. +# Writes authorized, reason, label_removed, head_sha and live to GITHUB_OUTPUT +# when set. head_sha is the current PR head in /ok-to-test mode once the +# commenter passes the role check, and empty otherwise. Exits 0 always; callers +# inspect outputs. set -euo pipefail @@ -65,9 +71,10 @@ write_error_output() { echo "reason=error" echo "label_removed=false" echo "head_sha=" + echo "live=false" } >>"${GITHUB_OUTPUT}" fi - printf 'authorized=false reason=error label_removed=false head_sha=\n' + printf 'authorized=false reason=error label_removed=false head_sha= live=false\n' } write_outputs() { @@ -77,10 +84,11 @@ write_outputs() { echo "reason=${reason}" echo "label_removed=${label_removed}" echo "head_sha=${head_sha}" + echo "live=${live}" } >>"${GITHUB_OUTPUT}" fi - printf 'authorized=%s reason=%s label_removed=%s head_sha=%s\n' \ - "${authorized}" "${reason}" "${label_removed}" "${head_sha}" + printf 'authorized=%s reason=%s label_removed=%s head_sha=%s live=%s\n' \ + "${authorized}" "${reason}" "${label_removed}" "${head_sha}" "${live}" } trap 'write_error_output; exit 0' ERR @@ -178,6 +186,7 @@ label_removed=false authorized=false reason="unauthorized" head_sha="" +live=false # --- /ok-to-test command mode ------------------------------------------------- # Kept at top level (not in a function) so the ERR trap covers every API call. @@ -214,9 +223,13 @@ if [[ "${EVENT_NAME:-}" == "issue_comment" ]]; then else first_line="${comment_body%%$'\n'*}" first_line="${first_line%$'\r'}" - ok_to_test_re='^/ok-to-test[[:space:]]+([0-9a-fA-F]{40})[[:space:]]*$' + ok_to_test_re='^/ok-to-test[[:space:]]+([0-9a-fA-F]{40})([[:space:]]+live)?[[:space:]]*$' named_sha="" + wants_live=false if [[ "${first_line}" =~ ${ok_to_test_re} ]]; then + if [[ -n "${BASH_REMATCH[2]}" ]]; then + wants_live=true + fi named_sha="$(tr '[:upper:]' '[:lower:]' <<<"${BASH_REMATCH[1]}")" fi @@ -228,6 +241,7 @@ if [[ "${EVENT_NAME:-}" == "issue_comment" ]]; then elif [[ "${head_sha}" == "${named_sha}" ]]; then authorized=true reason="ok_to_test" + live="${wants_live}" else # The head is not the commit the maintainer reviewed. reason="stale_ok_to_test" From bcde0ea33aa2a7498dd681b64bf741ac5373ac05 Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:43:24 +0000 Subject: [PATCH 020/208] fix(#9759): fetch ONNX Runtime from NuGet in the runner image The runner image has not built since 2026-11-18, so fullsend-runner:0.57.0 was never published: the ONNX Runtime GitHub release tarballs it downloaded now return 404 along with the whole github.com/microsoft/onnxruntime repository. images/runner/Containerfile now takes libonnxruntime.so from Microsoft's official Microsoft.ML.OnnxRuntime NuGet package, bumped to 1.32.0 at the maintainer's request (still >= the ORT C API 28 that onnxruntime_go requests). The .nupkg is a zip that carries both architectures, so the per-arch ORT_SHA256_{AMD64,ARM64} pins become one ORT_SHA256. It is still verified with sha256sum -c, and python3 then extracts runtimes/linux-{x64,arm64}/native/libonnxruntime.so to /usr/lib/libonnxruntime.so.${ORT_VERSION}. The existing symlinks are kept. Renovate tracking moves to the nuget datasource (Microsoft.ML.OnnxRuntime, no v-prefix extraction), and its postUpgradeTasks rule matches the new dep name. update-ort-checksums.sh now uses lib-checksums.sh single mode against the NuGet package URL. NuGet publishes no sha256, so the hash is computed from the HTTPS download (ALLOW_UNPUBLISHED, like gcloud). The ORT case in update-pin-checksums-test.sh and the images/README.md pin table are updated to match. Note: the sandbox cannot reach api.nuget.org, so the ORT_SHA256 value comes from the issue comment and was not recomputed here; the image build's sha256sum -c step verifies it. pre-commit could not fetch hook repos (TLS failure); the applicable hooks (check-json, whitespace/EOF/line-ending, merge-conflict, private-key, gitleaks via scan-secrets, shellcheck 0.10.0.1, lychee, broken symlinks) were run directly and passed. Closes #9759 Co-Authored-By: Claude Opus 5.5 --- images/README.md | 2 +- images/runner/Containerfile | 32 +++++++++++-------- renovate.json | 11 +++---- scripts/renovate/update-ort-checksums.sh | 28 ++++++++-------- scripts/renovate/update-pin-checksums-test.sh | 2 +- 5 files changed, 41 insertions(+), 34 deletions(-) diff --git a/images/README.md b/images/README.md index 0c9b109fb9..5b63652a93 100644 --- a/images/README.md +++ b/images/README.md @@ -147,7 +147,7 @@ Every binary downloaded during the build is **version-pinned** and | Tool | Pinning | Verification | |------|---------|-------------| | OpenShell base image | Manifest list digest (`@sha256:...`) | Immutable OCI content hash | -| ONNX Runtime (runner) | `ORT_VERSION` + `ORT_SHA256_{AMD64,ARM64}` | `sha256sum -c` | +| ONNX Runtime (runner) | `ORT_VERSION` + `ORT_SHA256` of the `Microsoft.ML.OnnxRuntime` NuGet package (both arches in one `.nupkg`) | `sha256sum -c` | | ProtectAI DeBERTa model (runner) | `PROTECTAI_MODEL_REV` + per-file SHA256 | `sha256sum -c` | | libtokenizers (runner) | `TOKENIZERS_VERSION` + `TOKENIZERS_SHA256_{AMD64,ARM64}` | `sha256sum -c` | | Gitleaks | `GITLEAKS_VERSION` + `GITLEAKS_SHA256_{AMD64,ARM64}` | `sha256sum -c` | diff --git a/images/runner/Containerfile b/images/runner/Containerfile index 12055e8adb..fe610a9428 100644 --- a/images/runner/Containerfile +++ b/images/runner/Containerfile @@ -286,26 +286,32 @@ RUN pip install --no-cache-dir --break-system-packages \ # # Must be >= 1.28: onnxruntime_go v1.32.0 requests ORT C API version 28, and # older runtimes refuse with "requested API version [28] is not available". -# To update: bump ORT_VERSION and ORT_SHA256_{AMD64,ARM64} from: -# https://github.com/microsoft/onnxruntime/releases -ARG ORT_VERSION=1.28.1 -ARG ORT_SHA256_AMD64=2529aef968d0ad0603365054bc46ebefa7f0fe3bc12f28c5f729c99ddffe2a81 -ARG ORT_SHA256_ARM64=53bab9a5c6ae198b7be75663b780c64caa388d30257fac458c71fbff0a82e98e +# +# Taken from Microsoft's official Microsoft.ML.OnnxRuntime NuGet package, +# not the GitHub release tarballs: github.com/microsoft/onnxruntime answers +# 404 (#9759). One .nupkg (a zip) carries both architectures under +# runtimes/linux-{x64,arm64}/native/, so a single ORT_SHA256 covers it; +# python3 (installed above) extracts the one library needed. +# To update: bump ORT_VERSION and ORT_SHA256 (sha256 of the .nupkg) from: +# https://www.nuget.org/packages/Microsoft.ML.OnnxRuntime +ARG ORT_VERSION=1.32.0 +ARG ORT_SHA256=a9150bc2992cbbb6722070da9910e1ffa989a8bfc67bdd5bb8e745ca755641db RUN case "$TARGETARCH" in \ - amd64) ORT_ARCH="x64"; ORT_SHA="$ORT_SHA256_AMD64" ;; \ - arm64) ORT_ARCH="aarch64"; ORT_SHA="$ORT_SHA256_ARM64" ;; \ + amd64) ORT_RID="linux-x64" ;; \ + arm64) ORT_RID="linux-arm64" ;; \ *) echo "unsupported TARGETARCH=$TARGETARCH" >&2; exit 1 ;; \ esac \ && curl -fsSL --retry 3 --retry-delay 5 \ - "https://github.com/microsoft/onnxruntime/releases/download/v${ORT_VERSION}/onnxruntime-linux-${ORT_ARCH}-${ORT_VERSION}.tgz" \ - -o /tmp/ort.tgz \ - && echo "${ORT_SHA} /tmp/ort.tgz" | sha256sum -c - \ - && tar xzf /tmp/ort.tgz -C /tmp/ \ - && cp "/tmp/onnxruntime-linux-${ORT_ARCH}-${ORT_VERSION}/lib/libonnxruntime.so.${ORT_VERSION}" /usr/lib/ \ + "https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/${ORT_VERSION}/microsoft.ml.onnxruntime.${ORT_VERSION}.nupkg" \ + -o /tmp/ort.nupkg \ + && echo "${ORT_SHA256} /tmp/ort.nupkg" | sha256sum -c - \ + && python3 -c 'import shutil, sys, zipfile; src = zipfile.ZipFile(sys.argv[1]).open(sys.argv[2]); shutil.copyfileobj(src, open(sys.argv[3], "wb"))' \ + /tmp/ort.nupkg "runtimes/${ORT_RID}/native/libonnxruntime.so" "/usr/lib/libonnxruntime.so.${ORT_VERSION}" \ + && chmod 0755 "/usr/lib/libonnxruntime.so.${ORT_VERSION}" \ && ln -sf "/usr/lib/libonnxruntime.so.${ORT_VERSION}" /usr/lib/libonnxruntime.so \ && ln -sf "/usr/lib/libonnxruntime.so.${ORT_VERSION}" /usr/lib/libonnxruntime.so.1 \ && /sbin/ldconfig \ - && rm -rf /tmp/ort.tgz "/tmp/onnxruntime-linux-${ORT_ARCH}-${ORT_VERSION}" + && rm -f /tmp/ort.nupkg # --------------------------------------------------------------------------- # ProtectAI DeBERTa-v3 ONNX model, loaded by the ORT-enabled binary from the diff --git a/renovate.json b/renovate.json index 5d48ee6086..6951cc90c8 100644 --- a/renovate.json +++ b/renovate.json @@ -207,8 +207,8 @@ } }, { - "description": "After an ONNX Runtime bump, refresh ORT_SHA256_{AMD64,ARM64} in the runner Containerfile. ONNX Runtime ships no checksum file, so the download is checked against the digest GitHub records for each release asset (#9121)", - "matchPackageNames": ["microsoft/onnxruntime"], + "description": "After an ONNX Runtime bump, refresh ORT_SHA256 in the runner Containerfile from the sha256 of the Microsoft.ML.OnnxRuntime NuGet package (#9121, #9759)", + "matchPackageNames": ["Microsoft.ML.OnnxRuntime"], "postUpgradeTasks": { "commands": ["bash scripts/renovate/update-ort-checksums.sh"], "fileFilters": ["images/runner/Containerfile"], @@ -488,14 +488,13 @@ }, { "customType": "regex", - "description": "Track the ONNX Runtime pin in the runner image (must stay >= the ORT C API version onnxruntime_go requests; see the Containerfile comment). ORT_SHA256_{AMD64,ARM64} are updated automatically by postUpgradeTasks (scripts/renovate/update-ort-checksums.sh).", + "description": "Track the ONNX Runtime pin in the runner image (must stay >= the ORT C API version onnxruntime_go requests; see the Containerfile comment). The library comes from the Microsoft.ML.OnnxRuntime NuGet package since github.com/microsoft/onnxruntime went 404 (#9759). ORT_SHA256 is updated automatically by postUpgradeTasks (scripts/renovate/update-ort-checksums.sh).", "managerFilePatterns": ["/^images/runner/Containerfile$/"], "matchStrings": [ "ARG ORT_VERSION=(?\\d+\\.\\d+\\.\\d+)" ], - "depNameTemplate": "microsoft/onnxruntime", - "datasourceTemplate": "github-releases", - "extractVersionTemplate": "^v(?\\d+\\.\\d+\\.\\d+)$" + "depNameTemplate": "Microsoft.ML.OnnxRuntime", + "datasourceTemplate": "nuget" }, { "customType": "regex", diff --git a/scripts/renovate/update-ort-checksums.sh b/scripts/renovate/update-ort-checksums.sh index 02ffaeb69a..f0cc5ac20a 100755 --- a/scripts/renovate/update-ort-checksums.sh +++ b/scripts/renovate/update-ort-checksums.sh @@ -1,20 +1,22 @@ #!/usr/bin/env bash -# Called by Renovate postUpgradeTasks after a microsoft/onnxruntime bump. -# ONNX Runtime ships no checksum file, so the linux CPU release tarballs are -# checked against the sha256 digest GitHub records for each release asset. -# Updates ORT_SHA256_{AMD64,ARM64} in the runner Containerfile. +# Called by Renovate postUpgradeTasks after a Microsoft.ML.OnnxRuntime bump. +# The runner image takes libonnxruntime.so from Microsoft's official NuGet +# package (github.com/microsoft/onnxruntime answers 404, #9759). One .nupkg +# carries both architectures, so this updates the single ORT_SHA256 in the +# runner Containerfile. +# +# NuGet publishes no sha256 for a package (its catalog records only a +# base64 SHA512 packageHash), so the hash is computed from the HTTPS +# download from api.nuget.org. set -euo pipefail source "$(dirname "${BASH_SOURCE[0]}")/lib-checksums.sh" +# shellcheck disable=SC2034 # read by update_pin in lib-checksums.sh +ALLOW_UNPUBLISHED=1 + asset_url() { - local arch - case "$1" in - AMD64) arch="x64" ;; - ARM64) arch="aarch64" ;; - *) return 1 ;; - esac - echo "https://github.com/microsoft/onnxruntime/releases/download/v${VERSION}/onnxruntime-linux-${arch}-${VERSION}.tgz" + echo "https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/${VERSION}/microsoft.ml.onnxruntime.${VERSION}.nupkg" } -published_sha() { github_asset_digest microsoft/onnxruntime "v${VERSION}" "${2##*/}"; } +published_sha() { :; } -update_pin ORT multi images/runner/Containerfile +update_pin ORT single images/runner/Containerfile diff --git a/scripts/renovate/update-pin-checksums-test.sh b/scripts/renovate/update-pin-checksums-test.sh index 7a32077583..0d586e41b1 100755 --- a/scripts/renovate/update-pin-checksums-test.sh +++ b/scripts/renovate/update-pin-checksums-test.sh @@ -202,7 +202,7 @@ CASES=( "update-gitsign-checksums.sh|GITSIGN|multi|images/code/Containerfile|9.1.0|https://github.com/sigstore/gitsign/releases/download/v9.1.0/gitsign_9.1.0_linux_amd64|https://github.com/sigstore/gitsign/releases/download/v9.1.0/gitsign_9.1.0_linux_arm64|checksums:https://github.com/sigstore/gitsign/releases/download/v9.1.0/checksums.txt" "update-lychee-checksums.sh|LYCHEE|multi|images/code/Containerfile|9.1.0|https://github.com/lycheeverse/lychee/releases/download/lychee-v9.1.0/lychee-x86_64-unknown-linux-gnu.tar.gz|https://github.com/lycheeverse/lychee/releases/download/lychee-v9.1.0/lychee-aarch64-unknown-linux-gnu.tar.gz|sha256" "update-opencode-checksums.sh|OPENCODE|multi|images/sandbox/Containerfile|9.1.0|https://github.com/anomalyco/opencode/releases/download/v9.1.0/opencode-linux-x64.tar.gz|https://github.com/anomalyco/opencode/releases/download/v9.1.0/opencode-linux-arm64.tar.gz|digest:anomalyco/opencode:v9.1.0" - "update-ort-checksums.sh|ORT|multi|images/runner/Containerfile|9.1.0|https://github.com/microsoft/onnxruntime/releases/download/v9.1.0/onnxruntime-linux-x64-9.1.0.tgz|https://github.com/microsoft/onnxruntime/releases/download/v9.1.0/onnxruntime-linux-aarch64-9.1.0.tgz|digest:microsoft/onnxruntime:v9.1.0" + "update-ort-checksums.sh|ORT|single|images/runner/Containerfile|9.1.0|https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/9.1.0/microsoft.ml.onnxruntime.9.1.0.nupkg||none" ) # publish — serve the published checksums for URLS/SHAS. From 57a041eb577d977886852668dafbd1b74e919fa3 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 20 Nov 2026 14:44:08 -0500 Subject: [PATCH 021/208] ci(e2e): run live behaviour and playback on `/ok-to-test live` The gate action passes the script's live output through. When an authorized comment asks for live, e2e-ok-to-test.yml creates and completes behaviour-live and playback-live check runs on the named sha and calls e2e.yml with live: true; the behaviour and playback jobs run for that issue_comment call, as in the merge queue. The new check names are not required, so the required behaviour and playback checks are unchanged. Refs #9757 Assisted-by: Claude Signed-off-by: Wayne Sun --- .../check-e2e-authorization/action.yml | 7 +++- .github/workflows/e2e-ok-to-test.yml | 35 ++++++++++++++++--- .github/workflows/e2e.yml | 25 ++++++++----- 3 files changed, 54 insertions(+), 13 deletions(-) diff --git a/.github/actions/check-e2e-authorization/action.yml b/.github/actions/check-e2e-authorization/action.yml index fdcc1fc6fc..d0398855c5 100644 --- a/.github/actions/check-e2e-authorization/action.yml +++ b/.github/actions/check-e2e-authorization/action.yml @@ -65,6 +65,11 @@ outputs: PR head sha a /ok-to-test comment authorized or refused (empty for an untrusted commenter and in other modes) value: ${{ steps.check.outputs.head_sha }} + live: + description: >- + true when an authorized comment was `/ok-to-test live`, asking for + the live behaviour and playback suites as well + value: ${{ steps.check.outputs.live }} runs: using: composite @@ -119,7 +124,7 @@ runs: " ;; issue_comment:missing_sha) - body+="\`/ok-to-test\` must name the commit you reviewed, as its full 40-character sha: \`/ok-to-test \`. The PR head is now \`${HEAD_SHA}\`; if that is not the commit you reviewed, review it first. A later push needs a new comment. + body+="\`/ok-to-test\` must name the commit you reviewed, as its full 40-character sha: \`/ok-to-test \`, or \`/ok-to-test live\` to run the live suites too. The PR head is now \`${HEAD_SHA}\`; if that is not the commit you reviewed, review it first. A later push needs a new comment. " ;; issue_comment:untrusted_commenter) diff --git a/.github/workflows/e2e-ok-to-test.yml b/.github/workflows/e2e-ok-to-test.yml index 41c237ece8..a0ac04f44c 100644 --- a/.github/workflows/e2e-ok-to-test.yml +++ b/.github/workflows/e2e-ok-to-test.yml @@ -14,6 +14,11 @@ name: E2E ok-to-test # write scopes; the suite jobs that run PR code never do (gh-aw's safe-outputs # split). # +# `/ok-to-test live` also runs the live behaviour and playback jobs for +# that sha, as the merge queue does, and reports them as behaviour-live and +# playback-live. Those names are not required checks, so a live run on a PR +# never stands in for, or blocks on, the required behaviour and playback. +# # No caller-level concurrency: e2e.yml queues /ok-to-test runs in its own # e2e-ok-to-test-{n} group, and sharing a group with the callee deadlocks. @@ -39,6 +44,9 @@ jobs: outputs: authorized: ${{ steps.auth.outputs.authorized }} head_sha: ${{ steps.auth.outputs.head_sha }} + live: ${{ steps.auth.outputs.live }} + behaviour_live_check_id: ${{ steps.checks.outputs.behaviour_live }} + playback_live_check_id: ${{ steps.checks.outputs.playback_live }} forgejo_behaviour_check_id: ${{ steps.checks.outputs.forgejo_behaviour }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -72,12 +80,16 @@ jobs: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} HEAD_SHA: ${{ steps.auth.outputs.head_sha }} + LIVE: ${{ steps.auth.outputs.live }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | set -euo pipefail # Behaviour and playback run on a GitHub emulator for every pull - # request (behaviour-github-emulator.yml), so /ok-to-test runs only Forgejo. - for name in forgejo-behaviour; do + # request (behaviour-github-emulator.yml), so /ok-to-test runs only + # Forgejo, plus the live suites when the comment asked for them. + names=(forgejo-behaviour) + [[ "${LIVE}" == "true" ]] && names+=(behaviour-live playback-live) + for name in "${names[@]}"; do id=$(gh api -X POST "repos/${REPO}/check-runs" \ -f name="${name}" -f head_sha="${HEAD_SHA}" -f status=in_progress \ -f details_url="${RUN_URL}" \ @@ -86,6 +98,8 @@ jobs: --jq .id) case "${name}" in forgejo-behaviour) key=forgejo_behaviour ;; + behaviour-live) key=behaviour_live ;; + playback-live) key=playback_live ;; *) key=${name} ;; esac echo "${key}=${id}" >> "$GITHUB_OUTPUT" @@ -98,9 +112,12 @@ jobs: REPO: ${{ github.repository }} PR_NUMBER: ${{ github.event.issue.number }} HEAD_SHA: ${{ steps.auth.outputs.head_sha }} + LIVE: ${{ steps.auth.outputs.live }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | - body="E2E authorized for \`${HEAD_SHA}\` ([run](${RUN_URL})). A new push needs a new \`/ok-to-test \`." + suites="" + [[ "${LIVE}" == "true" ]] && suites=", with the live behaviour and playback suites" + body="E2E authorized for \`${HEAD_SHA}\`${suites} ([run](${RUN_URL})). A new push needs a new \`/ok-to-test \`." gh api -X POST "repos/${REPO}/issues/${PR_NUMBER}/comments" -f body="${body}" --silent run: @@ -117,6 +134,7 @@ jobs: with: pr_number: ${{ github.event.issue.number }} head_sha: ${{ needs.authorize.outputs.head_sha }} + live: ${{ needs.authorize.outputs.live == 'true' }} secrets: inherit report: @@ -127,13 +145,18 @@ jobs: permissions: checks: write steps: - - name: Complete the Forgejo behaviour check + - name: Complete the E2E checks env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} RUN_RESULT: ${{ needs.run.result }} FORGEJO_BEHAVIOUR_ID: ${{ needs.authorize.outputs.forgejo_behaviour_check_id }} FORGEJO_BEHAVIOUR_RESULT: ${{ needs.run.outputs.forgejo_behaviour_result }} + LIVE: ${{ needs.authorize.outputs.live }} + BEHAVIOUR_LIVE_ID: ${{ needs.authorize.outputs.behaviour_live_check_id }} + BEHAVIOUR_LIVE_RESULT: ${{ needs.run.outputs.behaviour_result }} + PLAYBACK_LIVE_ID: ${{ needs.authorize.outputs.playback_live_check_id }} + PLAYBACK_LIVE_RESULT: ${{ needs.run.outputs.playback_result }} RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | set -euo pipefail @@ -147,6 +170,10 @@ jobs: } status=0 pairs=("forgejo-behaviour:${FORGEJO_BEHAVIOUR_ID}:${FORGEJO_BEHAVIOUR_RESULT}") + if [[ "${LIVE}" == "true" ]]; then + pairs+=("behaviour-live:${BEHAVIOUR_LIVE_ID}:${BEHAVIOUR_LIVE_RESULT}") + pairs+=("playback-live:${PLAYBACK_LIVE_ID}:${PLAYBACK_LIVE_RESULT}") + fi for pair in "${pairs[@]}"; do IFS=: read -r name id result <<<"${pair}" [[ -n "${id}" ]] || { echo "::error::no ${name} check run id"; status=1; continue; } diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 6bb66ee595..dab3ab6859 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -72,6 +72,11 @@ on: description: PR head sha the comment authorized (checked out by each test job) type: string required: true + live: + description: The comment was `/ok-to-test live`; also run live behaviour and playback + type: boolean + required: false + default: false outputs: behaviour_result: description: behaviour job status (success, failure or cancelled) @@ -137,10 +142,11 @@ jobs: group: ${{ github.workflow }}-${{ github.run_id }}-${{ github.event_name == 'push' && 'stage-org' || 'behaviour-dev' }} cancel-in-progress: false # Gate authorization protects checkout of untrusted PR-head code with secrets. - # Runs only on merge_group (required check; treated as PR-class / dev) - # and push to main (stage). Pull requests run behaviour-github-emulator.yml - # instead; this job skips there, which the required check accepts. - # Skip workflow_dispatch. + # Runs on merge_group (required check; treated as PR-class / dev), push to + # main (stage), and an authorized `/ok-to-test live` (dev; reported + # by e2e-ok-to-test.yml as behaviour-live). Pull requests run + # behaviour-github-emulator.yml instead; this job skips there, which the + # required check accepts. Skip workflow_dispatch. # Environment uses event_name, not github.ref: pull_request sets # github.ref to refs/pull/N/merge and issue_comment to the default branch. needs: gate @@ -148,7 +154,8 @@ jobs: !cancelled() && ( (github.event_name == 'push' && github.ref == 'refs/heads/main') || - (github.event_name == 'merge_group') + (github.event_name == 'merge_group') || + (github.event_name == 'issue_comment' && inputs.head_sha != '' && inputs.live) ) # Scalar form keeps default deployment: true so runs list under Environments. environment: ${{ github.event_name == 'push' && 'stage' || 'dev' }} @@ -162,7 +169,7 @@ jobs: contents: read id-token: write outputs: - # Read by e2e-ok-to-test.yml to complete the behaviour check run on the PR head. + # Read by e2e-ok-to-test.yml to complete the behaviour-live check run on the PR head. result: ${{ steps.result.outputs.result }} env: ENVIRONMENT: ${{ github.event_name == 'push' && 'stage' || 'dev' }} @@ -450,13 +457,15 @@ jobs: group: ${{ github.workflow }}-${{ github.run_id }}-${{ github.event_name == 'push' && 'stage-org' || 'playback-dev' }} cancel-in-progress: false # Manual dispatch uses the selected trusted branch and the dev environment. + # An authorized `/ok-to-test live` runs it on that sha (dev). needs: gate if: >- !cancelled() && ( (github.event_name == 'push' && github.ref == 'refs/heads/main') || (github.event_name == 'merge_group') || - (github.event_name == 'workflow_dispatch' && inputs.run_playback) + (github.event_name == 'workflow_dispatch' && inputs.run_playback) || + (github.event_name == 'issue_comment' && inputs.head_sha != '' && inputs.live) ) # Scalar form keeps default deployment: true so runs list under Environments. environment: ${{ github.event_name == 'push' && 'stage' || 'dev' }} @@ -470,7 +479,7 @@ jobs: contents: read id-token: write outputs: - # Read by e2e-ok-to-test.yml to complete the playback check run on the PR head. + # Read by e2e-ok-to-test.yml to complete the playback-live check run on the PR head. result: ${{ steps.result.outputs.result }} env: ENVIRONMENT: ${{ github.event_name == 'push' && 'stage' || 'dev' }} From de6a79af0a9cb00c6f8615db4a1f7b8b08f3c4d5 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 20 Nov 2026 14:48:45 -0500 Subject: [PATCH 022/208] fix(#9759): verify the ONNX Runtime package against NuGet SHA512 NuGet publishes no sha256, but its catalog records a SHA512 for every package. update-ort-checksums.sh now checks the downloaded .nupkg against that SHA512 (new nuget_package_sha256 helper in lib-checksums.sh) before writing ORT_SHA256, instead of trusting the computed hash. The checksum test serves a NuGet registration and catalog fixture, so the mismatch case runs for ORT too. Validated: update-pin-checksums-test.sh passes; the script against live NuGet verifies 1.32.0 and writes the pinned ORT_SHA256; a native arm64 runner build passes the runner-image.yml smoke checks, ML scan included. Assisted-by: Claude Signed-off-by: Wayne Sun --- renovate.json | 2 +- scripts/renovate/lib-checksums.sh | 32 ++++++++++++++++++- scripts/renovate/update-ort-checksums.sh | 19 ++++------- scripts/renovate/update-pin-checksums-test.sh | 26 ++++++++++++++- 4 files changed, 63 insertions(+), 16 deletions(-) diff --git a/renovate.json b/renovate.json index 6951cc90c8..3323f1555e 100644 --- a/renovate.json +++ b/renovate.json @@ -207,7 +207,7 @@ } }, { - "description": "After an ONNX Runtime bump, refresh ORT_SHA256 in the runner Containerfile from the sha256 of the Microsoft.ML.OnnxRuntime NuGet package (#9121, #9759)", + "description": "After an ONNX Runtime bump, refresh ORT_SHA256 in the runner Containerfile. The NuGet package is checked against the SHA512 NuGet records for it before its sha256 is written (#9121, #9759)", "matchPackageNames": ["Microsoft.ML.OnnxRuntime"], "postUpgradeTasks": { "commands": ["bash scripts/renovate/update-ort-checksums.sh"], diff --git a/scripts/renovate/lib-checksums.sh b/scripts/renovate/lib-checksums.sh index 4e1a9582d6..f0b2cccacd 100644 --- a/scripts/renovate/lib-checksums.sh +++ b/scripts/renovate/lib-checksums.sh @@ -26,7 +26,7 @@ # exits non-zero before a file is touched. # # Helpers for published_sha: checksum_file_sha, github_asset_digest, -# release_notes_sha. +# release_notes_sha, nuget_package_sha256. if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then echo "error: lib-checksums.sh is a library; source it from an update-*-checksums.sh script" >&2 @@ -168,6 +168,36 @@ release_notes_sha() { printf '%s\n' "${matches}" } +# nuget_package_sha256 — NuGet records a SHA512 +# (base64) for every package in its catalog, not a sha256. Check the +# downloaded package against that SHA512 and, only when it matches, print the +# package's sha256 for update_pin. is the lowercase package id. +nuget_package_sha256() { + local id="$1" version="$2" url="$3" reg catalog_url catalog algo want got artifact + reg=$(fetch_cached "https://api.nuget.org/v3/registration5-semver1/${id}/${version}.json") || return 1 + if ! catalog_url=$(jq -er '.catalogEntry | strings' "${reg}"); then + echo "error: no catalogEntry in the NuGet registration for ${id} ${version}" >&2 + return 1 + fi + catalog=$(fetch_cached "${catalog_url}") || return 1 + if ! algo=$(jq -er '.packageHashAlgorithm | strings' "${catalog}") \ + || ! want=$(jq -er '.packageHash | strings' "${catalog}"); then + echo "error: no packageHash in the NuGet catalog entry for ${id} ${version}" >&2 + return 1 + fi + if [[ "${algo}" != "SHA512" ]]; then + echo "error: NuGet catalog entry for ${id} ${version} uses ${algo}, expected SHA512" >&2 + return 1 + fi + artifact=$(fetch_cached "${url}") || return 1 + got=$(openssl dgst -sha512 -binary "${artifact}" | base64 | tr -d '\n') + if [[ "${got}" != "${want}" ]]; then + echo "error: checksum mismatch for ${url}: NuGet records SHA512 ${want}, downloaded ${got}" >&2 + return 1 + fi + sha256sum "${artifact}" | cut -d' ' -f1 +} + # read_pin_version — print ARG _VERSION from . read_pin_version() { local file="$1" pin="$2" count value diff --git a/scripts/renovate/update-ort-checksums.sh b/scripts/renovate/update-ort-checksums.sh index f0cc5ac20a..62063b5e57 100755 --- a/scripts/renovate/update-ort-checksums.sh +++ b/scripts/renovate/update-ort-checksums.sh @@ -1,22 +1,15 @@ #!/usr/bin/env bash -# Called by Renovate postUpgradeTasks after a Microsoft.ML.OnnxRuntime bump. -# The runner image takes libonnxruntime.so from Microsoft's official NuGet -# package (github.com/microsoft/onnxruntime answers 404, #9759). One .nupkg -# carries both architectures, so this updates the single ORT_SHA256 in the -# runner Containerfile. -# -# NuGet publishes no sha256 for a package (its catalog records only a -# base64 SHA512 packageHash), so the hash is computed from the HTTPS -# download from api.nuget.org. +# Called by Renovate postUpgradeTasks after a Microsoft.ML.OnnxRuntime (NuGet) +# bump. Downloads the NuGet package the runner Containerfile installs from, +# checks it against the SHA512 NuGet records for that version, and updates +# ORT_SHA256 in the runner Containerfile. One package carries both linux +# architectures, so the pin has a single checksum. set -euo pipefail source "$(dirname "${BASH_SOURCE[0]}")/lib-checksums.sh" -# shellcheck disable=SC2034 # read by update_pin in lib-checksums.sh -ALLOW_UNPUBLISHED=1 - asset_url() { echo "https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/${VERSION}/microsoft.ml.onnxruntime.${VERSION}.nupkg" } -published_sha() { :; } +published_sha() { nuget_package_sha256 microsoft.ml.onnxruntime "${VERSION}" "$2"; } update_pin ORT single images/runner/Containerfile diff --git a/scripts/renovate/update-pin-checksums-test.sh b/scripts/renovate/update-pin-checksums-test.sh index 0d586e41b1..1b48c1bf4d 100755 --- a/scripts/renovate/update-pin-checksums-test.sh +++ b/scripts/renovate/update-pin-checksums-test.sh @@ -180,6 +180,25 @@ publish_release_notes() { WRONG_SHA="5555555555555555555555555555555555555555555555555555555555555555" +# publish_nuget_hash — NuGet registration leaf +# pointing at a catalog entry that records the package's base64 SHA512. Any +# override publishes the SHA512 of other bytes, to provoke a mismatch. +publish_nuget_hash() { + local id="$1" version="$2" override="$3" reg cat hash catalog_url + catalog_url="https://api.nuget.org/v3/catalog0/data/fixture/${id}.${version}.json" + if [[ -n "${override}" ]]; then + hash=$(printf '%s' "${override}" | openssl dgst -sha512 -binary | base64 | tr -d '\n') + else + hash=$(openssl dgst -sha512 -binary "$(awk -F '\t' -v u="${URLS[0]}" '$1 == u { print $2; exit }' "${URLMAP}")" | base64 | tr -d '\n') + fi + reg="${FIXTURES}/nuget-reg-$RANDOM.json" + cat="${FIXTURES}/nuget-cat-$RANDOM.json" + jq -n --arg c "${catalog_url}" '{catalogEntry: $c}' > "${reg}" + jq -n --arg h "${hash}" '{packageHashAlgorithm: "SHA512", packageHash: $h}' > "${cat}" + serve "https://api.nuget.org/v3/registration5-semver1/${id}/${version}.json" "${reg}" + serve "${catalog_url}" "${cat}" +} + # --- Case table ------------------------------------------------------------- # script | PIN | mode | files (space-separated) | version | amd64/single URL | # arm64 URL | published source @@ -189,6 +208,7 @@ WRONG_SHA="5555555555555555555555555555555555555555555555555555555555555555" # sha256 .sha256 per arch # digest:: GitHub release asset digests # notes:: SHA256 row in GitHub release notes +# nuget:: SHA512 in the NuGet catalog entry # none upstream publishes nothing; computed hash used CASES=( "update-pi-anthropic-vertex-checksum.sh|PI_ANTHROPIC_VERTEX|single|images/sandbox/Containerfile|9.8.7|https://github.com/fullsend-ai/pi-anthropic-vertex/archive/refs/tags/v9.8.7.tar.gz||notes:fullsend-ai/pi-anthropic-vertex:v9.8.7" @@ -202,7 +222,7 @@ CASES=( "update-gitsign-checksums.sh|GITSIGN|multi|images/code/Containerfile|9.1.0|https://github.com/sigstore/gitsign/releases/download/v9.1.0/gitsign_9.1.0_linux_amd64|https://github.com/sigstore/gitsign/releases/download/v9.1.0/gitsign_9.1.0_linux_arm64|checksums:https://github.com/sigstore/gitsign/releases/download/v9.1.0/checksums.txt" "update-lychee-checksums.sh|LYCHEE|multi|images/code/Containerfile|9.1.0|https://github.com/lycheeverse/lychee/releases/download/lychee-v9.1.0/lychee-x86_64-unknown-linux-gnu.tar.gz|https://github.com/lycheeverse/lychee/releases/download/lychee-v9.1.0/lychee-aarch64-unknown-linux-gnu.tar.gz|sha256" "update-opencode-checksums.sh|OPENCODE|multi|images/sandbox/Containerfile|9.1.0|https://github.com/anomalyco/opencode/releases/download/v9.1.0/opencode-linux-x64.tar.gz|https://github.com/anomalyco/opencode/releases/download/v9.1.0/opencode-linux-arm64.tar.gz|digest:anomalyco/opencode:v9.1.0" - "update-ort-checksums.sh|ORT|single|images/runner/Containerfile|9.1.0|https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/9.1.0/microsoft.ml.onnxruntime.9.1.0.nupkg||none" + "update-ort-checksums.sh|ORT|single|images/runner/Containerfile|9.1.0|https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/9.1.0/microsoft.ml.onnxruntime.9.1.0.nupkg||nuget:microsoft.ml.onnxruntime:9.1.0" ) # publish — serve the published checksums for URLS/SHAS. @@ -219,6 +239,10 @@ publish() { IFS=: read -r _ repo tag <<< "${src}" publish_release_notes "${repo}" "${tag}" "${override}" ;; + nuget:*) + IFS=: read -r _ repo tag <<< "${src}" + publish_nuget_hash "${repo}" "${tag}" "${override}" + ;; none) ;; *) echo "unknown published source: ${src}" >&2; exit 1 ;; esac From 0c0dd7e10a408d731993f747c8285ddcf90a7562 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 20 Nov 2026 15:01:04 -0500 Subject: [PATCH 023/208] docs(e2e): describe `/ok-to-test live` everywhere it applies The playback trigger bullet and the ENVIRONMENT description now say the issue_comment call runs the live suites in dev after an authorized `/ok-to-test live`. LADDER.md's Triage and Write sections and the e2e-testing quick summary mention the live option. Rename the check-run creation step, which now also creates the live checks. Refs #9757 Assisted-by: Claude Signed-off-by: Wayne Sun --- .github/workflows/e2e-ok-to-test.yml | 2 +- LADDER.md | 8 ++++++-- docs/guides/dev/behaviour-testing.md | 4 ++-- docs/guides/dev/e2e-testing.md | 4 +++- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/e2e-ok-to-test.yml b/.github/workflows/e2e-ok-to-test.yml index a0ac04f44c..0bfcb00392 100644 --- a/.github/workflows/e2e-ok-to-test.yml +++ b/.github/workflows/e2e-ok-to-test.yml @@ -73,7 +73,7 @@ jobs: run: | [[ "${HEAD_SHA}" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::bad head sha '${HEAD_SHA}'"; exit 1; } - - name: Create the Forgejo behaviour check on the PR head + - name: Create the E2E checks on the PR head id: checks if: steps.auth.outputs.authorized == 'true' env: diff --git a/LADDER.md b/LADDER.md index 67191fbf44..ed8a6e18ba 100644 --- a/LADDER.md +++ b/LADDER.md @@ -73,8 +73,9 @@ repository. - Pull requests from any author, forks included, run the behaviour and playback scenarios on the GitHub emulator automatically (the required `behaviour-github-emulator` check). - `/ok-to-test `, from someone with the Write role, authorizes only - the optional Forgejo behaviour suite on your PRs. + `/ok-to-test `, from someone with the Write role, authorizes the + optional Forgejo behaviour suite on your PRs; `/ok-to-test live` + also runs the live behaviour and playback suites. **Criteria:** @@ -123,6 +124,9 @@ repository. a `/ok-to-test ` comment for it, which you may post yourself. The required `behaviour-github-emulator` check needs no authorization: every PR, forks included, runs it +- Running the live behaviour and playback suites on a PR, by commenting + `/ok-to-test live` (reported as `behaviour-live` and + `playback-live`) **Criteria:** diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index dadd6a9be4..4bc3471336 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -458,7 +458,7 @@ The target runs `go test -tags playback -race -v -count=1 -timeout 45m ./e2e/beh The `playback` job mirrors the `behaviour` job in [`.github/workflows/e2e.yml`](../../../.github/workflows/e2e.yml), with these specifics: - **Target and environment.** Run `make playback-test` with `shell: bash`, teeing output (for example to `playback-test.log`) so `pipefail` propagates failures. Pass the same `env:` block as the behaviour job: `BEHAVIOUR_SCM=github`, `BEHAVIOUR_CI=githubactions`, `BEHAVIOUR_INSTALL_MODE=per-repo`, `E2E_GCP_*`, `TEST_*_PEM`, and the `TEST_CLOUDFLARE_*` credentials. Point `BEHAVIOUR_ARTIFACT_DIR` at a playback-specific directory (for example `${{ runner.temp }}/playback-artifacts`). You do not need to set `GODOG_TAGS` or `PLAYBACK_RUNTIME`, because `RunPlaybackSuite` sets them itself. -- **Triggers, gate, and environment binding.** Use `needs: gate` with `!cancelled()` and run for `merge_group` and push to `main`; manual dispatch runs playback when `run_playback=true`. Skip pull requests, including the `issue_comment` call from `e2e-ok-to-test.yml`: they get playback from the GitHub emulator ([`behaviour-github-emulator.yml`](../../../.github/workflows/behaviour-github-emulator.yml)), and a skipped job satisfies the required `playback` check. Bind to the same GitHub Environment (`stage` on push, `dev` otherwise) and set `ENVIRONMENT` to match. The job checks out and runs the code under test with secrets, so the [CI Workflows security rules](../../contributing/ci-workflows.md#review-checklist-for-secrets-in-behaviourplayback-jobs) apply. +- **Triggers, gate, and environment binding.** Use `needs: gate` with `!cancelled()` and run for `merge_group` and push to `main`; manual dispatch runs playback when `run_playback=true`. Skip pull requests: they get playback from the GitHub emulator ([`behaviour-github-emulator.yml`](../../../.github/workflows/behaviour-github-emulator.yml)), and a skipped job satisfies the required `playback` check. The exception is the `issue_comment` call from `e2e-ok-to-test.yml` after an authorized `/ok-to-test live`: it runs playback in `dev` on that sha, reported as the non-required `playback-live` check. Bind to the same GitHub Environment (`stage` on push, `dev` otherwise) and set `ENVIRONMENT` to match. The job checks out and runs the code under test with secrets, so the [CI Workflows security rules](../../contributing/ci-workflows.md#review-checklist-for-secrets-in-behaviourplayback-jobs) apply. - **Slot leasing.** Neither suite reserves a whole org. `RunPlaybackSuite` and `RunSuite` lease individual `(org, test-repo-NN)` slots through the same shared install driver and allocator (see [Repo allocation via the shared slot driver](#repo-allocation-via-the-shared-slot-driver)), so the two suites and other concurrent runs can share an org without resetting each other's repos. Neither suite takes the exclusive `e2e-lock` (`e2etest.AcquireOrg`) or runs the broad startup `e2etest.CleanupStaleResources`. Abandoned slot repos are reclaimed by the allocator's [repo-slot GC](#repo-slot-gc). The playback and behaviour jobs still share a job concurrency group within each stage workflow run, because the STAGE pool is the single `halfsend` org with only 12 slots. Dev jobs use distinct groups and run concurrently across the numbered orgs. - **Change detection.** Reuse the behaviour job's file filter (its `grep -qE` path list and the `push.paths` entries under the same `SYNC-WITH` comment). It already covers `e2e/behaviour/` (playback features, fixtures and results), `pkg/behaviourtest/`, `internal/runtime/` (the `dummy-playback` runtime), and `Makefile`. Keep the two filters in sync, and keep the behaviour job's fallback of running the tests when the file list cannot be fetched or may be truncated. - **Cancellation.** The job inherits the workflow-level `concurrency` group and `cancel-in-progress` expression. A cancelled or killed run cannot run `t.Cleanup`, so its slot repos stay occupied until the [repo-slot GC](#repo-slot-gc) reclaims them, exactly as for the behaviour job. Gate post-test steps on `always()` rather than `success()` so that redaction still runs after a failure. @@ -946,7 +946,7 @@ TEST_ACTOR_TRIAGE_PAT=... # triage-level human-like actor PAT TEST_ACTOR_OUTSIDER_PAT=... # outsider human-like actor PAT (no org write on base) ``` -`ENVIRONMENT` is `dev`, `stage`, `github-emulator`, or `forgejo-dev`. Local runs default to `dev` when unset. `github-emulator` runs the suite against a GitHub emulator instead of github.com (see [Running against a GitHub emulator](#running-against-a-github-emulator)). `forgejo-dev` selects the Forgejo SCM, CI, and install drivers, which are not-implemented stubs for now (see [Forgejo driver stubs](behaviour-drivers.md#forgejo-driver-stubs)). The standard `behaviour` job sets it to match its GitHub Environment (`dev` in the merge queue, `stage` on push to `main`). The separate, non-required `forgejo-behaviour` job selects only `@forgejo` scenarios and always sets `ENVIRONMENT=forgejo-dev`; its GitHub Environment is `forgejo-stage` on push to `main` and `forgejo-dev` otherwise. Promotion to a required check is tracked in [#9656](https://github.com/fullsend-ai/fullsend/issues/9656). +`ENVIRONMENT` is `dev`, `stage`, `github-emulator`, or `forgejo-dev`. Local runs default to `dev` when unset. `github-emulator` runs the suite against a GitHub emulator instead of github.com (see [Running against a GitHub emulator](#running-against-a-github-emulator)). `forgejo-dev` selects the Forgejo SCM, CI, and install drivers, which are not-implemented stubs for now (see [Forgejo driver stubs](behaviour-drivers.md#forgejo-driver-stubs)). The standard `behaviour` job sets it to match its GitHub Environment (`dev` in the merge queue and on an authorized `/ok-to-test live`, `stage` on push to `main`). The separate, non-required `forgejo-behaviour` job selects only `@forgejo` scenarios and always sets `ENVIRONMENT=forgejo-dev`; its GitHub Environment is `forgejo-stage` on push to `main` and `forgejo-dev` otherwise. Promotion to a required check is tracked in [#9656](https://github.com/fullsend-ai/fullsend/issues/9656). When `BEHAVIOUR_CONFIG_PRESET` is set to a local path or HTTPS URL, install drivers forward it as `fullsend github setup --config ` and omit `--runtime dummy` so the preset's `runtime: dummy` is inherited rather than pinned in the overlay. Unset (the default) leaves install behaviour unchanged. diff --git a/docs/guides/dev/e2e-testing.md b/docs/guides/dev/e2e-testing.md index e01069a28f..47104edf11 100644 --- a/docs/guides/dev/e2e-testing.md +++ b/docs/guides/dev/e2e-testing.md @@ -54,7 +54,9 @@ The obsolete admin install/uninstall suite and `make e2e-test` target have been removed. CI keeps both the regular behaviour and playback suites. Pull requests run them on a GitHub emulator ([`behaviour-github-emulator.yml`](../../../.github/workflows/behaviour-github-emulator.yml)), -and `e2e.yml` runs them live in the merge queue and on push to `main`. +and `e2e.yml` runs them live in the merge queue and on push to `main`. A +user with write access can also run them live on a pull request with +`/ok-to-test live`. To run playback manually, select **E2E Tests → Run workflow**, choose the branch, and leave **Run the playback behaviour suite** enabled. From the CLI: From 34cf51b26da46401926c036f49332a73cad99dd4 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 20 Nov 2026 15:01:20 -0500 Subject: [PATCH 024/208] fix(#9759): address review on the ORT NuGet switch - images/README.md: ORT gets its own verification row (NuGet catalog SHA512) and the update steps note its single ORT_SHA256. - Containerfile: close the extracted library explicitly, so a failed flush fails the build instead of leaving a truncated .so. - renovate.json: match the ORT postUpgradeTasks rule case-insensitively. - nuget_package_sha256: report a failed SHA512 computation as a tool error, not a checksum mismatch. - update-pin-checksums-test.sh: cover a missing catalogEntry, a non-SHA512 algorithm and a missing packageHash; stop shadowing cat. Assisted-by: Claude Signed-off-by: Wayne Sun --- images/README.md | 5 ++-- images/runner/Containerfile | 2 +- renovate.json | 2 +- scripts/renovate/lib-checksums.sh | 5 +++- scripts/renovate/update-pin-checksums-test.sh | 27 ++++++++++++++++--- 5 files changed, 32 insertions(+), 9 deletions(-) diff --git a/images/README.md b/images/README.md index 5b63652a93..43a055e6d6 100644 --- a/images/README.md +++ b/images/README.md @@ -174,7 +174,7 @@ Each tool section in the Containerfile has an update comment with the source URL for checksums. When bumping a version: 1. Download the new release checksums from the URL in the comment. -2. Update both `*_SHA256_AMD64` and `*_SHA256_ARM64` ARGs. +2. Update both `*_SHA256_AMD64` and `*_SHA256_ARM64` ARGs (ONNX Runtime has a single `ORT_SHA256`: one NuGet package covers both arches). 3. The base image digest can be updated by running `podman manifest inspect :` and extracting the index digest. @@ -211,7 +211,8 @@ share `scripts/renovate/lib-checksums.sh` and are tested by | `RIPGREP` | sandbox | release `.tar.gz.sha256` assets | | `LYCHEE` | code | release `.tar.gz.sha256` assets | | `GH`, `GITLEAKS` (sandbox + runner), `GITSIGN` | runner, sandbox, code | release checksums file | -| `FD`, `OPENCODE`, `ORT` | sandbox, runner | sha256 digest GitHub records for each release asset (no upstream checksum file) | +| `FD`, `OPENCODE` | sandbox | sha256 digest GitHub records for each release asset (no upstream checksum file) | +| `ORT` | runner | SHA512 the NuGet catalog records for the `Microsoft.ML.OnnxRuntime` package (one `.nupkg` for both arches, so a single `ORT_SHA256`) | | `GCLOUD` | runner | nothing — Google lists checksums only for the current release on its HTML install page, so the hash is computed from the HTTPS download | These pins stay manual: diff --git a/images/runner/Containerfile b/images/runner/Containerfile index fe610a9428..5bd345120a 100644 --- a/images/runner/Containerfile +++ b/images/runner/Containerfile @@ -305,7 +305,7 @@ RUN case "$TARGETARCH" in \ "https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/${ORT_VERSION}/microsoft.ml.onnxruntime.${ORT_VERSION}.nupkg" \ -o /tmp/ort.nupkg \ && echo "${ORT_SHA256} /tmp/ort.nupkg" | sha256sum -c - \ - && python3 -c 'import shutil, sys, zipfile; src = zipfile.ZipFile(sys.argv[1]).open(sys.argv[2]); shutil.copyfileobj(src, open(sys.argv[3], "wb"))' \ + && python3 -c 'import shutil, sys, zipfile; z = zipfile.ZipFile(sys.argv[1]); exec("with z.open(sys.argv[2]) as src, open(sys.argv[3], \"wb\") as dst: shutil.copyfileobj(src, dst)")' \ /tmp/ort.nupkg "runtimes/${ORT_RID}/native/libonnxruntime.so" "/usr/lib/libonnxruntime.so.${ORT_VERSION}" \ && chmod 0755 "/usr/lib/libonnxruntime.so.${ORT_VERSION}" \ && ln -sf "/usr/lib/libonnxruntime.so.${ORT_VERSION}" /usr/lib/libonnxruntime.so \ diff --git a/renovate.json b/renovate.json index 3323f1555e..06d991e0ea 100644 --- a/renovate.json +++ b/renovate.json @@ -208,7 +208,7 @@ }, { "description": "After an ONNX Runtime bump, refresh ORT_SHA256 in the runner Containerfile. The NuGet package is checked against the SHA512 NuGet records for it before its sha256 is written (#9121, #9759)", - "matchPackageNames": ["Microsoft.ML.OnnxRuntime"], + "matchPackageNames": ["/^microsoft\\.ml\\.onnxruntime$/i"], "postUpgradeTasks": { "commands": ["bash scripts/renovate/update-ort-checksums.sh"], "fileFilters": ["images/runner/Containerfile"], diff --git a/scripts/renovate/lib-checksums.sh b/scripts/renovate/lib-checksums.sh index f0b2cccacd..bc63e16438 100644 --- a/scripts/renovate/lib-checksums.sh +++ b/scripts/renovate/lib-checksums.sh @@ -190,7 +190,10 @@ nuget_package_sha256() { return 1 fi artifact=$(fetch_cached "${url}") || return 1 - got=$(openssl dgst -sha512 -binary "${artifact}" | base64 | tr -d '\n') + if ! got=$(openssl dgst -sha512 -binary "${artifact}" | base64 | tr -d '\n') || [[ -z "${got}" ]]; then + echo "error: could not compute the SHA512 of ${url}" >&2 + return 1 + fi if [[ "${got}" != "${want}" ]]; then echo "error: checksum mismatch for ${url}: NuGet records SHA512 ${want}, downloaded ${got}" >&2 return 1 diff --git a/scripts/renovate/update-pin-checksums-test.sh b/scripts/renovate/update-pin-checksums-test.sh index 1b48c1bf4d..61e3b5dc7f 100755 --- a/scripts/renovate/update-pin-checksums-test.sh +++ b/scripts/renovate/update-pin-checksums-test.sh @@ -184,7 +184,7 @@ WRONG_SHA="5555555555555555555555555555555555555555555555555555555555555555" # pointing at a catalog entry that records the package's base64 SHA512. Any # override publishes the SHA512 of other bytes, to provoke a mismatch. publish_nuget_hash() { - local id="$1" version="$2" override="$3" reg cat hash catalog_url + local id="$1" version="$2" override="$3" reg catalog hash catalog_url catalog_url="https://api.nuget.org/v3/catalog0/data/fixture/${id}.${version}.json" if [[ -n "${override}" ]]; then hash=$(printf '%s' "${override}" | openssl dgst -sha512 -binary | base64 | tr -d '\n') @@ -192,11 +192,11 @@ publish_nuget_hash() { hash=$(openssl dgst -sha512 -binary "$(awk -F '\t' -v u="${URLS[0]}" '$1 == u { print $2; exit }' "${URLMAP}")" | base64 | tr -d '\n') fi reg="${FIXTURES}/nuget-reg-$RANDOM.json" - cat="${FIXTURES}/nuget-cat-$RANDOM.json" + catalog="${FIXTURES}/nuget-cat-$RANDOM.json" jq -n --arg c "${catalog_url}" '{catalogEntry: $c}' > "${reg}" - jq -n --arg h "${hash}" '{packageHashAlgorithm: "SHA512", packageHash: $h}' > "${cat}" + jq -n --arg h "${hash}" '{packageHashAlgorithm: "SHA512", packageHash: $h}' > "${catalog}" serve "https://api.nuget.org/v3/registration5-semver1/${id}/${version}.json" "${reg}" - serve "${catalog_url}" "${cat}" + serve "${catalog_url}" "${catalog}" } # --- Case table ------------------------------------------------------------- @@ -335,6 +335,25 @@ WD=$(setup_workdir GITLEAKS 9.1.0 images/sandbox/Containerfile) sed -i "s/^ARG GITLEAKS_VERSION=.*/ARG GITLEAKS_VERSION=9.0.0/" "${WD}/images/runner/Containerfile" expect_failure "gitleaks: version mismatch between images" "${WD}" update-gitleaks-checksums.sh "GITLEAKS_VERSION mismatch" +# NuGet catalog entries that cannot be trusted fail before anything is written. +ORT_NUPKG="https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/9.1.0/microsoft.ml.onnxruntime.9.1.0.nupkg" +ORT_REG="https://api.nuget.org/v3/registration5-semver1/microsoft.ml.onnxruntime/9.1.0.json" +ORT_CAT="https://api.nuget.org/v3/catalog0/data/fixture/microsoft.ml.onnxruntime.9.1.0.json" +for nuget_case in \ + 'no catalogEntry|{}|{"packageHashAlgorithm":"SHA512","packageHash":"x"}|no catalogEntry in the NuGet registration' \ + 'wrong algorithm|{"catalogEntry":"'"${ORT_CAT}"'"}|{"packageHashAlgorithm":"SHA256","packageHash":"x"}|uses SHA256, expected SHA512' \ + 'no packageHash|{"catalogEntry":"'"${ORT_CAT}"'"}|{"packageHashAlgorithm":"SHA512"}|no packageHash in the NuGet catalog entry'; do + IFS='|' read -r label reg_json cat_json want <<< "${nuget_case}" + reset_urls + serve "${ORT_NUPKG}" "$(make_artifact "${ORT_NUPKG}")" + printf '%s\n' "${reg_json}" > "${FIXTURES}/nuget-reg-case.json" + printf '%s\n' "${cat_json}" > "${FIXTURES}/nuget-cat-case.json" + serve "${ORT_REG}" "${FIXTURES}/nuget-reg-case.json" + serve "${ORT_CAT}" "${FIXTURES}/nuget-cat-case.json" + WD=$(setup_workdir ORT 9.1.0 images/runner/Containerfile) + expect_failure "ort: ${label}" "${WD}" update-ort-checksums.sh "${want}" +done + # A missing SHA ARG line fails before anything is written. WD=$(setup_workdir RIPGREP 99.1.0 images/sandbox/Containerfile) sed -i '/^ARG RIPGREP_SHA256_ARM64=/d' "${WD}/images/sandbox/Containerfile" From dd764d991c20360a6c01d9f07930deb5311f65a4 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 18 Nov 2026 12:11:02 -0500 Subject: [PATCH 025/208] chore(sandbox): bump codex to 0.170.0 and re-verify the re-check table Move CODEX_VERSION to 0.170.0, regenerate the bundled-model catalog fixture and recapture basic_run.ndjson with regen.sh. Re-verify the codex re-check table and the version-stamped comments at rust-v0.170.0 and record what changed upstream: after a success, a failed auth.command run keeps the last token until a later re-run, on expiry or on a 401, succeeds; each sub-agent start re-issues the denied GET /v1/models; the code-mode host truncates exec output at the same cap; exec binds the -o file before the first turn; and exec names no thread cwd. The launcher row also shows that bin/codex.js has replaced node with the native binary (process.execve) since 0.166.0, so no node ancestor admits codex: the egress docs, comments and runtimeEgressBinaries now say only **/codex does. Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 49 ++++++++++-------- docs/runtimes/codex.md | 19 ++++--- images/sandbox/Containerfile | 4 +- internal/cli/run_openai_test.go | 2 +- internal/cli/runtime_binaries_test.go | 16 +++--- internal/runtime/codex_bootstrap.go | 8 ++- internal/runtime/codex_bootstrap_test.go | 2 +- internal/runtime/codex_config.go | 12 ++--- internal/runtime/codex_gateway_test.go | 2 +- .../runtime/codex_hook/fullsend-codex-hook.py | 2 +- internal/runtime/codex_hook/gateway-token.sh | 7 ++- internal/runtime/codex_hook/openai-token.sh | 7 ++- internal/runtime/codex_hook_test.go | 2 +- internal/runtime/codex_personas.go | 4 +- internal/runtime/codex_personas_test.go | 10 ++-- internal/runtime/codex_progress_test.go | 38 +++++++------- internal/runtime/codex_redact.go | 2 +- internal/runtime/codex_run_test.go | 2 +- internal/runtime/codex_subagents.go | 2 +- internal/runtime/codex_subagents_test.go | 2 +- internal/runtime/testdata/codex/README.md | 15 +++--- .../runtime/testdata/codex/basic_run.ndjson | 24 +++++---- ...166.0.json => models-bundled-0.170.0.json} | 50 +++++++++++++++++++ internal/runtime/testdata/codex/regen.sh | 2 +- .../profiles/fullsend-openai.yaml | 2 +- 25 files changed, 178 insertions(+), 107 deletions(-) rename internal/runtime/testdata/codex/{models-bundled-0.166.0.json => models-bundled-0.170.0.json} (85%) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 4c9054d446..5198b70d1b 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -504,8 +504,8 @@ Record every applicable item in the PR description as `verified`, `blocked`, or The inference profiles (`profiles/fullsend-vertex-ai.yaml` in this repo and in fullsend-ai/agents; `profiles/fullsend-openai.yaml`, which has no fleet copy — the runner imports the embedded scaffold) carry a `binaries:` list. OpenShell's OPA (`sandbox-policy.rego`, `binary_allowed`) matches each glob against the kernel-resolved `/proc//exe` of the process that opens the connection **or of any of its ancestors**. That gives two kinds of runtime: -- **Wrapped by node** (pi, codex): `**/node` admits them through the ancestor, so a pin bump cannot take them off the allowlist unless the wrapper disappears. -- **Exec'd directly** (Claude Code, OpenCode): `claude` on PATH is a symlink to the npm package's `bin/claude.exe`, while OpenCode is the native `/usr/local/bin/opencode` binary. Neither has a wrapper ancestor, so only a glob on the real file name admits it. A renamed native binary breaks every run of that runtime on its first model call with `API Error: Error code policy_denied`, 0 tokens, and the only explanation is the gateway's `NET:OPEN … DENIED … binary '…' not allowed in policy '_provider_'` line (#6971). +- **Wrapped by node** (pi): `**/node` admits it, so a pin bump cannot take it off the allowlist unless the wrapper disappears. +- **Exec'd directly** (Claude Code, OpenCode, Codex): `claude` on PATH is a symlink to the npm package's `bin/claude.exe`, OpenCode is the native `/usr/local/bin/opencode` binary, and Codex's npm launcher `bin/codex.js` replaces node with the native binary (`process.execve`). None has a wrapper ancestor, so only a glob on the real file name admits it. A renamed native binary breaks every run of that runtime on its first model call (Claude Code reports `API Error: Error code policy_denied`, 0 tokens), and the only explanation is the gateway's `NET:OPEN … DENIED … binary '…' not allowed in policy '_provider_'` line (#6971). `TestScaffoldProfilesAllowRuntimeBinaries` (`internal/cli/runtime_binaries_test.go`) fails for any selectable runtime without a mapping and pins the ones below. @@ -513,7 +513,7 @@ The inference profiles (`profiles/fullsend-vertex-ai.yaml` in this repo and in f |---------|-----------------------------------|-----------------|----------| | Claude Code | `bin/claude.exe` in the npm package — 2.1.2xx's `install.cjs` places the native binary there ("Always write to bin/claude.exe"); the Containerfile installs it *with* scripts so that runs | `**/claude`, `**/claude.exe` | gateway deny log in #6971; `npm view @anthropic-ai/claude-code@ bin` | | pi | `node` (`bin = dist/bundle/cli.js`; no native network path in the package) | `**/node` | `images/sandbox/Containerfile`, `npm view @earendil-works/pi-coding-agent@ bin` | -| Codex | `vendor//bin/codex`, spawned by the npm launcher `bin/codex.js` under node; codex also spawns `codex-code-mode-host` (default-enabled in 0.152.1), covered by ancestor matching, not by name | `**/node` (ancestor), `**/codex` (the process) | `npm pack --dry-run "@openai/codex@-linux-x64"` | +| Codex | `vendor//bin/codex`, which the npm launcher `bin/codex.js` execs in place of node (`process.execve`); codex also spawns `codex-code-mode-host` (default-enabled in 0.152.1), covered by ancestor matching, not by name | `**/codex` (the process) | `npm pack --dry-run "@openai/codex@-linux-x64"`, `bin/codex.js` in `@openai/codex@` | | OpenCode | `/usr/local/bin/opencode`, the per-architecture glibc release binary installed directly by the Containerfile | `**/opencode` | `images/sandbox/Containerfile`; `internal/cli/runtime_binaries_test.go` | ## Sandbox workspace layout @@ -1250,7 +1250,7 @@ re-checked on a `CODEX_VERSION` bump. The decisions are Everything below was read at tag `rust-v0.152.1`; the rows of [Re-check on a `CODEX_VERSION` bump](#re-check-on-a-codex_version-bump) were -re-verified at `rust-v0.157.0`, at `rust-v0.159.3` and again at `rust-v0.166.0`. +re-verified at `rust-v0.157.0`, at `rust-v0.159.3`, at `rust-v0.166.0` and again at `rust-v0.170.0`. Two of the findings are the reason the hook adapter exists at all, because forwarding the scripts' own convention would fail **open**. @@ -1287,8 +1287,8 @@ flowchart TB - **The project is pinned untrusted.** `config.toml` carries `[projects.""] trust_level = "untrusted"` for the target repo, so its own `.codex/` layer — settings, instructions and repo-authored hooks — is never loaded. The entry has to be written: - codex records a trust level for a git checkout it starts in when none is set, and only skips - that when one already is. This is codex's equivalent of pi's `defaultProjectTrust: "never"`. + an unset trust level is not untrusted, and codex skips a project's own `AGENTS.md` only for an + explicit untrusted entry. This is codex's equivalent of pi's `defaultProjectTrust: "never"`. - **Config layering.** The sandbox image bakes a root-owned managed `/etc/codex/config.toml`; the runner's `$CODEX_HOME/config.toml` layers above it, and the `-c` SessionFlags above that. Only the `-c` layer is beyond an agent's reach between iterations, which is why the security-relevant @@ -1303,8 +1303,8 @@ flowchart TB `Read`, `Glob`, `Grep`, `WebFetch` and `WebSearch` have no codex tool — codex does that work through the shell, so the `Bash` groups already cover it. - **Skills** come from `$CODEX_HOME/skills`, which `Bootstrap` populates. Codex also discovers a - repo's `.agents/skills`, and (verified live at 0.157.0; discovery source unchanged through - 0.166.0) its `.codex/skills` even with the project untrusted; both are covered by the host-side + repo's `.agents/skills`, and (verified live at 0.157.0; the same skill roots through + 0.170.0) its `.codex/skills` even with the project untrusted; both are covered by the host-side and in-sandbox context scans, which match `SKILL.md` anywhere in the repo. The agent reads those files through the shell, and Codex 0.157.0 truncates a single exec at 10,000 tokens (head and tail), so both runtime notes (`codexChunkedReadNote`) tell it to count lines with `awk 'END { print NR }'` (`wc -l` @@ -1324,7 +1324,9 @@ flowchart TB - `Run` executes `codex exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox [--dangerously-bypass-hook-trust] -C --model -c model_provider=fullsend-openai -c approval_policy=never -c sandbox_mode=danger-full-access [-c model_reasoning_effort=] - -o /output/last-message.txt -` with the prompt piped to stdin. + -o $CODEX_HOME/last-message.txt -` with the prompt piped to stdin. At 0.170.0 codex opens the + `-o` file before the first turn and refuses a symlinked or hard-linked path; a failed open or + final write ends exec with exit 1, and codex writes the file only when a turn completes. - **The prompt is never on argv.** On a retry iteration it carries the previous failure's text (#1050/#6494), and argv is world-readable in the sandbox. `-` is codex's explicit read-from-stdin sentinel; the pipe closes when `printf` finishes, so there is none of the @@ -1369,12 +1371,15 @@ cannot be overridden, so it cannot follow the mid-run refresh a short-lived WIF `auth.command` is an absolute path to the runner-written `openai-token.sh`. - Codex runs that command, uses its trimmed stdout verbatim as the bearer token, caches it for `refresh_interval_ms` (30 s here; codex's default is 300 s) and re-runs it on expiry and on the - 401 retry path. A non-zero exit or empty stdout **fails the request with no fallback to the - environment**, which is what makes the path fail closed. + 401 retry path. A non-zero exit, empty stdout or timeout gives codex no token from that run, + with **no fallback to the environment**: with no earlier token the request fails, and after a + success codex (0.170.0) keeps sending the last token the script printed until one of those + re-runs succeeds. Codex never sends a value the script refused, which is what makes the path + fail closed. - The script prints the placeholder from `$CODEX_HOME/openai-token`, which `CodexRuntime`'s `OpenAICredentialSeeder` implementation seeds at iteration start and the runner re-seeds through - `sandbox exec` after every refresh. Anything that is not a gateway placeholder fails the run - rather than being forwarded, and the script never echoes the value it rejects. + `sandbox exec` after every refresh. Anything that is not a gateway placeholder is refused + with a non-zero exit rather than forwarded, and the script never echoes the value it rejects. - `supports_websockets` is left unset: custom providers default to false, which keeps codex on HTTP/SSE `POST /v1/responses` — the only thing the `fullsend-openai` egress profile allows. - **Inference gateway route (ADR 0137, #8295).** `CodexRuntime` implements @@ -1706,22 +1711,22 @@ Two artefacts of the run are worth knowing about: | `async` and `can_apply_control_effects` | a synchronous-only rule that changed would alter what the wiring must omit | `codex-rs/hooks/src/engine/mod.rs` | | `PostToolUse` output fields | if `updatedToolOutput` ever lands, the sanitizers can start redacting again | `codex-rs/hooks/src/schema.rs` | | Hook payload shape (`tool_name`, `tool_input.command` as a string, `tool_response`, and `cwd`, which since 0.166.0 is the shell call's own `workdir` when it passes one and the session cwd otherwise) | the scripts read these keys directly; the secret redactor derives the checkout root from `cwd`, so a `workdir` inside a submodule narrows it, as its docstring already allows | `codex-rs/core/src/{hook_runtime.rs,tools/context.rs}`, `codex-rs/hooks/src/events/common.rs` (`command_input_cwd`) | -| `auth.command` semantics (trimmed stdout, non-zero exit fails, no env fallback) | the whole credential path | `codex-rs/login/src/auth/external_bearer.rs` | +| `auth.command` semantics (trimmed stdout; a non-zero exit, empty stdout or timeout fails that run, with no env fallback; after a success, a failed run keeps the last token until a later re-run, on expiry or on a 401, succeeds) | the whole credential path | `codex-rs/login/src/auth/external_bearer.rs`, `codex-rs/login/src/auth/manager.rs` (`AuthManager::load_auth`, `AuthManager::auth`) | | `supports_websockets` default for custom providers | a true default would take traffic off `POST /v1/responses` and break the egress profile | `codex-rs/model-provider-info/src/lib.rs` | | `[skills.bundled]` and skill discovery | the bundled skills are disabled by the runner-owned config; a renamed key would silently bring `skill-installer` and friends back into the agent's roster | `codex-rs/config/src/skills_config.rs` | -| Exec output truncation (`DEFAULT_MAX_OUTPUT_TOKENS`, head+tail) | the runtime note's 200-line window is sized to stay under this cap; on bump, confirm 200 lines of a dense `SKILL.md` still fits under the new cap and that a truncated exec still emits a warning the split rule can detect | `codex-rs/core/src/unified_exec/mod.rs`, `codex-rs/core/src/tools/context.rs`, `codex-rs/utils/string/src/truncate.rs` | +| Exec output truncation (`DEFAULT_MAX_OUTPUT_TOKENS`, and for a `code_mode_only` model such as `gpt-5.6-luna` the code-mode host's `DEFAULT_MAX_OUTPUT_TOKENS_PER_EXEC_CALL`; both 10,000 tokens at 0.170.0, head+tail) | the runtime note's 200-line window is sized to stay under this cap; on bump, confirm 200 lines of a dense `SKILL.md` still fits under the new cap and that a truncated exec still emits a warning the split rule can detect | `codex-rs/core/src/unified_exec/mod.rs`, `codex-rs/core/src/tools/context.rs`, `codex-rs/utils/string/src/truncate.rs`, `codex-rs/code-mode-protocol/src/runtime.rs`, `codex-rs/code-mode-runtime/src/output/output_render.rs`, `codex-rs/utils/output-truncation/src/lib.rs` | | The `plugins` feature and what it gates | `[features] plugins = false` is what stops the startup fetch of `github.com/openai/plugins.git`; a renamed key, or a sync no longer gated on it, would bring the fetch back | `codex-rs/features/src/lib.rs`, `codex-rs/core-plugins/src/manager.rs` (`maybe_start_plugin_startup_tasks_for_config`) | -| The native binary's path inside the platform package (`vendor//bin/codex` at 0.166.0) | the `fullsend-openai` profile names it as `**/codex`; the node ancestor still admits a renamed file, but the pin in `runtimeEgressBinaries` should follow the rename | `npm pack --dry-run "@openai/codex@-linux-x64"` | -| Whether a custom provider still issues `GET /v1/models` at startup | the `fullsend-openai` egress profile denies it; if the request ever became fatal or retried, it would delay or fail every first turn | `codex-rs/models-manager/` | +| The native binary's path inside the platform package (`vendor//bin/codex` at 0.170.0), and the launcher's `process.execve` | the `fullsend-openai` and `fullsend-inference-gateway` profiles name it as `**/codex`; with no node ancestor, a renamed file is denied on every model call until the profiles and `runtimeEgressBinaries` follow the rename | `npm pack --dry-run "@openai/codex@-linux-x64"`, `codex-cli/bin/codex.js` | +| Whether a custom provider still issues `GET /v1/models` at startup, every 4.5 minutes from the in-process models refresh and, at 0.170.0, before each sub-agent starts, and whether each denial stays non-fatal, unretried on a 403 and capped at 5 s | the `fullsend-openai` egress profile denies it; if the request ever became fatal or retried, it would delay or fail every first turn and every child start | `codex-rs/models-manager/` (`ensure_initialized`), `codex-rs/core/src/thread_manager/model_catalog.rs`, `codex-rs/app-server/src/models_refresh_worker.rs`, `codex-rs/model-provider/src/models_endpoint.rs` (`MODELS_REFRESH_TIMEOUT`) | | `models_cache.json` name and location, its TTL and the version/identity checks that decide whether it is used | `buildCodexRunCommand` deletes `$CODEX_HOME/models_cache.json` before launch so every run starts from the bundled catalog; a renamed or relocated file would need the deletion to follow it | `codex-rs/models-manager/src/manager.rs` (`MODEL_CACHE_FILE`, `DEFAULT_MODEL_CACHE_TTL`, `try_load_cache`), `codex-rs/models-manager/src/cache.rs` (`load_fresh_file`) | | `ConfigToml` keys and the `ReasoningEffort` enum | a renamed or removed key silently changes behaviour; `--strict-config` reports it | `codex-rs/config/src/config_toml.rs`, `codex-rs/protocol/src/openai_models.rs` | -| Project trust and `AGENTS.md` | the pinned untrusted entry must still stop codex recording its own trust level, the repo's `.codex/` layer must stay unloaded, and `$CODEX_HOME/AGENTS.md` must still load while the project is untrusted, or the bridge stops reaching the agent | `codex-rs/app-server/src/request_processors/thread_processor.rs` (trust write), `codex-rs/config/src/loader/mod.rs`, `codex-rs/core/src/agents_md.rs`, `codex-rs/codex-home/src/instructions/mod.rs` | +| Project trust and `AGENTS.md` | the pinned untrusted entry must still stop codex recording its own trust level, the repo's `.codex/` layer must stay unloaded, and `$CODEX_HOME/AGENTS.md` must still load while the project is untrusted, or the bridge stops reaching the agent; at 0.170.0 exec also prints a stderr warning naming `codex exec --trust` whenever it disables the repo's `.codex/` layer, and the runner must never pass that flag | `codex-rs/app-server/src/request_processors/thread_processor.rs` (trust write), `codex-rs/exec/src/lib.rs` (`thread_start_params_from_config`, which names no cwd at 0.170.0, and `--trust`), `codex-rs/config/src/loader/mod.rs`, `codex-rs/core/src/agents_md.rs`, `codex-rs/codex-home/src/instructions/mod.rs` | | JSONL event structs, rollout line types and rollout file naming | the stream parser and transcript extraction; a rollout line type missing from `codexRolloutEnvelopes` discards the whole transcript | `codex-rs/exec/src/exec_events.rs`, `codex-rs/history/src/rollout_payload.rs` (`RolloutItemWire`), `codex-rs/thread-store/src/local/helpers.rs` | -| Stderr warning markers (`dropping in-process server notification (queue full)`, `thread/items/list failed during turn completion`, `thread/items/list returned a repeated cursor during turn completion`, and the prefix `thread/read failed while backfilling turn items`), their log targets and levels, and the `RUST_LOG` filter (`error,opentelemetry_sdk=off,opentelemetry_otlp=off,codex_exec=warn,codex_app_server::in_process=warn`; `info` with debug) | `codexStderrDrops` and the debug-log counts match these literals; changed text, targets, levels or filter semantics can silently stop the dropped-notification and failed-backfill warnings | `codex-rs/exec/src/lib.rs` (backfill `warn!` calls, `EXEC_DEFAULT_LOG_FILTER`), `codex-rs/app-server/src/in_process.rs` (drop `warn!` call) | +| Stderr warning markers (`dropping in-process server notification (queue full)`, `thread/items/list failed during turn completion`, `thread/items/list returned a repeated cursor during turn completion`, and the prefix `thread/read failed while backfilling turn items`; 0.170.0 adds `thread/items/list returned an incomplete item during turn completion`, which exec cannot reach while it asks for no deferred output), their log targets and levels, and the `RUST_LOG` filter (`error,opentelemetry_sdk=off,opentelemetry_otlp=off,codex_exec=warn,codex_app_server::in_process=warn`; `info` with debug) | `codexStderrDrops` and the debug-log counts match these literals; changed text, targets, levels or filter semantics can silently stop the dropped-notification and failed-backfill warnings | `codex-rs/exec/src/lib.rs` (backfill `warn!` calls, `EXEC_DEFAULT_LOG_FILTER`), `codex-rs/app-server/src/in_process.rs` (drop `warn!` call) | | The multi-agent tool names (`multi_agent_v1*`, `collaboration*`, the bare V1 `spawn_agent`), the block contract (exit 2 with non-empty stderr blocks; a timeout kills the handler and lets the call through), `agent_id` and `agent_type` in a child's payload, the spawn arguments, and what a child start rereads (`hooks.json` and the role file) | the spawn guard's matcher, pass-through set, policy, digest set and deadline rest on them; a renamed tool is denied (loud), but a payload without `agent_id` or `agent_type`, a new model or effort argument, a changed `fork_turns` reading, a changed block contract or a child that rereads another file turns a deny into a pass | `codex-rs/core/src/tools/handlers/multi_agents_spec.rs`, `codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs` (`SpawnAgentArgs::fork_mode`, which the hook's `_is_none_fork` mirrors), `codex-rs/core/src/tools/registry.rs` (`function_hook_tool_name`), `codex-rs/hooks/src/engine/command_runner.rs` (the timeout branch), `codex-rs/core/src/agent/role.rs` (the role file, read at spawn) | -| The bundled catalog's `multi_agent_version`, `default_reasoning_level` and `supported_reasoning_levels` entries, the version codex supplies to an entry that carries none, and the floor model (`codex debug models --bundled`; at 0.166.0 `gpt-5.6-luna` is the listed model that selects `v1` and defaults to `medium`, and `gpt-5.5` carries no version, which the `multi_agent` feature, on by default, resolves to V1, and lists `low` to `xhigh`) | part two of the delegation gate, the child-model floor and the child-effort check rest on them: the floor must stay listed, or every delegating agent without `subagents.default` or `FULLSEND_CODEX_SUBAGENT_MODEL` fails Bootstrap, while the floor's own collaboration version matters only under a V2 parent, which delegates only while no child model selects V2 (moving luna to V2 would stop every V2 parent on the default child model from delegating); a bump that turns `multi_agent` off by default, or gives the null entry a version, changes which parents delegate; a changed level set changes which run efforts Bootstrap accepts; and the fixture `internal/runtime/testdata/codex/models-bundled-0.166.0.json` must be regenerated, never edited | `codex-rs/models-manager/models.json` in the bumped tag; regenerate the fixture with the one-liner in `codex_personas_test.go`'s `TestCodexCatalog` comment and run `go test ./internal/runtime/ -run 'TestCodexCatalog\|TestCodexParentCollabVersion\|TestCodexV2ChildModelReason\|TestResolveCodexChildModels_Effort'` | +| The bundled catalog's `multi_agent_version`, `default_reasoning_level` and `supported_reasoning_levels` entries, the version codex supplies to an entry that carries none, and the floor model (`codex debug models --bundled`; at 0.170.0 `gpt-5.6-luna` is the listed model that selects `v1` and defaults to `medium`, and `gpt-5.5` carries no version, which the `multi_agent` feature, on by default (deprecated at 0.170.0, still on), resolves to V1, and lists `low` to `xhigh`) | part two of the delegation gate, the child-model floor and the child-effort check rest on them: the floor must stay listed, or every delegating agent without `subagents.default` or `FULLSEND_CODEX_SUBAGENT_MODEL` fails Bootstrap, while the floor's own collaboration version matters only under a V2 parent, which delegates only while no child model selects V2 (moving luna to V2 would stop every V2 parent on the default child model from delegating); a bump that turns `multi_agent` off by default, or gives the null entry a version, changes which parents delegate; a changed level set changes which run efforts Bootstrap accepts; and the fixture `internal/runtime/testdata/codex/models-bundled-0.170.0.json` must be regenerated, never edited | `codex-rs/models-manager/models.json` in the bumped tag; regenerate the fixture with the one-liner in `codex_personas_test.go`'s `TestCodexCatalog` comment and run `go test ./internal/runtime/ -run 'TestCodexCatalog\|TestCodexParentCollabVersion\|TestCodexV2ChildModelReason\|TestResolveCodexChildModels_Effort'` | | The `[agents]` keys codex reads (`enabled`, `max_concurrent_threads_per_session`, `max_depth`, `default_subagent_model`, `default_subagent_reasoning_effort`, and `[agents.]` `description` and `config_file`) and the order of the child path: with no model argument a child takes `default_subagent_model` and, with no effort argument, `default_subagent_reasoning_effort`, else that model's catalog default; a role file applies after and its effort is checked against its own model | `codexAgentsBlock` writes the keys and Bootstrap checks the child efforts on that order; a renamed key or a changed order silently changes every child's model or effort | `codex-rs/config/src/config_toml.rs` (`AgentsToml`), `codex-rs/core/src/config/mod.rs`, `codex-rs/core/src/agent/child_config.rs` (`apply_requested_spawn_agent_model_overrides`, `apply_spawn_agent_role`), `codex-rs/core/src/agent/role.rs` | | What writes a rollout under the sessions directory in an exec run, rollout naming and the date layout, creation at a child's first recorded item, a PreToolUse block returning before the tool handler, and spawn-slot reservation before thread creation | the disk side of the admission cross-check (the four facts are in `internal/runtime/testdata/codex/README.md`) | `codex-rs/core/src/tools/registry.rs`, `codex-rs/core/src/agent/control/spawn.rs`, `codex-rs/rollout/src/rollout_file_name.rs`, `codex-rs/features/src/lib.rs` (the memories default) | -| The `enabled`, `disable_direct_message`, `max_wait_timeout_ms`, `expose_spawn_agent_model_overrides` and `max_concurrent_threads_per_session` keys of the `[features.multi_agent_v2]` table (codex parses it with `deny_unknown_fields`) and how codex derives the V2 child cap: the table's own key, else `[agents] max_concurrent_threads_per_session + 1`, else 4, minus one at reservation | ADR 0159 keeps the four-child cap under `[agents]`; a changed derivation silently gives a V2 parent three or five children, and the runner renders the table on every run (`enabled`, plus `disable_direct_message`, `max_wait_timeout_ms` and `expose_spawn_agent_model_overrides` for an admitted V2 parent), so a renamed key fails the config of every run that renders it; a changed `collab_tools_enabled` changes which children of a V2 parent get the multi-agent tools (at 0.166.0 only a child whose own model selects V2), and the V2 spawn's backstop, a V2 parent delegating only while no child model selects V2 (`codexV2ChildModelReason`), rests on it | `codex-rs/core/src/config/mod.rs` (`resolve_multi_agent_v2_config`, `effective_agent_max_threads`), `codex-rs/features/src/feature_configs.rs` (`MultiAgentV2ConfigToml`), `codex-rs/core/src/tools/spec_plan.rs` (`collab_tools_enabled`), codex's test `multi_agent_v2_uses_agents_max_concurrent_threads_per_session` in `codex-rs/core/src/config/config_tests.rs` | -| The wait cap (`codexWaitTimeoutMaxMS`, 120000, #9657): the `max_wait_timeout_ms` key of `[features.multi_agent_v2]` (the table is `deny_unknown_fields`, so a renamed key fails config parsing), the V2 wait's check of `timeout_ms` against that max and the schema max it feeds, and V1's wait limits, which are constants with a max of 3600000 | on V2 the cap is Codex's own: the wait schema the parent reads carries the configured max and the wait returns an error to the model for a longer `timeout_ms`, so the parent waits again; the spawn guard passes a wait through unread (ADR 0126, ADR 0159). A renamed key fails the config of every run that renders the table with `disable_direct_message`; a V2 wait that stopped checking the max leaves only the dispatch note. V1 has no setting, its schema asks for longer waits, and the dispatch note's rule is the only cap there, so a changed V1 limit or wait default changes nothing the runner enforces | `codex-rs/core/src/config/mod.rs` (`max_wait_timeout_ms`, validated in `resolve_multi_agent_v2_config`), `codex-rs/core/src/tools/spec_plan.rs` (the V2 wait schema's max), `codex-rs/core/src/tools/handlers/multi_agents_v2/wait.rs` (the `timeout_ms` max check), `codex-rs/core/src/tools/handlers/multi_agents_common.rs` (V1's wait constants) | +| The `enabled`, `disable_direct_message`, `max_wait_timeout_ms`, `expose_spawn_agent_model_overrides` and `max_concurrent_threads_per_session` keys of the `[features.multi_agent_v2]` table (codex parses it with `deny_unknown_fields`) and how codex derives the V2 child cap: the table's own key, else `[agents] max_concurrent_threads_per_session + 1`, else 4, minus one at reservation | ADR 0159 keeps the four-child cap under `[agents]`; a changed derivation silently gives a V2 parent three or five children, and the runner renders the table on every run (`enabled`, plus `disable_direct_message`, `max_wait_timeout_ms` and `expose_spawn_agent_model_overrides` for an admitted V2 parent), so a renamed key fails the config of every run that renders it; a changed `collab_tools_enabled` changes which children of a V2 parent get the multi-agent tools (at 0.170.0 only a child whose own model selects V2), and the V2 spawn's backstop, a V2 parent delegating only while no child model selects V2 (`codexV2ChildModelReason`), rests on it | `codex-rs/core/src/config/mod.rs` (`resolve_multi_agent_v2_config`, `effective_agent_max_threads`), `codex-rs/features/src/feature_configs.rs` (`MultiAgentV2ConfigToml`), `codex-rs/core/src/tools/spec_plan.rs` (`collab_tools_enabled`), codex's test `multi_agent_v2_uses_agents_max_concurrent_threads_per_session` in `codex-rs/core/src/config/config_tests.rs` | +| The wait cap (`codexWaitTimeoutMaxMS`, 120000, #9657): the `max_wait_timeout_ms` key of `[features.multi_agent_v2]` (the table is `deny_unknown_fields`, so a renamed key fails config parsing), the V2 wait's check of `timeout_ms` against that max and the schema max it feeds, and V1's wait limits, which are constants with a max of 3600000 | on V2 the cap is Codex's own: the wait schema the parent reads carries the configured max and the wait returns an error to the model for a longer `timeout_ms`, so the parent waits again; the spawn guard passes a wait through unread (ADR 0126, ADR 0159). A renamed key fails the config of every run that renders the table with `disable_direct_message`; a V2 wait that stopped checking the max leaves only the dispatch note. V1 has no setting, its schema asks for longer waits, and the dispatch note's rule is the only cap there, so a changed V1 limit or wait default changes nothing the runner enforces | `codex-rs/core/src/config/mod.rs` (`max_wait_timeout_ms`, read in `resolve_multi_agent_v2_config` and validated in `load_config_with_layer_stack`), `codex-rs/core/src/tools/spec_plan.rs` (the V2 wait schema's max), `codex-rs/core/src/tools/handlers/multi_agents_v2/wait.rs` (the `timeout_ms` max check), `codex-rs/core/src/tools/handlers/multi_agents_common.rs` (V1's wait constants) | | The V2 child-result path: `SubagentStop` runs in a thread-spawned child with `last_assistant_message`, the text that becomes its result, before the turn completes and `notify_parent_of_terminal_turn` queues the result to the parent; exit 2 with a non-empty stderr makes the child continue with that stderr as its prompt (an empty one is ignored and the message delivered), `continue: false` ends the child and delivers the message, and the result reaches the parent's next model request as an `agent_message` item, which codex sends only from a thread on V2: the feature table must keep putting every thread of the run on V2, whatever the child's model | the child-result gate (ADR 0159 decision 4) rests on it: re-check on every bump that `SubagentStop` still runs before the result is delivered, that a block still continues the child, and that the hook runs after a block still carry `stop_hook_active: true` for the rest of the turn; if either of the first two changes, a flagged result reaches the parent unchecked, and if the third does, a blocked child can retry through the chain | `codex-rs/core/src/session/turn.rs` (the stop-hook block), `codex-rs/core/src/hook_runtime.rs` (`run_turn_stop_hooks`), `codex-rs/hooks/src/events/stop.rs`, `codex-rs/core/src/agent/control/completion.rs`, `codex-rs/core/src/session/mod.rs` (`record_inter_agent_communication`); run `go test ./internal/runtime/ -run 'TestCodexAdapter_SubagentStopGate'` | diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index 01d4327f8f..3e371d9dba 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -319,7 +319,7 @@ bare — and `metrics.json` records the same (`runtime`, `runtime_source`, `requ ... runtime: selected "codex" from --runtime flag ... -→ Agent: gpt-5.6-luna (v0.166.0) +→ Agent: gpt-5.6-luna (v0.170.0) ✓ Agent exited with code 0 ``` @@ -335,7 +335,7 @@ What a local codex run needs, beyond the guide: - **fullsend from the release that carries `CODEX_VERSION`** — the first one cut after the codex runtime lands. The release download and the container image both work as-is. - **A sandbox image that includes codex** — `ghcr.io/fullsend-ai/fullsend-sandbox` built with - `CODEX_VERSION` (0.166.0 today). A stale image fails Bootstrap's preflight before the agent + `CODEX_VERSION` (0.170.0 today). A stale image fails Bootstrap's preflight before the agent starts, with ``codex preflight: `codex --version` exited 127``; `podman pull ghcr.io/fullsend-ai/fullsend-sandbox:latest` fixes it. - **A harness that declares the provider and a policy** — `providers: [openai]` and @@ -401,7 +401,10 @@ What a local codex run needs, beyond the guide: `PATH` that codex and its tools inherit does not change. - **The repository's own `.codex/` config is never loaded.** fullsend pins the cloned repo's project trust to untrusted, so `.codex/config.toml` and `.codex/hooks.json` (model, instructions, - MCP servers, hooks) never apply. A target repo cannot change how the agent runs. + MCP servers, hooks) never apply. A target repo cannot change how the agent runs. When the repo + has a `.codex/` directory at its root, codex warns on stderr at every run that untrusted + project-local configuration is disabled and suggests `codex exec --trust`; the warning is + expected, and fullsend never passes `--trust`. - **Two tools, not a menu.** Codex works through a shell and `apply_patch`, so a harness `tools:` list has no native allowlist to map onto. A `Bash(...)` allowlist is **recorded but not enforced** on codex, and the run says so: @@ -428,7 +431,7 @@ What a local codex run needs, beyond the guide: scrubbed before they are written. - **Skills** work as they do on Claude Code: the harness's skills, plus your repository's own `.agents/skills` (codex's documented location for repository skills), both scanned for injected - content before the agent sees them. Codex 0.166.0 also picks up `.codex/skills` even though the + content before the agent sees them. Codex 0.170.0 also picks up `.codex/skills` even though the project is untrusted; that is not documented upstream and may change, so keep repository skills in `.agents/skills`. Codex's bundled skills (`skill-installer`, `imagegen` and friends) are switched off, so an agent sees only yours. @@ -487,12 +490,12 @@ so there is no codex to run. Pull a current when its `codex` is found only through a directory the sandbox user owns or can write. Install it, and `node`, outside such directories. -**Denied requests in the sandbox egress log at startup.** Expected noise, not failures. Codex -probes on the way up and the policy refuses what the run does not need: +**Denied requests in the sandbox egress log.** Expected noise, not failures. Codex probes on +the way up and again during the run, and the policy refuses what the run does not need: | Denied | Why it appears | |---|---| -| `GET /v1/models` on `api.openai.com` | Codex refreshes its model catalog on a custom provider. The `fullsend-openai` profile allows only `POST /v1/responses`, so the probe is denied at L7, up to three times. The first allowed `POST` follows about 100 ms later. | +| `GET /v1/models` on `api.openai.com` | Codex refreshes its model catalog on a custom provider. The `fullsend-openai` profile allows only `POST /v1/responses`, so the probe is denied at L7: up to three times at startup, again every 4.5 minutes while the run lasts, and once before each sub-agent starts (0.170.0; codex logs that one as `failed to initialize model catalog`). The first allowed `POST` follows about 100 ms later. | | `GET /v1/models` on the inference gateway host | The same catalog refresh on a `gateway/` run. The gateway profile allows only the model `POST`s, so it is denied at L7 and logged by codex as `failed to refresh available models: 403`. | | `chatgpt.com:443` | A sign-in/account probe the agent run has no use for; denied at L4. | | `api.github.com:443` | Denied at L4 from codex itself — the agent reaches GitHub through the `gh` CLI and its own provider, not from the model client. | @@ -572,7 +575,7 @@ bytes`. ``` codex_spawn_without_admission: a spawn was not sent by the primary thread ``` -A spawn item without a sender, or sent by a thread other than the run's own. Codex 0.166.0 emits +A spawn item without a sender, or sent by a thread other than the run's own. Codex 0.170.0 emits neither; look for a malformed or planted stream line. ``` codex_spawn_without_admission: a spawn_agent item longer than 1048576 bytes could not be read diff --git a/images/sandbox/Containerfile b/images/sandbox/Containerfile index 73e0dd5de7..e3b2605fb7 100644 --- a/images/sandbox/Containerfile +++ b/images/sandbox/Containerfile @@ -264,14 +264,14 @@ RUN curl -fsSL --retry 3 --retry-delay 5 \ # The native binary is a *version* of the same package — # `@openai/codex@${CODEX_VERSION}-linux-`, aliased as the # optionalDependency `@openai/codex-linux-` — and the launcher -# bin/codex.js spawns that musl-static executable directly. So it is +# bin/codex.js execs that musl-static executable in place of node. So it is # `codex`, not `node`, that makes the model calls, and an egress profile # serving codex must name `**/codex` in its `binaries:` rules. That wiring # lands with the OpenAI credential work, not here. # # To update: bump CODEX_VERSION; renovate tracks this ARG via a # customManagers regex entry in renovate.json. -ARG CODEX_VERSION=0.166.0 +ARG CODEX_VERSION=0.170.0 RUN npm install -g --ignore-scripts @openai/codex@${CODEX_VERSION} \ && npm cache clean --force diff --git a/internal/cli/run_openai_test.go b/internal/cli/run_openai_test.go index a48e2bc7b3..511d205726 100644 --- a/internal/cli/run_openai_test.go +++ b/internal/cli/run_openai_test.go @@ -2312,7 +2312,7 @@ func TestReseedOpenAIAuth_WaitsForSandboxLock(t *testing.T) { // TestEmbeddedOpenAIProfileBinaries pins the `binaries:` rules of the // profile the runner imports for every fullsend-openai provider. The rule // list is what the gateway will let open a connection to api.openai.com: -// pi issues its requests from node, and codex's npm launcher spawns a +// pi issues its requests from node, and codex's npm launcher execs a // per-platform native binary that makes them itself (#6920), so both names // must be there or that runtime's first model call is refused by the proxy // with nothing in the agent's log to explain it. diff --git a/internal/cli/runtime_binaries_test.go b/internal/cli/runtime_binaries_test.go index cd119b4d31..e3b94950f6 100644 --- a/internal/cli/runtime_binaries_test.go +++ b/internal/cli/runtime_binaries_test.go @@ -18,17 +18,17 @@ import ( // kernel-resolved /proc//exe of the process that opens the connection // OR of any of its ancestors. That makes two kinds of runtime: // -// - Wrapped by node: pi is a script run by node, and codex's npm launcher -// bin/codex.js spawns the native vendor//bin/codex under node. -// **/node admits both through the ancestor; **/codex names the process -// itself. A pin bump cannot break these unless the wrapper goes away. +// - Wrapped by node: pi is a script run by node, so **/node admits it. A +// pin bump cannot break it unless the wrapper goes away. // - Exec'd directly: `claude` on PATH is a symlink to the npm package's // bin/claude.exe (2.1.2xx places the native binary there — install.cjs, // "Always write to bin/claude.exe"), so the connecting process has no // wrapper ancestor. OpenCode is installed directly as the native -// /usr/local/bin/opencode binary. Only globs on the real file names admit -// them. This is what broke every 0.40.0-image Claude run (fullsend#6971): -// **/claude alone never matched. +// /usr/local/bin/opencode binary, and codex's npm launcher bin/codex.js +// replaces node with the native vendor//bin/codex +// (process.execve). Only globs on the real file names admit them. This is +// what broke every 0.40.0-image Claude run (fullsend#6971): **/claude +// alone never matched. // // A new runtime must add its mapping here; TestScaffoldProfilesAllowRuntimeBinaries // fails for any selectable runtime without one. Decide the globs against the @@ -45,7 +45,7 @@ var runtimeEgressBinaries = map[string]map[string][]string{ "fullsend-inference-gateway": {"**/node"}, }, "codex": { - "fullsend-openai": {"**/node", "**/codex"}, + "fullsend-openai": {"**/codex"}, "fullsend-inference-gateway": {"**/codex"}, }, "opencode": { diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index 96d675030e..30d7f6bee8 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -120,7 +120,9 @@ func (r CodexRuntime) codexModelsCachePath() string { // `Failed to write last message file ... No such file or directory` in the // first end-to-end smoke. The final message is in the stream as an // agent_message either way; this file is a convenience for an operator -// inspecting a kept sandbox, and ClearIterationArtifacts removes it. +// inspecting a kept sandbox, and ClearIterationArtifacts removes it. At +// 0.170.0 codex opens it before the first turn and refuses a symlinked or +// hard-linked path; a failed open or final write ends exec with exit 1. const codexLastMessageFile = "last-message.txt" // Bootstrap prepares the runner-owned codex config directory for one agent @@ -425,7 +427,9 @@ const codexNoSubagentNote = "\n## Runtime note\n\n" + // codexChunkedReadNote is the chunked-read rule for Codex's exec truncation // (10,000 tokens, head and tail; verified at 0.157.0 and 0.166.0, the latter // live: a 200-line dense file rides whole, a larger one is cut in the middle -// behind an "N tokens truncated" marker). A single cat of a long SKILL.md +// behind an "N tokens truncated" marker; at 0.170.0 the code-mode host cuts a +// code_mode_only model such as gpt-5.6-luna at the same cap, with the same +// marker). A single cat of a long SKILL.md // drops the middle with no retry (#7831). Reading in ranges is not enough on // its own: a parent that stopped after four ranges of a 1,457-line SKILL.md // missed the dispatch rules past line 800 (#9657), so the note also says to diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index 61cea2e74f..8e81341c35 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -68,7 +68,7 @@ if [ "$2" = "exec" ]; then sh -c 'mkdir() { :; }; mv() { shift; shift; cp -- "$1" '\''` + storeDir + `/'\''"$(printf "%s" "$2" | tr / _)"; }; '"$last" exit $? ;; "codex --version") echo "` + versionOutput + `"; exit 0 ;; - "codex debug models --bundled") cat "${FULLSEND_TEST_CATALOG:-testdata/codex/models-bundled-0.166.0.json}"; exit 0 ;; + "codex debug models --bundled") cat "${FULLSEND_TEST_CATALOG:-testdata/codex/models-bundled-0.170.0.json}"; exit 0 ;; *"` + hookInterpreterSep + `"*) printf '%s` + hookInterpreterSep + `%s\n' /usr/bin/python3 /usr/local/bin:/usr/bin:/bin; exit 0 ;; # What a plain PATH lookup finds in the fleet image; Bootstrap must not use it. "command -v python3") echo "/sandbox/.venv/bin/python3"; exit 0 ;; diff --git a/internal/runtime/codex_config.go b/internal/runtime/codex_config.go index a0dcf2770d..b681f477bc 100644 --- a/internal/runtime/codex_config.go +++ b/internal/runtime/codex_config.go @@ -84,8 +84,8 @@ const codexAuthTimeoutMS = 5000 // // `[projects.""] trust_level = "untrusted"` pins the target repo's trust // decision, so its own `.codex/` layer (settings, hooks, instructions) never -// loads. It has to be stated: codex records a trust level for a git checkout -// it starts in when none is set, and "none" is not the same as untrusted. +// loads. It has to be stated: "none" is not the same as untrusted, and codex +// skips a project's own AGENTS.md only for an explicit untrusted entry. // This is the codex equivalent of pi's defaultProjectTrust "never". // // Deliberately absent: @@ -119,14 +119,14 @@ const codexAuthTimeoutMS = 5000 // children and the run-level child model. `[features] multi_agent = false` // is not enough to turn the tools off: the model's catalog entry overrides // it (verified on 0.157.0, 0.158.0 and 0.159.3; the resolution order is -// unchanged at 0.166.0). +// unchanged through 0.170.0). // // The `[features.multi_agent_v2]` table decides the collaboration protocol // of the run and of every child, whatever its model: codex checks this // feature before `[agents] enabled`. When it is on, the root gets the V2 -// tools whatever its model (verified on 0.159.3, unchanged at 0.166.0) and +// tools whatever its model (verified on 0.159.3, unchanged through 0.170.0) and // a child gets them only when its own model selects V2 in the catalog -// (collab_tools_enabled, 0.166.0). `enabled = false` is codex's default, +// (collab_tools_enabled, 0.170.0). `enabled = false` is codex's default, // the same as the scalar `[features] multi_agent_v2 = false`, stated so // that the `[agents]` table decides. `enabled = true`, for an admitted V2 // parent with a roster (ADR 0159 decision 1), brings @@ -511,7 +511,7 @@ const codexSpawnGuardMode = "SpawnGuard" // result, before the parent is notified; a block (exit 2 with a reason) // makes the child continue with the reason as its prompt instead of // finishing (codex-rs/hooks/src/events/stop.rs, core/src/session/turn.rs, -// rust-v0.166.0). +// rust-v0.170.0). const codexSubagentStopEvent = "SubagentStop" // codexWithheldNotice is the adapter's WITHHELD_NOTICE: a SubagentStop block diff --git a/internal/runtime/codex_gateway_test.go b/internal/runtime/codex_gateway_test.go index 74cd354948..967fac8864 100644 --- a/internal/runtime/codex_gateway_test.go +++ b/internal/runtime/codex_gateway_test.go @@ -155,7 +155,7 @@ func TestCodexGatewayAuthSeed_Concurrent(t *testing.T) { } // The gateway auth.command prints the seeded placeholder and nothing else; -// every other content fails the model call with no fallback. +// every other content exits non-zero, with no fallback. func TestCodexGatewayAuthScript_Executes(t *testing.T) { dir := t.TempDir() scriptPath := filepath.Join(dir, codexGatewayAuthScriptFile) diff --git a/internal/runtime/codex_hook/fullsend-codex-hook.py b/internal/runtime/codex_hook/fullsend-codex-hook.py index 8cc081d6b8..3fe6553b0e 100644 --- a/internal/runtime/codex_hook/fullsend-codex-hook.py +++ b/internal/runtime/codex_hook/fullsend-codex-hook.py @@ -18,7 +18,7 @@ CodexRuntime.Run checks this file's SHA-256 against the copy embedded in the fullsend binary before every iteration. -Wire translation (codex `rust-v0.166.0`, verified against +Wire translation (codex `rust-v0.170.0`, verified against codex-rs/hooks/src/{schema.rs,engine/output_parser.rs,events/*.rs} and codex-rs/core/src/tools/registry.rs function_hook_tool_name): diff --git a/internal/runtime/codex_hook/gateway-token.sh b/internal/runtime/codex_hook/gateway-token.sh index d0a31b2abd..b0293e1cb0 100644 --- a/internal/runtime/codex_hook/gateway-token.sh +++ b/internal/runtime/codex_hook/gateway-token.sh @@ -5,8 +5,11 @@ # (ADR 0137) and SHA-256 checked by Run before every iteration. codex runs # it with stdin on /dev/null, caches the trimmed stdout as the bearer token # for `refresh_interval_ms`, and re-runs it on expiry and on the 401 retry -# path. A non-zero exit or empty stdout fails the model call — there is no -# fallback to the environment, which is what makes this fail closed. +# path. A non-zero exit or empty stdout gives codex no token from this run, +# and there is no fallback to the environment: codex never sends a value this +# script refused, which is what makes this fail closed. After a success, codex +# (0.170.0) keeps sending the last token this script printed until one of +# those re-runs succeeds. # # What it prints is never a credential: it is the OpenShell gateway # placeholder for INFERENCE_GATEWAY_API_KEY that the runner seeded into the diff --git a/internal/runtime/codex_hook/openai-token.sh b/internal/runtime/codex_hook/openai-token.sh index 50992ea841..c8e2e13d42 100644 --- a/internal/runtime/codex_hook/openai-token.sh +++ b/internal/runtime/codex_hook/openai-token.sh @@ -5,8 +5,11 @@ # iteration. codex runs it with stdin on /dev/null, caches the trimmed stdout # as the bearer token for `refresh_interval_ms`, and re-runs it on expiry and # on the 401 retry path (codex-rs/login/src/auth/external_bearer.rs). A -# non-zero exit or empty stdout fails the model call — there is no fallback to -# the environment, which is what makes this fail closed. +# non-zero exit or empty stdout gives codex no token from this run, and there +# is no fallback to the environment: codex never sends a value this script +# refused, which is what makes this fail closed. After a success, codex +# (0.170.0) keeps sending the last token this script printed until one of +# those re-runs succeeds. # # What it prints is never a credential: it is the OpenShell gateway # placeholder for OPENAI_API_KEY that the runner seeded into the token file, diff --git a/internal/runtime/codex_hook_test.go b/internal/runtime/codex_hook_test.go index bad47fe0e9..887aa7a8e6 100644 --- a/internal/runtime/codex_hook_test.go +++ b/internal/runtime/codex_hook_test.go @@ -1779,7 +1779,7 @@ func TestCodexAdapter_SpawnGuardDenies(t *testing.T) { } // codexSubagentStopInput is the SubagentStop payload codex sends from a -// thread-spawned child (rust-v0.166.0 hooks/src/schema.rs +// thread-spawned child (rust-v0.170.0 hooks/src/schema.rs // SubagentStopCommandInput), with message as last_assistant_message. func codexSubagentStopInput(message any) map[string]any { return map[string]any{ diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index 0a566b3074..317c70cc09 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -169,7 +169,7 @@ func resolveCodexChildModels(roles []codexRole, skipped map[string]string, subag // The child effort. Codex resets a child to the run-level child model's // catalog default unless agents.default_subagent_reasoning_effort is set - // (child_config.rs, rust-v0.166.0), so the run's effort is written there + // (child_config.rs, rust-v0.170.0), so the run's effort is written there // when the run has one. Either way codex checks the effort against the // run-level child model and against a persona's own model at spawn and // refuses the spawn when the model lacks it: each is checked here. @@ -443,7 +443,7 @@ func codexParentCollabVersion(catalog codexCatalog, parentModel, agentModel stri // no agents.max_depth under V2 and gives a child of a V2 parent the // multi-agent tools only when the child's own model selects V2 // (collab_tools_enabled, codex-rs/core/src/tools/spec_plan.rs, -// rust-v0.166.0). With every model the runner binds off V2, a child it +// rust-v0.170.0). With every model the runner binds off V2, a child it // starts holds no spawn_agent. A spawn the guard did not screen can still // name a model (the schema hides the argument; the handler accepts it) or // use a rewritten role file, so for such a spawn depth one still rests on diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index 90ff887b6b..e2c87286f1 100644 --- a/internal/runtime/codex_personas_test.go +++ b/internal/runtime/codex_personas_test.go @@ -368,9 +368,9 @@ func TestCodexRole_TOMLParsesWithTheThreeKeys(t *testing.T) { // version the gate takes from its entry, and which efforts a child on it may // run at. The reduction keeps only the four fields Bootstrap reads, so a bump // that changes other catalog fields (0.166.0 rewrote model_messages for -// every entry) leaves the fixture untouched; 0.166.0's only visible change -// is the added gpt-6.1-terra entry. On a CODEX_VERSION bump regenerate it, -// never edit it (the file name carries the pin): +// every entry) leaves the fixture untouched; 0.170.0's only visible change +// is two added V2 entries, gpt-6.2-sol and gpt-6.2-astra. On a CODEX_VERSION +// bump regenerate it, never edit it (the file name carries the pin): // // codex debug models --bundled | python3 -c 'import json,sys; d=json.load(sys.stdin); json.dump({"models":[{"slug":m["slug"],"multi_agent_version":m.get("multi_agent_version"),"default_reasoning_level":m.get("default_reasoning_level"),"supported_reasoning_levels":[{"effort":l["effort"]} for l in m.get("supported_reasoning_levels") or []]} for m in d["models"]]}, sys.stdout, indent=2); print()' > testdata/codex/models-bundled-.json func TestCodexCatalog(t *testing.T) { @@ -385,7 +385,7 @@ func TestCodexCatalog(t *testing.T) { require.NoError(t, err) assert.True(t, catalog.has(codexDefaultSubagentModel), "the floor must be listed; a child takes its parent's collaboration version, so the floor's own does not matter") - assert.Equal(t, "v1", catalog.collabVersion("gpt-5.6-luna"), "a luna parent delegates on 0.166.0") + assert.Equal(t, "v1", catalog.collabVersion("gpt-5.6-luna"), "a luna parent delegates on 0.170.0") assert.Equal(t, "medium", catalog["gpt-5.6-luna"].DefaultEffort, "children on the floor run at medium when the run sets no effort") assert.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, catalog["gpt-5.6-luna"].Efforts) assert.Equal(t, "low", catalog["gpt-5.6-sol"].DefaultEffort) @@ -704,7 +704,7 @@ func TestResolveCodexChildModels_NonOpenAIValueNamesTheKey(t *testing.T) { // codexTestCatalog lists every model the tables above use, with the versions, // default efforts and supported efforts of -// testdata/codex/models-bundled-0.166.0.json; add any id a new row introduces. +// testdata/codex/models-bundled-0.170.0.json; add any id a new row introduces. func codexTestCatalog() codexCatalog { upToMax := []string{"low", "medium", "high", "xhigh", "max"} upToUltra := []string{"low", "medium", "high", "xhigh", "max", "ultra"} diff --git a/internal/runtime/codex_progress_test.go b/internal/runtime/codex_progress_test.go index bd629edb5c..b4e584650e 100644 --- a/internal/runtime/codex_progress_test.go +++ b/internal/runtime/codex_progress_test.go @@ -77,12 +77,12 @@ func TestParseCodexStream_BasicRun(t *testing.T) { thinking := codexEventsOfType[ThinkingEvent](events) require.Len(t, thinking, 1) - assert.Contains(t, thinking[0].Text, "Planning ls command and patch application") + assert.Contains(t, thinking[0].Text, "Planning sequential command execution") texts := codexEventsOfType[TextEvent](events) require.Len(t, texts, 2) assert.Contains(t, texts[0].Text, "hello.txt") - assert.Equal(t, "done", texts[1].Text) + assert.Equal(t, "Done.", texts[1].Text) // The capture has item.started *and* item.completed for both commands // and the file change; only the completions are reported. @@ -96,19 +96,19 @@ func TestParseCodexStream_BasicRun(t *testing.T) { assert.Equal(t, "Bash", tools[2].Name) assert.Equal(t, "$ /bin/zsh -lc 'cat hello.txt'", tools[2].Summary) - // codex nests its categories: input_tokens 57322 includes the 49024 + // codex nests its categories: input_tokens 78713 includes the 50048 // cached tokens (this capture wrote nothing to the cache), and - // output_tokens 295 includes the 21 reasoning tokens. The normalized - // counters are disjoint, so the five sum to the 57617 tokens the thread - // actually used rather than to 106662. + // output_tokens 322 includes the 51 reasoning tokens. The normalized + // counters are disjoint, so the five sum to the 79035 tokens the thread + // actually used rather than to 129134. tokens := codexEventsOfType[TokensEvent](events) require.Len(t, tokens, 1) - assert.Equal(t, 8298, tokens[0].InputTokens, "57322 - 49024 - 0") - assert.Equal(t, 274, tokens[0].OutputTokens, "295 - 21") - assert.Equal(t, 21, tokens[0].ReasoningTokens) - assert.Equal(t, 49024, tokens[0].CacheRead) + assert.Equal(t, 28665, tokens[0].InputTokens, "78713 - 50048 - 0") + assert.Equal(t, 271, tokens[0].OutputTokens, "322 - 51") + assert.Equal(t, 51, tokens[0].ReasoningTokens) + assert.Equal(t, 50048, tokens[0].CacheRead) assert.Equal(t, 0, tokens[0].CacheWrite) - assert.Equal(t, 57617, + assert.Equal(t, 79035, tokens[0].InputTokens+tokens[0].OutputTokens+tokens[0].ReasoningTokens+ tokens[0].CacheRead+tokens[0].CacheWrite, "the renderer sums all five, so they must not overlap") @@ -118,11 +118,11 @@ func TestParseCodexStream_BasicRun(t *testing.T) { assert.Empty(t, result.Subtype) assert.Equal(t, 1, result.NumTurns) assert.Zero(t, result.TotalCostUSD, "codex reports no cost") - assert.Equal(t, 8298, result.InputTokens) - assert.Equal(t, 274, result.OutputTokens) - assert.Equal(t, 21, result.ReasoningTokens) + assert.Equal(t, 28665, result.InputTokens) + assert.Equal(t, 271, result.OutputTokens) + assert.Equal(t, 51, result.ReasoningTokens) assert.Equal(t, 0, result.CacheCreationInputTokens) - assert.Equal(t, 49024, result.CacheReadInputTokens) + assert.Equal(t, 50048, result.CacheReadInputTokens) } // --- fixture table ---------------------------------------------------------- @@ -749,11 +749,11 @@ func TestApplyCodexMetrics(t *testing.T) { } assert.Equal(t, 1, metrics.NumTurns) - assert.Equal(t, 8298, metrics.InputTokens) - assert.Equal(t, 274, metrics.OutputTokens) - assert.Equal(t, 21, metrics.ReasoningTokens) + assert.Equal(t, 28665, metrics.InputTokens) + assert.Equal(t, 271, metrics.OutputTokens) + assert.Equal(t, 51, metrics.ReasoningTokens) assert.Equal(t, 0, metrics.CacheCreationInputTokens) - assert.Equal(t, 49024, metrics.CacheReadInputTokens) + assert.Equal(t, 50048, metrics.CacheReadInputTokens) assert.Equal(t, int32(3), metrics.ToolCalls.Load()) // Left for the runner: the stream carries neither. diff --git a/internal/runtime/codex_redact.go b/internal/runtime/codex_redact.go index 4f4bcbcbfe..98113818bc 100644 --- a/internal/runtime/codex_redact.go +++ b/internal/runtime/codex_redact.go @@ -194,7 +194,7 @@ func codexReadBounded(path string) ([]byte, error) { // codexRolloutEnvelopes are the top-level `type` values a codex rollout line // carries: every variant of RolloutItemWire in -// codex-rs/history/src/rollout_payload.rs, 0.152.1 through 0.166.0 +// codex-rs/history/src/rollout_payload.rs, 0.152.1 through 0.170.0 // (dynamic_tools_updated arrived in 0.166.0; the set was unchanged from // 0.157.0 to 0.159.3). Update it on a CODEX_VERSION bump, since one unknown // line discards the whole file. They are diff --git a/internal/runtime/codex_run_test.go b/internal/runtime/codex_run_test.go index 427f1f6554..dcd11a8579 100644 --- a/internal/runtime/codex_run_test.go +++ b/internal/runtime/codex_run_test.go @@ -730,7 +730,7 @@ func TestCodexOpenAIAuthSeed_Executes(t *testing.T) { } // TestCodexAuthScript_Executes runs the embedded auth.command script the way -// codex runs it. A non-zero exit fails the model call with no fallback to the +// codex runs it. A non-zero exit gives codex no token, with no fallback to the // environment, which is what makes the credential path fail closed. func TestCodexAuthScript_Executes(t *testing.T) { dir := t.TempDir() diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index 3e7199542f..1bdc2dd3a0 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -500,7 +500,7 @@ const codexChildRolloutsMarker = "fullsend-rollout-heads" // Codex names a rollout rollout--.jsonl (with _ // after a revert), creates it, and then writes its session_meta as the first // line, carrying parent_thread_id for a child; a root carries none (codex -// rust-v0.166.0). So a child's file can be empty while that line waits, or +// rust-v0.170.0). So a child's file can be empty while that line waits, or // start for good with a fragment a failed write left (codex closes it with a // newline and writes session_meta on the next line). Every field before // parent_thread_id is a scalar, so a line cut before its parent cannot end diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index e37b90cbd2..7a58f84ede 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -837,7 +837,7 @@ func TestCodexRun_DelegatingWithoutSpawnHasParentEntry(t *testing.T) { assert.Equal(t, 0, exit) assert.Equal(t, map[string]ModelUsage{ - "gpt-5.6-luna": {Requests: 1, InputTokens: 8298, OutputTokens: 274, CacheCreationInputTokens: 0, CacheReadInputTokens: 49024}, + "gpt-5.6-luna": {Requests: 1, InputTokens: 28665, OutputTokens: 271, CacheCreationInputTokens: 0, CacheReadInputTokens: 50048}, }, metrics.PerModelUsage, "the numbers TestApplyCodexMetrics pins for basic_run.ndjson") assertCodexUsageSumsToTotals(t, metrics) assert.NotContains(t, log, codexChildUsageMarker, "no id, no sandbox command") diff --git a/internal/runtime/testdata/codex/README.md b/internal/runtime/testdata/codex/README.md index c809233a9d..965e780ab7 100644 --- a/internal/runtime/testdata/codex/README.md +++ b/internal/runtime/testdata/codex/README.md @@ -6,7 +6,7 @@ Inputs for `parseCodexStream` (`internal/runtime/codex_progress.go`) and its tes | Fixture | Origin | |---|---| -| `basic_run.ndjson` | **Live capture**, 2026-11-03, `@openai/codex@0.166.0` (`npx`), model `gpt-5.6-luna`, host ChatGPT login. Captured by the committed `regen.sh`; the script rewrote only the throwaway working directory to `/sandbox/workspace/repo`. No manual edits. The 12 events include one reasoning item, `ls .` listing `raw.ndjson`, and `cat hello.txt` returning `hi`. | +| `basic_run.ndjson` | **Live capture**, 2026-11-18, `@openai/codex@0.170.0` (`npx`), model `gpt-5.6-luna`, host ChatGPT login. Captured by the committed `regen.sh`; the script rewrote only the throwaway working directory to `/sandbox/workspace/repo`. No manual edits. The 14 events include one reasoning item, `ls .` listing `raw.ndjson`, and `cat hello.txt` returning `hi`. The two `error` items before `turn.started` are Codex's startup warning that the capturing host's own config sets the deprecated `[features] multi_agent`; fullsend's runner config does not set that key, and the parser skips `error` items. | | everything else | Hand-authored to the structs below. | `regen.sh` re-captures `basic_run.ndjson` only. It reads `ARG CODEX_VERSION` from @@ -47,7 +47,7 @@ Codex **rollouts** (`$CODEX_HOME/sessions/**/rollout-*.jsonl`) for `foldCodexChi | `child_usage_other_model.jsonl` | A child on `gpt-5.6-terra`, every normalized counter non-zero. | | `child_usage_failed.jsonl` | A child whose model the provider rejected (404): `turn_context` names the model, `task_complete` carries `error`, and there is no `token_usage_record`, so it contributes nothing. | | `child_usage_no_model.jsonl` | A child with a `token_usage_record` and no `turn_context`: its usage is bucketed under `unknown`. | -| `child_usage_forked.jsonl` | A forked child (hand-authored from codex's fork rules, the same at 0.159.3 and 0.166.0): the parent's `turn_context` (`gpt-5.6-luna`) and `token_count` copied ahead of the child's own `turn_context` (`gpt-5.6-terra`) and `token_usage_record`; its usage lands under `gpt-5.6-terra`. | +| `child_usage_forked.jsonl` | A forked child (hand-authored from codex's fork rules, the same at 0.159.3, 0.166.0 and 0.170.0): the parent's `turn_context` (`gpt-5.6-luna`) and `token_count` copied ahead of the child's own `turn_context` (`gpt-5.6-terra`) and `token_usage_record`; its usage lands under `gpt-5.6-terra`. | The tests lay the rollouts out under a temporary sessions tree as `2026/09/29/rollout-2026-09-29T15-46-38-.jsonl`, the name codex gives a rollout, @@ -62,13 +62,14 @@ capture, with synthetic ids: `parent_thread_id` at the top level and again under ## Event structs Copied from `openai/codex` tag `rust-v0.152.1` and re-checked at `rust-v0.157.0`, -`rust-v0.159.3` and `rust-v0.166.0` (`exec_events.rs` is byte-identical from -`rust-v0.157.0` to `rust-v0.166.0`; the processor only renamed its item type to -`ThreadItemPayload` at `rust-v0.166.0`), +`rust-v0.159.3`, `rust-v0.166.0` and `rust-v0.170.0` (`exec_events.rs` is +byte-identical from `rust-v0.157.0` to `rust-v0.170.0`; the processor renamed its +item type to `ThreadItemPayload` at `rust-v0.166.0` and changed only how it +writes the `-o` file at `rust-v0.170.0`), `codex-rs/exec/src/exec_events.rs` (shapes) and `codex-rs/exec/src/event_processor_with_jsonl_output.rs` (when each event is emitted). Re-check both when `CODEX_VERSION` moves, and with them three facts the -admission cross-check (`codex_subagents.go`) rests on at `rust-v0.166.0`: a resume +admission cross-check (`codex_subagents.go`) rests on at `rust-v0.170.0`: a resume reaches the stream as a `wait` item (`CollabAgentTool::ResumeAgent => CollabTool::Wait` in the same processor); in-process delivery guarantees only TurnCompleted, the thread-state @@ -183,7 +184,7 @@ in `parseCodexStream`: does, and the renderer's total sums the counters. `codexUsage.counters()` subtracts the subsets so the five normalized counters sum to the tokens actually used. In `basic_run.ndjson` that is - 57,617; passed through unchanged it would render as 106,662. Keeping + 79,035; passed through unchanged it would render as 129,134. Keeping reasoning out of output is specific to this parser and to OpenCode: Claude Code and pi count reasoning inside output (`OutputExcludesReasoning`). - **An `error` item is not a failure.** The processor emits one for config diff --git a/internal/runtime/testdata/codex/basic_run.ndjson b/internal/runtime/testdata/codex/basic_run.ndjson index 44e5a987c5..fe67aaf854 100644 --- a/internal/runtime/testdata/codex/basic_run.ndjson +++ b/internal/runtime/testdata/codex/basic_run.ndjson @@ -1,12 +1,14 @@ -{"type":"thread.started","thread_id":"01a1a360-2fdd-73d2-9eaf-7d48d6dc1d9a"} +{"type":"thread.started","thread_id":"01a1ef70-aaae-7b33-80d6-6074b78c415d"} +{"type":"item.completed","item":{"id":"item_0","type":"error","message":"`[features].multi_agent` is deprecated. It still controls the V1 fallback. `[agents].enabled = false` disables subagent tools even when the model selects a subagent version, unless `[features].multi_agent_v2` is enabled."}} +{"type":"item.completed","item":{"id":"item_1","type":"error","message":"`[features].multi_agent` is deprecated. It still controls the V1 fallback. `[agents].enabled = false` disables subagent tools even when the model selects a subagent version, unless `[features].multi_agent_v2` is enabled."}} {"type":"turn.started"} -{"type":"item.completed","item":{"id":"item_0","type":"reasoning","text":"**Planning ls command and patch application**"}} -{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"I’ll list the workspace, create `hello.txt`, and verify its contents."}} -{"type":"item.started","item":{"id":"item_2","type":"command_execution","command":"/bin/zsh -lc 'ls .'","aggregated_output":"","exit_code":null,"status":"in_progress"}} -{"type":"item.completed","item":{"id":"item_2","type":"command_execution","command":"/bin/zsh -lc 'ls .'","aggregated_output":"raw.ndjson\n","exit_code":0,"status":"completed"}} -{"type":"item.started","item":{"id":"item_3","type":"file_change","changes":[{"path":"/sandbox/workspace/repo/hello.txt","kind":"add"}],"status":"in_progress"}} -{"type":"item.completed","item":{"id":"item_3","type":"file_change","changes":[{"path":"/sandbox/workspace/repo/hello.txt","kind":"add"}],"status":"completed"}} -{"type":"item.started","item":{"id":"item_4","type":"command_execution","command":"/bin/zsh -lc 'cat hello.txt'","aggregated_output":"","exit_code":null,"status":"in_progress"}} -{"type":"item.completed","item":{"id":"item_4","type":"command_execution","command":"/bin/zsh -lc 'cat hello.txt'","aggregated_output":"hi\n","exit_code":0,"status":"completed"}} -{"type":"item.completed","item":{"id":"item_5","type":"agent_message","text":"done"}} -{"type":"turn.completed","usage":{"input_tokens":57322,"cached_input_tokens":49024,"cache_write_input_tokens":0,"output_tokens":295,"reasoning_output_tokens":21}} +{"type":"item.completed","item":{"id":"item_2","type":"reasoning","text":"**Planning sequential command execution**"}} +{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"I’ll list the workspace, create `hello.txt`, and verify its contents."}} +{"type":"item.started","item":{"id":"item_4","type":"command_execution","command":"/bin/zsh -lc 'ls .'","aggregated_output":"","exit_code":null,"status":"in_progress"}} +{"type":"item.completed","item":{"id":"item_4","type":"command_execution","command":"/bin/zsh -lc 'ls .'","aggregated_output":"raw.ndjson\n","exit_code":0,"status":"completed"}} +{"type":"item.started","item":{"id":"item_5","type":"file_change","changes":[{"path":"/sandbox/workspace/repo/hello.txt","kind":"add"}],"status":"in_progress"}} +{"type":"item.completed","item":{"id":"item_5","type":"file_change","changes":[{"path":"/sandbox/workspace/repo/hello.txt","kind":"add"}],"status":"completed"}} +{"type":"item.started","item":{"id":"item_6","type":"command_execution","command":"/bin/zsh -lc 'cat hello.txt'","aggregated_output":"","exit_code":null,"status":"in_progress"}} +{"type":"item.completed","item":{"id":"item_6","type":"command_execution","command":"/bin/zsh -lc 'cat hello.txt'","aggregated_output":"hi\n","exit_code":0,"status":"completed"}} +{"type":"item.completed","item":{"id":"item_7","type":"agent_message","text":"Done."}} +{"type":"turn.completed","usage":{"input_tokens":78713,"cached_input_tokens":50048,"cache_write_input_tokens":0,"output_tokens":322,"reasoning_output_tokens":51}} diff --git a/internal/runtime/testdata/codex/models-bundled-0.166.0.json b/internal/runtime/testdata/codex/models-bundled-0.170.0.json similarity index 85% rename from internal/runtime/testdata/codex/models-bundled-0.166.0.json rename to internal/runtime/testdata/codex/models-bundled-0.170.0.json index 3a965d0b8a..46ef9515bd 100644 --- a/internal/runtime/testdata/codex/models-bundled-0.166.0.json +++ b/internal/runtime/testdata/codex/models-bundled-0.170.0.json @@ -1,5 +1,55 @@ { "models": [ + { + "slug": "gpt-6.2-sol", + "multi_agent_version": "v2", + "default_reasoning_level": "low", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + }, + { + "effort": "ultra" + } + ] + }, + { + "slug": "gpt-6.2-astra", + "multi_agent_version": "v2", + "default_reasoning_level": "low", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + }, + { + "effort": "ultra" + } + ] + }, { "slug": "gpt-6-astra", "multi_agent_version": "v2", diff --git a/internal/runtime/testdata/codex/regen.sh b/internal/runtime/testdata/codex/regen.sh index 6d7bb11c9b..13c6f93236 100755 --- a/internal/runtime/testdata/codex/regen.sh +++ b/internal/runtime/testdata/codex/regen.sh @@ -50,7 +50,7 @@ RAW="${WORKDIR}/raw.ndjson" # is a -c override. model_reasoning_summary=detailed is what makes the run emit # `reasoning` items, which the fixture needs to cover. stdin is closed because # codex exec reads additional prompt input from a non-terminal stdin and -# waits on it forever when the caller leaves stdin open (0.159.3; at 0.166.0 +# waits on it forever when the caller leaves stdin open (0.159.3; at 0.170.0 # it still blocks, before the first model request). npx -y --ignore-scripts "${PKG}" exec --json \ --skip-git-repo-check \ diff --git a/internal/scaffold/fullsend-repo/profiles/fullsend-openai.yaml b/internal/scaffold/fullsend-repo/profiles/fullsend-openai.yaml index 3715e4ae5f..42345dfd4c 100644 --- a/internal/scaffold/fullsend-repo/profiles/fullsend-openai.yaml +++ b/internal/scaffold/fullsend-repo/profiles/fullsend-openai.yaml @@ -33,7 +33,7 @@ endpoints: - allow: method: POST path: /v1/responses -# pi calls the API from node; codex's npm launcher (bin/codex.js) spawns the +# pi calls the API from node; codex's npm launcher (bin/codex.js) execs the # per-platform native binary, so it is `codex` — not node — that opens the # connection on that runtime (#6920). binaries: From 06ff5d8a10aa660bbb2a92d8a2ff53ff650dccf0 Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:39:20 +0000 Subject: [PATCH 026/208] ci(#9755): run agents behaviour suite on GitHub emulator Add BT_SUITE=agents to e2e/behaviour/github-emulator/run-job.sh so the agents repository's make behaviour-test can run against the GitHub emulator, built against this checkout, with no secrets. - AGENTS_DIR names the agents checkout; BT_SUITE=agents exits 2 before anything starts when $AGENTS_DIR/behaviour is missing. - BT_SUITE=agents forces AGENTS_SEED=1. Step 0b clones AGENTS_DIR and checks out its HEAD instead of github.com at AGENTS_REF; the image pre-pull, gitleaks pre-install and 4b push use that clone. The 4b log line names the source (AGENTS_DIR or AGENTS_REF). - AGENTS_PRS fetches pull/N/head from the github.com agents URL, not origin, so it also works for a clone of AGENTS_DIR. - Step 5 copies the agents go.mod to $STATE/agents.mod, adds replaces for github.com/fullsend-ai/fullsend and its separate internal/mintcore module (a dependency's replace does not apply to the main module), tidies it, and runs make behaviour-test with FULLSEND_CHECKOUT and BEHAVIOUR_GOFLAGS=-modfile=... The agents checkout's go.mod and go.sum are not modified. - The warm go test -c build uses -tags playback for playback and behaviour otherwise, never an "agents" tag. - Update the script header and the emulator section of docs/guides/dev/behaviour-testing.md. Verified: shellcheck 0.10.0 (repo args) passes; BT_SUITE=agents with AGENTS_DIR unset, missing, or lacking behaviour/ exits 2. pre-commit could not fetch hook repos (TLS error in the sandbox), so the applicable hooks (shellcheck, lint-docs-links, lychee, whitespace, EOF) were run directly and passed. The full emulator run was not exercised (needs a throwaway VM). Closes #9755 Co-Authored-By: Claude Opus 5.5 --- docs/guides/dev/behaviour-testing.md | 12 +++-- e2e/behaviour/github-emulator/run-job.sh | 67 +++++++++++++++++++----- 2 files changed, 63 insertions(+), 16 deletions(-) diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index b1acdde461..fcc794d25d 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -566,13 +566,19 @@ The script does these steps: creates the human-like test actors and their tokens. 7. It builds a supervisor image that trusts the run's CA (`supervisor-ca-image.sh`) and samples VM load (`sample-vm.sh`). -8. It runs the given features, or the playback suite when - `BT_SUITE=playback`. +8. It runs the given features, the playback suite when + `BT_SUITE=playback`, or the agents repository's `make behaviour-test` + when `BT_SUITE=agents`. The agents suite needs `AGENTS_DIR`, an agents + checkout: its `HEAD` is pushed into the emulator as `fullsend-ai/agents` + main, and its suite is built against this checkout through a modfile in + the state directory, so the checkout's `go.mod` and `go.sum` are not + changed. The script header lists every setting. The main ones are `EMULATOR_DIR` and `EMULATOR_PY` (required), `STATE_DIR` (logs; default `$RUNNER_TEMP/bt-github-emulator`, or `/tmp/bt-github-emulator`), `BT_SUITE`, -`AGENTS_SEED`, `AGENTS_REF`, `AGENTS_PRS` and `BEHAVIOUR_CAPABILITIES`. When +`AGENTS_DIR`, `AGENTS_SEED`, `AGENTS_REF`, `AGENTS_PRS` and +`BEHAVIOUR_CAPABILITIES`. When the run passes, the suite's summary line shows the passed scenarios. The state directory holds the logs, `phases.tsv` (time per phase) and the suite's artifacts. diff --git a/e2e/behaviour/github-emulator/run-job.sh b/e2e/behaviour/github-emulator/run-job.sh index 5a6a482093..76dfa8d17a 100755 --- a/e2e/behaviour/github-emulator/run-job.sh +++ b/e2e/behaviour/github-emulator/run-job.sh @@ -11,12 +11,19 @@ # EMULATOR_PY python with its requirements.txt installed [required] # STATE_DIR logs and state (default $RUNNER_TEMP/bt-github-emulator) # UPSTREAM_TOKEN optional token the emulator uses to fetch github.com actions -# BT_SUITE behaviour (default; runs the features given) or playback -# (the @playback suite, -tags playback) +# BT_SUITE behaviour (default; runs the features given), playback +# (the @playback suite, -tags playback) or agents (the +# agents repository's make behaviour-test, built against +# this checkout) +# AGENTS_DIR agents checkout, required for BT_SUITE=agents: its HEAD +# is mirrored as fullsend-ai/agents main and its behaviour +# suite is run. Its go.mod and go.sum are not changed. # AGENTS_SEED 1 to mirror github.com/fullsend-ai/agents into the # emulator as fullsend-ai/agents; the shipped agents (which -# playback runs) resolve from it. Default 1 for playback. -# AGENTS_REF agents ref to mirror as main (default main) +# playback runs) resolve from it. Default 1 for playback; +# always 1 for agents. +# AGENTS_REF agents ref to mirror as main (default main; not used with +# AGENTS_DIR) # AGENTS_PRS agents pull request numbers merged on top, space-separated # (e.g. "1871 1873", the host-aware ops scripts) # BEHAVIOUR_CAPABILITIES passed to the suite (default none). With @@ -34,8 +41,20 @@ SUITE="${BT_SUITE:-behaviour}" case "$SUITE" in behaviour) AGENTS_SEED="${AGENTS_SEED:-0}" ;; playback) AGENTS_SEED="${AGENTS_SEED:-1}" ;; - *) echo "BT_SUITE must be behaviour or playback, got $SUITE" >&2; exit 2 ;; + agents) + if [ -z "${AGENTS_DIR:-}" ] || [ ! -d "$AGENTS_DIR/behaviour" ]; then + echo "BT_SUITE=agents needs AGENTS_DIR, an agents checkout with a behaviour/ directory, got '${AGENTS_DIR:-}'" >&2 + exit 2 + fi + AGENTS_DIR="$(cd "$AGENTS_DIR" && pwd)" + AGENTS_SEED=1 + ;; + *) echo "BT_SUITE must be behaviour, playback or agents, got $SUITE" >&2; exit 2 ;; esac +# The Go build tag of the suite's own test build: the agents suite builds +# this checkout's behaviour package. +BUILD_TAG=behaviour +[ "$SUITE" = playback ] && BUILD_TAG=playback EMU_HOST=ghemu.localhost EMU="https://$EMU_HOST" ORG=halfsend @@ -99,7 +118,7 @@ build_mint() { } ( build_mint - cd "$ROOT" && go test -c -tags "$SUITE" -o "$STATE/suite-warm.test" ./e2e/behaviour/ && rm -f "$STATE/suite-warm.test" + cd "$ROOT" && go test -c -tags "$BUILD_TAG" -o "$STATE/suite-warm.test" ./e2e/behaviour/ && rm -f "$STATE/suite-warm.test" ) >"$STATE/go-warm.log" 2>&1 & go_warm_pid=$! @@ -138,16 +157,24 @@ fi tail -1 "$STATE/sandbox-host.log" phase sandbox-host -# 0b. The shipped agents, fetched from github.com before the stack starts so -# the sandbox image pre-pull overlaps the stack start instead of following -# it. They are pushed into the emulator as fullsend-ai/agents in step 4b. +# 0b. The shipped agents, fetched from github.com (or AGENTS_DIR's HEAD for +# BT_SUITE=agents) before the stack starts so the sandbox image pre-pull +# overlaps the stack start instead of following it. They are pushed into the +# emulator as fullsend-ai/agents in step 4b. if [ "$AGENTS_SEED" = 1 ]; then agents="$STATE/agents.git" rm -rf "$agents" - git clone -q --no-checkout "https://github.com/fullsend-ai/agents.git" "$agents" - git -C "$agents" checkout -q --detach "${AGENTS_REF:-main}" + if [ "$SUITE" = agents ]; then + git clone -q --no-checkout "$AGENTS_DIR" "$agents" + git -C "$agents" checkout -q --detach "$(git -C "$AGENTS_DIR" rev-parse HEAD)" + agents_source="AGENTS_DIR $AGENTS_DIR" + else + git clone -q --no-checkout "https://github.com/fullsend-ai/agents.git" "$agents" + git -C "$agents" checkout -q --detach "${AGENTS_REF:-main}" + agents_source="AGENTS_REF ${AGENTS_REF:-main}" + fi for pr in ${AGENTS_PRS:-}; do - git -C "$agents" fetch -q origin "pull/$pr/head" + git -C "$agents" fetch -q "https://github.com/fullsend-ai/agents.git" "pull/$pr/head" git -C "$agents" -c user.name=bt-github-emulator -c user.email=bt-github-emulator@localhost \ merge -q --no-edit -m "bt-github-emulator: merge agents#$pr" FETCH_HEAD done @@ -292,7 +319,7 @@ if [ "$AGENTS_SEED" = 1 ]; then ensure_source_repo agents git -C "$agents" -c credential.helper= -c http.extraheader= push -q --force \ "https://admin:$ADMIN@$EMU_HOST/fullsend-ai/agents.git" "HEAD:refs/heads/main" - echo "fullsend-ai/agents main on the emulator: $(git -C "$agents" rev-parse --short HEAD) (${AGENTS_REF:-main}${AGENTS_PRS:+ + PRs $AGENTS_PRS})" + echo "fullsend-ai/agents main on the emulator: $(git -C "$agents" rev-parse --short HEAD) ($agents_source${AGENTS_PRS:+ + PRs $AGENTS_PRS})" phase agents-push fi @@ -375,6 +402,20 @@ status=0 BEHAVIOUR_NEGATIVE_SETTLE="${BEHAVIOUR_NEGATIVE_SETTLE:-20s}" if [ "$SUITE" = playback ]; then go test -tags playback -count=1 -timeout "${SUITE_TIMEOUT:-40m}" -v ./e2e/behaviour/ -run TestPlaybackSuite + elif [ "$SUITE" = agents ]; then + # The agents suite builds against this checkout through a modfile in + # $STATE, so the agents checkout's go.mod and go.sum stay as they are. + # A dependency's own replace does not apply to the main module, so + # internal/mintcore (its own module) needs its own replace too. + cp "$AGENTS_DIR/go.mod" "$STATE/agents.mod" + : >"$STATE/agents.sum" + cd "$AGENTS_DIR" + go mod edit -modfile="$STATE/agents.mod" \ + -replace "github.com/fullsend-ai/fullsend=$ROOT" \ + -replace "github.com/fullsend-ai/fullsend/internal/mintcore=$ROOT/internal/mintcore" + go mod tidy -modfile="$STATE/agents.mod" + FULLSEND_CHECKOUT="$ROOT" BEHAVIOUR_GOFLAGS="-modfile=$STATE/agents.mod" \ + make behaviour-test BEHAVIOUR_CAPABILITIES="$CAPABILITIES" else BEHAVIOUR_FEATURES="${FEATURES[*]}" \ go test -tags behaviour -count=1 -timeout "${SUITE_TIMEOUT:-40m}" -v ./e2e/behaviour/ -run TestBehaviourSuite From 366a8138278949d149eac1424532dd962129bbd3 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 20 Nov 2026 14:43:18 -0500 Subject: [PATCH 027/208] ci(behaviour-github-emulator): run the agents suite as a non-required job Add a behaviour-github-emulator (agents) job that runs fullsend-ai/agents main's behaviour suite with BT_SUITE=agents against this checkout, on pull requests and full dispatches. It is not in the result job's needs, so the required behaviour-github-emulator check is unchanged; it shows a fullsend change that breaks the agents suite before it merges. Refs #9755 Assisted-by: Claude Signed-off-by: Wayne Sun --- .../workflows/behaviour-github-emulator.yml | 80 +++++++++++++++++++ docs/guides/dev/behaviour-testing.md | 6 ++ 2 files changed, 86 insertions(+) diff --git a/.github/workflows/behaviour-github-emulator.yml b/.github/workflows/behaviour-github-emulator.yml index fe4217a340..d4f8150e79 100644 --- a/.github/workflows/behaviour-github-emulator.yml +++ b/.github/workflows/behaviour-github-emulator.yml @@ -204,6 +204,86 @@ jobs: !${{ runner.temp }}/bt-github-emulator/stack/runner-*/_work/** if-no-files-found: warn + # The agents repository's behaviour suite (BT_SUITE=agents) against this + # checkout and fullsend-ai/agents main, so a fullsend change that breaks + # the agents suite shows here before it merges. Not required: it is not in + # the result job's needs. Pull requests only; a dispatch with explicit + # features skips it. + behaviour-github-emulator-agents: + name: behaviour-github-emulator (agents) + if: ${{ github.event_name == 'pull_request' || (github.event_name == 'workflow_dispatch' && !inputs.features) }} + runs-on: ubuntu-24.04 + timeout-minutes: 60 + steps: + - name: Checkout fullsend + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Checkout agents + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: fullsend-ai/agents + ref: main + path: .agents + persist-credentials: false + + - name: Checkout github-emulator + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ env.EMULATOR_REPO }} + ref: ${{ env.EMULATOR_REF }} + path: .emulator + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: go.mod + + - uses: astral-sh/setup-uv@e92bafb6253dcd438e0484186d7669ea7a8ca1cc # v6.4.3 + with: + enable-cache: false + + # The emulator's locked dependencies, installed with hashes, as its + # own smoke workflow does. + - name: Install emulator dependencies + run: | + python3 -m venv "$RUNNER_TEMP/emu-venv" + uv export -q --frozen --no-dev --no-emit-project --format requirements-txt --project .emulator -o "$RUNNER_TEMP/emu-requirements.txt" + uv pip install -q --python "$RUNNER_TEMP/emu-venv/bin/python" --require-hashes -r "$RUNNER_TEMP/emu-requirements.txt" + + - name: Run the agents suite + env: + EMULATOR_DIR: ${{ github.workspace }}/.emulator + EMULATOR_PY: ${{ runner.temp }}/emu-venv/bin/python + STATE_DIR: ${{ runner.temp }}/bt-github-emulator + # Read-only job token, only so the emulator can fetch public + # github.com actions without the anonymous rate limit. + UPSTREAM_TOKEN: ${{ github.token }} + BT_SUITE: agents + AGENTS_DIR: ${{ github.workspace }}/.agents + EMULATOR_RUNNERS: "12" + BEHAVIOUR_POOL_SIZE: "6" + GODOG_CONCURRENCY: "6" + SUITE_TIMEOUT: 45m + BEHAVIOUR_CAPABILITIES: applier-branch-namespace,review-skill-overrides + run: e2e/behaviour/github-emulator/run-job.sh + + - name: Upload logs + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: behaviour-github-emulator-logs-agents + path: | + ${{ runner.temp }}/bt-github-emulator/**/*.log + ${{ runner.temp }}/bt-github-emulator/phases.tsv + ${{ runner.temp }}/bt-github-emulator/bt-artifacts/ + ${{ runner.temp }}/bt-github-emulator/openshell-logs/ + !${{ runner.temp }}/bt-github-emulator/stack/runner-*/_work/** + if-no-files-found: warn + # The one check to require: green only when every shard and playback passed. behaviour-github-emulator-result: name: behaviour-github-emulator diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index fcc794d25d..7a0c28c17a 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -599,6 +599,12 @@ gated on a `@requires:capability:` tag, goes in `e2e/behaviour/github-emulator/not-sharded.txt` instead, one `` per line with a `#` comment giving the reason. +On pull requests, `behaviour-github-emulator.yml` also runs the agents +repository's suite (`BT_SUITE=agents`) against the PR and fullsend-ai/agents +`main`, as the `behaviour-github-emulator (agents)` job. It is not part of the +required `behaviour-github-emulator` check: it shows a fullsend change that +breaks the agents suite before it merges. + ### Failure classification and infrastructure retry Behaviour tests run against live infrastructure — the GitHub API, Actions From 12f4f1df89ad7df20e191c51ea7feec7e9896f3c Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 20 Nov 2026 14:52:56 -0500 Subject: [PATCH 028/208] ci(behaviour-github-emulator): skip custom-persona in the agents job The agents suite's custom-persona scenario (review-skill-overrides) needs real inference and asserts a model-computed marker, so it cannot pass on the emulator. Leave the capability off here; it stays in the agents repository's live job. Refs #9755 Assisted-by: Claude Signed-off-by: Wayne Sun --- .github/workflows/behaviour-github-emulator.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/behaviour-github-emulator.yml b/.github/workflows/behaviour-github-emulator.yml index d4f8150e79..ddf47c2c8e 100644 --- a/.github/workflows/behaviour-github-emulator.yml +++ b/.github/workflows/behaviour-github-emulator.yml @@ -268,7 +268,9 @@ jobs: BEHAVIOUR_POOL_SIZE: "6" GODOG_CONCURRENCY: "6" SUITE_TIMEOUT: 45m - BEHAVIOUR_CAPABILITIES: applier-branch-namespace,review-skill-overrides + # Not review-skill-overrides: its custom-persona scenario needs a + # real model, so it stays in the agents repository's live job. + BEHAVIOUR_CAPABILITIES: applier-branch-namespace run: e2e/behaviour/github-emulator/run-job.sh - name: Upload logs From e254d6ea143867fd12c303c2931e13e94e93d54e Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 20 Nov 2026 15:10:15 -0500 Subject: [PATCH 029/208] ci(behaviour-github-emulator): check out agents with full history run-job.sh pushes the agents checkout into the emulator as fullsend-ai/agents main. A shallow checkout is rejected there with "shallow update not allowed", so fetch the full history. Refs #9755 Assisted-by: Claude Signed-off-by: Wayne Sun --- .github/workflows/behaviour-github-emulator.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/behaviour-github-emulator.yml b/.github/workflows/behaviour-github-emulator.yml index ddf47c2c8e..ed5f4d64d4 100644 --- a/.github/workflows/behaviour-github-emulator.yml +++ b/.github/workflows/behaviour-github-emulator.yml @@ -227,6 +227,9 @@ jobs: repository: fullsend-ai/agents ref: main path: .agents + # Full history: run-job.sh pushes this checkout into the emulator + # as fullsend-ai/agents main, and a shallow clone cannot be pushed. + fetch-depth: 0 persist-credentials: false - name: Checkout github-emulator From 0819db85cef760af8b33e9bd62191f3f6fc4b97c Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Fri, 20 Nov 2026 17:02:11 -0500 Subject: [PATCH 030/208] fix(runtime): stop passing -o to codex exec At 0.170.0 codex opens the --output-last-message file before the first turn, and a failed open or final write ends exec with exit 1 even after a completed turn; 0.166.0 only warned. Nothing in the runner reads the file, so drop the flag, its constant and its ClearIterationArtifacts entry, and say in the Run bullet why there is no -o. Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 6 +++--- docs/runtimes/codex.md | 2 +- internal/runtime/codex_bootstrap.go | 14 -------------- internal/runtime/codex_run.go | 10 +++------- internal/runtime/codex_run_test.go | 1 - internal/runtime/codex_subagents_test.go | 2 -- .../testdata/codex/golden/launch-delegating.txt | 2 +- .../testdata/codex/golden/launch-gateway.txt | 2 +- .../runtime/testdata/codex/golden/launch-hooks.txt | 2 +- .../testdata/codex/golden/launch-nohooks.txt | 2 +- 10 files changed, 11 insertions(+), 32 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 5198b70d1b..069f8223da 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1324,9 +1324,9 @@ flowchart TB - `Run` executes `codex exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox [--dangerously-bypass-hook-trust] -C --model -c model_provider=fullsend-openai -c approval_policy=never -c sandbox_mode=danger-full-access [-c model_reasoning_effort=] - -o $CODEX_HOME/last-message.txt -` with the prompt piped to stdin. At 0.170.0 codex opens the - `-o` file before the first turn and refuses a symlinked or hard-linked path; a failed open or - final write ends exec with exit 1, and codex writes the file only when a turn completes. + -` with the prompt piped to stdin. It passes no `-o` (`--output-last-message`): nothing in the + runner reads that file, and at 0.170.0 a failed open or write of it ends exec with exit 1, even + after a completed turn. - **The prompt is never on argv.** On a retry iteration it carries the previous failure's text (#1050/#6494), and argv is world-readable in the sandbox. `-` is codex's explicit read-from-stdin sentinel; the pipe closes when `printf` finishes, so there is none of the diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index 3e371d9dba..c2366989b9 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -277,7 +277,7 @@ serve, and native children have not been run on that route. |---|---| | Credentials | A runner-exchanged OpenAI WIF token in CI, or your `OPENAI_API_KEY` on the runner locally — never in the sandbox. Codex reads a placeholder from a runner-owned token file and re-reads it when the credential is refreshed ([ADR 0092](../ADRs/0092-openai-wif-credential-delivery.md)). A `gateway/` model uses the inference gateway's credential the same way ([Models through an inference gateway](#models-through-an-inference-gateway-experimental)) | | Unattended | Approvals off; codex's own sandbox off, because OpenShell is the boundary. A missing credential exits before the agent starts | -| Artifacts | `output.jsonl` (the `codex exec --json` stream), `transcripts/-.jsonl` for the root thread and `transcripts/-sub-.jsonl` for each native child (`generic` for the `default` role, which codex records as no role when the spawn names no `agent_type`; `explore` keeps its name), `metrics.json` with `runtime: codex` (and `per_model_usage` for a delegating agent), plus `codex-debug.log` with `--debug`. Only uncompressed rollouts are extracted — codex compresses older sessions, so a `.jsonl.zst` is never the run's own transcript. The agent's final message is in the stream; `--output-last-message` also drops it in the runner-owned config directory inside the sandbox, which is a convenience when inspecting a kept sandbox rather than a downloaded artifact | +| Artifacts | `output.jsonl` (the `codex exec --json` stream), `transcripts/-.jsonl` for the root thread and `transcripts/-sub-.jsonl` for each native child (`generic` for the `default` role, which codex records as no role when the spawn names no `agent_type`; `explore` keeps its name), `metrics.json` with `runtime: codex` (and `per_model_usage` for a delegating agent), plus `codex-debug.log` with `--debug`. Only uncompressed rollouts are extracted — codex compresses older sessions, so a `.jsonl.zst` is never the run's own transcript. The agent's final message is in the stream | | Sub-agents | Native Codex children for an agent whose tools include `Agent` (or that declares no `tools:`), with harness security on, on a parent model Codex resolves to collaboration V1 or V2 on the direct route, under a runner-owned policy: registered roles only, fresh context, depth one, four at once, and on V2 each child's result checked before the parent receives it; see [Sub-agents](#sub-agents) | | Extra knobs | `FULLSEND_CODEX_MODEL` (the runner-side model default for codex runs; see [Models](#models)), `FULLSEND_CODEX_SUBAGENT_MODEL` (the run-level child model; the GitHub fleet workflows do not pass it; see [Child models](#child-models)) | | Not supported | `plugins:`, fallback chains, non-OpenAI providers (other than through a Responses-capable inference gateway), Chat Completions or Messages on a gateway, delegation from a `gateway/` parent, or from a V2 parent with a V2 child model (see [Sub-agents](#sub-agents)) | diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index 30d7f6bee8..7473c03469 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -111,20 +111,6 @@ func (r CodexRuntime) codexModelsCachePath() string { return r.ConfigDir() + "/" + codexModelsCacheFile } -// codexLastMessageFile is where --output-last-message writes the agent's final -// message, under the runner-owned config dir. -// -// Deliberately not the workspace output directory: that is the agent's own -// result location (FULLSEND_OUTPUT_DIR), the runner extracts everything there -// as the run's output files, and nothing creates it up front — codex reported -// `Failed to write last message file ... No such file or directory` in the -// first end-to-end smoke. The final message is in the stream as an -// agent_message either way; this file is a convenience for an operator -// inspecting a kept sandbox, and ClearIterationArtifacts removes it. At -// 0.170.0 codex opens it before the first turn and refuses a symlinked or -// hard-linked path; a failed open or final write ends exec with exit 1. -const codexLastMessageFile = "last-message.txt" - // Bootstrap prepares the runner-owned codex config directory for one agent // run: the agent body as developer_instructions in config.toml, the auth // script for the run-scoped OpenAI provider, skills, the hook scripts plus the diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index bd28c809cc..4ed22ad3a5 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -503,10 +503,7 @@ func buildCodexRunCommand(params RunParams, model codexModel, effort string, hoo if effort != "" { parts = append(parts, "-c "+shellQuote("model_reasoning_effort="+effort)) } - parts = append(parts, - "-o "+shellQuote(r.ConfigDir()+"/"+codexLastMessageFile), - "-", - ) + parts = append(parts, "-") if params.Debug != "" { parts = append(parts, "2>>"+shellQuote(sandbox.SandboxWorkspace+"/"+codexDebugLogFile)) } @@ -761,11 +758,10 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri // per-iteration. func (r CodexRuntime) ClearIterationArtifacts(sandboxName string) error { clearStrayProcesses(sandbox.Exec, sandboxName, os.Stderr, "the previous iteration") - clearCmd := fmt.Sprintf("rm -rf %s/output/* %s/* %s %s", + clearCmd := fmt.Sprintf("rm -rf %s/output/* %s/* %s", shellQuote(r.WorkspaceDir()), shellQuote(r.codexSessionsDir()), - shellQuote(r.WorkspaceDir()+"/"+codexDebugLogFile), - shellQuote(r.ConfigDir()+"/"+codexLastMessageFile)) + shellQuote(r.WorkspaceDir()+"/"+codexDebugLogFile)) _, _, _, err := sandbox.Exec(sandboxName, clearCmd, 10*time.Second) return err } diff --git a/internal/runtime/codex_run_test.go b/internal/runtime/codex_run_test.go index dcd11a8579..23863bfde2 100644 --- a/internal/runtime/codex_run_test.go +++ b/internal/runtime/codex_run_test.go @@ -228,7 +228,6 @@ func TestBuildCodexRunCommand_OrderAndFlags(t *testing.T) { "-c 'approval_policy=never'", "-c 'sandbox_mode=danger-full-access'", "-c 'model_reasoning_effort=high'", - "-o '" + sandbox.SandboxCodexConfig + "/last-message.txt'", } { assert.Contains(t, cmd, want) } diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 7a58f84ede..400f0db2c0 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -1148,7 +1148,6 @@ func TestCodexRuntime_ClearIterationArtifacts_KeepsTheFindingsLog(t *testing.T) filepath.Join(ws, ".security", "findings.jsonl"), filepath.Join(ws, "output", "result.txt"), filepath.Join(cfg, "sessions", "2026", "10", "22", "rollout-x.jsonl"), - filepath.Join(cfg, codexLastMessageFile), } { require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o755)) require.NoError(t, os.WriteFile(p, []byte("x\n"), 0o600)) @@ -1158,7 +1157,6 @@ func TestCodexRuntime_ClearIterationArtifacts_KeepsTheFindingsLog(t *testing.T) assert.FileExists(t, filepath.Join(ws, ".security", "findings.jsonl"), "the admissions of earlier iterations stay") assert.NoFileExists(t, filepath.Join(ws, "output", "result.txt")) assert.NoFileExists(t, filepath.Join(cfg, "sessions", "2026", "10", "22", "rollout-x.jsonl"), "the iteration's rollouts go") - assert.NoFileExists(t, filepath.Join(cfg, codexLastMessageFile)) } func TestCodexStderrDrops_CountsAcrossChunks(t *testing.T) { diff --git a/internal/runtime/testdata/codex/golden/launch-delegating.txt b/internal/runtime/testdata/codex/golden/launch-delegating.txt index 2c10b87e78..fb9de38877 100644 --- a/internal/runtime/testdata/codex/golden/launch-delegating.txt +++ b/internal/runtime/testdata/codex/golden/launch-delegating.txt @@ -334,4 +334,4 @@ export FULLSEND_CODEX_SPAWN_DIGESTS='agents/correctness.toml: agents/def unset TIRITH_FAIL_ON FULLSEND_CANARY_TOKEN FULLSEND_TOOL_ALLOWLIST && export TIRITH_REQUIRED='1' && export FULLSEND_EGRESS_ALLOWLIST='api.github.com:443' && -printf '%s' 'Run the agent task' | ${FULLSEND_CODEX_NODE:+"$FULLSEND_CODEX_NODE"} "$FULLSEND_CODEX_BIN" exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust -C '/sandbox/workspace/repo' --model 'gpt-5.6-luna' -c 'model_provider=fullsend-openai' -c 'approval_policy=never' -c 'sandbox_mode=danger-full-access' -c 'model_providers.fullsend-openai.base_url="https://api.openai.com/v1"' -c 'model_providers.fullsend-openai.auth.command="/sandbox/codex-config/openai-token.sh"' -c 'model_reasoning_effort=high' -o '/sandbox/codex-config/last-message.txt' - +printf '%s' 'Run the agent task' | ${FULLSEND_CODEX_NODE:+"$FULLSEND_CODEX_NODE"} "$FULLSEND_CODEX_BIN" exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust -C '/sandbox/workspace/repo' --model 'gpt-5.6-luna' -c 'model_provider=fullsend-openai' -c 'approval_policy=never' -c 'sandbox_mode=danger-full-access' -c 'model_providers.fullsend-openai.base_url="https://api.openai.com/v1"' -c 'model_providers.fullsend-openai.auth.command="/sandbox/codex-config/openai-token.sh"' -c 'model_reasoning_effort=high' - diff --git a/internal/runtime/testdata/codex/golden/launch-gateway.txt b/internal/runtime/testdata/codex/golden/launch-gateway.txt index bf27c6513f..f65293dff8 100644 --- a/internal/runtime/testdata/codex/golden/launch-gateway.txt +++ b/internal/runtime/testdata/codex/golden/launch-gateway.txt @@ -338,4 +338,4 @@ export FULLSEND_CODEX_SPAWN_DIGESTS='hooks.json:' && unset TIRITH_FAIL_ON FULLSEND_CANARY_TOKEN FULLSEND_TOOL_ALLOWLIST && export TIRITH_REQUIRED='1' && export FULLSEND_EGRESS_ALLOWLIST='api.github.com:443' && -printf '%s' 'Run the agent task' | ${FULLSEND_CODEX_NODE:+"$FULLSEND_CODEX_NODE"} "$FULLSEND_CODEX_BIN" exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust -C '/sandbox/workspace/repo' --model 'vendor/org/model' -c 'model_provider=fullsend-gateway' -c 'approval_policy=never' -c 'sandbox_mode=danger-full-access' -c 'model_providers.fullsend-gateway.base_url="https://gateway.example.com/v1"' -c 'model_providers.fullsend-gateway.auth.command="/sandbox/codex-config/gateway-token.sh"' -c 'model_reasoning_effort=high' -o '/sandbox/codex-config/last-message.txt' - +printf '%s' 'Run the agent task' | ${FULLSEND_CODEX_NODE:+"$FULLSEND_CODEX_NODE"} "$FULLSEND_CODEX_BIN" exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust -C '/sandbox/workspace/repo' --model 'vendor/org/model' -c 'model_provider=fullsend-gateway' -c 'approval_policy=never' -c 'sandbox_mode=danger-full-access' -c 'model_providers.fullsend-gateway.base_url="https://gateway.example.com/v1"' -c 'model_providers.fullsend-gateway.auth.command="/sandbox/codex-config/gateway-token.sh"' -c 'model_reasoning_effort=high' - diff --git a/internal/runtime/testdata/codex/golden/launch-hooks.txt b/internal/runtime/testdata/codex/golden/launch-hooks.txt index 3548bd7780..f79d773d63 100644 --- a/internal/runtime/testdata/codex/golden/launch-hooks.txt +++ b/internal/runtime/testdata/codex/golden/launch-hooks.txt @@ -334,4 +334,4 @@ export FULLSEND_CODEX_SPAWN_DIGESTS='hooks.json:' && unset TIRITH_FAIL_ON FULLSEND_CANARY_TOKEN FULLSEND_TOOL_ALLOWLIST && export TIRITH_REQUIRED='1' && export FULLSEND_EGRESS_ALLOWLIST='api.github.com:443' && -printf '%s' 'Run the agent task' | ${FULLSEND_CODEX_NODE:+"$FULLSEND_CODEX_NODE"} "$FULLSEND_CODEX_BIN" exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust -C '/sandbox/workspace/repo' --model 'gpt-5.6-luna' -c 'model_provider=fullsend-openai' -c 'approval_policy=never' -c 'sandbox_mode=danger-full-access' -c 'model_providers.fullsend-openai.base_url="https://api.openai.com/v1"' -c 'model_providers.fullsend-openai.auth.command="/sandbox/codex-config/openai-token.sh"' -c 'model_reasoning_effort=high' -o '/sandbox/codex-config/last-message.txt' - +printf '%s' 'Run the agent task' | ${FULLSEND_CODEX_NODE:+"$FULLSEND_CODEX_NODE"} "$FULLSEND_CODEX_BIN" exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust -C '/sandbox/workspace/repo' --model 'gpt-5.6-luna' -c 'model_provider=fullsend-openai' -c 'approval_policy=never' -c 'sandbox_mode=danger-full-access' -c 'model_providers.fullsend-openai.base_url="https://api.openai.com/v1"' -c 'model_providers.fullsend-openai.auth.command="/sandbox/codex-config/openai-token.sh"' -c 'model_reasoning_effort=high' - diff --git a/internal/runtime/testdata/codex/golden/launch-nohooks.txt b/internal/runtime/testdata/codex/golden/launch-nohooks.txt index e2024b8b4d..765bfbea30 100644 --- a/internal/runtime/testdata/codex/golden/launch-nohooks.txt +++ b/internal/runtime/testdata/codex/golden/launch-nohooks.txt @@ -277,4 +277,4 @@ test -f '/sandbox/codex-config/openai-token.sh' && { [ "$(command -p sha256sum '/sandbox/codex-config/config.toml' | command -p cut -d' ' -f1)" = '' ] || { echo 'fullsend: codex config.toml or hooks.json is not the file fullsend wrote; refusing to run (a rewritten config can trust the target repo, which loads its .codex/ layer and its hooks)' >&2; exit 98; }; } && command -p rm -f '/sandbox/codex-config/models_cache.json' && export RUST_LOG='error,opentelemetry_sdk=off,opentelemetry_otlp=off,codex_exec=warn,codex_app_server::in_process=warn' && -printf '%s' 'Run the agent task' | ${FULLSEND_CODEX_NODE:+"$FULLSEND_CODEX_NODE"} "$FULLSEND_CODEX_BIN" exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox -C '/sandbox/workspace/repo' --model 'gpt-5.6-luna' -c 'model_provider=fullsend-openai' -c 'approval_policy=never' -c 'sandbox_mode=danger-full-access' -c 'model_providers.fullsend-openai.base_url="https://api.openai.com/v1"' -c 'model_providers.fullsend-openai.auth.command="/sandbox/codex-config/openai-token.sh"' -o '/sandbox/codex-config/last-message.txt' - +printf '%s' 'Run the agent task' | ${FULLSEND_CODEX_NODE:+"$FULLSEND_CODEX_NODE"} "$FULLSEND_CODEX_BIN" exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox -C '/sandbox/workspace/repo' --model 'gpt-5.6-luna' -c 'model_provider=fullsend-openai' -c 'approval_policy=never' -c 'sandbox_mode=danger-full-access' -c 'model_providers.fullsend-openai.base_url="https://api.openai.com/v1"' -c 'model_providers.fullsend-openai.auth.command="/sandbox/codex-config/openai-token.sh"' - From 7450e6a24f95cf2714cb432aa32922bf3d4c30b0 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Fri, 20 Nov 2026 17:59:33 -0500 Subject: [PATCH 031/208] docs(runtime): rewrap the paragraphs this bump edits Whitespace only: wrap the two egress binary identity bullets and the re-check version line near 80 columns, as docs/contributing/ documentation.md asks for an edited paragraph. Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 069f8223da..87ae10986a 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -504,8 +504,18 @@ Record every applicable item in the PR description as `verified`, `blocked`, or The inference profiles (`profiles/fullsend-vertex-ai.yaml` in this repo and in fullsend-ai/agents; `profiles/fullsend-openai.yaml`, which has no fleet copy — the runner imports the embedded scaffold) carry a `binaries:` list. OpenShell's OPA (`sandbox-policy.rego`, `binary_allowed`) matches each glob against the kernel-resolved `/proc//exe` of the process that opens the connection **or of any of its ancestors**. That gives two kinds of runtime: -- **Wrapped by node** (pi): `**/node` admits it, so a pin bump cannot take it off the allowlist unless the wrapper disappears. -- **Exec'd directly** (Claude Code, OpenCode, Codex): `claude` on PATH is a symlink to the npm package's `bin/claude.exe`, OpenCode is the native `/usr/local/bin/opencode` binary, and Codex's npm launcher `bin/codex.js` replaces node with the native binary (`process.execve`). None has a wrapper ancestor, so only a glob on the real file name admits it. A renamed native binary breaks every run of that runtime on its first model call (Claude Code reports `API Error: Error code policy_denied`, 0 tokens), and the only explanation is the gateway's `NET:OPEN … DENIED … binary '…' not allowed in policy '_provider_'` line (#6971). +- **Wrapped by node** (pi): `**/node` admits it, so a pin bump cannot take it + off the allowlist unless the wrapper disappears. +- **Exec'd directly** (Claude Code, OpenCode, Codex): `claude` on PATH is a + symlink to the npm package's `bin/claude.exe`, OpenCode is the native + `/usr/local/bin/opencode` binary, and Codex's npm launcher `bin/codex.js` + replaces node with the native binary (`process.execve`). None has a wrapper + ancestor, so only a glob on the real file name admits it. A renamed native + binary breaks every run of that runtime on its first model call (Claude Code + reports `API Error: Error code policy_denied`, 0 tokens), and the only + explanation is the gateway's + `NET:OPEN … DENIED … binary '…' not allowed in policy '_provider_'` + line (#6971). `TestScaffoldProfilesAllowRuntimeBinaries` (`internal/cli/runtime_binaries_test.go`) fails for any selectable runtime without a mapping and pins the ones below. @@ -1250,7 +1260,8 @@ re-checked on a `CODEX_VERSION` bump. The decisions are Everything below was read at tag `rust-v0.152.1`; the rows of [Re-check on a `CODEX_VERSION` bump](#re-check-on-a-codex_version-bump) were -re-verified at `rust-v0.157.0`, at `rust-v0.159.3`, at `rust-v0.166.0` and again at `rust-v0.170.0`. +re-verified at `rust-v0.157.0`, at `rust-v0.159.3`, at `rust-v0.166.0` and +again at `rust-v0.170.0`. Two of the findings are the reason the hook adapter exists at all, because forwarding the scripts' own convention would fail **open**. From c96f47c47064571bbb0a0b7fdcdc4ab130028ae1 Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:22:37 +0000 Subject: [PATCH 032/208] docs(#9767): document moving the GitHub emulator pin Add a "Moving to a new emulator release" subsection to the behaviour testing guide's GitHub emulator section. It says where the pin lives (EMULATOR_REPO / EMULATOR_REF in behaviour-github-emulator.yml), its " # " format, the check to run first (the whole workflow twice on a branch that changes only EMULATOR_REF), that the agents repository's emulator job follows the pin, and that a maintainer adds the change because it edits a workflow file. The EMULATOR_REF bump to 2026.11.20.2 is out of scope here; per the issue it is added during review. Note: pre-commit could not fetch hook repositories (TLS error), so the applicable hooks were run directly: whitespace, end-of-file, line-ending and merge-marker checks, gitleaks, lint-docs-links, lint-broken-symlinks, and the lychee lint-md-links command. All passed. `make lint-md-links` itself could not exec lychee in the sandbox; the same lychee command run directly passed. Closes #9767 Co-Authored-By: Claude Opus 5.5 --- docs/guides/dev/behaviour-testing.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index 7a0c28c17a..a9a7181a3e 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -605,6 +605,22 @@ repository's suite (`BT_SUITE=agents`) against the PR and fullsend-ai/agents required `behaviour-github-emulator` check: it shows a fullsend change that breaks the agents suite before it merges. +#### Moving to a new emulator release + +1. The pin is `EMULATOR_REPO` / `EMULATOR_REF` in + `.github/workflows/behaviour-github-emulator.yml`. `EMULATOR_REF` is written + like an action pin: ` # `. + Releases are CalVer tags on fullsend-ai/github-emulator. The + [release notes](https://github.com/fullsend-ai/github-emulator/releases) + list behaviour changes. +2. Before you move the pin, make a branch of current fullsend `main` that + changes only `EMULATOR_REF` to the release's commit. Run the whole workflow + on it twice. Every shard and the playback job must pass both times, and the + `behaviour-github-emulator (agents)` job should pass too. +3. The agents repository's emulator job reads the pin from the fullsend + checkout it builds. It follows this pin with no change of its own. +4. Changing the pin edits a workflow file, so a maintainer adds it. + ### Failure classification and infrastructure retry Behaviour tests run against live infrastructure — the GitHub API, Actions From c3108a2b066f7f2ce606a58b85731af049d19eea Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 20 Nov 2026 18:25:03 -0500 Subject: [PATCH 033/208] ci(behaviour-github-emulator): pin the GitHub emulator to 2026.11.20.2 2026.11.20.2 answers the runner's GET jobrequests/{requestId}, keeps a finished job's first end report, and gives no new job to a Busy poll. This fixes a job handed to a runner whose previous worker was still exiting failing before any step ran (fullsend-ai/github-emulator#99). Validated twice on a branch of current main changing only EMULATOR_REF: every shard and playback passed (86/86), and the agents job passed 11/11 with custom-persona skipped. Refs #9767 Assisted-by: Claude Signed-off-by: Wayne Sun --- .github/workflows/behaviour-github-emulator.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/behaviour-github-emulator.yml b/.github/workflows/behaviour-github-emulator.yml index ed5f4d64d4..f4cdc41930 100644 --- a/.github/workflows/behaviour-github-emulator.yml +++ b/.github/workflows/behaviour-github-emulator.yml @@ -47,7 +47,7 @@ env: # scripts/ci-seed-mint-apps.py run the stack, so a bump changes what # every scenario runs against. Bump on purpose, like an action pin. EMULATOR_REPO: fullsend-ai/github-emulator - EMULATOR_REF: c70f705a1a8c0888975ef3723ba913a2166277fa # 2026.11.20.1 + EMULATOR_REF: 8e2ac09353f3f1cfbd138de29ebf158ce1f8451f # 2026.11.20.2 jobs: behaviour-github-emulator: From eae86990db073fd576e962b5b2d2e52bfeef5413 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Fri, 20 Nov 2026 18:27:46 -0500 Subject: [PATCH 034/208] docs(behaviour-testing): say how to run and land an emulator pin move Say how to run the two validation runs (a draft pull request, then Re-run all jobs), keep the pin's tag comment in the branch, make the agents job a hard requirement, say who lands the change, and turn the agents note into a note rather than a step. Refs #9767 Assisted-by: Claude Signed-off-by: Wayne Sun --- docs/guides/dev/behaviour-testing.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index a9a7181a3e..85d374cb8a 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -613,13 +613,17 @@ breaks the agents suite before it merges. Releases are CalVer tags on fullsend-ai/github-emulator. The [release notes](https://github.com/fullsend-ai/github-emulator/releases) list behaviour changes. -2. Before you move the pin, make a branch of current fullsend `main` that - changes only `EMULATOR_REF` to the release's commit. Run the whole workflow - on it twice. Every shard and the playback job must pass both times, and the - `behaviour-github-emulator (agents)` job should pass too. -3. The agents repository's emulator job reads the pin from the fullsend - checkout it builds. It follows this pin with no change of its own. -4. Changing the pin edits a workflow file, so a maintainer adds it. +2. Make a branch from current fullsend `main` that changes only + `EMULATOR_REF`, to ` # `, and open a draft + pull request from it: the workflow runs on `pull_request`. Run it a second + time with **Re-run all jobs** on the pull request's + `behaviour-github-emulator` run. Every shard, the playback job and the + `behaviour-github-emulator (agents)` job must pass both times. +3. A maintainer opens or takes over the pull request that moves the pin, since + it edits a workflow file, and links the two validation runs in it. + +The agents repository's emulator job reads the pin from the fullsend checkout it +builds, so it follows this pin with no change in that repository. ### Failure classification and infrastructure retry From 8639cdd41715a89c26407cd6601f0f13e9d69a5f Mon Sep 17 00:00:00 2001 From: Gwenneg Lepage <10584698+gwenneg@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:17:09 +0100 Subject: [PATCH 035/208] feat(#9132): read Jira authorization lists from the environment The jira authorization entry's write and triage lists can now name an environment variable with groups_from and accounts_from, so group and account IDs stay out of a public repository's config.yaml. Config and poller: - The poller reads the variable on every poll. The value is a list separated by commas or newlines. An unset or empty variable grants no one, and the poller logs a warning that names the variable. - Config loading rejects a role that sets both forms of one field, and an empty or invalid variable name. - The poller never logs the values. - The docs and the config test use a placeholder account ID. Managed GitHub poll workflow: - The managed caller forwards FULLSEND_JIRA_WRITE_GROUPS, FULLSEND_JIRA_WRITE_ACCOUNTS, FULLSEND_JIRA_TRIAGE_GROUPS and FULLSEND_JIRA_TRIAGE_ACCOUNTS to the poll step when config.yaml reads them. reusable-poll-jira.yml declares them as optional. - A new job with no secrets sets the dispatch matrix output. GitHub drops a job output that contains a value of a secret the job has, and the matrix holds the acting account's ID, which can equal a list secret. The poll job saves the dispatch file as an artifact, after checking it for Jira credentials, including ones that JSON escaped. Each call names its artifact with a random suffix, so two calls in one run do not share it. repos install: - It fails before any write when config.yaml uses groups_from or accounts_from and the repository's jobs run a release that predates them, on any forge. Every job runs the CLI at the scaffold's ref, and an older CLI cannot load the config. repos status reports the same error. Without an upstream GitHub client, a stamped scaffold's ref is not checked. A vendored install runs its own binary, so it is checked only when the managed GitHub poll caller passes a list secret: that caller calls the upstream workflow at the pinned ref. A user-owned GitHub poll caller that pins a reusable-poll-jira.yml older than the keys fails too, unless the install is vendored: that workflow installs the CLI at its own ref. - It warns about a variable name other than the four above, for the managed caller and for a user-owned caller of reusable-poll-jira.yml, because that workflow accepts only those four. It also warns about a user-owned caller that does not pass one of the four that the config names. It never writes or deletes these secrets. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Gwenneg Lepage <10584698+gwenneg@users.noreply.github.com> --- .github/workflows/reusable-poll-jira.yml | 130 +++++++++-- docs/cli/repos.md | 17 +- docs/guides/getting-started/operations.md | 1 + .../infrastructure-reference.md | 5 + docs/guides/user/custom-poller-example.md | 8 + docs/guides/user/jira-integration.md | 202 +++++++++++++++++- docs/reference/config-reference.md | 26 ++- internal/cli/poll.go | 42 ++-- internal/cli/poll_jira_gitlab.go | 2 +- internal/cli/poll_test.go | 47 +++- internal/config/config.go | 104 ++++++++- internal/config/config_test.go | 100 ++++++++- internal/config/effective_test.go | 6 +- internal/config/managed-config-schema | 4 + internal/config/managed.go | 8 +- internal/repos/converge.go | 9 +- internal/repos/github_jira_poll.go | 189 ++++++++++++++-- internal/repos/github_jira_poll_test.go | 156 +++++++++++++- internal/repos/jira_poll.go | 130 ++++++++++- internal/repos/jira_poll_test.go | 140 +++++++++++- internal/repos/status.go | 25 +++ internal/repos/workflow_test_helper_test.go | 13 +- .../templates/jira-poll-per-repo.yaml | 8 +- internal/scaffold/github_kill_switch_test.go | 11 +- internal/scaffold/jira_poll.go | 33 ++- internal/scaffold/jira_poll_test.go | 118 +++++++++- .../scaffold/workflow_call_alignment_test.go | 24 ++- 27 files changed, 1426 insertions(+), 132 deletions(-) diff --git a/.github/workflows/reusable-poll-jira.yml b/.github/workflows/reusable-poll-jira.yml index 0bbe60e618..91252c17dd 100644 --- a/.github/workflows/reusable-poll-jira.yml +++ b/.github/workflows/reusable-poll-jira.yml @@ -6,30 +6,36 @@ # - Optional secrets: FULLSEND_JIRA_TOKEN / FULLSEND_JIRA_EMAIL for API-token # authentication, or FULLSEND_JIRA_CLIENT_ID / FULLSEND_JIRA_CLIENT_SECRET # for OAuth 2.0 client credentials. The Jira client validates the pair. -# - Optional inputs: runner_image (runner for the poll job) and timeout_minutes -# (job timeout; defaults to 15 minutes and can be raised by the caller). +# - Optional secrets FULLSEND_JIRA_WRITE_GROUPS, FULLSEND_JIRA_WRITE_ACCOUNTS, +# FULLSEND_JIRA_TRIAGE_GROUPS and FULLSEND_JIRA_TRIAGE_ACCOUNTS: the jira +# authorization lists that .fullsend/config.yaml reads with groups_from and +# accounts_from, so the lists stay out of a public repository (#9132). +# - Optional inputs: runner_image (runner for both jobs) and timeout_minutes +# (timeout of each job; defaults to 15 minutes and can be raised by the +# caller). # - Output: matrix is the JSON include matrix for reusable-dispatch.yml; an -# empty include array means there were no Jira issues to dispatch. +# empty include array means there were no Jira issues to dispatch. The matrix +# job sets it, not the poll job (see the comment on that job). # Runs `fullsend poll --input-driver jira-poll` against the caller's # .fullsend/config.yaml and returns the dispatch matrix to the caller. The # caller passes it to reusable-dispatch.yml at the same ref (ADR 62). # The poll normally completes within 15 minutes; the caller controls the job # timeout through timeout_minutes to account for its runner and Jira latency. # -# Security: Jira credentials reach only the poll step. They are never -# forwarded to agents or the runner-secret bundle. +# Security: Jira credentials reach only the poll and check steps. They are +# never forwarded to agents or the runner-secret bundle. name: Jira poll on: workflow_call: inputs: runner_image: - description: GitHub Actions runner image for the poll job. + description: GitHub Actions runner image for the Jira poll jobs. type: string required: false default: "ubuntu-24.04" timeout_minutes: - description: Maximum runtime in minutes for the Jira poll job. + description: Maximum runtime in minutes for each Jira poll job. type: number required: false default: 15 @@ -42,10 +48,18 @@ on: required: false FULLSEND_JIRA_CLIENT_SECRET: required: false + FULLSEND_JIRA_WRITE_GROUPS: + required: false + FULLSEND_JIRA_WRITE_ACCOUNTS: + required: false + FULLSEND_JIRA_TRIAGE_GROUPS: + required: false + FULLSEND_JIRA_TRIAGE_ACCOUNTS: + required: false outputs: matrix: description: Dispatch matrix accepted by reusable-dispatch.yml. - value: ${{ jobs.poll.outputs.matrix }} + value: ${{ jobs.matrix.outputs.matrix || '{"include":[]}' }} jobs: poll: @@ -55,7 +69,8 @@ jobs: permissions: contents: read outputs: - matrix: ${{ steps.matrix.outputs.matrix }} + dispatch_count: ${{ steps.check.outputs.count }} + artifact_suffix: ${{ steps.check.outputs.artifact_suffix }} steps: - name: Checkout caller repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -104,6 +119,12 @@ jobs: FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + # The poller reads these only when config.yaml names them with + # groups_from or accounts_from, and never prints them. + FULLSEND_JIRA_WRITE_GROUPS: ${{ secrets.FULLSEND_JIRA_WRITE_GROUPS }} + FULLSEND_JIRA_WRITE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_WRITE_ACCOUNTS }} + FULLSEND_JIRA_TRIAGE_GROUPS: ${{ secrets.FULLSEND_JIRA_TRIAGE_GROUPS }} + FULLSEND_JIRA_TRIAGE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_TRIAGE_ACCOUNTS }} TARGET_REPO: ${{ github.repository }} run: | set -euo pipefail @@ -113,16 +134,95 @@ jobs: --output dispatches.json \ --fullsend-dir .fullsend + # The matrix job has no secrets, so GitHub no longer blocks a Jira + # credential in its output. Check for one here instead. + - name: Check dispatches + id: check + env: + FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }} + FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} + FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} + FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + run: | + set -euo pipefail + jq -e 'type == "array"' dispatches.json > /dev/null + # JSON escapes characters such as quotes, so search the decoded + # strings, not the file. + jq -r '.. | strings' dispatches.json > dispatch-strings.txt + for name in FULLSEND_JIRA_TOKEN FULLSEND_JIRA_EMAIL FULLSEND_JIRA_CLIENT_ID FULLSEND_JIRA_CLIENT_SECRET; do + # Trim the value as the CLI does. An empty grep pattern matches + # every line, and a padded one matches nothing. + value="$(sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e '/^$/d' <<< "${!name}")" + if [[ -n "${value}" ]] && grep -qF -f <(printf '%s\n' "${value}") dispatch-strings.txt; then + echo "::error::dispatches.json contains ${name}; not passing it on." + exit 1 + fi + done + # A run can call this workflow more than once, and artifact names are + # unique per run, so each call names its artifact with its own suffix. + echo "artifact_suffix=$(openssl rand -hex 8)" >> "${GITHUB_OUTPUT}" + echo "count=$(jq length dispatches.json)" >> "${GITHUB_OUTPUT}" + + # The poller has already advanced its Jira checkpoints, so a failed + # upload would lose this cycle's dispatches. Try it twice. + - name: Save dispatches + id: save + if: ${{ steps.check.outputs.count != '0' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fullsend-jira-dispatches-${{ steps.check.outputs.artifact_suffix }} + path: dispatches.json + if-no-files-found: error + retention-days: 1 + overwrite: true + + - name: Save dispatches (second try) + if: ${{ steps.save.outcome == 'failure' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fullsend-jira-dispatches-${{ steps.check.outputs.artifact_suffix }} + path: dispatches.json + if-no-files-found: error + retention-days: 1 + overwrite: true + + # Builds the matrix in a job without secrets. GitHub drops a job output that + # contains the value of a secret the job has, and the matrix holds the ID of + # the account that acted, which can equal a list secret such as + # FULLSEND_JIRA_WRITE_ACCOUNTS. + matrix: + name: Build dispatch matrix + needs: poll + # "!= '0'", not "> 0": an empty (dropped) count still runs this job. + if: ${{ needs.poll.outputs.dispatch_count != '0' }} + runs-on: ${{ inputs.runner_image }} + timeout-minutes: ${{ inputs.timeout_minutes }} + permissions: {} + outputs: + matrix: ${{ steps.matrix.outputs.matrix }} + steps: + # If both tries fail, "Re-run failed jobs" reads the artifact again + # while it is kept (1 day). "Re-run all jobs" would poll again and find + # nothing. + - name: Read dispatches + id: read + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: fullsend-jira-dispatches-${{ needs.poll.outputs.artifact_suffix }} + + - name: Read dispatches (second try) + if: ${{ steps.read.outcome == 'failure' }} + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: fullsend-jira-dispatches-${{ needs.poll.outputs.artifact_suffix }} + - name: Build dispatch matrix id: matrix run: | set -euo pipefail - jq -e 'type == "array"' dispatches.json > /dev/null - if jq -e 'length == 0' dispatches.json > /dev/null; then - echo "No dispatches." - echo 'matrix={"include":[]}' >> "${GITHUB_OUTPUT}" - exit 0 - fi + jq -e 'type == "array" and length > 0' dispatches.json > /dev/null MATRIX=$(jq -c '{include: .}' dispatches.json) DELIM="MATRIX_$(openssl rand -hex 8)" { diff --git a/docs/cli/repos.md b/docs/cli/repos.md index c5d95574dc..9f608c9efa 100644 --- a/docs/cli/repos.md +++ b/docs/cli/repos.md @@ -677,6 +677,16 @@ flag or environment variable supplies them. When install manages the caller, it checks that its upstream ref contains `reusable-poll-jira.yml`. An older pin fails with no credential or workflow changes; upgrade the pin to a ref that includes the workflow. + When the `jira` authorization entry reads a list with `groups_from` or + `accounts_from`, the poll job also receives the + `FULLSEND_JIRA_WRITE_GROUPS`, `FULLSEND_JIRA_WRITE_ACCOUNTS`, + `FULLSEND_JIRA_TRIAGE_GROUPS`, or `FULLSEND_JIRA_TRIAGE_ACCOUNTS` secret it + names. Install warns about any other name, which the caller cannot pass. + It also warns when a poll workflow you maintain calls + `reusable-poll-jira.yml` without passing a secret the entry names. + You set these secrets + yourself; install and uninstall never write or delete them. See + [Keeping the lists out of the repository](../guides/user/jira-integration.md#keeping-the-lists-out-of-the-repository). Install changes the file only when it carries the `# fullsend-component: jira-poll` marker line. A workflow at that path without the marker, such as one copied from the Jira guide, is reported and @@ -692,7 +702,12 @@ flag or environment variable supplies them. environment variable available to all environments. The same rules apply to `--jira-client-secret` and an existing `FULLSEND_JIRA_CLIENT_SECRET`. Supplying any Jira credential flag when no selected repo enables polling - fails the run. + fails the run. When the `jira` authorization entry uses `groups_from` or + `accounts_from` and `fullsend_ref` pins a release that predates them, the + repo fails before any write, on GitHub and GitLab, with polling enabled or + not. On GitHub with polling enabled, it also fails when a poll workflow you + maintain calls a `reusable-poll-jira.yml` that predates them, unless the + install is vendored. `repos status` reports the same errors. - **Dry run.** `--dry-run` lists Jira secrets by name only and reports the poll-resource changes it would make. - **Command-line only.** `--jira-token`, `--jira-email`, `--jira-client-id`, diff --git a/docs/guides/getting-started/operations.md b/docs/guides/getting-started/operations.md index 9efdd77657..2e3424d206 100644 --- a/docs/guides/getting-started/operations.md +++ b/docs/guides/getting-started/operations.md @@ -44,6 +44,7 @@ fullsend github set "$OWNER/$REPO" FULLSEND_GCP_REGION global | `FULLSEND_JIRA_TOKEN` | Repo secret | Jira API token for polling and Jira-originated agent status updates when effective `tracker.jira.poll.enabled` is `true`, written by `repos install --jira-token` (required on the first install unless client credentials are supplied; an omitted flag keeps the existing secret; `repos uninstall` deletes it) | (Jira API token) | | `FULLSEND_JIRA_EMAIL` | Repo secret | Optional Jira account email for the same poller and agent status calls, written by `repos install --jira-email`; an omitted flag keeps the existing secret; `repos uninstall` deletes it | `poller@example.com` | | `FULLSEND_JIRA_CLIENT_ID` / `FULLSEND_JIRA_CLIENT_SECRET` | Repo secret | A service account's OAuth 2.0 credential, used instead of `FULLSEND_JIRA_TOKEN` (never both). GitHub poll and Jira-originated dispatch workflows forward them to the Jira client; `repos install` writes them on GitHub and GitLab. `repos uninstall` deletes them | (OAuth client credentials) | +| `FULLSEND_JIRA_WRITE_GROUPS` / `FULLSEND_JIRA_WRITE_ACCOUNTS` / `FULLSEND_JIRA_TRIAGE_GROUPS` / `FULLSEND_JIRA_TRIAGE_ACCOUNTS` | Repo secret (optional) | Comma-separated Jira group IDs or account IDs that the `jira` authorization entry reads with `groups_from` or `accounts_from`, so the lists stay out of the repository. The managed poll workflow passes the ones the entry names to the poll job only. Set with `gh secret set`; `repos install` and `repos uninstall` never write or delete them. See [Keeping the lists out of the repository](../user/jira-integration.md#keeping-the-lists-out-of-the-repository) | `,` | | `FULLSEND_TRACE_SIGNING_KEY` | Repo secret | Trace-context signing key ([ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)): standard base64 of a 32-byte Ed25519 seed, generated by `repos install`, which records its public key in `repos.yaml` as `config.trace_context`. [Trace signing keys](../../cli/repos.md#trace-signing-keys) lists when install writes it. Nothing reads it yet. `fullsend run` keeps it from harnesses. `repos uninstall` deletes it | (generated) | | `FULLSEND_GITHUB_RUNNER_SECRETS` | Repo or org secret (optional) | JSON object of name → value for host-side scripts, read through each harness's `env.runner`. Set with `gh secret set`, not `fullsend github set`; see [Pass secrets to host-side scripts](../user/bring-your-own-agent.md#pass-secrets-to-host-side-scripts-github) | `{"JIRA_API_TOKEN":"..."}` | diff --git a/docs/guides/infrastructure/infrastructure-reference.md b/docs/guides/infrastructure/infrastructure-reference.md index bb8de5bf54..055c7d7b3a 100644 --- a/docs/guides/infrastructure/infrastructure-reference.md +++ b/docs/guides/infrastructure/infrastructure-reference.md @@ -348,6 +348,11 @@ Secrets and variables are deployed on the target repository. not by `github setup`) - `FULLSEND_JIRA_TOKEN`, `FULLSEND_JIRA_EMAIL` — Jira API token and optional account email for repos whose effective `tracker.jira.poll.enabled` is `true`, used by the poller and Jira-originated agent status updates (written by `repos install --jira-token` / `--jira-email`; an omitted flag keeps the existing secret; deleted by `repos uninstall`; not set by `github setup`) - `FULLSEND_JIRA_CLIENT_ID`, `FULLSEND_JIRA_CLIENT_SECRET` — a service account's OAuth 2.0 credential, an alternative to `FULLSEND_JIRA_TOKEN` (never both). GitHub poll and Jira-originated dispatch workflows forward them to the Jira client, and `repos install` writes them on GitHub and GitLab; `repos uninstall` deletes them +- `FULLSEND_JIRA_WRITE_GROUPS`, `FULLSEND_JIRA_WRITE_ACCOUNTS`, + `FULLSEND_JIRA_TRIAGE_GROUPS`, `FULLSEND_JIRA_TRIAGE_ACCOUNTS` — optional, + set by you: the Jira group or account IDs that the `jira` authorization + entry reads with `groups_from` or `accounts_from` + ([setup](../user/jira-integration.md#keeping-the-lists-out-of-the-repository)) - `FULLSEND_TRACE_SIGNING_KEY` — trace-context signing key ([ADR 0154](../../ADRs/0154-correlate-work-item-and-behaviour-scenario-traces.md)): standard base64 of a 32-byte Ed25519 seed, generated by `repos install`, diff --git a/docs/guides/user/custom-poller-example.md b/docs/guides/user/custom-poller-example.md index e9928aa76e..574cd33730 100644 --- a/docs/guides/user/custom-poller-example.md +++ b/docs/guides/user/custom-poller-example.md @@ -112,6 +112,14 @@ tracker: See [Jira Integration § Custom JQL](jira-integration.md#custom-jql). +> **If the poll job receives a `jira` authorization list secret** (see +> [Keeping the lists out of the repository](jira-integration.md#keeping-the-lists-out-of-the-repository)), +> do not set the `matrix` output in that job, as this example does. GitHub +> drops a job output that contains the value of a secret the job has, and +> the matrix contains the ID of the account that acted. Set the output from +> a second job that receives no list secret. See +> [GitHub: Vault or another secret store](jira-integration.md#github-vault-or-another-secret-store). + ## Matrix Format The `matrix` input (a GitHub Actions [matrix strategy](https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/running-variations-of-jobs-in-a-workflow#using-a-matrix-strategy) that runs parallel jobs) must follow the format produced by `fullsend dispatch --output-driver gha-matrix`: diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 16201c9d38..860200fab6 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -962,7 +962,10 @@ commit or pull request as the rest of the installation. The workflow: - passes the selected Jira credential set to the poll job. For Jira-originated runs, it passes the same set to Fullsend's status writer; the values do not enter the runner-secret bundle or sandbox. The built-in agents' harnesses - map the same set in `env.runner` for their post-scripts' own Jira writes. + map the same set in `env.runner` for their post-scripts' own Jira writes; +- passes the poll job the authorization list secrets that the `jira` entry + reads, if any (see + [Keeping the lists out of the repository](#keeping-the-lists-out-of-the-repository)). The workflow has no Jira URL, project, or query inputs. The poller reads them from the configuration. Both reusable workflows are pinned to the scaffold's @@ -980,7 +983,8 @@ earlier version of this guide, it has no marker: install reports it and leaves it untouched. Delete that file and re-run `repos install` to switch to the managed workflow. -**How this works:** The poll job queries Jira and builds a dispatch matrix in +**How this works:** The poll job queries Jira and saves the dispatch records. +A second job, which receives no secrets, turns them into a dispatch matrix in the format expected by `reusable-dispatch.yml`. When the `matrix` input is provided, `reusable-dispatch.yml` skips its routing and dispatch steps and goes directly to running harness agents with the pre-computed matrix. Because @@ -1297,7 +1301,7 @@ The `event_payload` field is a structured execution payload object wrapping issu } }, "actor": { - "id": "5f7c012e0b2a4c001f3d9876", + "id": "712020:00000000-0000-0000-0000-000000000000", "kind": "human", "role": "write", "is_entity_author": false, @@ -1332,7 +1336,7 @@ authorization: - provider: jira write: # Fullsend role write groups: [example-team-developers] - accounts: ["5f7c012e0b2a4c001f3d9876"] # Jira account IDs + accounts: ["712020:00000000-0000-0000-0000-000000000000"] # Jira account IDs triage: # Fullsend role triage groups: [example-team] accounts: [] @@ -1385,6 +1389,193 @@ Jira's user-groups API, once per actor per poll cycle. Account entries are compared with the actor's account ID directly. To find an account ID, open the user's Jira profile: the ID is the last part of its URL. +### Keeping the lists out of the repository + +On a public repository, anyone can read `.fullsend/config.yaml`, and so the +`jira` lists: + +- An account ID identifies a person on your Atlassian site. +- A group name often describes the team. +- Together, the lists show which accounts can make the agents change the + repository. + +List groups by group ID, not by name, and use groups rather than `accounts`. +Jira returns a group's name or members only to a caller with the *Browse +users and groups* global permission +([Get users from group](https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-groups/#api-rest-api-3-group-member-get)). +A site does not grant it to people who are not signed in unless an admin +chose to +([Prevent or remove public access](https://confluence.atlassian.com/servicedeskcloud/prevent-or-remove-public-access-1097175896.html)). +To keep the IDs private whatever the site's settings, read a list from an +environment variable with `groups_from` or `accounts_from`: + +```yaml +authorization: + - provider: jira + write: + groups_from: FULLSEND_JIRA_WRITE_GROUPS # value: "," + triage: + groups_from: FULLSEND_JIRA_TRIAGE_GROUPS + labels: allowlist +``` + +- The variable holds a comma-separated list. One entry per line also works. + The poller trims spaces around each entry and drops empty entries. Write + the entries bare, with no quotes or brackets. Entries match like the + inline list: a group name or group ID for `groups_from`, an account ID + for `accounts_from`. +- The poller reads the variable on every poll, so a new value applies from + the next poll, with no change to the repository. +- An unset or empty variable grants no one, like an empty inline list. The + list still counts as set, so Jira project roles do not decide instead. The + poller logs a warning that names the variable on every poll. +- A role sets either `groups` or `groups_from`, and either `accounts` or + `accounts_from`. Config loading fails when a role sets both forms of one + field. Mixing fields is fine, for example `groups_from` with inline + `accounts`. +- The poller never prints the values or the groups it resolves. +- The lists stay out of the repository, but the account that acts is not + hidden. On GitHub, when an account triggers an agent, its account ID is in + that run's dispatch record. The record is in the poll run's artifact and in + the agent job's log, as it is with inline lists. Groups are never in it. +- Every job runs the CLI at the repository's `fullsend_ref`, and a release + that predates `groups_from` and `accounts_from` can't load the config. When + the `jira` entry uses them and `fullsend_ref` pins such a release, + `fullsend repos install` fails before it changes anything. Upgrade + `fullsend_ref` and run install again. + +The poll job checks the roles, so the variable must be in the poll job's +environment. + +#### GitHub: repository secrets + +The managed poll workflow can pass four repository secrets to the poller: +`FULLSEND_JIRA_WRITE_GROUPS`, `FULLSEND_JIRA_WRITE_ACCOUNTS`, +`FULLSEND_JIRA_TRIAGE_GROUPS`, and `FULLSEND_JIRA_TRIAGE_ACCOUNTS`. + +1. Store each list as a repository secret: + + ```bash + gh secret set FULLSEND_JIRA_WRITE_GROUPS --repo / --body "," + ``` + +2. Name the secret in the `jira` entry, as in the example above. +3. Run `fullsend repos install`. Install adds the secrets that the `jira` + entry names to `.github/workflows/fullsend-poll-jira.yml`, which passes + them to the poll job only. GitHub masks secret values in logs. + +To change who is authorized, update the secret. Install never writes or +deletes these secrets, and `repos uninstall` leaves them in place. + +When the `jira` entry names any other variable, install warns: the managed +workflow cannot pass it, so that list grants no one unless the runner's own +environment sets the variable. + +#### GitHub: Vault or another secret store + +Fullsend does not read Vault or any other store itself. Choose one route: + +- Keep the managed workflow, and let the store keep the repository secret + above up to date. For example, Vault Enterprise secrets sync can write + GitHub repository secrets. +- Maintain your own poll workflow (see [Scheduled workflow](#scheduled-workflow) + for how install treats a workflow without the marker line). Add a step + before the step that runs `fullsend poll --input-driver jira-poll`, and + give the variable any name. + +In your own workflow, `hashicorp/vault-action` can read Vault with GitHub's +OIDC token, so GitHub stores no Vault token. The job needs +`id-token: write`, and Vault needs a JWT role bound to the repository and +workflow. The action exports each value as an environment variable and masks +it in logs: + +```yaml + - name: Read the Jira lists from Vault + uses: hashicorp/vault-action@ # pin to a release + with: + url: https://vault.example.com + method: jwt + role: fullsend-jira-poll + secrets: | + secret/data/fullsend/jira write_groups | FULLSEND_JIRA_WRITE_GROUPS ; + secret/data/fullsend/jira triage_groups | FULLSEND_JIRA_TRIAGE_GROUPS +``` + +Your workflow must install a fullsend release that supports `groups_from` +and `accounts_from`. An older release rejects them as unknown fields. + +For a store with no GitHub Action: + +1. Fetch the value in a script step, as one line: + + ```bash + VALUE="$( | tr -s '\r\n' ',')" + ``` + + `tr` joins a list stored one entry per line. Without it, step 2 masks + only the first line and prints the others. +2. Mask it before anything else prints it: + + ```bash + echo "::add-mask::$VALUE" + ``` + + GitHub then replaces the value with `***` in logs. +3. Append `NAME=value` to `$GITHUB_ENV`: + + ```bash + echo "FULLSEND_JIRA_WRITE_GROUPS=$VALUE" >> "$GITHUB_ENV" + ``` + + Later steps in the job, including the poll step, then see the variable. + +Set the dispatch matrix output in a job that does not receive the list +secrets. GitHub drops a job output that contains a value of a secret the job +has, and the matrix contains the ID of the account that acted, which can equal +a list value. For example, save the dispatch file as an artifact in the poll +job, and set the output from a second job that reads it. +`reusable-poll-jira.yml` does it this way. + +#### GitLab: CI/CD variables + +The Jira poll job receives the project's CI/CD variables, so any variable +name works. Use a name without the `FULLSEND_` prefix, for example +`JIRA_WRITE_GROUPS`: `fullsend repos status` reports a `FULLSEND_` variable +it does not manage as an orphan and exits with an error. Add one CI/CD +variable per list, under the name the `jira` entry uses, set up like +fullsend's own secrets: + +- **Type:** Variable, not File. +- **Environments:** All (default). +- **Visibility:** Masked and hidden (GitLab 17.4 or later), or Masked. +- **Flags:** select **Protect variable** and clear **Expand variable + reference**. GitLab masks a value that contains a comma only when + expansion is off, and only in GitLab 15.9 or later. See + [Mask a CI/CD variable](https://docs.gitlab.com/ci/variables/#mask-a-cicd-variable). +- **Value:** at least 8 characters, with no spaces, for example + `,`. A group name that contains a space can't be + masked, so use the group ID. + +GitLab gives the variable to every job in pipelines on protected branches or +tags, not only the Jira poll job: agent jobs and the project's own jobs get it +too. The poller never prints the value, and if another job does, the log +shows `[MASKED]`. + +GitLab refuses to save a masked variable whose value breaks its masking +rules. Before GitLab 15.9 a masked value can't contain a comma, so only a +list with one entry can be masked there: upgrade GitLab to store a longer +list. Do not save the list unmasked. + +A pipeline variable with the same name, such as one set on a pipeline +schedule, replaces the project variable +([CI/CD variable precedence](https://docs.gitlab.com/ci/variables/#cicd-variable-precedence)). +Keep `ci_pipeline_variables_minimum_override_role` at `no_one_allowed`, which +`fullsend repos install` requires +([Prerequisites](../getting-started/configuring-gitlab.md#prerequisites)): +GitLab then refuses new schedule variables. A variable added to a schedule +earlier still applies, so run `fullsend repos install` after you apply the +setting: it replaces a Jira poll schedule that has variables. + ### Minimum Jira permissions | Permission | When the poller account needs it | @@ -1533,6 +1724,9 @@ However, more pollers against the same Jira project means more API calls per cyc | `load project roles for PROJ: ... 401 You cannot edit the configuration of this project` | The poller read Jira project roles without Administer Projects. That happens with no `jira` entry in `.fullsend/config.yaml`, with `labels: project_roles`, or on a slash command when the entry sets no lists | Add a `jira` entry with `write`/`triage` lists so project roles are not read, or grant the poller account the **Administrators** project role. See [Minimum Jira permissions](#minimum-jira-permissions) | | `resolve jira list groups: ... get user groups` errors | The `jira` lists name groups, or project-role resolution found a role granted to a group, but the poller account lacks the Browse users and groups global permission | Grant Browse users and groups, or list account IDs instead of groups | | Slash command ignored (with `jira` lists) | Actor is not in the `write` list (or the `triage` list for triage-level agents) | Add the actor's account ID or one of their groups to the right list — see [Actor role resolution](#actor-role-resolution) | +| Everyone is denied after a list moves to `groups_from` or `accounts_from`, and the poll log shows ` is unset or empty, so it grants no one` | The variable is unset or empty in the poll job: the secret is missing, or the managed GitHub workflow cannot pass its name (install warns) | Set the variable. On GitHub with the managed workflow, use one of the four `FULLSEND_JIRA_*` secret names and run `fullsend repos install` — see [Keeping the lists out of the repository](#keeping-the-lists-out-of-the-repository) | +| `pinned fullsend_ref "..." does not support` or `the installed scaffold's ref "..." does not support` from `repos install` | The repository's jobs run a release that predates `groups_from` and `accounts_from` | Set `fullsend_ref` to a release that includes them and run install again | +| `set groups or groups_from, not both` (or `accounts`) | One role sets both the inline list and its `*_from` form | Keep one form for that field | | Slash command ignored (without `jira` lists) | Actor lacks `write` role in Jira project | The actor must be a member of a Jira project role named exactly "Developers" or "Administrators" — see [Project role mapping](#project-role-mapping) if you use custom role names | | Issue opened or edited on Jira never dispatches triage | A `jira` entry is present but sets no `write` or `triage` list and not `labels: project_roles`, so opened and edited events are unresolved (with no `jira` entry, or with `labels: project_roles` and no lists, they resolve through project roles) | Add `write`/`triage` lists to the entry, or set `labels: project_roles`. See [Actor role resolution](#actor-role-resolution) | | Label added but nothing dispatched | There is no `jira` entry, or it sets `labels: allowlist` or `labels: project_roles`, and the label author is not authorized by it | Add the author to the lists, or add a `jira` entry with the default `labels: jira_editors` | diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index a937ef8efa..9030a48b64 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -89,9 +89,9 @@ authorization: # Extra sources of permission for triggerin - provider: jira # Jira (jira-poll): who may trigger agents from Jira events write: # Fullsend role write groups: [example-team-developers] # Jira group names (or group IDs) - accounts: ["5f7c012e0b2a4c001f3d9876"] # Jira account IDs + accounts: ["712020:00000000-0000-0000-0000-000000000000"] # Jira account IDs triage: # Fullsend role triage - groups: [example-team] + groups_from: FULLSEND_JIRA_TRIAGE_GROUPS # Or read a list from an environment variable (GitLab: use a name without the FULLSEND_ prefix) accounts: [] labels: jira_editors # Label-added events: jira_editors (default), allowlist, project_roles @@ -692,6 +692,7 @@ GitLab authorization |---|---| | `write.groups`, `write.accounts` | Jira groups (by name or group ID) and Jira account IDs granted the fullsend `write` role | | `triage.groups`, `triage.accounts` | Jira groups and account IDs granted the fullsend `triage` role | +| `write.groups_from`, `write.accounts_from`, `triage.groups_from`, `triage.accounts_from` | The name of an environment variable that holds that list as comma-separated values, instead of the inline list | | `labels` | How a label-added event is authorized: `jira_editors` (default once the entry is present), `allowlist`, or `project_roles` | - **Slash commands and other non-label events:** when the entry sets a @@ -718,14 +719,31 @@ GitLab authorization resolution calls the same API for an actor when a project role is granted to a group. +- **Lists from the environment:** on a public repository, anyone can read + `config.yaml`, including the lists. `groups_from` and `accounts_from` name + an environment variable instead, such as a GitHub repository secret. The + poller reads it on every poll, splits it on commas and newlines, trims each + entry, and drops empty ones. It never prints the values. An unset or empty variable grants + no one, the list still counts as set, and the poller logs a warning that + names the variable. A role cannot set both `groups` + and `groups_from`, or both `accounts` and `accounts_from`. The variable + name must use letters, digits, and underscores, and must not start with a + digit. The managed GitHub poll workflow passes only + `FULLSEND_JIRA_WRITE_GROUPS`, `FULLSEND_JIRA_WRITE_ACCOUNTS`, + `FULLSEND_JIRA_TRIAGE_GROUPS`, and `FULLSEND_JIRA_TRIAGE_ACCOUNTS`. On + GitLab, use a name without the `FULLSEND_` prefix, such as + `JIRA_TRIAGE_GROUPS` + ([GitLab: CI/CD variables](../guides/user/jira-integration.md#gitlab-cicd-variables)). See + [Keeping the lists out of the repository](../guides/user/jira-integration.md#keeping-the-lists-out-of-the-repository). + To keep today's behavior explicitly, use the two-line entry `- provider: jira` with `labels: project_roles` and no lists. The provider is opt-in. Without a `jira` entry, every Jira event, including label-added events, resolves through the project role lookup and takes the per-harness role threshold, which needs Administer Projects. Unknown keys in a `jira` entry, an -unknown `labels` value, and empty group or account entries fail config -loading. See +unknown `labels` value, empty group or account entries, and an empty or +invalid `*_from` variable name fail config loading. See [Jira integration](../guides/user/jira-integration.md#actor-role-resolution) for the permissions each setting needs. diff --git a/internal/cli/poll.go b/internal/cli/poll.go index 5ff2d42e40..846158fc9b 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -3,6 +3,7 @@ package cli import ( "context" "fmt" + "log" "os" "regexp" "strconv" @@ -204,7 +205,7 @@ func runJiraPoll(cmd *cobra.Command, jiraURL, jiraProject, jqlOverride, targetRe return fmt.Errorf("build CEL matcher: %w", err) } - poller := jirapoll.New(jiraClient, matcher, jiraPollOptions(args, matcher)) + poller := jirapoll.New(jiraClient, matcher, jiraPollOptions(args, matcher, os.Getenv)) return poller.Run(cmd.Context()) } @@ -564,10 +565,11 @@ func jiraAuthOptions(p *config.AuthorizationProvider) harnessdispatch.AuthOption // jiraPollOptions builds the poller options every jira-poll target forge // shares: the Jira connection, the query, the output path and the jira -// authorization provider the matcher loaded. Forge-specific callers set +// authorization provider the matcher loaded, with any groups_from and +// accounts_from list read through getenv. Forge-specific callers set // their own TargetForge, GitLabURL and Dispatcher on the result, so the // authorization lists reach the poller on every target. -func jiraPollOptions(args jiraPollArgs, matcher *celMatcher) jirapoll.Options { +func jiraPollOptions(args jiraPollArgs, matcher *celMatcher, getenv func(string) string) jirapoll.Options { return jirapoll.Options{ TargetRepo: args.targetRepo, JiraBaseURL: args.jira.baseURL, @@ -575,27 +577,43 @@ func jiraPollOptions(args jiraPollArgs, matcher *celMatcher) jirapoll.Options { JQL: args.jira.jql, OutputPath: args.outputPath, - Authorization: jiraPollAuthorization(matcher.jiraAuth), + Authorization: jiraPollAuthorization(matcher.jiraAuth, getenv), } } // jiraPollAuthorization converts the jira authorization provider to the -// poller's option type. A nil provider is the zero value. -func jiraPollAuthorization(p *config.AuthorizationProvider) jirapoll.Authorization { +// poller's option type, reading each groups_from and accounts_from list +// through getenv on every poll. An unset or empty variable leaves that list +// empty, which denies everyone it would have named, and logs a warning. A +// nil provider is the zero value. The resolved lists can identify people, +// so they are never logged. +func jiraPollAuthorization(p *config.AuthorizationProvider, getenv func(string) string) jirapoll.Authorization { if p == nil { return jirapoll.Authorization{} } - list := func(l *config.JiraActorList) jirapoll.ActorList { - if l == nil { - return jirapoll.ActorList{} + list := func(role string, l *config.JiraActorList) jirapoll.ActorList { + groups, accounts := l.Resolved(getenv) + if l != nil { + warnEmptyJiraEnvList(role+".groups_from", l.GroupsFrom, groups) + warnEmptyJiraEnvList(role+".accounts_from", l.AccountsFrom, accounts) } - return jirapoll.ActorList{Groups: l.Groups, Accounts: l.Accounts} + return jirapoll.ActorList{Groups: groups, Accounts: accounts} } return jirapoll.Authorization{ Configured: true, - Write: list(p.Write), - Triage: list(p.Triage), + Write: list("write", p.Write), + Triage: list("triage", p.Triage), ListsConfigured: p.Write != nil || p.Triage != nil, Labels: p.EffectiveJiraLabels(), } } + +// warnEmptyJiraEnvList logs when the variable a groups_from or accounts_from +// key names grants no one, so a missing secret does not stop every agent +// without a sign. It prints the variable's name, which config.yaml already +// shows, never its value. +func warnEmptyJiraEnvList(key, name string, entries []string) { + if name != "" && len(entries) == 0 { + log.Printf("WARNING: jira authorization %s: %s is unset or empty, so it grants no one", key, name) + } +} diff --git a/internal/cli/poll_jira_gitlab.go b/internal/cli/poll_jira_gitlab.go index 090f0f5e1b..e3a9b372b5 100644 --- a/internal/cli/poll_jira_gitlab.go +++ b/internal/cli/poll_jira_gitlab.go @@ -156,7 +156,7 @@ func runJiraPollGitLab(cmd *cobra.Command, f jiraPollGitLabFlags) error { ChildDispatchJobToken: childJobToken, }) - opts := jiraPollOptions(args, matcher) + opts := jiraPollOptions(args, matcher, os.Getenv) opts.TargetForge = jirapoll.TargetForgeGitLab opts.GitLabURL = gitlabURL opts.Dispatcher = jiradispatch.GitLabDispatcher{Poller: glPoller} diff --git a/internal/cli/poll_test.go b/internal/cli/poll_test.go index 918d534409..d07baa6fef 100644 --- a/internal/cli/poll_test.go +++ b/internal/cli/poll_test.go @@ -1,7 +1,9 @@ package cli import ( + "bytes" "context" + "log" "net/http" "net/http/httptest" "os" @@ -737,7 +739,7 @@ authorization: Triage: jirapoll.ActorList{Accounts: []string{"acct"}}, ListsConfigured: true, Labels: config.JiraLabelsAllowlist, - }, jiraPollAuthorization(m.jiraAuth)) + }, jiraPollAuthorization(m.jiraAuth, noJiraEnv)) // Kill switch keeps the provider so the poller's role resolution is // configured consistently. @@ -750,7 +752,7 @@ authorization: require.NoError(t, err) require.NotNil(t, m.jiraAuth) assert.True(t, m.Auth.JiraLabelsByEditPermission) - assert.Equal(t, jirapoll.Authorization{Configured: true, Labels: config.JiraLabelsEditors}, jiraPollAuthorization(m.jiraAuth)) + assert.Equal(t, jirapoll.Authorization{Configured: true, Labels: config.JiraLabelsEditors}, jiraPollAuthorization(m.jiraAuth, noJiraEnv)) // An invalid labels value fails config loading. require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" @@ -763,6 +765,9 @@ authorization: assert.Contains(t, err.Error(), "invalid labels") } +// noJiraEnv is a getenv that sets no variable. +func noJiraEnv(string) string { return "" } + func TestJiraPollOptions_ForwardsAuthorization(t *testing.T) { dir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" @@ -781,7 +786,7 @@ authorization: jira: jiraPollSettings{baseURL: "https://jira.example.com", apiURL: config.DefaultJiraAPIURL, project: "PROJ", jql: "project = PROJ", enabled: true}, targetRepo: "group/sub/repo", outputPath: "out.json", fullsendDir: dir, } - opts := jiraPollOptions(args, m) + opts := jiraPollOptions(args, m, noJiraEnv) assert.Equal(t, jirapoll.Options{ TargetRepo: "group/sub/repo", JiraBaseURL: "https://jira.example.com", @@ -805,13 +810,39 @@ authorization: assert.True(t, opts.Authorization.Configured) assert.Equal(t, jirapoll.ActorList{Groups: []string{"devs"}}, opts.Authorization.Write) + // Lists read from the environment convert to the same authorization. + // An unset variable leaves its list empty, which denies everyone, and + // logs a warning that names the variable. + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" +authorization: + - provider: jira + write: + groups_from: WRITE_GROUPS + triage: + accounts_from: TRIAGE_ACCOUNTS + labels: allowlist +`), 0o644)) + m, err = newCELMatcher(context.Background(), dir) + require.NoError(t, err) + var logs bytes.Buffer + prevOut := log.Writer() + log.SetOutput(&logs) + t.Cleanup(func() { log.SetOutput(prevOut) }) + env := map[string]string{"WRITE_GROUPS": "devs", "TRIAGE_ACCOUNTS": "acct"} + assert.Equal(t, opts.Authorization, jiraPollOptions(args, m, func(k string) string { return env[k] }).Authorization) + assert.Empty(t, logs.String()) + assert.Equal(t, jirapoll.Authorization{Configured: true, ListsConfigured: true, Labels: config.JiraLabelsAllowlist}, + jiraPollOptions(args, m, noJiraEnv).Authorization) + assert.Contains(t, logs.String(), "write.groups_from: WRITE_GROUPS is unset or empty") + assert.Contains(t, logs.String(), "triage.accounts_from: TRIAGE_ACCOUNTS is unset or empty") + // With no jira entry both forges get the zero value: project roles for // every event, as before the provider existed. require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte(`version: "1" `), 0o644)) m, err = newCELMatcher(context.Background(), dir) require.NoError(t, err) - assert.Equal(t, jirapoll.Authorization{}, jiraPollOptions(args, m).Authorization) + assert.Equal(t, jirapoll.Authorization{}, jiraPollOptions(args, m, noJiraEnv).Authorization) } func TestNewCELMatcher_RejectsInvalidAuthorization(t *testing.T) { @@ -849,10 +880,10 @@ func TestJiraPollAuthorization_EmptyListsStayConfigured(t *testing.T) { got := jiraPollAuthorization(&config.AuthorizationProvider{ Provider: config.AuthProviderJira, Write: &config.JiraActorList{}, - }) + }, noJiraEnv) assert.True(t, got.ListsConfigured) assert.True(t, got.HasLists()) - assert.False(t, jiraPollAuthorization(&config.AuthorizationProvider{Provider: config.AuthProviderJira}).HasLists()) + assert.False(t, jiraPollAuthorization(&config.AuthorizationProvider{Provider: config.AuthProviderJira}, noJiraEnv).HasLists()) } func TestNewCELMatcher_NullListKeysStayConfigured(t *testing.T) { @@ -869,7 +900,7 @@ func TestNewCELMatcher_NullListKeysStayConfigured(t *testing.T) { m, err := newCELMatcher(context.Background(), dir) require.NoError(t, err) require.NotNil(t, m.jiraAuth) - got := jiraPollAuthorization(m.jiraAuth) + got := jiraPollAuthorization(m.jiraAuth, noJiraEnv) assert.True(t, got.ListsConfigured) assert.True(t, got.HasLists()) }) @@ -886,6 +917,6 @@ func TestNewCELMatcher_RejectsAliasedMisspelledJiraKey(t *testing.T) { } func TestJiraPollAuthorization_NilProvider(t *testing.T) { - assert.Equal(t, jirapoll.Authorization{}, jiraPollAuthorization(nil)) + assert.Equal(t, jirapoll.Authorization{}, jiraPollAuthorization(nil, noJiraEnv)) assert.False(t, jiraAuthOptions(nil).JiraLabelsByEditPermission) } diff --git a/internal/config/config.go b/internal/config/config.go index 2e0a7b4ea7..5d7619cc74 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -361,16 +361,85 @@ type AuthorizationProvider struct { // JiraActorList names the Jira actors granted one Fullsend role by the // jira authorization provider. Groups are Jira group names (or group IDs); // accounts are Jira account IDs. +// +// GroupsFrom and AccountsFrom name an environment variable that holds the +// list instead, as comma-separated values, so the list stays out of a +// public repository. The poller reads the variable on every run (see +// Resolved). A list sets either Groups or GroupsFrom, and either Accounts +// or AccountsFrom, not both. type JiraActorList struct { - Groups []string `yaml:"groups,omitempty"` - Accounts []string `yaml:"accounts,omitempty"` + Groups []string `yaml:"groups,omitempty"` + GroupsFrom string `yaml:"groups_from,omitempty"` + Accounts []string `yaml:"accounts,omitempty"` + AccountsFrom string `yaml:"accounts_from,omitempty"` } -// IsEmpty reports whether l lists no group and no account. +// IsEmpty reports whether l lists no group and no account, and names no +// environment variable to read them from. func (l *JiraActorList) IsEmpty() bool { - return l == nil || (len(l.Groups) == 0 && len(l.Accounts) == 0) + return l == nil || (len(l.Groups) == 0 && len(l.Accounts) == 0 && l.GroupsFrom == "" && l.AccountsFrom == "") } +// Resolved returns the groups and accounts l grants. Inline entries are +// returned as configured. A GroupsFrom or AccountsFrom variable is read +// with getenv and split on commas and newlines; blank entries are dropped, so an unset +// or empty variable grants no one. The values can identify people: callers +// must never log or print them. +func (l *JiraActorList) Resolved(getenv func(string) string) (groups, accounts []string) { + if l == nil { + return nil, nil + } + groups, accounts = l.Groups, l.Accounts + if l.GroupsFrom != "" { + groups = splitJiraActorEnv(getenv(l.GroupsFrom)) + } + if l.AccountsFrom != "" { + accounts = splitJiraActorEnv(getenv(l.AccountsFrom)) + } + return groups, accounts +} + +// splitJiraActorEnv splits a *_from variable's value on commas and +// newlines, trimming each entry and dropping blank ones. Newlines separate +// entries so a secret stored one ID per line still matches. Spaces do not, +// because a Jira group name can contain them. +func splitJiraActorEnv(value string) []string { + var out []string + for _, entry := range strings.FieldsFunc(value, func(r rune) bool { return r == ',' || r == '\n' }) { + if entry = strings.TrimSpace(entry); entry != "" { + out = append(out, entry) + } + } + return out +} + +// JiraEnvNames returns the sorted, de-duplicated environment variable +// names that the jira provider's write: and triage: lists read through +// groups_from and accounts_from. It returns nil when p is nil or names none. +func (p *AuthorizationProvider) JiraEnvNames() []string { + if p == nil { + return nil + } + var names []string + for _, l := range []*JiraActorList{p.Write, p.Triage} { + if l == nil { + continue + } + for _, name := range []string{l.GroupsFrom, l.AccountsFrom} { + if name != "" && !slices.Contains(names, name) { + names = append(names, name) + } + } + } + slices.Sort(names) + return names +} + +// validJiraEnvName matches a groups_from or accounts_from value: a portable +// environment variable name, using only the characters that GitHub Actions +// secret names and GitLab CI/CD variable keys allow. +var validJiraEnvName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + // HasJiraLists reports whether the jira provider sets a write: or triage: // list, even an empty one. When it does, the lists are authoritative for // Jira actors (an actor they do not name is denied) and the Jira project @@ -393,7 +462,7 @@ var jiraProviderKeys = map[string]bool{"provider": true, "write": true, "triage" // jiraActorListKeys are the keys allowed in a jira provider write:/triage: // mapping. -var jiraActorListKeys = map[string]bool{"groups": true, "accounts": true} +var jiraActorListKeys = map[string]bool{"groups": true, "groups_from": true, "accounts": true, "accounts_from": true} // UnmarshalYAML implements yaml.Unmarshaler. Per-repo config is decoded // without strict field checking, so a jira provider entry's keys (and its @@ -429,6 +498,13 @@ func (p *AuthorizationProvider) UnmarshalYAML(value *yaml.Node) error { if err := checkMappingKeys(v, jiraActorListKeys, "authorization: jira provider "+key); err != nil { return err } + // An empty or null *_from decodes to "", which would read + // as "not set" and silently drop the key. + for _, from := range []string{"groups_from", "accounts_from"} { + if f := mappingNode(v, from); f != nil && f.Kind == yaml.ScalarNode && (f.Tag == "!!null" || strings.TrimSpace(f.Value) == "") { + return managedFieldError(f, fmt.Sprintf("authorization: jira provider %s.%s: empty environment variable name", key, from)) + } + } } } } @@ -524,6 +600,24 @@ func validateJiraProvider(p AuthorizationProvider) error { if l.list == nil { continue } + for _, f := range []struct { + field, from string + inline bool + }{ + // A present inline key conflicts even when its list is empty. + {"groups", l.list.GroupsFrom, l.list.Groups != nil}, + {"accounts", l.list.AccountsFrom, l.list.Accounts != nil}, + } { + if f.from == "" { + continue + } + if f.inline { + return fmt.Errorf("jira provider %s: set %s or %s_from, not both", l.name, f.field, f.field) + } + if !validJiraEnvName.MatchString(f.from) { + return fmt.Errorf("jira provider %s.%s_from: invalid environment variable name %q: use letters, digits and underscores, not starting with a digit", l.name, f.field, f.from) + } + } for _, g := range l.list.Groups { if strings.TrimSpace(g) == "" { return fmt.Errorf("jira provider %s.groups: empty group name", l.name) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 7b31480a1b..dcc34b380c 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -205,7 +205,7 @@ authorization: - provider: jira write: groups: [example-team-developers] - accounts: ["5f7c012e0b2a4c001f3d9876"] + accounts: ["712020:00000000-0000-0000-0000-000000000000"] triage: groups: [example-team] accounts: [] @@ -216,7 +216,7 @@ authorization: ja := cfg.JiraAuthorization() require.NotNil(t, ja) assert.Equal(t, []string{"example-team-developers"}, ja.Write.Groups) - assert.Equal(t, []string{"5f7c012e0b2a4c001f3d9876"}, ja.Write.Accounts) + assert.Equal(t, []string{"712020:00000000-0000-0000-0000-000000000000"}, ja.Write.Accounts) assert.Equal(t, []string{"example-team"}, ja.Triage.Groups) assert.True(t, ja.HasJiraLists()) assert.Equal(t, JiraLabelsAllowlist, ja.EffectiveJiraLabels()) @@ -227,6 +227,66 @@ authorization: assert.Equal(t, []string{"example-team-developers"}, cfg.JiraAuthorization().Write.Groups) } +func TestParsePerRepoConfig_JiraAuthorizationFromEnv(t *testing.T) { + cfg, err := ParsePerRepoConfig([]byte(` +authorization: + - provider: jira + write: + groups_from: FULLSEND_JIRA_WRITE_GROUPS + accounts_from: FULLSEND_JIRA_WRITE_ACCOUNTS + triage: + groups_from: FULLSEND_JIRA_TRIAGE_GROUPS + accounts: ["712020:00000000-0000-0000-0000-000000000000"] + labels: allowlist +`)) + require.NoError(t, err) + require.NoError(t, cfg.(PerRepoConfigWriter).Validate()) + ja := cfg.JiraAuthorization() + require.NotNil(t, ja) + assert.Equal(t, &JiraActorList{GroupsFrom: "FULLSEND_JIRA_WRITE_GROUPS", AccountsFrom: "FULLSEND_JIRA_WRITE_ACCOUNTS"}, ja.Write) + // Different fields of one role may use different forms. + assert.Equal(t, &JiraActorList{GroupsFrom: "FULLSEND_JIRA_TRIAGE_GROUPS", Accounts: []string{"712020:00000000-0000-0000-0000-000000000000"}}, ja.Triage) + assert.False(t, ja.Write.IsEmpty()) + assert.Equal(t, []string{"FULLSEND_JIRA_TRIAGE_GROUPS", "FULLSEND_JIRA_WRITE_ACCOUNTS", "FULLSEND_JIRA_WRITE_GROUPS"}, ja.JiraEnvNames()) +} + +func TestJiraActorList_Resolved(t *testing.T) { + env := map[string]string{ + "GROUPS": " gid-1 , gid-2,, ,gid-3 ", + "ACCOUNTS": "712020:00000000-0000-0000-0000-000000000000", + "LINES": "gid-1\r\ngid-2\n", + "BLANK": " , ", + "EMPTY": "", + } + getenv := func(k string) string { return env[k] } + + groups, accounts := (&JiraActorList{GroupsFrom: "GROUPS", AccountsFrom: "ACCOUNTS"}).Resolved(getenv) + assert.Equal(t, []string{"gid-1", "gid-2", "gid-3"}, groups) + assert.Equal(t, []string{"712020:00000000-0000-0000-0000-000000000000"}, accounts) + + groups, _ = (&JiraActorList{GroupsFrom: "LINES"}).Resolved(getenv) + assert.Equal(t, []string{"gid-1", "gid-2"}, groups, "one entry per line") + + groups, accounts = (&JiraActorList{Groups: []string{"devs"}, Accounts: []string{"acct"}}).Resolved(getenv) + assert.Equal(t, []string{"devs"}, groups) + assert.Equal(t, []string{"acct"}, accounts) + + for _, name := range []string{"UNSET", "EMPTY", "BLANK"} { + groups, accounts = (&JiraActorList{GroupsFrom: name, AccountsFrom: name}).Resolved(getenv) + assert.Empty(t, groups, name) + assert.Empty(t, accounts, name) + } +} + +func TestJiraEnvNames_Deduplicates(t *testing.T) { + p := &AuthorizationProvider{ + Provider: AuthProviderJira, + Write: &JiraActorList{GroupsFrom: "SHARED"}, + Triage: &JiraActorList{GroupsFrom: "SHARED"}, + } + assert.Equal(t, []string{"SHARED"}, p.JiraEnvNames()) +} + func TestParsePerRepoConfig_JiraAuthorizationDefaults(t *testing.T) { cfg, err := ParsePerRepoConfig([]byte("authorization:\n - provider: jira\n")) require.NoError(t, err) @@ -274,6 +334,31 @@ func TestParsePerRepoConfig_JiraAuthorizationRejectsInvalid(t *testing.T) { yaml: "authorization:\n - provider: jira\n triage:\n accounts: [\" \"]\n", wantErr: "empty account ID", }, + { + name: "groups and groups_from on one role", + yaml: "authorization:\n - provider: jira\n write:\n groups: [g]\n groups_from: WRITE_GROUPS\n", + wantErr: "jira provider write: set groups or groups_from, not both", + }, + { + name: "empty inline list with its _from form", + yaml: "authorization:\n - provider: jira\n write:\n accounts: []\n accounts_from: WRITE_ACCOUNTS\n", + wantErr: "jira provider write: set accounts or accounts_from, not both", + }, + { + name: "env name written as an expansion", + yaml: "authorization:\n - provider: jira\n write:\n groups_from: ${WRITE_GROUPS}\n", + wantErr: `jira provider write.groups_from: invalid environment variable name "${WRITE_GROUPS}"`, + }, + { + name: "empty groups_from", + yaml: "authorization:\n - provider: jira\n write:\n groups_from: \"\"\n", + wantErr: "jira provider write.groups_from: empty environment variable name", + }, + { + name: "null accounts_from", + yaml: "authorization:\n - provider: jira\n triage:\n accounts_from:\n", + wantErr: "jira provider triage.accounts_from: empty environment variable name", + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -408,6 +493,17 @@ func TestPerRepoConfigValidate_JiraAuthorization(t *testing.T) { err = jiraFieldsOnOwners.Validate() require.Error(t, err) assert.Contains(t, err.Error(), "only valid for provider") + + bothForms := &perRepoConfig{ + Version: "1", + Authorization: []AuthorizationProvider{{ + Provider: AuthProviderJira, + Triage: &JiraActorList{Groups: []string{"g"}, GroupsFrom: "TRIAGE_GROUPS"}, + }}, + } + err = bothForms.Validate() + require.Error(t, err) + assert.Contains(t, err.Error(), "authorization[0]: jira provider triage: set groups or groups_from, not both") } func TestParsePerRepoConfig(t *testing.T) { diff --git a/internal/config/effective_test.go b/internal/config/effective_test.go index 3607b65415..f1eaba77c7 100644 --- a/internal/config/effective_test.go +++ b/internal/config/effective_test.go @@ -107,7 +107,7 @@ func TestEffectiveYAML_InheritsInferenceGateway(t *testing.T) { } func TestEffectiveYAML_ListsJiraAuthorizationProvider(t *testing.T) { - overlay, err := ParsePerRepoConfigWriter([]byte("authorization:\n - provider: jira\n write:\n accounts: [acct]\n")) + overlay, err := ParsePerRepoConfigWriter([]byte("authorization:\n - provider: jira\n write:\n accounts: [acct]\n triage:\n groups_from: TRIAGE_GROUPS\n")) require.NoError(t, err) layered, err := LayerOnBase(overlay, nil) require.NoError(t, err) @@ -118,6 +118,7 @@ func TestEffectiveYAML_ListsJiraAuthorizationProvider(t *testing.T) { assert.Equal(t, []any{map[string]any{ "provider": "jira", "write": map[string]any{"accounts": []any{"acct"}}, + "triage": map[string]any{"groups_from": "TRIAGE_GROUPS"}, "labels": JiraLabelsEditors, }}, got["authorization"]) } @@ -148,6 +149,9 @@ func TestCloneAuthorizationSlice_DeepCopiesJiraLists(t *testing.T) { out[0].Write.Groups[0] = "changed" assert.Equal(t, "g", in[0].Write.Groups[0]) assert.Nil(t, out[0].Triage) + + fromEnv := []AuthorizationProvider{{Provider: AuthProviderJira, Write: &JiraActorList{GroupsFrom: "G", AccountsFrom: "A"}}} + assert.Equal(t, &JiraActorList{GroupsFrom: "G", AccountsFrom: "A"}, cloneAuthorizationSlice(fromEnv)[0].Write) } func TestEffectiveYAML_CodeDefaultsAndNil(t *testing.T) { diff --git a/internal/config/managed-config-schema b/internal/config/managed-config-schema index 5b721307dd..97b34b1e56 100644 --- a/internal/config/managed-config-schema +++ b/internal/config/managed-config-schema @@ -3,4 +3,8 @@ # 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. +# +# groups_from and accounts_from (#9132) did not increment it, although older +# releases reject them: install and status refuse them for an older ref with +# checkJiraAuthorizationEnvSupport (internal/repos/jira_poll.go). 3 diff --git a/internal/config/managed.go b/internal/config/managed.go index 814bd88174..bf4e3c0ffe 100644 --- a/internal/config/managed.go +++ b/internal/config/managed.go @@ -600,10 +600,10 @@ func cloneAuthorizationProvider(p AuthorizationProvider) AuthorizationProvider { if l == nil { return nil } - return &JiraActorList{ - Groups: slices.Clone(l.Groups), - Accounts: slices.Clone(l.Accounts), - } + out := *l + out.Groups = slices.Clone(l.Groups) + out.Accounts = slices.Clone(l.Accounts) + return &out } p.Write = cloneList(p.Write) p.Triage = cloneList(p.Triage) diff --git a/internal/repos/converge.go b/internal/repos/converge.go index 387f6c5d50..e16403e206 100644 --- a/internal/repos/converge.go +++ b/internal/repos/converge.go @@ -851,7 +851,7 @@ func Converge(ctx context.Context, cfg ConvergeConfig, } if presetErr != nil { excludedUsesJira = true - } else if jira, jiraErr := effectiveJiraTracking(excludedResolved, excludedPreset); jiraErr != nil || jira.PollEnabled() { + } else if st, jiraErr := effectiveJiraPollState(excludedResolved, excludedPreset); jiraErr != nil || st.enabled { excludedUsesJira = true } } @@ -989,12 +989,11 @@ func Converge(ctx context.Context, cfg ConvergeConfig, discoveries[idx] = convergeDiscovery{repo: rr, resolved: resolved, configErr: inputErr} return } - jiraTracking, jiraErr := effectiveJiraTracking(resolved, presetData) + jiraState, jiraErr := effectiveJiraPollState(resolved, presetData) if jiraErr != nil { discoveries[idx] = convergeDiscovery{repo: rr, resolved: resolved, configErr: jiraErr} return } - jiraState := jiraPollState{jira: jiraTracking, enabled: jiraTracking.PollEnabled()} repoFullName := rr.Owner + "/" + rr.Repo progress(repoFullName, "discover", "Checking installation status") @@ -1578,6 +1577,10 @@ func convergeRepo(ctx context.Context, return cr } } + if err := checkJiraAuthorizationEnvSupport(ctx, d, cfg, refResolver); err != nil { + cr.Error = err + return cr + } if err := checkGitHubJiraPollWorkflow(ctx, d, cfg, refResolver); err != nil { cr.Error = err return cr diff --git a/internal/repos/github_jira_poll.go b/internal/repos/github_jira_poll.go index b897561fd5..beae3f7cc0 100644 --- a/internal/repos/github_jira_poll.go +++ b/internal/repos/github_jira_poll.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "slices" "sort" "strings" @@ -152,18 +153,10 @@ func userJiraCallerOAuthUses(caller []byte) ([]string, bool) { // rejected, since its OAuth support cannot be established. func requireUserJiraCallerWorkflowsOAuth(ctx context.Context, resolved ResolvedConfig, refResolver *RefResolver, uses []string) error { for _, u := range uses { - var content []byte - var err error - if localPath, local := strings.CutPrefix(u, "./"); local { - content, err = resolved.ForgeConfig.Client.GetFileContent(ctx, resolved.Owner, resolved.Repo, localPath) - } else { - target, ref, hasRef := strings.Cut(u, "@") - parts := strings.SplitN(target, "/", 3) - if !hasRef || len(parts) != 3 || refResolver == nil { - return fmt.Errorf("%s/%s: %s calls %q, whose Jira OAuth support cannot be verified; pin it to owner/repo/path@ref of a Fullsend version that supports OAuth credentials (existing Jira credentials were left unchanged)", - resolved.Owner, resolved.Repo, scaffold.JiraPollCallerPath, u) - } - content, err = refResolver.client.GetFileContentAtRef(ctx, parts[0], parts[1], parts[2], ref) + content, located, err := readUserJiraCallerWorkflow(ctx, resolved, refResolver, u) + if !located { + return fmt.Errorf("%s/%s: %s calls %q, whose Jira OAuth support cannot be verified; pin it to owner/repo/path@ref of a Fullsend version that supports OAuth credentials (existing Jira credentials were left unchanged)", + resolved.Owner, resolved.Repo, scaffold.JiraPollCallerPath, u) } if err != nil { return fmt.Errorf("%s/%s: %s calls %q, whose Jira OAuth support could not be verified: %w (existing Jira credentials were left unchanged)", @@ -177,6 +170,86 @@ func requireUserJiraCallerWorkflowsOAuth(ctx context.Context, resolved ResolvedC return nil } +// readUserJiraCallerWorkflow reads the reusable workflow a user-owned caller's +// `uses` names: at the ref it pins, or from the caller's own repository for a +// local `./` reference. located is false when the reference has no +// owner/repo/path@ref form or no upstream client can read it. +func readUserJiraCallerWorkflow(ctx context.Context, resolved ResolvedConfig, refResolver *RefResolver, uses string) (content []byte, located bool, err error) { + if localPath, local := strings.CutPrefix(uses, "./"); local { + content, err = resolved.ForgeConfig.Client.GetFileContent(ctx, resolved.Owner, resolved.Repo, localPath) + return content, true, err + } + target, ref, hasRef := strings.Cut(uses, "@") + parts := strings.SplitN(target, "/", 3) + if !hasRef || len(parts) != 3 || refResolver == nil { + return nil, false, nil + } + content, err = refResolver.client.GetFileContentAtRef(ctx, parts[0], parts[1], parts[2], ref) + return content, true, err +} + +// checkUserJiraCallerAuthorizationEnv fails when a user-owned Jira poll caller +// calls a reusable-poll-jira.yml that predates groups_from and accounts_from. +// That workflow installs the CLI at its own ref, and an older CLI cannot load +// the config, so every poll would fail. A vendored install runs its own +// binary there, so it is not checked. Neither is a reference that cannot be +// located. +func checkUserJiraCallerAuthorizationEnv(ctx context.Context, d convergeDiscovery, refResolver *RefResolver) error { + resolved := d.resolved + if resolved.Forge != ForgeGitHub || !d.jira.enabled || resolved.Vendor { + return nil + } + caller, exists, err := readJiraPollCaller(ctx, jiraPollRequest{ + Client: resolved.ForgeConfig.Client, + Owner: resolved.Owner, + Repo: resolved.Repo, + }) + if err != nil { + return fmt.Errorf("%s/%s: checking %s for groups_from/accounts_from support: %w", + resolved.Owner, resolved.Repo, scaffold.JiraPollCallerPath, err) + } + if !exists || scaffold.IsManagedJiraPollCaller(caller) { + return nil + } + for _, u := range userJiraCallerPollUses(caller) { + content, located, err := readUserJiraCallerWorkflow(ctx, resolved, refResolver, u) + if !located { + continue + } + if err != nil && !forge.IsNotFound(err) { + return fmt.Errorf("%s/%s: checking %q, called by %s, for groups_from/accounts_from support: %w", + resolved.Owner, resolved.Repo, u, scaffold.JiraPollCallerPath, err) + } + if err != nil || !bytes.Contains(content, []byte(jiraAuthorizationEnvMarker)) { + return fmt.Errorf("%s/%s: config.yaml reads %s with groups_from/accounts_from, which %q, called by %s, does not support; update the reference to a release that includes them", + resolved.Owner, resolved.Repo, strings.Join(d.jira.authEnv, ", "), u, scaffold.JiraPollCallerPath) + } + } + return nil +} + +// userJiraCallerPollUses returns the sorted, de-duplicated `uses` references +// of a user-owned caller's jobs that call the reusable Jira poll workflow. A +// caller that does not parse returns none. +func userJiraCallerPollUses(caller []byte) []string { + var wf struct { + Jobs map[string]struct { + Uses string `yaml:"uses"` + } `yaml:"jobs"` + } + if err := yaml.Unmarshal(caller, &wf); err != nil { + return nil + } + var uses []string + for _, job := range wf.Jobs { + if strings.Contains(job.Uses, "reusable-poll-jira.yml") && !slices.Contains(uses, job.Uses) { + uses = append(uses, job.Uses) + } + } + sort.Strings(uses) + return uses +} + // missingJiraOAuthSecret returns the first Jira OAuth client secret a workflow // does not declare, or "" when it declares them all. func missingJiraOAuthSecret(content []byte) string { @@ -188,25 +261,82 @@ func missingJiraOAuthSecret(content []byte) string { return "" } +// splitJiraAuthorizationEnv splits the variables the jira authorization +// lists read (#9132) into those the managed caller forwards to the poll +// job, in scaffold.JiraAuthorizationSecrets order, and the others, which +// it cannot pass. +func splitJiraAuthorizationEnv(names []string) (forwarded, unforwarded []string) { + for _, name := range scaffold.JiraAuthorizationSecrets { + if slices.Contains(names, name) { + forwarded = append(forwarded, name) + } + } + for _, name := range names { + if !slices.Contains(scaffold.JiraAuthorizationSecrets, name) { + unforwarded = append(unforwarded, name) + } + } + return forwarded, unforwarded +} + // jiraJobForwardsOAuth reports whether a job's secrets node is `inherit` or a // mapping that names every Jira OAuth client secret. func jiraJobForwardsOAuth(secrets yaml.Node) bool { + return len(jiraJobUnforwarded(secrets, jiraOAuthSecrets)) == 0 +} + +// jiraJobUnforwarded returns the names a job's secrets node does not pass to +// the workflow it calls: none for `inherit`, and for a mapping the names it +// leaves out. Any other node passes nothing. +func jiraJobUnforwarded(secrets yaml.Node, names []string) []string { + named := map[string]bool{} switch secrets.Kind { case yaml.ScalarNode: - return secrets.Value == "inherit" + if secrets.Value == "inherit" { + return nil + } case yaml.MappingNode: - named := map[string]bool{} for i := 0; i+1 < len(secrets.Content); i += 2 { named[secrets.Content[i].Value] = true } - for _, name := range jiraOAuthSecrets { - if !named[name] { - return false + } + var missing []string + for _, name := range names { + if !named[name] { + missing = append(missing, name) + } + } + return missing +} + +// userJiraCallerUnforwarded returns the names that a user-owned caller's +// jobs calling the reusable Jira poll workflow do not pass to it, and +// reports whether it has such a job. A caller that runs the poller itself, +// or does not parse, returns none: only its owner knows what its +// environment sets. +func userJiraCallerUnforwarded(caller []byte, names []string) (missing []string, calls bool) { + var wf struct { + Jobs map[string]struct { + Uses string `yaml:"uses"` + Secrets yaml.Node `yaml:"secrets"` + } `yaml:"jobs"` + } + if err := yaml.Unmarshal(caller, &wf); err != nil { + return nil, false + } + for _, job := range wf.Jobs { + if !strings.Contains(job.Uses, "reusable-poll-jira.yml") { + continue + } + calls = true + for _, name := range jiraJobUnforwarded(job.Secrets, names) { + if !slices.Contains(missing, name) { + missing = append(missing, name) } } - return true } - return false + sort.Strings(missing) + return missing, calls } // requireJiraOAuthSecrets rejects a reusable workflow that does not declare @@ -221,7 +351,8 @@ func requireJiraOAuthSecrets(resolved ResolvedConfig, source, ref, workflowPath // Ensure makes the managed caller present and current. func (githubJiraPollReconciler) Ensure(ctx context.Context, req jiraPollRequest) ([]ComponentAction, error) { - want, err := scaffold.RenderJiraPollCaller(req.Render, req.EmailConfigured, req.OAuthConfigured) + forwarded, unforwarded := splitJiraAuthorizationEnv(req.AuthorizationEnv) + want, err := scaffold.RenderJiraPollCaller(req.Render, req.EmailConfigured, req.OAuthConfigured, forwarded) if err != nil { return nil, err } @@ -230,6 +361,17 @@ func (githubJiraPollReconciler) Ensure(ctx context.Context, req jiraPollRequest) return nil, err } if exists && !scaffold.IsManagedJiraPollCaller(have) { + // A reusable workflow gets only the secrets its caller passes, and + // the poll workflow accepts only the fixed names. + missing, calls := userJiraCallerUnforwarded(have, forwarded) + if len(missing) > 0 && req.Warn != nil { + req.Warn(fmt.Sprintf("authorization: jira groups_from/accounts_from reads %s, which %s does not pass to reusable-poll-jira.yml; add it to that job's secrets, or that list grants no one", + strings.Join(missing, ", "), scaffold.JiraPollCallerPath)) + } + if calls && len(unforwarded) > 0 && req.Warn != nil { + req.Warn(fmt.Sprintf("authorization: jira groups_from/accounts_from reads %s, which reusable-poll-jira.yml does not pass to the poller; rename it to one of %s, or run the poller in your own job", + strings.Join(unforwarded, ", "), strings.Join(scaffold.JiraAuthorizationSecrets, ", "))) + } return []ComponentAction{{ Component: jiraPollComponent, Action: "none", @@ -237,6 +379,13 @@ func (githubJiraPollReconciler) Ensure(ctx context.Context, req jiraPollRequest) scaffold.JiraPollCallerPath), }}, nil } + // The managed caller passes only the fixed names. The poller finds any + // other variable unset, so that list grants no one unless the runner + // itself sets it. + if len(unforwarded) > 0 && req.Warn != nil { + req.Warn(fmt.Sprintf("authorization: jira groups_from/accounts_from reads %s, which the managed %s does not pass to the poller; rename it to one of %s, or set it in the runner's environment", + strings.Join(unforwarded, ", "), scaffold.JiraPollCallerPath, strings.Join(scaffold.JiraAuthorizationSecrets, ", "))) + } if exists && bytes.Equal(have, want) { return []ComponentAction{{ Component: jiraPollComponent, diff --git a/internal/repos/github_jira_poll_test.go b/internal/repos/github_jira_poll_test.go index c1ca8bc3a0..55adf6c263 100644 --- a/internal/repos/github_jira_poll_test.go +++ b/internal/repos/github_jira_poll_test.go @@ -5,6 +5,7 @@ import ( "errors" "slices" "strings" + "sync" "testing" "github.com/stretchr/testify/assert" @@ -60,16 +61,33 @@ func assertNoUnrelatedFiles(t *testing.T, spy *spyScaffoldCommit) { // runJiraConverge converges acme/api with raw as its repository config. func runJiraConverge(t *testing.T, fc *forge.FakeClient, raw string, mutate func(*ConvergeConfig)) (*ConvergeResult, *spyScaffoldCommit) { + t.Helper() + cr, spy, _ := runJiraConvergeWarnings(t, fc, raw, mutate) + return cr, spy +} + +// runJiraConvergeWarnings is runJiraConverge that also returns the +// warnings the run reported, one per line. +func runJiraConvergeWarnings(t *testing.T, fc *forge.FakeClient, raw string, mutate func(*ConvergeConfig)) (*ConvergeResult, *spyScaffoldCommit, string) { t.Helper() cfg := withoutInferenceInputs(convergeCfgWithDefaults(jiraManifest(t, raw))) if mutate != nil { mutate(&cfg) } spy := &spyScaffoldCommit{} - result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), spy.fn(), noopProgress) + var mu sync.Mutex + var warnings []string + progress := func(_, phase, message string) { + if phase == "warning" { + mu.Lock() + defer mu.Unlock() + warnings = append(warnings, message) + } + } + result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), spy.fn(), progress) require.NoError(t, err) require.Len(t, result.Results, 1) - return &result.Results[0], spy + return &result.Results[0], spy, strings.Join(warnings, "\n") } func TestConverge_GitHubJiraPoll_FreshInstallCommitsCaller(t *testing.T) { @@ -152,7 +170,7 @@ func TestConverge_GitHubJiraPoll_EstablishedInstallAddsThenIsIdempotent(t *testi func TestConverge_GitHubJiraPoll_StaleManagedCallerUpdated(t *testing.T) { fc := installedJiraRepo(forge.SecretJiraToken) - stale, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{UpstreamRef: "v0.9.0"}, true, false) + stale, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{UpstreamRef: "v0.9.0"}, true, false, nil) require.NoError(t, err) fc.FileContents[jiraCallerKey] = stale @@ -179,7 +197,7 @@ func TestConverge_GitHubJiraPoll_DisabledRemovesManagedCaller(t *testing.T) { } { t.Run(name, func(t *testing.T) { fc := installedJiraRepo(forge.SecretJiraToken, forge.SecretJiraEmail) - managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false) + managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false, nil) require.NoError(t, err) fc.FileContents[jiraCallerKey] = managed fc.FileContents[unrelatedKey] = []byte(unrelatedFlow) @@ -246,7 +264,7 @@ func TestConverge_GitHubJiraPoll_DryRunStagesNothing(t *testing.T) { t.Run("remove", func(t *testing.T) { fc := installedJiraRepo() - managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false) + managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false, nil) require.NoError(t, err) fc.FileContents[jiraCallerKey] = managed cr, spy := runJiraConverge(t, fc, "", func(c *ConvergeConfig) { c.DryRun = true }) @@ -435,7 +453,7 @@ func TestCheckGitHubJiraPollWorkflowUserOwnedCallerOAuth(t *testing.T) { func TestGitHubJiraPollReconciler_RequiresScaffoldCommit(t *testing.T) { fc := forge.NewFakeClient() - managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false) + managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, false, false, nil) require.NoError(t, err) req := jiraPollRequest{Client: fc, Owner: "acme", Repo: "api"} @@ -450,7 +468,7 @@ func TestGitHubJiraPollReconciler_RequiresScaffoldCommit(t *testing.T) { } func TestUninstall_RemovesManagedJiraPollCaller(t *testing.T) { - managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, true, false) + managed, err := scaffold.RenderJiraPollCaller(scaffold.RenderOptions{}, true, false, nil) require.NoError(t, err) tests := []struct { @@ -506,3 +524,127 @@ func TestUninstall_RemovesManagedJiraPollCaller(t *testing.T) { }) } } + +// jiraAuthFromEnvConfig reads two lists from secrets the caller can forward. +const jiraAuthFromEnvConfig = jiraPollEnabledConfig + `authorization: + - provider: jira + write: + groups_from: FULLSEND_JIRA_WRITE_GROUPS + triage: + accounts_from: FULLSEND_JIRA_TRIAGE_ACCOUNTS +` + +func TestConverge_GitHubJiraPoll_ForwardsAuthorizationListSecrets(t *testing.T) { + fc := installedJiraRepo(forge.SecretJiraToken) + + cr, spy, warnings := runJiraConvergeWarnings(t, fc, jiraAuthFromEnvConfig, nil) + require.NoError(t, cr.Error) + assert.Empty(t, warnings) + f, ok := stagedJiraCaller(t, spy) + require.True(t, ok) + var caller renderedJiraPollCaller + require.NoError(t, yaml.Unmarshal(f.Content, &caller)) + poll := caller.Jobs["poll"].Secrets + assert.Contains(t, poll, "FULLSEND_JIRA_WRITE_GROUPS") + assert.Contains(t, poll, "FULLSEND_JIRA_TRIAGE_ACCOUNTS") + assert.NotContains(t, poll, "FULLSEND_JIRA_WRITE_ACCOUNTS") + assert.NotContains(t, poll, "FULLSEND_JIRA_TRIAGE_GROUPS") + + // The poller reads the names from the committed config. + spy.mu.Lock() + defer spy.mu.Unlock() + var configYAML string + for _, file := range spy.files { + if file.Path == ".fullsend/config.yaml" { + configYAML = string(file.Content) + } + } + assert.Contains(t, configYAML, "groups_from: FULLSEND_JIRA_WRITE_GROUPS") + assert.Contains(t, configYAML, "accounts_from: FULLSEND_JIRA_TRIAGE_ACCOUNTS") +} + +func TestConverge_JiraAuthorizationEnv_RejectsOldPinBeforeWrites(t *testing.T) { + fc := newFakeClientForBatch("acme/api") + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@v0.54.0"] = []byte(jiraOAuthWorkflowFixture) + m := jiraManifest(t, jiraAuthFromEnvConfig) + m.GitHub.Repos[0].FullsendRef = "v0.54.0" + cfg := convergeCfgWithDefaults(m) + cfg.JiraToken = testJiraToken + spy := &spyScaffoldCommit{} + + result, err := Converge(context.Background(), cfg, newTestClientFactory(fc), spy.fn(), noopProgress) + require.NoError(t, err) + require.Len(t, result.Failed(), 1) + assert.ErrorContains(t, result.Results[0].Error, `pinned fullsend_ref "v0.54.0" does not support`) + assert.Empty(t, jiraSecretWrites(fc)) + _, staged := stagedJiraCaller(t, spy) + assert.False(t, staged) +} + +func TestStatus_JiraAuthorizationEnv_ReportsOldPin(t *testing.T) { + // Not installed: the schema check alone would call the config compatible. + for name, fc := range map[string]*forge.FakeClient{ + "installed": installedJiraRepo(forge.SecretJiraToken), + "not installed": newFakeClientForBatch("acme/api"), + } { + t.Run(name, func(t *testing.T) { + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@v0.54.0"] = []byte(jiraOAuthWorkflowFixture) + m := jiraManifest(t, jiraAuthFromEnvConfig) + m.GitHub.Repos[0].FullsendRef = "v0.54.0" + + status, err := Status(context.Background(), m, newTestClientFactory(fc), 4, nil) + require.NoError(t, err) + require.Len(t, status.Repos, 1) + assert.Contains(t, status.Repos[0].Error, `pinned fullsend_ref "v0.54.0" does not support`) + assert.Empty(t, status.Repos[0].ConfigCompatibility) + }) + } +} + +func TestConverge_GitHubJiraPoll_WarnsAboutListVariableItCannotForward(t *testing.T) { + raw := jiraPollEnabledConfig + `authorization: + - provider: jira + write: + groups_from: MY_WRITE_GROUPS +` + t.Run("managed caller", func(t *testing.T) { + cr, _, warnings := runJiraConvergeWarnings(t, installedJiraRepo(forge.SecretJiraToken), raw, nil) + require.NoError(t, cr.Error, "the runner may still set the variable") + assert.Contains(t, warnings, "reads MY_WRITE_GROUPS") + }) + + t.Run("user-owned caller", func(t *testing.T) { + fc := installedJiraRepo(forge.SecretJiraToken) + fc.FileContents[jiraCallerKey] = []byte(userJiraCaller) + cr, _, warnings := runJiraConvergeWarnings(t, fc, raw, nil) + require.NoError(t, cr.Error) + assert.Empty(t, warnings, "a workflow that runs the poller itself can set any variable") + }) + + t.Run("user-owned caller of the reusable workflow", func(t *testing.T) { + const job = "jobs:\n poll:\n uses: fullsend-ai/fullsend/.github/workflows/reusable-poll-jira.yml@v1.0.0\n" + const mapping = " secrets:\n FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }}\n" + const rename = "reads MY_WRITE_GROUPS, which reusable-poll-jira.yml does not pass to the poller; rename it" + const add = "reads FULLSEND_JIRA_WRITE_GROUPS, which " + scaffold.JiraPollCallerPath + " does not pass to reusable-poll-jira.yml; add it" + for _, tc := range []struct{ name, variable, secrets, want string }{ + {"other name, mapping", "MY_WRITE_GROUPS", mapping, rename}, + {"other name, inherit", "MY_WRITE_GROUPS", " secrets: inherit\n", rename}, + {"fixed name, mapping without it", "FULLSEND_JIRA_WRITE_GROUPS", mapping, add}, + {"fixed name, inherit", "FULLSEND_JIRA_WRITE_GROUPS", " secrets: inherit\n", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + fc := installedJiraRepo(forge.SecretJiraToken) + fc.FileContents[jiraCallerKey] = []byte(userJiraCaller + job + tc.secrets) + _, _, warnings := runJiraConvergeWarnings(t, fc, strings.Replace(raw, "MY_WRITE_GROUPS", tc.variable, 1), nil) + if tc.want == "" { + assert.Empty(t, warnings) + return + } + assert.Contains(t, warnings, tc.want) + if tc.want == rename { + assert.NotContains(t, warnings, "add it", "the poll workflow rejects a secret it does not declare") + } + }) + } + }) +} diff --git a/internal/repos/jira_poll.go b/internal/repos/jira_poll.go index 714b07f852..8c1c0efdba 100644 --- a/internal/repos/jira_poll.go +++ b/internal/repos/jira_poll.go @@ -1,8 +1,10 @@ package repos import ( + "bytes" "context" "fmt" + "strings" "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge" @@ -33,6 +35,15 @@ type jiraPollRequest struct { // workflows pinned to a ref that predates OAuth support. Only // meaningful for Ensure. OAuthConfigured bool + // AuthorizationEnv names the environment variables the effective jira + // authorization lists read with groups_from and accounts_from (#9132). + // The GitHub caller forwards those in scaffold.JiraAuthorizationSecrets + // to the poll job and cannot pass any other. Only meaningful for Ensure. + AuthorizationEnv []string + // Warn reports a problem that does not fail the run, such as a list + // variable the managed caller cannot pass. It is nil when nothing + // listens. + Warn func(detail string) // DryRun asks the reconciler to report the actions it would take // without any forge write. DryRun bool @@ -108,6 +119,9 @@ type jiraPollState struct { // clientSecretDefect names why an existing GitLab // FULLSEND_JIRA_CLIENT_SECRET cannot be reused; empty when it can. clientSecretDefect string + // authEnv names the environment variables the effective jira + // authorization lists read with groups_from and accounts_from, sorted. + authEnv []string } // jiraTokenSecrets and jiraOAuthSecrets are the two mutually exclusive Jira @@ -135,27 +149,119 @@ func jiraUsesOAuth(st jiraPollState, cfg ConvergeConfig) bool { return !st.tokenExists && (st.clientIDExists || st.clientSecretExists) } -// effectiveJiraTracking returns the repository's effective tracker.jira -// mapping, the managed configuration layered over the declared preset (the -// same layers committed as the .fullsend files), or nil when the selected -// tracker provider is not Jira. When polling is enabled the connection -// settings are validated, so an incomplete mapping fails before any write. -// URL, project and query never come from flags or the environment. -func effectiveJiraTracking(resolved ResolvedConfig, preset []byte) (*config.JiraTrackingConfig, error) { +// effectiveJiraPollState returns the Jira polling state that the effective +// configuration sets: the managed configuration layered over the declared +// preset (the same layers committed as the .fullsend files). It holds the +// tracker.jira mapping, or nil when the selected tracker provider is not +// Jira, whether polling is enabled, and the variables the jira authorization +// lists read. When polling is enabled the connection settings are validated, +// so an incomplete mapping fails before any write. URL, project and query +// never come from flags or the environment. The secret probes are filled in +// later by probeJiraPollSecrets. +func effectiveJiraPollState(resolved ResolvedConfig, preset []byte) (jiraPollState, error) { layered, err := config.LayerOnBase(resolved.Managed, preset) if err != nil { - return nil, fmt.Errorf("%s/%s: reading the effective configuration: %w", resolved.Owner, resolved.Repo, err) + return jiraPollState{}, fmt.Errorf("%s/%s: reading the effective configuration: %w", resolved.Owner, resolved.Repo, err) } + // Collected for any tracker: every job loads the config, not only the poller. + authEnv := layered.JiraAuthorization().JiraEnvNames() tracking := layered.IssueTracking() if tracking.Provider() != config.TrackingProviderJira { - return nil, nil + return jiraPollState{authEnv: authEnv}, nil } if tracking.Jira.PollEnabled() { if err := tracking.Jira.ValidateConnection(); err != nil { - return nil, fmt.Errorf("%s/%s: tracker.jira.poll.enabled is true: %w", resolved.Owner, resolved.Repo, err) + return jiraPollState{}, fmt.Errorf("%s/%s: tracker.jira.poll.enabled is true: %w", resolved.Owner, resolved.Repo, err) } } - return tracking.Jira, nil + return jiraPollState{ + jira: tracking.Jira, + enabled: tracking.Jira.PollEnabled(), + authEnv: authEnv, + }, nil +} + +// jiraAuthorizationEnvMarker appears in reusable-poll-jira.yml at every ref +// whose CLI supports groups_from and accounts_from: both landed together +// (#9132). +const jiraAuthorizationEnvMarker = "FULLSEND_JIRA_WRITE_GROUPS" + +// checkJiraAuthorizationEnvSupport fails before any write when the config +// reads a jira authorization list with groups_from or accounts_from and the +// repository's jobs run a release that predates them. Every job runs the CLI +// at the scaffold's ref, and an older CLI rejects the keys, so no job could +// load the config. The ref checked is the pinned fullsend_ref, or the ref the +// installed scaffold is stamped with when install will not refresh it (see +// establishedScaffoldRef). Any other repository runs the current release. +func checkJiraAuthorizationEnvSupport(ctx context.Context, d convergeDiscovery, cfg ConvergeConfig, refResolver *RefResolver) error { + if len(d.jira.authEnv) == 0 { + return nil + } + resolved := d.resolved + // A vendored install runs its own binary and workflows. Only the managed + // GitHub poll caller still calls upstream at that ref, and the workflow + // there must declare each list secret the caller passes. A poll caller + // the user maintains does not call upstream at that ref. + if resolved.Vendor { + forwarded, _ := splitJiraAuthorizationEnv(d.jira.authEnv) + if resolved.Forge != ForgeGitHub || !d.jira.enabled || len(forwarded) == 0 { + return nil + } + caller, exists, err := readJiraPollCaller(ctx, jiraPollRequest{Client: resolved.ForgeConfig.Client, Owner: resolved.Owner, Repo: resolved.Repo}) + if err != nil { + return fmt.Errorf("%s/%s: checking %s for groups_from/accounts_from support: %w", + resolved.Owner, resolved.Repo, scaffold.JiraPollCallerPath, err) + } + if exists && !scaffold.IsManagedJiraPollCaller(caller) { + return nil + } + } + if err := checkUserJiraCallerAuthorizationEnv(ctx, d, refResolver); err != nil { + return err + } + ref, source := resolveTargetRef(ctx, resolved.FullsendRef, cfg.UpstreamRef, cfg.UpstreamTag, refResolver).manifestRef, "pinned fullsend_ref" + if ref == "" { + // A stamped scaffold's ref cannot be read without an upstream GitHub + // client, so it is not checked, as in checkGitLabJiraOAuthSupport. + if refResolver == nil { + return nil + } + ref, source = establishedScaffoldRef(resolved, cfg, d.components), "the installed scaffold's ref" + } + if ref == "" { + return nil + } + names := strings.Join(d.jira.authEnv, ", ") + if refResolver == nil { + return fmt.Errorf("%s/%s: config.yaml reads %s with groups_from/accounts_from, and %s %q cannot be checked for support without an upstream GitHub client", + resolved.Owner, resolved.Repo, names, source, ref) + } + content, err := refResolver.client.GetFileContentAtRef(ctx, shimOwner, shimRepo, reusableJiraPollWorkflowPath, ref) + if err != nil && !forge.IsNotFound(err) { + return fmt.Errorf("%s/%s: checking %s %q for groups_from/accounts_from support: %w", + resolved.Owner, resolved.Repo, source, ref, err) + } + if err != nil || !bytes.Contains(content, []byte(jiraAuthorizationEnvMarker)) { + return fmt.Errorf("%s/%s: config.yaml reads %s with groups_from/accounts_from, which %s %q does not support; set fullsend_ref to a release that includes them", + resolved.Owner, resolved.Repo, names, source, ref) + } + return nil +} + +// establishedScaffoldRef returns the ref an installed scaffold is stamped +// with when this run will not move it: the manifest sets no fullsend_ref and +// the build has no release ref. It returns "" for a missing or unstamped +// scaffold, which convergence renders from the embedded templates. +func establishedScaffoldRef(resolved ResolvedConfig, cfg ConvergeConfig, components []ComponentStatus) string { + if resolved.FullsendRef != "" || cfg.UpstreamRef != "" { + return "" + } + for _, c := range components { + if c.Name == "workflow" && c.Present && !isUnstampedInstallRef(resolved.Forge, c.Actual) { + return c.Actual + } + } + return "" } // probeJiraPollSecrets reads whether the Jira credential secrets exist. It @@ -424,6 +530,8 @@ func convergeJiraPoll(ctx context.Context, d convergeDiscovery, cfg ConvergeConf _, emailSupplied := values[forge.SecretJiraEmail] req.EmailConfigured = !useOAuth && (d.jira.emailExists || emailSupplied) req.OAuthConfigured = useOAuth + req.AuthorizationEnv = d.jira.authEnv + req.Warn = func(detail string) { progress(repoFullName, "warning", detail) } ensured, err := reconciler.Ensure(ctx, req) actions = append(actions, ensured...) if err != nil { diff --git a/internal/repos/jira_poll_test.go b/internal/repos/jira_poll_test.go index eab8d1b526..9b201ee952 100644 --- a/internal/repos/jira_poll_test.go +++ b/internal/repos/jira_poll_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "os" "strings" "sync" "testing" @@ -11,7 +12,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/scaffold" ) const ( @@ -496,7 +499,7 @@ func TestProbeJiraPollSecrets(t *testing.T) { } } -func TestEffectiveJiraTracking(t *testing.T) { +func TestEffectiveJiraPollState(t *testing.T) { resolve := func(t *testing.T, raw string) ResolvedConfig { t.Helper() m := jiraManifest(t, raw) @@ -506,37 +509,37 @@ func TestEffectiveJiraTracking(t *testing.T) { } t.Run("managed config enables polling", func(t *testing.T) { - jira, err := effectiveJiraTracking(resolve(t, jiraPollEnabledConfig), nil) + st, err := effectiveJiraPollState(resolve(t, jiraPollEnabledConfig), nil) require.NoError(t, err) - assert.True(t, jira.PollEnabled()) + assert.True(t, st.enabled) }) t.Run("preset enables polling", func(t *testing.T) { - jira, err := effectiveJiraTracking(resolve(t, ""), []byte(jiraPollEnabledConfig)) + st, err := effectiveJiraPollState(resolve(t, ""), []byte(jiraPollEnabledConfig)) require.NoError(t, err) - assert.True(t, jira.PollEnabled()) + assert.True(t, st.enabled) }) t.Run("managed config overrides preset", func(t *testing.T) { - jira, err := effectiveJiraTracking(resolve(t, jiraPollDisabledConfig), []byte(jiraPollEnabledConfig)) + st, err := effectiveJiraPollState(resolve(t, jiraPollDisabledConfig), []byte(jiraPollEnabledConfig)) require.NoError(t, err) - assert.False(t, jira.PollEnabled()) + assert.False(t, st.enabled) }) t.Run("other provider", func(t *testing.T) { - jira, err := effectiveJiraTracking(resolve(t, "tracker:\n github: {}\n"), nil) + st, err := effectiveJiraPollState(resolve(t, "tracker:\n github: {}\n"), nil) require.NoError(t, err) - assert.Nil(t, jira) + assert.Nil(t, st.jira) }) t.Run("enabled with incomplete connection", func(t *testing.T) { - _, err := effectiveJiraTracking(resolve(t, ""), []byte("tracker:\n jira:\n poll:\n enabled: true\n")) + _, err := effectiveJiraPollState(resolve(t, ""), []byte("tracker:\n jira:\n poll:\n enabled: true\n")) require.Error(t, err) assert.True(t, strings.Contains(err.Error(), "tracker.jira.poll.enabled is true"), err.Error()) }) t.Run("invalid preset", func(t *testing.T) { - _, err := effectiveJiraTracking(resolve(t, ""), []byte("tracker: [\n")) + _, err := effectiveJiraPollState(resolve(t, ""), []byte("tracker: [\n")) require.Error(t, err) assert.Contains(t, err.Error(), "reading the effective configuration") }) @@ -792,3 +795,118 @@ func TestConverge_JiraPoll_GitHubAcceptsOAuth(t *testing.T) { forge.SecretJiraClientSecret: testJiraClientSecret, }, jiraSecretWrites(fc)) } + +func TestCheckJiraAuthorizationEnvSupport(t *testing.T) { + const pin = "v0.54.0" + const upstreamPoll = shimOwner + "/" + shimRepo + "/" + reusableJiraPollWorkflowPath + serve := func(content string) func(*forge.FakeClient) { + return func(fc *forge.FakeClient) { + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@"+pin] = []byte(content) + } + } + tests := []struct { + name string + setup func(*forge.FakeClient) + authEnv []string + ref string + installed string // ref the installed scaffold is stamped with + enabled bool + vendored bool // a vendored GitHub install + managed bool // the managed GitHub poll caller is already committed + uses string // poll workflow a user-owned GitHub caller calls + wantErr string + }{ + {name: "config reads no list from the environment", authEnv: nil, ref: pin, enabled: true}, + {name: "unpinned repository runs the current release", authEnv: []string{"WRITE_GROUPS"}, enabled: true}, + {name: "pin that supports the keys", setup: serve(jiraAuthListsWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, ref: pin, enabled: true}, + // Agent runs load the config too, so the check does not depend on polling. + {name: "pin that predates the keys, polling disabled", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"MY_GROUPS"}, ref: pin, + wantErr: `config.yaml reads MY_GROUPS with groups_from/accounts_from, which pinned fullsend_ref "v0.54.0" does not support`}, + {name: "pin without the Jira poll workflow", authEnv: []string{"WRITE_GROUPS"}, ref: pin, enabled: true, wantErr: "does not support"}, + {name: "fetch error fails closed", setup: func(fc *forge.FakeClient) { fc.Errors["GetFileContentAtRef"] = errors.New("upstream unavailable") }, + authEnv: []string{"WRITE_GROUPS"}, ref: pin, enabled: true, wantErr: "upstream unavailable"}, + // With no fullsend_ref and no release ref, install leaves a stamped scaffold where it is. + {name: "installed scaffold that predates the keys", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, installed: pin, enabled: true, + wantErr: `which the installed scaffold's ref "v0.54.0" does not support`}, + {name: "installed scaffold that supports the keys", setup: serve(jiraAuthListsWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, installed: pin, enabled: true}, + // A vendored install runs its own binary, but its managed poll caller calls upstream at the pin. + {name: "vendored, polling disabled", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, vendored: true}, + {name: "vendored, caller passes no list secret", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"MY_GROUPS"}, ref: pin, enabled: true, vendored: true}, + {name: "vendored, caller passes a list secret", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, enabled: true, vendored: true, + wantErr: "does not support"}, + {name: "vendored, committed managed caller passes a list secret", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, enabled: true, vendored: true, managed: true, + wantErr: "does not support"}, + // The reusable poll workflow installs the CLI at the ref the caller pins, not at fullsend_ref. + {name: "user-owned caller pins a poll workflow that predates the keys", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, enabled: true, uses: upstreamPoll + "@" + pin, + wantErr: `which "fullsend-ai/fullsend/.github/workflows/reusable-poll-jira.yml@v0.54.0", called by .github/workflows/fullsend-poll-jira.yml, does not support`}, + {name: "user-owned caller pins a poll workflow that supports the keys", setup: serve(jiraAuthListsWorkflowFixture), authEnv: []string{"WRITE_GROUPS"}, enabled: true, uses: upstreamPoll + "@" + pin}, + {name: "user-owned caller calls its own copy that predates the keys", setup: func(fc *forge.FakeClient) { + fc.FileContents["group/project/"+reusableJiraPollWorkflowPath] = []byte(jiraOAuthWorkflowFixture) + }, authEnv: []string{"WRITE_GROUPS"}, enabled: true, uses: "./" + reusableJiraPollWorkflowPath, wantErr: "does not support"}, + {name: "user-owned caller whose reference has no ref is not checked", authEnv: []string{"WRITE_GROUPS"}, enabled: true, uses: upstreamPoll}, + // The old workflow then runs the vendored binary, which supports the keys. + {name: "vendored, user-owned caller pins a poll workflow that predates the keys", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, enabled: true, vendored: true, uses: upstreamPoll + "@" + pin}, + {name: "vendored, caller read error fails closed", setup: func(fc *forge.FakeClient) { + fc.GetFileContentErrors = map[string]error{"group/project/" + scaffold.JiraPollCallerPath: errors.New("api down")} + }, authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, enabled: true, vendored: true, wantErr: "api down"}, + {name: "vendored, user-owned caller, fullsend_ref predates the keys", setup: serve(jiraOAuthWorkflowFixture), authEnv: []string{"FULLSEND_JIRA_WRITE_GROUPS"}, ref: pin, enabled: true, vendored: true, uses: upstreamPoll + "@" + pin}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fc := forge.NewFakeClient() + if tt.setup != nil { + tt.setup(fc) + } + d := gitlabJiraDiscovery(fc, jiraPollState{authEnv: tt.authEnv}) + d.jira.enabled = tt.enabled + d.resolved.FullsendRef = tt.ref + if tt.vendored { + d.resolved.Vendor, d.resolved.Forge = true, ForgeGitHub + } + if tt.managed { + fc.FileContents["group/project/"+scaffold.JiraPollCallerPath] = []byte(scaffold.JiraPollCallerMarker + "\n") + } + if tt.uses != "" { + d.resolved.Forge = ForgeGitHub + fc.FileContents["group/project/"+scaffold.JiraPollCallerPath] = []byte("jobs:\n poll:\n uses: " + tt.uses + "\n secrets: inherit\n") + } + if tt.installed != "" { + d.components = []ComponentStatus{{Name: "workflow", Present: true, Actual: tt.installed}} + } + err := checkJiraAuthorizationEnvSupport(context.Background(), d, ConvergeConfig{}, NewRefResolver(fc)) + if tt.wantErr == "" { + require.NoError(t, err) + return + } + require.ErrorContains(t, err, tt.wantErr) + }) + } + + // The check finds supporting refs by this marker, so the workflow must keep it. + t.Run("the current workflow carries the marker", func(t *testing.T) { + content, err := os.ReadFile("../../" + reusableJiraPollWorkflowPath) + require.NoError(t, err) + assert.Contains(t, string(content), jiraAuthorizationEnvMarker) + }) + + t.Run("pin without an upstream client", func(t *testing.T) { + d := gitlabJiraDiscovery(forge.NewFakeClient(), jiraPollState{authEnv: []string{"WRITE_GROUPS"}}) + d.resolved.FullsendRef = pin + require.ErrorContains(t, checkJiraAuthorizationEnvSupport(context.Background(), d, ConvergeConfig{}, nil), "cannot be checked") + }) + + t.Run("stamped scaffold without an upstream client", func(t *testing.T) { + d := gitlabJiraDiscovery(forge.NewFakeClient(), jiraPollState{authEnv: []string{"WRITE_GROUPS"}}) + d.components = []ComponentStatus{{Name: "workflow", Present: true, Actual: pin}} + require.NoError(t, checkJiraAuthorizationEnvSupport(context.Background(), d, ConvergeConfig{}, nil)) + }) +} + +func TestEffectiveJiraPollState_CollectsListVariablesForAnyTracker(t *testing.T) { + managed, err := config.ParsePerRepoConfigWriter([]byte("authorization:\n - provider: jira\n write:\n groups_from: WRITE_GROUPS\n")) + require.NoError(t, err) + st, err := effectiveJiraPollState(ResolvedConfig{Owner: "acme", Repo: "api", Managed: managed}, nil) + require.NoError(t, err) + assert.Nil(t, st.jira) + assert.Equal(t, []string{"WRITE_GROUPS"}, st.authEnv) +} diff --git a/internal/repos/status.go b/internal/repos/status.go index db49fb5090..225833b0a1 100644 --- a/internal/repos/status.go +++ b/internal/repos/status.go @@ -386,6 +386,20 @@ func checkRepoStatus(ctx context.Context, cfg ResolvedConfig, dcfg DriftConfig, status.Error = fmt.Sprintf("probing components for %s/%s: %v", owner, repo, probeErr) return status } + // jiraAuthorizationEnvError is the configuration error install would fail + // on: the release the repository's jobs run cannot load a config that uses + // groups_from or accounts_from. + jiraAuthorizationEnvError := func() error { + if !presetLoaded { + return nil + } + jira, err := effectiveJiraPollState(cfg, cfg.ProposedBase) + if err != nil { + return nil + } + d := convergeDiscovery{resolved: cfg, components: components, jira: jira} + return checkJiraAuthorizationEnvSupport(ctx, d, ConvergeConfig{UpstreamRef: dcfg.UpstreamRef, UpstreamTag: dcfg.UpstreamTag}, resolver) + } if !anyComponentPresent(components) { // Leftover credentials of an unselected method are drift even // when none of the selected method's components exist. @@ -403,6 +417,12 @@ func checkRepoStatus(ctx context.Context, cfg ResolvedConfig, dcfg DriftConfig, if status.Error != "" { return status } + // Before the drift check, which would report the config as + // compatible with the pinned ref's schema. + if err := jiraAuthorizationEnvError(); err != nil { + status.Error = err.Error() + return status + } checkManagedConfigDrift(ctx, cfg, &status) if status.Error != "" { return status @@ -447,6 +467,11 @@ func checkRepoStatus(ctx context.Context, cfg ResolvedConfig, dcfg DriftConfig, }) } + if err := jiraAuthorizationEnvError(); err != nil { + status.Error = err.Error() + return status + } + // Report the configuration error install would fail on: nothing will // refresh a live agent job script that ignores the service account. if workflowPresent && presetLoaded { diff --git a/internal/repos/workflow_test_helper_test.go b/internal/repos/workflow_test_helper_test.go index b38a55084c..afdda9bed5 100644 --- a/internal/repos/workflow_test_helper_test.go +++ b/internal/repos/workflow_test_helper_test.go @@ -11,6 +11,8 @@ import ( // jiraOAuthWorkflowFixture stands in for a reusable workflow that declares // the Jira OAuth client credential secrets. jiraPreOAuthWorkflowFixture is // a pre-OAuth workflow that exists but lacks those declarations. +// jiraAuthListsWorkflowFixture also declares the jira authorization list +// secrets, like the current release. const ( jiraOAuthWorkflowFixture = `name: Jira poll on: @@ -29,6 +31,15 @@ on: secrets: FULLSEND_JIRA_TOKEN: required: false +` + jiraAuthListsWorkflowFixture = jiraOAuthWorkflowFixture + ` FULLSEND_JIRA_WRITE_GROUPS: + required: false + FULLSEND_JIRA_WRITE_ACCOUNTS: + required: false + FULLSEND_JIRA_TRIAGE_GROUPS: + required: false + FULLSEND_JIRA_TRIAGE_ACCOUNTS: + required: false ` ) @@ -68,7 +79,7 @@ func newFakeClientForBatch(repos ...string) *forge.FakeClient { } // v1.0.0 is the current-release fixture for tests that enable GitHub // Jira polling. Older pins intentionally lack this file in the fixture. - fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@v1.0.0"] = []byte(jiraOAuthWorkflowFixture) + fc.FileContentsRef[shimOwner+"/"+shimRepo+"/"+reusableJiraPollWorkflowPath+"@v1.0.0"] = []byte(jiraAuthListsWorkflowFixture) // A GitHub OpenAI install that cannot fetch its explicit pin's scaffold // fails closed, so the default test pin serves the embedded per-repo // shim and thin callers, which forward the key and match what the diff --git a/internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml b/internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml index 3a7e6f07a4..dc1cddeb76 100644 --- a/internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml +++ b/internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml @@ -13,7 +13,9 @@ # # Security: Jira credentials reach the poll job and are passed to the agent # workflow only for Jira-originated status writes. They are never put in the -# runner-secret bundle. +# runner-secret bundle. The jira authorization list secrets, rendered only when +# config.yaml reads them with groups_from or accounts_from, reach the poll job +# alone. # # Concurrency: overlapping poll cycles queue rather than cancel each other. name: fullsend Jira poll @@ -41,6 +43,10 @@ jobs: FULLSEND_JIRA_EMAIL: ${{ secrets.FULLSEND_JIRA_EMAIL }} FULLSEND_JIRA_CLIENT_ID: ${{ secrets.FULLSEND_JIRA_CLIENT_ID }} FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }} + FULLSEND_JIRA_WRITE_GROUPS: ${{ secrets.FULLSEND_JIRA_WRITE_GROUPS }} + FULLSEND_JIRA_WRITE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_WRITE_ACCOUNTS }} + FULLSEND_JIRA_TRIAGE_GROUPS: ${{ secrets.FULLSEND_JIRA_TRIAGE_GROUPS }} + FULLSEND_JIRA_TRIAGE_ACCOUNTS: ${{ secrets.FULLSEND_JIRA_TRIAGE_ACCOUNTS }} dispatch: needs: poll diff --git a/internal/scaffold/github_kill_switch_test.go b/internal/scaffold/github_kill_switch_test.go index 46c8e98c31..8473e62512 100644 --- a/internal/scaffold/github_kill_switch_test.go +++ b/internal/scaffold/github_kill_switch_test.go @@ -35,15 +35,20 @@ type ghWorkflowFile struct { // Actions run. func extractReusableDispatchStepScript(t *testing.T, jobName, stepName string) string { t.Helper() - path := filepath.Join("..", "..", ".github", "workflows", "reusable-dispatch.yml") - content, err := os.ReadFile(path) + return extractWorkflowStepScript(t, "reusable-dispatch.yml", jobName, stepName) +} + +// extractWorkflowStepScript does the same for any file in .github/workflows. +func extractWorkflowStepScript(t *testing.T, file, jobName, stepName string) string { + t.Helper() + content, err := os.ReadFile(filepath.Join("..", "..", ".github", "workflows", file)) require.NoError(t, err) var wf ghWorkflowFile require.NoError(t, yaml.Unmarshal(content, &wf)) job, ok := wf.Jobs[jobName] - require.True(t, ok, "job %q not found in reusable-dispatch.yml", jobName) + require.True(t, ok, "job %q not found in %s", jobName, file) for _, step := range job.Steps { if step.Name == stepName { require.NotEmpty(t, step.Run, "step %q has no run script", stepName) diff --git a/internal/scaffold/jira_poll.go b/internal/scaffold/jira_poll.go index 408bbfae43..b4e97322df 100644 --- a/internal/scaffold/jira_poll.go +++ b/internal/scaffold/jira_poll.go @@ -2,6 +2,7 @@ package scaffold import ( "fmt" + "slices" "strings" "github.com/fullsend-ai/fullsend/internal/config" @@ -37,6 +38,22 @@ var jiraPollOAuthSecretLines = []string{ " FULLSEND_JIRA_CLIENT_SECRET: ${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }}\n", } +// JiraAuthorizationSecrets are the secrets the managed GitHub Jira poll +// caller can forward to the poll job for the jira authorization provider's +// groups_from and accounts_from lists (#9132). The managed caller cannot pass +// any other variable to the poller. +var JiraAuthorizationSecrets = []string{ + "FULLSEND_JIRA_WRITE_GROUPS", + "FULLSEND_JIRA_WRITE_ACCOUNTS", + "FULLSEND_JIRA_TRIAGE_GROUPS", + "FULLSEND_JIRA_TRIAGE_ACCOUNTS", +} + +// jiraPollSecretLine is the caller line that forwards secret name. +func jiraPollSecretLine(name string) string { + return " " + name + ": ${{ secrets." + name + " }}\n" +} + // RenderJiraPollCaller renders the managed GitHub Jira poll caller. Its // reusable workflows are pinned to the upstream ref in opts; the caller // always references the upstream repository, so it does not depend on a @@ -45,8 +62,11 @@ var jiraPollOAuthSecretLines = []string{ // credentials to Jira-originated Fullsend status updates only. oauthConfigured // controls whether the OAuth client credentials are forwarded; a token-only // caller omits them so it stays valid against reusable workflows pinned to a -// ref that predates OAuth support. -func RenderJiraPollCaller(opts RenderOptions, emailConfigured, oauthConfigured bool) ([]byte, error) { +// ref that predates OAuth support. authorizationSecrets lists the +// JiraAuthorizationSecrets the poll job receives; the others are omitted for +// the same reason, so a caller whose config reads none of them is unchanged. +// Any other name is ignored: the caller cannot forward it. +func RenderJiraPollCaller(opts RenderOptions, emailConfigured, oauthConfigured bool, authorizationSecrets []string) ([]byte, error) { raw, err := FullsendRepoFile(jiraPollCallerTemplate) if err != nil { return nil, fmt.Errorf("loading Jira poll caller template: %w", err) @@ -66,6 +86,15 @@ func RenderJiraPollCaller(opts RenderOptions, emailConfigured, oauthConfigured b out = strings.ReplaceAll(out, line, "") } } + for _, name := range JiraAuthorizationSecrets { + line := jiraPollSecretLine(name) + if strings.Count(out, line) != 1 { + return nil, fmt.Errorf("the Jira poll caller template must forward %s to the poll job", name) + } + if !slices.Contains(authorizationSecrets, name) { + out = strings.Replace(out, line, "", 1) + } + } upstream := opts upstream.Vendored = false out = strings.ReplaceAll(out, "__REUSABLE_WORKFLOW__", upstreamReusableWorkflowUses("reusable-poll-jira.yml", upstream)) diff --git a/internal/scaffold/jira_poll_test.go b/internal/scaffold/jira_poll_test.go index d6f5d07225..74281264a6 100644 --- a/internal/scaffold/jira_poll_test.go +++ b/internal/scaffold/jira_poll_test.go @@ -1,7 +1,9 @@ package scaffold import ( + "encoding/json" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -15,7 +17,7 @@ func TestRenderJiraPollCaller(t *testing.T) { pinned := RenderOptions{UpstreamRef: "0123456789abcdef0123456789abcdef01234567", UpstreamTag: "v1.2.3"} t.Run("with email", func(t *testing.T) { - out, err := RenderJiraPollCaller(pinned, true, true) + out, err := RenderJiraPollCaller(pinned, true, true, nil) require.NoError(t, err) s := string(out) @@ -53,7 +55,7 @@ func TestRenderJiraPollCaller(t *testing.T) { }) t.Run("without email", func(t *testing.T) { - out, err := RenderJiraPollCaller(pinned, false, true) + out, err := RenderJiraPollCaller(pinned, false, true, nil) require.NoError(t, err) assert.Contains(t, string(out), "FULLSEND_JIRA_TOKEN: ${{ secrets.FULLSEND_JIRA_TOKEN }}") var wf callerWorkflow @@ -68,7 +70,7 @@ func TestRenderJiraPollCaller(t *testing.T) { }) t.Run("token only omits the OAuth client credentials", func(t *testing.T) { - out, err := RenderJiraPollCaller(pinned, true, false) + out, err := RenderJiraPollCaller(pinned, true, false, nil) require.NoError(t, err) assert.NotContains(t, string(out), "FULLSEND_JIRA_CLIENT_ID") assert.NotContains(t, string(out), "FULLSEND_JIRA_CLIENT_SECRET") @@ -84,8 +86,24 @@ func TestRenderJiraPollCaller(t *testing.T) { assert.Contains(t, wf.Jobs["dispatch"].Secrets, "FULLSEND_JIRA_TOKEN") }) + t.Run("authorization list secrets", func(t *testing.T) { + out, err := RenderJiraPollCaller(pinned, true, false, []string{"FULLSEND_JIRA_WRITE_GROUPS", "FULLSEND_JIRA_TRIAGE_ACCOUNTS"}) + require.NoError(t, err) + var wf callerWorkflow + require.NoError(t, yaml.Unmarshal(out, &wf)) + assert.Equal(t, map[string]string{ + "FULLSEND_JIRA_TOKEN": "${{ secrets.FULLSEND_JIRA_TOKEN }}", + "FULLSEND_JIRA_EMAIL": "${{ secrets.FULLSEND_JIRA_EMAIL }}", + "FULLSEND_JIRA_WRITE_GROUPS": "${{ secrets.FULLSEND_JIRA_WRITE_GROUPS }}", + "FULLSEND_JIRA_TRIAGE_ACCOUNTS": "${{ secrets.FULLSEND_JIRA_TRIAGE_ACCOUNTS }}", + }, wf.Jobs["poll"].Secrets) + for _, name := range JiraAuthorizationSecrets { + assert.NotContains(t, wf.Jobs["dispatch"].Secrets, name, "agents never receive the lists") + } + }) + t.Run("default ref and vendored install", func(t *testing.T) { - out, err := RenderJiraPollCaller(RenderOptions{Vendored: true}, true, true) + out, err := RenderJiraPollCaller(RenderOptions{Vendored: true}, true, true, nil) require.NoError(t, err) s := string(out) assert.Contains(t, s, "uses: fullsend-ai/fullsend/.github/workflows/reusable-poll-jira.yml@main\n", @@ -96,9 +114,9 @@ func TestRenderJiraPollCaller(t *testing.T) { }) t.Run("idempotent", func(t *testing.T) { - a, err := RenderJiraPollCaller(pinned, true, true) + a, err := RenderJiraPollCaller(pinned, true, true, nil) require.NoError(t, err) - b, err := RenderJiraPollCaller(pinned, true, true) + b, err := RenderJiraPollCaller(pinned, true, true, nil) require.NoError(t, err) assert.Equal(t, a, b) }) @@ -108,7 +126,7 @@ func TestRenderJiraPollCaller(t *testing.T) { // against the workflow_call interface of reusable-dispatch.yml: it passes // every required input and secret, and nothing undeclared. func TestJiraPollCallerDispatchAlignment(t *testing.T) { - out, err := RenderJiraPollCaller(RenderOptions{}, true, true) + out, err := RenderJiraPollCaller(RenderOptions{}, true, true, JiraAuthorizationSecrets) require.NoError(t, err) var caller callerWorkflow require.NoError(t, yaml.Unmarshal(out, &caller)) @@ -140,7 +158,7 @@ func TestJiraPollCallerDispatchAlignment(t *testing.T) { // TestJiraPollCallerPollAlignment checks the poll caller against the shared // reusable Jira poll workflow's workflow_call contract and output. func TestJiraPollCallerPollAlignment(t *testing.T) { - out, err := RenderJiraPollCaller(RenderOptions{}, true, true) + out, err := RenderJiraPollCaller(RenderOptions{}, true, true, JiraAuthorizationSecrets) require.NoError(t, err) var caller callerWorkflow require.NoError(t, yaml.Unmarshal(out, &caller)) @@ -183,10 +201,88 @@ func TestJiraPollCallerPollAlignment(t *testing.T) { assert.Contains(t, reusable.On.WorkflowCall.Secrets, name, "secret %q is not declared by reusable-poll-jira.yml", name) } - assert.Equal(t, "${{ jobs.poll.outputs.matrix }}", reusable.On.WorkflowCall.Outputs["matrix"].Value) - assert.Equal(t, "${{ steps.matrix.outputs.matrix }}", reusable.Jobs["poll"].Outputs["matrix"]) + assert.Equal(t, `${{ jobs.matrix.outputs.matrix || '{"include":[]}' }}`, reusable.On.WorkflowCall.Outputs["matrix"].Value) + assert.Equal(t, "${{ steps.matrix.outputs.matrix }}", reusable.Jobs["matrix"].Outputs["matrix"]) assert.Equal(t, "${{ needs.poll.outputs.matrix }}", caller.Jobs["dispatch"].With["matrix"]) - assert.Equal(t, "${{ inputs.timeout_minutes }}", reusable.Jobs["poll"].TimeoutMinutes) + for _, job := range []string{"poll", "matrix"} { + assert.Equal(t, "${{ inputs.timeout_minutes }}", reusable.Jobs[job].TimeoutMinutes, job) + } + + // GitHub drops a job output that contains a value of a secret the job + // has, so the job that holds the secrets outputs only a count and a + // random artifact suffix, and the job that sets the matrix holds none. + assert.Equal(t, map[string]string{ + "dispatch_count": "${{ steps.check.outputs.count }}", + "artifact_suffix": "${{ steps.check.outputs.artifact_suffix }}", + }, reusable.Jobs["poll"].Outputs) + var raw struct { + Jobs map[string]yaml.Node `yaml:"jobs"` + } + require.NoError(t, yaml.Unmarshal(content, &raw)) + matrixNode := raw.Jobs["matrix"] + matrixJob, err := yaml.Marshal(&matrixNode) + require.NoError(t, err) + require.Contains(t, string(matrixJob), "download-artifact", "the matrix job was parsed") + assert.NotContains(t, string(matrixJob), "secrets.") +} + +// The check step must find a Jira credential that JSON escaped inside +// event_payload, an object as the poller writes it. +func TestJiraPollWorkflowCheckDispatches(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not found in PATH") + } + script := extractWorkflowStepScript(t, "reusable-poll-jira.yml", "poll", "Check dispatches") + + // Only the secret under test is set. The others are empty, as the secrets + // of the unused credential type are, and an empty one must match nothing. + secrets := map[string]string{ + "FULLSEND_JIRA_TOKEN": `to"k<1`, + "FULLSEND_JIRA_EMAIL": "poller@example.invalid", + "FULLSEND_JIRA_CLIENT_ID": "client-id-1", + "FULLSEND_JIRA_CLIENT_SECRET": "client-secret-1", + } + tests := []struct { + name, comment string + want string // the secret the step must name, or "" to pass + }{ + {name: "no credential", comment: "/fs-triage"}, + {name: "token that JSON escapes", comment: "my token is " + secrets["FULLSEND_JIRA_TOKEN"], want: "FULLSEND_JIRA_TOKEN"}, + {name: "email", comment: "ask " + secrets["FULLSEND_JIRA_EMAIL"], want: "FULLSEND_JIRA_EMAIL"}, + {name: "client ID", comment: "id " + secrets["FULLSEND_JIRA_CLIENT_ID"], want: "FULLSEND_JIRA_CLIENT_ID"}, + {name: "client secret", comment: "secret " + secrets["FULLSEND_JIRA_CLIENT_SECRET"], want: "FULLSEND_JIRA_CLIENT_SECRET"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + payload := map[string]any{"comment": map[string]any{"body": tt.comment}} + dispatches, err := json.Marshal([]map[string]any{{"agent": "triage", "event_payload": payload}}) + require.NoError(t, err) + dir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(dir, "dispatches.json"), dispatches, 0o600)) + output := filepath.Join(dir, "output") + + cmd := exec.Command("bash", "-c", script) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GITHUB_OUTPUT="+output) + for name, value := range secrets { + if name != tt.want { + value = "" + } + cmd.Env = append(cmd.Env, name+"="+value) + } + out, err := cmd.CombinedOutput() + if tt.want != "" { + require.Error(t, err) + assert.Contains(t, string(out), "dispatches.json contains "+tt.want) + assert.NotContains(t, string(out), secrets[tt.want]) + return + } + require.NoError(t, err, string(out)) + got, err := os.ReadFile(output) + require.NoError(t, err) + assert.Contains(t, string(got), "count=1\n") + }) + } } func TestIsManagedJiraPollCaller(t *testing.T) { diff --git a/internal/scaffold/workflow_call_alignment_test.go b/internal/scaffold/workflow_call_alignment_test.go index 714f631741..8abc1ed04d 100644 --- a/internal/scaffold/workflow_call_alignment_test.go +++ b/internal/scaffold/workflow_call_alignment_test.go @@ -927,20 +927,34 @@ func TestJiraSecretsActionWiring(t *testing.T) { // TestJiraPollWorkflowSecretThreading validates the GitHub poller workflow // contract and its scaffold caller. OAuth credentials must reach the poll // step, while the caller also forwards them to reusable-dispatch for Jira -// run-status updates. +// run-status updates. The jira authorization list secrets (#9132) reach the +// poll step under their own names. func TestJiraPollWorkflowSecretThreading(t *testing.T) { content := string(loadRepoFile(".github/workflows/reusable-poll-jira.yml")(t)) var parsed reusableWorkflow require.NoError(t, yaml.Unmarshal([]byte(content), &parsed)) - for _, name := range []string{"FULLSEND_JIRA_TOKEN", "FULLSEND_JIRA_EMAIL", "FULLSEND_JIRA_CLIENT_ID", "FULLSEND_JIRA_CLIENT_SECRET"} { + credentials := []string{"FULLSEND_JIRA_TOKEN", "FULLSEND_JIRA_EMAIL", "FULLSEND_JIRA_CLIENT_ID", "FULLSEND_JIRA_CLIENT_SECRET"} + names := append(append([]string{}, credentials...), JiraAuthorizationSecrets...) + // Scoped to the step: the check step also reads the credentials. + pollStep := extractStepSection(t, content, "Poll Jira") + for _, name := range names { secret, ok := parsed.On.WorkflowCall.Secrets[name] require.True(t, ok, "reusable-poll-jira.yml must declare %s", name) - assert.False(t, secret.Required, "%s must be optional so either credential type can be used", name) - assert.Contains(t, content, name+": ${{ secrets."+name+" }}", "poll step must receive %s", name) + assert.False(t, secret.Required, "%s must be optional: either credential type can be used, and the lists are opt-in", name) + assert.Contains(t, pollStep, name+": ${{ secrets."+name+" }}", "poll step must receive %s", name) + } + // The check step looks for every credential in the dispatches. It must + // not get a list secret: a list holds the ID of the account that acted. + checkStep := extractStepSection(t, content, "Check dispatches") + for _, name := range credentials { + assert.Contains(t, checkStep, name+": ${{ secrets."+name+" }}", "check step must receive %s", name) + } + for _, name := range JiraAuthorizationSecrets { + assert.NotContains(t, checkStep, name, "check step must not look for %s", name) } caller := string(loadScaffoldFile("templates/jira-poll-per-repo.yaml")(t)) - for _, name := range []string{"FULLSEND_JIRA_TOKEN", "FULLSEND_JIRA_EMAIL", "FULLSEND_JIRA_CLIENT_ID", "FULLSEND_JIRA_CLIENT_SECRET"} { + for _, name := range names { assert.Contains(t, caller, name+": ${{ secrets."+name+" }}", "managed poll caller must forward %s", name) } } From 6d51a8e317fdf349ac864c270e01f3f926c6e0ba Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Fri, 20 Nov 2026 19:20:27 -0500 Subject: [PATCH 036/208] fix(runtime): count codex's incomplete-item backfill warning At 0.170.0 exec logs a third thread/items/list warning, when a page returns an incomplete item, and returns without the backfill, so a dropped completed item stays lost as after the other two. Count it with the other backfill markers, and list it with them in the re-check row and the testdata README. Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 2 +- internal/runtime/codex_subagents.go | 1 + internal/runtime/codex_subagents_test.go | 5 +++-- internal/runtime/testdata/codex/README.md | 7 ++++--- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 87ae10986a..40357b7253 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1733,7 +1733,7 @@ Two artefacts of the run are worth knowing about: | `ConfigToml` keys and the `ReasoningEffort` enum | a renamed or removed key silently changes behaviour; `--strict-config` reports it | `codex-rs/config/src/config_toml.rs`, `codex-rs/protocol/src/openai_models.rs` | | Project trust and `AGENTS.md` | the pinned untrusted entry must still stop codex recording its own trust level, the repo's `.codex/` layer must stay unloaded, and `$CODEX_HOME/AGENTS.md` must still load while the project is untrusted, or the bridge stops reaching the agent; at 0.170.0 exec also prints a stderr warning naming `codex exec --trust` whenever it disables the repo's `.codex/` layer, and the runner must never pass that flag | `codex-rs/app-server/src/request_processors/thread_processor.rs` (trust write), `codex-rs/exec/src/lib.rs` (`thread_start_params_from_config`, which names no cwd at 0.170.0, and `--trust`), `codex-rs/config/src/loader/mod.rs`, `codex-rs/core/src/agents_md.rs`, `codex-rs/codex-home/src/instructions/mod.rs` | | JSONL event structs, rollout line types and rollout file naming | the stream parser and transcript extraction; a rollout line type missing from `codexRolloutEnvelopes` discards the whole transcript | `codex-rs/exec/src/exec_events.rs`, `codex-rs/history/src/rollout_payload.rs` (`RolloutItemWire`), `codex-rs/thread-store/src/local/helpers.rs` | -| Stderr warning markers (`dropping in-process server notification (queue full)`, `thread/items/list failed during turn completion`, `thread/items/list returned a repeated cursor during turn completion`, and the prefix `thread/read failed while backfilling turn items`; 0.170.0 adds `thread/items/list returned an incomplete item during turn completion`, which exec cannot reach while it asks for no deferred output), their log targets and levels, and the `RUST_LOG` filter (`error,opentelemetry_sdk=off,opentelemetry_otlp=off,codex_exec=warn,codex_app_server::in_process=warn`; `info` with debug) | `codexStderrDrops` and the debug-log counts match these literals; changed text, targets, levels or filter semantics can silently stop the dropped-notification and failed-backfill warnings | `codex-rs/exec/src/lib.rs` (backfill `warn!` calls, `EXEC_DEFAULT_LOG_FILTER`), `codex-rs/app-server/src/in_process.rs` (drop `warn!` call) | +| Stderr warning markers (`dropping in-process server notification (queue full)`, `thread/items/list failed during turn completion`, `thread/items/list returned a repeated cursor during turn completion`, `thread/items/list returned an incomplete item during turn completion`, and the prefix `thread/read failed while backfilling turn items`), their log targets and levels, and the `RUST_LOG` filter (`error,opentelemetry_sdk=off,opentelemetry_otlp=off,codex_exec=warn,codex_app_server::in_process=warn`; `info` with debug) | `codexStderrDrops` and the debug-log counts match these literals; changed text, targets, levels or filter semantics can silently stop the dropped-notification and failed-backfill warnings | `codex-rs/exec/src/lib.rs` (backfill `warn!` calls, `EXEC_DEFAULT_LOG_FILTER`), `codex-rs/app-server/src/in_process.rs` (drop `warn!` call) | | The multi-agent tool names (`multi_agent_v1*`, `collaboration*`, the bare V1 `spawn_agent`), the block contract (exit 2 with non-empty stderr blocks; a timeout kills the handler and lets the call through), `agent_id` and `agent_type` in a child's payload, the spawn arguments, and what a child start rereads (`hooks.json` and the role file) | the spawn guard's matcher, pass-through set, policy, digest set and deadline rest on them; a renamed tool is denied (loud), but a payload without `agent_id` or `agent_type`, a new model or effort argument, a changed `fork_turns` reading, a changed block contract or a child that rereads another file turns a deny into a pass | `codex-rs/core/src/tools/handlers/multi_agents_spec.rs`, `codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs` (`SpawnAgentArgs::fork_mode`, which the hook's `_is_none_fork` mirrors), `codex-rs/core/src/tools/registry.rs` (`function_hook_tool_name`), `codex-rs/hooks/src/engine/command_runner.rs` (the timeout branch), `codex-rs/core/src/agent/role.rs` (the role file, read at spawn) | | The bundled catalog's `multi_agent_version`, `default_reasoning_level` and `supported_reasoning_levels` entries, the version codex supplies to an entry that carries none, and the floor model (`codex debug models --bundled`; at 0.170.0 `gpt-5.6-luna` is the listed model that selects `v1` and defaults to `medium`, and `gpt-5.5` carries no version, which the `multi_agent` feature, on by default (deprecated at 0.170.0, still on), resolves to V1, and lists `low` to `xhigh`) | part two of the delegation gate, the child-model floor and the child-effort check rest on them: the floor must stay listed, or every delegating agent without `subagents.default` or `FULLSEND_CODEX_SUBAGENT_MODEL` fails Bootstrap, while the floor's own collaboration version matters only under a V2 parent, which delegates only while no child model selects V2 (moving luna to V2 would stop every V2 parent on the default child model from delegating); a bump that turns `multi_agent` off by default, or gives the null entry a version, changes which parents delegate; a changed level set changes which run efforts Bootstrap accepts; and the fixture `internal/runtime/testdata/codex/models-bundled-0.170.0.json` must be regenerated, never edited | `codex-rs/models-manager/models.json` in the bumped tag; regenerate the fixture with the one-liner in `codex_personas_test.go`'s `TestCodexCatalog` comment and run `go test ./internal/runtime/ -run 'TestCodexCatalog\|TestCodexParentCollabVersion\|TestCodexV2ChildModelReason\|TestResolveCodexChildModels_Effort'` | | The `[agents]` keys codex reads (`enabled`, `max_concurrent_threads_per_session`, `max_depth`, `default_subagent_model`, `default_subagent_reasoning_effort`, and `[agents.]` `description` and `config_file`) and the order of the child path: with no model argument a child takes `default_subagent_model` and, with no effort argument, `default_subagent_reasoning_effort`, else that model's catalog default; a role file applies after and its effort is checked against its own model | `codexAgentsBlock` writes the keys and Bootstrap checks the child efforts on that order; a renamed key or a changed order silently changes every child's model or effort | `codex-rs/config/src/config_toml.rs` (`AgentsToml`), `codex-rs/core/src/config/mod.rs`, `codex-rs/core/src/agent/child_config.rs` (`apply_requested_spawn_agent_model_overrides`, `apply_spawn_agent_role`), `codex-rs/core/src/agent/role.rs` | diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index 1bdc2dd3a0..dc4ca7021e 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -218,6 +218,7 @@ const codexDroppedNotification = "dropping in-process server notification (queue var codexBackfillFailedMarkers = []string{ "thread/items/list failed during turn completion", "thread/items/list returned a repeated cursor during turn completion", + "thread/items/list returned an incomplete item during turn completion", "thread/read failed while backfilling turn items", } diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 400f0db2c0..af8a703b08 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -1173,8 +1173,9 @@ func TestCodexStderrDrops_CountsAcrossChunks(t *testing.T) { } assert.Equal(t, 2, d.Dropped, "one per line, however the writes split it") assert.Equal(t, whole, sink.String(), "every byte still reaches the runner's stderr") - // Every backfill marker counts: the paginated thread's two (a failed - // page, a looping cursor) and the legacy-mode thread's read. + // Every backfill marker counts: the paginated thread's three (a failed + // page, a looping cursor, an incomplete item) and the legacy-mode + // thread's read. for _, m := range codexBackfillFailedMarkers { _, err := d.Write([]byte("WARN codex_exec: " + m + ": boom\n")) require.NoError(t, err) diff --git a/internal/runtime/testdata/codex/README.md b/internal/runtime/testdata/codex/README.md index 965e780ab7..25dba95418 100644 --- a/internal/runtime/testdata/codex/README.md +++ b/internal/runtime/testdata/codex/README.md @@ -83,9 +83,10 @@ runner scans for, while exec re-emits at `turn/completed` the completed items wh `item.started` it saw (`maybe_backfill_turn_completed_items`, `reconcile_unfinished_started_items`), only for a non-ephemeral thread, which is paginated, and only when its `thread/items/list` pages succeed -(`should_backfill_turn_completed_items`; a failed or looping read logs -`thread/items/list failed during turn completion` or -`thread/items/list returned a repeated cursor during turn completion` at warn from +(`should_backfill_turn_completed_items`; a failed or looping read, or a page +with an incomplete item, logs `thread/items/list failed during turn completion`, +`thread/items/list returned a repeated cursor during turn completion` or +`thread/items/list returned an incomplete item during turn completion` at warn from `codex_exec`, which the runner counts too; a non-ephemeral thread whose history mode is not paginated reads `thread/read` and logs `thread/read failed while backfilling turn items for turn completion`; an From 88501af0902b3a1f000adb7a95e8cfd5e98a69f8 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Fri, 20 Nov 2026 19:21:14 -0500 Subject: [PATCH 037/208] docs(runtime): align the project-trust re-check row with the posture The row still said the pinned untrusted entry must stop codex recording its own trust level, which the Posture bullet no longer claims: at 0.170.0 the app server's trust write needs a requested cwd, and exec names none. State the row's why as the Posture bullet does, and drop the trust-write and thread-start sources it rested on. Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 40357b7253..10e4fa0d38 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1731,7 +1731,7 @@ Two artefacts of the run are worth knowing about: | Whether a custom provider still issues `GET /v1/models` at startup, every 4.5 minutes from the in-process models refresh and, at 0.170.0, before each sub-agent starts, and whether each denial stays non-fatal, unretried on a 403 and capped at 5 s | the `fullsend-openai` egress profile denies it; if the request ever became fatal or retried, it would delay or fail every first turn and every child start | `codex-rs/models-manager/` (`ensure_initialized`), `codex-rs/core/src/thread_manager/model_catalog.rs`, `codex-rs/app-server/src/models_refresh_worker.rs`, `codex-rs/model-provider/src/models_endpoint.rs` (`MODELS_REFRESH_TIMEOUT`) | | `models_cache.json` name and location, its TTL and the version/identity checks that decide whether it is used | `buildCodexRunCommand` deletes `$CODEX_HOME/models_cache.json` before launch so every run starts from the bundled catalog; a renamed or relocated file would need the deletion to follow it | `codex-rs/models-manager/src/manager.rs` (`MODEL_CACHE_FILE`, `DEFAULT_MODEL_CACHE_TTL`, `try_load_cache`), `codex-rs/models-manager/src/cache.rs` (`load_fresh_file`) | | `ConfigToml` keys and the `ReasoningEffort` enum | a renamed or removed key silently changes behaviour; `--strict-config` reports it | `codex-rs/config/src/config_toml.rs`, `codex-rs/protocol/src/openai_models.rs` | -| Project trust and `AGENTS.md` | the pinned untrusted entry must still stop codex recording its own trust level, the repo's `.codex/` layer must stay unloaded, and `$CODEX_HOME/AGENTS.md` must still load while the project is untrusted, or the bridge stops reaching the agent; at 0.170.0 exec also prints a stderr warning naming `codex exec --trust` whenever it disables the repo's `.codex/` layer, and the runner must never pass that flag | `codex-rs/app-server/src/request_processors/thread_processor.rs` (trust write), `codex-rs/exec/src/lib.rs` (`thread_start_params_from_config`, which names no cwd at 0.170.0, and `--trust`), `codex-rs/config/src/loader/mod.rs`, `codex-rs/core/src/agents_md.rs`, `codex-rs/codex-home/src/instructions/mod.rs` | +| Project trust and `AGENTS.md` | the pinned untrusted entry must keep the repo's `.codex/` layer and its own `AGENTS.md` unloaded, and `$CODEX_HOME/AGENTS.md` must still load while the project is untrusted, or the bridge stops reaching the agent; at 0.170.0 exec also prints a stderr warning naming `codex exec --trust` whenever it disables the repo's `.codex/` layer, and the runner must never pass that flag | `codex-rs/exec/src/lib.rs` (`--trust`), `codex-rs/config/src/loader/mod.rs`, `codex-rs/core/src/agents_md.rs`, `codex-rs/codex-home/src/instructions/mod.rs` | | JSONL event structs, rollout line types and rollout file naming | the stream parser and transcript extraction; a rollout line type missing from `codexRolloutEnvelopes` discards the whole transcript | `codex-rs/exec/src/exec_events.rs`, `codex-rs/history/src/rollout_payload.rs` (`RolloutItemWire`), `codex-rs/thread-store/src/local/helpers.rs` | | Stderr warning markers (`dropping in-process server notification (queue full)`, `thread/items/list failed during turn completion`, `thread/items/list returned a repeated cursor during turn completion`, `thread/items/list returned an incomplete item during turn completion`, and the prefix `thread/read failed while backfilling turn items`), their log targets and levels, and the `RUST_LOG` filter (`error,opentelemetry_sdk=off,opentelemetry_otlp=off,codex_exec=warn,codex_app_server::in_process=warn`; `info` with debug) | `codexStderrDrops` and the debug-log counts match these literals; changed text, targets, levels or filter semantics can silently stop the dropped-notification and failed-backfill warnings | `codex-rs/exec/src/lib.rs` (backfill `warn!` calls, `EXEC_DEFAULT_LOG_FILTER`), `codex-rs/app-server/src/in_process.rs` (drop `warn!` call) | | The multi-agent tool names (`multi_agent_v1*`, `collaboration*`, the bare V1 `spawn_agent`), the block contract (exit 2 with non-empty stderr blocks; a timeout kills the handler and lets the call through), `agent_id` and `agent_type` in a child's payload, the spawn arguments, and what a child start rereads (`hooks.json` and the role file) | the spawn guard's matcher, pass-through set, policy, digest set and deadline rest on them; a renamed tool is denied (loud), but a payload without `agent_id` or `agent_type`, a new model or effort argument, a changed `fork_turns` reading, a changed block contract or a child that rereads another file turns a deny into a pass | `codex-rs/core/src/tools/handlers/multi_agents_spec.rs`, `codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs` (`SpawnAgentArgs::fork_mode`, which the hook's `_is_none_fork` mirrors), `codex-rs/core/src/tools/registry.rs` (`function_hook_tool_name`), `codex-rs/hooks/src/engine/command_runner.rs` (the timeout branch), `codex-rs/core/src/agent/role.rs` (the role file, read at spawn) | From a80fafe1e8240b7dd2f9a57eb6e22b59a2380a1d Mon Sep 17 00:00:00 2001 From: fullsend-code <278716306+fullsend-ai-coder[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:31:27 +0000 Subject: [PATCH 038/208] docs(#9770): document the behaviour-github-emulator check on a PR Add an "On a pull request" section near the top of docs/guides/dev/behaviour-testing.md. It says which jobs make up the required behaviour-github-emulator check, which artifact each job uploads and what it holds, how to tell a failure in the change from an emulator failure, when to re-run and where to file emulator bugs. It documents the workflow_dispatch inputs (features, workers, runners), the write access dispatch needs, and the rule to grow the emulator instead of listing scenarios in not-sharded.txt. Also update the intro table and "When to add a behaviour test" to mention the emulator. Mark "Failure classification and infrastructure retry" and two Prerequisites items as live-suite only. Add a shards.txt step to the new-scenario checklist, and a pointer to the check in CONTRIBUTING.md. Left out, as the issue directs when evidence is missing: - the troubleshooting table. The sandbox could not download the logs or artifacts of the two failed emulator runs, and their annotations carry only "Process completed with exit code 1."; - the fork dispatch route. No fork run has been verified. The gh workflow run command is marked as not run: the workflow has no workflow_dispatch runs yet. Pre-commit could not fetch its hook repositories (TLS verification failure). The markdown hooks were run directly and passed: end-of-file-fixer, trailing-whitespace, detect-private-key, check-merge-conflict, mixed-line-ending, lint-broken-symlinks, lint-docs-links and lychee (lint-md-links). Closes #9770 Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 3 + docs/guides/dev/behaviour-testing.md | 150 ++++++++++++++++++++++++++- 2 files changed, 149 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6a09b83c08..4146f3af25 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,6 +53,9 @@ contribution. lines you changed. Tables, code blocks, headings, and long URLs are exceptions. See [Documentation § Line wrapping](docs/contributing/documentation.md#line-wrapping). +- Every PR must pass the required `behaviour-github-emulator` check. To read + a failure and re-run it, see + [Behaviour testing § On a pull request](docs/guides/dev/behaviour-testing.md#on-a-pull-request). - Keep PRs focused. One problem area or decision per PR is easier to review than a grab-bag. - If your change touches a problem doc, make sure the "Open questions" section still makes sense after your edit. diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index 85d374cb8a..0fec1dd8cf 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -6,12 +6,136 @@ End-to-end Gherkin tests under `e2e/behaviour/` validate **deterministic platfor |---|-----------------|-----------|------------| | **Target** | Platform workflows, sandbox, SCM | Prompts, models | Go functions | | **Inference** | Dummy runtime | Real LLM | N/A | -| **Infrastructure** | Live GitHub + GHA | Varies | None | +| **Infrastructure** | GitHub emulator on pull requests; live GitHub + GHA in the merge queue and on `main` | Varies | None | ## When to add a behaviour test Add one when a **user-visible workflow** must be verified end-to-end (dispatch → workflow → post-script → SCM state) and the assertion is **binary**. Prefer unit tests for pure Go logic. +Pull requests run the scenarios on a GitHub emulator, and the merge queue and +`main` run them on live GitHub. Write the scenario so it runs on the emulator, +which lets every pull request run it; see +[Adding a scenario](#adding-a-scenario). + +## On a pull request + +Every pull request runs the behaviour scenarios against the +[GitHub emulator](#running-against-a-github-emulator), from +[`behaviour-github-emulator.yml`](../../../.github/workflows/behaviour-github-emulator.yml). +The run needs no repository secrets. + +### What runs, and what you see in Checks + +- **`behaviour-github-emulator`** is the required check. It passes only when + the 16 shard jobs, `behaviour-github-emulator (a)` to + `behaviour-github-emulator (p)`, and the `behaviour-github-emulator + (playback)` job all pass. +- **`behaviour-github-emulator (agents)`** runs the agents repository's suite + against your change. It is not required. It is advisory: it shows whether a + fullsend change breaks the agents suite. +- **`behaviour`** and **`playback`**, from `e2e.yml`, show as skipped. This is + expected, and a skipped job still satisfies these required checks. + +The live `behaviour` and `playback` suites run in the merge queue and on push +to `main`. The merge queue runs `behaviour-github-emulator` as well. To run the +live suites on a pull request before it is enqueued, see +[Run the live suites on a pull request](e2e-testing.md#run-the-live-suites-on-a-pull-request). + +### When the check fails + +1. Open the failed job. Find the failing scenario in the log of its main step: + `Run behaviour features` for a shard, `Run the playback suite` or + `Run the agents suite`. +2. Download the job's artifact from the **Artifacts** list on the run's + summary page. Every job uploads it, whether it passed or failed. + + | Job | Artifact | + |-----|----------| + | A shard | `behaviour-github-emulator-logs-` (`a` to `p`, or `custom` for a [dispatch with features](#running-chosen-scenarios-in-ci)) | + | Playback | `behaviour-github-emulator-logs-playback` | + | Agents | `behaviour-github-emulator-logs-agents` | + + The `Upload logs` step in `behaviour-github-emulator.yml` lists the paths. + Each artifact holds: + + - the run's `*.log` files. `bt-run.log` is the suite output, + `stack/emulator.log` is the emulator's log and `stack/runner-.log` is + each emulator runner's log; + - `phases.tsv`, with the time each phase of the job took; + - `emulator-profile.json`, a profile of the emulator process. Only the + shard artifacts hold it; + - `bt-artifacts/`, the per-scenario output, such as + `debug-scenario--/failure-summary.txt` for a failed + scenario; + - `openshell-logs/`, the OpenShell logs of each agent run. +3. Decide whether the failure comes from your change or from the emulator. + - It is likely an **emulator failure** when the emulator answers HTTP 4xx + or 5xx to an API call that GitHub supports, or when a workflow job never + starts because no emulator runner picks it up. Look for the call in + `bt-run.log` and `stack/emulator.log`, and for the job in + `stack/runner-.log`. + - Otherwise, treat it as a failure in the code under test. A scenario + that fails on an assertion, or a fullsend command that exits with an + error, usually points at the change. +4. Re-run the failed jobs once, with **Re-run failed jobs** on the run. + Re-running needs write access to the repository. Without it, ask a + maintainer to re-run the jobs, or push a new commit. +5. If the job fails again and the failure looks like an emulator bug, file it + at . Include the + run link, the scenario and the emulator log lines. + +To run the job yourself, see +[Running the emulator job on a VM](#running-the-emulator-job-on-a-vm). +[Moving to a new emulator release](#moving-to-a-new-emulator-release) covers +the emulator version the job runs. + +### Running chosen scenarios in CI + +`behaviour-github-emulator.yml` has a `workflow_dispatch` trigger with three +inputs: + +| Input | Meaning | +|-------|---------| +| `features` | Space-separated feature paths under `e2e/behaviour`, each with an optional `:line`. They run as one shard named `custom`, and the playback and agents jobs are skipped. Empty runs the 16 shards, playback and agents. | +| `workers` | Scenarios run in parallel: the slot pool size and the godog concurrency. Empty uses the shard's value from `shards.txt`, or `DEFAULT_WORKERS` (2) with `features`. | +| `runners` | Real `actions/runner` processes on the emulator. Empty uses the shard's value from `shards.txt`, or `DEFAULT_RUNNERS` (4) with `features`. | + +To run one feature from a branch in `fullsend-ai/fullsend`: + +```bash +gh workflow run behaviour-github-emulator.yml --repo fullsend-ai/fullsend \ + --ref -f features="features/triage/triage.feature" \ + -f workers=2 -f runners=4 +``` + +Not run: when this section was written, the workflow had no +`workflow_dispatch` runs, so this command and its output are not yet +verified. + +Dispatching a workflow in `fullsend-ai/fullsend` needs write access to the +repository, and `--ref` must name a branch in it. A contributor without write +access gets every sharded scenario from the pull request run on each push. +To run chosen scenarios alone, use +[Running the emulator job on a VM](#running-the-emulator-job-on-a-vm). + +### Adding a scenario + +Prefer a scenario that uses the dummy runtime, with no real model, and runs on +the emulator, so every pull request runs it. List it in +`e2e/behaviour/github-emulator/shards.txt` (see +[Checklist for new scenarios](#checklist-for-new-scenarios)). + +If the emulator lacks a GitHub behaviour that the scenario needs, add that +behaviour to the emulator. Do not list the scenario in +`e2e/behaviour/github-emulator/not-sharded.txt` for that reason. The +emulator's +[CONTRIBUTING.md](https://github.com/fullsend-ai/github-emulator/blob/main/CONTRIBUTING.md) +and +[development guide](https://github.com/fullsend-ai/github-emulator/blob/main/docs/guides/development.md) +describe how to change it. `not-sharded.txt` is for scenarios that cannot run +on the emulator for another reason, such as a real model behind a +`@requires:capability:` tag. + ## Layout Shared framework (importable by external repos): @@ -338,6 +462,15 @@ Before merging a scenario that dispatches an agent stage: And the agent will succeed to Emit JSON ``` 5. Verify that fixture field values satisfy downstream CLI validation, not just the JSON schema. For example, `head_sha` in `review-result` must be a full-length 40-character hex SHA (`abcdef0123456789abcdef0123456789abcdef01`), not a short prefix. +6. List the scenario in `e2e/behaviour/github-emulator/shards.txt`, or in + `e2e/behaviour/github-emulator/not-sharded.txt` with the reason it cannot + run on the emulator (see [Adding a scenario](#adding-a-scenario)). + `e2e/behaviour/shards_test.go` fails when a scenario is in neither list. + It has no build tag, so plain `go test` runs it: + ```console + $ go test ./e2e/behaviour/ + ok github.com/fullsend-ai/fullsend/e2e/behaviour 0.026s + ``` ### Fixture inventory @@ -378,18 +511,21 @@ The first row proves execution via an auxiliary file; the second row emits the s ## Prerequisites -The procedures in this guide need the following before the first step: +The procedures in this guide need the following before the first step. The +items marked live suite only are not needed for an emulator run, which makes +its own credentials (see +[Running against a GitHub emulator](#running-against-a-github-emulator)). - **Go toolchain.** The repo's Go version (see `go.mod`), used by the `make behaviour-test`, `make playback-test`, and `make behaviour-test-unit` targets. - **`jq`.** `scripts/run-with-infra-retry.sh` reads the failure-class report with `jq` when deciding whether a failed attempt can be retried. -- **GitHub credentials.** Locally, `gh auth login` or export +- **GitHub credentials (live suite only).** Locally, `gh auth login` or export `GH_TOKEN`/`GITHUB_TOKEN` with access to the `halfsend` org pool. In CI, the suite mints per-org tokens through the mint service (`id-token: write` and `ACTIONS_ID_TOKEN_REQUEST_URL`). -- **Driver credentials.** The install factories read the role PEM files +- **Driver credentials (live suite only).** The install factories read the role PEM files (`TEST_*_PEM`) and Cloudflare credentials (`TEST_CLOUDFLARE_*`), and `E2E_GCP_*` configures the GCP side, as described in [Running the playback suite in CI](#running-the-playback-suite-in-ci). @@ -627,6 +763,12 @@ builds, so it follows this pin with no change in that repository. ### Failure classification and infrastructure retry +This section applies to the live suite. For a failure in the +`behaviour-github-emulator` check, see +[When the check fails](#when-the-check-fails). +The `behaviour-artifacts-*` artifact below belongs to the live `behaviour` +job; the emulator jobs upload `behaviour-github-emulator-logs-*`. + Behaviour tests run against live infrastructure — the GitHub API, Actions runners, GCP WIF and the mint — and historically about one required-check failure in four came from that environment rather than from product From 95b7283f8b94da8ca12e4aeb14bec7f2498035f1 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Sat, 21 Nov 2026 08:35:33 -0500 Subject: [PATCH 039/208] docs(#9770): verified dispatch route, troubleshooting table, prose pass Replace the unverified dispatch command with the fork route, run end to end. Add a troubleshooting table keyed on error text from real failed runs. Assisted-by: Claude Signed-off-by: Wayne Sun --- CONTRIBUTING.md | 4 +- docs/guides/dev/behaviour-testing.md | 57 +++++++++++++++++----------- 2 files changed, 37 insertions(+), 24 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4146f3af25..cd233d7f77 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,8 +53,8 @@ contribution. lines you changed. Tables, code blocks, headings, and long URLs are exceptions. See [Documentation § Line wrapping](docs/contributing/documentation.md#line-wrapping). -- Every PR must pass the required `behaviour-github-emulator` check. To read - a failure and re-run it, see +- Every PR must pass the required `behaviour-github-emulator` check. To find + why it failed and re-run it, see [Behaviour testing § On a pull request](docs/guides/dev/behaviour-testing.md#on-a-pull-request). - Keep PRs focused. One problem area or decision per PR is easier to review than a grab-bag. - If your change touches a problem doc, make sure the "Open questions" section still makes sense after your edit. diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index 0fec1dd8cf..3abebc0598 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -31,8 +31,8 @@ The run needs no repository secrets. `behaviour-github-emulator (p)`, and the `behaviour-github-emulator (playback)` job all pass. - **`behaviour-github-emulator (agents)`** runs the agents repository's suite - against your change. It is not required. It is advisory: it shows whether a - fullsend change breaks the agents suite. + against your change. It is advisory, not required: it shows whether a fullsend + change breaks the agents suite. - **`behaviour`** and **`playback`**, from `e2e.yml`, show as skipped. This is expected, and a skipped job still satisfies these required checks. @@ -58,9 +58,9 @@ live suites on a pull request before it is enqueued, see The `Upload logs` step in `behaviour-github-emulator.yml` lists the paths. Each artifact holds: - - the run's `*.log` files. `bt-run.log` is the suite output, - `stack/emulator.log` is the emulator's log and `stack/runner-.log` is - each emulator runner's log; + - the run's `*.log` files: `bt-run.log` (the suite output), + `stack/emulator.log` (the emulator) and `stack/runner-.log` (one per + emulator runner); - `phases.tsv`, with the time each phase of the job took; - `emulator-profile.json`, a profile of the emulator process. Only the shard artifacts hold it; @@ -77,17 +77,30 @@ live suites on a pull request before it is enqueued, see - Otherwise, treat it as a failure in the code under test. A scenario that fails on an assertion, or a fullsend command that exits with an error, usually points at the change. -4. Re-run the failed jobs once, with **Re-run failed jobs** on the run. +4. Re-run the failed jobs once, with **Re-run failed jobs** on the run's + summary page. Re-running needs write access to the repository. Without it, ask a maintainer to re-run the jobs, or push a new commit. 5. If the job fails again and the failure looks like an emulator bug, file it at . Include the run link, the scenario and the emulator log lines. +#### Troubleshooting + +Each row is error text from a real failed run. + +| Error text | What it means | What to do | +|------------|---------------|------------| +| `behaviour suite failed with status 1: scenario failure (0 infrastructure, 1 scenario); report: .../failure-class.json` | A summary line. The counts say how many failed scenarios were classified as infrastructure and how many as scenario failures. | Scroll up to the `Error:` line under `Failed steps:` for the cause. | +| `harness agent "retro": workflow run 5 concluded with "failure" before producing artifact (url=https://ghemu.localhost/...)` | The agent's workflow ran on the emulator and failed. | Find the run's job in `stack/runner-.log` and read the failing step. In past runs, the cause was in the change under test. | +| `harness agent "pr-ping" did not complete successfully; no recent workflow runs found after trigger time; no repository artifacts listed` | The trigger started no workflow run. | Look in `stack/emulator.log` for the event and the run. If the emulator answered HTTP 4xx or 5xx to an API that GitHub supports, the bug is likely in the emulator. | +| `"review" agent was not dispatched since