diff --git a/docs/ADRs/0146-sandbox-environment-contract-manifest.md b/docs/ADRs/0146-sandbox-environment-contract-manifest.md new file mode 100644 index 0000000000..eb277b03cd --- /dev/null +++ b/docs/ADRs/0146-sandbox-environment-contract-manifest.md @@ -0,0 +1,127 @@ +--- +title: "146. Sandbox environment contract manifest" +status: Accepted +relates_to: + - agent-infrastructure + - security-threat-model +topics: + - sandbox + - runtime + - security + - drift +--- + +# 146. Sandbox environment contract manifest + +Date: 2026-10-21 + +## Status + +Accepted + +## Context + +The sandbox environment surface — what the runner injects into the sandbox and +reserves from harness override — was hand-synced in three descriptions, none +machine-checked: the sync note on the `reservedSandboxKeys` map in +`internal/cli/run.go`, +the agents repo's `SANDBOX_RUNTIME_VARS` allowlist in +`scripts/skill-env-reachability-test.sh`, and per-runtime `EnvExports()` in +prose only. The drift was realized in +[fullsend-ai/agents#1677](https://github.com/fullsend-ai/agents/issues/1677): +a skill migrating `CLAUDE_CONFIG_DIR` to a proposed `FULLSEND_SKILLS_DIR` +passed the agents repo's reachability gate because the same PR edited the +allowlist — no released runner exports it, and a bot reviewer, not CI, caught +it. Content repos cannot verify at PR time that env vars their skills +reference are exported by any released runner — a drift-control gap in the +[threat model's](../problems/security-threat-model.md) ranked priorities. + +The lockstep with the fleet harnesses fullsend loads +([ADR 0058](0058-agent-registration.md)) is enforced only by tribal +knowledge; the topology this needs — released tag at PR time via +[ADR 0038](0038-universal-harness-access.md)'s pinned-URL mechanism, +`main` nightly +([ADR 0139](0139-agent-functional-test-suite-lives-in-agents-repo.md)) — +already exists for functional tests. The proposed `FULLSEND_SKILLS_DIR` +([fullsend-ai/agents#1672](https://github.com/fullsend-ai/agents/issues/1672)) +is a follow-up to close the remaining drift surface. + +## Options + +- **Hand-maintained manifest** — rejected: it recreates the drift + (#1677 passed review the same way). +- **Generated bespoke JSON document** — rejected in review: every other + contract under `docs/normative/` is JSON Schema, and a schema lets any + consumer validate with stock tooling instead of parsing a custom format. +- **Behavior-level golden over `bootstrapEnv`** — strongest check, but + needs fixtures for every emission gate; hardening follow-up. + +## Decision + +Publish the sandbox environment contract as generated, committed JSON +Schemas (Draft 2020-12) under +[`docs/normative/sandbox-env/v1/`](../normative/sandbox-env/v1/README.md): + +- [`harness-env.schema.json`](../normative/sandbox-env/v1/harness-env.schema.json) + validates a harness YAML's `env.sandbox` blocks: no key may be a name + the runner reserves. +- [`env-references.schema.json`](../normative/sandbox-env/v1/env-references.schema.json) + validates that code running under a runtime reads only variables the + contract makes reachable there, and carries the full inventory — + always, conditional (with gates), per-runtime, harness-delivered, + reserved, deprecated — in its `$defs`. + +A build-time collector generates the schemas by running every code path +that injects environment variables into the sandbox: the +`.env` emission in `bootstrapEnv` (`internal/cli/run.go`), the +per-iteration env, trace-ID injection, the security-hook env, each +production runtime's `EnvExports()` and launch-command exports, the +`fullsend agent new` Vertex scaffold, and the effective reserved-key set +after the init-time merges. Commands are replayed in a scratch workspace +and parsed for real `export` bindings, and each runtime's declared launch +exports are checked against its built launch commands, so the contract +cannot disagree with the code that builds the environment. An always-on +golden test byte-compares the committed schemas against collector output +(`-update` regenerates); a companion runtime-enumeration test fails when +a runtime is newly registered without a contract decision. + +The schemas are fetchable at any tag via raw.githubusercontent.com +(tag-pinned URLs complement the commit-SHA + integrity-hash mechanism of +[ADR 0038](0038-universal-harness-access.md) for read-only contract +data that does not execute). The `v1` path and the tag identify the +version. Consumers validate against the latest released tag at PR time +and `main` nightly, following the +[ADR 0139](0139-agent-functional-test-suite-lives-in-agents-repo.md) +bridge. `fullsend lint` keeps checking reserved keys in-process; the +schemas serve repos that validate without running the fullsend binary. + +Scope is the sandbox only. The environment of host-side pre-scripts, +post-scripts, and validation scripts (`childScriptEnv`, +`validationScriptEnv`) is a different surface — the runner's own +environment plus `env.runner` — and is out of scope here. + +## Consequences + +- Adding, changing, or reserving a runner env var requires a same-PR + schema regeneration, visible in the diff. +- Content repos gain a fail-closed gate: a failed or unparseable schema + fetch fails the check rather than skipping it. +- The [ADR 0058](0058-agent-registration.md) transitional lockstep between + runner and fleet harnesses becomes verifiable instead of tribal knowledge. +- The schemas are derived contract data — no runtime cost or behavior + change. +- Harness-delivered variables are not runner guarantees: their + provenance is the stock scaffold and may lag the fleet's + `gcp-vertex.env`. +- A future per-version harness JSON Schema + ([ADR 0127](0127-harness-schema-versioning-and-field-types.md) + follow-up) can `$ref` the env definitions here instead of restating them. + +## Forge scope + +The schemas are forge-agnostic: they describe the variables the runner +injects into the sandbox regardless of which forge hosts the repository. +The fetch URL uses raw.githubusercontent.com because fullsend is hosted on +GitHub; a GitLab or Forgejo deployment would use the equivalent raw-file +endpoint. Consumer validation logic (parse, fail closed) is +forge-independent. diff --git a/docs/architecture.md b/docs/architecture.md index 5c37648299..82bd9ae8cc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -88,7 +88,13 @@ each target repository's **`.fullsend/`** directory - What is the right isolation level — process, container, microVM, or separate cluster? (See [agent-infrastructure.md](problems/agent-infrastructure.md) and [security-threat-model.md](problems/security-threat-model.md).) - ~~How granular is network regulation? Allowlist of endpoints, or coarser controls?~~ Decided in [ADR 0065](ADRs/0065-provider-backed-policy-composition.md): network access is granted through provider profiles with per-endpoint allowlists. -- Does the sandbox provide a pre-built environment (tools, language runtimes, repo clones), or does the agent set up its own workspace within the sandbox? +- Does the sandbox provide a pre-built environment (tools, language + runtimes, repo clones), or does the agent set up its own workspace + within the sandbox? (The environment-variable dimension is now a + published, generated contract — + [ADR 0146](ADRs/0146-sandbox-environment-contract-manifest.md), + [contract](normative/sandbox-env/v1/README.md); tools, runtimes, + and workspace setup remain open.) - ~~Is the sandbox the same for all agent roles, or does each role get a differently-scoped sandbox?~~ Decided in [ADR 0020](ADRs/0020-composable-single-responsibility-agents-with-individual-sandboxes.md): each agent gets its own sandbox with policies designed for its responsibility. **Decided:** @@ -133,7 +139,12 @@ repo baseline and overrides) sub-maps replaces `runner_env` and manual `.env` files. The runner generates the sandbox `.env` file from `env.sandbox` at bootstrap. `runner_env` is deprecated ([ADR 0055](ADRs/0055-unified-env-var-delivery.md), amending - [ADR 0024](ADRs/0024-harness-definitions.md)). + [ADR 0024](ADRs/0024-harness-definitions.md)). What the runner itself + injects — which env vars every sandbox receives, which arrive per runtime + via `EnvExports()`, and which keys are reserved from harness override — is + published as generated, tag-pinned JSON Schemas enforced by an always-on + golden test ([ADR 0146](ADRs/0146-sandbox-environment-contract-manifest.md); + [contract](normative/sandbox-env/v1/README.md)). - Runner secrets on GitHub (interim until external secret manager support or #6359 settles the long-term route, then kept as the fallback for workflows without GitHub OIDC or WIF; integrations fullsend owns keep their diff --git a/docs/cli/run.md b/docs/cli/run.md index 570a436a96..c33fe67bcf 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -211,6 +211,11 @@ on every runtime (claude, pi, codex, opencode): | `FULLSEND_ITERATION_DEADLINE` | Unix time (seconds) at which the running iteration is killed | | `TRACEPARENT` | W3C trace context of this iteration's **agent** span (not the run-root span that pre/post scripts receive). Runtimes use it to join fullsend traces. An inbound unsampled parent (`-00`) is preserved so runtime export stays suppressed. Empty when telemetry produced no valid span context. Reserved: an `env.sandbox` entry with this name is dropped. | +The full inventory of what the runner injects into the sandbox — these names +included — and of the keys it reserves from `env.sandbox` override is +published as the generated [sandbox environment +contract](../normative/sandbox-env/v1/README.md). + **Example.** A probe that shows both, and what a kill looks like. The agent prints the variables with its own clock, then sleeps past the budget: diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 2d8c95e421..8e2b6256e1 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -61,6 +61,14 @@ content that must be updated whenever a runtime is added or renamed. if the runtime is user-selectable). - [x] `internal/config/config_test.go` — update any assertion on `ValidRuntimes()` to include the new name. +- [x] `internal/cli/env_manifest_collector_test.go` and + `internal/cli/env_manifest_golden_test.go` — the runtime's `EnvExports()` + names must land in the generated + [sandbox environment contract](../normative/sandbox-env/v1/README.md); + registering a runtime without a contract decision fails + `TestEnvManifestRuntimeEnumeration`, and `TestEnvManifestGolden` pins the + committed schemas (regenerate with + `go test ./internal/cli -run TestEnvManifestGolden -update`). **CLI:** @@ -212,6 +220,7 @@ Harness `security.fail_mode` controls whether critical findings **block** the ru | `runtime.GatewayRouteRuntime` | Optional — for a runtime that carries the inference gateway route (ADR 0137). `PrepareGatewayRun(sandboxName, GatewayRun)` receives the resolved `inference.gateway` block, the committed `models_file` bytes and the gateway base URL before Bootstrap, and `ClearGatewayRun` releases it at the end of the run. `GatewayCredentialSeed() CredentialSeed` names the route's placeholder env key, `sh` seed fragment and credential file, which the runner re-runs after each token refresh, independently of the OpenAI route's seed (`OpenAIRouteSeed`). pi, codex and Claude Code implement it. pi and Claude Code read the placeholder before the agent-writable `.env` and own the route's environment after it. pi, and Claude Code in the `oidc` mode, seed the placeholder into a token file with the shared `gatewayTokenSeed`, and codex with its own seed; both write through `orderedSeedWrite`; Claude Code in the `api-key` mode writes no token file: it captures the placeholder in a readonly shell variable and exports it as `ANTHROPIC_AUTH_TOKEN` after `.env` (as `ANTHROPIC_API_KEY`, with `ANTHROPIC_AUTH_TOKEN` cleared, when the block sets `messages_auth_header: x-api-key`). Claude Code ignores the block's model list, and its `GatewayRun` registration also feeds its `--settings` document: the route pins and the helper, merged with the hooks and passed inline on gateway runs, never as the uploaded `hooks.json` path. The runner refuses a `gateway/` model on a runtime that does not implement it | | `runtime.ProviderResolver` | Optional — multi-provider runtimes return the OTEL GenAI serving-endpoint identity for the model the run will call (`ProviderFor`). The runner writes it as both `gen_ai.system` and `gen_ai.provider.name`. Single-vendor runtimes omit this and `GenAISystemFor` falls back to `System()` | +| `runtime.LaunchEnvExporter` | Optional — a runtime whose launch command exports environment variables beyond `EnvExports()` lists those bare names via `LaunchEnvExports()` (flat list, including provider-conditional names). The sandbox env contract collector unions them into that runtime's `runtime_` set (`docs/normative/sandbox-env/v1/`), and `TestLaunchEnvExportsMatchLaunchCommands` fails unless the list equals what the runtime's built launch commands export beyond `EnvExports()` — add a variant to `launchCommandVariants` for any new launch branch. claude, codex, opencode, and pi implement it; runtimes whose launch commands export nothing new omit it | **Per-iteration cleanup contract.** When a validation retry reuses the sandbox, the runner calls `ClearIterationArtifacts` before the next iteration. Every runtime runs the shared `clearStrayProcesses` sweep first (it terminates the processes the previous iteration left running as the sandbox user, sparing the exec channel and the `sandbox.KeepAliveCommand` main process), then deletes the iteration's output, sessions and debug log. A failed sweep is reported as a warning and never fails the iteration. The runner holds its sandbox lock (`withSandboxLock` in `internal/cli/run.go`) across the call so the credential refreshers' uploads are never killed mid-write. The same sweep runs as `TerminateStrayProcesses` right after an iteration ends at its budget: OpenShell's exec timeout drops the relay but leaves the agent's processes running, and a killed iteration is not followed by another `ClearIterationArtifacts` (see [`fullsend run` § Budget and deadline](../cli/run.md#budget-and-deadline)). @@ -404,6 +413,12 @@ Two traps when reproducing by hand: | `FULLSEND_CANARY_TOKEN` | both canary hooks | no-ops when empty; supply it via harness `env.sandbox`/`host_files` | | `FULLSEND_TRACE_ID` | all scripts | correlates findings with the run | +The runner-written rows in this table are entries in the generated +[sandbox environment contract](../normative/sandbox-env/v1/README.md) — the +machine-checkable schemas listing every variable the runner injects into +the sandbox, per gate and per runtime, and the keys it reserves from +harness override. The schemas are the source of truth; this table is prose. + ### Suppression reachability Under Claude Code a non-zero-exit command never reaches `PostToolUse` at all, so the suppressors only ever see zero-exit output; a tool that exits 0 with nothing to say is the case that used to be summarized as "passed". Adapters whose post-tool event also fires for failures (pi's `tool_result`) do deliver failed calls to the same chain, which is why the positive-evidence rule matters on both. diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index 00846db830..171d3b6060 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -663,6 +663,12 @@ Vendoring commit messages use title + body (upload and stale delete). `admin ins └─────────────────────────────────────────────────────────────────┘ ``` +The `bootstrapEnv()` writes and the `iteration.env` names in this diagram are +the runner's exports. The full, machine-checkable inventory — what every +sandbox receives, per gate and per runtime, and what arrives only through +harness configuration — is the generated [sandbox environment +contract](../../normative/sandbox-env/v1/README.md). + ### Sandbox Constants ```go diff --git a/docs/guides/user/bring-your-own-agent.md b/docs/guides/user/bring-your-own-agent.md index c69c1ac7f9..8f2dca35f4 100644 --- a/docs/guides/user/bring-your-own-agent.md +++ b/docs/guides/user/bring-your-own-agent.md @@ -515,7 +515,7 @@ Key patterns to note: - **`host_files`** copy credentials from the trusted runner into the sandbox. `expand: true` resolves `${VAR}` references before copying. - **`validation_loop.schema`** references the JSON schema file directly — the validation script checks agent output against it. - **`overlays`** uses CEL `when` expressions to conditionally apply scripts, skills, providers, openshell, host_files, and env vars. Resolution merges all matching entries in order: every entry whose `when` evaluates to true is applied, with later matches taking precedence over earlier ones. The CEL environment exposes `event` (the triggering event), `runtime.forge` (the effective forge platform), and `config` (per-repo config from config.yaml). When running without an event context (e.g., `fullsend run` or `fullsend lock`), `event` is an empty map — use `has(event.source)` to guard event field access: `has(event.source) && event.source.system == "jira"` instead of just `event.source.system == "jira"` to avoid "no such key" errors. -- **`common/env/gcp-vertex.env`** is referenced by relative path because both files live in the same repo. If your agent lives in a different repo, reference it by URL (see [Harness Field Reference — Referencing resources](../../reference/harness-reference.md#referencing-resources-local-vs-remote)) or copy it locally. +- **`common/env/gcp-vertex.env`** is referenced by relative path because both files live in the same repo. If your agent lives in a different repo, reference it by URL (see [Harness Field Reference — Referencing resources](../../reference/harness-reference.md#referencing-resources-local-vs-remote)) or copy it locally. The variables it delivers reach the sandbox through harness configuration rather than runner guarantee — they are catalogued as `harness_delivered` in the [sandbox environment contract](../../normative/sandbox-env/v1/README.md). For the complete list of harness fields, see the [Harness Field Reference](../../reference/harness-reference.md). diff --git a/docs/guides/user/customizing-agents.md b/docs/guides/user/customizing-agents.md index 7b814bb004..dae989a2bf 100644 --- a/docs/guides/user/customizing-agents.md +++ b/docs/guides/user/customizing-agents.md @@ -474,7 +474,9 @@ shell-behavior variables like `HTTPS_PROXY`, `SSL_CERT_FILE`, `GIT_SSH_COMMAND` and `NODE_OPTIONS`, instead of exporting them into the sandbox. Matching is case-insensitive, and `fullsend run` warns about every key it drops. The gate covers `env.sandbox` only; it is not a reason to move -those settings into `.env.d` files. +those settings into `.env.d` files. The full reserved set is published in the +generated [sandbox environment +contract](../../normative/sandbox-env/v1/README.md). For the full list, how to check a harness with `fullsend lint` or `fullsend lock`, and where proxy and certificate settings go instead, see diff --git a/docs/guides/user/running-agents-locally.md b/docs/guides/user/running-agents-locally.md index 97765a5548..69c8b27b61 100644 --- a/docs/guides/user/running-agents-locally.md +++ b/docs/guides/user/running-agents-locally.md @@ -160,7 +160,9 @@ with the credential kept out of the sandbox by an OpenShell provider. In CI the identity ([OpenAI Workload Identity](../infrastructure/openai-workload-identity.md)); on your machine there is no such identity, so use an API key from the same OpenAI project. Put it in an environment file, like the GCP settings above — never in the harness YAML and never under -`env.sandbox` (the runner refuses to export it into the sandbox): +`env.sandbox` (the runner refuses to export it into the sandbox; `OPENAI_API_KEY` is in the +reserved set published by the [sandbox environment +contract](../../normative/sandbox-env/v1/README.md)): ```bash # fullsend-openai.env diff --git a/docs/normative/sandbox-env/v1/README.md b/docs/normative/sandbox-env/v1/README.md new file mode 100644 index 0000000000..8fdc070924 --- /dev/null +++ b/docs/normative/sandbox-env/v1/README.md @@ -0,0 +1,196 @@ +# Sandbox environment variable contract v1 + +Which environment variables the fullsend runner injects into the agent +sandbox, under what conditions, per which runtime, which arrive only +through stock harness configuration, and which the runner reserves from +harness override. The contract is published as generated JSON Schemas +(Draft 2020-12), so a consumer — the agents repo, a custom-agent repo, any +CI job — validates with stock tooling against a released runner instead of +a hand-maintained mirror +([ADR 0146](../../../ADRs/0146-sandbox-environment-contract-manifest.md)). + +**Scope: the sandbox only.** Host-side pre-scripts, post-scripts, and +validation scripts run on the runner, not in the sandbox; their +environment is the runner's own plus `env.runner`, and this contract does +not describe it. + +## Schemas + +| File | Validates | Use it to | +|------|-----------|-----------| +| [`harness-env.schema.json`](harness-env.schema.json) | A harness YAML (converted to JSON) | Reject `env.sandbox` keys the runner reserves, in any letter case — at the top level, under `forge..env`, and under `overlays[].env` | +| [`env-references.schema.json`](env-references.schema.json) | `{"runtime": ..., "variables": [...]}` | Check that code running under a runtime reads only variables reachable there; its `$defs` are the full inventory | + +Each schema is self-contained: every definition it uses is in its own +`$defs`, so validating needs one fetched file and no cross-file `$ref` +resolution. + +### Validating a harness + +```sh +check-jsonschema --schemafile "$BASE/harness-env.schema.json" harness/*.yaml +``` + +A reserved key fails with the offending path: + +```text +$.env.sandbox: 'TRACEPARENT' should not be valid under {'$ref': '#/$defs/reserved_any_case'} +``` + +The runner upper-cases a key before checking it, so `traceparent` and +`Https_Proxy` are refused too; `#/$defs/reserved_any_case` matches the +reserved names in any letter case, while `#/$defs/reserved` keeps the +canonical uppercase inventory. The schema constrains only the env blocks; +other harness fields pass through. `fullsend lint` performs the same reserved-key check in-process +for repos that run the fullsend binary. + +### Validating env references + +List the variables a piece of sandbox code reads — a skill script, a +sandbox hook — minus the keys the harness's own `env.sandbox` declares +(those are reachable by construction), and name the runtime it runs +under: + +```json +{"runtime": "pi", "variables": ["FULLSEND_OUTPUT_DIR", "FULLSEND_TARGET_REPO_DIR"]} +``` + +`runtime` is one of the production runtimes, or `portable` for code that +must work under every runtime — a skill shared across agents should use +`portable`. A skill that reads `CLAUDE_CONFIG_DIR` validates under +`claude` and fails under `pi` or `portable`, which is the +[fullsend-ai/agents#1672](https://github.com/fullsend-ai/agents/issues/1672) +failure caught at PR time. + +## Inventory (`env-references.schema.json` `$defs`) + +| Definition | Contents | +|------------|----------| +| `always` | Exported by the runner into every sandbox it builds. | +| `conditional` | Exported only when a gate holds. Each entry is `{"const": NAME, "description": GATE}`, the gate transcribed from the emitter's guard. | +| `runtime_` | Exported only under that runtime: its `EnvExports()` plus the environment its launch command sets, including names a launch sets only on some paths (an inference gateway, a provider). | +| `harness_delivered` | Delivered by stock harness configuration, not the runner. Each entry's description names the configuration. | +| `reserved` | Refused in harness `env.sandbox`; the runner drops them instead of exporting them. | +| `deprecated` | Scheduled for removal; still reachable through their export category until then. | +| `runtime` | The accepted `runtime` values: `portable` plus each production runtime. | + +The categories form a guarantee ladder; read them as answers to "what may +I rely on?", not as a flat list. + +**`always` and `conditional` — runner-guaranteed, modulo gates.** Within +their gates these are reachable under any runtime, which is why +`portable` admits them. The security-hook variables are the exception: +only the claude, codex, and pi bootstraps append hook env, so +`TIRITH_FAIL_ON`, `TIRITH_REQUIRED`, and `FULLSEND_EGRESS_ALLOWLIST` never +reach an opencode sandbox. Their gate descriptions say so, and the +per-runtime rules enforce it: those names validate under claude, codex, +and pi, but not under opencode or `portable`. + +**`runtime_` — guaranteed only when that runtime runs.** Across +runtimes they are a portability gap: nothing promises `CLAUDE_CONFIG_DIR` +under codex or pi. A name a shared category already covers (`PATH`, or +hook env a launch command re-exports) stays in the shared category. + +**`harness_delivered` — configuration, not guarantee.** +`GOOGLE_APPLICATION_CREDENTIALS`, `CLAUDE_CODE_USE_VERTEX`, +`ANTHROPIC_VERTEX_PROJECT_ID`, and `CLOUD_ML_REGION` reach the sandbox +because the `fullsend agent new` Vertex scaffold delivers them through +`env.sandbox` plus a host file; fleet harnesses deliver these plus +`GOOGLE_CLOUD_PROJECT` and `ANTHROPIC_DEFAULT_SONNET_MODEL` through +`env/gcp-vertex.env` in fullsend-ai/agents. A hand-authored harness that +omits that configuration will not see them. + +**`reserved` — refused from harness override.** The runner keeps harness +configuration from shadowing runner infrastructure, injecting OIDC and +provider credentials, or overriding security-critical process variables +(`HTTPS_PROXY`, `LD_PRELOAD`, `NODE_OPTIONS`, …). A name may be both +exported and reserved — `PATH` is set by the runner *and* refused from +the harness. Exports answer "does the runner set it?"; `reserved` +answers "may the harness set it?". + +**`deprecated` — scheduled for removal.** A deprecated name stays in its +export category for at least one minor release after it is first listed +here, then moves out of both. Consumers should warn on a match against +`#/$defs/deprecated` and migrate. The definition matches nothing while no +deprecations are active. + +## Fetching + +The schemas are committed alongside this README, so every tag serves them +at the sibling path over HTTPS — no authentication, no repository code +execution: + +```text +BASE=https://raw.githubusercontent.com/fullsend-ai/fullsend/refs/tags//docs/normative/sandbox-env/v1 +``` + +**The tag is the version.** The schemas carry no fullsend version: a +committed file cannot know its future release, and stamping one at release +time would break the golden invariant below. The `$id` +(`https://fullsend.ai/normative/sandbox-env/v1/…`) names the schema, as +for the other normative schemas; it is not a fetch location. + +Validation cadence: + +- **At PR time, validate against the latest released tag** — what + production runs, so the contract a change must satisfy. +- **Nightly, validate against `main`** (`refs/heads/main` in the URL). + Released tags lag `main`; the nightly check catches drift within a day + ([ADR 0139](../../../ADRs/0139-agent-functional-test-suite-lives-in-agents-repo.md)). + +Tags released before the contract landed return `404` for these paths. + +## Treating the schemas as data + +The schemas arrive over the network. Treat them as untrusted input: + +- **Validate with a JSON Schema validator; never evaluate.** Do not `eval` + fetched content or interpolate it into a shell command or template. +- **Fail closed.** A failed fetch, a non-2xx response, or a body that does + not parse or is not a valid Draft 2020-12 schema MUST fail the consumer + gate. An unverifiable contract is a failed check, not a skipped one. + +The schemas carry names and gate descriptions only — never values — so +they are safe to fetch and inspect. + +## Regeneration + +The schemas are generated, never hand-authored. The collector in +`internal/cli/env_manifest_collector_test.go` runs every code path that +injects environment variables into the sandbox — the bootstrap `.env` +emission, the per-iteration env, trace-ID injection, the security-hook +env, every production runtime's `EnvExports()` and launch-command +exports, the `fullsend agent new` Vertex scaffold, and the effective +reserved-key set after the init-time merges. It replays the commands that +write sandbox env files in a scratch workspace and reads the resulting +files with an export-aware parser (`envmanifest.ExportedNames`), so a +quoted value or a dropped `export` keyword changes the result. +`TestLaunchEnvExportsMatchLaunchCommands` in `internal/runtime` pins each +runtime's declared launch exports to its built launch commands across +hooks, gateway, and provider variants. + +Any change to those emitters changes the schemas. Regenerate: + +```sh +go test ./internal/cli -run TestEnvManifestGolden -update +``` + +The always-on `TestEnvManifestGolden` byte-compares each committed schema +with collector output, and `TestEnvManifestRuntimeEnumeration` fails when +a runtime is registered without a contract decision. Output is +deterministic — fixed key order, sorted names, trailing newline. + +## Versioning + +Breaking changes to the schemas' shape require +`docs/normative/sandbox-env/v2/`. + +| Change | Version | Consumer impact | +|--------|---------|-----------------| +| Rename or remove a `$defs` entry, change the `env-references` instance shape, redefine a category | v2 | Consumers must migrate | +| Add a variable or runtime to a category, refine a gate or provenance description, add a `deprecated` entry | v1 | None | +| Add a name to `reserved` | v1 | A harness setting it starts failing — the runner already drops it, so the schema reports an existing no-op | +| Remove a name from an export category | v1, after a `deprecated` window | Code reading it starts failing `env-references` validation | + +Variable sets change with the code — that is the contract doing its job. +Consumers pin a tag and validate; a new failure is the drift signal. diff --git a/docs/normative/sandbox-env/v1/env-references.schema.json b/docs/normative/sandbox-env/v1/env-references.schema.json new file mode 100644 index 0000000000..8a3f5f8f0e --- /dev/null +++ b/docs/normative/sandbox-env/v1/env-references.schema.json @@ -0,0 +1,451 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://fullsend.ai/normative/sandbox-env/v1/env-references.schema.json", + "title": "Sandbox env references", + "description": "Validates that code running in a fullsend sandbox — a skill script, an agent prompt's tool calls, a sandbox hook — reads only environment variables the contract makes reachable under its runtime. List the variables the code reads, minus those the harness's own env.sandbox declares. The $defs are the full contract inventory. Generated from the runner's code (ADR 0146); see README.md.", + "type": "object", + "additionalProperties": false, + "required": [ + "runtime", + "variables" + ], + "properties": { + "runtime": { + "$ref": "#/$defs/runtime" + }, + "variables": { + "type": "array", + "uniqueItems": true, + "items": { + "$ref": "#/$defs/env_name" + } + } + }, + "allOf": [ + { + "if": { + "properties": { + "runtime": { + "const": "portable" + } + }, + "required": [ + "runtime" + ] + }, + "then": { + "properties": { + "variables": { + "items": { + "anyOf": [ + { + "$ref": "#/$defs/always" + }, + { + "allOf": [ + { + "$ref": "#/$defs/conditional" + }, + { + "not": { + "enum": [ + "FULLSEND_EGRESS_ALLOWLIST", + "TIRITH_FAIL_ON", + "TIRITH_REQUIRED" + ] + } + } + ] + }, + { + "$ref": "#/$defs/harness_delivered" + } + ] + } + } + } + } + }, + { + "if": { + "properties": { + "runtime": { + "const": "claude" + } + }, + "required": [ + "runtime" + ] + }, + "then": { + "properties": { + "variables": { + "items": { + "anyOf": [ + { + "$ref": "#/$defs/always" + }, + { + "$ref": "#/$defs/conditional" + }, + { + "$ref": "#/$defs/harness_delivered" + }, + { + "$ref": "#/$defs/runtime_claude" + } + ] + } + } + } + } + }, + { + "if": { + "properties": { + "runtime": { + "const": "codex" + } + }, + "required": [ + "runtime" + ] + }, + "then": { + "properties": { + "variables": { + "items": { + "anyOf": [ + { + "$ref": "#/$defs/always" + }, + { + "$ref": "#/$defs/conditional" + }, + { + "$ref": "#/$defs/harness_delivered" + }, + { + "$ref": "#/$defs/runtime_codex" + } + ] + } + } + } + } + }, + { + "if": { + "properties": { + "runtime": { + "const": "opencode" + } + }, + "required": [ + "runtime" + ] + }, + "then": { + "properties": { + "variables": { + "items": { + "anyOf": [ + { + "$ref": "#/$defs/always" + }, + { + "allOf": [ + { + "$ref": "#/$defs/conditional" + }, + { + "not": { + "enum": [ + "FULLSEND_EGRESS_ALLOWLIST", + "TIRITH_FAIL_ON", + "TIRITH_REQUIRED" + ] + } + } + ] + }, + { + "$ref": "#/$defs/harness_delivered" + }, + { + "$ref": "#/$defs/runtime_opencode" + } + ] + } + } + } + } + }, + { + "if": { + "properties": { + "runtime": { + "const": "pi" + } + }, + "required": [ + "runtime" + ] + }, + "then": { + "properties": { + "variables": { + "items": { + "anyOf": [ + { + "$ref": "#/$defs/always" + }, + { + "$ref": "#/$defs/conditional" + }, + { + "$ref": "#/$defs/harness_delivered" + }, + { + "$ref": "#/$defs/runtime_pi" + } + ] + } + } + } + } + } + ], + "$defs": { + "env_name": { + "type": "string", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + }, + "runtime": { + "description": "The runtime the referencing code runs under, or \"portable\" for code that must work under every runtime.", + "enum": [ + "portable", + "claude", + "codex", + "opencode", + "pi" + ] + }, + "always": { + "description": "Exported by the runner into every sandbox it builds.", + "enum": [ + "FULLSEND_OUTPUT_DIR", + "FULLSEND_PERSONAS_FILE", + "FULLSEND_ROLE", + "FULLSEND_TARGET_REPO_DIR", + "PATH" + ] + }, + "conditional": { + "description": "Exported by the runner only when the gate in each entry's description holds. Some entries are emitted only by certain runtimes' bootstraps; the per-runtime reachability rules exclude them elsewhere and under portable.", + "oneOf": [ + { + "const": "FULLSEND_EGRESS_ALLOWLIST", + "description": "an SSRF egress allowlist is configured, including the auto-merged forge egress entry; only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode" + }, + { + "const": "FULLSEND_FETCH_TOKEN", + "description": "the runtime fetch service is enabled (ADR 0038)" + }, + { + "const": "FULLSEND_FETCH_URL", + "description": "the runtime fetch service is enabled (ADR 0038)" + }, + { + "const": "FULLSEND_ITERATION_DEADLINE", + "description": "writeIterationEnv succeeds; the run warns and continues when it fails" + }, + { + "const": "FULLSEND_OUTPUT_FILE", + "description": "the legacy runner_env FULLSEND_OUTPUT_FILE is set" + }, + { + "const": "FULLSEND_OUTPUT_SCHEMA", + "description": "an output schema is configured (validation_loop.schema, or the legacy FULLSEND_OUTPUT_SCHEMA runner env) and its file uploads into the sandbox" + }, + { + "const": "FULLSEND_SLUG", + "description": "the harness sets a slug" + }, + { + "const": "FULLSEND_TIMEOUT_MINUTES", + "description": "writeIterationEnv succeeds; the run warns and continues when it fails" + }, + { + "const": "FULLSEND_TRACE_ID", + "description": "trace-ID injection succeeds; the run warns and continues when it fails" + }, + { + "const": "TIRITH_FAIL_ON", + "description": "security.sandbox_hooks.tirith.fail_on is set; only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode" + }, + { + "const": "TIRITH_REQUIRED", + "description": "Tirith scanning is required (security.sandbox_hooks.tirith.enabled, default true); only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode" + }, + { + "const": "TRACEPARENT", + "description": "writeIterationEnv succeeds; the run warns and continues when it fails" + } + ] + }, + "runtime_claude": { + "description": "Exported only when dispatch runs under claude: its EnvExports plus the environment its launch command sets. Not reachable under other runtimes.", + "enum": [ + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_BASE_URL", + "CLAUDE_CODE_API_KEY_HELPER_TTL_MS", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", + "CLAUDE_CONFIG_DIR" + ] + }, + "runtime_codex": { + "description": "Exported only when dispatch runs under codex: its EnvExports plus the environment its launch command sets. Not reachable under other runtimes.", + "enum": [ + "CODEX_HOME", + "FULLSEND_CODEX_HOOK_DIGESTS", + "FULLSEND_CODEX_SPAWN_DIGESTS", + "FULLSEND_RUNTIME", + "FULLSEND_TRUSTED_PATH", + "RUST_LOG" + ] + }, + "runtime_opencode": { + "description": "Exported only when dispatch runs under opencode: its EnvExports plus the environment its launch command sets. Not reachable under other runtimes.", + "enum": [ + "FULLSEND_RUNTIME", + "GOOGLE_APPLICATION_CREDENTIALS", + "GOOGLE_CLOUD_LOCATION", + "GOOGLE_CLOUD_PROJECT", + "HOME", + "OPENCODE_CONFIG_CONTENT", + "OPENCODE_CONFIG_DIR", + "OPENCODE_DISABLE_EXTERNAL_SKILLS", + "OPENCODE_DISABLE_PROJECT_CONFIG" + ] + }, + "runtime_pi": { + "description": "Exported only when dispatch runs under pi: its EnvExports plus the environment its launch command sets. Not reachable under other runtimes.", + "enum": [ + "FULLSEND_PI_CHILD_BIN", + "FULLSEND_PI_CHILD_NODE", + "FULLSEND_PI_HOOK_PATH", + "FULLSEND_PI_HOOK_PYTHON", + "FULLSEND_PI_MANIFEST", + "FULLSEND_PI_MANIFEST_SHA256", + "FULLSEND_RUNTIME", + "GOOGLE_CLOUD_LOCATION", + "GOOGLE_CLOUD_PROJECT", + "INFERENCE_GATEWAY_BASE_URL", + "INFERENCE_GATEWAY_CONFIG_FILE", + "INFERENCE_GATEWAY_TOKEN_FILE", + "JITI_FS_CACHE", + "PI_CODING_AGENT_DIR", + "PI_CODING_AGENT_SESSION_DIR", + "PI_OFFLINE", + "PI_SKIP_VERSION_CHECK", + "PI_TELEMETRY", + "XAI_VERTEX_PROJECT_ID" + ] + }, + "harness_delivered": { + "description": "Delivered by stock harness configuration, not by the runner: reachable only when the harness delivers it.", + "oneOf": [ + { + "const": "ANTHROPIC_VERTEX_PROJECT_ID", + "description": "fullsend agent new Vertex scaffold (internal/agentnew); the fleet delivers these plus GOOGLE_CLOUD_PROJECT and ANTHROPIC_DEFAULT_SONNET_MODEL through env/gcp-vertex.env in fullsend-ai/agents" + }, + { + "const": "CLAUDE_CODE_USE_VERTEX", + "description": "fullsend agent new Vertex scaffold (internal/agentnew); the fleet delivers these plus GOOGLE_CLOUD_PROJECT and ANTHROPIC_DEFAULT_SONNET_MODEL through env/gcp-vertex.env in fullsend-ai/agents" + }, + { + "const": "CLOUD_ML_REGION", + "description": "fullsend agent new Vertex scaffold (internal/agentnew); the fleet delivers these plus GOOGLE_CLOUD_PROJECT and ANTHROPIC_DEFAULT_SONNET_MODEL through env/gcp-vertex.env in fullsend-ai/agents" + }, + { + "const": "GOOGLE_APPLICATION_CREDENTIALS", + "description": "fullsend agent new Vertex scaffold (internal/agentnew); the fleet delivers these plus GOOGLE_CLOUD_PROJECT and ANTHROPIC_DEFAULT_SONNET_MODEL through env/gcp-vertex.env in fullsend-ai/agents" + } + ] + }, + "reserved": { + "description": "Reserved by the runner: a harness cannot set these through env.sandbox.", + "enum": [ + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ALL_PROXY", + "BASH_ENV", + "CDPATH", + "CURL_CA_BUNDLE", + "DYLD_INSERT_LIBRARIES", + "ENV", + "FULLSEND_FETCH_TOKEN", + "FULLSEND_FETCH_URL", + "FULLSEND_GCP_OIDC_AUTH_FILE", + "FULLSEND_GCP_OIDC_URL", + "FULLSEND_GCP_PROJECT_ID", + "FULLSEND_GCP_WIF_PROVIDER", + "FULLSEND_GITHUB_RUNNER_SECRETS", + "FULLSEND_GITHUB_RUNNER_SECRETS_FILE", + "FULLSEND_GITLAB_TRIGGER_ACCOUNT_TOKEN", + "FULLSEND_INFERENCE_GATEWAY_API_KEY", + "FULLSEND_ITERATION_DEADLINE", + "FULLSEND_OPENAI_API_KEY", + "FULLSEND_OPENAI_AUDIENCE", + "FULLSEND_OPENAI_IDENTITY_PROVIDER_ID", + "FULLSEND_OPENAI_SERVICE_ACCOUNT_ID", + "FULLSEND_OUTPUT_DIR", + "FULLSEND_OUTPUT_FILE", + "FULLSEND_OUTPUT_SCHEMA", + "FULLSEND_PERSONAS_FILE", + "FULLSEND_ROLE", + "FULLSEND_RUNNER_PATH", + "FULLSEND_SLUG", + "FULLSEND_TARGET_REPO_DIR", + "FULLSEND_TIMEOUT_MINUTES", + "FULLSEND_TRIGGER_TOKEN", + "FULLSEND_WEBHOOK_SECRET", + "GH_WORKFLOW_TOKEN", + "GIT_ASKPASS", + "GIT_CONFIG_GLOBAL", + "GIT_EXEC_PATH", + "GIT_SSH_COMMAND", + "GIT_TEMPLATE_DIR", + "HOME", + "HOSTALIASES", + "HTTPS_PROXY", + "HTTP_PROXY", + "IFS", + "JAVA_TOOL_OPTIONS", + "LD_AUDIT", + "LD_LIBRARY_PATH", + "LD_PRELOAD", + "NODE_EXTRA_CA_CERTS", + "NODE_OPTIONS", + "NO_PROXY", + "OPENAI_API_KEY", + "PATH", + "PERL5OPT", + "PROMPT_COMMAND", + "PYTHONPATH", + "PYTHONSTARTUP", + "RUBYOPT", + "SHELL", + "SSL_CERT_DIR", + "SSL_CERT_FILE", + "TRACEPARENT" + ] + }, + "deprecated": { + "description": "Deprecated and scheduled for removal in a future contract version; still reachable through its export category until then. Consumers should warn on a match and migrate.", + "not": {} + } + } +} diff --git a/docs/normative/sandbox-env/v1/harness-env.schema.json b/docs/normative/sandbox-env/v1/harness-env.schema.json new file mode 100644 index 0000000000..9831c65f7b --- /dev/null +++ b/docs/normative/sandbox-env/v1/harness-env.schema.json @@ -0,0 +1,136 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://fullsend.ai/normative/sandbox-env/v1/harness-env.schema.json", + "title": "Harness sandbox env contract", + "description": "Validates the env blocks of a fullsend harness YAML (top-level env, forge..env, and overlays[].env) against the sandbox environment-variable contract: an env.sandbox key must be a shell variable name and must not be a name the runner reserves, in any letter case, because the runner matches reserved keys case-insensitively and drops them instead of exporting them. Other harness fields are not constrained here. Generated from the runner's code (ADR 0146); see README.md.", + "type": "object", + "properties": { + "env": { + "$ref": "#/$defs/env_block" + }, + "forge": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "env": { + "$ref": "#/$defs/env_block" + } + } + } + }, + "overlays": { + "type": "array", + "items": { + "type": "object", + "properties": { + "env": { + "$ref": "#/$defs/env_block" + } + } + } + } + }, + "$defs": { + "env_block": { + "type": "object", + "properties": { + "sandbox": { + "$ref": "#/$defs/sandbox_env" + } + } + }, + "sandbox_env": { + "description": "Variables a harness delivers into the sandbox. The runner owns the reserved names and refuses them here in any letter case.", + "type": "object", + "propertyNames": { + "allOf": [ + { + "$ref": "#/$defs/env_name" + }, + { + "not": { + "$ref": "#/$defs/reserved_any_case" + } + } + ] + } + }, + "env_name": { + "type": "string", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + }, + "reserved": { + "description": "Reserved by the runner: a harness cannot set these through env.sandbox.", + "enum": [ + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ALL_PROXY", + "BASH_ENV", + "CDPATH", + "CURL_CA_BUNDLE", + "DYLD_INSERT_LIBRARIES", + "ENV", + "FULLSEND_FETCH_TOKEN", + "FULLSEND_FETCH_URL", + "FULLSEND_GCP_OIDC_AUTH_FILE", + "FULLSEND_GCP_OIDC_URL", + "FULLSEND_GCP_PROJECT_ID", + "FULLSEND_GCP_WIF_PROVIDER", + "FULLSEND_GITHUB_RUNNER_SECRETS", + "FULLSEND_GITHUB_RUNNER_SECRETS_FILE", + "FULLSEND_GITLAB_TRIGGER_ACCOUNT_TOKEN", + "FULLSEND_INFERENCE_GATEWAY_API_KEY", + "FULLSEND_ITERATION_DEADLINE", + "FULLSEND_OPENAI_API_KEY", + "FULLSEND_OPENAI_AUDIENCE", + "FULLSEND_OPENAI_IDENTITY_PROVIDER_ID", + "FULLSEND_OPENAI_SERVICE_ACCOUNT_ID", + "FULLSEND_OUTPUT_DIR", + "FULLSEND_OUTPUT_FILE", + "FULLSEND_OUTPUT_SCHEMA", + "FULLSEND_PERSONAS_FILE", + "FULLSEND_ROLE", + "FULLSEND_RUNNER_PATH", + "FULLSEND_SLUG", + "FULLSEND_TARGET_REPO_DIR", + "FULLSEND_TIMEOUT_MINUTES", + "FULLSEND_TRIGGER_TOKEN", + "FULLSEND_WEBHOOK_SECRET", + "GH_WORKFLOW_TOKEN", + "GIT_ASKPASS", + "GIT_CONFIG_GLOBAL", + "GIT_EXEC_PATH", + "GIT_SSH_COMMAND", + "GIT_TEMPLATE_DIR", + "HOME", + "HOSTALIASES", + "HTTPS_PROXY", + "HTTP_PROXY", + "IFS", + "JAVA_TOOL_OPTIONS", + "LD_AUDIT", + "LD_LIBRARY_PATH", + "LD_PRELOAD", + "NODE_EXTRA_CA_CERTS", + "NODE_OPTIONS", + "NO_PROXY", + "OPENAI_API_KEY", + "PATH", + "PERL5OPT", + "PROMPT_COMMAND", + "PYTHONPATH", + "PYTHONSTARTUP", + "RUBYOPT", + "SHELL", + "SSL_CERT_DIR", + "SSL_CERT_FILE", + "TRACEPARENT" + ] + }, + "reserved_any_case": { + "description": "The reserved names in any letter case: the runner upper-cases an env.sandbox key before checking it against the reserved set.", + "pattern": "^(?:[Aa][Cc][Tt][Ii][Oo][Nn][Ss]_[Ii][Dd]_[Tt][Oo][Kk][Ee][Nn]_[Rr][Ee][Qq][Uu][Ee][Ss][Tt]_[Tt][Oo][Kk][Ee][Nn]|[Aa][Cc][Tt][Ii][Oo][Nn][Ss]_[Ii][Dd]_[Tt][Oo][Kk][Ee][Nn]_[Rr][Ee][Qq][Uu][Ee][Ss][Tt]_[Uu][Rr][Ll]|[Aa][Ll][Ll]_[Pp][Rr][Oo][Xx][Yy]|[Bb][Aa][Ss][Hh]_[Ee][Nn][Vv]|[Cc][Dd][Pp][Aa][Tt][Hh]|[Cc][Uu][Rr][Ll]_[Cc][Aa]_[Bb][Uu][Nn][Dd][Ll][Ee]|[Dd][Yy][Ll][Dd]_[Ii][Nn][Ss][Ee][Rr][Tt]_[Ll][Ii][Bb][Rr][Aa][Rr][Ii][Ee][Ss]|[Ee][Nn][Vv]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Ff][Ee][Tt][Cc][Hh]_[Tt][Oo][Kk][Ee][Nn]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Ff][Ee][Tt][Cc][Hh]_[Uu][Rr][Ll]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Gg][Cc][Pp]_[Oo][Ii][Dd][Cc]_[Aa][Uu][Tt][Hh]_[Ff][Ii][Ll][Ee]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Gg][Cc][Pp]_[Oo][Ii][Dd][Cc]_[Uu][Rr][Ll]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Gg][Cc][Pp]_[Pp][Rr][Oo][Jj][Ee][Cc][Tt]_[Ii][Dd]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Gg][Cc][Pp]_[Ww][Ii][Ff]_[Pp][Rr][Oo][Vv][Ii][Dd][Ee][Rr]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Gg][Ii][Tt][Hh][Uu][Bb]_[Rr][Uu][Nn][Nn][Ee][Rr]_[Ss][Ee][Cc][Rr][Ee][Tt][Ss]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Gg][Ii][Tt][Hh][Uu][Bb]_[Rr][Uu][Nn][Nn][Ee][Rr]_[Ss][Ee][Cc][Rr][Ee][Tt][Ss]_[Ff][Ii][Ll][Ee]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Gg][Ii][Tt][Ll][Aa][Bb]_[Tt][Rr][Ii][Gg][Gg][Ee][Rr]_[Aa][Cc][Cc][Oo][Uu][Nn][Tt]_[Tt][Oo][Kk][Ee][Nn]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Ii][Nn][Ff][Ee][Rr][Ee][Nn][Cc][Ee]_[Gg][Aa][Tt][Ee][Ww][Aa][Yy]_[Aa][Pp][Ii]_[Kk][Ee][Yy]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Ii][Tt][Ee][Rr][Aa][Tt][Ii][Oo][Nn]_[Dd][Ee][Aa][Dd][Ll][Ii][Nn][Ee]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Oo][Pp][Ee][Nn][Aa][Ii]_[Aa][Pp][Ii]_[Kk][Ee][Yy]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Oo][Pp][Ee][Nn][Aa][Ii]_[Aa][Uu][Dd][Ii][Ee][Nn][Cc][Ee]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Oo][Pp][Ee][Nn][Aa][Ii]_[Ii][Dd][Ee][Nn][Tt][Ii][Tt][Yy]_[Pp][Rr][Oo][Vv][Ii][Dd][Ee][Rr]_[Ii][Dd]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Oo][Pp][Ee][Nn][Aa][Ii]_[Ss][Ee][Rr][Vv][Ii][Cc][Ee]_[Aa][Cc][Cc][Oo][Uu][Nn][Tt]_[Ii][Dd]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Oo][Uu][Tt][Pp][Uu][Tt]_[Dd][Ii][Rr]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Oo][Uu][Tt][Pp][Uu][Tt]_[Ff][Ii][Ll][Ee]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Oo][Uu][Tt][Pp][Uu][Tt]_[Ss][Cc][Hh][Ee][Mm][Aa]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Pp][Ee][Rr][Ss][Oo][Nn][Aa][Ss]_[Ff][Ii][Ll][Ee]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Rr][Oo][Ll][Ee]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Rr][Uu][Nn][Nn][Ee][Rr]_[Pp][Aa][Tt][Hh]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Ss][Ll][Uu][Gg]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Tt][Aa][Rr][Gg][Ee][Tt]_[Rr][Ee][Pp][Oo]_[Dd][Ii][Rr]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Tt][Ii][Mm][Ee][Oo][Uu][Tt]_[Mm][Ii][Nn][Uu][Tt][Ee][Ss]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Tt][Rr][Ii][Gg][Gg][Ee][Rr]_[Tt][Oo][Kk][Ee][Nn]|[Ff][Uu][Ll][Ll][Ss][Ee][Nn][Dd]_[Ww][Ee][Bb][Hh][Oo][Oo][Kk]_[Ss][Ee][Cc][Rr][Ee][Tt]|[Gg][Hh]_[Ww][Oo][Rr][Kk][Ff][Ll][Oo][Ww]_[Tt][Oo][Kk][Ee][Nn]|[Gg][Ii][Tt]_[Aa][Ss][Kk][Pp][Aa][Ss][Ss]|[Gg][Ii][Tt]_[Cc][Oo][Nn][Ff][Ii][Gg]_[Gg][Ll][Oo][Bb][Aa][Ll]|[Gg][Ii][Tt]_[Ee][Xx][Ee][Cc]_[Pp][Aa][Tt][Hh]|[Gg][Ii][Tt]_[Ss][Ss][Hh]_[Cc][Oo][Mm][Mm][Aa][Nn][Dd]|[Gg][Ii][Tt]_[Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee]_[Dd][Ii][Rr]|[Hh][Oo][Mm][Ee]|[Hh][Oo][Ss][Tt][Aa][Ll][Ii][Aa][Ss][Ee][Ss]|[Hh][Tt][Tt][Pp][Ss]_[Pp][Rr][Oo][Xx][Yy]|[Hh][Tt][Tt][Pp]_[Pp][Rr][Oo][Xx][Yy]|[Ii][Ff][Ss]|[Jj][Aa][Vv][Aa]_[Tt][Oo][Oo][Ll]_[Oo][Pp][Tt][Ii][Oo][Nn][Ss]|[Ll][Dd]_[Aa][Uu][Dd][Ii][Tt]|[Ll][Dd]_[Ll][Ii][Bb][Rr][Aa][Rr][Yy]_[Pp][Aa][Tt][Hh]|[Ll][Dd]_[Pp][Rr][Ee][Ll][Oo][Aa][Dd]|[Nn][Oo][Dd][Ee]_[Ee][Xx][Tt][Rr][Aa]_[Cc][Aa]_[Cc][Ee][Rr][Tt][Ss]|[Nn][Oo][Dd][Ee]_[Oo][Pp][Tt][Ii][Oo][Nn][Ss]|[Nn][Oo]_[Pp][Rr][Oo][Xx][Yy]|[Oo][Pp][Ee][Nn][Aa][Ii]_[Aa][Pp][Ii]_[Kk][Ee][Yy]|[Pp][Aa][Tt][Hh]|[Pp][Ee][Rr][Ll]5[Oo][Pp][Tt]|[Pp][Rr][Oo][Mm][Pp][Tt]_[Cc][Oo][Mm][Mm][Aa][Nn][Dd]|[Pp][Yy][Tt][Hh][Oo][Nn][Pp][Aa][Tt][Hh]|[Pp][Yy][Tt][Hh][Oo][Nn][Ss][Tt][Aa][Rr][Tt][Uu][Pp]|[Rr][Uu][Bb][Yy][Oo][Pp][Tt]|[Ss][Hh][Ee][Ll][Ll]|[Ss][Ss][Ll]_[Cc][Ee][Rr][Tt]_[Dd][Ii][Rr]|[Ss][Ss][Ll]_[Cc][Ee][Rr][Tt]_[Ff][Ii][Ll][Ee]|[Tt][Rr][Aa][Cc][Ee][Pp][Aa][Rr][Ee][Nn][Tt])$" + } + } +} diff --git a/docs/problems/agent-infrastructure.md b/docs/problems/agent-infrastructure.md index 731bb5a68f..03d4b04fc7 100644 --- a/docs/problems/agent-infrastructure.md +++ b/docs/problems/agent-infrastructure.md @@ -123,7 +123,7 @@ Many fullsend scenarios skew toward **ephemeral, task-scoped** execution (triage ## Open questions - 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.) +- 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 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? diff --git a/docs/problems/security-threat-model.md b/docs/problems/security-threat-model.md index fa7546288a..73316f86d3 100644 --- a/docs/problems/security-threat-model.md +++ b/docs/problems/security-threat-model.md @@ -188,6 +188,13 @@ It's slow and hard to detect. Each individual change looks fine. The degradation Drift becomes detectable when you have a declared baseline to measure against. An organization's architecture documentation — ADRs, per-service architecture docs — provides that baseline. See [architectural-invariants.md](architectural-invariants.md) for a full treatment of how agents can consume and enforce these constraints, both at PR time and through periodic drift detection scans. +The runner's environment surface now has such a baseline: which env +vars the sandbox receives, per runtime and under documented gates, is +published as generated, machine-checkable JSON Schemas rather than +hand-synced descriptions, so content repos can verify env-var +reachability against a released runner +([ADR 0146](../ADRs/0146-sandbox-environment-contract-manifest.md)). + Drift from security-relevant invariants (RBAC model, trusted component model, build provenance chain) is a security concern, not just a quality concern. ### Open questions diff --git a/docs/reference/harness-reference.md b/docs/reference/harness-reference.md index 2750257c26..a18489aa83 100644 --- a/docs/reference/harness-reference.md +++ b/docs/reference/harness-reference.md @@ -300,7 +300,7 @@ runtimes. **`policy`** — Path or pinned URL of the sandbox policy. Required at `fullsend run`; fullsend ships no default. A child that omits `policy:` still passes if it inherits one from `base:`. A local file that unmarshals to no fields (comments only) is rejected with the path named. Commit a copy of the fleet policy from [fullsend-ai/agents](https://github.com/fullsend-ai/agents), or set `policy:` to its URL with a `#sha256=` hash under `allowed_remote_resources`; `fullsend agent new` writes both the file and the field for a new agent. -**`timeout_minutes`** — Wall-clock budget for one agent iteration, default 30. The runner ends the iteration and sweeps the processes the agent left running in the sandbox (best effort) when it is spent, and a killed iteration ends the run with `agent timed out after without completing (timeout: )` unless its output validates anyway. Before every iteration the runner writes the budget as `FULLSEND_TIMEOUT_MINUTES`, the kill time as `FULLSEND_ITERATION_DEADLINE` (Unix seconds), and the current agent span as `TRACEPARENT` into the agent's environment — see [`fullsend run` § Budget and deadline](../cli/run.md#budget-and-deadline). Those names are reserved: an `env.sandbox` entry with any of them is dropped. +**`timeout_minutes`** — Wall-clock budget for one agent iteration, default 30. The runner ends the iteration and sweeps the processes the agent left running in the sandbox (best effort) when it is spent, and a killed iteration ends the run with `agent timed out after without completing (timeout: )` unless its output validates anyway. Before every iteration the runner writes the budget as `FULLSEND_TIMEOUT_MINUTES`, the kill time as `FULLSEND_ITERATION_DEADLINE` (Unix seconds), and the current agent span as `TRACEPARENT` into the agent's environment — see [`fullsend run` § Budget and deadline](../cli/run.md#budget-and-deadline). Those names are reserved: an `env.sandbox` entry with any of them is dropped. The full reserved set, and the inventory of what the runner injects, is the generated [sandbox environment contract](../normative/sandbox-env/v1/README.md). **`security.fail_mode`** — Determines what happens when a pre-run security scan finds issues or fails to complete. `closed` (default): the run aborts on scan failure or critical findings. `open`: the run continues with a warning. Omitting the `security` block is equivalent to `fail_mode: closed`. diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index a8c60eb31d..65d842f396 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -281,6 +281,13 @@ pinned. On gateway runs the cleared variables are also pinned in the inline `--s non-gateway runs that block is read by Claude Code itself, after launch. On every route, the egress profile and the endpoint-bound placeholder are what keep the credential on its host. +What the runner itself injects into the sandbox — for claude, +`CLAUDE_CONFIG_DIR` and `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` on every +run, plus `ANTHROPIC_BASE_URL` and a gateway credential variable when an +inference gateway applies — and the keys it reserves from `env.sandbox` are +published as generated, machine-checkable schemas: the +[sandbox environment contract](../normative/sandbox-env/v1/README.md). + **Sandbox hook settings come from the harness, not `.env`.** With sandbox hooks on, `TIRITH_FAIL_ON`, `TIRITH_REQUIRED`, `FULLSEND_EGRESS_ALLOWLIST`, `FULLSEND_CANARY_TOKEN` and `FULLSEND_TOOL_ALLOWLIST` are taken from the harness diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index 7071615ff3..1275f38f14 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -580,3 +580,4 @@ ran and why. - [OpenAI Workload Identity](../guides/infrastructure/openai-workload-identity.md) — the CI credential path - [codex runtime internals](../contributing/runtime-implementation.md#codex-runtime-internals-6920) — config layers, the hook adapter contract, and what to re-check on a `CODEX_VERSION` bump - [ADR 0099](../ADRs/0099-codex-agent-runtime.md) — why codex uses a custom model provider, a runner-seeded token file and a translating hook adapter +- [Sandbox environment contract](../normative/sandbox-env/v1/README.md) — the generated list of what the runner exports into a codex sandbox (`runtime_codex`) and the keys it reserves diff --git a/docs/runtimes/opencode.md b/docs/runtimes/opencode.md index e6832cc03d..af4cd5fe2d 100644 --- a/docs/runtimes/opencode.md +++ b/docs/runtimes/opencode.md @@ -160,3 +160,4 @@ example above. - [Agent runtimes](../runtimes.md): choosing and selecting a runtime - [Running agents locally](../guides/user/running-agents-locally.md): the local-run setup this page builds on - [Runtime implementation](../contributing/runtime-implementation.md): how the runtime is secured, per feature +- [Sandbox environment contract](../normative/sandbox-env/v1/README.md): the generated list of what the runner exports into an opencode sandbox (`runtime_opencode`) and the keys it reserves diff --git a/docs/runtimes/pi.md b/docs/runtimes/pi.md index bb324c5bd1..72115a97e0 100644 --- a/docs/runtimes/pi.md +++ b/docs/runtimes/pi.md @@ -841,7 +841,9 @@ that project's Model Garden, or the provider resolved a different project than y **`[pi-anthropic-vertex] disabled: set GOOGLE_CLOUD_PROJECT ...`.** The sandbox environment comes from the harness (`host_files`, `env.sandbox`), not from `--env-file`, which only reaches the runner process (ADR 0055). Files read from `.env.d/` need `export` on each line. The fleet harnesses -already wire this; a custom harness must too. +already wire this; a custom harness must too. What the runner itself injects — pi's +runtime-specific exports included, `INFERENCE_GATEWAY_*` on gateway runs — and the keys it reserves from harness override are published +in the generated [sandbox environment contract](../normative/sandbox-env/v1/README.md). **The run used Claude instead of pi.** The runtime falls back to `claude` when neither the config's `runtime:` (repo-wide or on the agent's `agents:` entry) nor `--runtime`/`FULLSEND_RUNTIME` selects diff --git a/internal/cli/env_manifest_collector_test.go b/internal/cli/env_manifest_collector_test.go new file mode 100644 index 0000000000..b52081624a --- /dev/null +++ b/internal/cli/env_manifest_collector_test.go @@ -0,0 +1,847 @@ +package cli + +import ( + "go/ast" + "go/parser" + "go/token" + "maps" + "os" + "os/exec" + "path/filepath" + "reflect" + "regexp" + "slices" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/agentnew" + "github.com/fullsend-ai/fullsend/internal/envmanifest" + "github.com/fullsend-ai/fullsend/internal/harness" + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" + "github.com/fullsend-ai/fullsend/internal/sandbox" + "github.com/fullsend-ai/fullsend/internal/security" +) + +// Fixtures for the sandbox env manifest collector: the probe agent and +// sandbox names, a shell-safe trace ID, a valid W3C traceparent, and the +// provenance recorded for harness-delivered variables. +const ( + envManifestAgentName = "env-manifest-probe" + envManifestSandboxName = "fs-env-manifest" + envManifestTraceID = "01234567-89ab-4cde-8f01-23456789abcd" + envManifestTraceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" + envManifestProvenance = "fullsend agent new Vertex scaffold (internal/agentnew); the fleet delivers these plus GOOGLE_CLOUD_PROJECT and ANTHROPIC_DEFAULT_SONNET_MODEL through env/gcp-vertex.env in fullsend-ai/agents" +) + +// productionSandboxRuntimes lists every runtime the sandbox env contract must +// represent: the registry entries a real agent can dispatch under. +// excludedSandboxRuntimes holds the registry's local test stubs, per the +// design's D5 stub exclusion — exactly dummy and dummy-playback. opencode is +// not a stub for this manifest even though the registry's config validation +// groups it with the stubs and keeps it out of config.ValidRuntimes: it +// resolves in the registry, so it stays in the production set. +// TestEnvManifestRuntimeEnumeration pins the enumeration to the registry. +var ( + productionSandboxRuntimes = []string{"claude", "codex", "opencode", "pi"} + excludedSandboxRuntimes = []string{"dummy", "dummy-playback"} +) + +// sandboxEnvGates transcribes, for each conditionally emitted sandbox env +// var, the emitter's guard that decides whether it is set. The collector +// fails when an emitter derives a conditional key missing here — a new gated +// export cannot enter the manifest undescribed — and when a gate's key no +// longer derives from any emitter, so the descriptions cannot go stale. +var sandboxEnvGates = map[string]string{ + "FULLSEND_SLUG": "the harness sets a slug", + "FULLSEND_OUTPUT_SCHEMA": "an output schema is configured (validation_loop.schema, or the legacy FULLSEND_OUTPUT_SCHEMA runner env) and its file uploads into the sandbox", + "FULLSEND_OUTPUT_FILE": "the legacy runner_env FULLSEND_OUTPUT_FILE is set", + "FULLSEND_FETCH_URL": "the runtime fetch service is enabled (ADR 0038)", + "FULLSEND_FETCH_TOKEN": "the runtime fetch service is enabled (ADR 0038)", + "FULLSEND_TRACE_ID": "trace-ID injection succeeds; the run warns and continues when it fails", + "TIRITH_FAIL_ON": "security.sandbox_hooks.tirith.fail_on is set; only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode", + "TIRITH_REQUIRED": "Tirith scanning is required (security.sandbox_hooks.tirith.enabled, default true); only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode", + "FULLSEND_EGRESS_ALLOWLIST": "an SSRF egress allowlist is configured, including the auto-merged forge egress entry; only the claude, codex, and pi bootstraps append hook env, so it is unreachable under opencode", + "FULLSEND_ITERATION_DEADLINE": "writeIterationEnv succeeds; the run warns and continues when it fails", + "FULLSEND_TIMEOUT_MINUTES": "writeIterationEnv succeeds; the run warns and continues when it fails", + "TRACEPARENT": "writeIterationEnv succeeds; the run warns and continues when it fails", +} + +// envManifestRegistryCaseRe matches a case clause of the Resolve switch at +// switch depth: gofmt keeps a clause's runtime labels on the line that starts +// with "case". +var envManifestRegistryCaseRe = regexp.MustCompile(`(?m)^\tcase\b[^\n]*:`) + +// envManifestRegistryLabelRe extracts the double-quoted labels from one case +// clause of the resolution registry's switch. +var envManifestRegistryLabelRe = regexp.MustCompile(`"([^"\n]*)"`) + +// TestEnvManifestCollector asserts the manifest the collector derives by +// executing the production sandbox-env emitters: the unconditional bootstrap +// and iteration-env exports, the gated exports with their gates, each +// production runtime's export set, the scaffold-delivered Vertex variables, +// and the reserved set the runner, OIDC and provider maps merge into. +func TestEnvManifestCollector(t *testing.T) { + m := collectSandboxEnvManifest(t) + + t.Run("always", func(t *testing.T) { + assert.Equal(t, []string{ + "FULLSEND_OUTPUT_DIR", + "FULLSEND_PERSONAS_FILE", + "FULLSEND_ROLE", + "FULLSEND_TARGET_REPO_DIR", + "PATH", + }, m.Exports.Always) + }) + + t.Run("conditional", func(t *testing.T) { + want := []string{ + "FULLSEND_EGRESS_ALLOWLIST", + "FULLSEND_FETCH_TOKEN", + "FULLSEND_FETCH_URL", + "FULLSEND_ITERATION_DEADLINE", + "FULLSEND_OUTPUT_FILE", + "FULLSEND_OUTPUT_SCHEMA", + "FULLSEND_SLUG", + "FULLSEND_TIMEOUT_MINUTES", + "FULLSEND_TRACE_ID", + "TIRITH_FAIL_ON", + "TIRITH_REQUIRED", + "TRACEPARENT", + } + got := slices.Collect(maps.Keys(m.Exports.Conditional)) + slices.Sort(got) + assert.Equal(t, want, got) + for _, tc := range []struct { + key string + gateContains string + }{ + {"FULLSEND_SLUG", "slug"}, + {"FULLSEND_OUTPUT_SCHEMA", "schema"}, + {"FULLSEND_OUTPUT_FILE", "FULLSEND_OUTPUT_FILE"}, + {"FULLSEND_FETCH_URL", "fetch service"}, + {"FULLSEND_FETCH_TOKEN", "fetch service"}, + {"FULLSEND_TRACE_ID", "warns"}, + {"TIRITH_FAIL_ON", "tirith"}, + {"TIRITH_REQUIRED", "tirith"}, + {"FULLSEND_EGRESS_ALLOWLIST", "egress"}, + {"FULLSEND_ITERATION_DEADLINE", "writeIterationEnv"}, + {"FULLSEND_TIMEOUT_MINUTES", "writeIterationEnv"}, + {"TRACEPARENT", "writeIterationEnv"}, + } { + assert.Contains(t, m.Exports.Conditional[tc.key], tc.gateContains, "gate for %s", tc.key) + } + }) + + t.Run("runtime specific", func(t *testing.T) { + for _, tc := range []struct { + runtime string + want []string + }{ + {"claude", []string{ + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_BASE_URL", + "CLAUDE_CODE_API_KEY_HELPER_TTL_MS", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", + "CLAUDE_CONFIG_DIR", + }}, + {"codex", []string{ + "CODEX_HOME", + "FULLSEND_CODEX_HOOK_DIGESTS", + "FULLSEND_CODEX_SPAWN_DIGESTS", + "FULLSEND_RUNTIME", + "FULLSEND_TRUSTED_PATH", + "RUST_LOG", + }}, + {"opencode", []string{ + "FULLSEND_RUNTIME", + "GOOGLE_APPLICATION_CREDENTIALS", + "GOOGLE_CLOUD_LOCATION", + "GOOGLE_CLOUD_PROJECT", + "HOME", + "OPENCODE_CONFIG_CONTENT", + "OPENCODE_CONFIG_DIR", + "OPENCODE_DISABLE_EXTERNAL_SKILLS", + "OPENCODE_DISABLE_PROJECT_CONFIG", + }}, + {"pi", []string{ + "FULLSEND_PI_CHILD_BIN", + "FULLSEND_PI_CHILD_NODE", + "FULLSEND_PI_HOOK_PATH", + "FULLSEND_PI_HOOK_PYTHON", + "FULLSEND_PI_MANIFEST", + "FULLSEND_PI_MANIFEST_SHA256", + "FULLSEND_RUNTIME", + "GOOGLE_CLOUD_LOCATION", + "GOOGLE_CLOUD_PROJECT", + "INFERENCE_GATEWAY_BASE_URL", + "INFERENCE_GATEWAY_CONFIG_FILE", + "INFERENCE_GATEWAY_TOKEN_FILE", + "JITI_FS_CACHE", + "PI_CODING_AGENT_DIR", + "PI_CODING_AGENT_SESSION_DIR", + "PI_OFFLINE", + "PI_SKIP_VERSION_CHECK", + "PI_TELEMETRY", + "XAI_VERTEX_PROJECT_ID", + }}, + } { + t.Run(tc.runtime, func(t *testing.T) { + assert.Equal(t, tc.want, m.Exports.RuntimeSpecific[tc.runtime]) + }) + } + assert.Len(t, m.Exports.RuntimeSpecific, len(productionSandboxRuntimes)) + }) + + // Every name a runtime's EnvExports or launch command exports must land + // in some export category, so a bare re-export or a launch-only name + // cannot fall out of the contract unnoticed. + t.Run("runtime exports accounted for", func(t *testing.T) { + for _, name := range productionSandboxRuntimes { + backend, err := agentruntime.Resolve(name) + require.NoError(t, err) + emitted := append(envmanifest.ExportedNames(backend.EnvExports()...), agentruntime.LaunchEnvExportsFor(backend.Runtime)...) + for _, key := range emitted { + _, conditional := m.Exports.Conditional[key] + covered := conditional || slices.Contains(m.Exports.Always, key) || slices.Contains(m.Exports.RuntimeSpecific[name], key) + assert.True(t, covered, "%s exports %q, which no manifest category lists", name, key) + } + } + }) + + t.Run("harness delivered", func(t *testing.T) { + want := []string{ + "ANTHROPIC_VERTEX_PROJECT_ID", + "CLAUDE_CODE_USE_VERTEX", + "CLOUD_ML_REGION", + "GOOGLE_APPLICATION_CREDENTIALS", + } + got := slices.Collect(maps.Keys(m.HarnessDelivered)) + slices.Sort(got) + assert.Equal(t, want, got) + for key, delivered := range m.HarnessDelivered { + assert.Equal(t, envManifestProvenance, delivered.Provenance, "provenance for %q", key) + } + }) + + t.Run("reserved", func(t *testing.T) { + assert.Equal(t, []string{ + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + "ACTIONS_ID_TOKEN_REQUEST_URL", + "ALL_PROXY", + "BASH_ENV", + "CDPATH", + "CURL_CA_BUNDLE", + "DYLD_INSERT_LIBRARIES", + "ENV", + "FULLSEND_FETCH_TOKEN", + "FULLSEND_FETCH_URL", + "FULLSEND_GCP_OIDC_AUTH_FILE", + "FULLSEND_GCP_OIDC_URL", + "FULLSEND_GCP_PROJECT_ID", + "FULLSEND_GCP_WIF_PROVIDER", + "FULLSEND_GITHUB_RUNNER_SECRETS", + "FULLSEND_GITHUB_RUNNER_SECRETS_FILE", + "FULLSEND_GITLAB_TRIGGER_ACCOUNT_TOKEN", + "FULLSEND_INFERENCE_GATEWAY_API_KEY", + "FULLSEND_ITERATION_DEADLINE", + "FULLSEND_OPENAI_API_KEY", + "FULLSEND_OPENAI_AUDIENCE", + "FULLSEND_OPENAI_IDENTITY_PROVIDER_ID", + "FULLSEND_OPENAI_SERVICE_ACCOUNT_ID", + "FULLSEND_OUTPUT_DIR", + "FULLSEND_OUTPUT_FILE", + "FULLSEND_OUTPUT_SCHEMA", + "FULLSEND_PERSONAS_FILE", + "FULLSEND_ROLE", + "FULLSEND_RUNNER_PATH", + "FULLSEND_SLUG", + "FULLSEND_TARGET_REPO_DIR", + "FULLSEND_TIMEOUT_MINUTES", + "FULLSEND_TRIGGER_TOKEN", + "FULLSEND_WEBHOOK_SECRET", + "GH_WORKFLOW_TOKEN", + "GIT_ASKPASS", + "GIT_CONFIG_GLOBAL", + "GIT_EXEC_PATH", + "GIT_SSH_COMMAND", + "GIT_TEMPLATE_DIR", + "HOME", + "HOSTALIASES", + "HTTPS_PROXY", + "HTTP_PROXY", + "IFS", + "JAVA_TOOL_OPTIONS", + "LD_AUDIT", + "LD_LIBRARY_PATH", + "LD_PRELOAD", + "NODE_EXTRA_CA_CERTS", + "NODE_OPTIONS", + "NO_PROXY", + "OPENAI_API_KEY", + "PATH", + "PERL5OPT", + "PROMPT_COMMAND", + "PYTHONPATH", + "PYTHONSTARTUP", + "RUBYOPT", + "SHELL", + "SSL_CERT_DIR", + "SSL_CERT_FILE", + "TRACEPARENT", + }, m.Reserved) + }) + + t.Run("renders deterministically", func(t *testing.T) { + first, err := m.RenderSchemas() + require.NoError(t, err) + second, err := m.RenderSchemas() + require.NoError(t, err) + assert.Equal(t, first, second) + }) +} + +// TestEnvManifestRuntimeEnumeration pins the collector's runtime enumeration +// to the production resolution registry: productionSandboxRuntimes must be +// exactly the registry's resolvable runtimes minus excludedSandboxRuntimes. +// The registry is internal/runtime.Resolve's switch; it exports no name list, +// and probing Resolve with candidate names cannot discover an entry nobody +// asked about (config.ValidRuntimes omits opencode, so config is no proxy), +// so the enumeration is driven from the registry's own case labels. A runtime +// registered without a manifest decision, a retired runtime the collector +// still lists, or an exclusion naming nothing the registry resolves all fail +// here. +func TestEnvManifestRuntimeEnumeration(t *testing.T) { + registry := envManifestRegistryRuntimes(t) + + for _, stub := range excludedSandboxRuntimes { + require.Contains(t, registry, stub, "excludedSandboxRuntimes excludes %q, which the registry does not resolve", stub) + } + want := slices.DeleteFunc(slices.Clone(registry), func(name string) bool { + return slices.Contains(excludedSandboxRuntimes, name) + }) + got := slices.Clone(productionSandboxRuntimes) + slices.Sort(got) + assert.Equal(t, want, got, "productionSandboxRuntimes must be exactly the registry's runtimes minus the stub exclusion") + + for _, name := range productionSandboxRuntimes { + _, err := agentruntime.Resolve(name) + require.NoError(t, err, "resolving runtime %q", name) + } +} + +// envManifestRegistryRuntimes returns the sorted runtime names the production +// resolution registry dispatches on, read from internal/runtime's Resolve +// switch — the registry's own case labels. Resolve offers no exported +// enumeration and cannot reveal names it is never asked about, so the labels +// are the only honest source; any registry edit that adds, removes, or +// reshapes a case changes what this function returns, and a registry.go that +// can no longer be parsed fails the caller. The empty label is Resolve's +// default alias for claude, not a distinct runtime, and is dropped. +func envManifestRegistryRuntimes(t *testing.T) []string { + t.Helper() + src, err := os.ReadFile(filepath.Join("..", "runtime", "registry.go")) + require.NoError(t, err, "reading the resolution registry") + start := strings.Index(string(src), "func Resolve(") + require.NotEqual(t, -1, start, "func Resolve not found in internal/runtime/registry.go") + body := string(src)[start:] + if end := strings.Index(body, "\nfunc "); end != -1 { + body = body[:end] + } + seen := map[string]bool{} + var names []string + for _, clause := range envManifestRegistryCaseRe.FindAllString(body, -1) { + for _, match := range envManifestRegistryLabelRe.FindAllStringSubmatch(clause, -1) { + name := match[1] + if name == "" || seen[name] { + continue + } + seen[name] = true + names = append(names, name) + } + } + require.NotEmpty(t, names, "no runtime case labels found in func Resolve") + slices.Sort(names) + return names +} + +// collectSandboxEnvManifest derives the sandbox environment-variable contract +// by executing the production emitters that build the sandbox environment: +// bootstrapEnv with every optional gate on and off, the iteration-env +// command, injectTraceID, the hook-env append through ClaudeRuntime.Bootstrap, +// every production runtime's EnvExports, and the agent-new Vertex scaffold, +// plus the live reserved map after init() merges the OIDC and provider-only +// sets into it. Keys are parsed from the emitters' real output, so the +// manifest cannot disagree with the emitters without this test failing. +func collectSandboxEnvManifest(t *testing.T) *envmanifest.Manifest { + t.Helper() + b := envmanifest.NewBuilder() + + gatedOn := bootstrapEnvExportKeys(t, true) + gatedOff := bootstrapEnvExportKeys(t, false) + for key := range gatedOff { + require.True(t, gatedOn[key], "bootstrapEnv emits %q only with its gates off", key) + } + alwaysKeys := map[string]bool{} + conditional := map[string]bool{} + for key := range gatedOn { + if gatedOff[key] { + b.AddAlways(key) + alwaysKeys[key] = true + } else { + conditional[key] = true + } + } + + iterationCmd := iterationEnvCommand(30, time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), envManifestTraceparent) + for _, key := range sandboxEnvFileKeys(t, iterationCmd) { + if !alwaysKeys[key] { + conditional[key] = true + } + } + + for _, key := range traceIDExportKeys(t) { + if !alwaysKeys[key] { + conditional[key] = true + } + } + // Hook env is appended by the runtime bootstrap, not by bootstrapEnv, + // so only the runtimes whose Bootstrap reaches appendHookEnv emit it. + // A hook key no shared emitter also produces is restricted to those + // runtimes. + sharedConditional := maps.Clone(conditional) + var hookOnly []string + for _, key := range hookEnvExportKeys(t) { + if !alwaysKeys[key] { + conditional[key] = true + if !sharedConditional[key] { + hookOnly = append(hookOnly, key) + } + } + } + hookRuntimes := hookEnvRuntimes(t) + for key := range conditional { + gate, ok := sandboxEnvGates[key] + require.True(t, ok, "sandbox env var %q is emitted under a gate the collector does not describe; add it to sandboxEnvGates", key) + b.AddConditional(key, gate) + } + for _, key := range hookOnly { + b.RestrictConditional(key, hookRuntimes...) + for _, rt := range productionSandboxRuntimes { + if !slices.Contains(hookRuntimes, rt) { + assert.Contains(t, sandboxEnvGates[key], "unreachable under "+rt, + "%s is hook env that %s's Bootstrap never appends; its gate description must say so", key, rt) + } + } + } + for key := range sandboxEnvGates { + require.True(t, conditional[key], "sandboxEnvGates describes %q, which no emitter emits under a gate anymore", key) + } + + for _, name := range productionSandboxRuntimes { + backend, err := agentruntime.Resolve(name) + require.NoError(t, err, "resolving runtime %q", name) + // runtime_specific unions the runtime's EnvExports statements with + // the bare names its launch command sets (LaunchEnvExporter, which + // internal/runtime pins to the launch commands themselves). Names + // the shared categories already cover — PATH, or the hook env a + // launch command re-exports — stay in their shared category, so + // runtime_specific lists only what the runtime adds. + keys := append(envmanifest.ExportedNames(backend.EnvExports()...), agentruntime.LaunchEnvExportsFor(backend.Runtime)...) + keys = slices.DeleteFunc(keys, func(key string) bool { return alwaysKeys[key] || conditional[key] }) + b.AddRuntimeSpecific(name, keys...) + } + + for _, key := range harnessDeliveredKeys(t) { + b.AddHarnessDelivered(key, envManifestProvenance) + } + + for key := range reservedSandboxKeys { + b.AddReserved(key) + } + for _, key := range sandbox.ReservedCredentialKeys() { + b.AddReserved(key) + } + + manifest := b.Build() + return &manifest +} + +// bootstrapEnvExportKeys runs the production bootstrapEnv under the recording +// openshell stub and returns the keys its uploaded .env assigns. gated +// selects the all-gates-on harness — slug, validation schema, legacy output +// file, fetch service — against the same emitter with every optional +// emission off. Role is set in both runs: it is a required harness field, so +// its emission is unconditional in practice. +func bootstrapEnvExportKeys(t *testing.T, gated bool) map[string]bool { + t.Helper() + captureDir := envManifestCaptureDir(envManifestOpenshell(t)) + h := &harness.Harness{Role: envManifestAgentName} + var fetch []fetchServiceEnv + if gated { + schemaFile := filepath.Join(t.TempDir(), "output-schema.json") + require.NoError(t, os.WriteFile(schemaFile, []byte(`{"type":"object"}`), 0o644)) + h.Slug = envManifestAgentName + "-slug" + h.ValidationLoop = &harness.ValidationLoop{Script: "scripts/validate.sh", Schema: schemaFile} + h.RunnerEnv = map[string]string{"FULLSEND_OUTPUT_FILE": "result.json"} + fetch = append(fetch, fetchServiceEnv{addr: "127.0.0.1:1", token: "env-manifest-probe-token"}) + } + require.NoError(t, bootstrapEnv(envManifestSandboxName, "/workspace/repo", h, nil, fetch...)) + keys := map[string]bool{} + for _, key := range envmanifest.ExportedNames(envManifestCapturedEnv(t, captureDir)) { + keys[key] = true + } + return keys +} + +// traceIDExportKeys runs injectTraceID under the recording stub, replays +// the command it sent to the sandbox, and returns the key its .env append +// exports. The emitter's call site only warns on failure, so the derived key +// is conditional, not always. +func traceIDExportKeys(t *testing.T) []string { + t.Helper() + execLog := envManifestOpenshell(t) + require.NoError(t, injectTraceID(envManifestSandboxName, envManifestTraceID)) + return sandboxEnvFileKeys(t, envManifestEnvWrites(t, execLog)...) +} + +// hookEnvExportKeys derives the security-hook env keys (TIRITH_FAIL_ON, +// TIRITH_REQUIRED, FULLSEND_EGRESS_ALLOWLIST) by driving the exported +// production path that emits them: ClaudeRuntime.Bootstrap ends in +// appendHookEnv, which is package-private to internal/runtime and cannot be +// called from here directly. Every hook gate is on, so all three keys +// derive; each remains conditional in the manifest because the emitters +// guard on the harness security config. +func hookEnvExportKeys(t *testing.T) []string { + t.Helper() + execLog := envManifestOpenshell(t) + agentPath := filepath.Join(t.TempDir(), "agent.md") + require.NoError(t, os.WriteFile(agentPath, []byte("# env manifest probe\n"), 0o644)) + h := &harness.Harness{Security: &harness.SecurityConfig{SandboxHooks: &harness.SandboxHooks{ + Tirith: &harness.TirithConfig{FailOn: "high"}, + SSRFEgressAllowlist: "env-manifest-probe.internal:443", + }}} + in := envManifestBootstrapInput{ + sandboxName: envManifestSandboxName, + agentPath: agentPath, + agentName: envManifestAgentName, + hooks: security.SandboxHookConfigFromHarness(h), + } + require.NoError(t, agentruntime.ClaudeRuntime{}.Bootstrap(in)) + return sandboxEnvFileKeys(t, envManifestEnvWrites(t, execLog)...) +} + +// hookEnvRuntimes returns the production runtimes whose Bootstrap reaches +// appendHookEnv, sorted. appendHookEnv is package-private to +// internal/runtime and some runtimes' bootstraps need a live sandbox to +// drive, so the set comes from the package's static call graph: every +// function and method body in internal/runtime, walked from +// .Bootstrap through plain calls and calls on the receiver. +func hookEnvRuntimes(t *testing.T) []string { + t.Helper() + dir := filepath.Join("..", "runtime") + entries, err := os.ReadDir(dir) + require.NoError(t, err) + fset := token.NewFileSet() + calls := map[string][]string{} + for _, entry := range entries { + name := entry.Name() + if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + file, err := parser.ParseFile(fset, filepath.Join(dir, name), nil, 0) + require.NoError(t, err, "parsing internal/runtime/%s", name) + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + key, recvName, recvType := fn.Name.Name, "", "" + if fn.Recv != nil && len(fn.Recv.List) == 1 { + typ := fn.Recv.List[0].Type + if star, ok := typ.(*ast.StarExpr); ok { + typ = star.X + } + if ident, ok := typ.(*ast.Ident); ok { + recvType = ident.Name + key = recvType + "." + fn.Name.Name + } + if len(fn.Recv.List[0].Names) == 1 { + recvName = fn.Recv.List[0].Names[0].Name + } + } + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + switch f := call.Fun.(type) { + case *ast.Ident: + calls[key] = append(calls[key], f.Name) + case *ast.SelectorExpr: + if x, ok := f.X.(*ast.Ident); ok && recvName != "" && x.Name == recvName { + calls[key] = append(calls[key], recvType+"."+f.Sel.Name) + } + } + return true + }) + } + } + require.Contains(t, calls, "appendHookEnv", "appendHookEnv not found in internal/runtime") + + reaches := func(start string) bool { + seen := map[string]bool{} + stack := []string{start} + for len(stack) > 0 { + fn := stack[len(stack)-1] + stack = stack[:len(stack)-1] + if fn == "appendHookEnv" { + return true + } + if seen[fn] { + continue + } + seen[fn] = true + stack = append(stack, calls[fn]...) + } + return false + } + + var runtimes []string + for _, name := range productionSandboxRuntimes { + backend, err := agentruntime.Resolve(name) + require.NoError(t, err, "resolving runtime %q", name) + typ := reflect.TypeOf(backend.Runtime) + if typ.Kind() == reflect.Pointer { + typ = typ.Elem() + } + bootstrap := typ.Name() + ".Bootstrap" + require.Contains(t, calls, bootstrap, "runtime %q: %s not found in internal/runtime", name, bootstrap) + if reaches(bootstrap) { + runtimes = append(runtimes, name) + } + } + // ClaudeRuntime.Bootstrap is the path hookEnvExportKeys drives, so the + // static walk must find it; otherwise the walk has stopped seeing calls. + require.Contains(t, runtimes, "claude", "the call-graph walk no longer finds ClaudeRuntime.Bootstrap reaching appendHookEnv") + slices.Sort(runtimes) + return runtimes +} + +// envManifestScaffoldOptions builds a valid agent-new Options whose +// renderings differ only in runtime and model, so the Vertex env block is +// the only env.sandbox difference between the pair. +func envManifestScaffoldOptions(t *testing.T, runtimeName, model string) agentnew.Options { + t.Helper() + role, err := agentnew.LookupRole("coder") + require.NoError(t, err) + trigger, err := agentnew.ExpandTrigger(agentnew.DefaultOn, envManifestAgentName) + require.NoError(t, err) + return agentnew.Options{ + Name: envManifestAgentName, + Role: "coder", + Description: "Env manifest probe agent", + Trigger: trigger, + Model: model, + Effort: agentnew.DefaultEffort, + Slug: envManifestAgentName, + Image: role.Image, + TimeoutMinutes: agentnew.DefaultTimeoutMinutes, + Runtime: runtimeName, + } +} + +// scaffoldSandboxEnvKeys renders a scaffold through the production +// generator, loads its harness through the production loader, and returns +// the env.sandbox key set the harness declares. +func scaffoldSandboxEnvKeys(t *testing.T, opts agentnew.Options) map[string]bool { + t.Helper() + require.NoError(t, opts.Validate()) + files, err := agentnew.Render(opts) + require.NoError(t, err) + dir := t.TempDir() + harnessPath := "" + for _, f := range files { + path := filepath.Join(dir, f.Path) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, f.Data, os.FileMode(f.Mode))) + if strings.HasPrefix(f.Path, "harness/") { + harnessPath = path + } + } + require.NotEmpty(t, harnessPath, "the scaffold must contain a harness file") + h, err := harness.Load(harnessPath) + require.NoError(t, err) + keys := map[string]bool{} + if h.Env != nil { + for key := range h.Env.Sandbox { + keys[key] = true + } + } + return keys +} + +// harnessDeliveredKeys derives the harness-delivered variables as the +// env.sandbox keys the Vertex scaffold adds over an otherwise identical +// scaffold without Vertex: the credentials and routing that stock harness +// configuration delivers rather than the runner. +func harnessDeliveredKeys(t *testing.T) []string { + t.Helper() + withVertex := scaffoldSandboxEnvKeys(t, envManifestScaffoldOptions(t, "", agentnew.DefaultModel)) + withoutVertex := scaffoldSandboxEnvKeys(t, envManifestScaffoldOptions(t, "codex", "openai/gpt-5.6-luna")) + var keys []string + for key := range withVertex { + if !withoutVertex[key] { + keys = append(keys, key) + } + } + return keys +} + +// envManifestOpenshell installs an openshell stub on PATH. On a sandbox +// upload whose local file is a fullsend-env-*.sh temp file it copies that +// file into a capture directory — bootstrapEnv composes the sandbox .env in +// exactly such a file — and on a sandbox exec it appends the command (the +// last argument) to a NUL-separated log, so the emitters' sandbox commands +// can be replayed. Only openshell is stubbed; tar and the other host tools +// the runtimes shell out to keep working. The capture directory is +// returned through envManifestCaptureDir. +func envManifestOpenshell(t *testing.T) (execLog string) { + t.Helper() + base := t.TempDir() + execLog = filepath.Join(base, "exec.log") + captureDir := filepath.Join(base, "captured") + binDir := filepath.Join(base, "bin") + require.NoError(t, os.MkdirAll(captureDir, 0o755)) + require.NoError(t, os.MkdirAll(binDir, 0o755)) + script := "#!/bin/sh\n" + + "if [ \"$1\" = \"sandbox\" ] && [ \"$2\" = \"upload\" ]; then\n" + + " case \"$5\" in\n" + + " *fullsend-env-*) cp \"$5\" '" + captureDir + "/' ;;\n" + + " esac\n" + + " exit 0\n" + + "fi\n" + + "if [ \"$1\" = \"sandbox\" ] && [ \"$2\" = \"exec\" ]; then\n" + + " for last; do :; done\n" + + " printf '%s\\0' \"$last\" >> '" + execLog + "'\n" + + " case \"$last\" in\n" + + " \"mkdir -m 700 -- \"*|\"rm -f -- \"*) sh -c \"$last\"; exit $? ;;\n" + + " \"test -f \"*) exit 0 ;;\n" + + " *\"|fullsend-hook-sep|\"*) printf '%s|fullsend-hook-sep|%s\\n' /usr/bin/python3 /usr/local/bin:/usr/bin:/bin; exit 0 ;;\n" + + " *\"sys.version_info\"*) echo 3.12; exit 0 ;;\n" + + " *fullsend-env-sep*) printf '%s' \"|fullsend-env-sep|\"; exit 0 ;;\n" + + " cat\\ *) exit 0 ;;\n" + + " esac\n" + + " exit 0\n" + + "fi\n" + + "exit 0\n" + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte(script), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + return execLog +} + +// envManifestCaptureDir returns the directory envManifestOpenshell copies +// uploaded .env files into, given the exec log path it returned. +func envManifestCaptureDir(execLog string) string { + return filepath.Join(filepath.Dir(execLog), "captured") +} + +// envManifestEnvWrites returns the recorded sandbox commands that write an +// env file under the sandbox workspace: the .env appends and the +// iteration-env rewrite. Bootstrap's other commands (launch-script pins, +// probes) touch no env file and are not replayed. +func envManifestEnvWrites(t *testing.T, execLog string) []string { + t.Helper() + data, err := os.ReadFile(execLog) + require.NoError(t, err, "the openshell stub recorded no sandbox exec") + var cmds []string + for _, cmd := range strings.Split(strings.TrimSuffix(string(data), "\x00"), "\x00") { + if strings.Contains(cmd, "> "+sandbox.SandboxWorkspace+"/") { + cmds = append(cmds, cmd) + } + } + return cmds +} + +// sandboxEnvFileKeys replays sandbox commands with /bin/sh against a scratch +// copy of the sandbox workspace and returns the names the env files they +// wrote export. Running the commands — rather than reading their text — +// means the derivation sees the file content the sandbox would source, so a +// quoted value or a dropped export keyword changes the result. +func sandboxEnvFileKeys(t *testing.T, cmds ...string) []string { + t.Helper() + require.NotEmpty(t, cmds, "no sandbox env-file writes to replay") + workspace := filepath.Join(t.TempDir(), "workspace") + require.NoError(t, os.MkdirAll(workspace, 0o755)) + for _, cmd := range cmds { + local := strings.ReplaceAll(cmd, sandbox.SandboxWorkspace, workspace) + out, err := exec.Command("/bin/sh", "-c", local).CombinedOutput() + require.NoError(t, err, "replaying sandbox command %q: %s", cmd, out) + } + var files []string + require.NoError(t, filepath.WalkDir(workspace, func(path string, d os.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + data, err := os.ReadFile(path) + files = append(files, string(data)) + return err + })) + require.NotEmpty(t, files, "the replayed commands wrote no env file") + return envmanifest.ExportedNames(files...) +} + +// envManifestCapturedEnv returns the .env content bootstrapEnv uploaded, and +// fails when more or fewer than one env file was captured. +func envManifestCapturedEnv(t *testing.T, captureDir string) string { + t.Helper() + entries, err := os.ReadDir(captureDir) + require.NoError(t, err) + require.Len(t, entries, 1, "bootstrapEnv must upload exactly one .env file") + data, err := os.ReadFile(filepath.Join(captureDir, entries[0].Name())) + require.NoError(t, err) + return string(data) +} + +// envManifestBootstrapInput implements runtime.BootstrapInput and +// runtime.SandboxHooksBootstrap for the hook-env derivation, mirroring the +// bootstrap inputs internal/runtime's own tests use. +type envManifestBootstrapInput struct { + sandboxName string + agentPath string + agentName string + hooks security.SandboxHookConfig +} + +func (i envManifestBootstrapInput) SandboxName() string { return i.sandboxName } + +func (i envManifestBootstrapInput) AgentPath() string { return i.agentPath } + +func (i envManifestBootstrapInput) AgentName() string { return i.agentName } + +func (i envManifestBootstrapInput) SkillDirs() []string { return nil } + +func (i envManifestBootstrapInput) Plugins() []agentruntime.PluginInput { return nil } + +func (i envManifestBootstrapInput) ModelAliases() map[string]string { return nil } + +func (i envManifestBootstrapInput) AgentSubagents() map[string]*string { return nil } + +func (i envManifestBootstrapInput) ParentModel() string { return "" } + +func (i envManifestBootstrapInput) Effort() string { return "" } + +func (i envManifestBootstrapInput) OpenAIProviderAttached() bool { return false } + +func (i envManifestBootstrapInput) SandboxHookConfig() security.SandboxHookConfig { + return i.hooks +} + +var ( + _ agentruntime.BootstrapInput = envManifestBootstrapInput{} + _ agentruntime.SandboxHooksBootstrap = envManifestBootstrapInput{} +) diff --git a/internal/cli/env_manifest_golden_test.go b/internal/cli/env_manifest_golden_test.go new file mode 100644 index 0000000000..2820117c92 --- /dev/null +++ b/internal/cli/env_manifest_golden_test.go @@ -0,0 +1,105 @@ +package cli + +import ( + "bytes" + "flag" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/envmanifest" +) + +// update rewrites the committed sandbox env schemas from collector output, +// following the repo's golden-test flag convention (internal/agentnew, +// internal/runtime). +var update = flag.Bool("update", false, "rewrite the committed sandbox env schemas under docs/normative/sandbox-env/v1/") + +// envManifestSchemaDir locates the committed sandbox env contract schemas, +// repo-relative from internal/cli's test working directory — the same ../.. +// relative-read pattern this package's other repo-root reads use. +var envManifestSchemaDir = filepath.Join("..", "..", "docs", "normative", "sandbox-env", "v1") + +// TestEnvManifestGolden byte-compares each committed sandbox env contract +// schema under docs/normative/sandbox-env/v1/ against the schema rendered +// from the manifest the collector derives by executing the production +// emitters, so the published contract cannot drift from the code that +// builds the sandbox environment. +// +// Regenerate with: go test ./internal/cli -run TestEnvManifestGolden -update +func TestEnvManifestGolden(t *testing.T) { + schemas, err := collectSandboxEnvManifest(t).RenderSchemas() + require.NoError(t, err, "rendering the collected manifest's schemas") + require.ElementsMatch(t, []string{envmanifest.HarnessEnvSchemaFile, envmanifest.EnvReferencesSchemaFile}, keysOf(schemas)) + + for file, rendered := range schemas { + path := filepath.Join(envManifestSchemaDir, file) + t.Run(file, func(t *testing.T) { + if *update { + require.NoError(t, os.MkdirAll(envManifestSchemaDir, 0o755)) + require.NoError(t, os.WriteFile(path, rendered, 0o644)) + // The update run must land exactly what the collector + // produced: a partial or failed write would otherwise pass + // here and fail the next plain run. + written, err := os.ReadFile(path) + require.NoError(t, err, "reading back the rewritten schema") + assert.Equal(t, rendered, written, "the rewritten schema must equal collector output byte for byte") + return + } + + committed, err := os.ReadFile(path) + if os.IsNotExist(err) { + t.Fatalf("committed sandbox env schema %s does not exist (not generated yet); run with -update to create it: go test ./internal/cli -run TestEnvManifestGolden -update", path) + } + require.NoError(t, err, "reading the committed sandbox env schema") + + if !bytes.Equal(committed, rendered) { + t.Fatalf("committed sandbox env schema %s differs from collector output:\n%s\nif the change is intended, regenerate and review the diff: go test ./internal/cli -run TestEnvManifestGolden -update", + path, envManifestDiffSummary(committed, rendered)) + } + }) + } +} + +func keysOf(m map[string][]byte) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + return keys +} + +// envManifestDiffSummary locates a committed/rendered divergence: the first +// few differing line numbers with the first difference's lines, or the +// line-count gap when one side is a prefix of the other. Deliberately short — +// the line numbers point review at the change, and the full diff is one +// -update away. +func envManifestDiffSummary(committed, rendered []byte) string { + committedLines := strings.Split(string(committed), "\n") + renderedLines := strings.Split(string(rendered), "\n") + var differing []int + for i := 0; i < len(committedLines) && i < len(renderedLines) && len(differing) < 3; i++ { + if committedLines[i] != renderedLines[i] { + differing = append(differing, i+1) + } + } + if len(differing) == 0 { + return "one side is a byte-prefix of the other: committed " + + strconv.Itoa(len(committedLines)) + " lines, rendered " + + strconv.Itoa(len(renderedLines)) + " lines" + } + numbers := make([]string, len(differing)) + for i, n := range differing { + numbers[i] = strconv.Itoa(n) + } + return "first differing lines: " + strings.Join(numbers, ", ") + + " (committed " + strconv.Itoa(len(committedLines)) + " lines, rendered " + + strconv.Itoa(len(renderedLines)) + " lines)\n" + + " line " + strconv.Itoa(differing[0]) + " committed: " + committedLines[differing[0]-1] + "\n" + + " line " + strconv.Itoa(differing[0]) + " rendered: " + renderedLines[differing[0]-1] +} diff --git a/internal/envmanifest/builder.go b/internal/envmanifest/builder.go new file mode 100644 index 0000000000..4d47142664 --- /dev/null +++ b/internal/envmanifest/builder.go @@ -0,0 +1,99 @@ +package envmanifest + +// Builder assembles a Manifest from derived emitter output. The zero value +// is usable, but NewBuilder is the documented entry point. +type Builder struct { + always []string + conditional map[string]string + conditionalRuntimes map[string][]string + runtimeSpecific map[string][]string + harnessDelivered map[string]HarnessDelivered + reserved []string + deprecated []string +} + +// NewBuilder returns an empty manifest builder. +func NewBuilder() *Builder { + return &Builder{ + conditional: map[string]string{}, + runtimeSpecific: map[string][]string{}, + harnessDelivered: map[string]HarnessDelivered{}, + } +} + +// AddAlways records variables the runner exports on every run. +func (b *Builder) AddAlways(names ...string) *Builder { + b.always = append(b.always, names...) + return b +} + +// AddConditional records a variable the runner exports only when gate holds. +// gate describes the condition; it is contract metadata, never a value. +func (b *Builder) AddConditional(name, gate string) *Builder { + if b.conditional == nil { + b.conditional = map[string]string{} + } + b.conditional[name] = gate + return b +} + +// RestrictConditional records that the conditional variable name can reach +// only the listed runtimes, because only their bootstraps emit it. An +// unrestricted conditional variable is reachable under every runtime. +func (b *Builder) RestrictConditional(name string, runtimes ...string) *Builder { + if b.conditionalRuntimes == nil { + b.conditionalRuntimes = map[string][]string{} + } + b.conditionalRuntimes[name] = append(b.conditionalRuntimes[name], runtimes...) + return b +} + +// AddRuntimeSpecific records the variables a runtime emits beyond the shared +// set: its EnvExports statements plus the names its launch command sets. A +// runtime that emits nothing is recorded with an empty set rather than +// omitted. +func (b *Builder) AddRuntimeSpecific(runtime string, names ...string) *Builder { + if b.runtimeSpecific == nil { + b.runtimeSpecific = map[string][]string{} + } + b.runtimeSpecific[runtime] = append(b.runtimeSpecific[runtime], names...) + return b +} + +// AddHarnessDelivered records a variable delivered by stock harness +// configuration, with provenance describing where the delivery happens. +func (b *Builder) AddHarnessDelivered(name, provenance string) *Builder { + if b.harnessDelivered == nil { + b.harnessDelivered = map[string]HarnessDelivered{} + } + b.harnessDelivered[name] = HarnessDelivered{Provenance: provenance} + return b +} + +// AddReserved records variables reserved from harness override. +func (b *Builder) AddReserved(names ...string) *Builder { + b.reserved = append(b.reserved, names...) + return b +} + +// AddDeprecated records variables that are deprecated and scheduled for +// removal in a future version. +func (b *Builder) AddDeprecated(names ...string) *Builder { + b.deprecated = append(b.deprecated, names...) + return b +} + +// Build returns the manifest with every category in canonical form. +func (b *Builder) Build() Manifest { + return Manifest{ + Exports: Exports{ + Always: b.always, + Conditional: b.conditional, + RuntimeSpecific: b.runtimeSpecific, + ConditionalRuntimes: b.conditionalRuntimes, + }, + HarnessDelivered: b.harnessDelivered, + Reserved: b.reserved, + Deprecated: b.deprecated, + }.normalized() +} diff --git a/internal/envmanifest/builder_test.go b/internal/envmanifest/builder_test.go new file mode 100644 index 0000000000..6c397d6537 --- /dev/null +++ b/internal/envmanifest/builder_test.go @@ -0,0 +1,47 @@ +package envmanifest + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestBuilder_CanonicalForm(t *testing.T) { + m := NewBuilder(). + AddAlways("PATH", "FULLSEND_ROLE", "PATH", "FULLSEND_OUTPUT_DIR"). + AddConditional("FULLSEND_SLUG", "harness sets a slug"). + AddRuntimeSpecific("pi", "PI_TELEMETRY", "PI_OFFLINE", "PI_OFFLINE"). + AddRuntimeSpecific("opencode"). + AddHarnessDelivered("GOOGLE_APPLICATION_CREDENTIALS", "Vertex scaffold"). + AddReserved("GH_WORKFLOW_TOKEN", "OPENAI_API_KEY", "GH_WORKFLOW_TOKEN"). + AddDeprecated("OLD_VAR_B", "OLD_VAR_A", "OLD_VAR_B"). + Build() + + assert.Equal(t, []string{"FULLSEND_OUTPUT_DIR", "FULLSEND_ROLE", "PATH"}, m.Exports.Always) + assert.Equal(t, map[string]string{"FULLSEND_SLUG": "harness sets a slug"}, m.Exports.Conditional) + assert.Equal(t, map[string][]string{ + "opencode": {}, + "pi": {"PI_OFFLINE", "PI_TELEMETRY"}, + }, m.Exports.RuntimeSpecific) + assert.Equal(t, map[string]HarnessDelivered{ + "GOOGLE_APPLICATION_CREDENTIALS": {Provenance: "Vertex scaffold"}, + }, m.HarnessDelivered) + assert.Equal(t, []string{"GH_WORKFLOW_TOKEN", "OPENAI_API_KEY"}, m.Reserved) + assert.Equal(t, []string{"OLD_VAR_A", "OLD_VAR_B"}, m.Deprecated) +} + +func TestBuilder_ZeroValueUsable(t *testing.T) { + var b Builder + m := b. + AddAlways("PATH"). + AddConditional("FULLSEND_SLUG", "harness sets a slug"). + AddRuntimeSpecific("opencode"). + AddHarnessDelivered("CLOUD_ML_REGION", "Vertex scaffold"). + AddReserved("GH_WORKFLOW_TOKEN"). + AddDeprecated("LEGACY_VAR"). + Build() + + assert.Equal(t, []string{"PATH"}, m.Exports.Always) + assert.Equal(t, []string{"LEGACY_VAR"}, m.Deprecated) + assert.Equal(t, []string{"opencode"}, m.Runtimes()) +} diff --git a/internal/envmanifest/manifest.go b/internal/envmanifest/manifest.go new file mode 100644 index 0000000000..3320079b45 --- /dev/null +++ b/internal/envmanifest/manifest.go @@ -0,0 +1,93 @@ +// Package envmanifest models the sandbox environment-variable contract: +// which variables the runner injects into the sandbox, under what +// conditions, per which runtime, which are delivered by stock harness +// configuration rather than the runner, which are reserved from harness +// override, and which are deprecated. RenderSchemas publishes the model as +// the JSON Schemas under docs/normative/sandbox-env/v1/. +// +// The model carries variable names and category metadata only — never +// values or secrets. Rendering is deterministic by contract: sorted names, +// fixed key order, and a trailing newline, so regenerating the committed +// schemas without a source change produces byte-identical files. Version +// identity comes from the v1 path and the release tag in the fetch URL; the +// schemas carry no fullsend version, which commit-time stamping would break. +package envmanifest + +import "slices" + +// Manifest is the sandbox environment-variable contract model. +type Manifest struct { + Exports Exports + HarnessDelivered map[string]HarnessDelivered + Reserved []string + Deprecated []string +} + +// Exports groups the runner-exported variable categories. Always and +// Conditional are runner-guaranteed modulo their gates; RuntimeSpecific is +// per-runtime and a portability gap, not a guarantee. +type Exports struct { + Always []string + Conditional map[string]string + RuntimeSpecific map[string][]string + // ConditionalRuntimes restricts a Conditional variable to the runtimes + // whose bootstrap can emit it. A Conditional variable with no entry + // here is reachable under every runtime; one with an entry is + // reachable only under the listed runtimes and never under portable. + ConditionalRuntimes map[string][]string +} + +// HarnessDelivered describes a variable delivered by stock harness +// configuration rather than by the runner. Such a variable is never a +// runner guarantee: one the runner guarantees belongs in Exports instead. +type HarnessDelivered struct { + Provenance string +} + +// normalized returns a canonical copy of m: name slices sorted and +// deduplicated, nil categories replaced with empty ones so every section +// is non-nil. m itself is not modified. +func (m Manifest) normalized() Manifest { + conditional := make(map[string]string, len(m.Exports.Conditional)) + for k, v := range m.Exports.Conditional { + conditional[k] = v + } + conditionalRuntimes := make(map[string][]string, len(m.Exports.ConditionalRuntimes)) + for name, runtimes := range m.Exports.ConditionalRuntimes { + conditionalRuntimes[name] = sortedUnique(runtimes) + } + runtimeSpecific := make(map[string][]string, len(m.Exports.RuntimeSpecific)) + for runtime, names := range m.Exports.RuntimeSpecific { + runtimeSpecific[runtime] = sortedUnique(names) + } + harnessDelivered := make(map[string]HarnessDelivered, len(m.HarnessDelivered)) + for name, delivered := range m.HarnessDelivered { + harnessDelivered[name] = delivered + } + return Manifest{ + Exports: Exports{ + Always: sortedUnique(m.Exports.Always), + Conditional: conditional, + RuntimeSpecific: runtimeSpecific, + ConditionalRuntimes: conditionalRuntimes, + }, + HarnessDelivered: harnessDelivered, + Reserved: sortedUnique(m.Reserved), + Deprecated: sortedUnique(m.Deprecated), + } +} + +// sortedUnique returns names deduplicated and sorted, never nil. +func sortedUnique(names []string) []string { + seen := make(map[string]struct{}, len(names)) + unique := make([]string, 0, len(names)) + for _, name := range names { + if _, dup := seen[name]; dup { + continue + } + seen[name] = struct{}{} + unique = append(unique, name) + } + slices.Sort(unique) + return unique +} diff --git a/internal/envmanifest/manifest_test.go b/internal/envmanifest/manifest_test.go new file mode 100644 index 0000000000..dd16e16e4e --- /dev/null +++ b/internal/envmanifest/manifest_test.go @@ -0,0 +1,79 @@ +package envmanifest + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// sampleManifest returns a manifest exercising every category, including a +// runtime with an empty export set and a harness-delivered entry. +func sampleManifest() Manifest { + return NewBuilder(). + AddAlways("PATH", "FULLSEND_ROLE", "FULLSEND_OUTPUT_DIR"). + AddConditional("FULLSEND_SLUG", "harness sets a slug"). + AddConditional("TRACEPARENT", "writeIterationEnv succeeds"). + AddConditional("TIRITH_REQUIRED", "Tirith scanning is required; only the claude and pi bootstraps append hook env"). + RestrictConditional("TIRITH_REQUIRED", "pi", "claude"). + AddRuntimeSpecific("claude", "CLAUDE_CONFIG_DIR"). + AddRuntimeSpecific("opencode"). + AddRuntimeSpecific("pi", "PI_TELEMETRY", "JITI_FS_CACHE"). + AddHarnessDelivered("GOOGLE_APPLICATION_CREDENTIALS", "stock harness configuration: Vertex scaffold"). + AddReserved("GH_WORKFLOW_TOKEN", "OPENAI_API_KEY", "TRACEPARENT"). + AddDeprecated("FULLSEND_ROLE"). + Build() +} + +func TestNormalized_DoesNotMutateReceiver(t *testing.T) { + m := Manifest{ + Exports: Exports{ + Always: []string{"B", "A"}, + Conditional: map[string]string{"C": "gate"}, + }, + } + n := m.normalized() + n.Exports.Conditional["D"] = "added" + assert.Equal(t, []string{"B", "A"}, m.Exports.Always, "normalized must not sort the receiver in place") + assert.NotContains(t, m.Exports.Conditional, "D", "normalized must not alias the receiver's maps") +} + +// namesOnlyFieldTypes is the complete field inventory of the manifest +// types. The names-only invariant is structural: every field carries names +// or category metadata, and the only string-to-string map is the +// conditional gate-description map — so a field that could carry variable +// values cannot be added without failing this inventory. +var namesOnlyFieldTypes = map[string]string{ + "Manifest.Exports": "envmanifest.Exports", + "Manifest.HarnessDelivered": "map[string]envmanifest.HarnessDelivered", + "Manifest.Reserved": "[]string", + "Manifest.Deprecated": "[]string", + "Exports.Always": "[]string", + "Exports.Conditional": "map[string]string", + "Exports.RuntimeSpecific": "map[string][]string", + "Exports.ConditionalRuntimes": "map[string][]string", + "HarnessDelivered.Provenance": "string", +} + +func TestManifest_NamesOnlyFieldInventory(t *testing.T) { + structTypes := map[string]reflect.Type{ + "Manifest": reflect.TypeOf(Manifest{}), + "Exports": reflect.TypeOf(Exports{}), + "HarnessDelivered": reflect.TypeOf(HarnessDelivered{}), + } + + seen := make(map[string]struct{}) + for typeName, typ := range structTypes { + for i := range typ.NumField() { + field := typ.Field(i) + key := typeName + "." + field.Name + want, ok := namesOnlyFieldTypes[key] + require.True(t, ok, "%s is not in the names-only field inventory", key) + assert.Equal(t, want, field.Type.String(), "%s must keep its names-only shape", key) + seen[key] = struct{}{} + } + } + + assert.Len(t, seen, len(namesOnlyFieldTypes), "every inventory entry must correspond to a real field") +} diff --git a/internal/envmanifest/schema.go b/internal/envmanifest/schema.go new file mode 100644 index 0000000000..dcb109bde9 --- /dev/null +++ b/internal/envmanifest/schema.go @@ -0,0 +1,355 @@ +package envmanifest + +import ( + "bytes" + "encoding/json" + "fmt" + "regexp" + "slices" + "strings" + "unicode" +) + +// SchemaBaseURI is the $id prefix of the published sandbox env schemas, +// matching the other normative schemas' https://fullsend.ai/normative/ +// identifiers. The schemas are fetched by tag URL, not from this host; +// the $id only names them. +const SchemaBaseURI = "https://fullsend.ai/normative/sandbox-env/v1/" + +// The published schema files, under docs/normative/sandbox-env/v1/. +const ( + // HarnessEnvSchemaFile validates a harness YAML's env blocks: no + // env.sandbox key may be a name the runner reserves. + HarnessEnvSchemaFile = "harness-env.schema.json" + // EnvReferencesSchemaFile validates a reachability claim — "code running + // under this runtime reads these variables" — and carries the full + // contract inventory in its $defs. + EnvReferencesSchemaFile = "env-references.schema.json" +) + +// PortableRuntime is the env-references runtime value for code that must +// work under every runtime: it may rely only on the shared categories. +const PortableRuntime = "portable" + +// envNamePattern is the POSIX shell variable-name grammar, as a JSON Schema +// pattern. +const envNamePattern = "^[A-Za-z_][A-Za-z0-9_]*$" + +// RenderSchemas returns the published JSON Schemas generated from m, keyed +// by file name. Each schema is self-contained — its $defs carry every +// category it needs — so a consumer validates against one fetched file with +// no cross-file $ref resolution. Output is deterministic: keys appear in a +// fixed order, names are sorted, and each file ends in a newline. +func (m Manifest) RenderSchemas() (map[string][]byte, error) { + n := m.normalized() + out := map[string][]byte{} + for file, schema := range map[string]object{ + HarnessEnvSchemaFile: n.harnessEnvSchema(), + EnvReferencesSchemaFile: n.envReferencesSchema(), + } { + data, err := encodeSchema(schema) + if err != nil { + return nil, fmt.Errorf("rendering %s: %w", file, err) + } + out[file] = data + } + return out, nil +} + +// Runtimes returns the runtimes the manifest lists, sorted. +func (m Manifest) Runtimes() []string { + runtimes := make([]string, 0, len(m.Exports.RuntimeSpecific)) + for name := range m.Exports.RuntimeSpecific { + runtimes = append(runtimes, name) + } + slices.Sort(runtimes) + return runtimes +} + +func (m Manifest) harnessEnvSchema() object { + return object{ + {"$schema", "https://json-schema.org/draft/2020-12/schema"}, + {"$id", SchemaBaseURI + HarnessEnvSchemaFile}, + {"title", "Harness sandbox env contract"}, + {"description", "Validates the env blocks of a fullsend harness YAML (top-level env, forge..env, and overlays[].env) against the sandbox environment-variable contract: an env.sandbox key must be a shell variable name and must not be a name the runner reserves, in any letter case, because the runner matches reserved keys case-insensitively and drops them instead of exporting them. Other harness fields are not constrained here. Generated from the runner's code (ADR 0146); see README.md."}, + {"type", "object"}, + {"properties", object{ + {"env", ref("#/$defs/env_block")}, + {"forge", object{ + {"type", "object"}, + {"additionalProperties", object{ + {"type", "object"}, + {"properties", object{{"env", ref("#/$defs/env_block")}}}, + }}, + }}, + {"overlays", object{ + {"type", "array"}, + {"items", object{ + {"type", "object"}, + {"properties", object{{"env", ref("#/$defs/env_block")}}}, + }}, + }}, + }}, + {"$defs", object{ + {"env_block", object{ + {"type", "object"}, + {"properties", object{{"sandbox", ref("#/$defs/sandbox_env")}}}, + }}, + {"sandbox_env", object{ + {"description", "Variables a harness delivers into the sandbox. The runner owns the reserved names and refuses them here in any letter case."}, + {"type", "object"}, + {"propertyNames", object{{"allOf", []any{ + ref("#/$defs/env_name"), + object{{"not", ref("#/$defs/reserved_any_case")}}, + }}}}, + }}, + {"env_name", envNameSchema()}, + {"reserved", m.reservedSchema()}, + {"reserved_any_case", m.reservedAnyCaseSchema()}, + }}, + } +} + +func (m Manifest) envReferencesSchema() object { + runtimes := m.Runtimes() + runtimeEnum := append([]string{PortableRuntime}, runtimes...) + var perRuntime []any + perRuntime = append(perRuntime, reachableWhen(PortableRuntime, []any{ref("#/$defs/always"), m.conditionalReachableUnder(PortableRuntime), ref("#/$defs/harness_delivered")})) + for _, rt := range runtimes { + perRuntime = append(perRuntime, reachableWhen(rt, []any{ref("#/$defs/always"), m.conditionalReachableUnder(rt), ref("#/$defs/harness_delivered"), ref("#/$defs/runtime_" + rt)})) + } + + defs := object{ + {"env_name", envNameSchema()}, + {"runtime", object{ + {"description", "The runtime the referencing code runs under, or \"" + PortableRuntime + "\" for code that must work under every runtime."}, + {"enum", runtimeEnum}, + }}, + {"always", object{ + {"description", "Exported by the runner into every sandbox it builds."}, + {"enum", m.Exports.Always}, + }}, + {"conditional", object{ + {"description", "Exported by the runner only when the gate in each entry's description holds. Some entries are emitted only by certain runtimes' bootstraps; the per-runtime reachability rules exclude them elsewhere and under portable."}, + {"oneOf", m.conditionalItems()}, + }}, + } + for _, rt := range runtimes { + defs = append(defs, member{"runtime_" + rt, nameSet( + "Exported only when dispatch runs under "+rt+": its EnvExports plus the environment its launch command sets. Not reachable under other runtimes.", + m.Exports.RuntimeSpecific[rt])}) + } + defs = append(defs, + member{"harness_delivered", object{ + {"description", "Delivered by stock harness configuration, not by the runner: reachable only when the harness delivers it."}, + {"oneOf", m.harnessDeliveredItems()}, + }}, + member{"reserved", m.reservedSchema()}, + member{"deprecated", nameSet("Deprecated and scheduled for removal in a future contract version; still reachable through its export category until then. Consumers should warn on a match and migrate.", m.Deprecated)}, + ) + + return object{ + {"$schema", "https://json-schema.org/draft/2020-12/schema"}, + {"$id", SchemaBaseURI + EnvReferencesSchemaFile}, + {"title", "Sandbox env references"}, + {"description", "Validates that code running in a fullsend sandbox — a skill script, an agent prompt's tool calls, a sandbox hook — reads only environment variables the contract makes reachable under its runtime. List the variables the code reads, minus those the harness's own env.sandbox declares. The $defs are the full contract inventory. Generated from the runner's code (ADR 0146); see README.md."}, + {"type", "object"}, + {"additionalProperties", false}, + {"required", []string{"runtime", "variables"}}, + {"properties", object{ + {"runtime", ref("#/$defs/runtime")}, + {"variables", object{ + {"type", "array"}, + {"uniqueItems", true}, + {"items", ref("#/$defs/env_name")}, + }}, + }}, + {"allOf", perRuntime}, + {"$defs", defs}, + } +} + +// reachableWhen restricts variables to the union of reachable categories +// when runtime equals rt. +func reachableWhen(rt string, reachable []any) object { + return object{ + {"if", object{ + {"properties", object{{"runtime", object{{"const", rt}}}}}, + {"required", []string{"runtime"}}, + }}, + {"then", object{ + {"properties", object{{"variables", object{{"items", object{{"anyOf", reachable}}}}}}}, + }}, + } +} + +func (m Manifest) reservedSchema() object { + return nameSet("Reserved by the runner: a harness cannot set these through env.sandbox.", m.Reserved) +} + +// conditionalReachableUnder returns the conditional category as reachable +// under rt: the whole category, minus names restricted to other runtimes. +// Under portable every restricted name is excluded, since portable code +// must work under every runtime. +func (m Manifest) conditionalReachableUnder(rt string) any { + var excluded []string + for name, runtimes := range m.Exports.ConditionalRuntimes { + if _, ok := m.Exports.Conditional[name]; !ok { + continue + } + if rt == PortableRuntime || !slices.Contains(runtimes, rt) { + excluded = append(excluded, name) + } + } + if len(excluded) == 0 { + return ref("#/$defs/conditional") + } + slices.Sort(excluded) + return object{{"allOf", []any{ + ref("#/$defs/conditional"), + object{{"not", object{{"enum", excluded}}}}, + }}} +} + +// reservedAnyCaseSchema matches the reserved names in any letter case, as +// the runner's isReservedSandboxKey does: it upper-cases a key before the +// lookup. JSON Schema patterns have no case-insensitive flag, so each +// letter becomes a two-case character class. +func (m Manifest) reservedAnyCaseSchema() object { + if len(m.Reserved) == 0 { + return object{{"description", reservedAnyCaseDescription}, {"not", object{}}} + } + alts := make([]string, 0, len(m.Reserved)) + for _, name := range m.Reserved { + alts = append(alts, anyCasePattern(name)) + } + return object{ + {"description", reservedAnyCaseDescription}, + {"pattern", "^(?:" + strings.Join(alts, "|") + ")$"}, + } +} + +const reservedAnyCaseDescription = "The reserved names in any letter case: the runner upper-cases an env.sandbox key before checking it against the reserved set." + +// anyCasePattern renders name as a pattern matching it in any letter case. +func anyCasePattern(name string) string { + var b strings.Builder + for _, r := range name { + switch { + case unicode.IsLetter(r): + b.WriteString("[" + string(unicode.ToUpper(r)) + string(unicode.ToLower(r)) + "]") + default: + b.WriteString(regexp.QuoteMeta(string(r))) + } + } + return b.String() +} + +func (m Manifest) conditionalItems() []any { + names := make([]string, 0, len(m.Exports.Conditional)) + for name := range m.Exports.Conditional { + names = append(names, name) + } + slices.Sort(names) + items := make([]any, 0, len(names)) + for _, name := range names { + items = append(items, object{{"const", name}, {"description", m.Exports.Conditional[name]}}) + } + return orNothing(items) +} + +func (m Manifest) harnessDeliveredItems() []any { + names := make([]string, 0, len(m.HarnessDelivered)) + for name := range m.HarnessDelivered { + names = append(names, name) + } + slices.Sort(names) + items := make([]any, 0, len(names)) + for _, name := range names { + items = append(items, object{{"const", name}, {"description", m.HarnessDelivered[name].Provenance}}) + } + return orNothing(items) +} + +// orNothing keeps a oneOf valid when a category is empty: oneOf must list +// at least one schema, and false matches no name. +func orNothing(items []any) []any { + if len(items) == 0 { + return []any{false} + } + return items +} + +// nameSet is a category as an enum of names; an empty category is a schema +// matching no name, since an enum must list at least one value. +func nameSet(description string, names []string) object { + if len(names) == 0 { + return object{{"description", description}, {"not", object{}}} + } + return object{{"description", description}, {"enum", names}} +} + +func envNameSchema() object { + return object{{"type", "string"}, {"pattern", envNamePattern}} +} + +func ref(target string) object { + return object{{"$ref", target}} +} + +// object is a JSON object whose keys encode in declaration order, so the +// schemas read $schema, $id, title first and stay byte-stable. +type object []member + +type member struct { + key string + value any +} + +func (o object) MarshalJSON() ([]byte, error) { + var buf bytes.Buffer + buf.WriteByte('{') + for i, m := range o { + if i > 0 { + buf.WriteByte(',') + } + key, err := json.Marshal(m.key) + if err != nil { + return nil, err + } + buf.Write(key) + buf.WriteByte(':') + value, err := marshalNoEscape(m.value) + if err != nil { + return nil, err + } + buf.Write(value) + } + buf.WriteByte('}') + return buf.Bytes(), nil +} + +func marshalNoEscape(v any) ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + if err := enc.Encode(v); err != nil { + return nil, err + } + return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil +} + +// encodeSchema renders a schema with two-space indentation and a trailing +// newline. +func encodeSchema(schema object) ([]byte, error) { + compact, err := marshalNoEscape(schema) + if err != nil { + return nil, err + } + var buf bytes.Buffer + if err := json.Indent(&buf, compact, "", " "); err != nil { + return nil, err + } + buf.WriteByte('\n') + return buf.Bytes(), nil +} diff --git a/internal/envmanifest/schema_test.go b/internal/envmanifest/schema_test.go new file mode 100644 index 0000000000..80132d4e47 --- /dev/null +++ b/internal/envmanifest/schema_test.go @@ -0,0 +1,229 @@ +package envmanifest + +import ( + "bytes" + "encoding/json" + "os" + "os/exec" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRenderSchemas_Files(t *testing.T) { + schemas, err := sampleManifest().RenderSchemas() + require.NoError(t, err) + assert.Len(t, schemas, 2) + for _, file := range []string{HarnessEnvSchemaFile, EnvReferencesSchemaFile} { + data, ok := schemas[file] + require.True(t, ok, "missing %s", file) + assert.True(t, json.Valid(data), "%s must be valid JSON", file) + assert.Equal(t, byte('\n'), data[len(data)-1], "%s must end in a newline", file) + var doc map[string]any + require.NoError(t, json.Unmarshal(data, &doc)) + assert.Equal(t, SchemaBaseURI+file, doc["$id"]) + assert.Equal(t, "https://json-schema.org/draft/2020-12/schema", doc["$schema"]) + } +} + +func TestRenderSchemas_Deterministic(t *testing.T) { + first, err := sampleManifest().RenderSchemas() + require.NoError(t, err) + second, err := sampleManifest().RenderSchemas() + require.NoError(t, err) + assert.Equal(t, first, second) + + // Input order must not matter: the builder normalizes. + shuffled := NewBuilder(). + AddReserved("TRACEPARENT", "OPENAI_API_KEY", "GH_WORKFLOW_TOKEN"). + AddRuntimeSpecific("pi", "JITI_FS_CACHE", "PI_TELEMETRY"). + AddRuntimeSpecific("opencode"). + AddRuntimeSpecific("claude", "CLAUDE_CONFIG_DIR"). + AddHarnessDelivered("GOOGLE_APPLICATION_CREDENTIALS", "stock harness configuration: Vertex scaffold"). + AddDeprecated("FULLSEND_ROLE"). + AddConditional("TRACEPARENT", "writeIterationEnv succeeds"). + AddConditional("FULLSEND_SLUG", "harness sets a slug"). + RestrictConditional("TIRITH_REQUIRED", "claude", "pi", "claude"). + AddConditional("TIRITH_REQUIRED", "Tirith scanning is required; only the claude and pi bootstraps append hook env"). + AddAlways("FULLSEND_OUTPUT_DIR", "PATH", "FULLSEND_ROLE"). + Build() + reordered, err := shuffled.RenderSchemas() + require.NoError(t, err) + assert.Equal(t, first, reordered) +} + +func TestRenderSchemas_KeyOrder(t *testing.T) { + schemas, err := sampleManifest().RenderSchemas() + require.NoError(t, err) + data := string(schemas[EnvReferencesSchemaFile]) + assert.Regexp(t, `^\{\n "\$schema": [^\n]*\n "\$id": [^\n]*\n "title": `, data, "$schema, $id and title lead every schema") +} + +func TestRenderSchemas_Defs(t *testing.T) { + schemas, err := sampleManifest().RenderSchemas() + require.NoError(t, err) + var doc struct { + Defs map[string]json.RawMessage `json:"$defs"` + } + require.NoError(t, json.Unmarshal(schemas[EnvReferencesSchemaFile], &doc)) + def := func(name string) string { + var buf bytes.Buffer + require.NoError(t, json.Compact(&buf, doc.Defs[name])) + return buf.String() + } + + for _, name := range []string{"env_name", "runtime", "always", "conditional", "runtime_claude", "runtime_opencode", "runtime_pi", "harness_delivered", "reserved", "deprecated"} { + assert.Contains(t, doc.Defs, name) + } + assert.JSONEq(t, `{"description":"The runtime the referencing code runs under, or \"portable\" for code that must work under every runtime.","enum":["portable","claude","opencode","pi"]}`, string(doc.Defs["runtime"])) + assert.Contains(t, def("conditional"), `{"const":"FULLSEND_SLUG","description":"harness sets a slug"}`) + assert.Contains(t, def("harness_delivered"), `"GOOGLE_APPLICATION_CREDENTIALS"`) + assert.Contains(t, def("deprecated"), `"enum":["FULLSEND_ROLE"]`) + // An empty runtime set is a schema that matches nothing, not an empty + // enum (which JSON Schema discourages). + assert.Contains(t, def("runtime_opencode"), `"not":{}`) +} + +func TestRenderSchemas_EmptyCategories(t *testing.T) { + schemas, err := NewBuilder().Build().RenderSchemas() + require.NoError(t, err) + refs := string(schemas[EnvReferencesSchemaFile]) + assert.Contains(t, refs, `"oneOf": [ + false + ]`, "an empty oneOf category renders as [false]") + assert.Contains(t, string(schemas[HarnessEnvSchemaFile]), `"not": {}`) +} + +// schemaValidatePy validates instance files against one of the rendered +// schemas with Draft 2020-12, the validator consumers are expected to use. +// It prints "ok" or "invalid: " per instance. +const schemaValidatePy = ` +import json, sys +from jsonschema import Draft202012Validator +with open(sys.argv[1], encoding="utf-8") as f: + schema = json.load(f) +Draft202012Validator.check_schema(schema) +v = Draft202012Validator(schema) +for path in sys.argv[2:]: + with open(path, encoding="utf-8") as f: + errs = sorted(v.iter_errors(json.load(f)), key=lambda e: list(e.path)) + print("ok" if not errs else "invalid: " + errs[0].message) +` + +func requirePythonJSONSchema(t *testing.T) { + t.Helper() + if err := exec.Command("python3", "-c", "from jsonschema import Draft202012Validator").Run(); err != nil { + t.Skip("python3 with jsonschema not installed") + } +} + +// validateInstances writes the schema and instances to a temp dir and +// returns the validator's verdict for each instance, in order. +func validateInstances(t *testing.T, schema []byte, instances ...string) []string { + t.Helper() + dir := t.TempDir() + schemaPath := filepath.Join(dir, "schema.json") + require.NoError(t, os.WriteFile(schemaPath, schema, 0o644)) + args := []string{"-c", schemaValidatePy, schemaPath} + for i, inst := range instances { + p := filepath.Join(dir, "instance-"+string(rune('a'+i))+".json") + require.NoError(t, os.WriteFile(p, []byte(inst), 0o644)) + args = append(args, p) + } + out, err := exec.Command("python3", args...).CombinedOutput() + require.NoError(t, err, "%s", out) + verdicts := splitLines(string(out)) + require.Len(t, verdicts, len(instances), "%s", out) + return verdicts +} + +func splitLines(s string) []string { + var lines []string + start := 0 + for i := range len(s) { + if s[i] == '\n' { + lines = append(lines, s[start:i]) + start = i + 1 + } + } + if start < len(s) { + lines = append(lines, s[start:]) + } + return lines +} + +func TestHarnessEnvSchema_Validates(t *testing.T) { + requirePythonJSONSchema(t) + schemas, err := sampleManifest().RenderSchemas() + require.NoError(t, err) + + verdicts := validateInstances(t, schemas[HarnessEnvSchemaFile], + // A harness whose env.sandbox keys are all the harness's own. + `{"role":"review","env":{"runner":{"PR_NUMBER":"1"},"sandbox":{"REVIEW_FINDING_SEVERITY_THRESHOLD":"low"}}}`, + // Reserved key at the top level: the case fullsend-ai/agents + // review.yaml once hit with TRACEPARENT. + `{"env":{"sandbox":{"TRACEPARENT":"x"}}}`, + // Reserved key under a forge override. + `{"forge":{"github":{"env":{"sandbox":{"OPENAI_API_KEY":"x"}}}}}`, + // Not a shell variable name. + `{"env":{"sandbox":{"BAD-NAME":"x"}}}`, + // env.runner is the runner's own environment: reserved names are + // not the sandbox contract's concern there. + `{"env":{"runner":{"TRACEPARENT":"x"}},"schema_version":1}`, + // The runner upper-cases keys before the reserved lookup, so + // lowercase and mixed-case spellings are reserved too. + `{"env":{"sandbox":{"traceparent":"x"}}}`, + `{"forge":{"github":{"env":{"sandbox":{"OpenAI_API_Key":"x"}}}}}`, + // Overlays supply env.sandbox like forge entries do. + `{"overlays":[{"when":"true","env":{"sandbox":{"TRACEPARENT":"x"}}}]}`, + `{"overlays":[{"when":"true","env":{"sandbox":{"gh_workflow_token":"x"}}}]}`, + `{"overlays":[{"when":"true","env":{"sandbox":{"BAD-NAME":"x"}}}]}`, + // A non-reserved overlay key, and a name that merely contains a + // reserved one, stay valid. + `{"overlays":[{"when":"true","env":{"sandbox":{"GOOGLE_CLOUD_PROJECT":"p","TRACEPARENT_COPY":"x"}}}]}`, + ) + assert.Equal(t, "ok", verdicts[0]) + for _, i := range []int{1, 2, 3, 5, 6, 7, 8, 9} { + assert.Contains(t, verdicts[i], "invalid", "instance %d", i) + } + assert.Equal(t, "ok", verdicts[4]) + assert.Equal(t, "ok", verdicts[10]) +} + +func TestEnvReferencesSchema_Validates(t *testing.T) { + requirePythonJSONSchema(t) + schemas, err := sampleManifest().RenderSchemas() + require.NoError(t, err) + + verdicts := validateInstances(t, schemas[EnvReferencesSchemaFile], + // Shared categories are reachable everywhere. + `{"runtime":"portable","variables":["FULLSEND_OUTPUT_DIR","FULLSEND_SLUG","GOOGLE_APPLICATION_CREDENTIALS"]}`, + // A runtime-specific name under its own runtime. + `{"runtime":"claude","variables":["CLAUDE_CONFIG_DIR"]}`, + // A runtime-restricted conditional name under a runtime that + // emits it. + `{"runtime":"pi","variables":["TIRITH_REQUIRED"]}`, + // ...but not under a runtime whose bootstrap never emits it, + `{"runtime":"opencode","variables":["TIRITH_REQUIRED"]}`, + // nor under portable. + `{"runtime":"portable","variables":["TIRITH_REQUIRED"]}`, + // The fullsend-ai/agents#1672 failure: a skill reading + // CLAUDE_CONFIG_DIR while running under pi. + `{"runtime":"pi","variables":["CLAUDE_CONFIG_DIR"]}`, + // Runtime-specific names are not portable. + `{"runtime":"portable","variables":["PI_TELEMETRY"]}`, + // A name nothing delivers. + `{"runtime":"claude","variables":["NOT_IN_CONTRACT"]}`, + // Unknown runtime. + `{"runtime":"cursor","variables":[]}`, + // Shape errors. + `{"runtime":"claude"}`, + `{"runtime":"claude","variables":["PATH"],"extra":true}`, + ) + assert.Equal(t, []string{"ok", "ok", "ok"}, verdicts[:3]) + for i, v := range verdicts[3:] { + assert.Contains(t, v, "invalid", "instance %d", i+3) + } +} diff --git a/internal/envmanifest/shellexports.go b/internal/envmanifest/shellexports.go new file mode 100644 index 0000000000..c50ba695da --- /dev/null +++ b/internal/envmanifest/shellexports.go @@ -0,0 +1,284 @@ +package envmanifest + +import ( + "regexp" + "slices" + "strings" +) + +// envNameRe is the POSIX shell variable-name grammar. +var envNameRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) + +// ExportedNames returns the sorted, distinct variable names the shell +// scripts place in a child process's environment. It recognizes three forms: +// +// - export statements, both "export NAME=value" and the bare re-export +// "export NAME"; +// - prefix assignments on a command ("NAME=value cmd" and +// "env NAME=value cmd"), which the command's process inherits; +// - the same forms inside the script argument of "sh -c" or "bash -c", +// parsed recursively. +// +// A plain assignment with no command ("NAME=value" alone, or "readonly +// NAME=value") is shell-local and is not reported, nor is a prefix +// assignment on a shell builtin ("IFS= read"). Assignment-shaped text +// inside a quoted value is data, not a binding, and a command +// substitution's exports stay in its subshell. The parser is a tokenizer, +// not a shell: it handles single and double quotes, backslash escapes, +// $(...) nesting, comments, and the ; && || | & ( ) { } newline +// separators, which is the subset the runner's emitters generate. +func ExportedNames(scripts ...string) []string { + seen := map[string]bool{} + for _, script := range scripts { + collectExportedNames(script, seen, 0) + } + names := make([]string, 0, len(seen)) + for name := range seen { + names = append(names, name) + } + slices.Sort(names) + return names +} + +// shellBuiltins are commands that run inside the shell itself, so a prefix +// assignment on them ("IFS= read -r line") scopes to that one builtin and +// never reaches a child process's environment. +var shellBuiltins = map[string]bool{ + ":": true, "[": true, "break": true, "cd": true, "continue": true, + "echo": true, "eval": true, "exit": true, "false": true, "printf": true, + "read": true, "return": true, "set": true, "shift": true, "test": true, + "true": true, "unset": true, +} + +// maxShellDepth bounds sh -c recursion so a malformed input cannot loop. +const maxShellDepth = 8 + +// shellWord is one word of a simple command after quote removal. +// nameQuoted records that a quote opened before the word's first '=': sh +// treats 'A'=b as a command word, not an assignment. +type shellWord struct { + text string + nameQuoted bool +} + +// assignmentName returns NAME when w is an unquoted-name NAME=value word, +// or "" otherwise. +func (w shellWord) assignmentName() string { + if w.nameQuoted { + return "" + } + name, _, ok := strings.Cut(w.text, "=") + if !ok || !envNameRe.MatchString(name) { + return "" + } + return name +} + +func collectExportedNames(script string, seen map[string]bool, depth int) { + if depth > maxShellDepth { + return + } + for _, words := range shellCommands(script) { + collectFromCommand(words, seen, depth) + } +} + +// collectFromCommand records the names one simple command exports. +func collectFromCommand(words []shellWord, seen map[string]bool, depth int) { + // Leading NAME=value words are prefix assignments when a command + // follows them, and shell-local assignments when nothing does. + i := 0 + for i < len(words) && words[i].assignmentName() != "" { + i++ + } + if i == len(words) { + return + } + cmd, args := words[i].text, words[i+1:] + if !shellBuiltins[cmd] { + for _, w := range words[:i] { + seen[w.assignmentName()] = true + } + } + switch cmd { + case "export": + for _, a := range args { + if strings.HasPrefix(a.text, "-") { + continue + } + if name := a.assignmentName(); name != "" { + seen[name] = true + } else if envNameRe.MatchString(a.text) { + seen[a.text] = true + } + } + case "env": + for j, a := range args { + if strings.HasPrefix(a.text, "-") { + continue + } + name := a.assignmentName() + if name == "" { + collectFromCommand(args[j:], seen, depth) + return + } + seen[name] = true + } + case "exec", "command", "nohup": + collectFromCommand(args, seen, depth) + case "sh", "bash", "/bin/sh", "/bin/bash": + for j, a := range args { + if strings.HasPrefix(a.text, "-") && strings.Contains(a.text, "c") && j+1 < len(args) { + collectExportedNames(args[j+1].text, seen, depth+1) + return + } + } + } +} + +// shellCommands splits script into simple commands, each a list of words +// with quotes removed. Command substitutions are kept as opaque word text. +func shellCommands(script string) [][]shellWord { + var ( + cmds [][]shellWord + words []shellWord + cur strings.Builder + inWord bool + nameQuoted bool + sawEq bool + ) + endWord := func() { + if inWord { + words = append(words, shellWord{text: cur.String(), nameQuoted: nameQuoted}) + } + cur.Reset() + inWord, nameQuoted, sawEq = false, false, false + } + endCmd := func() { + endWord() + if len(words) > 0 { + cmds = append(cmds, words) + } + words = nil + } + quote := func() { + inWord = true + if !sawEq { + nameQuoted = true + } + } + for i := 0; i < len(script); i++ { + c := script[i] + switch { + case c == '\'': + quote() + j := strings.IndexByte(script[i+1:], '\'') + if j < 0 { + cur.WriteString(script[i+1:]) + i = len(script) + break + } + cur.WriteString(script[i+1 : i+1+j]) + i += j + 1 + case c == '"': + quote() + for i++; i < len(script) && script[i] != '"'; i++ { + switch { + case script[i] == '\\' && i+1 < len(script) && strings.IndexByte("\"\\$`\n", script[i+1]) >= 0: + i++ + case strings.HasPrefix(script[i:], "$("): + end := skipSubstitution(script, i+2) + cur.WriteString(script[i:end]) + i = end - 1 + continue + } + cur.WriteByte(script[i]) + } + case strings.HasPrefix(script[i:], "$("): + // A command substitution runs in a subshell: its exports never + // reach the caller, so its text is kept as opaque word data. + inWord = true + end := skipSubstitution(script, i+2) + cur.WriteString(script[i:end]) + i = end - 1 + case c == '\\' && i+1 < len(script): + inWord = true + i++ + if script[i] != '\n' { + cur.WriteByte(script[i]) + } + case c == ' ' || c == '\t': + endWord() + case c == '\n' || c == ';' || c == '&' || c == '|' || c == '(' || c == ')': + endCmd() + case (c == '{' || c == '}') && !inWord: + endCmd() + case c == '#' && !inWord: + for i < len(script) && script[i] != '\n' { + i++ + } + endCmd() + default: + inWord = true + if c == '=' { + sawEq = true + } + cur.WriteByte(c) + } + } + endCmd() + return cmds +} + +// skipSubstitution returns the index just past the ")" closing the command +// substitution whose body starts at i (just after "$("), honoring nested +// quotes, escapes, and parentheses. An unterminated substitution consumes +// the rest of the script. +func skipSubstitution(s string, i int) int { + depth := 1 + for i < len(s) { + switch s[i] { + case '\\': + i += 2 + continue + case '\'': + j := strings.IndexByte(s[i+1:], '\'') + if j < 0 { + return len(s) + } + i += j + 2 + continue + case '"': + i = skipDoubleQuoted(s, i+1) + continue + case '(': + depth++ + case ')': + depth-- + if depth == 0 { + return i + 1 + } + } + i++ + } + return len(s) +} + +// skipDoubleQuoted returns the index just past the '"' closing the +// double-quoted string whose body starts at i, descending into command +// substitutions so their own quotes do not end it. +func skipDoubleQuoted(s string, i int) int { + for i < len(s) { + switch { + case s[i] == '\\': + i += 2 + case s[i] == '"': + return i + 1 + case strings.HasPrefix(s[i:], "$("): + i = skipSubstitution(s, i+2) + default: + i++ + } + } + return len(s) +} diff --git a/internal/envmanifest/shellexports_test.go b/internal/envmanifest/shellexports_test.go new file mode 100644 index 0000000000..7dce39781f --- /dev/null +++ b/internal/envmanifest/shellexports_test.go @@ -0,0 +1,46 @@ +package envmanifest + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestExportedNames(t *testing.T) { + tests := []struct { + name string + scripts []string + want []string + }{ + {"export with value", []string{"export FOO=bar"}, []string{"FOO"}}, + {"bare re-export", []string{"export OPENCODE_CONFIG_CONTENT"}, []string{"OPENCODE_CONFIG_CONTENT"}}, + {"several names in one export", []string{"export A=1 B C=3"}, []string{"A", "B", "C"}}, + {"export flags are skipped", []string{"export -n FOO"}, []string{"FOO"}}, + {"plain assignment is shell-local", []string{"FOO=bar"}, []string{}}, + {"readonly assignment is shell-local", []string{"readonly FOO=bar"}, []string{}}, + {"dropping export drops the name", []string{"PI_OFFLINE=1 && export PI_TELEMETRY=0"}, []string{"PI_TELEMETRY"}}, + {"assignment text inside a quoted value", []string{`export FULLSEND_OUTPUT_FILE='NAME=value'`}, []string{"FULLSEND_OUTPUT_FILE"}}, + {"assignment text inside double quotes", []string{`echo "PHANTOM=1" && export REAL=1`}, []string{"REAL"}}, + {"quoted name is not an assignment", []string{`'FOO'=bar cmd`}, []string{}}, + {"prefix assignment reaches the command", []string{`HOME="$X" PATH="$Y" opencode run`}, []string{"HOME", "PATH"}}, + {"prefix assignment on a builtin does not", []string{"IFS= read -r line"}, []string{}}, + {"env command assignments", []string{"env -i A=1 B=2 node app.js"}, []string{"A", "B"}}, + {"exec passes prefix through", []string{"exec env A=1 node"}, []string{"A"}}, + {"sh -c script is parsed", []string{`sh -c 'export INNER=1 && run'`}, []string{"INNER"}}, + {"bash -lc script is parsed", []string{`bash -lc "export INNER=1"`}, []string{"INNER"}}, + {"command substitution does not leak", []string{`X="$(export SUB=1; echo "$SUB")" && export OUTER=1`}, []string{"OUTER"}}, + {"separators split commands", []string{"export A=1; export B=2 && export C=3 || export D=4 | cat"}, []string{"A", "B", "C", "D"}}, + {"newlines split commands", []string{"export A=1\nB=2\nexport C=3\n"}, []string{"A", "C"}}, + {"comments are ignored", []string{"# export NOPE=1\nexport YES=1"}, []string{"YES"}}, + {"brace group", []string{"{ export A=1; } && ( export B=2 )"}, []string{"A", "B"}}, + {"escaped quote stays in the value", []string{`export A="x\"B=1"`}, []string{"A"}}, + {"dedupes and sorts across scripts", []string{"export Z=1", "export A=1 Z=2"}, []string{"A", "Z"}}, + {"invalid names are ignored", []string{"export 1BAD=x -flag"}, []string{}}, + {"unterminated quote does not panic", []string{`export A="x`, `export B='y`, `X="$(unterminated`}, []string{"A", "B"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, ExportedNames(tt.scripts...)) + }) + } +} diff --git a/internal/runtime/claude.go b/internal/runtime/claude.go index 9c81f5e174..2b640b58e0 100644 --- a/internal/runtime/claude.go +++ b/internal/runtime/claude.go @@ -1208,10 +1208,29 @@ func agentDestName(agentName, agentPath string) string { return filepath.Base(agentPath) } +// LaunchEnvExports implements LaunchEnvExporter: the environment names +// buildRunCommand sets beyond EnvExports. Nonessential traffic is always +// disabled; the rest are set only when an inference gateway is registered +// for the run (claudeGatewayPostEnv), with the credential variable chosen +// by the block's auth mode, and are recorded flat anyway: runtime_specific +// asks whether the runtime can set the name, not whether every +// configuration does. TestLaunchEnvExportsMatchLaunchCommands pins this +// list to the launch commands. +func (ClaudeRuntime) LaunchEnvExports() []string { + return []string{ + claudeNonessentialTrafficEnv, + claudeGatewayBaseURLEnv, + "ANTHROPIC_API_KEY", + "ANTHROPIC_AUTH_TOKEN", + "CLAUDE_CODE_API_KEY_HELPER_TTL_MS", + } +} + // Ensure ClaudeRuntime implements Runtime and TranscriptHandler. var ( _ Runtime = ClaudeRuntime{} _ TranscriptHandler = ClaudeRuntime{} _ DebugLogNamer = ClaudeRuntime{} _ ContextBridger = ClaudeRuntime{} + _ LaunchEnvExporter = ClaudeRuntime{} ) diff --git a/internal/runtime/codex.go b/internal/runtime/codex.go index e396fd5d63..029b097783 100644 --- a/internal/runtime/codex.go +++ b/internal/runtime/codex.go @@ -106,6 +106,28 @@ func (r CodexRuntime) OpenAIAuthSeed() string { `fullsend: writing the codex token file failed`, "exit 1") } +// LaunchEnvExports implements LaunchEnvExporter: the environment names +// buildCodexRunCommand sets beyond EnvExports. RUST_LOG, PATH (pinned to +// the trusted PATH) and FULLSEND_TRUSTED_PATH are always set; the digest +// variables and the re-exported hook env (TIRITH_*, FULLSEND_EGRESS_ALLOWLIST) +// are conditional on sandbox hooks being enabled and are recorded flat +// anyway: runtime_specific asks whether the runtime can set the name, not +// whether every configuration does. TestLaunchEnvExportsMatchLaunchCommands +// pins this list to the launch commands. +func (CodexRuntime) LaunchEnvExports() []string { + return []string{ + codexRuntimeEnv, + "RUST_LOG", + "PATH", + "FULLSEND_TRUSTED_PATH", + codexHookDigestsEnv, + codexSpawnDigestsEnv, + "TIRITH_REQUIRED", + "TIRITH_FAIL_ON", + "FULLSEND_EGRESS_ALLOWLIST", + } +} + // Compile-time interface assertions. var ( _ Runtime = CodexRuntime{} @@ -113,5 +135,6 @@ var ( _ DebugLogNamer = CodexRuntime{} _ ProviderResolver = CodexRuntime{} + _ LaunchEnvExporter = CodexRuntime{} _ OpenAICredentialSeeder = CodexRuntime{} ) diff --git a/internal/runtime/launchenv_test.go b/internal/runtime/launchenv_test.go new file mode 100644 index 0000000000..6bfe1f59e6 --- /dev/null +++ b/internal/runtime/launchenv_test.go @@ -0,0 +1,103 @@ +package runtime + +import ( + "slices" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/envmanifest" +) + +// launchCommandVariants builds each runtime's production launch command +// under every configuration that changes what it exports: hooks on and off, +// an inference gateway registered and not, and each provider path. The +// union of their exports is what the runtime can set, which is the set +// LaunchEnvExports must declare. +func launchCommandVariants(t *testing.T, rt Runtime) []string { + t.Helper() + t.Setenv("FULLSEND_PI_MODEL", "") + t.Setenv(piProviderEnv, "") + t.Setenv(openCodeProviderEnv, "") + switch rt.(type) { + case ClaudeRuntime: + cmds := []string{buildRunCommand(RunParams{SandboxName: "fs-launchenv-claude", AgentBaseName: "agent", RepoDir: "/r"})} + for _, gw := range []struct { + sandbox string + block config.InferenceGatewayConfig + }{ + {"fs-launchenv-claude-oidc", config.InferenceGatewayConfig{URL: "https://gw.example.com", Audience: "aud"}}, + {"fs-launchenv-claude-bearer", config.InferenceGatewayConfig{URL: "https://gw.example.com", Auth: config.GatewayAuthAPIKey}}, + {"fs-launchenv-claude-xapikey", config.InferenceGatewayConfig{URL: "https://gw.example.com", Auth: config.GatewayAuthAPIKey, MessagesAuthHeader: config.GatewayMessagesAuthHeaderXAPIKey}}, + } { + require.NoError(t, ClaudeRuntime{}.PrepareGatewayRun(gw.sandbox, GatewayRun{Block: gw.block, BaseURL: "https://gw.example.com"})) + t.Cleanup(func() { ClaudeRuntime{}.ClearGatewayRun(gw.sandbox) }) + cmds = append(cmds, buildRunCommand(RunParams{SandboxName: gw.sandbox, AgentBaseName: "agent", RepoDir: "/r", Model: "gateway/m", HooksSettingsPath: "/sandbox/claude-config/hooks.json"})) + } + return cmds + case CodexRuntime: + noHooks := testRunnerHeldDigests + noHooks.HooksJSON = "" + noHooks.HookScripts = nil + noHooks.SecurityEnv = nil + gateway := testRunnerHeldDigests + gateway.GatewayBaseURL = testCodexGatewayBaseURL + failOn := testRunnerHeldDigests + failOn.SecurityEnv = append(slices.Clone(failOn.SecurityEnv), hookEnvPair{"TIRITH_FAIL_ON", "high"}) + return []string{ + buildCodexRunCommand(hooksOn, codexModel{ID: "gpt-5.6-luna"}, "high", true, testRunnerHeldDigests), + buildCodexRunCommand(RunParams{RepoDir: "/r"}, codexModel{ID: "gpt-5.6-luna"}, "", false, noHooks), + buildCodexRunCommand(hooksOn, codexModel{ID: "vendor/org/model", Gateway: true}, "high", true, gateway), + buildCodexRunCommand(hooksOn, codexModel{ID: "gpt-5.6-luna"}, "high", true, failOn), + } + case OpenCodeRuntime: + params := RunParams{SandboxName: "fs-launchenv-opencode", AgentBaseName: "triage", Model: "opus", Effort: "high", RepoDir: "/r"} + return []string{ + buildOpenCodeRunCommand(params, "triage", openCodeTrustedEnv{ConfigContent: `{"permission":{"*":"deny"}}`, CredentialsPath: "/runner/adc.json"}), + } + case PiRuntime: + var cmds []string + for _, model := range []string{"opus", piXaiVertexProvider + "/xai/grok-4.6", piOpenAIProvider + "/gpt-5.6-luna"} { + params := piTestParams() + params.Model = model + cmds = append(cmds, buildPiRunCommand(params, &piManifest{}, nil, "manifest-sum")) + } + params := piTestParams() + params.SandboxName = "fs-launchenv-pi-gw" + params.Model = "gateway/m1" + run := piGatewayTestRun() + run.ConfigFile = "/sandbox/gateway/config.json" + registerPiGatewayRun(t, params.SandboxName, run) + return append(cmds, buildPiRunCommand(params, &piManifest{}, nil, "manifest-sum")) + } + return nil +} + +// TestLaunchEnvExportsMatchLaunchCommands pins every LaunchEnvExports list to +// the launch commands themselves: the names a runtime declares must be +// exactly the names its launch-command variants export beyond EnvExports. A +// launch builder that gains, drops, or renames an export without updating +// the declaration fails here, so the sandbox env contract cannot drift from +// the commands. +func TestLaunchEnvExportsMatchLaunchCommands(t *testing.T) { + for _, rt := range []Runtime{ClaudeRuntime{}, CodexRuntime{}, OpenCodeRuntime{}, PiRuntime{}} { + t.Run(rt.Name(), func(t *testing.T) { + fromEnvExports := envmanifest.ExportedNames(rt.EnvExports()...) + derived := slices.DeleteFunc(envmanifest.ExportedNames(launchCommandVariants(t, rt)...), func(name string) bool { + return slices.Contains(fromEnvExports, name) + }) + declared := slices.Clone(LaunchEnvExportsFor(rt)) + slices.Sort(declared) + assert.Equal(t, derived, declared, "LaunchEnvExports must list exactly what the launch commands export beyond EnvExports") + }) + } +} + +// TestLaunchEnvExportsFor_Stubs pins that the local test stubs declare no +// launch exports: they are outside the sandbox env contract. +func TestLaunchEnvExportsFor_Stubs(t *testing.T) { + assert.Nil(t, LaunchEnvExportsFor(DummyRuntime{})) + assert.Nil(t, LaunchEnvExportsFor(DummyPlaybackRuntime{})) +} diff --git a/internal/runtime/opencode.go b/internal/runtime/opencode.go index 277f4812bc..4aefdb5b6b 100644 --- a/internal/runtime/opencode.go +++ b/internal/runtime/opencode.go @@ -61,9 +61,28 @@ func (r OpenCodeRuntime) EnvExports() []string { } } +// LaunchEnvExports implements LaunchEnvExporter: the environment names +// buildOpenCodeRunCommand sets beyond EnvExports. The Vertex project +// mapping is always exported, and the opencode process is started with its +// own HOME and trusted PATH as prefix assignments; the location is exported +// only when the composed value is non-empty and is recorded flat anyway: +// runtime_specific asks whether the runtime can set the name, not whether +// every configuration does. TestLaunchEnvExportsMatchLaunchCommands pins +// this list to the launch commands. +func (OpenCodeRuntime) LaunchEnvExports() []string { + return []string{ + openCodeRuntimeEnv, + "GOOGLE_CLOUD_PROJECT", + "GOOGLE_CLOUD_LOCATION", + "HOME", + "PATH", + } +} + // Compile-time interface assertions. var ( _ Runtime = OpenCodeRuntime{} _ TranscriptHandler = OpenCodeRuntime{} _ DebugLogNamer = OpenCodeRuntime{} + _ LaunchEnvExporter = OpenCodeRuntime{} ) diff --git a/internal/runtime/pi.go b/internal/runtime/pi.go index 2d60fc6955..348dccfa9e 100644 --- a/internal/runtime/pi.go +++ b/internal/runtime/pi.go @@ -153,6 +153,35 @@ func (r PiRuntime) EnvExports() []string { } } +// LaunchEnvExports implements LaunchEnvExporter: the environment names +// buildPiRunCommand sets beyond EnvExports. The launch command pins the +// manifest the sandbox runs, re-exports the hook and child helper paths +// the bootstrap .env carried, and maps the Vertex project variables onto +// their GOOGLE_CLOUD_* names. GOOGLE_CLOUD_PROJECT and +// XAI_VERTEX_PROJECT_ID are conditional on the provider path and are +// recorded flat anyway: runtime_specific asks whether the runtime can set +// the name, not whether every provider path does. The INFERENCE_GATEWAY_* +// names are set only when an inference gateway is registered for the run +// (piGatewayEnvParts). TestLaunchEnvExportsMatchLaunchCommands pins this +// list to the launch commands. +func (PiRuntime) LaunchEnvExports() []string { + return []string{ + piRuntimeEnv, + piManifestEnv, + piManifestSumEnv, + piHookPythonEnv, + piHookPathEnv, + piChildBinEnv, + piChildNodeEnv, + "GOOGLE_CLOUD_LOCATION", + "GOOGLE_CLOUD_PROJECT", + "XAI_VERTEX_PROJECT_ID", + piInferenceGatewayBaseURLEnv, + piInferenceGatewayTokenFileEnv, + piInferenceGatewayConfigFileEnv, + } +} + // Compile-time interface assertions. var ( _ Runtime = PiRuntime{} @@ -160,5 +189,6 @@ var ( _ DebugLogNamer = PiRuntime{} _ ProviderResolver = PiRuntime{} + _ LaunchEnvExporter = PiRuntime{} _ OpenAICredentialSeeder = PiRuntime{} ) diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 2c604ed61d..52bc85d215 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -290,3 +290,29 @@ func GenAISystemFor(rt Runtime, model, agentModel string, aliases map[string]str } return rt.System() } + +// LaunchEnvExporter is an optional Runtime extension for runtimes whose +// launch command (buildXRunCommand) exports environment variables beyond +// the runtime's EnvExports: names the executed agent process sees but that +// are set in the command string itself rather than by the runtime method. +// LaunchEnvExports returns the bare variable names (no "export " prefix, no +// value), including conditionally exported names — the flat union is the +// contract: a consumer asks "can this runtime set it?", not "does it always +// set it?". Runtimes whose launch commands export nothing beyond EnvExports +// (dummy, dummy-playback) must not implement this. +// TestLaunchEnvExportsMatchLaunchCommands derives each list from the +// runtime's launch commands, so a declaration cannot omit a name the +// commands export or keep one they no longer do. +type LaunchEnvExporter interface { + Runtime + LaunchEnvExports() []string +} + +// LaunchEnvExportsFor returns the launch-command environment names for rt, +// or nil when the runtime does not implement LaunchEnvExporter. +func LaunchEnvExportsFor(rt Runtime) []string { + if l, ok := rt.(LaunchEnvExporter); ok { + return l.LaunchEnvExports() + } + return nil +}