From d71e1823805ab242c65744d5eaba681eccdff855 Mon Sep 17 00:00:00 2001 From: Jay Flowers Date: Tue, 3 Nov 2026 14:54:48 -0500 Subject: [PATCH 1/4] refactor(envmanifest): add sandbox environment variable contract Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jay Flowers --- ...6-sandbox-environment-contract-manifest.md | 101 +++ docs/architecture.md | 15 +- docs/cli/run.md | 5 + docs/contributing/runtime-implementation.md | 15 + docs/guides/dev/cli-internals.md | 6 + docs/guides/user/bring-your-own-agent.md | 2 +- docs/guides/user/customizing-agents.md | 4 +- docs/guides/user/running-agents-locally.md | 4 +- docs/normative/sandbox-env/v1/README.md | 219 ++++++ .../normative/sandbox-env/v1/sandbox-env.json | 146 ++++ docs/problems/agent-infrastructure.md | 2 +- docs/problems/security-threat-model.md | 7 + docs/reference/harness-reference.md | 2 +- docs/runtimes/claude.md | 5 + docs/runtimes/pi.md | 4 +- internal/cli/env_manifest_collector_test.go | 696 ++++++++++++++++++ internal/cli/env_manifest_golden_test.go | 92 +++ internal/envmanifest/builder.go | 89 +++ internal/envmanifest/builder_test.go | 65 ++ internal/envmanifest/manifest.go | 129 ++++ internal/envmanifest/manifest_test.go | 301 ++++++++ internal/runtime/codex.go | 16 + internal/runtime/launchenv_test.go | 76 ++ internal/runtime/opencode.go | 15 + internal/runtime/pi.go | 24 + internal/runtime/runtime.go | 24 + 26 files changed, 2056 insertions(+), 8 deletions(-) create mode 100644 docs/ADRs/0146-sandbox-environment-contract-manifest.md create mode 100644 docs/normative/sandbox-env/v1/README.md create mode 100644 docs/normative/sandbox-env/v1/sandbox-env.json create mode 100644 internal/cli/env_manifest_collector_test.go create mode 100644 internal/cli/env_manifest_golden_test.go create mode 100644 internal/envmanifest/builder.go create mode 100644 internal/envmanifest/builder_test.go create mode 100644 internal/envmanifest/manifest.go create mode 100644 internal/envmanifest/manifest_test.go create mode 100644 internal/runtime/launchenv_test.go 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..6a5a704a69 --- /dev/null +++ b/docs/ADRs/0146-sandbox-environment-contract-manifest.md @@ -0,0 +1,101 @@ +--- +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 +[`reservedSandboxKeys` sync note](https://github.com/fullsend-ai/fullsend/blob/487169a9da/internal/cli/run.go#L3375-L3427) +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). +- **Behavior-level golden over `bootstrapEnv`** — strongest check, + but needs fixtures for every emission gate; hardening follow-up. + +## Decision + +Publish the sandbox environment contract as a generated, committed manifest +at [`sandbox-env.json`](../normative/sandbox-env/v1/sandbox-env.json), with +schema and category semantics in its [README](../normative/sandbox-env/v1/README.md). +A build-time collector generates the manifest by running every code +path that injects environment variables into the sandbox — the +[`bootstrapEnv` `.env` emission](https://github.com/fullsend-ai/fullsend/blob/487169a9da/internal/cli/run.go#L3836-L3871), +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 — so the contract cannot disagree with the code +that builds the environment. An always-on golden test byte-compares the +committed file against collector output (`-update` regenerates); a +companion runtime-enumeration test fails when a runtime is newly +registered without a manifest decision. + +The manifest is 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 tag itself is +the version identifier, so the manifest carries no embedded +`fullsend_version` field. Consumers validate +env-var reachability 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. + +## Consequences + +- Adding, changing, or reserving a runner env var requires a same-PR manifest + bump, visible in the diff. +- Content repos gain a fail-closed gate: a failed or unparseable manifest + 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 manifest is derived contract data — no runtime cost or behavior change. +- `harness_delivered` variables are labeled not-runner-guaranteed: their + provenance is the stock scaffold and may lag the fleet's `gcp-vertex.env`. + +## Forge scope + +The manifest is forge-agnostic: it describes 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..6f8f03db70 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), + [manifest](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 a generated, tag-pinned manifest 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..9ebe80367d 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 manifest decision fails + `TestEnvManifestRuntimeEnumeration`, and `TestEnvManifestGolden` pins the + committed manifest content (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 manifest collector unions them into that runtime's `runtime_specific` set (`docs/normative/sandbox-env/v1/`). pi, codex, and opencode 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 manifest of every variable the runner injects into the +sandbox, per gate and per runtime, and of the keys it reserves from harness +override. The manifest is 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..97c679bb35 --- /dev/null +++ b/docs/normative/sandbox-env/v1/README.md @@ -0,0 +1,219 @@ +# Sandbox environment 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 a generated, versioned, +machine-readable manifest so consumers can verify env-var reachability +against a released runner instead of hand-maintained mirrors — the +transitional lockstep between fullsend and the fleet harnesses it loads +([ADR 0058](../../../ADRs/0058-agent-registration.md)) becomes verifiable +rather than assumed +([ADR 0146](../../../ADRs/0146-sandbox-environment-contract-manifest.md)). + +## Contract + +- **Manifest:** [`sandbox-env.json`](sandbox-env.json) — the committed, + generated contract document. It is authoritative; this README describes it. +- **Generated, never hand-authored:** the collector in + `internal/cli/env_manifest_collector_test.go` derives the manifest by + running 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. +- **Golden invariant:** `internal/cli/env_manifest_golden_test.go` + byte-compares the committed file against collector output on every test + run, so the published contract cannot drift from the code that builds the + sandbox environment. A hand edit, or a code change shipped without + regenerating, fails the test. +- **Names only, never values:** the manifest records variable names, + category membership, gate descriptions, and provenance — no credentials or + configuration values. Every name is already public in fullsend's source. + +## Schema + +| Field | Type | Semantics | +|-------|------|-----------| +| `schema_version` | integer | Shape version of this document; currently `1`. Check it before interpreting anything else — a version the consumer does not understand is a contract it cannot validate. | +| `exports.always` | array of strings | Variables the runner injects into every sandbox it builds (four in v1). | +| `exports.conditional` | object: variable name → gate description | Variables the runner injects only when the described gate holds (twelve in v1). Each description is the emitter's actual guard, transcribed from the production code. | +| `exports.runtime_specific` | object: runtime name → array of strings | Variables emitted only by the named runtime — its `EnvExports()` plus the environment its launch command sets: `claude`, `codex`, `opencode`, `pi`. | +| `harness_delivered` | object: variable name → `{ "provenance": string, "runner_guaranteed": boolean }` | Variables delivered by stock harness configuration, not by the runner (four in v1). `runner_guaranteed` is always `false` — a label, not a toggle: a variable the runner guarantees belongs in `exports` instead. `provenance` names the configuration that delivers it. | +| `reserved` | array of strings | Keys the runner reserves from harness override (62 in v1): `env.sandbox` cannot set them. The set merges the base runner-infrastructure keys, the OIDC-denied and provider-only credential keys, and the security-critical credential keys (`IsReservedCredentialKey`) at startup. | +| `deprecated` | array of strings | Variables that are deprecated and scheduled for removal in a future version. Consumers should migrate away from these variables. Empty when no deprecations are active. | + +Abridged shape (see [`sandbox-env.json`](sandbox-env.json) for the full +document): + +```json +{ + "schema_version": 1, + "exports": { + "always": ["FULLSEND_OUTPUT_DIR", "FULLSEND_ROLE", "FULLSEND_TARGET_REPO_DIR", "PATH"], + "conditional": { + "FULLSEND_FETCH_URL": "the runtime fetch service is enabled (ADR 0038)" + }, + "runtime_specific": { + "claude": ["CLAUDE_CONFIG_DIR"], + "opencode": ["OPENCODE_CONFIG_DIR", "..."] + } + }, + "harness_delivered": { + "GOOGLE_APPLICATION_CREDENTIALS": { + "provenance": "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", + "runner_guaranteed": false + } + }, + "reserved": ["BASH_ENV", "HOME", "LD_PRELOAD"], + "deprecated": [] +} +``` + +## Category semantics + +The categories form a guarantee ladder. Consumers should read them as +answers to "what may I rely on?", not as a flat inventory. + +**`always` and `conditional` — runner-guaranteed, modulo gates.** Every +fullsend runner injects the `always` variables into every sandbox it builds. +A `conditional` variable is guaranteed exactly when its gate holds — for +example, `FULLSEND_FETCH_URL` and `FULLSEND_FETCH_TOKEN` arrive when the +runtime fetch service is enabled +([ADR 0038](../../../ADRs/0038-universal-harness-access.md)), and +`FULLSEND_TRACE_ID` when trace-ID injection succeeds (injection is +best-effort; on failure the run warns and continues). Within their gates, +these two categories are universally reachable: a harness may rely on them +under any runtime. 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. + +**`runtime_specific` — guaranteed only when that runtime runs.** Both halves +matter: + +- When dispatch executes under a runtime, that runtime's listed variables are + reachable: a run under `claude` always has `CLAUDE_CONFIG_DIR`; a run + under `pi` sees its listed variables, with provider-path names like + `GOOGLE_CLOUD_PROJECT` set only on the paths that select them. +- Across runtimes, they are a portability gap, not a guarantee: nothing + promises `CLAUDE_CONFIG_DIR` under `codex` or `pi`. A harness that reads a + runtime-specific variable is coupled to that runtime and breaks when + configuration changes the runtime. + +The enumerated runtimes are the runner's resolution registry minus test +stubs. A runtime that emits nothing appears with an empty set rather than +being omitted. Registering a new runtime without a manifest decision +fails `TestEnvManifestRuntimeEnumeration`, which pins the collector's +runtime list to the resolution registry; the golden test covers the +committed manifest content. + +**`harness_delivered` — configuration, not guarantee.** These variables reach +the sandbox only because stock harness configuration injects them: +`GOOGLE_APPLICATION_CREDENTIALS`, `CLAUDE_CODE_USE_VERTEX`, +`ANTHROPIC_VERTEX_PROJECT_ID`, and `CLOUD_ML_REGION` are delivered by the +`fullsend agent new` Vertex scaffold through `env.sandbox` plus a host file, +and fleet harnesses deliver these plus `GOOGLE_CLOUD_PROJECT` and +`ANTHROPIC_DEFAULT_SONNET_MODEL` through `env/gcp-vertex.env` +in fullsend-ai/agents (see each entry's `provenance`). The runner never +injects them — `runner_guaranteed: false` — so a hand-authored harness that +omits that configuration will not see them. + +**`reserved` — stripped from harness override.** Harness `env.sandbox` +entries naming these keys are skipped with a warning: the runner removes +them so harness configuration cannot shadow runner infrastructure, inject +OIDC and provider credentials, or override security-critical process +variables (e.g. `HTTPS_PROXY`, `LD_PRELOAD`, `NODE_OPTIONS`). A key may +appear both here and in an export category — `PATH` is exported by the +runner *and* reserved against harness override. The categories answer +different questions: `exports` asks "does the runner set it?", +`reserved` asks "may the harness set it?". + +**`deprecated` — scheduled for removal.** Variables listed here still +function but are slated for removal in a future version. Consumers +should migrate to any documented replacement. The array is empty when no +deprecations are active. + +## Fetching the manifest + +The manifest is fetchable over HTTPS from raw.githubusercontent.com — no +authentication, no repository code execution. The manifest is committed +alongside this README, so every tag that serves this page serves the +manifest at the sibling path: + +```text +https://raw.githubusercontent.com/fullsend-ai/fullsend/refs/tags//docs/normative/sandbox-env/v1/sandbox-env.json +``` + +**The tag is the version.** The manifest deliberately carries no +`fullsend_version` field: a committed file cannot know its future release +version, and stamping one at release time would break the golden invariant +(committed file must byte-match generator output). Consumers pin by URL. + +Consumer validation cadence: + +- **At PR time, validate against the latest released tag.** The released tag + is what production actually runs, so it is the contract a proposed change + must satisfy. +- **Nightly, validate against `main`** + (`https://raw.githubusercontent.com/fullsend-ai/fullsend/refs/heads/main/docs/normative/sandbox-env/v1/sandbox-env.json`). + Released tags lag `main`; the nightly `main` check is the bridge that + catches contract drift within a day + ([ADR 0139](../../../ADRs/0139-agent-functional-test-suite-lives-in-agents-repo.md)). + +Tags released before the manifest landed (v0.48.1 and earlier) return `404` +for this path. A `404` means the pinned tag predates the contract; treat it +as a validation failure (below), not as an empty contract. + +## Treating the manifest as data + +The manifest arrives over the network from a remote host. Treat it as +untrusted input: + +- **Parse, never evaluate.** Feed the bytes to a JSON parser and read names + and gate descriptions as data. Never `eval`, never interpolate fetched + content into a shell command or template. +- **Fail closed.** A fetch that fails, a non-2xx response, a body that does + not parse, or a `schema_version` the consumer does not understand MUST + fail the consumer gate — not pass it. A manifest that cannot be fetched or + parsed is an unverifiable contract, and an unverifiable contract is a + failed check, not a skipped one. + +The manifest is itself a drift-control measure in fullsend's threat model; +publishing names and gate descriptions only — never values — keeps it safe +to fetch and inspect. + +## Regeneration + +Any change to the env-construction emitters changes the derived manifest. +Regenerate the committed file from collector output: + +```sh +go test ./internal/cli -run TestEnvManifestGolden -update +``` + +The golden invariant: the committed manifest must byte-match collector +output. Serialization is deterministic — sorted names, stable field order, +trailing newline — so regenerating without a source change produces a +byte-identical file. The always-on check + +```sh +go test ./internal/cli -run TestEnvManifestGolden +``` + +fails on any divergence between the committed file and the collector's +derivation of the production emitters. + +## Versioning + +Breaking changes require `docs/normative/sandbox-env/v2/`. + +| Change | v1 impact | +|--------|-----------| +| **Breaking** (requires v2): remove or rename schema fields, change a field's type, remove or rename a category, redefine category semantics | Consumers must migrate | +| **Non-breaking** (allowed in v1): add variables or runtimes to any category, refine gate descriptions, add `harness_delivered` provenance entries, add or remove `deprecated` entries | Existing consumers keep working | + +Variable sets change with the contract itself — that is the manifest doing +its job. Consumers pin a tag and compare; the comparison is the drift signal. +`schema_version` versions the document shape; a v2 directory bumps it. diff --git a/docs/normative/sandbox-env/v1/sandbox-env.json b/docs/normative/sandbox-env/v1/sandbox-env.json new file mode 100644 index 0000000000..cd15362977 --- /dev/null +++ b/docs/normative/sandbox-env/v1/sandbox-env.json @@ -0,0 +1,146 @@ +{ + "schema_version": 1, + "exports": { + "always": [ + "FULLSEND_OUTPUT_DIR", + "FULLSEND_ROLE", + "FULLSEND_TARGET_REPO_DIR", + "PATH" + ], + "conditional": { + "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_FETCH_TOKEN": "the runtime fetch service is enabled (ADR 0038)", + "FULLSEND_FETCH_URL": "the runtime fetch service is enabled (ADR 0038)", + "FULLSEND_ITERATION_DEADLINE": "writeIterationEnv succeeds; the run warns and continues when it fails", + "FULLSEND_OUTPUT_FILE": "the legacy runner_env FULLSEND_OUTPUT_FILE is set", + "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_SLUG": "the harness sets a slug", + "FULLSEND_TIMEOUT_MINUTES": "writeIterationEnv succeeds; the run warns and continues when it fails", + "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", + "TRACEPARENT": "writeIterationEnv succeeds; the run warns and continues when it fails" + }, + "runtime_specific": { + "claude": [ + "CLAUDE_CONFIG_DIR" + ], + "codex": [ + "CODEX_HOME", + "FULLSEND_CODEX_HOOK_DIGESTS", + "FULLSEND_CODEX_SPAWN_DIGESTS", + "FULLSEND_RUNTIME", + "RUST_LOG" + ], + "opencode": [ + "FULLSEND_RUNTIME", + "GOOGLE_CLOUD_LOCATION", + "GOOGLE_CLOUD_PROJECT", + "OPENCODE_CONFIG_DIR", + "OPENCODE_DISABLE_EXTERNAL_SKILLS", + "OPENCODE_DISABLE_PROJECT_CONFIG" + ], + "pi": [ + "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", + "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": { + "ANTHROPIC_VERTEX_PROJECT_ID": { + "provenance": "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", + "runner_guaranteed": false + }, + "CLAUDE_CODE_USE_VERTEX": { + "provenance": "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", + "runner_guaranteed": false + }, + "CLOUD_ML_REGION": { + "provenance": "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", + "runner_guaranteed": false + }, + "GOOGLE_APPLICATION_CREDENTIALS": { + "provenance": "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", + "runner_guaranteed": false + } + }, + "reserved": [ + "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_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": [] +} 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..1a5e38d6d7 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 a generated, machine-checkable manifest 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..f66d1898b2 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -281,6 +281,11 @@ 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 — `CLAUDE_CONFIG_DIR` is +claude's one runtime-specific export — and the keys it reserves from +`env.sandbox` are published as a generated, machine-checkable manifest: 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/pi.md b/docs/runtimes/pi.md index bb324c5bd1..b3de112ab6 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 six +runtime-specific exports included — 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..3f4ce0873b --- /dev/null +++ b/internal/cli/env_manifest_collector_test.go @@ -0,0 +1,696 @@ +package cli + +import ( + "maps" + "os" + "path/filepath" + "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", +} + +// envManifestKeyRe matches a KEY= assignment token while excluding $KEY +// references: an emitter's output assigns the names it exports and reads the +// ones it prefixes with $. +var envManifestKeyRe = regexp.MustCompile(`(?:^|[^A-Za-z0-9_$])([A-Za-z_][A-Za-z0-9_]*)=`) + +// 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_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{"CLAUDE_CONFIG_DIR"}}, + {"codex", []string{ + "CODEX_HOME", + "FULLSEND_CODEX_HOOK_DIGESTS", + "FULLSEND_CODEX_SPAWN_DIGESTS", + "FULLSEND_RUNTIME", + "RUST_LOG", + }}, + {"opencode", []string{ + "FULLSEND_RUNTIME", + "GOOGLE_CLOUD_LOCATION", + "GOOGLE_CLOUD_PROJECT", + "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", + "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)) + }) + + 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.False(t, delivered.RunnerGuaranteed, "%q is harness-delivered, not runner-guaranteed", key) + 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_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) { + assert.Equal(t, envmanifest.SchemaVersion, m.SchemaVersion) + first, err := m.Render() + require.NoError(t, err) + second, err := m.Render() + 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) + } + // These variables are assigned readonly WITHOUT export in the + // bootstrap/launch script (env_data.go, runnerPathCaptureLine): the + // sandbox never sees them as env vars, only as shell variables. + // Exclude them from every export category. + readonlyNotExported := map[string]bool{ + "FULLSEND_RUNNER_PATH": true, // runnerPathCaptureLine + "FULLSEND_ENV_PYTHON": true, // envDataPythonVar + "FULLSEND_ENV_EXPORTS": true, // envDataExportsVar + "FULLSEND_TRUSTED_PATH": true, // envDataTrustedPathVar + "FULLSEND_READLINK": true, // envDataReadlinkVar + } + alwaysKeys := map[string]bool{} + conditional := map[string]bool{} + for key := range gatedOn { + if readonlyNotExported[key] { + continue + } + 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 parseExportedEnvKeys(iterationCmd) { + if !readonlyNotExported[key] && !alwaysKeys[key] { + conditional[key] = true + } + } + + for _, key := range traceIDExportKeys(t) { + if !readonlyNotExported[key] && !alwaysKeys[key] { + conditional[key] = true + } + } + for _, key := range hookEnvExportKeys(t) { + if !readonlyNotExported[key] && !alwaysKeys[key] { + conditional[key] = true + } + } + 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 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); the + // builder normalizes the combined list. + keys := append(parseExportedEnvKeys(backend.EnvExports()...), agentruntime.LaunchEnvExportsFor(backend.Runtime)...) + 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 := 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 parseExportedEnvKeys(envManifestCapturedEnv(t, captureDir)) { + keys[key] = true + } + return keys +} + +// traceIDExportKeys runs injectTraceID under the recording stub and returns +// the key its .env append assigns. 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() + argsLog, _ := envManifestOpenshell(t) + require.NoError(t, injectTraceID(envManifestSandboxName, envManifestTraceID)) + return parseExportedEnvKeys(envManifestStubArgs(t, argsLog)...) +} + +// 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() + argsLog, _ := 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)) + // Filter to only args-log lines that write to .env — the + // appendHookEnv pattern "echo 'export KEY=...' >> .env". + // The full Bootstrap also runs env_data launch scripts whose + // shell-internal variables (p, d, s, r, IFS, NAME, etc.) would + // be noise if parsed. + var hookLines []string + for _, line := range envManifestStubArgs(t, argsLog) { + if strings.Contains(line, ".env") { + hookLines = append(hookLines, line) + } + } + return parseExportedEnvKeys(hookLines...) +} + +// 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 that records every +// invocation's arguments to a log and, on a sandbox upload whose local file +// is a fullsend-env-*.sh temp file, copies that file into a capture +// directory. bootstrapEnv composes the sandbox .env in exactly such a temp +// file and uploads it through openshell, so the capture holds the real .env +// content, while the args log carries the export tokens the sandbox-exec +// emitters append. Only openshell is stubbed; tar and the other host tools +// the runtimes shell out to keep working. +func envManifestOpenshell(t *testing.T) (argsLog, captureDir string) { + t.Helper() + base := t.TempDir() + argsLog = filepath.Join(base, "args.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" + + "printf '%s\\n' \"$*\" >> '" + argsLog + "'\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" + + " 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 argsLog, captureDir +} + +// envManifestStubArgs returns the arguments the openshell stub recorded, one +// invocation per line. +func envManifestStubArgs(t *testing.T, argsLog string) []string { + t.Helper() + data, err := os.ReadFile(argsLog) + require.NoError(t, err, "the openshell stub recorded no invocations") + return strings.Split(strings.TrimRight(string(data), "\n"), "\n") +} + +// 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) +} + +// parseExportedEnvKeys returns the distinct KEY names the lines assign, +// sorted. It reads emitter output — .env file content, recorded exec command +// lines, or an EnvExports slice — so the derivation tracks what the emitters +// actually emit. +func parseExportedEnvKeys(lines ...string) []string { + seen := map[string]bool{} + var keys []string + for _, line := range lines { + for _, match := range envManifestKeyRe.FindAllStringSubmatch(line, -1) { + if !seen[match[1]] { + seen[match[1]] = true + keys = append(keys, match[1]) + } + } + } + slices.Sort(keys) + return keys +} + +// 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) 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..a70e943877 --- /dev/null +++ b/internal/cli/env_manifest_golden_test.go @@ -0,0 +1,92 @@ +package cli + +import ( + "bytes" + "flag" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// update rewrites the committed sandbox env manifest 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 manifest at docs/normative/sandbox-env/v1/sandbox-env.json") + +// envManifestGoldenPath locates the committed sandbox env contract manifest, +// repo-relative from internal/cli's test working directory — the same ../.. +// relative-read pattern this package's other repo-root reads use. +var envManifestGoldenPath = filepath.Join("..", "..", "docs", "normative", "sandbox-env", "v1", "sandbox-env.json") + +// TestEnvManifestGolden byte-compares the committed sandbox env contract at +// docs/normative/sandbox-env/v1/sandbox-env.json against 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) { + rendered, err := collectSandboxEnvManifest(t).Render() + require.NoError(t, err, "rendering the collected manifest") + + if *update { + // MkdirAll covers first-time generation: a change that has never + // committed a manifest (or a fresh checkout mid-change) creates the + // normative directory here rather than failing on a missing parent. + require.NoError(t, os.MkdirAll(filepath.Dir(envManifestGoldenPath), 0o755)) + require.NoError(t, os.WriteFile(envManifestGoldenPath, 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, so verify the file now holds the rendered bytes. + written, err := os.ReadFile(envManifestGoldenPath) + require.NoError(t, err, "reading back the rewritten manifest") + assert.Equal(t, rendered, written, "the rewritten manifest must equal collector output byte for byte") + return + } + + committed, err := os.ReadFile(envManifestGoldenPath) + if os.IsNotExist(err) { + t.Fatalf("committed sandbox env manifest %s does not exist (not generated yet); run with -update to create it: go test ./internal/cli -run TestEnvManifestGolden -update", + envManifestGoldenPath) + } + require.NoError(t, err, "reading the committed sandbox env manifest") + + if !bytes.Equal(committed, rendered) { + t.Fatalf("committed sandbox env manifest %s differs from collector output:\n%s\nif the change is intended, regenerate and review the diff: go test ./internal/cli -run TestEnvManifestGolden -update", + envManifestGoldenPath, envManifestDiffSummary(committed, rendered)) + } +} + +// 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..8e76ca768e --- /dev/null +++ b/internal/envmanifest/builder.go @@ -0,0 +1,89 @@ +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 + 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 +} + +// 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. The +// entry is labeled not-runner-guaranteed. +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 stamped with the current schema version and +// every category in canonical form. +func (b *Builder) Build() Manifest { + return Manifest{ + SchemaVersion: SchemaVersion, + Exports: Exports{ + Always: b.always, + Conditional: b.conditional, + RuntimeSpecific: b.runtimeSpecific, + }, + 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..1220522d09 --- /dev/null +++ b/internal/envmanifest/builder_test.go @@ -0,0 +1,65 @@ +package envmanifest + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +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, SchemaVersion, m.SchemaVersion) + 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_EmptyCategoriesRenderEmptyJSON(t *testing.T) { + data, err := NewBuilder().Build().Render() + require.NoError(t, err) + + assert.Contains(t, string(data), `"always": []`) + assert.Contains(t, string(data), `"conditional": {}`) + assert.Contains(t, string(data), `"runtime_specific": {}`) + assert.Contains(t, string(data), `"harness_delivered": {}`) + assert.Contains(t, string(data), `"reserved": []`) + assert.Contains(t, string(data), `"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, SchemaVersion, m.SchemaVersion) + + data, err := m.Render() + require.NoError(t, err) + parsed, err := Parse(data) + require.NoError(t, err) + assert.Equal(t, m, *parsed) +} diff --git a/internal/envmanifest/manifest.go b/internal/envmanifest/manifest.go new file mode 100644 index 0000000000..5b82642e05 --- /dev/null +++ b/internal/envmanifest/manifest.go @@ -0,0 +1,129 @@ +// Package envmanifest defines the sandbox environment-variable contract +// manifest: 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, and which are reserved from harness +// override. Schema: docs/normative/sandbox-env/v1/. +// +// The manifest carries variable names and category metadata only — never +// values or secrets. Serialization is deterministic by contract: sorted +// variable names, stable field order, and a trailing newline, so +// regenerating the committed manifest without a source change produces a +// byte-identical file. The manifest deliberately has no fullsend_version +// field; version identity comes from the tag in the fetch URL, and +// commit-time stamping would break the byte-identical invariant. +package envmanifest + +import ( + "bytes" + "encoding/json" + "fmt" + "slices" +) + +// SchemaVersion is the schema version Builder stamps into every manifest and +// the version the committed contract file reports. +const SchemaVersion = 1 + +// Manifest is the sandbox environment-variable contract. Struct field order +// is the stable serialization order; Render canonicalizes content before +// encoding, so equal content renders byte-identically regardless of how the +// value was assembled. +type Manifest struct { + SchemaVersion int `json:"schema_version"` + Exports Exports `json:"exports"` + HarnessDelivered map[string]HarnessDelivered `json:"harness_delivered"` + Reserved []string `json:"reserved"` + Deprecated []string `json:"deprecated"` +} + +// 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 `json:"always"` + Conditional map[string]string `json:"conditional"` + RuntimeSpecific map[string][]string `json:"runtime_specific"` +} + +// HarnessDelivered describes a variable delivered by stock harness +// configuration rather than by the runner. RunnerGuaranteed is a label, not +// a toggle: it is always false, because a runner-guaranteed variable belongs +// in Exports instead. Render enforces the label so the serialized contract +// always states that harness-delivered variables are not runner guarantees. +type HarnessDelivered struct { + Provenance string `json:"provenance"` + RunnerGuaranteed bool `json:"runner_guaranteed"` +} + +// Render returns the deterministic JSON encoding of m: sorted variable +// names, stable field order, two-space indent, no HTML escaping, and a +// trailing newline. Rendering the same content twice yields identical +// bytes. +func (m Manifest) Render() ([]byte, error) { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + if err := enc.Encode(m.normalized()); err != nil { + return nil, fmt.Errorf("rendering sandbox env manifest: %w", err) + } + return buf.Bytes(), nil +} + +// Parse unmarshals a manifest from its committed JSON form. It is faithful +// to the input: schema_version and every category are preserved as data so +// consumers can branch on manifests fetched from other tags. Treat fetched +// input as untrusted data — parse it, never evaluate it. +func Parse(data []byte) (*Manifest, error) { + var m Manifest + if err := json.Unmarshal(data, &m); err != nil { + return nil, fmt.Errorf("parsing sandbox env manifest: %w", err) + } + return &m, nil +} + +// normalized returns a canonical copy of m: name slices sorted and +// deduplicated, nil categories replaced with empty ones so every section +// renders as [] or {} instead of null, and the harness-delivered +// not-runner-guaranteed label enforced. 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 + } + 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 { + delivered.RunnerGuaranteed = false + harnessDelivered[name] = delivered + } + return Manifest{ + SchemaVersion: m.SchemaVersion, + Exports: Exports{ + Always: sortedUnique(m.Exports.Always), + Conditional: conditional, + RuntimeSpecific: runtimeSpecific, + }, + 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..aba9340fb8 --- /dev/null +++ b/internal/envmanifest/manifest_test.go @@ -0,0 +1,301 @@ +package envmanifest + +import ( + "bytes" + "encoding/json" + "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("FULLSEND_OUTPUT_SCHEMA", "validation_loop.schema configured and uploadable"). + AddRuntimeSpecific("claude", "CLAUDE_CONFIG_DIR"). + AddRuntimeSpecific("opencode"). + AddRuntimeSpecific("pi", "PI_TELEMETRY", "JITI_FS_CACHE"). + AddHarnessDelivered("GOOGLE_APPLICATION_CREDENTIALS", "stock harness configuration: Vertex scaffold; fleet env/gcp-vertex.env"). + AddReserved("GH_WORKFLOW_TOKEN", "OPENAI_API_KEY"). + AddDeprecated("SOME_OLD_VAR"). + Build() +} + +func TestRender_SameInputTwiceIdenticalBytes(t *testing.T) { + m := sampleManifest() + + first, err := m.Render() + require.NoError(t, err) + second, err := m.Render() + require.NoError(t, err) + + assert.True(t, bytes.Equal(first, second), "rendering the same manifest twice must be byte-identical") +} + +func TestRender_InputOrderIndependent(t *testing.T) { + canonical, err := sampleManifest().Render() + require.NoError(t, err) + + // Same content assembled with different slice ordering, a nil runtime + // set, and a tampered runner_guaranteed label: rendering must still + // produce the canonical bytes. + shuffled := Manifest{ + SchemaVersion: 1, + Exports: Exports{ + Always: []string{"PATH", "FULLSEND_OUTPUT_DIR", "FULLSEND_ROLE"}, + Conditional: map[string]string{ + "FULLSEND_SLUG": "harness sets a slug", + "FULLSEND_OUTPUT_SCHEMA": "validation_loop.schema configured and uploadable", + }, + RuntimeSpecific: map[string][]string{ + "pi": {"PI_TELEMETRY", "JITI_FS_CACHE"}, + "opencode": nil, + "claude": {"CLAUDE_CONFIG_DIR"}, + }, + }, + HarnessDelivered: map[string]HarnessDelivered{ + "GOOGLE_APPLICATION_CREDENTIALS": { + Provenance: "stock harness configuration: Vertex scaffold; fleet env/gcp-vertex.env", + RunnerGuaranteed: true, + }, + }, + Reserved: []string{"OPENAI_API_KEY", "GH_WORKFLOW_TOKEN"}, + Deprecated: []string{"SOME_OLD_VAR"}, + } + + rendered, err := shuffled.Render() + require.NoError(t, err) + assert.True(t, bytes.Equal(canonical, rendered), "content order and tampered labels must not affect rendered bytes") + + // Render must not mutate the receiver. + assert.Equal(t, []string{"PATH", "FULLSEND_OUTPUT_DIR", "FULLSEND_ROLE"}, shuffled.Exports.Always) + assert.True(t, shuffled.HarnessDelivered["GOOGLE_APPLICATION_CREDENTIALS"].RunnerGuaranteed) +} + +func TestRender_ExactJSONOutput(t *testing.T) { + data, err := sampleManifest().Render() + require.NoError(t, err) + + expected := `{ + "schema_version": 1, + "exports": { + "always": [ + "FULLSEND_OUTPUT_DIR", + "FULLSEND_ROLE", + "PATH" + ], + "conditional": { + "FULLSEND_OUTPUT_SCHEMA": "validation_loop.schema configured and uploadable", + "FULLSEND_SLUG": "harness sets a slug" + }, + "runtime_specific": { + "claude": [ + "CLAUDE_CONFIG_DIR" + ], + "opencode": [], + "pi": [ + "JITI_FS_CACHE", + "PI_TELEMETRY" + ] + } + }, + "harness_delivered": { + "GOOGLE_APPLICATION_CREDENTIALS": { + "provenance": "stock harness configuration: Vertex scaffold; fleet env/gcp-vertex.env", + "runner_guaranteed": false + } + }, + "reserved": [ + "GH_WORKFLOW_TOKEN", + "OPENAI_API_KEY" + ], + "deprecated": [ + "SOME_OLD_VAR" + ] +} +` + assert.Equal(t, expected, string(data)) +} + +func TestRender_CategorySemantics(t *testing.T) { + tests := []struct { + name string + manifest Manifest + path []string + expected any + }{ + { + name: "always names render under exports.always", + manifest: NewBuilder().AddAlways("PATH", "FULLSEND_ROLE").Build(), + path: []string{"exports", "always"}, + expected: []any{"FULLSEND_ROLE", "PATH"}, + }, + { + name: "conditional values are gate-description strings", + manifest: NewBuilder().AddConditional("FULLSEND_SLUG", "harness sets a slug").Build(), + path: []string{"exports", "conditional"}, + expected: map[string]any{"FULLSEND_SLUG": "harness sets a slug"}, + }, + { + name: "runtime_specific maps runtime to variable names", + manifest: NewBuilder().AddRuntimeSpecific("claude", "CLAUDE_CONFIG_DIR").Build(), + path: []string{"exports", "runtime_specific"}, + expected: map[string]any{"claude": []any{"CLAUDE_CONFIG_DIR"}}, + }, + { + name: "runtime with an explicitly empty export set renders an empty array", + manifest: NewBuilder().AddRuntimeSpecific("opencode").Build(), + path: []string{"exports", "runtime_specific", "opencode"}, + expected: []any{}, + }, + { + name: "harness_delivered entries carry provenance and the not-runner-guaranteed label", + manifest: NewBuilder().AddHarnessDelivered("CLOUD_ML_REGION", "Vertex scaffold").Build(), + path: []string{"harness_delivered", "CLOUD_ML_REGION"}, + expected: map[string]any{"provenance": "Vertex scaffold", "runner_guaranteed": false}, + }, + { + name: "reserved names render under reserved", + manifest: NewBuilder().AddReserved("GH_WORKFLOW_TOKEN").Build(), + path: []string{"reserved"}, + expected: []any{"GH_WORKFLOW_TOKEN"}, + }, + { + name: "deprecated names render under deprecated", + manifest: NewBuilder().AddDeprecated("SOME_OLD_VAR").Build(), + path: []string{"deprecated"}, + expected: []any{"SOME_OLD_VAR"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + data, err := tt.manifest.Render() + require.NoError(t, err) + + var doc map[string]any + require.NoError(t, json.Unmarshal(data, &doc)) + + var got any = doc + for _, key := range tt.path { + obj, ok := got.(map[string]any) + require.True(t, ok, "path segment %q must resolve to a JSON object", key) + got = obj[key] + } + assert.Equal(t, tt.expected, got) + }) + } +} + +func TestRender_HarnessDeliveredLabelEnforced(t *testing.T) { + m := NewBuilder(). + AddHarnessDelivered("CLOUD_ML_REGION", "Vertex scaffold"). + Build() + delivered := m.HarnessDelivered["CLOUD_ML_REGION"] + delivered.RunnerGuaranteed = true + m.HarnessDelivered["CLOUD_ML_REGION"] = delivered + + data, err := m.Render() + require.NoError(t, err) + + var doc map[string]any + require.NoError(t, json.Unmarshal(data, &doc)) + + entry, ok := doc["harness_delivered"].(map[string]any)["CLOUD_ML_REGION"].(map[string]any) + require.True(t, ok, "harness-delivered entry must render as a JSON object") + + label, ok := entry["runner_guaranteed"].(bool) + require.True(t, ok, "runner_guaranteed must render as a present JSON boolean") + assert.False(t, label, "Render enforces the not-runner-guaranteed label even when the input is tampered true") +} + +func TestRoundTripParse(t *testing.T) { + m := sampleManifest() + + data, err := m.Render() + require.NoError(t, err) + + parsed, err := Parse(data) + require.NoError(t, err) + assert.Equal(t, m, *parsed) + + reRendered, err := parsed.Render() + require.NoError(t, err) + assert.True(t, bytes.Equal(data, reRendered), "parse must preserve the rendered bytes") +} + +func TestRender_ZeroValue(t *testing.T) { + var m Manifest + + data, err := m.Render() + require.NoError(t, err) + assert.NotContains(t, string(data), "null", "empty categories must render as [] or {}, not null") + + parsed, err := Parse(data) + require.NoError(t, err) + assert.Empty(t, parsed.Exports.Always) + assert.Empty(t, parsed.Exports.Conditional) + assert.Empty(t, parsed.Exports.RuntimeSpecific) + assert.Empty(t, parsed.HarnessDelivered) + assert.Empty(t, parsed.Reserved) + assert.Empty(t, parsed.Deprecated) +} + +func TestParse_PreservesSchemaVersion(t *testing.T) { + data, err := Manifest{SchemaVersion: 2}.Render() + require.NoError(t, err) + + parsed, err := Parse(data) + require.NoError(t, err) + assert.Equal(t, 2, parsed.SchemaVersion, "schema_version is data, not stamping") +} + +func TestParse_InvalidJSON(t *testing.T) { + _, err := Parse([]byte("{not json")) + require.Error(t, err) + assert.ErrorContains(t, err, "parsing sandbox env manifest") +} + +// namesOnlyFieldTypes is the complete field inventory of the manifest +// types. The names-only invariant (design D8) 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.SchemaVersion": "int", + "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", + "HarnessDelivered.Provenance": "string", + "HarnessDelivered.RunnerGuaranteed": "bool", +} + +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/runtime/codex.go b/internal/runtime/codex.go index e396fd5d63..38caa0fadf 100644 --- a/internal/runtime/codex.go +++ b/internal/runtime/codex.go @@ -106,6 +106,21 @@ 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 is always set +// (stderr filtering for the codex server); the two digest variables 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. +func (CodexRuntime) LaunchEnvExports() []string { + return []string{ + codexRuntimeEnv, + "RUST_LOG", + codexHookDigestsEnv, + codexSpawnDigestsEnv, + } +} + // Compile-time interface assertions. var ( _ Runtime = CodexRuntime{} @@ -113,5 +128,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..74c34187b2 --- /dev/null +++ b/internal/runtime/launchenv_test.go @@ -0,0 +1,76 @@ +package runtime + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +// TestLaunchEnvExportsFor pins the launch-export contract: runtimes whose +// launch commands export environment variables beyond EnvExports() list +// those bare names, and runtimes without such exports report none. Expected +// values are literals on purpose so a constant rename cannot silently +// drift the published sandbox env manifest contract. +func TestLaunchEnvExportsFor(t *testing.T) { + tests := []struct { + name string + rt Runtime + want []string + }{ + { + name: "pi", + rt: PiRuntime{}, + want: []string{ + "FULLSEND_RUNTIME", + "FULLSEND_PI_MANIFEST", + "FULLSEND_PI_MANIFEST_SHA256", + "FULLSEND_PI_HOOK_PYTHON", + "FULLSEND_PI_HOOK_PATH", + "FULLSEND_PI_CHILD_BIN", + "FULLSEND_PI_CHILD_NODE", + "GOOGLE_CLOUD_LOCATION", + "GOOGLE_CLOUD_PROJECT", + "XAI_VERTEX_PROJECT_ID", + }, + }, + { + name: "codex", + rt: CodexRuntime{}, + want: []string{ + "FULLSEND_RUNTIME", + "RUST_LOG", + "FULLSEND_CODEX_HOOK_DIGESTS", + "FULLSEND_CODEX_SPAWN_DIGESTS", + }, + }, + { + name: "opencode", + rt: OpenCodeRuntime{}, + want: []string{ + "FULLSEND_RUNTIME", + "GOOGLE_CLOUD_PROJECT", + "GOOGLE_CLOUD_LOCATION", + }, + }, + { + name: "claude has no launch exports beyond EnvExports", + rt: ClaudeRuntime{}, + want: nil, + }, + { + name: "dummy has no launch exports", + rt: DummyRuntime{}, + want: nil, + }, + { + name: "dummy-playback has no launch exports", + rt: DummyPlaybackRuntime{}, + want: nil, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equal(t, tt.want, LaunchEnvExportsFor(tt.rt)) + }) + } +} diff --git a/internal/runtime/opencode.go b/internal/runtime/opencode.go index 277f4812bc..9f579b4f15 100644 --- a/internal/runtime/opencode.go +++ b/internal/runtime/opencode.go @@ -61,9 +61,24 @@ func (r OpenCodeRuntime) EnvExports() []string { } } +// LaunchEnvExports implements LaunchEnvExporter: the environment names +// buildOpenCodeRunCommand sets beyond EnvExports. The Vertex project +// mapping is always exported; 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. +func (OpenCodeRuntime) LaunchEnvExports() []string { + return []string{ + openCodeRuntimeEnv, + "GOOGLE_CLOUD_PROJECT", + "GOOGLE_CLOUD_LOCATION", + } +} + // 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..d870a5c239 100644 --- a/internal/runtime/pi.go +++ b/internal/runtime/pi.go @@ -153,6 +153,29 @@ 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. +func (PiRuntime) LaunchEnvExports() []string { + return []string{ + piRuntimeEnv, + piManifestEnv, + piManifestSumEnv, + piHookPythonEnv, + piHookPathEnv, + piChildBinEnv, + piChildNodeEnv, + "GOOGLE_CLOUD_LOCATION", + "GOOGLE_CLOUD_PROJECT", + "XAI_VERTEX_PROJECT_ID", + } +} + // Compile-time interface assertions. var ( _ Runtime = PiRuntime{} @@ -160,5 +183,6 @@ var ( _ DebugLogNamer = PiRuntime{} _ ProviderResolver = PiRuntime{} + _ LaunchEnvExporter = PiRuntime{} _ OpenAICredentialSeeder = PiRuntime{} ) diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 2c604ed61d..441fb3ac1e 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -290,3 +290,27 @@ 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 +// (claude, dummy, dummy-playback) must not implement this; hook-env keys the +// bootstrap injects are covered separately by the conditional category. +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 +} From 0f17e2d948f42a260b1ebbb09e535123f56a7c34 Mon Sep 17 00:00:00 2001 From: Jay Flowers Date: Tue, 3 Nov 2026 15:14:23 -0500 Subject: [PATCH 2/4] refactor(envmanifest): publish sandbox env contract as JSON Schema Replace the bespoke sandbox-env.json with two generated, self-contained Draft 2020-12 schemas, per review: every other docs/normative contract is JSON Schema, and consumers can validate with stock tooling. - harness-env.schema.json rejects reserved keys in a harness's env.sandbox blocks (top level and forge..env). - env-references.schema.json checks that code running under a runtime (or "portable") reads only reachable variables; its $defs carry the full inventory, with gates and provenance as const descriptions. Make collection export-aware (review finding): a new envmanifest.ExportedNames parser recognizes export statements, bare re-exports, and prefix assignments, and ignores shell-local assignments, quoted data, and command substitutions. The collector replays the commands that write sandbox env files in a scratch workspace instead of regex-matching their text. This surfaces OPENCODE_CONFIG_CONTENT, which the regex missed. Pin LaunchEnvExports to the launch commands (review finding): TestLaunchEnvExportsMatchLaunchCommands builds each runtime's launch command across hooks, gateway, auth-mode and provider variants and requires the declared list to equal what they export. Claude now implements LaunchEnvExporter, and the lists gain the names they were missing (CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC and the gateway variables, INFERENCE_GATEWAY_*, codex FULLSEND_TRUSTED_PATH, opencode HOME). Scope the ADR and README to the sandbox; host-side script env is out of scope. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jay Flowers --- ...6-sandbox-environment-contract-manifest.md | 99 ++-- docs/architecture.md | 4 +- docs/contributing/runtime-implementation.md | 12 +- docs/normative/sandbox-env/v1/README.md | 332 +++++++------- .../sandbox-env/v1/env-references.schema.json | 425 ++++++++++++++++++ .../sandbox-env/v1/harness-env.schema.json | 121 +++++ .../normative/sandbox-env/v1/sandbox-env.json | 146 ------ docs/problems/security-threat-model.md | 2 +- docs/runtimes/claude.md | 8 +- docs/runtimes/codex.md | 1 + docs/runtimes/opencode.md | 1 + docs/runtimes/pi.md | 4 +- internal/cli/env_manifest_collector_test.go | 209 +++++---- internal/cli/env_manifest_golden_test.go | 77 ++-- internal/envmanifest/builder.go | 7 +- internal/envmanifest/builder_test.go | 24 +- internal/envmanifest/manifest.go | 94 +--- internal/envmanifest/manifest_test.go | 273 +---------- internal/envmanifest/schema.go | 288 ++++++++++++ internal/envmanifest/schema_test.go | 208 +++++++++ internal/envmanifest/shellexports.go | 284 ++++++++++++ internal/envmanifest/shellexports_test.go | 46 ++ internal/runtime/claude.go | 19 + internal/runtime/codex.go | 17 +- internal/runtime/launchenv_test.go | 155 ++++--- internal/runtime/opencode.go | 10 +- internal/runtime/pi.go | 8 +- internal/runtime/runtime.go | 6 +- 28 files changed, 1963 insertions(+), 917 deletions(-) create mode 100644 docs/normative/sandbox-env/v1/env-references.schema.json create mode 100644 docs/normative/sandbox-env/v1/harness-env.schema.json delete mode 100644 docs/normative/sandbox-env/v1/sandbox-env.json create mode 100644 internal/envmanifest/schema.go create mode 100644 internal/envmanifest/schema_test.go create mode 100644 internal/envmanifest/shellexports.go create mode 100644 internal/envmanifest/shellexports_test.go diff --git a/docs/ADRs/0146-sandbox-environment-contract-manifest.md b/docs/ADRs/0146-sandbox-environment-contract-manifest.md index 6a5a704a69..1d2794412e 100644 --- a/docs/ADRs/0146-sandbox-environment-contract-manifest.md +++ b/docs/ADRs/0146-sandbox-environment-contract-manifest.md @@ -37,11 +37,13 @@ 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` +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. @@ -49,51 +51,76 @@ is a follow-up to close the remaining drift surface. - **Hand-maintained manifest** — rejected: it recreates the drift (#1677 passed review the same way). -- **Behavior-level golden over `bootstrapEnv`** — strongest check, - but needs fixtures for every emission gate; hardening follow-up. +- **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 a generated, committed manifest -at [`sandbox-env.json`](../normative/sandbox-env/v1/sandbox-env.json), with -schema and category semantics in its [README](../normative/sandbox-env/v1/README.md). -A build-time collector generates the manifest by running every code -path that injects environment variables into the sandbox — the +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 [`bootstrapEnv` `.env` emission](https://github.com/fullsend-ai/fullsend/blob/487169a9da/internal/cli/run.go#L3836-L3871), -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 — so the contract cannot disagree with the code -that builds the environment. An always-on golden test byte-compares the -committed file against collector output (`-update` regenerates); a -companion runtime-enumeration test fails when a runtime is newly -registered without a manifest decision. - -The manifest is 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 tag itself is -the version identifier, so the manifest carries no embedded -`fullsend_version` field. Consumers validate -env-var reachability against the latest released tag at PR time +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. +[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 manifest - bump, visible in the diff. -- Content repos gain a fail-closed gate: a failed or unparseable manifest +- 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 manifest is derived contract data — no runtime cost or behavior change. -- `harness_delivered` variables are labeled not-runner-guaranteed: their - provenance is the stock scaffold and may lag the fleet's `gcp-vertex.env`. +- 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 manifest is forge-agnostic: it describes the variables the runner +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 diff --git a/docs/architecture.md b/docs/architecture.md index 6f8f03db70..82bd9ae8cc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -93,7 +93,7 @@ each target repository's **`.fullsend/`** directory within the sandbox? (The environment-variable dimension is now a published, generated contract — [ADR 0146](ADRs/0146-sandbox-environment-contract-manifest.md), - [manifest](normative/sandbox-env/v1/README.md); tools, runtimes, + [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. @@ -142,7 +142,7 @@ repo baseline and overrides) [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 a generated, tag-pinned manifest enforced by an always-on + 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 diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 9ebe80367d..8e2b6256e1 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -65,9 +65,9 @@ content that must be updated whenever a runtime is added or renamed. `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 manifest decision fails + registering a runtime without a contract decision fails `TestEnvManifestRuntimeEnumeration`, and `TestEnvManifestGolden` pins the - committed manifest content (regenerate with + committed schemas (regenerate with `go test ./internal/cli -run TestEnvManifestGolden -update`). **CLI:** @@ -220,7 +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 manifest collector unions them into that runtime's `runtime_specific` set (`docs/normative/sandbox-env/v1/`). pi, codex, and opencode implement it; runtimes whose launch commands export nothing new omit it | +| `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)). @@ -415,9 +415,9 @@ Two traps when reproducing by hand: The runner-written rows in this table are entries in the generated [sandbox environment contract](../normative/sandbox-env/v1/README.md) — the -machine-checkable manifest of every variable the runner injects into the -sandbox, per gate and per runtime, and of the keys it reserves from harness -override. The manifest is the source of truth; this table is prose. +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 diff --git a/docs/normative/sandbox-env/v1/README.md b/docs/normative/sandbox-env/v1/README.md index 97c679bb35..ae983120c0 100644 --- a/docs/normative/sandbox-env/v1/README.md +++ b/docs/normative/sandbox-env/v1/README.md @@ -1,219 +1,191 @@ -# Sandbox environment contract v1 +# 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 a generated, versioned, -machine-readable manifest so consumers can verify env-var reachability -against a released runner instead of hand-maintained mirrors — the -transitional lockstep between fullsend and the fleet harnesses it loads -([ADR 0058](../../../ADRs/0058-agent-registration.md)) becomes verifiable -rather than assumed +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)). -## Contract - -- **Manifest:** [`sandbox-env.json`](sandbox-env.json) — the committed, - generated contract document. It is authoritative; this README describes it. -- **Generated, never hand-authored:** the collector in - `internal/cli/env_manifest_collector_test.go` derives the manifest by - running 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. -- **Golden invariant:** `internal/cli/env_manifest_golden_test.go` - byte-compares the committed file against collector output on every test - run, so the published contract cannot drift from the code that builds the - sandbox environment. A hand edit, or a code change shipped without - regenerating, fails the test. -- **Names only, never values:** the manifest records variable names, - category membership, gate descriptions, and provenance — no credentials or - configuration values. Every name is already public in fullsend's source. - -## Schema - -| Field | Type | Semantics | -|-------|------|-----------| -| `schema_version` | integer | Shape version of this document; currently `1`. Check it before interpreting anything else — a version the consumer does not understand is a contract it cannot validate. | -| `exports.always` | array of strings | Variables the runner injects into every sandbox it builds (four in v1). | -| `exports.conditional` | object: variable name → gate description | Variables the runner injects only when the described gate holds (twelve in v1). Each description is the emitter's actual guard, transcribed from the production code. | -| `exports.runtime_specific` | object: runtime name → array of strings | Variables emitted only by the named runtime — its `EnvExports()` plus the environment its launch command sets: `claude`, `codex`, `opencode`, `pi`. | -| `harness_delivered` | object: variable name → `{ "provenance": string, "runner_guaranteed": boolean }` | Variables delivered by stock harness configuration, not by the runner (four in v1). `runner_guaranteed` is always `false` — a label, not a toggle: a variable the runner guarantees belongs in `exports` instead. `provenance` names the configuration that delivers it. | -| `reserved` | array of strings | Keys the runner reserves from harness override (62 in v1): `env.sandbox` cannot set them. The set merges the base runner-infrastructure keys, the OIDC-denied and provider-only credential keys, and the security-critical credential keys (`IsReservedCredentialKey`) at startup. | -| `deprecated` | array of strings | Variables that are deprecated and scheduled for removal in a future version. Consumers should migrate away from these variables. Empty when no deprecations are active. | - -Abridged shape (see [`sandbox-env.json`](sandbox-env.json) for the full -document): +**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 — at the top level and under `forge..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'} +``` + +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 -{ - "schema_version": 1, - "exports": { - "always": ["FULLSEND_OUTPUT_DIR", "FULLSEND_ROLE", "FULLSEND_TARGET_REPO_DIR", "PATH"], - "conditional": { - "FULLSEND_FETCH_URL": "the runtime fetch service is enabled (ADR 0038)" - }, - "runtime_specific": { - "claude": ["CLAUDE_CONFIG_DIR"], - "opencode": ["OPENCODE_CONFIG_DIR", "..."] - } - }, - "harness_delivered": { - "GOOGLE_APPLICATION_CREDENTIALS": { - "provenance": "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", - "runner_guaranteed": false - } - }, - "reserved": ["BASH_ENV", "HOME", "LD_PRELOAD"], - "deprecated": [] -} +{"runtime": "pi", "variables": ["FULLSEND_OUTPUT_DIR", "FULLSEND_TARGET_REPO_DIR"]} ``` -## Category semantics - -The categories form a guarantee ladder. Consumers should read them as -answers to "what may I rely on?", not as a flat inventory. - -**`always` and `conditional` — runner-guaranteed, modulo gates.** Every -fullsend runner injects the `always` variables into every sandbox it builds. -A `conditional` variable is guaranteed exactly when its gate holds — for -example, `FULLSEND_FETCH_URL` and `FULLSEND_FETCH_TOKEN` arrive when the -runtime fetch service is enabled -([ADR 0038](../../../ADRs/0038-universal-harness-access.md)), and -`FULLSEND_TRACE_ID` when trace-ID injection succeeds (injection is -best-effort; on failure the run warns and continues). Within their gates, -these two categories are universally reachable: a harness may rely on them -under any runtime. 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. - -**`runtime_specific` — guaranteed only when that runtime runs.** Both halves -matter: - -- When dispatch executes under a runtime, that runtime's listed variables are - reachable: a run under `claude` always has `CLAUDE_CONFIG_DIR`; a run - under `pi` sees its listed variables, with provider-path names like - `GOOGLE_CLOUD_PROJECT` set only on the paths that select them. -- Across runtimes, they are a portability gap, not a guarantee: nothing - promises `CLAUDE_CONFIG_DIR` under `codex` or `pi`. A harness that reads a - runtime-specific variable is coupled to that runtime and breaks when - configuration changes the runtime. - -The enumerated runtimes are the runner's resolution registry minus test -stubs. A runtime that emits nothing appears with an empty set rather than -being omitted. Registering a new runtime without a manifest decision -fails `TestEnvManifestRuntimeEnumeration`, which pins the collector's -runtime list to the resolution registry; the golden test covers the -committed manifest content. - -**`harness_delivered` — configuration, not guarantee.** These variables reach -the sandbox only because stock harness configuration injects them: +`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. + +**`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` are delivered by the -`fullsend agent new` Vertex scaffold through `env.sandbox` plus a host file, -and fleet harnesses deliver these plus `GOOGLE_CLOUD_PROJECT` and -`ANTHROPIC_DEFAULT_SONNET_MODEL` through `env/gcp-vertex.env` -in fullsend-ai/agents (see each entry's `provenance`). The runner never -injects them — `runner_guaranteed: false` — so a hand-authored harness that +`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` — stripped from harness override.** Harness `env.sandbox` -entries naming these keys are skipped with a warning: the runner removes -them so harness configuration cannot shadow runner infrastructure, inject -OIDC and provider credentials, or override security-critical process -variables (e.g. `HTTPS_PROXY`, `LD_PRELOAD`, `NODE_OPTIONS`). A key may -appear both here and in an export category — `PATH` is exported by the -runner *and* reserved against harness override. The categories answer -different questions: `exports` asks "does the runner set it?", -`reserved` asks "may the harness set it?". - -**`deprecated` — scheduled for removal.** Variables listed here still -function but are slated for removal in a future version. Consumers -should migrate to any documented replacement. The array is empty when no +**`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 manifest +## Fetching -The manifest is fetchable over HTTPS from raw.githubusercontent.com — no -authentication, no repository code execution. The manifest is committed -alongside this README, so every tag that serves this page serves the -manifest at the sibling path: +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 -https://raw.githubusercontent.com/fullsend-ai/fullsend/refs/tags//docs/normative/sandbox-env/v1/sandbox-env.json +BASE=https://raw.githubusercontent.com/fullsend-ai/fullsend/refs/tags//docs/normative/sandbox-env/v1 ``` -**The tag is the version.** The manifest deliberately carries no -`fullsend_version` field: a committed file cannot know its future release -version, and stamping one at release time would break the golden invariant -(committed file must byte-match generator output). Consumers pin by URL. +**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. -Consumer validation cadence: +Validation cadence: -- **At PR time, validate against the latest released tag.** The released tag - is what production actually runs, so it is the contract a proposed change - must satisfy. -- **Nightly, validate against `main`** - (`https://raw.githubusercontent.com/fullsend-ai/fullsend/refs/heads/main/docs/normative/sandbox-env/v1/sandbox-env.json`). - Released tags lag `main`; the nightly `main` check is the bridge that - catches contract drift within a day +- **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 manifest landed (v0.48.1 and earlier) return `404` -for this path. A `404` means the pinned tag predates the contract; treat it -as a validation failure (below), not as an empty contract. +Tags released before the contract landed return `404` for these paths. -## Treating the manifest as data +## Treating the schemas as data -The manifest arrives over the network from a remote host. Treat it as -untrusted input: +The schemas arrive over the network. Treat them as untrusted input: -- **Parse, never evaluate.** Feed the bytes to a JSON parser and read names - and gate descriptions as data. Never `eval`, never interpolate fetched - content into a shell command or template. -- **Fail closed.** A fetch that fails, a non-2xx response, a body that does - not parse, or a `schema_version` the consumer does not understand MUST - fail the consumer gate — not pass it. A manifest that cannot be fetched or - parsed is an unverifiable contract, and an unverifiable contract is a - failed check, not a skipped one. +- **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 manifest is itself a drift-control measure in fullsend's threat model; -publishing names and gate descriptions only — never values — keeps it safe -to fetch and inspect. +The schemas carry names and gate descriptions only — never values — so +they are safe to fetch and inspect. ## Regeneration -Any change to the env-construction emitters changes the derived manifest. -Regenerate the committed file from collector output: +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 golden invariant: the committed manifest must byte-match collector -output. Serialization is deterministic — sorted names, stable field order, -trailing newline — so regenerating without a source change produces a -byte-identical file. The always-on check - -```sh -go test ./internal/cli -run TestEnvManifestGolden -``` - -fails on any divergence between the committed file and the collector's -derivation of the production emitters. +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 require `docs/normative/sandbox-env/v2/`. +Breaking changes to the schemas' shape require +`docs/normative/sandbox-env/v2/`. -| Change | v1 impact | -|--------|-----------| -| **Breaking** (requires v2): remove or rename schema fields, change a field's type, remove or rename a category, redefine category semantics | Consumers must migrate | -| **Non-breaking** (allowed in v1): add variables or runtimes to any category, refine gate descriptions, add `harness_delivered` provenance entries, add or remove `deprecated` entries | Existing consumers keep working | +| 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 contract itself — that is the manifest doing -its job. Consumers pin a tag and compare; the comparison is the drift signal. -`schema_version` versions the document shape; a v2 directory bumps it. +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..d9f4410213 --- /dev/null +++ b/docs/normative/sandbox-env/v1/env-references.schema.json @@ -0,0 +1,425 @@ +{ + "$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" + }, + { + "$ref": "#/$defs/conditional" + }, + { + "$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" + }, + { + "$ref": "#/$defs/conditional" + }, + { + "$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.", + "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..8858535431 --- /dev/null +++ b/docs/normative/sandbox-env/v1/harness-env.schema.json @@ -0,0 +1,121 @@ +{ + "$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 and forge..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, because the runner drops reserved keys 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" + } + } + } + } + }, + "$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.", + "type": "object", + "propertyNames": { + "allOf": [ + { + "$ref": "#/$defs/env_name" + }, + { + "not": { + "$ref": "#/$defs/reserved" + } + } + ] + } + }, + "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" + ] + } + } +} diff --git a/docs/normative/sandbox-env/v1/sandbox-env.json b/docs/normative/sandbox-env/v1/sandbox-env.json deleted file mode 100644 index cd15362977..0000000000 --- a/docs/normative/sandbox-env/v1/sandbox-env.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "schema_version": 1, - "exports": { - "always": [ - "FULLSEND_OUTPUT_DIR", - "FULLSEND_ROLE", - "FULLSEND_TARGET_REPO_DIR", - "PATH" - ], - "conditional": { - "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_FETCH_TOKEN": "the runtime fetch service is enabled (ADR 0038)", - "FULLSEND_FETCH_URL": "the runtime fetch service is enabled (ADR 0038)", - "FULLSEND_ITERATION_DEADLINE": "writeIterationEnv succeeds; the run warns and continues when it fails", - "FULLSEND_OUTPUT_FILE": "the legacy runner_env FULLSEND_OUTPUT_FILE is set", - "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_SLUG": "the harness sets a slug", - "FULLSEND_TIMEOUT_MINUTES": "writeIterationEnv succeeds; the run warns and continues when it fails", - "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", - "TRACEPARENT": "writeIterationEnv succeeds; the run warns and continues when it fails" - }, - "runtime_specific": { - "claude": [ - "CLAUDE_CONFIG_DIR" - ], - "codex": [ - "CODEX_HOME", - "FULLSEND_CODEX_HOOK_DIGESTS", - "FULLSEND_CODEX_SPAWN_DIGESTS", - "FULLSEND_RUNTIME", - "RUST_LOG" - ], - "opencode": [ - "FULLSEND_RUNTIME", - "GOOGLE_CLOUD_LOCATION", - "GOOGLE_CLOUD_PROJECT", - "OPENCODE_CONFIG_DIR", - "OPENCODE_DISABLE_EXTERNAL_SKILLS", - "OPENCODE_DISABLE_PROJECT_CONFIG" - ], - "pi": [ - "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", - "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": { - "ANTHROPIC_VERTEX_PROJECT_ID": { - "provenance": "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", - "runner_guaranteed": false - }, - "CLAUDE_CODE_USE_VERTEX": { - "provenance": "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", - "runner_guaranteed": false - }, - "CLOUD_ML_REGION": { - "provenance": "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", - "runner_guaranteed": false - }, - "GOOGLE_APPLICATION_CREDENTIALS": { - "provenance": "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", - "runner_guaranteed": false - } - }, - "reserved": [ - "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_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": [] -} diff --git a/docs/problems/security-threat-model.md b/docs/problems/security-threat-model.md index 1a5e38d6d7..73316f86d3 100644 --- a/docs/problems/security-threat-model.md +++ b/docs/problems/security-threat-model.md @@ -190,7 +190,7 @@ Drift becomes detectable when you have a declared baseline to measure against. A 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 a generated, machine-checkable manifest rather than +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)). diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index f66d1898b2..65d842f396 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -281,9 +281,11 @@ 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 — `CLAUDE_CONFIG_DIR` is -claude's one runtime-specific export — and the keys it reserves from -`env.sandbox` are published as a generated, machine-checkable manifest: the +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 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 b3de112ab6..72115a97e0 100644 --- a/docs/runtimes/pi.md +++ b/docs/runtimes/pi.md @@ -841,8 +841,8 @@ 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. What the runner itself injects — pi's six -runtime-specific exports included — and the keys it reserves from harness override are published +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 diff --git a/internal/cli/env_manifest_collector_test.go b/internal/cli/env_manifest_collector_test.go index 3f4ce0873b..1b8563ae0d 100644 --- a/internal/cli/env_manifest_collector_test.go +++ b/internal/cli/env_manifest_collector_test.go @@ -3,6 +3,7 @@ package cli import ( "maps" "os" + "os/exec" "path/filepath" "regexp" "slices" @@ -65,11 +66,6 @@ var sandboxEnvGates = map[string]string{ "TRACEPARENT": "writeIterationEnv succeeds; the run warns and continues when it fails", } -// envManifestKeyRe matches a KEY= assignment token while excluding $KEY -// references: an emitter's output assigns the names it exports and reads the -// ones it prefixes with $. -var envManifestKeyRe = regexp.MustCompile(`(?:^|[^A-Za-z0-9_$])([A-Za-z_][A-Za-z0-9_]*)=`) - // 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". @@ -90,6 +86,7 @@ func TestEnvManifestCollector(t *testing.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", @@ -140,18 +137,29 @@ func TestEnvManifestCollector(t *testing.T) { runtime string want []string }{ - {"claude", []string{"CLAUDE_CONFIG_DIR"}}, + {"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", @@ -166,6 +174,9 @@ func TestEnvManifestCollector(t *testing.T) { "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", @@ -182,6 +193,22 @@ func TestEnvManifestCollector(t *testing.T) { 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", @@ -193,7 +220,6 @@ func TestEnvManifestCollector(t *testing.T) { slices.Sort(got) assert.Equal(t, want, got) for key, delivered := range m.HarnessDelivered { - assert.False(t, delivered.RunnerGuaranteed, "%q is harness-delivered, not runner-guaranteed", key) assert.Equal(t, envManifestProvenance, delivered.Provenance, "provenance for %q", key) } }) @@ -226,6 +252,7 @@ func TestEnvManifestCollector(t *testing.T) { "FULLSEND_OUTPUT_DIR", "FULLSEND_OUTPUT_FILE", "FULLSEND_OUTPUT_SCHEMA", + "FULLSEND_PERSONAS_FILE", "FULLSEND_ROLE", "FULLSEND_RUNNER_PATH", "FULLSEND_SLUG", @@ -266,10 +293,9 @@ func TestEnvManifestCollector(t *testing.T) { }) t.Run("renders deterministically", func(t *testing.T) { - assert.Equal(t, envmanifest.SchemaVersion, m.SchemaVersion) - first, err := m.Render() + first, err := m.RenderSchemas() require.NoError(t, err) - second, err := m.Render() + second, err := m.RenderSchemas() require.NoError(t, err) assert.Equal(t, first, second) }) @@ -356,23 +382,9 @@ func collectSandboxEnvManifest(t *testing.T) *envmanifest.Manifest { for key := range gatedOff { require.True(t, gatedOn[key], "bootstrapEnv emits %q only with its gates off", key) } - // These variables are assigned readonly WITHOUT export in the - // bootstrap/launch script (env_data.go, runnerPathCaptureLine): the - // sandbox never sees them as env vars, only as shell variables. - // Exclude them from every export category. - readonlyNotExported := map[string]bool{ - "FULLSEND_RUNNER_PATH": true, // runnerPathCaptureLine - "FULLSEND_ENV_PYTHON": true, // envDataPythonVar - "FULLSEND_ENV_EXPORTS": true, // envDataExportsVar - "FULLSEND_TRUSTED_PATH": true, // envDataTrustedPathVar - "FULLSEND_READLINK": true, // envDataReadlinkVar - } alwaysKeys := map[string]bool{} conditional := map[string]bool{} for key := range gatedOn { - if readonlyNotExported[key] { - continue - } if gatedOff[key] { b.AddAlways(key) alwaysKeys[key] = true @@ -382,19 +394,19 @@ func collectSandboxEnvManifest(t *testing.T) *envmanifest.Manifest { } iterationCmd := iterationEnvCommand(30, time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), envManifestTraceparent) - for _, key := range parseExportedEnvKeys(iterationCmd) { - if !readonlyNotExported[key] && !alwaysKeys[key] { + for _, key := range sandboxEnvFileKeys(t, iterationCmd) { + if !alwaysKeys[key] { conditional[key] = true } } for _, key := range traceIDExportKeys(t) { - if !readonlyNotExported[key] && !alwaysKeys[key] { + if !alwaysKeys[key] { conditional[key] = true } } for _, key := range hookEnvExportKeys(t) { - if !readonlyNotExported[key] && !alwaysKeys[key] { + if !alwaysKeys[key] { conditional[key] = true } } @@ -411,9 +423,13 @@ func collectSandboxEnvManifest(t *testing.T) *envmanifest.Manifest { 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); the - // builder normalizes the combined list. - keys := append(parseExportedEnvKeys(backend.EnvExports()...), agentruntime.LaunchEnvExportsFor(backend.Runtime)...) + // 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...) } @@ -440,7 +456,7 @@ func collectSandboxEnvManifest(t *testing.T) *envmanifest.Manifest { // its emission is unconditional in practice. func bootstrapEnvExportKeys(t *testing.T, gated bool) map[string]bool { t.Helper() - _, captureDir := envManifestOpenshell(t) + captureDir := envManifestCaptureDir(envManifestOpenshell(t)) h := &harness.Harness{Role: envManifestAgentName} var fetch []fetchServiceEnv if gated { @@ -453,20 +469,21 @@ func bootstrapEnvExportKeys(t *testing.T, gated bool) map[string]bool { } require.NoError(t, bootstrapEnv(envManifestSandboxName, "/workspace/repo", h, nil, fetch...)) keys := map[string]bool{} - for _, key := range parseExportedEnvKeys(envManifestCapturedEnv(t, captureDir)) { + for _, key := range envmanifest.ExportedNames(envManifestCapturedEnv(t, captureDir)) { keys[key] = true } return keys } -// traceIDExportKeys runs injectTraceID under the recording stub and returns -// the key its .env append assigns. The emitter's call site only warns on -// failure, so the derived key is conditional, not always. +// 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() - argsLog, _ := envManifestOpenshell(t) + execLog := envManifestOpenshell(t) require.NoError(t, injectTraceID(envManifestSandboxName, envManifestTraceID)) - return parseExportedEnvKeys(envManifestStubArgs(t, argsLog)...) + return sandboxEnvFileKeys(t, envManifestEnvWrites(t, execLog)...) } // hookEnvExportKeys derives the security-hook env keys (TIRITH_FAIL_ON, @@ -478,7 +495,7 @@ func traceIDExportKeys(t *testing.T) []string { // guard on the harness security config. func hookEnvExportKeys(t *testing.T) []string { t.Helper() - argsLog, _ := envManifestOpenshell(t) + 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{ @@ -492,18 +509,7 @@ func hookEnvExportKeys(t *testing.T) []string { hooks: security.SandboxHookConfigFromHarness(h), } require.NoError(t, agentruntime.ClaudeRuntime{}.Bootstrap(in)) - // Filter to only args-log lines that write to .env — the - // appendHookEnv pattern "echo 'export KEY=...' >> .env". - // The full Bootstrap also runs env_data launch scripts whose - // shell-internal variables (p, d, s, r, IFS, NAME, etc.) would - // be noise if parsed. - var hookLines []string - for _, line := range envManifestStubArgs(t, argsLog) { - if strings.Contains(line, ".env") { - hookLines = append(hookLines, line) - } - } - return parseExportedEnvKeys(hookLines...) + return sandboxEnvFileKeys(t, envManifestEnvWrites(t, execLog)...) } // envManifestScaffoldOptions builds a valid agent-new Options whose @@ -576,24 +582,23 @@ func harnessDeliveredKeys(t *testing.T) []string { return keys } -// envManifestOpenshell installs an openshell stub on PATH that records every -// invocation's arguments to a log and, on a sandbox upload whose local file -// is a fullsend-env-*.sh temp file, copies that file into a capture -// directory. bootstrapEnv composes the sandbox .env in exactly such a temp -// file and uploads it through openshell, so the capture holds the real .env -// content, while the args log carries the export tokens the sandbox-exec -// emitters append. Only openshell is stubbed; tar and the other host tools -// the runtimes shell out to keep working. -func envManifestOpenshell(t *testing.T) (argsLog, captureDir string) { +// 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() - argsLog = filepath.Join(base, "args.log") - captureDir = filepath.Join(base, "captured") + 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" + - "printf '%s\\n' \"$*\" >> '" + argsLog + "'\n" + "if [ \"$1\" = \"sandbox\" ] && [ \"$2\" = \"upload\" ]; then\n" + " case \"$5\" in\n" + " *fullsend-env-*) cp \"$5\" '" + captureDir + "/' ;;\n" + @@ -602,6 +607,7 @@ func envManifestOpenshell(t *testing.T) (argsLog, captureDir string) { "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" + @@ -615,16 +621,58 @@ func envManifestOpenshell(t *testing.T) (argsLog, captureDir string) { "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 argsLog, captureDir + 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 } -// envManifestStubArgs returns the arguments the openshell stub recorded, one -// invocation per line. -func envManifestStubArgs(t *testing.T, argsLog string) []string { +// 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() - data, err := os.ReadFile(argsLog) - require.NoError(t, err, "the openshell stub recorded no invocations") - return strings.Split(strings.TrimRight(string(data), "\n"), "\n") + 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 @@ -639,25 +687,6 @@ func envManifestCapturedEnv(t *testing.T, captureDir string) string { return string(data) } -// parseExportedEnvKeys returns the distinct KEY names the lines assign, -// sorted. It reads emitter output — .env file content, recorded exec command -// lines, or an EnvExports slice — so the derivation tracks what the emitters -// actually emit. -func parseExportedEnvKeys(lines ...string) []string { - seen := map[string]bool{} - var keys []string - for _, line := range lines { - for _, match := range envManifestKeyRe.FindAllStringSubmatch(line, -1) { - if !seen[match[1]] { - seen[match[1]] = true - keys = append(keys, match[1]) - } - } - } - slices.Sort(keys) - return keys -} - // envManifestBootstrapInput implements runtime.BootstrapInput and // runtime.SandboxHooksBootstrap for the hook-env derivation, mirroring the // bootstrap inputs internal/runtime's own tests use. @@ -684,6 +713,8 @@ func (i envManifestBootstrapInput) AgentSubagents() map[string]*string { return 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 { diff --git a/internal/cli/env_manifest_golden_test.go b/internal/cli/env_manifest_golden_test.go index a70e943877..2820117c92 100644 --- a/internal/cli/env_manifest_golden_test.go +++ b/internal/cli/env_manifest_golden_test.go @@ -11,54 +11,67 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/envmanifest" ) -// update rewrites the committed sandbox env manifest from collector output, +// 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 manifest at docs/normative/sandbox-env/v1/sandbox-env.json") +var update = flag.Bool("update", false, "rewrite the committed sandbox env schemas under docs/normative/sandbox-env/v1/") -// envManifestGoldenPath locates the committed sandbox env contract manifest, +// 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 envManifestGoldenPath = filepath.Join("..", "..", "docs", "normative", "sandbox-env", "v1", "sandbox-env.json") +var envManifestSchemaDir = filepath.Join("..", "..", "docs", "normative", "sandbox-env", "v1") -// TestEnvManifestGolden byte-compares the committed sandbox env contract at -// docs/normative/sandbox-env/v1/sandbox-env.json against the manifest the -// collector derives by executing the production emitters, so the published -// contract cannot drift from the code that builds the sandbox environment. +// 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) { - rendered, err := collectSandboxEnvManifest(t).Render() - require.NoError(t, err, "rendering the collected manifest") + 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)) - if *update { - // MkdirAll covers first-time generation: a change that has never - // committed a manifest (or a fresh checkout mid-change) creates the - // normative directory here rather than failing on a missing parent. - require.NoError(t, os.MkdirAll(filepath.Dir(envManifestGoldenPath), 0o755)) - require.NoError(t, os.WriteFile(envManifestGoldenPath, 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, so verify the file now holds the rendered bytes. - written, err := os.ReadFile(envManifestGoldenPath) - require.NoError(t, err, "reading back the rewritten manifest") - assert.Equal(t, rendered, written, "the rewritten manifest must equal collector output byte for byte") - return - } + 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(envManifestGoldenPath) - if os.IsNotExist(err) { - t.Fatalf("committed sandbox env manifest %s does not exist (not generated yet); run with -update to create it: go test ./internal/cli -run TestEnvManifestGolden -update", - envManifestGoldenPath) + 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)) + } + }) } - require.NoError(t, err, "reading the committed sandbox env manifest") +} - if !bytes.Equal(committed, rendered) { - t.Fatalf("committed sandbox env manifest %s differs from collector output:\n%s\nif the change is intended, regenerate and review the diff: go test ./internal/cli -run TestEnvManifestGolden -update", - envManifestGoldenPath, 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 diff --git a/internal/envmanifest/builder.go b/internal/envmanifest/builder.go index 8e76ca768e..b41d273315 100644 --- a/internal/envmanifest/builder.go +++ b/internal/envmanifest/builder.go @@ -49,8 +49,7 @@ func (b *Builder) AddRuntimeSpecific(runtime string, names ...string) *Builder { } // AddHarnessDelivered records a variable delivered by stock harness -// configuration, with provenance describing where the delivery happens. The -// entry is labeled not-runner-guaranteed. +// 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{} @@ -72,11 +71,9 @@ func (b *Builder) AddDeprecated(names ...string) *Builder { return b } -// Build returns the manifest stamped with the current schema version and -// every category in canonical form. +// Build returns the manifest with every category in canonical form. func (b *Builder) Build() Manifest { return Manifest{ - SchemaVersion: SchemaVersion, Exports: Exports{ Always: b.always, Conditional: b.conditional, diff --git a/internal/envmanifest/builder_test.go b/internal/envmanifest/builder_test.go index 1220522d09..6c397d6537 100644 --- a/internal/envmanifest/builder_test.go +++ b/internal/envmanifest/builder_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestBuilder_CanonicalForm(t *testing.T) { @@ -18,7 +17,6 @@ func TestBuilder_CanonicalForm(t *testing.T) { AddDeprecated("OLD_VAR_B", "OLD_VAR_A", "OLD_VAR_B"). Build() - assert.Equal(t, SchemaVersion, m.SchemaVersion) 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{ @@ -32,18 +30,6 @@ func TestBuilder_CanonicalForm(t *testing.T) { assert.Equal(t, []string{"OLD_VAR_A", "OLD_VAR_B"}, m.Deprecated) } -func TestBuilder_EmptyCategoriesRenderEmptyJSON(t *testing.T) { - data, err := NewBuilder().Build().Render() - require.NoError(t, err) - - assert.Contains(t, string(data), `"always": []`) - assert.Contains(t, string(data), `"conditional": {}`) - assert.Contains(t, string(data), `"runtime_specific": {}`) - assert.Contains(t, string(data), `"harness_delivered": {}`) - assert.Contains(t, string(data), `"reserved": []`) - assert.Contains(t, string(data), `"deprecated": []`) -} - func TestBuilder_ZeroValueUsable(t *testing.T) { var b Builder m := b. @@ -55,11 +41,7 @@ func TestBuilder_ZeroValueUsable(t *testing.T) { AddDeprecated("LEGACY_VAR"). Build() - assert.Equal(t, SchemaVersion, m.SchemaVersion) - - data, err := m.Render() - require.NoError(t, err) - parsed, err := Parse(data) - require.NoError(t, err) - assert.Equal(t, m, *parsed) + 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 index 5b82642e05..8ac483741f 100644 --- a/internal/envmanifest/manifest.go +++ b/internal/envmanifest/manifest.go @@ -1,91 +1,47 @@ -// Package envmanifest defines the sandbox environment-variable contract -// manifest: which variables the runner injects into the sandbox, under what +// 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, and which are reserved from harness -// override. Schema: docs/normative/sandbox-env/v1/. +// 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 manifest carries variable names and category metadata only — never -// values or secrets. Serialization is deterministic by contract: sorted -// variable names, stable field order, and a trailing newline, so -// regenerating the committed manifest without a source change produces a -// byte-identical file. The manifest deliberately has no fullsend_version -// field; version identity comes from the tag in the fetch URL, and -// commit-time stamping would break the byte-identical invariant. +// 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 ( - "bytes" - "encoding/json" - "fmt" - "slices" -) +import "slices" -// SchemaVersion is the schema version Builder stamps into every manifest and -// the version the committed contract file reports. -const SchemaVersion = 1 - -// Manifest is the sandbox environment-variable contract. Struct field order -// is the stable serialization order; Render canonicalizes content before -// encoding, so equal content renders byte-identically regardless of how the -// value was assembled. +// Manifest is the sandbox environment-variable contract model. type Manifest struct { - SchemaVersion int `json:"schema_version"` - Exports Exports `json:"exports"` - HarnessDelivered map[string]HarnessDelivered `json:"harness_delivered"` - Reserved []string `json:"reserved"` - Deprecated []string `json:"deprecated"` + 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 `json:"always"` - Conditional map[string]string `json:"conditional"` - RuntimeSpecific map[string][]string `json:"runtime_specific"` + Always []string + Conditional map[string]string + RuntimeSpecific map[string][]string } // HarnessDelivered describes a variable delivered by stock harness -// configuration rather than by the runner. RunnerGuaranteed is a label, not -// a toggle: it is always false, because a runner-guaranteed variable belongs -// in Exports instead. Render enforces the label so the serialized contract -// always states that harness-delivered variables are not runner guarantees. +// 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 `json:"provenance"` - RunnerGuaranteed bool `json:"runner_guaranteed"` -} - -// Render returns the deterministic JSON encoding of m: sorted variable -// names, stable field order, two-space indent, no HTML escaping, and a -// trailing newline. Rendering the same content twice yields identical -// bytes. -func (m Manifest) Render() ([]byte, error) { - var buf bytes.Buffer - enc := json.NewEncoder(&buf) - enc.SetEscapeHTML(false) - enc.SetIndent("", " ") - if err := enc.Encode(m.normalized()); err != nil { - return nil, fmt.Errorf("rendering sandbox env manifest: %w", err) - } - return buf.Bytes(), nil -} - -// Parse unmarshals a manifest from its committed JSON form. It is faithful -// to the input: schema_version and every category are preserved as data so -// consumers can branch on manifests fetched from other tags. Treat fetched -// input as untrusted data — parse it, never evaluate it. -func Parse(data []byte) (*Manifest, error) { - var m Manifest - if err := json.Unmarshal(data, &m); err != nil { - return nil, fmt.Errorf("parsing sandbox env manifest: %w", err) - } - return &m, nil + Provenance string } // normalized returns a canonical copy of m: name slices sorted and // deduplicated, nil categories replaced with empty ones so every section -// renders as [] or {} instead of null, and the harness-delivered -// not-runner-guaranteed label enforced. m itself is not modified. +// 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 { @@ -97,11 +53,9 @@ func (m Manifest) normalized() Manifest { } harnessDelivered := make(map[string]HarnessDelivered, len(m.HarnessDelivered)) for name, delivered := range m.HarnessDelivered { - delivered.RunnerGuaranteed = false harnessDelivered[name] = delivered } return Manifest{ - SchemaVersion: m.SchemaVersion, Exports: Exports{ Always: sortedUnique(m.Exports.Always), Conditional: conditional, diff --git a/internal/envmanifest/manifest_test.go b/internal/envmanifest/manifest_test.go index aba9340fb8..ebf05c2d0b 100644 --- a/internal/envmanifest/manifest_test.go +++ b/internal/envmanifest/manifest_test.go @@ -1,8 +1,6 @@ package envmanifest import ( - "bytes" - "encoding/json" "reflect" "testing" @@ -16,266 +14,43 @@ func sampleManifest() Manifest { return NewBuilder(). AddAlways("PATH", "FULLSEND_ROLE", "FULLSEND_OUTPUT_DIR"). AddConditional("FULLSEND_SLUG", "harness sets a slug"). - AddConditional("FULLSEND_OUTPUT_SCHEMA", "validation_loop.schema configured and uploadable"). + AddConditional("TRACEPARENT", "writeIterationEnv succeeds"). AddRuntimeSpecific("claude", "CLAUDE_CONFIG_DIR"). AddRuntimeSpecific("opencode"). AddRuntimeSpecific("pi", "PI_TELEMETRY", "JITI_FS_CACHE"). - AddHarnessDelivered("GOOGLE_APPLICATION_CREDENTIALS", "stock harness configuration: Vertex scaffold; fleet env/gcp-vertex.env"). - AddReserved("GH_WORKFLOW_TOKEN", "OPENAI_API_KEY"). - AddDeprecated("SOME_OLD_VAR"). + AddHarnessDelivered("GOOGLE_APPLICATION_CREDENTIALS", "stock harness configuration: Vertex scaffold"). + AddReserved("GH_WORKFLOW_TOKEN", "OPENAI_API_KEY", "TRACEPARENT"). + AddDeprecated("FULLSEND_ROLE"). Build() } -func TestRender_SameInputTwiceIdenticalBytes(t *testing.T) { - m := sampleManifest() - - first, err := m.Render() - require.NoError(t, err) - second, err := m.Render() - require.NoError(t, err) - - assert.True(t, bytes.Equal(first, second), "rendering the same manifest twice must be byte-identical") -} - -func TestRender_InputOrderIndependent(t *testing.T) { - canonical, err := sampleManifest().Render() - require.NoError(t, err) - - // Same content assembled with different slice ordering, a nil runtime - // set, and a tampered runner_guaranteed label: rendering must still - // produce the canonical bytes. - shuffled := Manifest{ - SchemaVersion: 1, +func TestNormalized_DoesNotMutateReceiver(t *testing.T) { + m := Manifest{ Exports: Exports{ - Always: []string{"PATH", "FULLSEND_OUTPUT_DIR", "FULLSEND_ROLE"}, - Conditional: map[string]string{ - "FULLSEND_SLUG": "harness sets a slug", - "FULLSEND_OUTPUT_SCHEMA": "validation_loop.schema configured and uploadable", - }, - RuntimeSpecific: map[string][]string{ - "pi": {"PI_TELEMETRY", "JITI_FS_CACHE"}, - "opencode": nil, - "claude": {"CLAUDE_CONFIG_DIR"}, - }, - }, - HarnessDelivered: map[string]HarnessDelivered{ - "GOOGLE_APPLICATION_CREDENTIALS": { - Provenance: "stock harness configuration: Vertex scaffold; fleet env/gcp-vertex.env", - RunnerGuaranteed: true, - }, + Always: []string{"B", "A"}, + Conditional: map[string]string{"C": "gate"}, }, - Reserved: []string{"OPENAI_API_KEY", "GH_WORKFLOW_TOKEN"}, - Deprecated: []string{"SOME_OLD_VAR"}, - } - - rendered, err := shuffled.Render() - require.NoError(t, err) - assert.True(t, bytes.Equal(canonical, rendered), "content order and tampered labels must not affect rendered bytes") - - // Render must not mutate the receiver. - assert.Equal(t, []string{"PATH", "FULLSEND_OUTPUT_DIR", "FULLSEND_ROLE"}, shuffled.Exports.Always) - assert.True(t, shuffled.HarnessDelivered["GOOGLE_APPLICATION_CREDENTIALS"].RunnerGuaranteed) -} - -func TestRender_ExactJSONOutput(t *testing.T) { - data, err := sampleManifest().Render() - require.NoError(t, err) - - expected := `{ - "schema_version": 1, - "exports": { - "always": [ - "FULLSEND_OUTPUT_DIR", - "FULLSEND_ROLE", - "PATH" - ], - "conditional": { - "FULLSEND_OUTPUT_SCHEMA": "validation_loop.schema configured and uploadable", - "FULLSEND_SLUG": "harness sets a slug" - }, - "runtime_specific": { - "claude": [ - "CLAUDE_CONFIG_DIR" - ], - "opencode": [], - "pi": [ - "JITI_FS_CACHE", - "PI_TELEMETRY" - ] - } - }, - "harness_delivered": { - "GOOGLE_APPLICATION_CREDENTIALS": { - "provenance": "stock harness configuration: Vertex scaffold; fleet env/gcp-vertex.env", - "runner_guaranteed": false - } - }, - "reserved": [ - "GH_WORKFLOW_TOKEN", - "OPENAI_API_KEY" - ], - "deprecated": [ - "SOME_OLD_VAR" - ] -} -` - assert.Equal(t, expected, string(data)) -} - -func TestRender_CategorySemantics(t *testing.T) { - tests := []struct { - name string - manifest Manifest - path []string - expected any - }{ - { - name: "always names render under exports.always", - manifest: NewBuilder().AddAlways("PATH", "FULLSEND_ROLE").Build(), - path: []string{"exports", "always"}, - expected: []any{"FULLSEND_ROLE", "PATH"}, - }, - { - name: "conditional values are gate-description strings", - manifest: NewBuilder().AddConditional("FULLSEND_SLUG", "harness sets a slug").Build(), - path: []string{"exports", "conditional"}, - expected: map[string]any{"FULLSEND_SLUG": "harness sets a slug"}, - }, - { - name: "runtime_specific maps runtime to variable names", - manifest: NewBuilder().AddRuntimeSpecific("claude", "CLAUDE_CONFIG_DIR").Build(), - path: []string{"exports", "runtime_specific"}, - expected: map[string]any{"claude": []any{"CLAUDE_CONFIG_DIR"}}, - }, - { - name: "runtime with an explicitly empty export set renders an empty array", - manifest: NewBuilder().AddRuntimeSpecific("opencode").Build(), - path: []string{"exports", "runtime_specific", "opencode"}, - expected: []any{}, - }, - { - name: "harness_delivered entries carry provenance and the not-runner-guaranteed label", - manifest: NewBuilder().AddHarnessDelivered("CLOUD_ML_REGION", "Vertex scaffold").Build(), - path: []string{"harness_delivered", "CLOUD_ML_REGION"}, - expected: map[string]any{"provenance": "Vertex scaffold", "runner_guaranteed": false}, - }, - { - name: "reserved names render under reserved", - manifest: NewBuilder().AddReserved("GH_WORKFLOW_TOKEN").Build(), - path: []string{"reserved"}, - expected: []any{"GH_WORKFLOW_TOKEN"}, - }, - { - name: "deprecated names render under deprecated", - manifest: NewBuilder().AddDeprecated("SOME_OLD_VAR").Build(), - path: []string{"deprecated"}, - expected: []any{"SOME_OLD_VAR"}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - data, err := tt.manifest.Render() - require.NoError(t, err) - - var doc map[string]any - require.NoError(t, json.Unmarshal(data, &doc)) - - var got any = doc - for _, key := range tt.path { - obj, ok := got.(map[string]any) - require.True(t, ok, "path segment %q must resolve to a JSON object", key) - got = obj[key] - } - assert.Equal(t, tt.expected, got) - }) } -} - -func TestRender_HarnessDeliveredLabelEnforced(t *testing.T) { - m := NewBuilder(). - AddHarnessDelivered("CLOUD_ML_REGION", "Vertex scaffold"). - Build() - delivered := m.HarnessDelivered["CLOUD_ML_REGION"] - delivered.RunnerGuaranteed = true - m.HarnessDelivered["CLOUD_ML_REGION"] = delivered - - data, err := m.Render() - require.NoError(t, err) - - var doc map[string]any - require.NoError(t, json.Unmarshal(data, &doc)) - - entry, ok := doc["harness_delivered"].(map[string]any)["CLOUD_ML_REGION"].(map[string]any) - require.True(t, ok, "harness-delivered entry must render as a JSON object") - - label, ok := entry["runner_guaranteed"].(bool) - require.True(t, ok, "runner_guaranteed must render as a present JSON boolean") - assert.False(t, label, "Render enforces the not-runner-guaranteed label even when the input is tampered true") -} - -func TestRoundTripParse(t *testing.T) { - m := sampleManifest() - - data, err := m.Render() - require.NoError(t, err) - - parsed, err := Parse(data) - require.NoError(t, err) - assert.Equal(t, m, *parsed) - - reRendered, err := parsed.Render() - require.NoError(t, err) - assert.True(t, bytes.Equal(data, reRendered), "parse must preserve the rendered bytes") -} - -func TestRender_ZeroValue(t *testing.T) { - var m Manifest - - data, err := m.Render() - require.NoError(t, err) - assert.NotContains(t, string(data), "null", "empty categories must render as [] or {}, not null") - - parsed, err := Parse(data) - require.NoError(t, err) - assert.Empty(t, parsed.Exports.Always) - assert.Empty(t, parsed.Exports.Conditional) - assert.Empty(t, parsed.Exports.RuntimeSpecific) - assert.Empty(t, parsed.HarnessDelivered) - assert.Empty(t, parsed.Reserved) - assert.Empty(t, parsed.Deprecated) -} - -func TestParse_PreservesSchemaVersion(t *testing.T) { - data, err := Manifest{SchemaVersion: 2}.Render() - require.NoError(t, err) - - parsed, err := Parse(data) - require.NoError(t, err) - assert.Equal(t, 2, parsed.SchemaVersion, "schema_version is data, not stamping") -} - -func TestParse_InvalidJSON(t *testing.T) { - _, err := Parse([]byte("{not json")) - require.Error(t, err) - assert.ErrorContains(t, err, "parsing sandbox env manifest") + 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 (design D8) 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. +// 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.SchemaVersion": "int", - "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", - "HarnessDelivered.Provenance": "string", - "HarnessDelivered.RunnerGuaranteed": "bool", + "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", + "HarnessDelivered.Provenance": "string", } func TestManifest_NamesOnlyFieldInventory(t *testing.T) { diff --git a/internal/envmanifest/schema.go b/internal/envmanifest/schema.go new file mode 100644 index 0000000000..673b51137e --- /dev/null +++ b/internal/envmanifest/schema.go @@ -0,0 +1,288 @@ +package envmanifest + +import ( + "bytes" + "encoding/json" + "fmt" + "slices" +) + +// 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 and forge..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, because the runner drops reserved keys 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")}}}, + }}, + }}, + }}, + {"$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."}, + {"type", "object"}, + {"propertyNames", object{{"allOf", []any{ + ref("#/$defs/env_name"), + object{{"not", ref("#/$defs/reserved")}}, + }}}}, + }}, + {"env_name", envNameSchema()}, + {"reserved", m.reservedSchema()}, + }}, + } +} + +func (m Manifest) envReferencesSchema() object { + runtimes := m.Runtimes() + runtimeEnum := append([]string{PortableRuntime}, runtimes...) + shared := []any{ref("#/$defs/always"), ref("#/$defs/conditional"), ref("#/$defs/harness_delivered")} + + var perRuntime []any + perRuntime = append(perRuntime, reachableWhen(PortableRuntime, shared)) + for _, rt := range runtimes { + perRuntime = append(perRuntime, reachableWhen(rt, append(slices.Clone(shared), 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."}, + {"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) +} + +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..58333bf145 --- /dev/null +++ b/internal/envmanifest/schema_test.go @@ -0,0 +1,208 @@ +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"). + 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}`, + ) + assert.Equal(t, "ok", verdicts[0]) + assert.Contains(t, verdicts[1], "invalid") + assert.Contains(t, verdicts[2], "invalid") + assert.Contains(t, verdicts[3], "invalid") + assert.Equal(t, "ok", verdicts[4]) +} + +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"]}`, + // 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"}, verdicts[:2]) + for i, v := range verdicts[2:] { + assert.Contains(t, v, "invalid", "instance %d", i+2) + } +} 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 38caa0fadf..029b097783 100644 --- a/internal/runtime/codex.go +++ b/internal/runtime/codex.go @@ -107,17 +107,24 @@ func (r CodexRuntime) OpenAIAuthSeed() string { } // LaunchEnvExports implements LaunchEnvExporter: the environment names -// buildCodexRunCommand sets beyond EnvExports. RUST_LOG is always set -// (stderr filtering for the codex server); the two digest variables 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. +// 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", } } diff --git a/internal/runtime/launchenv_test.go b/internal/runtime/launchenv_test.go index 74c34187b2..6bfe1f59e6 100644 --- a/internal/runtime/launchenv_test.go +++ b/internal/runtime/launchenv_test.go @@ -1,76 +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" ) -// TestLaunchEnvExportsFor pins the launch-export contract: runtimes whose -// launch commands export environment variables beyond EnvExports() list -// those bare names, and runtimes without such exports report none. Expected -// values are literals on purpose so a constant rename cannot silently -// drift the published sandbox env manifest contract. -func TestLaunchEnvExportsFor(t *testing.T) { - tests := []struct { - name string - rt Runtime - want []string - }{ - { - name: "pi", - rt: PiRuntime{}, - want: []string{ - "FULLSEND_RUNTIME", - "FULLSEND_PI_MANIFEST", - "FULLSEND_PI_MANIFEST_SHA256", - "FULLSEND_PI_HOOK_PYTHON", - "FULLSEND_PI_HOOK_PATH", - "FULLSEND_PI_CHILD_BIN", - "FULLSEND_PI_CHILD_NODE", - "GOOGLE_CLOUD_LOCATION", - "GOOGLE_CLOUD_PROJECT", - "XAI_VERTEX_PROJECT_ID", - }, - }, - { - name: "codex", - rt: CodexRuntime{}, - want: []string{ - "FULLSEND_RUNTIME", - "RUST_LOG", - "FULLSEND_CODEX_HOOK_DIGESTS", - "FULLSEND_CODEX_SPAWN_DIGESTS", - }, - }, - { - name: "opencode", - rt: OpenCodeRuntime{}, - want: []string{ - "FULLSEND_RUNTIME", - "GOOGLE_CLOUD_PROJECT", - "GOOGLE_CLOUD_LOCATION", - }, - }, - { - name: "claude has no launch exports beyond EnvExports", - rt: ClaudeRuntime{}, - want: nil, - }, - { - name: "dummy has no launch exports", - rt: DummyRuntime{}, - want: nil, - }, - { - name: "dummy-playback has no launch exports", - rt: DummyPlaybackRuntime{}, - want: nil, - }, +// 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")) } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - assert.Equal(t, tt.want, LaunchEnvExportsFor(tt.rt)) + 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 9f579b4f15..4aefdb5b6b 100644 --- a/internal/runtime/opencode.go +++ b/internal/runtime/opencode.go @@ -63,15 +63,19 @@ func (r OpenCodeRuntime) EnvExports() []string { // LaunchEnvExports implements LaunchEnvExporter: the environment names // buildOpenCodeRunCommand sets beyond EnvExports. The Vertex project -// mapping is always exported; the location is exported only when the -// composed value is non-empty and is recorded flat anyway: +// 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. +// 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", } } diff --git a/internal/runtime/pi.go b/internal/runtime/pi.go index d870a5c239..348dccfa9e 100644 --- a/internal/runtime/pi.go +++ b/internal/runtime/pi.go @@ -160,7 +160,10 @@ func (r PiRuntime) EnvExports() []string { // 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 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, @@ -173,6 +176,9 @@ func (PiRuntime) LaunchEnvExports() []string { "GOOGLE_CLOUD_LOCATION", "GOOGLE_CLOUD_PROJECT", "XAI_VERTEX_PROJECT_ID", + piInferenceGatewayBaseURLEnv, + piInferenceGatewayTokenFileEnv, + piInferenceGatewayConfigFileEnv, } } diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 441fb3ac1e..52bc85d215 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -299,8 +299,10 @@ func GenAISystemFor(rt Runtime, model, agentModel string, aliases map[string]str // 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 -// (claude, dummy, dummy-playback) must not implement this; hook-env keys the -// bootstrap injects are covered separately by the conditional category. +// (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 From 7130c962804eb9986323d17be55ab1a436673dbb Mon Sep 17 00:00:00 2001 From: Jay Flowers Date: Thu, 5 Nov 2026 07:06:52 -0500 Subject: [PATCH 3/4] fix(envmanifest): match runner reserved-key and hook-env semantics in schemas The runner upper-cases an env.sandbox key before the reserved lookup and reads env from overlays as well as forge entries, but the harness schema matched reserved names case-sensitively and left overlays[].env unconstrained, so traceparent or an overlay's OPENAI_API_KEY validated and was then silently dropped. Add a reserved_any_case pattern (each letter as a two-case class, since JSON Schema patterns have no case-insensitive flag) and validate overlays[].env with env_block. Hook env (TIRITH_FAIL_ON, TIRITH_REQUIRED, FULLSEND_EGRESS_ALLOWLIST) is appended only by runtimes whose Bootstrap reaches appendHookEnv, yet every runtime admitted the whole conditional category, so opencode and portable claims validated for names those sandboxes never see. Model the restriction as Exports.ConditionalRuntimes; the collector derives the runtime set from internal/runtime's call graph and checks each gate description names the runtimes it excludes. Regenerated the schemas. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jay Flowers --- docs/normative/sandbox-env/v1/README.md | 15 ++- .../sandbox-env/v1/env-references.schema.json | 32 ++++- .../sandbox-env/v1/harness-env.schema.json | 21 ++- internal/cli/env_manifest_collector_test.go | 120 ++++++++++++++++++ internal/envmanifest/builder.go | 31 +++-- internal/envmanifest/manifest.go | 16 ++- internal/envmanifest/manifest_test.go | 3 + internal/envmanifest/schema.go | 83 ++++++++++-- internal/envmanifest/schema_test.go | 33 ++++- 9 files changed, 317 insertions(+), 37 deletions(-) diff --git a/docs/normative/sandbox-env/v1/README.md b/docs/normative/sandbox-env/v1/README.md index ae983120c0..8fdc070924 100644 --- a/docs/normative/sandbox-env/v1/README.md +++ b/docs/normative/sandbox-env/v1/README.md @@ -18,7 +18,7 @@ not describe it. | 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 — at the top level and under `forge..env` | +| [`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 @@ -34,11 +34,14 @@ 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'} +$.env.sandbox: 'TRACEPARENT' should not be valid under {'$ref': '#/$defs/reserved_any_case'} ``` -The schema constrains only the env blocks; other harness fields pass -through. `fullsend lint` performs the same reserved-key check in-process +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 @@ -79,7 +82,9 @@ 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. +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` diff --git a/docs/normative/sandbox-env/v1/env-references.schema.json b/docs/normative/sandbox-env/v1/env-references.schema.json index d9f4410213..8a3f5f8f0e 100644 --- a/docs/normative/sandbox-env/v1/env-references.schema.json +++ b/docs/normative/sandbox-env/v1/env-references.schema.json @@ -42,7 +42,20 @@ "$ref": "#/$defs/always" }, { - "$ref": "#/$defs/conditional" + "allOf": [ + { + "$ref": "#/$defs/conditional" + }, + { + "not": { + "enum": [ + "FULLSEND_EGRESS_ALLOWLIST", + "TIRITH_FAIL_ON", + "TIRITH_REQUIRED" + ] + } + } + ] }, { "$ref": "#/$defs/harness_delivered" @@ -141,7 +154,20 @@ "$ref": "#/$defs/always" }, { - "$ref": "#/$defs/conditional" + "allOf": [ + { + "$ref": "#/$defs/conditional" + }, + { + "not": { + "enum": [ + "FULLSEND_EGRESS_ALLOWLIST", + "TIRITH_FAIL_ON", + "TIRITH_REQUIRED" + ] + } + } + ] }, { "$ref": "#/$defs/harness_delivered" @@ -216,7 +242,7 @@ ] }, "conditional": { - "description": "Exported by the runner only when the gate in each entry's description holds.", + "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", diff --git a/docs/normative/sandbox-env/v1/harness-env.schema.json b/docs/normative/sandbox-env/v1/harness-env.schema.json index 8858535431..9831c65f7b 100644 --- a/docs/normative/sandbox-env/v1/harness-env.schema.json +++ b/docs/normative/sandbox-env/v1/harness-env.schema.json @@ -2,7 +2,7 @@ "$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 and forge..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, because the runner drops reserved keys instead of exporting them. Other harness fields are not constrained here. Generated from the runner's code (ADR 0146); see README.md.", + "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": { @@ -18,6 +18,17 @@ } } } + }, + "overlays": { + "type": "array", + "items": { + "type": "object", + "properties": { + "env": { + "$ref": "#/$defs/env_block" + } + } + } } }, "$defs": { @@ -30,7 +41,7 @@ } }, "sandbox_env": { - "description": "Variables a harness delivers into the sandbox. The runner owns the reserved names and refuses them here.", + "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": [ @@ -39,7 +50,7 @@ }, { "not": { - "$ref": "#/$defs/reserved" + "$ref": "#/$defs/reserved_any_case" } } ] @@ -116,6 +127,10 @@ "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/internal/cli/env_manifest_collector_test.go b/internal/cli/env_manifest_collector_test.go index 1b8563ae0d..b52081624a 100644 --- a/internal/cli/env_manifest_collector_test.go +++ b/internal/cli/env_manifest_collector_test.go @@ -1,10 +1,14 @@ package cli import ( + "go/ast" + "go/parser" + "go/token" "maps" "os" "os/exec" "path/filepath" + "reflect" "regexp" "slices" "strings" @@ -405,16 +409,35 @@ func collectSandboxEnvManifest(t *testing.T) *envmanifest.Manifest { 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) } @@ -512,6 +535,103 @@ func hookEnvExportKeys(t *testing.T) []string { 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. diff --git a/internal/envmanifest/builder.go b/internal/envmanifest/builder.go index b41d273315..4d47142664 100644 --- a/internal/envmanifest/builder.go +++ b/internal/envmanifest/builder.go @@ -3,12 +3,13 @@ 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 - runtimeSpecific map[string][]string - harnessDelivered map[string]HarnessDelivered - reserved []string - deprecated []string + 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. @@ -36,6 +37,17 @@ func (b *Builder) AddConditional(name, gate string) *Builder { 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 @@ -75,9 +87,10 @@ func (b *Builder) AddDeprecated(names ...string) *Builder { func (b *Builder) Build() Manifest { return Manifest{ Exports: Exports{ - Always: b.always, - Conditional: b.conditional, - RuntimeSpecific: b.runtimeSpecific, + Always: b.always, + Conditional: b.conditional, + RuntimeSpecific: b.runtimeSpecific, + ConditionalRuntimes: b.conditionalRuntimes, }, HarnessDelivered: b.harnessDelivered, Reserved: b.reserved, diff --git a/internal/envmanifest/manifest.go b/internal/envmanifest/manifest.go index 8ac483741f..3320079b45 100644 --- a/internal/envmanifest/manifest.go +++ b/internal/envmanifest/manifest.go @@ -30,6 +30,11 @@ 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 @@ -47,6 +52,10 @@ func (m Manifest) normalized() Manifest { 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) @@ -57,9 +66,10 @@ func (m Manifest) normalized() Manifest { } return Manifest{ Exports: Exports{ - Always: sortedUnique(m.Exports.Always), - Conditional: conditional, - RuntimeSpecific: runtimeSpecific, + Always: sortedUnique(m.Exports.Always), + Conditional: conditional, + RuntimeSpecific: runtimeSpecific, + ConditionalRuntimes: conditionalRuntimes, }, HarnessDelivered: harnessDelivered, Reserved: sortedUnique(m.Reserved), diff --git a/internal/envmanifest/manifest_test.go b/internal/envmanifest/manifest_test.go index ebf05c2d0b..dd16e16e4e 100644 --- a/internal/envmanifest/manifest_test.go +++ b/internal/envmanifest/manifest_test.go @@ -15,6 +15,8 @@ func sampleManifest() Manifest { 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"). @@ -50,6 +52,7 @@ var namesOnlyFieldTypes = map[string]string{ "Exports.Always": "[]string", "Exports.Conditional": "map[string]string", "Exports.RuntimeSpecific": "map[string][]string", + "Exports.ConditionalRuntimes": "map[string][]string", "HarnessDelivered.Provenance": "string", } diff --git a/internal/envmanifest/schema.go b/internal/envmanifest/schema.go index 673b51137e..dcb109bde9 100644 --- a/internal/envmanifest/schema.go +++ b/internal/envmanifest/schema.go @@ -4,7 +4,10 @@ import ( "bytes" "encoding/json" "fmt" + "regexp" "slices" + "strings" + "unicode" ) // SchemaBaseURI is the $id prefix of the published sandbox env schemas, @@ -68,7 +71,7 @@ func (m Manifest) harnessEnvSchema() 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 and forge..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, because the runner drops reserved keys instead of exporting them. Other harness fields are not constrained here. Generated from the runner's code (ADR 0146); see README.md."}, + {"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")}, @@ -79,6 +82,13 @@ func (m Manifest) harnessEnvSchema() 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{ @@ -86,15 +96,16 @@ func (m Manifest) harnessEnvSchema() 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."}, + {"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")}}, + object{{"not", ref("#/$defs/reserved_any_case")}}, }}}}, }}, {"env_name", envNameSchema()}, {"reserved", m.reservedSchema()}, + {"reserved_any_case", m.reservedAnyCaseSchema()}, }}, } } @@ -102,12 +113,10 @@ func (m Manifest) harnessEnvSchema() object { func (m Manifest) envReferencesSchema() object { runtimes := m.Runtimes() runtimeEnum := append([]string{PortableRuntime}, runtimes...) - shared := []any{ref("#/$defs/always"), ref("#/$defs/conditional"), ref("#/$defs/harness_delivered")} - var perRuntime []any - perRuntime = append(perRuntime, reachableWhen(PortableRuntime, shared)) + 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, append(slices.Clone(shared), ref("#/$defs/runtime_"+rt)))) + perRuntime = append(perRuntime, reachableWhen(rt, []any{ref("#/$defs/always"), m.conditionalReachableUnder(rt), ref("#/$defs/harness_delivered"), ref("#/$defs/runtime_" + rt)})) } defs := object{ @@ -121,7 +130,7 @@ func (m Manifest) envReferencesSchema() object { {"enum", m.Exports.Always}, }}, {"conditional", object{ - {"description", "Exported by the runner only when the gate in each entry's description holds."}, + {"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()}, }}, } @@ -178,6 +187,64 @@ 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 { diff --git a/internal/envmanifest/schema_test.go b/internal/envmanifest/schema_test.go index 58333bf145..80132d4e47 100644 --- a/internal/envmanifest/schema_test.go +++ b/internal/envmanifest/schema_test.go @@ -45,6 +45,8 @@ func TestRenderSchemas_Deterministic(t *testing.T) { 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() @@ -170,12 +172,24 @@ func TestHarnessEnvSchema_Validates(t *testing.T) { // 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]) - assert.Contains(t, verdicts[1], "invalid") - assert.Contains(t, verdicts[2], "invalid") - assert.Contains(t, verdicts[3], "invalid") + 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) { @@ -188,6 +202,13 @@ func TestEnvReferencesSchema_Validates(t *testing.T) { `{"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"]}`, @@ -201,8 +222,8 @@ func TestEnvReferencesSchema_Validates(t *testing.T) { `{"runtime":"claude"}`, `{"runtime":"claude","variables":["PATH"],"extra":true}`, ) - assert.Equal(t, []string{"ok", "ok"}, verdicts[:2]) - for i, v := range verdicts[2:] { - assert.Contains(t, v, "invalid", "instance %d", i+2) + assert.Equal(t, []string{"ok", "ok", "ok"}, verdicts[:3]) + for i, v := range verdicts[3:] { + assert.Contains(t, v, "invalid", "instance %d", i+3) } } From 42237e7fb0f9db39062beedfe4a3692ef235d6d1 Mon Sep 17 00:00:00 2001 From: Jay Flowers Date: Thu, 5 Nov 2026 07:06:55 -0500 Subject: [PATCH 4/4] docs(adr): describe reserved-key and bootstrapEnv sources in prose ADR 0146 cited internal/cli/run.go through commit-SHA permalinks in its Context and Decision sections; docs/contributing/adrs.md asks for plain prose there, with code evidence in the PR description. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Jay Flowers --- docs/ADRs/0146-sandbox-environment-contract-manifest.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/ADRs/0146-sandbox-environment-contract-manifest.md b/docs/ADRs/0146-sandbox-environment-contract-manifest.md index 1d2794412e..eb277b03cd 100644 --- a/docs/ADRs/0146-sandbox-environment-contract-manifest.md +++ b/docs/ADRs/0146-sandbox-environment-contract-manifest.md @@ -23,9 +23,8 @@ Accepted 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 -[`reservedSandboxKeys` sync note](https://github.com/fullsend-ai/fullsend/blob/487169a9da/internal/cli/run.go#L3375-L3427) -in `internal/cli/run.go`, +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 @@ -74,8 +73,8 @@ Schemas (Draft 2020-12) under A build-time collector generates the schemas by running every code path that injects environment variables into the sandbox: the -[`bootstrapEnv` `.env` emission](https://github.com/fullsend-ai/fullsend/blob/487169a9da/internal/cli/run.go#L3836-L3871), -the per-iteration env, trace-ID injection, the security-hook env, each +`.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