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
32 changes: 28 additions & 4 deletions pkgs/mcpx/internal/config/execid.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,17 @@ func (r *Resolved) ExecIdentity() string {
// lands in between leaves a stamp that differs from the file and the next
// check sees it.
func (r *Resolved) ExecState() (st ExecStamp, identity string, ok bool) {
return r.ExecStateAt(r.Cwd)
}

// ExecStateAt is ExecState for a child whose effective spawn cwd is cwd.
// Scope-rooted instances use this instead of resolving a relative command
// against the daemon's cwd (decision 0004, review of #958).
func (r *Resolved) ExecStateAt(cwd string) (st ExecStamp, identity string, ok bool) {
if !r.Stdio() {
return ExecStamp{}, "", false
}
st, found := r.ExecStamp()
st, found := r.ExecStampAt(cwd)
if found {
if id, err := st.Identity(); err == nil {
return st, id, true
Expand All @@ -91,10 +98,15 @@ type ExecStamp struct {
// server that is not a child process, and for a command that does not
// resolve to a file it can stat.
func (r *Resolved) ExecStamp() (ExecStamp, bool) {
return r.ExecStampAt(r.Cwd)
}

// ExecStampAt is ExecStamp for a child with effective spawn cwd cwd.
func (r *Resolved) ExecStampAt(cwd string) (ExecStamp, bool) {
if !r.Stdio() {
return ExecStamp{}, false
}
path := r.resolveExec()
path := r.resolveExecAt(cwd)
if path == "" {
return ExecStamp{}, false
}
Expand Down Expand Up @@ -168,10 +180,22 @@ func (r *Resolved) ProcessID() string {
// child will see -- the server's own env if it sets one, else the daemon's --
// rather than the daemon's PATH alone, since a server can set its own.
func (r *Resolved) resolveExec() string {
return r.resolveExecAt(r.Cwd)
}

// ExecUsesScopeRoot reports whether resolving the configured executable can
// depend on a scope root. A relative command containing a path separator is
// resolved by the child relative to its effective spawn cwd when no config
// cwd is set.
func (r *Resolved) ExecUsesScopeRoot() bool {
return r.Cwd == "" && strings.Contains(r.Command, string(filepath.Separator)) && !filepath.IsAbs(r.Command)
}

func (r *Resolved) resolveExecAt(cwd string) string {
if strings.Contains(r.Command, string(filepath.Separator)) {
p := r.Command
if !filepath.IsAbs(p) && r.Cwd != "" {
p = filepath.Join(r.Cwd, p)
if !filepath.IsAbs(p) && cwd != "" {
p = filepath.Join(cwd, p)
}
if isExecutable(p) {
return p
Expand Down
18 changes: 18 additions & 0 deletions pkgs/mcpx/internal/config/execid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,24 @@ func TestExecIdentityResolvesAgainstTheServersOwnPath(t *testing.T) {
}
}

func TestExecStampAtResolvesRelativeCommandFromEffectiveSpawnCwd(t *testing.T) {
root := testsupport.TempDir(t)
bin := filepath.Join(root, "server")
writeExec(t, bin, "#!/bin/sh\n")
r := &Resolved{Server: &Server{Command: "./server"}}
st, ok := r.ExecStampAt(root)
if !ok || st.Path != bin {
t.Fatalf("stamp at scope root = %+v, %v; want %s", st, ok, bin)
}
if !r.ExecUsesScopeRoot() {
t.Fatal("relative command without config cwd was not marked scope-root-dependent")
}
r.Cwd = root
if r.ExecUsesScopeRoot() {
t.Fatal("explicit config cwd should keep executable resolution pool-wide")
}
}

// A symlink re-pointed at a byte-identical file runs the same program, so it
// keeps its identity; the stamp still moves, which is what makes the check
// look again.
Expand Down
80 changes: 58 additions & 22 deletions pkgs/mcpx/internal/config/scope.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,64 +64,100 @@ func (c CallContext) CallerOwned(key string) bool {
(c.PID > 0 && !c.PIDShared && key == "pid:"+strconv.Itoa(c.PID))
}

// Key resolves the instance key for a scope. The returned key is opaque; only
// equality matters. Degraded reports whether a more specific scope fell back
// to something weaker, which the daemon logs once so the cause is visible.
func (s Scope) Key(ctx CallContext) (key string, degraded string) {
// ResolvedScope is the full result of resolving a Scope against a
// CallContext: the instance Key, the directory the scope resolved to
// (Root, "" when the scope has none), and Degraded, exactly as Key
// reports it. Root is a pure function of the key for repo, worktree and
// cwd scopes, so two callers who share a key always resolve the same
// root (decision 0004 §1).
type ResolvedScope struct {
Key string
Root string
Degraded string
}

// Resolve resolves the scope against ctx: the instance key, the
// scope-resolved root, and whether resolution degraded to something
// weaker than the scope asked for.
func (s Scope) Resolve(ctx CallContext) ResolvedScope {
switch s {
case ScopeGlobal:
return "global", ""
return ResolvedScope{Key: "global"}

case ScopeCwd:
if ctx.Cwd == "" {
return fallback(ctx), "cwd is unknown"
return ResolvedScope{Key: fallback(ctx), Degraded: "cwd is unknown"}
}
return "cwd:" + keyPath(ctx.Cwd), ""
root := keyPath(ctx.Cwd)
return ResolvedScope{Key: "cwd:" + root, Root: root}

case ScopeRepo, ScopeWorktree:
if ctx.Cwd == "" {
return fallback(ctx), "cwd is unknown"
return ResolvedScope{Key: fallback(ctx), Degraded: "cwd is unknown"}
}
// A directory outside any repository -- or one whose repository
// cannot be read -- keys by itself: narrower than the scope asked
// for, never wider.
// for, never wider. The degraded key is a cwd key, so the root
// follows it: the instance is effectively per-cwd.
w, _, err := locateGit(ctx.Cwd)
switch {
case err != nil:
return "cwd:" + keyPath(ctx.Cwd), err.Error()
root := keyPath(ctx.Cwd)
return ResolvedScope{Key: "cwd:" + root, Root: root, Degraded: err.Error()}
case s == ScopeRepo:
return "repo:" + keyPath(w.commonDir), ""
// The main worktree is the parent of the common dir, but
// only when that dir is a worktree's .git: a bare repo's
// common dir, or a submodule-style one, has no worktree
// root to name, and guessing one would root an instance
// in the wrong checkout.
root := ""
if filepath.Base(w.commonDir) == ".git" {
root = canonical(filepath.Dir(w.commonDir))
}
return ResolvedScope{Key: "repo:" + keyPath(w.commonDir), Root: root}
case w.worktree != "":
return "worktree:" + keyPath(w.worktree), ""
return ResolvedScope{Key: "worktree:" + keyPath(w.worktree), Root: canonical(w.worktree)}
default:
return "cwd:" + keyPath(ctx.Cwd), "no worktree: " + w.noWorktree
root := keyPath(ctx.Cwd)
return ResolvedScope{Key: "cwd:" + root, Root: root, Degraded: "no worktree: " + w.noWorktree}
}

case ScopeSession:
if ctx.SessionID != "" {
return "session:" + ctx.SessionID, ""
return ResolvedScope{Key: "session:" + ctx.SessionID}
}
return fallback(ctx), "no session id; set MCPX_SESSION_ID or pass --session"
return ResolvedScope{Key: fallback(ctx), Degraded: "no session id; set MCPX_SESSION_ID or pass --session"}

case ScopeParentSession:
if ctx.ParentSessionID != "" {
return "psession:" + ctx.ParentSessionID, ""
return ResolvedScope{Key: "psession:" + ctx.ParentSessionID}
}
if ctx.SessionID != "" {
return "session:" + ctx.SessionID, "no parent session id; using the session id"
return ResolvedScope{Key: "session:" + ctx.SessionID, Degraded: "no parent session id; using the session id"}
}
return fallback(ctx), "no parent or session id; set MCPX_PARENT_SESSION_ID"
return ResolvedScope{Key: fallback(ctx), Degraded: "no parent or session id; set MCPX_PARENT_SESSION_ID"}

case ScopePid:
if ctx.PID > 0 {
return "pid:" + strconv.Itoa(ctx.PID), ""
return ResolvedScope{Key: "pid:" + strconv.Itoa(ctx.PID)}
}
return fallback(ctx), "caller pid is unknown"
return ResolvedScope{Key: fallback(ctx), Degraded: "caller pid is unknown"}

case ScopeCall:
return fallback(ctx), ""
return ResolvedScope{Key: fallback(ctx)}
}
return fallback(ctx), fmt.Sprintf("unknown scope %q", s)
return ResolvedScope{Key: fallback(ctx), Degraded: fmt.Sprintf("unknown scope %q", s)}
}

// Key resolves the instance key for a scope. The returned key is opaque; only
// equality matters. Degraded reports whether a more specific scope fell back
// to something weaker, which the daemon logs once so the cause is visible.
//
// Key is Resolve's key and nothing else, so there is one resolution
// path, not two that can drift (decision 0004 §1).
func (s Scope) Key(ctx CallContext) (key string, degraded string) {
rs := s.Resolve(ctx)
return rs.Key, rs.Degraded
}

// fallback is per-call isolation: the safe direction to fail, since sharing a
Expand Down
122 changes: 122 additions & 0 deletions pkgs/mcpx/internal/config/scope_resolve_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package config_test

import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"

"github.com/developing-today/code/pkgs/mcpx/internal/config"
)

// Decision 0004 §1: Resolve returns the key Key returns, plus the root
// the scope resolved to. These tests pin the root semantics per scope.

func canon(t *testing.T, p string) string {
t.Helper()
r, err := filepath.EvalSymlinks(p)
if err != nil {
return filepath.Clean(p)
}
return r
}

func TestResolveWorktreeRootIsCheckoutTopLevel(t *testing.T) {
root := gitRepo(t)
rs := config.ScopeWorktree.Resolve(config.CallContext{Cwd: root, CallID: "c1"})
if rs.Degraded != "" {
t.Fatalf("unexpected degradation: %s", rs.Degraded)
}
if !strings.HasPrefix(rs.Key, "worktree:") {
t.Fatalf("expected a worktree key, got %q", rs.Key)
}
if rs.Root != canon(t, root) {
t.Fatalf("worktree root = %q, want the checkout top level %q", rs.Root, canon(t, root))
}
}

func TestResolveRepoRootIsMainWorktreeFromSubdir(t *testing.T) {
root := gitRepo(t)
sub := filepath.Join(root, "a", "b")
if err := os.MkdirAll(sub, 0o755); err != nil {
t.Fatal(err)
}
rs := config.ScopeRepo.Resolve(config.CallContext{Cwd: sub, CallID: "c1"})
if !strings.HasPrefix(rs.Key, "repo:") {
t.Fatalf("expected a repo key, got %q", rs.Key)
}
if rs.Root != canon(t, root) {
t.Fatalf("repo root = %q, want the main worktree %q", rs.Root, canon(t, root))
}
}

func TestResolveRepoRootFromLinkedWorktreeIsMainWorktree(t *testing.T) {
root := gitRepo(t)
linked := filepath.Join(t.TempDir(), "linked")
cmd := exec.Command("git", "worktree", "add", "-q", linked)
cmd.Dir = root
if out, err := cmd.CombinedOutput(); err != nil {
t.Skipf("git worktree add failed: %v\n%s", err, out)
}
// The linked worktree's own top level roots a worktree scope...
if rs := config.ScopeWorktree.Resolve(config.CallContext{Cwd: linked, CallID: "c1"}); rs.Root != canon(t, linked) {
t.Fatalf("worktree root from linked worktree = %q, want %q", rs.Root, canon(t, linked))
}
// ...while a repo scope roots at the main worktree, the parent of
// the shared common dir.
if rs := config.ScopeRepo.Resolve(config.CallContext{Cwd: linked, CallID: "c2"}); rs.Root != canon(t, root) {
t.Fatalf("repo root from linked worktree = %q, want main worktree %q", rs.Root, canon(t, root))
}
}

func TestResolveCwdRootIsCallerCwd(t *testing.T) {
dir := t.TempDir()
rs := config.ScopeCwd.Resolve(config.CallContext{Cwd: dir, CallID: "c1"})
if rs.Key != "cwd:"+rs.Root {
t.Fatalf("cwd root must be the key's directory: key %q root %q", rs.Key, rs.Root)
}
if rs.Root != canon(t, dir) {
t.Fatalf("cwd root = %q, want %q", rs.Root, canon(t, dir))
}
}

func TestResolveDegradedRepoRootIsCallerCwd(t *testing.T) {
dir := t.TempDir()
cmd := exec.Command("git", "rev-parse", "--git-common-dir")
cmd.Dir = dir
if err := cmd.Run(); err == nil {
t.Skip("temp dir is inside a git repository")
}
rs := config.ScopeRepo.Resolve(config.CallContext{Cwd: dir, CallID: "c1"})
if rs.Degraded == "" {
t.Fatal("falling back should be reported")
}
if !strings.HasPrefix(rs.Key, "cwd:") {
t.Fatalf("expected a degraded cwd key, got %q", rs.Key)
}
if rs.Root != canon(t, dir) {
t.Fatalf("degraded root = %q, want the caller cwd %q", rs.Root, canon(t, dir))
}
}

func TestResolveRootlessScopesHaveNoRoot(t *testing.T) {
cc := ctx()
for _, s := range []config.Scope{config.ScopeGlobal, config.ScopeSession, config.ScopeParentSession, config.ScopePid, config.ScopeCall} {
if rs := s.Resolve(cc); rs.Root != "" {
t.Errorf("scope %q resolved root %q, want none", s, rs.Root)
}
}
}

func TestKeyIsResolveKey(t *testing.T) {
repo := gitRepo(t)
for _, s := range []config.Scope{config.ScopeGlobal, config.ScopeCwd, config.ScopeRepo, config.ScopeWorktree, config.ScopeSession, config.ScopeParentSession, config.ScopePid, config.ScopeCall} {
cc := config.CallContext{Cwd: repo, SessionID: "s1", ParentSessionID: "p1", PID: 4242, CallID: "c1"}
key, deg := s.Key(cc)
rs := s.Resolve(cc)
if key != rs.Key || deg != rs.Degraded {
t.Errorf("scope %q: Key = (%q, %q), Resolve = (%q, %q)", s, key, deg, rs.Key, rs.Degraded)
}
}
}
Loading
Loading