From 5c12c0424edc838db72993caddc621e5452d5566 Mon Sep 17 00:00:00 2001 From: Angel Davila Date: Mon, 23 Nov 2026 23:37:27 -0600 Subject: [PATCH 1/4] Load provider keys from a .env at the repo root. thee now reads the nearest .env at or above the current directory, stopping at the directory that holds .git. Shell variables win over the file, and a malformed line fails with its path and line number. Adds .env.example and un-ignores it. The M0 e2e test now runs the binary from its temp fixture so it never picks up a developer's real .env. --- .env.example | 12 +++ .gitignore | 1 + README.md | 2 + docs/harness-architecture/providers.md | 2 +- harness/cmd/thee/root.go | 10 +++ harness/internal/config/dotenv.go | 106 +++++++++++++++++++++++++ harness/internal/config/dotenv_test.go | 88 ++++++++++++++++++++ harness/internal/e2e/m0_test.go | 1 + 8 files changed, 221 insertions(+), 1 deletion(-) create mode 100644 .env.example create mode 100644 harness/internal/config/dotenv.go create mode 100644 harness/internal/config/dotenv_test.go diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..f01889e --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +# Copy to .env and fill in the keys you use. .env is gitignored. +# thee reads the nearest .env at or above the current directory, up to the +# repo root. Variables already set in your shell take precedence. + +# OpenCode Go (task eval, /providers in the TUI) +OPENCODE_API_KEY= + +# DeepInfra (default worker role, weekly CI eval matrix) +DEEPINFRA_API_KEY= + +# OpenAI +OPENAI_API_KEY= diff --git a/.gitignore b/.gitignore index 8a53019..4a8e3a8 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ # Env / secrets .env .env.* +!.env.example diff --git a/README.md b/README.md index de6e863..9c507e4 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,8 @@ go test ./... | `THEE_TRUST` | — | Set to `1` to trust the workspace (same as `--trust`) | | `DEEPINFRA_API_KEY` (etc.) | — | Provider keys per embedded `models.yaml` / `~/.thee/catalog.json` | +`thee` also reads the nearest `.env` at or above the current directory, stopping at the repo root. Shell variables win over the file. To set it up, copy [`.env.example`](.env.example) to `.env` and fill in your keys. + --- ## Install diff --git a/docs/harness-architecture/providers.md b/docs/harness-architecture/providers.md index 0089308..9f2f71f 100644 --- a/docs/harness-architecture/providers.md +++ b/docs/harness-architecture/providers.md @@ -18,7 +18,7 @@ The harness lets users bring their own key. Our own inference is the provider we ### Credential resolution order -1. Per-provider `api_key_env` in `models.yaml` or `catalog.json` (e.g. `DEEPINFRA_API_KEY`). +1. Per-provider `api_key_env` in `models.yaml` or `catalog.json` (e.g. `DEEPINFRA_API_KEY`). At startup `thee` loads the nearest `.env` at or above the current directory (stopping at the directory that holds `.git`). It never overrides variables already set in the environment. 2. Generic fallbacks where documented (e.g. `OPENAI_API_KEY` for OpenAI-compatible base URLs)—explicit in config, not magic. 3. OS keychain entries via `thee auth login `. 4. **(team)** CI/org secret injection—same env-based contract. diff --git a/harness/cmd/thee/root.go b/harness/cmd/thee/root.go index 6dff704..c5a83bd 100644 --- a/harness/cmd/thee/root.go +++ b/harness/cmd/thee/root.go @@ -5,12 +5,22 @@ import ( "os" "github.com/spf13/cobra" + + "github.com/PLACEHOLDER/thee/harness/internal/config" ) var rootCmd = &cobra.Command{ Use: "thee", Short: "thee coding agent harness", SilenceUsage: true, + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + wd, err := os.Getwd() + if err != nil { + return err + } + _, err = config.LoadDotEnv(wd) + return err + }, } func execute() error { diff --git a/harness/internal/config/dotenv.go b/harness/internal/config/dotenv.go new file mode 100644 index 0000000..d872fe8 --- /dev/null +++ b/harness/internal/config/dotenv.go @@ -0,0 +1,106 @@ +package config + +import ( + "bufio" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" +) + +const dotEnvName = ".env" + +var utf8BOM = string([]byte{0xEF, 0xBB, 0xBF}) + +// FindDotEnv returns the nearest .env file at or above dir, stopping at the +// first directory that holds .git. It returns "" when there is none. +func FindDotEnv(dir string) (string, error) { + dir, err := filepath.Abs(dir) + if err != nil { + return "", err + } + for { + path := filepath.Join(dir, dotEnvName) + info, err := os.Stat(path) + if err == nil && !info.IsDir() { + return path, nil + } + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return "", err + } + if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil { + return "", nil + } + parent := filepath.Dir(dir) + if parent == dir { + return "", nil + } + dir = parent + } +} + +// LoadDotEnv sets environment variables from the nearest .env file at or above +// dir. Variables already set in the environment win. It returns the file it +// read, or "" when there was none. +func LoadDotEnv(dir string) (string, error) { + path, err := FindDotEnv(dir) + if err != nil || path == "" { + return "", err + } + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + vars, err := ParseDotEnv(f.Name(), bufio.NewScanner(f)) + if err != nil { + return "", err + } + for k, v := range vars { + if _, set := os.LookupEnv(k); set { + continue + } + if err := os.Setenv(k, v); err != nil { + return "", fmt.Errorf("%s: set %s: %w", path, k, err) + } + } + return path, nil +} + +// ParseDotEnv reads KEY=VALUE lines. Blank lines, # comments, an optional +// export prefix, and single or double quotes around values are accepted. +func ParseDotEnv(name string, sc *bufio.Scanner) (map[string]string, error) { + vars := map[string]string{} + for n := 1; sc.Scan(); n++ { + line := strings.TrimSpace(sc.Text()) + if n == 1 { + line = strings.TrimPrefix(line, utf8BOM) + } + if line == "" || strings.HasPrefix(line, "#") { + continue + } + line = strings.TrimSpace(strings.TrimPrefix(line, "export ")) + key, val, ok := strings.Cut(line, "=") + key = strings.TrimSpace(key) + if !ok || key == "" || strings.ContainsAny(key, " \t") { + return nil, fmt.Errorf("%s:%d: want KEY=VALUE", name, n) + } + vars[key] = dotEnvValue(strings.TrimSpace(val)) + } + if err := sc.Err(); err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + return vars, nil +} + +func dotEnvValue(v string) string { + if len(v) >= 2 && (v[0] == '"' || v[0] == '\'') && v[len(v)-1] == v[0] { + return v[1 : len(v)-1] + } + if i := strings.Index(v, " #"); i >= 0 { + v = strings.TrimSpace(v[:i]) + } + return v +} diff --git a/harness/internal/config/dotenv_test.go b/harness/internal/config/dotenv_test.go new file mode 100644 index 0000000..e4be73e --- /dev/null +++ b/harness/internal/config/dotenv_test.go @@ -0,0 +1,88 @@ +package config + +import ( + "bufio" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestParseDotEnv(t *testing.T) { + in := utf8BOM + "# keys\n\nexport A=1\nB = \"two words\"\nC='x # y'\nD=plain # note\nE=\n" + got, err := ParseDotEnv("test.env", bufio.NewScanner(strings.NewReader(in))) + if err != nil { + t.Fatal(err) + } + want := map[string]string{"A": "1", "B": "two words", "C": "x # y", "D": "plain", "E": ""} + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("ParseDotEnv (-want +got):\n%s", diff) + } +} + +func TestParseDotEnvBadLine(t *testing.T) { + for _, in := range []string{"NOEQUALS", "=v", "BAD KEY=v"} { + if _, err := ParseDotEnv("test.env", bufio.NewScanner(strings.NewReader(in))); err == nil { + t.Errorf("ParseDotEnv(%q): got nil error", in) + } + } +} + +func unsetForTest(t *testing.T, keys ...string) { + t.Helper() + for _, k := range keys { + t.Setenv(k, "") + os.Unsetenv(k) + } +} + +func writeFile(t *testing.T, path, body string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } +} + +func TestLoadDotEnvWalksUpToRepoRoot(t *testing.T) { + unsetForTest(t, "THEE_DOTENV_A", "THEE_DOTENV_B") + root := t.TempDir() + writeFile(t, filepath.Join(root, ".git", "HEAD"), "ref: refs/heads/main\n") + writeFile(t, filepath.Join(root, ".env"), "THEE_DOTENV_A=from-file\nTHEE_DOTENV_B=from-file\n") + t.Setenv("THEE_DOTENV_B", "from-env") + sub := filepath.Join(root, "harness", "cmd") + if err := os.MkdirAll(sub, 0o755); err != nil { + t.Fatal(err) + } + path, err := LoadDotEnv(sub) + if err != nil { + t.Fatal(err) + } + if path != filepath.Join(root, ".env") { + t.Errorf("LoadDotEnv: got path %q", path) + } + if got := os.Getenv("THEE_DOTENV_A"); got != "from-file" { + t.Errorf("THEE_DOTENV_A: got %q, want from-file", got) + } + if got := os.Getenv("THEE_DOTENV_B"); got != "from-env" { + t.Errorf("THEE_DOTENV_B: got %q, want from-env", got) + } +} + +func TestFindDotEnvStopsAtRepoRoot(t *testing.T) { + outer := t.TempDir() + writeFile(t, filepath.Join(outer, ".env"), "THEE_DOTENV_OUTER=1\n") + repo := filepath.Join(outer, "repo") + writeFile(t, filepath.Join(repo, ".git"), "gitdir: elsewhere\n") + path, err := FindDotEnv(repo) + if err != nil { + t.Fatal(err) + } + if path != "" { + t.Errorf("FindDotEnv: got %q, want none", path) + } +} diff --git a/harness/internal/e2e/m0_test.go b/harness/internal/e2e/m0_test.go index 39fb1bb..4c9bd2e 100644 --- a/harness/internal/e2e/m0_test.go +++ b/harness/internal/e2e/m0_test.go @@ -27,6 +27,7 @@ func TestM0RunE2E(t *testing.T) { } bin := buildThee(t) cmd := exec.Command(bin, "run", "-p", "fix the failing test", "--trust", "--directory", fixtureDir) + cmd.Dir = fixtureDir cmd.Env = append(os.Environ(), "THEE_HOME="+home, "THEE_SCRIPTED_PROVIDER_FILE="+scriptPath, From e9f81c69c8547ef063d43937082b5b84f982d94a Mon Sep 17 00:00:00 2001 From: Angel Davila Date: Mon, 23 Nov 2026 23:38:46 -0600 Subject: [PATCH 2/4] Add a changeset for loading provider keys from .env. --- .changeset/dotenv-provider-keys.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .changeset/dotenv-provider-keys.md diff --git a/.changeset/dotenv-provider-keys.md b/.changeset/dotenv-provider-keys.md new file mode 100644 index 0000000..0bdd202 --- /dev/null +++ b/.changeset/dotenv-provider-keys.md @@ -0,0 +1,7 @@ +--- +"thee": minor +--- + +`thee` reads provider keys such as `OPENCODE_API_KEY` from the nearest `.env` at or above the current directory, up to the repo root. Variables already set in your shell win over the file. Copy `.env.example` to `.env` to get started. + +**Upgrade:** a `.env` line that isn't `KEY=VALUE` (for example `name: value`) now stops every `thee` command with the file and line number. Fix or remove that line. From f01f869e8afe65c7eaab4caa4b5b111d1250ea56 Mon Sep 17 00:00:00 2001 From: Angel Davila Date: Mon, 23 Nov 2026 23:43:02 -0600 Subject: [PATCH 3/4] Fix lint errors in the .env loader and its tests. --- harness/internal/config/dotenv.go | 6 +++--- harness/internal/config/dotenv_test.go | 8 +++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/harness/internal/config/dotenv.go b/harness/internal/config/dotenv.go index d872fe8..b78cd9b 100644 --- a/harness/internal/config/dotenv.go +++ b/harness/internal/config/dotenv.go @@ -2,6 +2,7 @@ package config import ( "bufio" + "bytes" "errors" "fmt" "io/fs" @@ -49,12 +50,11 @@ func LoadDotEnv(dir string) (string, error) { if err != nil || path == "" { return "", err } - f, err := os.Open(path) + b, err := os.ReadFile(path) if err != nil { return "", err } - defer f.Close() - vars, err := ParseDotEnv(f.Name(), bufio.NewScanner(f)) + vars, err := ParseDotEnv(path, bufio.NewScanner(bytes.NewReader(b))) if err != nil { return "", err } diff --git a/harness/internal/config/dotenv_test.go b/harness/internal/config/dotenv_test.go index e4be73e..bb6c635 100644 --- a/harness/internal/config/dotenv_test.go +++ b/harness/internal/config/dotenv_test.go @@ -34,13 +34,15 @@ func unsetForTest(t *testing.T, keys ...string) { t.Helper() for _, k := range keys { t.Setenv(k, "") - os.Unsetenv(k) + if err := os.Unsetenv(k); err != nil { + t.Fatal(err) + } } } func writeFile(t *testing.T, path, body string) { t.Helper() - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil { t.Fatal(err) } if err := os.WriteFile(path, []byte(body), 0o600); err != nil { @@ -55,7 +57,7 @@ func TestLoadDotEnvWalksUpToRepoRoot(t *testing.T) { writeFile(t, filepath.Join(root, ".env"), "THEE_DOTENV_A=from-file\nTHEE_DOTENV_B=from-file\n") t.Setenv("THEE_DOTENV_B", "from-env") sub := filepath.Join(root, "harness", "cmd") - if err := os.MkdirAll(sub, 0o755); err != nil { + if err := os.MkdirAll(sub, 0o750); err != nil { t.Fatal(err) } path, err := LoadDotEnv(sub) From 2087152756e6bd1c8205ffbff8f13151cc6ff2cd Mon Sep 17 00:00:00 2001 From: Angel Davila Date: Mon, 23 Nov 2026 23:46:37 -0600 Subject: [PATCH 4/4] Mark the .env read as a fixed path for gosec. --- harness/internal/config/dotenv.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/harness/internal/config/dotenv.go b/harness/internal/config/dotenv.go index b78cd9b..28ea6d0 100644 --- a/harness/internal/config/dotenv.go +++ b/harness/internal/config/dotenv.go @@ -50,7 +50,7 @@ func LoadDotEnv(dir string) (string, error) { if err != nil || path == "" { return "", err } - b, err := os.ReadFile(path) + b, err := os.ReadFile(path) //nolint:gosec // G304: path is always /.env from FindDotEnv if err != nil { return "", err }