Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions .github/workflows/codex-contract.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ jobs:
timeout-minutes: 10
env:
CGO_ENABLED: "0"
WITNESS_CODEX_CONTRACT_LATEST: ${{ matrix.codex == 'latest' && '1' || '0' }}
steps:
- uses: actions/checkout@v4
with:
Expand All @@ -50,10 +49,12 @@ jobs:
run: |
npm install -g @openai/codex@${{ matrix.codex }}
codex --version
# The test supplies a dummy API key and a loopback endpoint. No account,
# stored login, model call or repository secret is used in this job.
- name: Verify outgoing requests
run: go test -tags codexcontract -run TestContractToolFreeWire -v ./internal/platform/codex
# The tests supply a dummy API key and a loopback endpoint. No account,
# stored login, model call or repository secret is used in this job. An
# unpinned CLI passes only if witness's own self-check admits it, which is
# exactly what users on that CLI get.
- name: Verify outgoing requests and the self-check
run: go test -tags codexcontract -run 'TestContract(ToolFreeWire|SelfCheck)$' -v ./internal/platform/codex

report:
needs: wire
Expand All @@ -69,7 +70,7 @@ jobs:
steps:
- name: Open or update the daily failure issue
run: |
body="The daily Codex check against npm latest failed. See $RUN_URL for the CLI version, wire contract and version-pin results."
body="The daily Codex check against npm latest failed: witness's self-check or wire contract rejects this CLI, so users on it cannot distill with Codex. See $RUN_URL for the CLI version and the failing assertion."
gh label create codex-contract --force --description 'The daily Codex compatibility check is failing'
issue=$(gh issue list --label codex-contract --state open --json number --jq '.[0].number // empty')
if [ -n "$issue" ]; then
Expand Down
8 changes: 5 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,11 @@ self-copy with `os.SameFile` + writes atomically via temp+rename.)
`internal/proc/proc_windows.go` and `cmd/commands/worker.go`.
- **Private Codex isolation.** `codex exec` uses a witness-owned login under
`runtime/codex/home`; never copy the coding login or mutate the parent CODEX_HOME.
The per-login OS lock covers every call, including lens try. New CLI versions need
the `codexcontract` wire test before extending the supported version. Feature flags
alone leave tools on; the stripped model catalog is required as well.
The per-login OS lock covers every call, including lens try. A CLI version outside
`testedVersions` reaches a transcript only after `selfcheck.go` has run the
`codexcontract` wire check on that machine for that model (passes are recorded in
`runtime/codex/verified.json`). Feature flags alone leave tools on; the stripped
model catalog is required as well.
- **Private OpenCode isolation.** witness's private `opencode serve` gets no
inherited `OPENCODE_*` variable except `OPENCODE_API_KEY` (an env-var key).
Its deny-all tool policy goes on the agent AND on every session, because
Expand Down
20 changes: 13 additions & 7 deletions docs/codex-runner.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@ your coding home. Capture still reads `WITNESS_CODEX_HOME`, `CODEX_HOME`, or
## Set up

Use Codex CLI **0.169.0**, **0.169.0-alpha.11.1**, **0.170.0** or **0.171.0**. Each build is covered by
the Linux and Windows wire contract. A daily check runs against npm latest
and files an issue when the contract fails or the release is still unpinned.
`witness doctor` checks the binary, version,
login, managed policy and configured models. After a CLI update, use
`WITNESS_CODEX_BINARY` to point witness at an installed supported binary.
the Linux and Windows wire contract. Any other version is checked on your
machine the first time witness uses it with a model: witness sends its exact
`codex exec` call to a local fake endpoint, with a throwaway home and key (never
your key or login), and requires that no tools are offered and that only the
instructions and the transcript are sent. A pass is remembered per installed binary
and model in `<archive>/runtime/codex/verified.json`, so reinstalling re-checks; a failure refuses the version,
as for an unsupported CLI. A daily check runs the same self-check against npm
latest and files an issue when it fails. `witness doctor` checks the binary,
version, login, managed policy and configured models. If a CLI update is
refused, use `WITNESS_CODEX_BINARY` to point witness at a listed binary.

```sh
witness auth codex
Expand Down Expand Up @@ -90,14 +95,15 @@ The ordinary suite uses subprocess stand-ins and never calls a model. To check
the real CLI against a local fake endpoint (dummy API key; no account needed):

```sh
CGO_ENABLED=0 go test -tags codexcontract -run TestContractToolFreeWire -v ./internal/platform/codex
CGO_ENABLED=0 go test -tags codexcontract -run 'TestContract(ToolFreeWire|SelfCheck)$' -v ./internal/platform/codex
```

The contract covers `gpt-6.1-sol` (Responses Lite) and `gpt-5.5` (ordinary
Responses). It requires captured requests for both models, checks top-level
tools and rejects all input items other than the expected messages. A
negative control drops the catalog override for `gpt-6.1-sol` and must
trigger the `additional_tools` assertion.
trigger the `additional_tools` assertion. `TestContractSelfCheck` runs the
self-check users get for an unpinned CLI on both models.

Live ChatGPT checks on November 16, 2026, Windows x64:

Expand Down
80 changes: 22 additions & 58 deletions internal/platform/codex/contract_runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/http/httptest"
"os"
"os/exec"
"slices"
"strings"
"sync"
"testing"
Expand All @@ -29,23 +30,6 @@ func TestContractToolFreeWire(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if os.Getenv("WITNESS_CODEX_CONTRACT_LATEST") == "1" {
version, err := cliVersion(context.Background(), bin, t.TempDir(), childEnv(t.TempDir()))
if err != nil {
t.Fatal(err)
}
pinned := supportsVersion(version)
original := supportsVersion
supportsVersion = func(observed string) bool { return observed == version }
t.Cleanup(func() { supportsVersion = original })
// Run the wire assertions first. Even if they pass, flag an unsupported
// latest release so maintainers can verify it and update the pins.
defer func() {
if !pinned {
t.Errorf("latest Codex CLI %s is not pinned by witness", version)
}
}()
}
cmd := exec.CommandContext(context.Background(), bin, "debug", "models", "--bundled")
cmd.Env = childEnv(t.TempDir())
catalog, err := cmd.Output()
Expand Down Expand Up @@ -101,6 +85,10 @@ func TestContractToolFreeWire(t *testing.T) {
requests = nil
mu.Unlock()
commandContext = func(ctx context.Context, binary string, args ...string) *exec.Cmd {
// An unpinned CLI (the latest leg) self-checks first; leave its calls as sent.
if slices.ContainsFunc(args, func(a string) bool { return strings.HasPrefix(a, "openai_base_url=") }) {
return exec.CommandContext(ctx, binary, args...)
}
forwarded := []string{"-c", configPath("openai_base_url", srv.URL+"/v1")}
for i := 0; i < len(args); i++ {
if tc.dropCatalog && args[i] == "-c" && i+1 < len(args) && strings.HasPrefix(args[i+1], "model_catalog_json=") {
Expand Down Expand Up @@ -132,7 +120,7 @@ func TestContractToolFreeWire(t *testing.T) {
if string(req["model"]) != fmt.Sprintf("%q", tc.slug) {
t.Fatalf("unexpected model %s", req["model"])
}
err := checkWireRequest(req)
err := checkWireRequest(req, probeSystem, probeCorpus)
if tc.dropCatalog {
if err != nil && strings.Contains(err.Error(), "additional_tools") {
caught = true
Expand All @@ -148,50 +136,26 @@ func TestContractToolFreeWire(t *testing.T) {
}
}

func checkWireRequest(req map[string]json.RawMessage) error {
var offered []json.RawMessage
if raw := req["tools"]; len(raw) > 0 {
if err := json.Unmarshal(raw, &offered); err != nil {
return err
}
}
if len(offered) != 0 {
return fmt.Errorf("tools offered: %s", req["tools"])
}
var input []struct {
Type, Role string
Content []struct{ Type, Text string }
// The check an unpinned CLI gets on a user's machine, run on the real CLI. A pass
// includes its sensitivity run, so the checker demonstrably saw this CLI's tools.
func TestContractSelfCheck(t *testing.T) {
bin, err := FindBinary()
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(req["input"], &input); err != nil {
return err
cmd := exec.Command(bin, "debug", "models", "--bundled")
cmd.Env = childEnv(t.TempDir())
catalog, err := cmd.Output()
if err != nil {
t.Fatal(err)
}
dev, user := 0, 0
for _, msg := range input {
if msg.Type != "message" {
return fmt.Errorf("unexpected wire input item: %s", msg.Type)
}
if len(msg.Content) != 1 || msg.Content[0].Type != "input_text" {
return fmt.Errorf("unexpected %s message content", msg.Role)
}
switch msg.Role {
case "developer":
if msg.Content[0].Text != "WITNESS-SYSTEM-ONLY" {
return fmt.Errorf("unexpected developer instructions")
}
dev++
case "user":
if msg.Content[0].Text != "WITNESS-CORPUS-ONLY" {
return fmt.Errorf("unexpected corpus")
for _, slug := range []string{"gpt-6.1-sol", "gpt-5.5"} {
t.Run(slug, func(t *testing.T) {
if err := selfCheck(context.Background(), bin, catalog, slug); err != nil {
t.Fatal(err)
}
user++
default:
return fmt.Errorf("unexpected message role %q", msg.Role)
}
}
if dev == 0 || user != 1 {
return fmt.Errorf("instruction/corpus channels: developer=%d user=%d", dev, user)
})
}
return nil
}

// Opt-in only, uses an already-authorized witness-owned login. Never run by CI.
Expand Down
93 changes: 47 additions & 46 deletions internal/platform/codex/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"time"

Expand All @@ -21,8 +20,9 @@ import (
)

// The tool policy is a versioned protocol, not a sandbox policy: transcripts are
// untrusted and must never be offered tools, even read-only ones. New CLI versions
// need the wire contract checked before this range is extended.
// untrusted and must never be offered tools, even read-only ones. These versions
// passed the contract matrix in CI; any other version must pass the same wire check
// on this machine before a transcript reaches it (selfcheck.go).
// TestTestedVersionsMatchTheContractMatrixAndTheDocs keeps this list,
// codex-contract.yml's pinned matrix and docs/codex-runner.md equal.
var testedVersions = []string{"0.169.0", "0.169.0-alpha.11.1", "0.170.0", "0.171.0"}
Expand Down Expand Up @@ -196,9 +196,6 @@ func LoginReady(ctx context.Context, root string) error {
if err != nil {
return err
}
if err := checkVersion(ctx, bin, dir, env); err != nil {
return err
}
return checkLogin(ctx, bin, dir, env)
}

Expand Down Expand Up @@ -266,12 +263,6 @@ func loginCommand(ctx context.Context, root string, logout bool) error {
}
args := []string{"logout"}
if !logout {
versionCtx, cancel := context.WithTimeout(ctx, preflightTimeout)
err := checkVersion(versionCtx, bin, dir, env)
cancel()
if err != nil {
return err
}
args = []string{"login", "--device-auth"}
}
cmd := commandContext(ctx, bin, args...)
Expand Down Expand Up @@ -334,12 +325,17 @@ func (r *runner) validate(ctx context.Context, models []string, diagnostic bool)
if err != nil {
return "", err
}
raw, err := prepareCatalog(preflightCtx, bin, dir, env)
version, raw, err := prepareCatalog(preflightCtx, bin, dir, env)
if err != nil {
return "", preflightError(ctx, err)
}
_, err = stripCatalog(raw, models...)
return bin, err
if _, err := stripCatalog(raw, models...); err != nil {
return "", err
}
if err := ensureToolFree(ctx, bin, r.root, version, raw, models...); err != nil {
return "", preflightError(ctx, err)
}
return bin, nil
}

func validModelName(model string) bool {
Expand All @@ -355,22 +351,6 @@ func validateModelNames(models ...string) error {
return nil
}

func checkVersion(ctx context.Context, bin, dir string, env []string) error {
version, err := cliVersion(ctx, bin, dir, env)
if err != nil {
return err
}
if !supportsVersion(version) {
return fmt.Errorf("Codex CLI %s has no verified tool-free contract; install one of %s and point WITNESS_CODEX_BINARY at it", version, strings.Join(testedVersions, ", "))
}
return nil
}

// Contract tests can exercise the newest CLI without admitting its version in production.
var supportsVersion = func(version string) bool {
return slices.Contains(testedVersions, version)
}

func cliVersion(ctx context.Context, bin, dir string, env []string) (string, error) {
cmd := commandContext(ctx, bin, "--version")
cmd.Dir, cmd.Env = dir, env
Expand Down Expand Up @@ -415,15 +395,18 @@ func runnerEnv(dir, root string) ([]string, error) {
return childEnv(home), nil
}

func prepareCatalog(ctx context.Context, bin, dir string, env []string) ([]byte, error) {
if err := checkVersion(ctx, bin, dir, env); err != nil {
return nil, err
// prepareCatalog returns the CLI version with the catalog; the caller gates the pair
// with ensureToolFree before any transcript is sent.
func prepareCatalog(ctx context.Context, bin, dir string, env []string) (string, []byte, error) {
version, err := cliVersion(ctx, bin, dir, env)
if err != nil {
return "", nil, err
}
if err := checkManagedConfig(ctx, bin, dir, env); err != nil {
return nil, err
return "", nil, err
}
if err := checkLogin(ctx, bin, dir, env); err != nil {
return nil, err
return "", nil, err
}
cmd := commandContext(ctx, bin, append(isolationArgs(), "debug", "models")...)
cmd.Env, cmd.Dir = env, dir
Expand All @@ -432,9 +415,9 @@ func prepareCatalog(ctx context.Context, bin, dir string, env []string) ([]byte,
cmd.Stderr = &stderr
raw, err := cmd.Output()
if err != nil && !errors.Is(err, exec.ErrWaitDelay) { // a clean exit; only a grandchild held stdout (see Run)
return nil, childError(ctx, "catalog", err, stderr.String())
return "", nil, childError(ctx, "catalog", err, stderr.String())
}
return raw, nil
return version, raw, nil
}

// These flags remove configurable tools and all implicit user/project context.
Expand Down Expand Up @@ -491,6 +474,26 @@ func configPath(key, path string) string {
return key + "=" + string(b)
}

// execArgs writes the instructions, and the stripped catalog unless it is nil, into dir
// and returns the argv of the generation call. Run and the self-check share it, so the
// check judges the exact request a transcript would ride in.
func execArgs(dir, cwd, model, prompt string, catalog []byte) ([]string, error) {
promptPath := filepath.Join(dir, "system.md")
if err := os.WriteFile(promptPath, []byte(prompt), 0600); err != nil {
return nil, err
}
args := isolationArgs()
if catalog != nil {
catPath := filepath.Join(dir, "models.json")
if err := os.WriteFile(catPath, catalog, 0600); err != nil {
return nil, err
}
args = append(args, "-c", configPath("model_catalog_json", catPath))
}
args = append(args, "-c", configPath("model_instructions_file", promptPath))
return append(args, "exec", "--ignore-user-config", "--ignore-rules", "--json", "--ephemeral", "--skip-git-repo-check", "-C", cwd, "-s", "read-only", "-m", model, "-"), nil
}

func (r *runner) Run(ctx context.Context, model, prompt, input string) (string, error) {
if platform.ExternalRunnersDisabled() {
return "", fmt.Errorf("codex runner disabled by %s", platform.DisableExternalRunnersEnv)
Expand All @@ -517,11 +520,14 @@ func (r *runner) Run(ctx context.Context, model, prompt, input string) (string,
return "", err
}
preflightCtx, stop := context.WithTimeout(ctx, preflightTimeout)
raw, err := prepareCatalog(preflightCtx, r.binary, dir, env)
version, raw, err := prepareCatalog(preflightCtx, r.binary, dir, env)
stop()
if err != nil {
return "", preflightError(ctx, err)
}
if err := ensureToolFree(ctx, r.binary, r.root, version, raw, model); err != nil {
return "", preflightError(ctx, err)
}
cwd := filepath.Join(dir, "cwd")
if err := os.Mkdir(cwd, 0700); err != nil {
return "", err
Expand All @@ -530,15 +536,10 @@ func (r *runner) Run(ctx context.Context, model, prompt, input string) (string,
if err != nil {
return "", err
}
catPath, promptPath := filepath.Join(dir, "models.json"), filepath.Join(dir, "system.md")
if err := os.WriteFile(catPath, catalog, 0600); err != nil {
return "", err
}
if err := os.WriteFile(promptPath, []byte(prompt), 0600); err != nil {
args, err := execArgs(dir, cwd, model, prompt, catalog)
if err != nil {
return "", err
}
args := append(isolationArgs(), "-c", configPath("model_catalog_json", catPath), "-c", configPath("model_instructions_file", promptPath))
args = append(args, "exec", "--ignore-user-config", "--ignore-rules", "--json", "--ephemeral", "--skip-git-repo-check", "-C", cwd, "-s", "read-only", "-m", model, "-")
callCtx, cancel := context.WithTimeout(ctx, runTimeout)
defer cancel()
cmd := commandContext(callCtx, r.binary, args...)
Expand Down
Loading
Loading