Merge: worktree-agent-add396073f8f3e026
This commit is contained in:
+58
-1
@@ -199,7 +199,9 @@ $EDITOR ~/.config/pipelines/claude-token
|
||||
`PIPELINES_CLAUDE_TOKEN_FILE` names another file. The file must be a regular,
|
||||
owner-only file. The startup report shows `Claude service token present` when
|
||||
it is read. An `ANTHROPIC_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN` or
|
||||
`CLAUDE_CONFIG_DIR` in the server's environment takes precedence.
|
||||
`CLAUDE_CONFIG_DIR` in the server's environment takes precedence, and a chat
|
||||
directory that chooses its own account wins over all of these (see
|
||||
[Per-directory accounts and environment](#per-directory-accounts-and-environment)).
|
||||
|
||||
**Models:** the catalog comes from the CLI; switching applies live and is kept
|
||||
for the next turn.
|
||||
@@ -228,6 +230,61 @@ approval cards.
|
||||
**Mid-turn messages:** yes, with `turn/steer` pinned to the running turn. If
|
||||
the turn already ended, the message is queued for the next turn instead.
|
||||
|
||||
## Per-directory accounts and environment
|
||||
|
||||
A chat runs in the directory you choose for it. For Claude Code the server
|
||||
also applies that directory's own environment, so the chat behaves as if you
|
||||
had opened a terminal there and started `claude`:
|
||||
|
||||
- **Working directory.** The `claude` process starts in the chat directory
|
||||
with `PWD` set to it. Codex threads are started with that `cwd` and OpenCode
|
||||
sessions with that location, so every harness runs tools there.
|
||||
- **Git identity.** `includeIf "gitdir:..."` rules in your git config apply
|
||||
automatically: git resolves them from the working directory of a repository
|
||||
under the chosen directory.
|
||||
- **direnv.** When `direnv` is installed (the service's `PATH`, then
|
||||
`/opt/homebrew/bin`, `/usr/local/bin`, `~/.local/bin`, `~/.nix-profile/bin`)
|
||||
the server runs `direnv export json` in the chat directory, so an `.envrc`
|
||||
there or in a parent applies. Only an `.envrc` you already allowed is used;
|
||||
the server never runs `direnv allow`. A blocked `.envrc` is logged and shown
|
||||
in the chat as a "Directory environment" notice, and nothing from it is
|
||||
applied.
|
||||
- **mise.** When `mise` is installed the server merges `mise env --json`
|
||||
(untrusted config is reported the same way). When both set a variable,
|
||||
direnv wins.
|
||||
- A plain `.env` file is not read on its own; use an `.envrc` (`dotenv` loads
|
||||
one) so the allow check applies.
|
||||
|
||||
The result is merged onto the server's environment and cached per directory;
|
||||
editing an `.envrc`, a mise config, a file direnv watches, or allowing or
|
||||
denying an `.envrc` makes the next chat process read it again. Set
|
||||
`PIPELINES_DIRECTORY_ENV=off` in the server's environment to turn this off.
|
||||
|
||||
**Choosing the Claude account per directory.** When the directory's
|
||||
environment sets or unsets any of `CLAUDE_CONFIG_DIR`, `CLAUDE_CODE_OAUTH_TOKEN`,
|
||||
`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `CLAUDE_SECURESTORAGE_CONFIG_DIR`,
|
||||
`CLAUDE_CODE_USE_BEDROCK` or `CLAUDE_CODE_USE_VERTEX`, that directory owns the
|
||||
account: the service token and the `~/.claude` login-file fallback are not
|
||||
added, and inherited server credentials (`CLAUDE_CODE_OAUTH_TOKEN`,
|
||||
`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`) are dropped unless the directory
|
||||
sets them. Transcripts kept in a directory's `CLAUDE_CONFIG_DIR` are found for
|
||||
history and resume, also after a restart. For example:
|
||||
|
||||
```sh
|
||||
# ~/work/.envrc (then run `direnv allow ~/work`)
|
||||
export CLAUDE_CONFIG_DIR="$HOME/work/.claude-profile"
|
||||
export GH_CONFIG_DIR="$HOME/work/.gh"
|
||||
```
|
||||
|
||||
Sign that profile in once from a terminal in that directory (`claude`, then
|
||||
`/login`). Shell functions or aliases in `~/.zshrc` that switch accounts by
|
||||
`$PWD` are not seen by the server, which does not run your shell; move them
|
||||
into an `.envrc`.
|
||||
|
||||
Codex and OpenCode chats share one App Server or `opencode serve` process
|
||||
across directories, so only the working directory applies to them; their
|
||||
account is the one that process uses.
|
||||
|
||||
## Adopting existing sessions
|
||||
|
||||
```sh
|
||||
|
||||
@@ -3,10 +3,15 @@ package claude
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/workenv"
|
||||
)
|
||||
|
||||
// secureStorageEnvKey points Claude Code's credential lookup at a config
|
||||
@@ -88,6 +93,92 @@ func SignedIn(ctx context.Context, binary string, env []string) (bool, string) {
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// accountEnvKeys select which account Claude Code signs in with. When a chat
|
||||
// directory's own environment (direnv, mise) sets or unsets any of them, that
|
||||
// directory owns the account: the server's fallbacks (service token, login
|
||||
// file) are not added and inherited credentials are dropped, exactly as a
|
||||
// terminal opened in that directory would behave.
|
||||
var accountEnvKeys = []string{
|
||||
"CLAUDE_CONFIG_DIR", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN",
|
||||
secureStorageEnvKey, "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX",
|
||||
}
|
||||
|
||||
// credentialEnvKeys are inherited server credentials a directory account
|
||||
// must not be overridden by. An inherited CLAUDE_CONFIG_DIR is kept.
|
||||
var credentialEnvKeys = []string{"CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", secureStorageEnvKey}
|
||||
|
||||
func directoryOwnsAccount(dir workenv.Result) bool {
|
||||
for _, key := range accountEnvKeys {
|
||||
if dir.Touches(key) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// processEnv is the environment for a CLI process started in directory: the
|
||||
// server's environment, then the directory's own environment, then the
|
||||
// server's sign-in fallbacks only when the directory does not choose an
|
||||
// account. The second result holds operator-facing warnings.
|
||||
func (c *Chat) processEnv(ctx context.Context, directory string) ([]string, []string) {
|
||||
return c.processEnvFrom(ctx, directory, os.Environ())
|
||||
}
|
||||
|
||||
func (c *Chat) processEnvFrom(ctx context.Context, directory string, base []string) ([]string, []string) {
|
||||
var dir workenv.Result
|
||||
if c.dirEnv != nil {
|
||||
dir = c.dirEnv.Resolve(ctx, directory, base)
|
||||
}
|
||||
for _, warning := range dir.Warnings {
|
||||
log.Printf("claude chat directory %s: %s", directory, warning)
|
||||
}
|
||||
var env []string
|
||||
if directoryOwnsAccount(dir) {
|
||||
kept := make([]string, 0, len(base))
|
||||
for _, item := range base {
|
||||
key, _, _ := strings.Cut(item, "=")
|
||||
if slices.Contains(credentialEnvKeys, key) && !dir.Touches(key) {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, item)
|
||||
}
|
||||
env = dir.Apply(kept)
|
||||
} else {
|
||||
env = c.auth.resolve(c.ctx, c.binary, withServiceToken(dir.Apply(base)))
|
||||
}
|
||||
if value, ok := envValue(env, "CLAUDE_CONFIG_DIR"); ok {
|
||||
rememberConfigDir(value)
|
||||
}
|
||||
return workenv.WithPWD(env, directory), dir.Warnings
|
||||
}
|
||||
|
||||
// HintDirectory tells the adapter the recorded directory of a session it has
|
||||
// not opened in this server process, so a transcript kept in that
|
||||
// directory's own CLAUDE_CONFIG_DIR is found after a restart.
|
||||
func (c *Chat) HintDirectory(ctx context.Context, id, directory string) {
|
||||
if id == "" || strings.TrimSpace(directory) == "" || c.session(id) != nil {
|
||||
return
|
||||
}
|
||||
if _, done := c.hinted.LoadOrStore(id, true); done {
|
||||
return
|
||||
}
|
||||
if c.dirEnv == nil {
|
||||
return
|
||||
}
|
||||
if value, ok := c.dirEnv.Resolve(ctx, directory, os.Environ()).Value("CLAUDE_CONFIG_DIR"); ok {
|
||||
rememberConfigDir(value)
|
||||
}
|
||||
}
|
||||
|
||||
func envValue(env []string, key string) (string, bool) {
|
||||
for i := len(env) - 1; i >= 0; i-- {
|
||||
if k, v, ok := strings.Cut(env[i], "="); ok && k == key {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// ServiceTokenPath is the token file the server reads.
|
||||
func ServiceTokenPath() string { return serviceTokenPath() }
|
||||
|
||||
|
||||
@@ -187,8 +187,13 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
|
||||
s.steered = 0
|
||||
s.awaitFollowUp = false
|
||||
s.recordPromptLocked(messageID, text)
|
||||
notices := s.envNotices
|
||||
s.envNotices = nil
|
||||
s.mu.Unlock()
|
||||
s.emit(protocol.ChatEventFrame{SessionID: id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
|
||||
for index, notice := range notices {
|
||||
s.emitEnvNotice(turn, index, notice)
|
||||
}
|
||||
payload := map[string]any{
|
||||
"type": "user",
|
||||
"message": map[string]any{"role": "user", "content": content},
|
||||
@@ -266,6 +271,25 @@ func (s *session) adoptFollowUpTurn() {
|
||||
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
|
||||
}
|
||||
|
||||
// emitEnvNotice shows a directory-environment warning (for example a blocked
|
||||
// .envrc) in the turn, so the operator sees why the directory's account or
|
||||
// tools were not applied.
|
||||
func (s *session) emitEnvNotice(turn string, index int, notice string) {
|
||||
id := fmt.Sprintf("claude-env-%s-%d", turn, index)
|
||||
s.emit(protocol.ChatEventFrame{
|
||||
SessionID: s.id,
|
||||
NativeTurnID: turn,
|
||||
MessageID: id,
|
||||
Kind: protocol.ChatEventTool,
|
||||
Part: &protocol.ChatPart{
|
||||
Type: protocol.ChatPartTool,
|
||||
ID: id,
|
||||
Name: "Directory environment",
|
||||
State: &protocol.ChatToolState{Status: protocol.ChatToolError, Error: &protocol.ChatError{Type: "environment", Message: boundedText(notice, 2<<10)}},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// finishTurn settles a turn that never reached a CLI result.
|
||||
func (s *session) finishTurn(turn, diagnostic string) {
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/workenv"
|
||||
)
|
||||
|
||||
// Backend is the wire value stored in the operator-session registry.
|
||||
@@ -93,6 +94,10 @@ type Chat struct {
|
||||
binary string
|
||||
// auth picks how started CLI processes sign in (see authEnv).
|
||||
auth authEnv
|
||||
// dirEnv supplies each chat directory's own environment (direnv, mise).
|
||||
dirEnv *workenv.Resolver
|
||||
// hinted records sessions whose registry directory has been resolved.
|
||||
hinted sync.Map
|
||||
|
||||
mu sync.Mutex
|
||||
sessions map[string]*session
|
||||
@@ -104,7 +109,7 @@ func New(ctx context.Context) *Chat {
|
||||
ctx = context.Background()
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
c := &Chat{ctx: ctx, cancel: cancel, binary: BinaryPath(), sessions: map[string]*session{}}
|
||||
c := &Chat{ctx: ctx, cancel: cancel, binary: BinaryPath(), dirEnv: workenv.Default, sessions: map[string]*session{}}
|
||||
go c.reapIdle()
|
||||
return c
|
||||
}
|
||||
@@ -252,6 +257,9 @@ type session struct {
|
||||
awaitFollowUp bool
|
||||
lastUsed time.Time
|
||||
lastErr string
|
||||
// envNotices are directory-environment warnings from the last spawn,
|
||||
// shown once in the next turn.
|
||||
envNotices []string
|
||||
|
||||
subs map[chan protocol.ChatEventFrame]struct{}
|
||||
approvals map[string]*pendingApproval
|
||||
@@ -362,17 +370,58 @@ func (s *session) closeProcess() {
|
||||
// findTranscriptFile locates the CLI's session file. Project directories are
|
||||
// named from the working directory, so searching is more robust than deriving
|
||||
// the encoding (and avoids guessing for a resumed/adopted session).
|
||||
// Sessions whose directory selects its own CLAUDE_CONFIG_DIR keep their
|
||||
// transcripts there, so every config directory seen is searched too.
|
||||
func findTranscriptFile(id string) string {
|
||||
base := ConfigDir()
|
||||
if base == "" || id == "" {
|
||||
if id == "" {
|
||||
return ""
|
||||
}
|
||||
matches, err := filepath.Glob(filepath.Join(base, "projects", "*", id+".jsonl"))
|
||||
if err != nil || len(matches) == 0 {
|
||||
return ""
|
||||
for _, base := range configDirs() {
|
||||
matches, err := filepath.Glob(filepath.Join(base, "projects", "*", id+".jsonl"))
|
||||
if err != nil || len(matches) == 0 {
|
||||
continue
|
||||
}
|
||||
sort.Strings(matches)
|
||||
return matches[len(matches)-1]
|
||||
}
|
||||
sort.Strings(matches)
|
||||
return matches[len(matches)-1]
|
||||
return ""
|
||||
}
|
||||
|
||||
var (
|
||||
extraConfigMu sync.Mutex
|
||||
extraConfigDirs []string
|
||||
)
|
||||
|
||||
// rememberConfigDir records a directory-provided CLAUDE_CONFIG_DIR.
|
||||
func rememberConfigDir(dir string) {
|
||||
dir = strings.TrimSpace(dir)
|
||||
if dir == "" || !filepath.IsAbs(dir) {
|
||||
return
|
||||
}
|
||||
dir = filepath.Clean(dir)
|
||||
extraConfigMu.Lock()
|
||||
defer extraConfigMu.Unlock()
|
||||
for _, known := range extraConfigDirs {
|
||||
if known == dir {
|
||||
return
|
||||
}
|
||||
}
|
||||
extraConfigDirs = append(extraConfigDirs, dir)
|
||||
}
|
||||
|
||||
func configDirs() []string {
|
||||
var dirs []string
|
||||
if base := ConfigDir(); base != "" {
|
||||
dirs = append(dirs, filepath.Clean(base))
|
||||
}
|
||||
extraConfigMu.Lock()
|
||||
defer extraConfigMu.Unlock()
|
||||
for _, dir := range extraConfigDirs {
|
||||
if len(dirs) == 0 || dir != dirs[0] {
|
||||
dirs = append(dirs, dir)
|
||||
}
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
// newSessionID returns an RFC 4122 version 4 UUID, the exact form the CLI's
|
||||
|
||||
@@ -296,8 +296,9 @@ func TestModelChoiceIsAppliedAndProcessResumes(t *testing.T) {
|
||||
}
|
||||
|
||||
type argsEntry struct {
|
||||
Args []string `json:"args"`
|
||||
Cwd string `json:"cwd"`
|
||||
Args []string `json:"args"`
|
||||
Cwd string `json:"cwd"`
|
||||
Env map[string]*string `json:"env"`
|
||||
}
|
||||
|
||||
func readArgs(t *testing.T, path string) []argsEntry {
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/workenv"
|
||||
)
|
||||
|
||||
// fakeDirenv exports .envrc.json for an allowed .envrc (marked by
|
||||
// .envrc.allowed) and reports any other .envrc as blocked, like direnv.
|
||||
const fakeDirenv = `#!/bin/sh
|
||||
[ "$1 $2" = "export json" ] || exit 2
|
||||
[ -f .envrc ] || exit 0
|
||||
if [ ! -f .envrc.allowed ]; then
|
||||
echo "direnv: error $PWD/.envrc is blocked. Run ` + "`direnv allow`" + ` to approve its content" >&2
|
||||
exit 1
|
||||
fi
|
||||
cat .envrc.json
|
||||
`
|
||||
|
||||
// directoryChat is a test chat whose server has a service token and an
|
||||
// inherited OAuth token, and whose PATH has a fake direnv.
|
||||
func directoryChat(t *testing.T) *Chat {
|
||||
t.Helper()
|
||||
chat := testChat(t)
|
||||
bin := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(bin, "direnv"), []byte(fakeDirenv), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
token := filepath.Join(t.TempDir(), "claude-token")
|
||||
if err := os.WriteFile(token, []byte("service-token\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv(ServiceTokenEnvKey, token)
|
||||
t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")
|
||||
os.Unsetenv("CLAUDE_CODE_OAUTH_TOKEN")
|
||||
t.Setenv("FAKE_CLAUDE_ENV_KEYS", "CLAUDE_CONFIG_DIR,CLAUDE_CODE_OAUTH_TOKEN,ANTHROPIC_API_KEY,GH_CONFIG_DIR,PWD")
|
||||
chat.dirEnv = &workenv.Resolver{Timeout: 10 * time.Second}
|
||||
return chat
|
||||
}
|
||||
|
||||
func writeFile(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func lastSpawn(t *testing.T) argsEntry {
|
||||
t.Helper()
|
||||
entries := readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))
|
||||
if len(entries) == 0 {
|
||||
t.Fatal("Claude Code was not started")
|
||||
}
|
||||
return entries[len(entries)-1]
|
||||
}
|
||||
|
||||
func envOf(entry argsEntry, key string) string {
|
||||
if value := entry.Env[key]; value != nil {
|
||||
return *value
|
||||
}
|
||||
return "<unset>"
|
||||
}
|
||||
|
||||
func TestDirectoryAccountWinsOverServerFallbacks(t *testing.T) {
|
||||
chat := directoryChat(t)
|
||||
t.Setenv("ANTHROPIC_API_KEY", "server-inherited-key")
|
||||
directory := t.TempDir()
|
||||
profile := filepath.Join(t.TempDir(), "profile")
|
||||
writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n")
|
||||
writeFile(t, filepath.Join(directory, ".envrc.allowed"), "")
|
||||
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`","GH_CONFIG_DIR":"/dir/gh"}`)
|
||||
|
||||
session, err := chat.Create(context.Background(), "Directory account", directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
frames := subscribe(t, chat, session.ID)
|
||||
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitStepEnded(t, frames)
|
||||
spawn := lastSpawn(t)
|
||||
if spawn.Cwd != directory && spawn.Cwd != "/private"+directory {
|
||||
t.Fatalf("cwd = %q, want %q", spawn.Cwd, directory)
|
||||
}
|
||||
if envOf(spawn, "PWD") != directory {
|
||||
t.Fatalf("PWD = %q", envOf(spawn, "PWD"))
|
||||
}
|
||||
if envOf(spawn, "CLAUDE_CONFIG_DIR") != profile || envOf(spawn, "GH_CONFIG_DIR") != "/dir/gh" {
|
||||
t.Fatalf("directory environment not applied: %v", spawn.Env)
|
||||
}
|
||||
if envOf(spawn, "CLAUDE_CODE_OAUTH_TOKEN") != "<unset>" {
|
||||
t.Fatal("the service token overrode the directory's account")
|
||||
}
|
||||
if envOf(spawn, "ANTHROPIC_API_KEY") != "<unset>" {
|
||||
t.Fatal("an inherited server credential overrode the directory's account")
|
||||
}
|
||||
// The transcript lives in the directory's profile; history and resume find it.
|
||||
if matches, _ := filepath.Glob(filepath.Join(profile, "projects", "*", session.ID+".jsonl")); len(matches) != 1 {
|
||||
t.Fatalf("transcript not in the directory profile: %v", matches)
|
||||
}
|
||||
page, err := chat.Messages(context.Background(), session.ID, 50, "")
|
||||
if err != nil || len(page.Messages) == 0 {
|
||||
t.Fatalf("history from the directory profile: %+v %v", page, err)
|
||||
}
|
||||
chat.session(session.ID).closeProcess()
|
||||
if err := chat.Prompt(context.Background(), session.ID, "again"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitStepEnded(t, frames)
|
||||
if argValue(lastSpawn(t).Args, "--resume") != session.ID {
|
||||
t.Fatalf("restart did not resume from the directory profile: %+v", lastSpawn(t).Args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlockedEnvrcIsNotAppliedAndShownInChat(t *testing.T) {
|
||||
chat := directoryChat(t)
|
||||
directory := t.TempDir()
|
||||
writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n")
|
||||
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"/never"}`)
|
||||
|
||||
session, err := chat.Create(context.Background(), "Blocked", directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
frames := subscribe(t, chat, session.ID)
|
||||
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFrame(t, frames, "environment notice", func(frame protocol.ChatEventFrame) bool {
|
||||
return frame.Kind == protocol.ChatEventTool && frame.Part != nil && frame.Part.Name == "Directory environment" &&
|
||||
frame.Part.State != nil && frame.Part.State.Error != nil &&
|
||||
strings.Contains(frame.Part.State.Error.Message, "not allowed") &&
|
||||
strings.Contains(frame.Part.State.Error.Message, "direnv allow")
|
||||
})
|
||||
waitStepEnded(t, frames)
|
||||
spawn := lastSpawn(t)
|
||||
if envOf(spawn, "CLAUDE_CONFIG_DIR") == "/never" {
|
||||
t.Fatal("a blocked .envrc was applied")
|
||||
}
|
||||
// Without a directory account the server's own fallback still signs in.
|
||||
if envOf(spawn, "CLAUDE_CODE_OAUTH_TOKEN") != "service-token" {
|
||||
t.Fatalf("service token fallback missing without a directory account: %v", spawn.Env)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(directory, ".envrc.allowed")); err == nil {
|
||||
t.Fatal("the .envrc was allowed by the server")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectoryWithoutEnvironmentKeepsServerSignIn(t *testing.T) {
|
||||
chat := directoryChat(t)
|
||||
session := newCreatedChat(t, chat)
|
||||
frames := subscribe(t, chat, session.ID)
|
||||
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitStepEnded(t, frames)
|
||||
if spawn := lastSpawn(t); envOf(spawn, "CLAUDE_CODE_OAUTH_TOKEN") != "service-token" {
|
||||
t.Fatalf("env: %v", spawn.Env)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitIdentityFollowsTheChatDirectory(t *testing.T) {
|
||||
if _, err := exec.LookPath("git"); err != nil {
|
||||
t.Skip("git not installed")
|
||||
}
|
||||
chat := directoryChat(t)
|
||||
root := t.TempDir()
|
||||
repo := filepath.Join(root, "work", "repo")
|
||||
if err := os.MkdirAll(repo, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out, err := exec.Command("git", "init", "-q", repo).CombinedOutput(); err != nil {
|
||||
t.Fatalf("git init: %v %s", err, out)
|
||||
}
|
||||
included := filepath.Join(root, "work.gitconfig")
|
||||
writeFile(t, included, "[user]\n\temail = work@example.test\n")
|
||||
global := filepath.Join(root, "global.gitconfig")
|
||||
writeFile(t, global, "[user]\n\temail = personal@example.test\n[includeIf \"gitdir:"+filepath.Join(root, "work")+"/\"]\n\tpath = "+included+"\n")
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", global)
|
||||
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
t.Setenv("FAKE_CLAUDE_GIT_EMAIL", "1")
|
||||
|
||||
session, err := chat.Create(context.Background(), "Git", repo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
frames := subscribe(t, chat, session.ID)
|
||||
if err := chat.Prompt(context.Background(), session.ID, "hello"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitStepEnded(t, frames)
|
||||
if got := envOf(lastSpawn(t), "git user.email"); got != "work@example.test" {
|
||||
t.Fatalf("git identity in the chat directory = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHintDirectoryFindsATranscriptInTheDirectoryProfile(t *testing.T) {
|
||||
chat := directoryChat(t)
|
||||
directory := t.TempDir()
|
||||
profile := filepath.Join(t.TempDir(), "hinted-profile")
|
||||
writeFile(t, filepath.Join(directory, ".envrc"), "")
|
||||
writeFile(t, filepath.Join(directory, ".envrc.allowed"), "")
|
||||
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`"}`)
|
||||
id := "11111111-2222-4333-8444-555555555555"
|
||||
projects := filepath.Join(profile, "projects", "x")
|
||||
if err := os.MkdirAll(projects, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeFile(t, filepath.Join(projects, id+".jsonl"), `{"type":"user","cwd":"`+directory+`","timestamp":"2026-01-01T00:00:00Z","message":{"role":"user","content":"hi"}}`+"\n")
|
||||
if _, found, _ := chat.Session(context.Background(), id); found {
|
||||
t.Fatal("found before the hint")
|
||||
}
|
||||
chat.HintDirectory(context.Background(), id, directory)
|
||||
if session, found, err := chat.Session(context.Background(), id); err != nil || !found || session.Directory != directory {
|
||||
t.Fatalf("after hint: %+v %v %v", session, found, err)
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,11 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
|
||||
}
|
||||
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
|
||||
cmd.Dir = s.directory
|
||||
cmd.Env = s.chat.auth.resolve(s.chat.ctx, s.chat.binary, withServiceToken(os.Environ()))
|
||||
env, notices := s.chat.processEnv(ctx, s.directory)
|
||||
cmd.Env = env
|
||||
s.mu.Lock()
|
||||
s.envNotices = notices
|
||||
s.mu.Unlock()
|
||||
cmd.WaitDelay = 5 * time.Second
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
|
||||
+7
-1
@@ -22,7 +22,13 @@ for index, arg in enumerate(args):
|
||||
log_path = os.environ.get("FAKE_CLAUDE_LOG")
|
||||
if log_path:
|
||||
with open(log_path, "a", encoding="utf-8") as log:
|
||||
log.write(json.dumps({"args": args, "cwd": os.getcwd()}) + "\n")
|
||||
keys = [k for k in os.environ.get("FAKE_CLAUDE_ENV_KEYS", "").split(",") if k]
|
||||
env = {k: os.environ.get(k) for k in keys}
|
||||
if os.environ.get("FAKE_CLAUDE_GIT_EMAIL"):
|
||||
import subprocess
|
||||
result = subprocess.run(["git", "config", "user.email"], capture_output=True, text=True)
|
||||
env["git user.email"] = result.stdout.strip()
|
||||
log.write(json.dumps({"args": args, "cwd": os.getcwd(), "env": env}) + "\n")
|
||||
|
||||
if os.environ.get("FAKE_CLAUDE_FAIL"):
|
||||
sys.stderr.write("Please run /login to sign in\n")
|
||||
|
||||
@@ -41,6 +41,7 @@ type chatManager struct {
|
||||
claude chatBroker // guarded by mu once the manager is shared
|
||||
closed bool
|
||||
cache map[string]string // session id -> backend
|
||||
hinted map[string]bool // sessions whose directory was given to a chatDirectoryHinter
|
||||
}
|
||||
|
||||
// harnessProbeInterval bounds how often a missing harness is probed again, so
|
||||
@@ -272,9 +273,33 @@ func (m *chatManager) brokerFor(ctx context.Context, sessionID string) (chatBrok
|
||||
if adapter == nil {
|
||||
return nil, errors.New("chat backend " + backend + " is not available")
|
||||
}
|
||||
if hinter, ok := adapter.(chatDirectoryHinter); ok && m.registry != nil {
|
||||
m.mu.Lock()
|
||||
done := m.hinted[sessionID]
|
||||
m.mu.Unlock()
|
||||
if !done {
|
||||
if row, found, err := m.registry.OperatorSession(ctx, sessionID); err == nil && found {
|
||||
hinter.HintDirectory(ctx, sessionID, row.Directory)
|
||||
m.mu.Lock()
|
||||
if m.hinted == nil {
|
||||
m.hinted = map[string]bool{}
|
||||
}
|
||||
m.hinted[sessionID] = true
|
||||
m.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
return adapter, nil
|
||||
}
|
||||
|
||||
// chatDirectoryHinter is a harness that needs a session's recorded directory
|
||||
// to find it after a restart (Claude Code keeps a transcript in the
|
||||
// directory's own CLAUDE_CONFIG_DIR). HintDirectory is cheap after the first
|
||||
// call for a session.
|
||||
type chatDirectoryHinter interface {
|
||||
HintDirectory(ctx context.Context, sessionID, directory string)
|
||||
}
|
||||
|
||||
// CreateBackend creates a session on the requested harness. An empty backend
|
||||
// keeps the OpenCode default.
|
||||
func (m *chatManager) CreateBackend(ctx context.Context, title, directory, backend string) (protocol.ChatSession, error) {
|
||||
@@ -576,6 +601,9 @@ func (m *chatManager) Sessions(ctx context.Context) ([]protocol.ChatSession, err
|
||||
if adapter == nil {
|
||||
continue
|
||||
}
|
||||
if hinter, ok := adapter.(chatDirectoryHinter); ok {
|
||||
hinter.HintDirectory(ctx, row.ID, row.Directory)
|
||||
}
|
||||
if session, found, err := adapter.Session(ctx, row.ID); err == nil && found {
|
||||
seen[row.ID] = true
|
||||
sessions = append(sessions, session)
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
// Package workenv computes the environment a shell would have after `cd` into
|
||||
// a directory, so a harness the server starts there behaves as if the
|
||||
// operator had opened a terminal in that directory and started it.
|
||||
//
|
||||
// Two per-directory mechanisms are applied when their tool is installed:
|
||||
// direnv (`direnv export json`, only for an .envrc the operator already
|
||||
// allowed) and mise (`mise env --json`, only for trusted config). A plain
|
||||
// .env file is deliberately not read: direnv decides whether it applies.
|
||||
// Results are cached per directory until a watched file changes.
|
||||
package workenv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DisableEnvKey turns per-directory environments off when set to "off" in the
|
||||
// server's environment.
|
||||
const DisableEnvKey = "PIPELINES_DIRECTORY_ENV"
|
||||
|
||||
// Result is the change a directory makes to the server's base environment.
|
||||
type Result struct {
|
||||
// Changes maps a variable to its new value; a nil value unsets it.
|
||||
Changes map[string]*string
|
||||
// Sources names what contributed, for example "direnv" or "mise".
|
||||
Sources []string
|
||||
// Warnings are operator-facing notices: a blocked .envrc, an untrusted
|
||||
// mise config, or a tool that failed. Nothing from a warned source is applied.
|
||||
Warnings []string
|
||||
}
|
||||
|
||||
// Touches reports whether the directory sets or unsets key.
|
||||
func (r Result) Touches(key string) bool {
|
||||
_, ok := r.Changes[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Value returns the directory's value for key; ok is false when it does not
|
||||
// set it (an unset also reports ok false).
|
||||
func (r Result) Value(key string) (string, bool) {
|
||||
value, ok := r.Changes[key]
|
||||
if !ok || value == nil {
|
||||
return "", false
|
||||
}
|
||||
return *value, true
|
||||
}
|
||||
|
||||
// Apply returns base with the directory's changes merged on top.
|
||||
func (r Result) Apply(base []string) []string {
|
||||
if len(r.Changes) == 0 {
|
||||
return append([]string{}, base...)
|
||||
}
|
||||
out := make([]string, 0, len(base)+len(r.Changes))
|
||||
for _, item := range base {
|
||||
key, _, _ := strings.Cut(item, "=")
|
||||
if _, changed := r.Changes[key]; changed {
|
||||
continue
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
keys := make([]string, 0, len(r.Changes))
|
||||
for key := range r.Changes {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
if value := r.Changes[key]; value != nil {
|
||||
out = append(out, key+"="+*value)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Resolver runs and caches the per-directory tools.
|
||||
type Resolver struct {
|
||||
// SearchDirs are tried after the base environment's PATH when looking for
|
||||
// direnv and mise (a login service often has a short PATH).
|
||||
SearchDirs []string
|
||||
Timeout time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
cache map[string]cacheEntry
|
||||
running map[string]*sync.Mutex
|
||||
}
|
||||
|
||||
type cacheEntry struct {
|
||||
fingerprint string
|
||||
watches []string
|
||||
result Result
|
||||
}
|
||||
|
||||
// New returns a resolver that also looks in the usual install locations.
|
||||
func New() *Resolver {
|
||||
dirs := []string{"/opt/homebrew/bin", "/usr/local/bin"}
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
dirs = append(dirs, filepath.Join(home, ".local", "bin"), filepath.Join(home, ".nix-profile", "bin"))
|
||||
}
|
||||
return &Resolver{SearchDirs: dirs, Timeout: 30 * time.Second}
|
||||
}
|
||||
|
||||
// Default is the server-wide resolver.
|
||||
var Default = New()
|
||||
|
||||
// Resolve returns the environment changes for directory relative to base.
|
||||
// It never fails: problems are reported as warnings and nothing from the
|
||||
// failing source is applied.
|
||||
func (r *Resolver) Resolve(ctx context.Context, directory string, base []string) Result {
|
||||
directory = filepath.Clean(directory)
|
||||
if strings.EqualFold(strings.TrimSpace(lookup(base, DisableEnvKey)), "off") || !filepath.IsAbs(directory) {
|
||||
return Result{}
|
||||
}
|
||||
lock := r.dirLock(directory)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
direnv := r.find(base, "direnv")
|
||||
mise := r.find(base, "mise")
|
||||
if direnv == "" && mise == "" {
|
||||
return Result{}
|
||||
}
|
||||
r.mu.Lock()
|
||||
previous, cached := r.cache[directory]
|
||||
r.mu.Unlock()
|
||||
fingerprint := r.fingerprint(directory, base, direnv, mise, previous.watches)
|
||||
if cached && previous.fingerprint == fingerprint {
|
||||
return previous.result
|
||||
}
|
||||
|
||||
result := Result{Changes: map[string]*string{}}
|
||||
var watches []string
|
||||
clean := withoutDirenvState(base)
|
||||
if mise != "" {
|
||||
changes, warning := r.runMise(ctx, mise, directory, clean)
|
||||
if warning != "" {
|
||||
result.Warnings = append(result.Warnings, warning)
|
||||
} else if len(changes) > 0 {
|
||||
for key, value := range changes {
|
||||
result.Changes[key] = value
|
||||
}
|
||||
result.Sources = append(result.Sources, "mise")
|
||||
}
|
||||
}
|
||||
if direnv != "" {
|
||||
changes, watched, warning := r.runDirenv(ctx, direnv, directory, clean)
|
||||
watches = watched
|
||||
if warning != "" {
|
||||
result.Warnings = append(result.Warnings, warning)
|
||||
} else if len(changes) > 0 {
|
||||
for key, value := range changes {
|
||||
result.Changes[key] = value
|
||||
}
|
||||
result.Sources = append(result.Sources, "direnv")
|
||||
}
|
||||
}
|
||||
// A cancelled lookup is not cached; the next start tries again.
|
||||
if ctx.Err() == nil {
|
||||
entry := cacheEntry{result: result, watches: watches}
|
||||
entry.fingerprint = r.fingerprint(directory, base, direnv, mise, watches)
|
||||
r.mu.Lock()
|
||||
if r.cache == nil {
|
||||
r.cache = map[string]cacheEntry{}
|
||||
}
|
||||
r.cache[directory] = entry
|
||||
r.mu.Unlock()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (r *Resolver) dirLock(directory string) *sync.Mutex {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.running == nil {
|
||||
r.running = map[string]*sync.Mutex{}
|
||||
}
|
||||
lock := r.running[directory]
|
||||
if lock == nil {
|
||||
lock = &sync.Mutex{}
|
||||
r.running[directory] = lock
|
||||
}
|
||||
return lock
|
||||
}
|
||||
|
||||
func (r *Resolver) find(base []string, name string) string {
|
||||
dirs := filepath.SplitList(lookup(base, "PATH"))
|
||||
dirs = append(dirs, r.SearchDirs...)
|
||||
for _, dir := range dirs {
|
||||
if dir == "" || !filepath.IsAbs(dir) {
|
||||
continue
|
||||
}
|
||||
candidate := filepath.Join(dir, name)
|
||||
if info, err := os.Stat(candidate); err == nil && !info.IsDir() && info.Mode()&0o111 != 0 {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (r *Resolver) timeout() time.Duration {
|
||||
if r.Timeout > 0 {
|
||||
return r.Timeout
|
||||
}
|
||||
return 30 * time.Second
|
||||
}
|
||||
|
||||
// run executes one tool in directory and returns stdout, a bounded stderr
|
||||
// and the error.
|
||||
func (r *Resolver) run(ctx context.Context, binary, directory string, env []string, args ...string) ([]byte, string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, r.timeout())
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, binary, args...)
|
||||
cmd.Dir = directory
|
||||
cmd.Env = WithPWD(env, directory)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
cmd.WaitDelay = 2 * time.Second
|
||||
err := cmd.Run()
|
||||
return stdout.Bytes(), stderr.String(), err
|
||||
}
|
||||
|
||||
var blockedRC = regexp.MustCompile(`(\S+) is blocked`)
|
||||
|
||||
func (r *Resolver) runDirenv(ctx context.Context, binary, directory string, env []string) (map[string]*string, []string, string) {
|
||||
stdout, stderr, err := r.run(ctx, binary, directory, env, "export", "json")
|
||||
if match := blockedRC.FindStringSubmatch(stderr); match != nil {
|
||||
return nil, nil, fmt.Sprintf("direnv: %s is not allowed, so its environment was not applied. Run `direnv allow` in %s to use it.", match[1], filepath.Dir(match[1]))
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, "direnv export failed in " + directory + ", so its environment was not applied: " + firstLine(stderr, err)
|
||||
}
|
||||
changes := map[string]*string{}
|
||||
if text := bytes.TrimSpace(stdout); len(text) > 0 {
|
||||
if err := json.Unmarshal(text, &changes); err != nil {
|
||||
return nil, nil, "direnv export returned invalid output in " + directory + "; its environment was not applied"
|
||||
}
|
||||
}
|
||||
var watches []string
|
||||
if encoded := changes["DIRENV_WATCHES"]; encoded != nil {
|
||||
watches = decodeWatches(*encoded)
|
||||
}
|
||||
for key := range changes {
|
||||
if strings.HasPrefix(key, "DIRENV_") {
|
||||
delete(changes, key)
|
||||
}
|
||||
}
|
||||
return changes, watches, ""
|
||||
}
|
||||
|
||||
func (r *Resolver) runMise(ctx context.Context, binary, directory string, env []string) (map[string]*string, string) {
|
||||
stdout, stderr, err := r.run(ctx, binary, directory, env, "env", "--json")
|
||||
if err != nil {
|
||||
lower := strings.ToLower(stderr)
|
||||
if strings.Contains(lower, "not trusted") {
|
||||
return nil, "mise: config for " + directory + " is not trusted, so its environment was not applied. Run `mise trust` there to use it."
|
||||
}
|
||||
return nil, "mise env failed in " + directory + ", so its environment was not applied: " + firstLine(stderr, err)
|
||||
}
|
||||
values := map[string]string{}
|
||||
if text := bytes.TrimSpace(stdout); len(text) > 0 {
|
||||
if err := json.Unmarshal(text, &values); err != nil {
|
||||
return nil, "mise env returned invalid output in " + directory + "; its environment was not applied"
|
||||
}
|
||||
}
|
||||
changes := map[string]*string{}
|
||||
for key, value := range values {
|
||||
if current, ok := lookupOK(env, key); ok && current == value {
|
||||
continue
|
||||
}
|
||||
value := value
|
||||
changes[key] = &value
|
||||
}
|
||||
return changes, ""
|
||||
}
|
||||
|
||||
// fingerprint changes when anything that can change the tools' answers
|
||||
// changes: the candidate config files from directory up to /, the files
|
||||
// direnv reported watching, direnv's allow/deny records, and the binaries.
|
||||
func (r *Resolver) fingerprint(directory string, base []string, direnv, mise string, watches []string) string {
|
||||
var paths []string
|
||||
paths = append(paths, direnv, mise)
|
||||
for dir := directory; ; dir = filepath.Dir(dir) {
|
||||
for _, name := range configNames {
|
||||
paths = append(paths, filepath.Join(dir, name))
|
||||
}
|
||||
if parent := filepath.Dir(dir); parent == dir {
|
||||
break
|
||||
}
|
||||
}
|
||||
paths = append(paths, watches...)
|
||||
data := lookup(base, "XDG_DATA_HOME")
|
||||
config := lookup(base, "XDG_CONFIG_HOME")
|
||||
if home := lookup(base, "HOME"); home != "" {
|
||||
if data == "" {
|
||||
data = filepath.Join(home, ".local", "share")
|
||||
}
|
||||
if config == "" {
|
||||
config = filepath.Join(home, ".config")
|
||||
}
|
||||
}
|
||||
if data != "" {
|
||||
paths = append(paths, filepath.Join(data, "direnv", "allow"), filepath.Join(data, "direnv", "deny"), filepath.Join(data, "mise", "trusted-configs"))
|
||||
}
|
||||
if config != "" {
|
||||
paths = append(paths, filepath.Join(config, "direnv", "direnv.toml"), filepath.Join(config, "mise", "config.toml"))
|
||||
}
|
||||
var b strings.Builder
|
||||
for _, path := range paths {
|
||||
if path == "" {
|
||||
continue
|
||||
}
|
||||
b.WriteString(path)
|
||||
if info, err := os.Stat(path); err == nil {
|
||||
fmt.Fprintf(&b, ":%d:%d:%o", info.ModTime().UnixNano(), info.Size(), info.Mode())
|
||||
} else {
|
||||
b.WriteString(":-")
|
||||
}
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// configNames are the per-directory files direnv and mise read.
|
||||
var configNames = []string{
|
||||
".envrc", ".env",
|
||||
"mise.toml", ".mise.toml", "mise.local.toml", ".mise.local.toml",
|
||||
filepath.Join(".config", "mise.toml"), filepath.Join(".config", "mise", "config.toml"),
|
||||
filepath.Join("mise", "config.toml"), filepath.Join(".mise", "config.toml"),
|
||||
".tool-versions",
|
||||
}
|
||||
|
||||
// decodeWatches reads direnv's DIRENV_WATCHES (zlib-compressed JSON in URL
|
||||
// base64). An unreadable value only means less precise invalidation.
|
||||
func decodeWatches(encoded string) []string {
|
||||
raw, err := base64.URLEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
if raw, err = base64.RawURLEncoding.DecodeString(encoded); err != nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
reader, err := zlib.NewReader(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer reader.Close()
|
||||
plain, err := io.ReadAll(io.LimitReader(reader, 1<<20))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var entries []struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if json.Unmarshal(plain, &entries) != nil {
|
||||
return nil
|
||||
}
|
||||
paths := make([]string, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.Path != "" {
|
||||
paths = append(paths, entry.Path)
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// WithPWD returns env with PWD naming directory, as a shell that changed into
|
||||
// it would have (the logical path, not a resolved symlink).
|
||||
func WithPWD(env []string, directory string) []string {
|
||||
out := make([]string, 0, len(env)+1)
|
||||
for _, item := range env {
|
||||
if !strings.HasPrefix(item, "PWD=") {
|
||||
out = append(out, item)
|
||||
}
|
||||
}
|
||||
return append(out, "PWD="+directory)
|
||||
}
|
||||
|
||||
// withoutDirenvState drops direnv's own bookkeeping so the export is computed
|
||||
// from the server's environment, not a shell the server was started from.
|
||||
func withoutDirenvState(base []string) []string {
|
||||
out := make([]string, 0, len(base))
|
||||
for _, item := range base {
|
||||
if strings.HasPrefix(item, "DIRENV_") {
|
||||
continue
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func firstLine(stderr string, err error) string {
|
||||
for _, line := range strings.Split(stderr, "\n") {
|
||||
if line = strings.TrimSpace(line); line != "" {
|
||||
if len(line) > 300 {
|
||||
line = line[:300] + "..."
|
||||
}
|
||||
return line
|
||||
}
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func lookup(env []string, key string) string {
|
||||
value, _ := lookupOK(env, key)
|
||||
return value
|
||||
}
|
||||
|
||||
func lookupOK(env []string, key string) (string, bool) {
|
||||
for i := len(env) - 1; i >= 0; i-- {
|
||||
if k, v, ok := strings.Cut(env[i], "="); ok && k == key {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package workenv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// FakeDirenv is a stand-in for direnv: an .envrc next to an .envrc.allowed
|
||||
// marker exports the JSON in .envrc.json; any other .envrc is blocked. Each
|
||||
// call appends a line to $FAKE_TOOL_CALLS.
|
||||
const FakeDirenv = `#!/bin/sh
|
||||
echo direnv >> "$FAKE_TOOL_CALLS"
|
||||
[ "$1 $2" = "export json" ] || exit 2
|
||||
[ -f .envrc ] || exit 0
|
||||
if [ ! -f .envrc.allowed ]; then
|
||||
echo "direnv: error $PWD/.envrc is blocked. Run ` + "`direnv allow`" + ` to approve its content" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "direnv: loading $PWD/.envrc" >&2
|
||||
cat .envrc.json
|
||||
`
|
||||
|
||||
const fakeMise = `#!/bin/sh
|
||||
echo mise >> "$FAKE_TOOL_CALLS"
|
||||
[ "$1 $2" = "env --json" ] || exit 2
|
||||
if [ -f mise.toml ]; then
|
||||
if [ -f mise.untrusted ]; then echo "mise ERROR Config files in $PWD/mise.toml are not trusted." >&2; exit 1; fi
|
||||
cat mise.json
|
||||
exit 0
|
||||
fi
|
||||
echo '{}'
|
||||
`
|
||||
|
||||
func install(t *testing.T, bin, name, script string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(bin, name), []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func write(t *testing.T, path, content string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func setup(t *testing.T) (*Resolver, string, []string, string) {
|
||||
t.Helper()
|
||||
bin := t.TempDir()
|
||||
calls := filepath.Join(t.TempDir(), "calls")
|
||||
base := []string{"PATH=" + bin + ":/usr/bin:/bin", "HOME=" + t.TempDir(), "FAKE_TOOL_CALLS=" + calls, "KEEP=1", "DROP=1"}
|
||||
return &Resolver{Timeout: 10 * time.Second}, bin, base, calls
|
||||
}
|
||||
|
||||
func calls(t *testing.T, path string) int {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return strings.Count(string(data), "\n")
|
||||
}
|
||||
|
||||
func TestNoToolsNoChanges(t *testing.T) {
|
||||
r, _, base, _ := setup(t)
|
||||
if got := r.Resolve(context.Background(), t.TempDir(), base); len(got.Changes) != 0 || len(got.Warnings) != 0 {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowedEnvrcIsAppliedAndCached(t *testing.T) {
|
||||
r, bin, base, callLog := setup(t)
|
||||
install(t, bin, "direnv", FakeDirenv)
|
||||
dir := t.TempDir()
|
||||
write(t, filepath.Join(dir, ".envrc"), "export CLAUDE_CONFIG_DIR=x\nunset DROP\n")
|
||||
write(t, filepath.Join(dir, ".envrc.allowed"), "")
|
||||
write(t, filepath.Join(dir, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"/profile","DROP":null,"DIRENV_DIR":"-`+dir+`"}`)
|
||||
got := r.Resolve(context.Background(), dir, base)
|
||||
if v, ok := got.Value("CLAUDE_CONFIG_DIR"); !ok || v != "/profile" || len(got.Warnings) != 0 {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
if got.Touches("DIRENV_DIR") {
|
||||
t.Fatal("direnv bookkeeping leaked into the environment")
|
||||
}
|
||||
env := strings.Join(got.Apply(base), "\n")
|
||||
if !strings.Contains(env, "CLAUDE_CONFIG_DIR=/profile") || strings.Contains(env, "DROP=") || !strings.Contains(env, "KEEP=1") {
|
||||
t.Fatalf("merged env: %s", env)
|
||||
}
|
||||
r.Resolve(context.Background(), dir, base)
|
||||
if n := calls(t, callLog); n != 1 {
|
||||
t.Fatalf("unchanged directory ran direnv %d times", n)
|
||||
}
|
||||
// Editing the .envrc invalidates the cache.
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
write(t, filepath.Join(dir, ".envrc"), "export CLAUDE_CONFIG_DIR=y\n")
|
||||
write(t, filepath.Join(dir, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"/other"}`)
|
||||
got = r.Resolve(context.Background(), dir, base)
|
||||
if v, _ := got.Value("CLAUDE_CONFIG_DIR"); v != "/other" || calls(t, callLog) != 2 {
|
||||
t.Fatalf("edited .envrc not re-read: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParentEnvrcAppliesToSubdirectory(t *testing.T) {
|
||||
r, bin, base, _ := setup(t)
|
||||
// A real direnv walks up; the fake only reads the cwd, so point a wrapper
|
||||
// at the parent to check the resolver runs in the chosen directory and
|
||||
// fingerprints parent files.
|
||||
parent := t.TempDir()
|
||||
child := filepath.Join(parent, "repo")
|
||||
if err := os.Mkdir(child, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
install(t, bin, "direnv", "#!/bin/sh\necho direnv >> \"$FAKE_TOOL_CALLS\"\n[ \"$PWD\" = \""+child+"\" ] || exit 3\ncat ../.envrc.json\n")
|
||||
write(t, filepath.Join(parent, ".envrc.json"), `{"A":"1"}`)
|
||||
got := r.Resolve(context.Background(), child, base)
|
||||
if v, _ := got.Value("A"); v != "1" {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
write(t, filepath.Join(parent, ".envrc"), "x")
|
||||
write(t, filepath.Join(parent, ".envrc.json"), `{"A":"2"}`)
|
||||
if v, _ := r.Resolve(context.Background(), child, base).Value("A"); v != "2" {
|
||||
t.Fatal("a new parent .envrc did not invalidate the cache")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlockedEnvrcWarnsAndIsNotApplied(t *testing.T) {
|
||||
r, bin, base, _ := setup(t)
|
||||
install(t, bin, "direnv", FakeDirenv)
|
||||
dir := t.TempDir()
|
||||
write(t, filepath.Join(dir, ".envrc"), "export CLAUDE_CONFIG_DIR=x\n")
|
||||
write(t, filepath.Join(dir, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"/profile"}`)
|
||||
got := r.Resolve(context.Background(), dir, base)
|
||||
if len(got.Changes) != 0 {
|
||||
t.Fatalf("blocked .envrc applied: %+v", got)
|
||||
}
|
||||
if len(got.Warnings) != 1 || !strings.Contains(got.Warnings[0], "not allowed") || !strings.Contains(got.Warnings[0], "direnv allow") {
|
||||
t.Fatalf("warnings: %+v", got.Warnings)
|
||||
}
|
||||
// Allowing it later (direnv's allow record or the file changes) is seen.
|
||||
write(t, filepath.Join(dir, ".envrc.allowed"), "")
|
||||
write(t, filepath.Join(dir, ".envrc"), "export CLAUDE_CONFIG_DIR=x \n")
|
||||
if v, _ := r.Resolve(context.Background(), dir, base).Value("CLAUDE_CONFIG_DIR"); v != "/profile" {
|
||||
t.Fatal("allowed .envrc not applied after change")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiseEnvIsAppliedAndUntrustedWarns(t *testing.T) {
|
||||
r, bin, base, _ := setup(t)
|
||||
install(t, bin, "mise", fakeMise)
|
||||
dir := t.TempDir()
|
||||
write(t, filepath.Join(dir, "mise.toml"), "[env]\nGH_CONFIG_DIR='/gh'\n")
|
||||
write(t, filepath.Join(dir, "mise.json"), `{"GH_CONFIG_DIR":"/gh","KEEP":"1"}`)
|
||||
got := r.Resolve(context.Background(), dir, base)
|
||||
if v, _ := got.Value("GH_CONFIG_DIR"); v != "/gh" || got.Touches("KEEP") {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
write(t, filepath.Join(dir, "mise.untrusted"), "")
|
||||
write(t, filepath.Join(dir, "mise.toml"), "[env]\nGH_CONFIG_DIR='/gh2'\n")
|
||||
got = r.Resolve(context.Background(), dir, base)
|
||||
if len(got.Changes) != 0 || len(got.Warnings) != 1 || !strings.Contains(got.Warnings[0], "mise trust") {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirenvWinsOverMise(t *testing.T) {
|
||||
r, bin, base, _ := setup(t)
|
||||
install(t, bin, "mise", fakeMise)
|
||||
install(t, bin, "direnv", FakeDirenv)
|
||||
dir := t.TempDir()
|
||||
write(t, filepath.Join(dir, "mise.toml"), "")
|
||||
write(t, filepath.Join(dir, "mise.json"), `{"X":"mise","M":"1"}`)
|
||||
write(t, filepath.Join(dir, ".envrc"), "")
|
||||
write(t, filepath.Join(dir, ".envrc.allowed"), "")
|
||||
write(t, filepath.Join(dir, ".envrc.json"), `{"X":"direnv"}`)
|
||||
got := r.Resolve(context.Background(), dir, base)
|
||||
if x, _ := got.Value("X"); x != "direnv" {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
if m, _ := got.Value("M"); m != "1" {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisabled(t *testing.T) {
|
||||
r, bin, base, _ := setup(t)
|
||||
install(t, bin, "direnv", FakeDirenv)
|
||||
dir := t.TempDir()
|
||||
write(t, filepath.Join(dir, ".envrc"), "")
|
||||
if got := r.Resolve(context.Background(), dir, append(base, DisableEnvKey+"=off")); len(got.Changes)+len(got.Warnings) != 0 {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeWatches(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
w := zlib.NewWriter(&buf)
|
||||
_, _ = w.Write([]byte(`[{"path":"/a/.envrc","modtime":1,"exists":true}]`))
|
||||
_ = w.Close()
|
||||
got := decodeWatches(base64.URLEncoding.EncodeToString(buf.Bytes()))
|
||||
if len(got) != 1 || got[0] != "/a/.envrc" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
if decodeWatches("!!") != nil {
|
||||
t.Fatal("garbage decoded")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user