diff --git a/pkgs/mcpx/internal/config/execid.go b/pkgs/mcpx/internal/config/execid.go index 3aa21e1ed2..7af58cd88d 100644 --- a/pkgs/mcpx/internal/config/execid.go +++ b/pkgs/mcpx/internal/config/execid.go @@ -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 @@ -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 } @@ -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 diff --git a/pkgs/mcpx/internal/config/execid_test.go b/pkgs/mcpx/internal/config/execid_test.go index 342d0a5a96..e5af21446d 100644 --- a/pkgs/mcpx/internal/config/execid_test.go +++ b/pkgs/mcpx/internal/config/execid_test.go @@ -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. diff --git a/pkgs/mcpx/internal/config/scope.go b/pkgs/mcpx/internal/config/scope.go index 9787f05ab6..10d5379f41 100644 --- a/pkgs/mcpx/internal/config/scope.go +++ b/pkgs/mcpx/internal/config/scope.go @@ -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 diff --git a/pkgs/mcpx/internal/config/scope_resolve_test.go b/pkgs/mcpx/internal/config/scope_resolve_test.go new file mode 100644 index 0000000000..cb588fde44 --- /dev/null +++ b/pkgs/mcpx/internal/config/scope_resolve_test.go @@ -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) + } + } +} diff --git a/pkgs/mcpx/internal/daemon/consumer.go b/pkgs/mcpx/internal/daemon/consumer.go index 03345e85cf..8505932161 100644 --- a/pkgs/mcpx/internal/daemon/consumer.go +++ b/pkgs/mcpx/internal/daemon/consumer.go @@ -300,41 +300,41 @@ func (r *Registry) DiagnoseCatalog() diagnose.Catalog { // caller already has an instance, the scope key is the answer and a question // would be theatre. // -// The returned key is the one to lease. Every path returns something: an +// The returned scope is the one to lease. Every path returns something: an // unanswered question falls back to the configured default, because the // caller is frequently headless and a call that waits forever is worse than // one that takes the conservative option. -func (r *Registry) disambiguate(ctx context.Context, p *pool.Pool, cc config.CallContext, key string) string { +func (r *Registry) disambiguate(ctx context.Context, p *pool.Pool, cc config.CallContext, rs config.ResolvedScope) config.ResolvedScope { if r.consumer.Disambiguate != "ask" || r.broker == nil { - return key + return rs } st := p.Status() if st.Sharing != string(config.SharingExclusive) || len(st.Instances) < 2 { - return key + return rs } choices := []elicit.Choice{{ - Value: key, Title: "new", + Value: rs.Key, Title: "new", Detail: "start an instance for this caller, which is what happens today", }} - recent := key + recent := rs bestIdle := -1 for _, in := range st.Instances { - if in.Key == key { + if in.Key == rs.Key { // The caller already has one. That is the answer. - return key + return rs } choices = append(choices, elicit.Choice{ Value: in.Key, Title: in.Key, Detail: describeInstance(in), }) if bestIdle < 0 || in.IdleSec < bestIdle { - bestIdle, recent = in.IdleSec, in.Key + bestIdle, recent = in.IdleSec, resolvedInstanceScope(in) } } sort.SliceStable(choices[1:], func(i, j int) bool { return choices[1+i].Title < choices[1+j].Title }) - fallback := key + fallback := rs if r.consumer.DisambiguateDefault == "recent" { fallback = recent } @@ -344,7 +344,7 @@ func (r *Registry) disambiguate(ctx context.Context, p *pool.Pool, cc config.Cal Message: fmt.Sprintf("%s has %d live instances and this call named none of them. Which should it use?", p.Namespace(), len(st.Instances)), Choices: choices, - Default: fallback, + Default: fallback.Key, TTL: r.consumer.AskTimeout, }) opened, err := r.broker.OpenRequest(req) @@ -358,10 +358,10 @@ func (r *Registry) disambiguate(ctx context.Context, p *pool.Pool, cc config.Cal defer cancel() ans, aerr := r.broker.Await(actx, opened.ID) if aerr != nil { - r.logf("disambiguate %s: nobody answered, using %s", p.Name(), fallback) + r.logf("disambiguate %s: nobody answered, using %s", p.Name(), fallback.Key) return fallback } - chosen, answered := elicit.Resolve(ans, elicit.FieldInstance, fallback) + chosen, answered := elicit.Resolve(ans, elicit.FieldInstance, fallback.Key) if !answered { return fallback } @@ -370,13 +370,29 @@ func (r *Registry) disambiguate(ctx context.Context, p *pool.Pool, cc config.Cal // text somebody typed. for _, c := range choices { if c.Value == chosen { - return chosen + if chosen == rs.Key { + return rs + } + for _, in := range st.Instances { + if in.Key == chosen { + return resolvedInstanceScope(in) + } + } + return config.ResolvedScope{Key: chosen} } } - r.logf("disambiguate %s: %q is not one of the choices, using %s", p.Name(), chosen, fallback) + r.logf("disambiguate %s: %q is not one of the choices, using %s", p.Name(), chosen, fallback.Key) return fallback } +// resolvedInstanceScope carries the root chosen with a live instance into +// Acquire. The instance may need a new protocol lane or may exit while the +// disambiguation answer is pending, so the selected root cannot be recovered +// by assuming Acquire will reuse the exact process shown in the choices. +func resolvedInstanceScope(in pool.InstanceStatus) config.ResolvedScope { + return config.ResolvedScope{Key: in.Key, Root: in.Root} +} + func describeInstance(in pool.InstanceStatus) string { who := "idle" if in.Holders > 0 { diff --git a/pkgs/mcpx/internal/daemon/consumer_scope_test.go b/pkgs/mcpx/internal/daemon/consumer_scope_test.go new file mode 100644 index 0000000000..9b95fa4680 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/consumer_scope_test.go @@ -0,0 +1,14 @@ +package daemon + +import ( + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/pool" +) + +func TestResolvedInstanceScopePreservesRootForNewLane(t *testing.T) { + got := resolvedInstanceScope(pool.InstanceStatus{Key: "worktree:/checkout", Root: "/checkout"}) + if got.Key != "worktree:/checkout" || got.Root != "/checkout" { + t.Fatalf("selected instance scope = %+v, want key and root from instance", got) + } +} diff --git a/pkgs/mcpx/internal/daemon/exec_watch_test.go b/pkgs/mcpx/internal/daemon/exec_watch_test.go index b75c2d677a..b35c80ec16 100644 --- a/pkgs/mcpx/internal/daemon/exec_watch_test.go +++ b/pkgs/mcpx/internal/daemon/exec_watch_test.go @@ -95,7 +95,7 @@ func livePID(p *pool.Pool) int { // goes through a real call, so it shows the child is serving. func servedPID(t *testing.T, p *pool.Pool) int { t.Helper() - raw, err := p.Call(context.Background(), "global", "state", map[string]any{}) + raw, err := p.Call(context.Background(), config.ResolvedScope{Key: "global"}, "state", map[string]any{}) if err != nil { t.Fatalf("state call on %s: %v", p.Name(), err) } diff --git a/pkgs/mcpx/internal/daemon/input_required.go b/pkgs/mcpx/internal/daemon/input_required.go index dfab28d7d6..8cda7438b9 100644 --- a/pkgs/mcpx/internal/daemon/input_required.go +++ b/pkgs/mcpx/internal/daemon/input_required.go @@ -72,13 +72,13 @@ func (r *Registry) CallReporting(ctx context.Context, id, server, tool string, c if !ok { return nil, UnknownServer{Name: server} } - key, err := r.resolveAndGuard(ctx, p, server, tool, cc, args) + rs, err := r.resolveAndGuard(ctx, p, server, tool, cc, args) if err != nil { return nil, err } - r.beginAsk(id, server, key, cc.SessionID) + r.beginAsk(id, server, rs.Key, cc.SessionID) defer r.endAsk(id) - res, err := p.Call(withRequestedCallTimeout(ctx), key, tool, args) + res, err := p.Call(withRequestedCallTimeout(ctx), rs, tool, args) if err != nil { return nil, r.explainCall(ctx, server, tool, args, err) } diff --git a/pkgs/mcpx/internal/daemon/ops.go b/pkgs/mcpx/internal/daemon/ops.go index 4868874218..cb9f3609b4 100644 --- a/pkgs/mcpx/internal/daemon/ops.go +++ b/pkgs/mcpx/internal/daemon/ops.go @@ -397,7 +397,7 @@ func (s *Server) handleComplete(w http.ResponseWriter, r *http.Request) { fwd["context"] = map[string]any{"arguments": req.Arguments} } params, _ := json.Marshal(fwd) - raw, upstream, err := p.Complete(r.Context(), s.reg.keyFor(p, cc), params) + raw, upstream, err := p.Complete(r.Context(), s.reg.resolvedFor(p, cc), params) if err != nil { writeErr(w, http.StatusBadGateway, err) return diff --git a/pkgs/mcpx/internal/daemon/registry.go b/pkgs/mcpx/internal/daemon/registry.go index d9478de113..b2f69811b2 100644 --- a/pkgs/mcpx/internal/daemon/registry.go +++ b/pkgs/mcpx/internal/daemon/registry.go @@ -1222,12 +1222,12 @@ func (r *Registry) Call(ctx context.Context, server, tool string, cc config.Call if !ok { return nil, UnknownServer{Name: server} } - key, err := r.resolveAndGuard(ctx, p, server, tool, cc, args) + rs, err := r.resolveAndGuard(ctx, p, server, tool, cc, args) if err != nil { return nil, err } - defer r.joinAsk(ctx, server, key)() - res, err := p.Call(withRequestedCallTimeout(ctx), key, tool, args) + defer r.joinAsk(ctx, server, rs.Key)() + res, err := p.Call(withRequestedCallTimeout(ctx), rs, tool, args) if err != nil { return nil, r.explainCall(ctx, server, tool, args, err) } @@ -1238,38 +1238,38 @@ func (r *Registry) Call(ctx context.Context, server, tool string, cc config.Call // consumer policies. Every path that calls a tool goes through it: the ask // path once skipped both, so a destructive-tool guard was off for exactly the // clients that declared they could answer it. -func (r *Registry) resolveAndGuard(ctx context.Context, p *pool.Pool, server, tool string, cc config.CallContext, args any) (string, error) { +func (r *Registry) resolveAndGuard(ctx context.Context, p *pool.Pool, server, tool string, cc config.CallContext, args any) (config.ResolvedScope, error) { // The view, not the pool: aliases share one pool and filter differently. if view, ok := r.View(server); ok { // Before the child is touched: a server waiting for a secret is not // started just to fail. if err := r.refuseBlocked(server); err != nil { - return "", err + return config.ResolvedScope{}, err } if !view.VisibleTool(tool) { if ok, reason := view.PassesPreconditions(tool, func(s string) bool { _, exists := r.Pool(s); return exists }); !ok { - return "", fmt.Errorf("tool %q failed preconditions: %s", tool, reason) + return config.ResolvedScope{}, fmt.Errorf("tool %q failed preconditions: %s", tool, reason) } - return "", HiddenTool{Server: server, Tool: tool} + return config.ResolvedScope{}, HiddenTool{Server: server, Tool: tool} } } - key := r.keyFor(p, cc) + rs := r.resolvedFor(p, cc) // Two policies sit between resolving the instance and using it, and both // are off unless somebody turned them on. See internal/daemon/consumer.go. - key = r.disambiguate(ctx, p, cc, key) + rs = r.disambiguate(ctx, p, cc, rs) asked, err := r.applyWritePolicy(ctx, p, server, tool, cc, args) if err != nil { - return "", err + return config.ResolvedScope{}, err } if !asked { // Not asked by the write policy: the destructive floor still // gets its say. Under ask the policy already asked once, and // asking twice about one call would be noise, not consent. if err := r.confirmDestructive(ctx, p, tool, cc); err != nil { - return "", err + return config.ResolvedScope{}, err } } - return key, nil + return rs, nil } // ReadResource dispatches a resource read. @@ -1281,10 +1281,10 @@ func (r *Registry) ReadResource(ctx context.Context, server, uri string, cc conf if err := r.refuseBlocked(server); err != nil { return nil, err } - key := r.keyFor(p, cc) + rs := r.resolvedFor(p, cc) // The listing drops a leading '/', so mcpx://ns/abs/doc names /abs/doc; // the server only knows its own spelling. - return p.ReadResource(ctx, key, upstreamResourceURI(ctx, p, uri)) + return p.ReadResource(ctx, rs, upstreamResourceURI(ctx, p, uri)) } // PromptInfo is one prompt, with the namespace it came from. @@ -1424,14 +1424,21 @@ func (r *Registry) GetPrompt(ctx context.Context, server, name string, args map[ if err := r.refuseBlocked(server); err != nil { return nil, err } - return p.GetPrompt(ctx, r.keyFor(p, cc), name, args) + return p.GetPrompt(ctx, r.resolvedFor(p, cc), name, args) } -// keyFor resolves a server's scope and records the association so the caller -// can later release exactly what it created. +// keyFor resolves a server's scope key; resolvedFor is the full +// resolution, for callers that also pass the root to the pool. func (r *Registry) keyFor(p *pool.Pool, cc config.CallContext) string { + return r.resolvedFor(p, cc).Key +} + +// resolvedFor resolves a server's scope and records the association so +// the caller can later release exactly what it created. +func (r *Registry) resolvedFor(p *pool.Pool, cc config.CallContext) config.ResolvedScope { scope := p.Config().Scope - key, degraded := scope.Key(cc) + rs := scope.Resolve(cc) + key, degraded := rs.Key, rs.Degraded if degraded != "" { r.warnDegraded(p.Name(), scope, key, degraded) } @@ -1448,7 +1455,7 @@ func (r *Registry) keyFor(p *pool.Pool, cc config.CallContext) string { } r.sessMu.Unlock() } - return key + return rs } // warnDegraded reports a scope that could not be resolved as configured, once diff --git a/pkgs/mcpx/internal/daemon/registry_handoff_test.go b/pkgs/mcpx/internal/daemon/registry_handoff_test.go index a24552c8b5..1cf50c6ac0 100644 --- a/pkgs/mcpx/internal/daemon/registry_handoff_test.go +++ b/pkgs/mcpx/internal/daemon/registry_handoff_test.go @@ -125,7 +125,7 @@ func detachRemote(t *testing.T, url string) (*Registry, *RegistryHandoff) { if !ok { t.Fatal("no pool for remote") } - lease, err := p.Acquire(context.Background(), "global") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err != nil { t.Fatal(err) } @@ -229,7 +229,7 @@ func TestSuccessorShutdownWaitsForABlockedOrphanTermination(t *testing.T) { if !ok { t.Fatal("no pool for remote") } - lease, err := p.Acquire(context.Background(), "global") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err != nil { t.Fatal(err) } @@ -297,7 +297,7 @@ func TestDaemonRestartWaitsForABlockedOrphanTermination(t *testing.T) { if !ok { t.Fatal("no pool for remote") } - lease, err := p.Acquire(context.Background(), "global") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err != nil { t.Fatal(err) } @@ -420,7 +420,7 @@ func TestAbortedTakeoverLeavesARemovedServersSessionAlone(t *testing.T) { t.Fatalf("an aborted handoff ended the upstream session with %d DELETE(s)", deletes) } p, _ := old.Pool("remote") - lease, err := p.Acquire(context.Background(), "global") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err != nil { t.Fatal(err) } @@ -452,7 +452,7 @@ func TestSuccessorServeWaitsForABlockedOrphanTerminationOnHandoff(t *testing.T) if !ok { t.Fatal("no pool for remote") } - lease, err := p.Acquire(context.Background(), "global") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err != nil { t.Fatal(err) } diff --git a/pkgs/mcpx/internal/daemon/reload_test.go b/pkgs/mcpx/internal/daemon/reload_test.go index 5ad3e66729..e378fa5da2 100644 --- a/pkgs/mcpx/internal/daemon/reload_test.go +++ b/pkgs/mcpx/internal/daemon/reload_test.go @@ -16,7 +16,7 @@ import ( // childPID starts (or finds) the global instance of p and reports its pid. func childPID(t *testing.T, p *pool.Pool) int { t.Helper() - lease, err := p.Acquire(context.Background(), "global") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err != nil { t.Fatalf("acquire %s: %v", p.Name(), err) } diff --git a/pkgs/mcpx/internal/daemon/routes_proto.go b/pkgs/mcpx/internal/daemon/routes_proto.go index 7afa5fd4f6..73fcd9c7d2 100644 --- a/pkgs/mcpx/internal/daemon/routes_proto.go +++ b/pkgs/mcpx/internal/daemon/routes_proto.go @@ -298,14 +298,14 @@ func (r *Registry) CallAsk(ctx context.Context, id, server, tool string, cc conf // the table before the upstream request goes out, so it is registered // between the two. The guard's own questions are mcpx's, not the // server's, and are never attributed through the table. - key, err := r.resolveAndGuard(ctx, p, server, tool, cc, args) + rs, err := r.resolveAndGuard(ctx, p, server, tool, cc, args) if err != nil { return nil, err } - r.beginAsk(id, server, key, cc.SessionID) + r.beginAsk(id, server, rs.Key, cc.SessionID) defer r.endAsk(id) ctx = withRequestedCallTimeout(withAskCall(ctx, id)) - return p.Call(ctx, key, tool, args) + return p.Call(ctx, rs, tool, args) } // ReadResourceAsk is resources/read, interruptibly. @@ -314,11 +314,11 @@ func (r *Registry) ReadResourceAsk(ctx context.Context, id, server, uri string, if !ok { return nil, fmt.Errorf("unknown server or namespace %q", server) } - key := r.keyFor(p, cc) - r.beginAsk(id, server, key, cc.SessionID) + rs := r.resolvedFor(p, cc) + r.beginAsk(id, server, rs.Key, cc.SessionID) defer r.endAsk(id) ctx = withRequestedCallTimeout(withAskCall(ctx, id)) - return p.ReadResource(ctx, key, upstreamResourceURI(ctx, p, uri)) + return p.ReadResource(ctx, rs, upstreamResourceURI(ctx, p, uri)) } // GetPromptAsk is prompts/get, interruptibly. @@ -327,11 +327,11 @@ func (r *Registry) GetPromptAsk(ctx context.Context, id, server, name string, ar if !ok { return nil, fmt.Errorf("unknown server or namespace %q", server) } - key := r.keyFor(p, cc) - r.beginAsk(id, server, key, cc.SessionID) + rs := r.resolvedFor(p, cc) + r.beginAsk(id, server, rs.Key, cc.SessionID) defer r.endAsk(id) ctx = withRequestedCallTimeout(withAskCall(ctx, id)) - return p.GetPrompt(ctx, key, name, args) + return p.GetPrompt(ctx, rs, name, args) } // runKey carries the exec run a /v1/call was made from. @@ -1002,7 +1002,7 @@ func (s *Server) watchResources(ctx context.Context, server string, uris []strin } upstream = upstreamResourceURI(ctx, p, upstream) match = append(match, upstream) - release, err := p.Watch(ctx, s.reg.keyFor(p, config.CallContext{}), upstream) + release, err := p.Watch(ctx, s.reg.resolvedFor(p, config.CallContext{}), upstream) if err != nil { w.refuse(u, err.Error()) s.warnUnwatched(owner, u, err.Error()) diff --git a/pkgs/mcpx/internal/daemon/takeover_test.go b/pkgs/mcpx/internal/daemon/takeover_test.go index b70e437e78..845cdb2ac1 100644 --- a/pkgs/mcpx/internal/daemon/takeover_test.go +++ b/pkgs/mcpx/internal/daemon/takeover_test.go @@ -166,7 +166,7 @@ func TestRegistryHandoffThatIsNotCommittedRestoresTheChild(t *testing.T) { if got := childPID(t, pa); got != pid { t.Fatalf("a restored child has pid %d, want %d", got, pid) } - lease, err := pa.Acquire(context.Background(), "global") + lease, err := pa.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err != nil { t.Fatalf("the restored pool does not serve: %v", err) } diff --git a/pkgs/mcpx/internal/pool/detach_test.go b/pkgs/mcpx/internal/pool/detach_test.go index 3f5a7ac1ea..2615d2f30b 100644 --- a/pkgs/mcpx/internal/pool/detach_test.go +++ b/pkgs/mcpx/internal/pool/detach_test.go @@ -15,7 +15,7 @@ func TestDetachRefusesWhileACallIsInFlight(t *testing.T) { p := pool.New(resolved(t, bin, &config.Extras{Sharing: config.SharingExclusive, Scope: config.ScopeSession, Max: 2})) defer p.Close() - lease, err := p.Acquire(context.Background(), "s1") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "s1"}) if err != nil { t.Fatal(err) } diff --git a/pkgs/mcpx/internal/pool/era_test.go b/pkgs/mcpx/internal/pool/era_test.go index 2c12350b91..e2cf7d9377 100644 --- a/pkgs/mcpx/internal/pool/era_test.go +++ b/pkgs/mcpx/internal/pool/era_test.go @@ -65,7 +65,7 @@ func startOnce(t *testing.T, p *pool.Pool) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - lease, err := p.Acquire(ctx, "") + lease, err := p.Acquire(ctx, config.ResolvedScope{Key: ""}) if err != nil { t.Fatal(err) } @@ -241,7 +241,7 @@ func TestPoolProbe(t *testing.T) { defer p.Close() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - res, err := p.Call(ctx, "", "hello", nil) + res, err := p.Call(ctx, config.ResolvedScope{Key: ""}, "hello", nil) if err != nil { t.Fatal(err) } @@ -267,7 +267,7 @@ func TestPoolProbe(t *testing.T) { defer p.Close() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - if _, err := p.Call(ctx, "", "hello", nil); err != nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: ""}, "hello", nil); err != nil { t.Fatal(err) } if era, v := p.Era(); era != mcpclient.EraModern || v != "2026-07-28" { diff --git a/pkgs/mcpx/internal/pool/execwatch.go b/pkgs/mcpx/internal/pool/execwatch.go index aa168fe78a..0a698802ee 100644 --- a/pkgs/mcpx/internal/pool/execwatch.go +++ b/pkgs/mcpx/internal/pool/execwatch.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "github.com/developing-today/code/pkgs/mcpx/internal/config" "github.com/developing-today/code/pkgs/mcpx/internal/defaults" ) @@ -69,6 +70,10 @@ func (p *Pool) checkExec() { if !p.cfg.Stdio() { return } + if p.cfg.ExecUsesScopeRoot() { + p.checkScopedExec() + return + } st, found := p.cfg.ExecStamp() p.execMu.Lock() @@ -116,6 +121,94 @@ func (p *Pool) checkExec() { p.replaceChildren() } +// checkScopedExec watches each instance against the executable resolved from +// its effective spawn cwd. A pool-wide check against the daemon cwd could miss +// the executable actually serving a workspace or restart it because an +// unrelated ./server changed in the daemon directory. +func (p *Pool) checkScopedExec() { + p.mu.Lock() + instances := append([]*Instance(nil), p.instances...) + p.mu.Unlock() + for _, in := range instances { + p.checkInstanceExec(in) + } +} + +func (p *Pool) checkInstanceExec(in *Instance) { + p.mu.Lock() + if p.closed || in.retiring { + p.mu.Unlock() + return + } + p.mu.Unlock() + + cwd, _ := SpawnCwd(p.cfg.Cwd, in.root) + st, found := p.cfg.ExecStampAt(cwd) + if !found { + p.markInstanceExecMissing(in, p.cfg.Command) + return + } + id, err := st.Identity() + if err != nil { + p.markInstanceExecMissing(in, st.Path) + return + } + + p.execMu.Lock() + unchanged := st == in.execStamp + wasMissing := in.execMissing + old := in.execIdentity + in.execStamp = st + in.execIdentity = id + in.execMissing = false + if in.root == "" { + // The daemon-cwd instance is the pool's configured executable identity. + p.exec = id + p.execStamp = st + p.execMissing = false + } + p.execMu.Unlock() + if unchanged { + return + } + if id == old { + if wasMissing { + lifecycle("server.exec", map[string]any{ + "server": p.cfg.Name, "instance": in.ID, "state": "restored", + "path": st.Path, "identity": id, "restarted": false, + }) + } + return + } + lifecycle("server.restart", map[string]any{ + "server": p.cfg.Name, "instance": in.ID, "reason": "executable changed", + "path": st.Path, "oldIdentity": old, "newIdentity": id, + }) + p.mu.Lock() + if p.closed || in.retiring { + p.mu.Unlock() + return + } + in.retiring = true + p.reserveSlotLocked(in) + p.mu.Unlock() + p.replaceChild(in) +} + +func (p *Pool) markInstanceExecMissing(in *Instance, path string) { + p.execMu.Lock() + first := !in.execMissing + in.execMissing = true + p.execMu.Unlock() + if first { + lifecycle("server.warning", map[string]any{ + "server": p.cfg.Name, "instance": in.ID, + "reason": "executable missing; keeping the running child and checking again", + "path": path, + }) + } +} + // execGone records that the executable cannot be read. The running child is // kept, since it still has the program open, and the warning is logged once // rather than on every check until the file returns. @@ -192,7 +285,7 @@ func (p *Pool) replaceChild(in *Instance) { p.mu.Unlock() return } - repl, err := p.startLane(context.Background(), in.legacyLane) + repl, err := p.startLane(context.Background(), in.legacyLane, config.ResolvedScope{Key: in.key, Root: in.root}) p.mu.Lock() p.releaseSlotLocked(in) diff --git a/pkgs/mcpx/internal/pool/execwatch_test.go b/pkgs/mcpx/internal/pool/execwatch_test.go index 7cefa766f4..1d5ff7b36a 100644 --- a/pkgs/mcpx/internal/pool/execwatch_test.go +++ b/pkgs/mcpx/internal/pool/execwatch_test.go @@ -70,7 +70,7 @@ func childPIDs(p *pool.Pool) []int { // servedPID asks the pool which child answers, through a real call. func servedPID(t *testing.T, p *pool.Pool) int { t.Helper() - res, err := p.Call(context.Background(), "global", "state", map[string]any{}) + res, err := p.Call(context.Background(), config.ResolvedScope{Key: "global"}, "state", map[string]any{}) if err != nil { t.Fatalf("state: %v", err) } @@ -113,7 +113,7 @@ func inFlight(t *testing.T, p *pool.Pool, ms int) <-chan struct { err error }, 1) go func() { - raw, err := p.Call(context.Background(), "global", "slow", map[string]any{"ms": ms}) + raw, err := p.Call(context.Background(), config.ResolvedScope{Key: "global"}, "slow", map[string]any{"ms": ms}) done <- struct { raw json.RawMessage err error @@ -252,3 +252,59 @@ func TestExecCheckKeepsAChildWhenALinkIsRePointedAtIdenticalBytes(t *testing.T) repoint(other) awaitReplacement(t, p, pid) } + +func TestExecCheckUsesEachScopeRootForRelativeCommand(t *testing.T) { + setExecWatch(t, execTick, 10*time.Second) + fake := testsupport.FakeMCPBinary(t) + rootA, rootB := t.TempDir(), t.TempDir() + binA, binB := filepath.Join(rootA, "server"), filepath.Join(rootB, "server") + writeExecWrapper(t, fake, binA, "root A initial") + writeExecWrapper(t, fake, binB, "root B initial") + + p := pool.New(resolved(t, "./server", &config.Extras{ + Sharing: config.SharingShared, + Scope: config.ScopeWorktree, + Max: 4, + })) + defer p.Close() + leaseA, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "worktree:" + rootA, Root: rootA}) + if err != nil { + t.Fatalf("acquire root A: %v", err) + } + defer leaseA.Release() + leaseB, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "worktree:" + rootB, Root: rootB}) + if err != nil { + t.Fatalf("acquire root B: %v", err) + } + defer leaseB.Release() + + pidForRoot := func(root string) int { + t.Helper() + for _, in := range p.Status().Instances { + if in.Root == root { + return in.PID + } + } + return 0 + } + oldA, oldB := pidForRoot(rootA), pidForRoot(rootB) + if oldA == 0 || oldB == 0 || oldA == oldB { + t.Fatalf("expected distinct rooted children, got A=%d B=%d", oldA, oldB) + } + leaseA.Release() + leaseB.Release() + + writeExecWrapper(t, fake, binA, "root A changed") + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + newA, stillB := pidForRoot(rootA), pidForRoot(rootB) + if newA != 0 && newA != oldA { + if stillB != oldB { + t.Fatalf("changing root A's executable also replaced root B: %d -> %d", oldB, stillB) + } + return + } + time.Sleep(time.Millisecond) + } + t.Fatalf("root A's changed executable was not replaced (pid stayed %d)", oldA) +} diff --git a/pkgs/mcpx/internal/pool/follow_test.go b/pkgs/mcpx/internal/pool/follow_test.go index eb50d65564..e99f1ecc3c 100644 --- a/pkgs/mcpx/internal/pool/follow_test.go +++ b/pkgs/mcpx/internal/pool/follow_test.go @@ -6,6 +6,7 @@ import ( "testing" "time" + "github.com/developing-today/code/pkgs/mcpx/internal/config" "github.com/developing-today/code/pkgs/mcpx/internal/mcpclient" "github.com/developing-today/code/pkgs/mcpx/internal/pool" ) @@ -16,7 +17,7 @@ func eraFor(t *testing.T, p *pool.Pool, version string) (mcpclient.Era, string) t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() - lease, err := p.Acquire(mcpclient.WithCallerVersion(ctx, version), "") + lease, err := p.Acquire(mcpclient.WithCallerVersion(ctx, version), config.ResolvedScope{Key: ""}) if err != nil { t.Fatal(err) } @@ -110,13 +111,13 @@ func TestFollowLanesHaveTheirOwnCapacity(t *testing.T) { for _, held := range []string{"2026-07-28", "2025-11-25"} { other := map[string]string{"2026-07-28": "2025-11-25", "2025-11-25": "2026-07-28"}[held] ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - lease, err := p.Acquire(mcpclient.WithCallerVersion(ctx, held), "") + lease, err := p.Acquire(mcpclient.WithCallerVersion(ctx, held), config.ResolvedScope{Key: ""}) cancel() if err != nil { t.Fatal(err) } ctx, cancel = context.WithTimeout(context.Background(), 3*time.Second) - second, err := p.Acquire(mcpclient.WithCallerVersion(ctx, other), "") + second, err := p.Acquire(mcpclient.WithCallerVersion(ctx, other), config.ResolvedScope{Key: ""}) cancel() if err != nil { lease.Release() diff --git a/pkgs/mcpx/internal/pool/handoff.go b/pkgs/mcpx/internal/pool/handoff.go index 0e8fb0a9c5..ab129ca1c1 100644 --- a/pkgs/mcpx/internal/pool/handoff.go +++ b/pkgs/mcpx/internal/pool/handoff.go @@ -7,6 +7,7 @@ import ( "sync" "time" + "github.com/developing-today/code/pkgs/mcpx/internal/config" "github.com/developing-today/code/pkgs/mcpx/internal/mcpclient" ) @@ -19,18 +20,27 @@ const resumeProbeTimeout = 5 * time.Second // pipes travel beside it as file descriptors, not in the JSON. A streamable // HTTP instance carries only its upstream session. type InstanceHandoff struct { - ID string `json:"id"` - Trace string `json:"trace"` - Key string `json:"key"` - StartedAt time.Time `json:"startedAt"` - LastUsed time.Time `json:"lastUsed"` - Calls int64 `json:"calls"` - EraSource string `json:"eraSource,omitempty"` - LegacyLane bool `json:"legacyLane,omitempty"` - Subscribed []string `json:"subscribed,omitempty"` - Stdio *mcpclient.StdioHandoff `json:"stdio"` - HTTP *mcpclient.HTTPHandoff `json:"http,omitempty"` - Session mcpclient.Session `json:"session"` + ID string `json:"id"` + Trace string `json:"trace"` + Key string `json:"key"` + Root string `json:"root,omitempty"` + // ExecStamp and ExecIdentity are the executable identity the instance + // was started with, resolved from its effective spawn cwd. They travel + // with the handoff so a successor's exec watch compares the adopted + // child against the executable it is actually running: without them a + // resumed instance reads as zero-valued, and the first check treats + // its unchanged executable as newly changed and restarts it. + ExecStamp config.ExecStamp `json:"execStamp"` + ExecIdentity string `json:"execIdentity,omitempty"` + StartedAt time.Time `json:"startedAt"` + LastUsed time.Time `json:"lastUsed"` + Calls int64 `json:"calls"` + EraSource string `json:"eraSource,omitempty"` + LegacyLane bool `json:"legacyLane,omitempty"` + Subscribed []string `json:"subscribed,omitempty"` + Stdio *mcpclient.StdioHandoff `json:"stdio"` + HTTP *mcpclient.HTTPHandoff `json:"http,omitempty"` + Session mcpclient.Session `json:"session"` } // PoolHandoff is one pool's children in transit. PoolID names the process @@ -74,7 +84,7 @@ func (p *Pool) Detach() (*PoolHandoff, error) { seq := p.seq metas := make([]InstanceHandoff, len(parked)) for i, in := range parked { - metas[i] = in.describe() + metas[i] = in.describe(p) } p.cond.Broadcast() p.mu.Unlock() @@ -161,24 +171,32 @@ func (p *Pool) restore(handed []*Instance) { p.mu.Unlock() } -// describe is the instance's record without its pipes. p.mu is held. -func (in *Instance) describe() InstanceHandoff { +// describe is the instance's record without its pipes. p.mu is held; the +// executable identity is read under p.execMu, which guards it everywhere +// else (see Pool). +func (in *Instance) describe(p *Pool) InstanceHandoff { in.subMu.Lock() subs := make([]string, 0, len(in.subscribed)) for uri := range in.subscribed { subs = append(subs, uri) } in.subMu.Unlock() + p.execMu.Lock() + execStamp, execIdentity := in.execStamp, in.execIdentity + p.execMu.Unlock() return InstanceHandoff{ - ID: in.ID, - Trace: in.trace, - Key: in.key, - StartedAt: in.startedAt, - LastUsed: in.lastUsed, - Calls: in.calls.Load(), - EraSource: in.eraSource, - LegacyLane: in.legacyLane, - Subscribed: subs, + ID: in.ID, + Trace: in.trace, + Key: in.key, + Root: in.root, + ExecStamp: execStamp, + ExecIdentity: execIdentity, + StartedAt: in.startedAt, + LastUsed: in.lastUsed, + Calls: in.calls.Load(), + EraSource: in.eraSource, + LegacyLane: in.legacyLane, + Subscribed: subs, } } @@ -224,7 +242,7 @@ func (p *Pool) AdoptSessions(hs []InstanceHandoff) ([]*Adopted, error) { if h.HTTP == nil { continue } - tr, err := p.dial(context.Background()) + tr, err := p.dial(context.Background(), "") if err != nil { abortAll(out) return nil, fmt.Errorf("instance %s: %w", h.ID, err) @@ -329,16 +347,19 @@ func (p *Pool) resumeInstance(a *Adopted) *Instance { cl := mcpclient.Resume(a.tr, h.Session, opts) p.subscribeServerEvents(cl) in := &Instance{ - ID: h.ID, - Client: cl, - transport: a.tr, - key: h.Key, - trace: h.Trace, - startedAt: h.StartedAt, - lastUsed: h.LastUsed, - eraSource: h.EraSource, - legacyLane: h.LegacyLane, - subscribed: make(map[string]bool, len(h.Subscribed)), + ID: h.ID, + Client: cl, + transport: a.tr, + key: h.Key, + root: h.Root, + execStamp: h.ExecStamp, + execIdentity: h.ExecIdentity, + trace: h.Trace, + startedAt: h.StartedAt, + lastUsed: h.LastUsed, + eraSource: h.EraSource, + legacyLane: h.LegacyLane, + subscribed: make(map[string]bool, len(h.Subscribed)), } in.calls.Store(h.Calls) for _, uri := range h.Subscribed { diff --git a/pkgs/mcpx/internal/pool/handoff_exec_test.go b/pkgs/mcpx/internal/pool/handoff_exec_test.go new file mode 100644 index 0000000000..e9c847ffb2 --- /dev/null +++ b/pkgs/mcpx/internal/pool/handoff_exec_test.go @@ -0,0 +1,101 @@ +package pool_test + +import ( + "context" + "encoding/json" + "path/filepath" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/config" + "github.com/developing-today/code/pkgs/mcpx/internal/pool" + "github.com/developing-today/code/pkgs/mcpx/internal/testsupport" +) + +// An adopted child keeps the executable identity it was started with. The +// command is relative ("./server") and resolves only under the scope root, +// so the identity exists solely as the instance's effective-spawn-cwd +// stamp. If the handoff dropped it, the successor's first exec check would +// read a zero stamp, treat the unchanged executable as newly changed, and +// restart the adopted child for no reason. +func TestHandoffCarriesExecIdentityForRelativeCommand(t *testing.T) { + setExecWatch(t, execTick, 10*time.Second) + fake := testsupport.FakeMCPBinary(t) + root := t.TempDir() + copyFake(t, fake, filepath.Join(root, "server"), nil) + + ex := &config.Extras{Sharing: config.SharingExclusive, Scope: config.ScopeSession, Max: 2} + from := pool.New(resolved(t, "./server", ex)) + defer from.Close() + scope := config.ResolvedScope{Key: "ws1", Root: root} + lease, err := from.Acquire(context.Background(), scope) + if err != nil { + t.Fatal(err) + } + lease.Release() + + ph, err := from.Detach() + if err != nil { + t.Fatalf("detach: %v", err) + } + if len(ph.Instances) != 1 { + t.Fatalf("want the one child handed on, got %d", len(ph.Instances)) + } + h := ph.Instances[0] + wantPath, err := filepath.EvalSymlinks(filepath.Join(root, "server")) + if err != nil { + t.Fatal(err) + } + if h.ExecStamp.Path != wantPath { + t.Fatalf("handoff exec stamp path = %q, want %q", h.ExecStamp.Path, wantPath) + } + if h.ExecIdentity == "" { + t.Fatal("handoff carries no exec identity for the adopted child") + } + + // The handoff metadata crosses a process boundary as JSON; the + // identity must survive the round trip. (The stdio pipes themselves + // travel beside the JSON as file descriptors, so adoption below uses + // the original handoff, not the unmarshalled copy.) + wire, err := json.Marshal(ph) + if err != nil { + t.Fatal(err) + } + var ph2 pool.PoolHandoff + if err := json.Unmarshal(wire, &ph2); err != nil { + t.Fatal(err) + } + if ph2.Instances[0].ExecIdentity != h.ExecIdentity || ph2.Instances[0].ExecStamp != h.ExecStamp { + t.Fatalf("exec identity lost on the wire: %+v", ph2.Instances[0]) + } + + to := pool.New(resolved(t, "./server", ex)) + defer to.Close() + ads, err := pool.Adopt(ph.Instances) + if err != nil { + t.Fatalf("adopt: %v", err) + } + from.Commit() + to.Attach(ads, ph.Seq) + + pids := childPIDs(to) + if len(pids) != 1 { + t.Fatalf("want the adopted child serving, got pids %v", pids) + } + // Several exec-watch ticks pass with the executable untouched: the + // adopted child must still be the one serving. + time.Sleep(300 * time.Millisecond) + res, err := to.Call(context.Background(), scope, "state", map[string]any{}) + if err != nil { + t.Fatalf("state after takeover: %v", err) + } + var st struct { + PID int `json:"pid"` + } + if err := json.Unmarshal([]byte(textOf(t, res)), &st); err != nil { + t.Fatalf("decode state: %v", err) + } + if st.PID != pids[0] { + t.Fatalf("adopted child pid %d was replaced by pid %d with its executable unchanged", pids[0], st.PID) + } +} diff --git a/pkgs/mcpx/internal/pool/pool.go b/pkgs/mcpx/internal/pool/pool.go index f1433964b1..743f8fcb09 100644 --- a/pkgs/mcpx/internal/pool/pool.go +++ b/pkgs/mcpx/internal/pool/pool.go @@ -81,6 +81,17 @@ type Instance struct { // key is the scope-resolved identity this instance serves. One live // instance per distinct key. key string + // root is the scope-resolved directory stored at creation + // (decision 0004 §2): the spawn cwd for stdio instances without a + // config cwd, read from the instance at every (re)start and never + // re-resolved at redial. "" when the scope has no root. + root string + // execStamp and execIdentity identify the executable actually used by + // this instance. Scope-rooted relative commands can differ per instance, + // so their exec watch cannot use one pool-wide identity. + execStamp config.ExecStamp + execIdentity string + execMissing bool // holders counts current callers. Exclusive sharing admits one; shared // sharing admits any number. holders int @@ -114,6 +125,10 @@ type Instance struct { // Trace is this instance's identifier, carried by every record about it. func (i *Instance) Trace() string { return i.trace } +// Root is the scope-resolved directory this instance was created with +// (decision 0004 §2), "" when its scope has none. +func (i *Instance) Root() string { return i.root } + // PID returns the child process id for stdio instances, 0 otherwise. func (i *Instance) PID() int { if st, ok := i.transport.(*mcpclient.StdioTransport); ok { @@ -215,9 +230,10 @@ type Pool struct { // watched counts, per upstream resource URI, the subscribers that want // its updates; watchKey is the scope key they were resolved under. - watchMu sync.Mutex - watched map[string]int - watchKey string + watchMu sync.Mutex + watched map[string]int + watchKey string + watchRoot string // noLegacy is set once a legacy-only start failed under protocol: // follow; legacy callers then share the modern session. @@ -250,12 +266,16 @@ func (p *Pool) Namespace() string { return p.cfg.Namespace } var errClosed = errors.New("pool closed") -// Acquire borrows an instance for a resolved scope key. +// Acquire borrows an instance for a resolved scope. // // The key decides *which* process; Sharing decides whether that process may // serve more than one caller at once. Those are independent, which is why they -// are separate config axes. -func (p *Pool) Acquire(ctx context.Context, key string) (*Lease, error) { +// are separate config axes. The resolved root rides along so a new +// instance is created rooted (decision 0004 §2); an existing instance +// keeps the root it was created with, which cannot differ, since the +// root is a pure function of the key. +func (p *Pool) Acquire(ctx context.Context, rs config.ResolvedScope) (*Lease, error) { + key := rs.Key exclusive := p.cfg.Sharing == config.SharingExclusive legacy := p.followLegacy(ctx) @@ -298,7 +318,7 @@ func (p *Pool) Acquire(ctx context.Context, key string) (*Lease, error) { } p.mu.Unlock() - in, err := p.startLane(ctx, legacy) + in, err := p.startLane(ctx, legacy, rs) p.mu.Lock() p.starting-- @@ -518,7 +538,9 @@ func (p *Pool) reapDeadLocked() { p.instances = kept } -func (p *Pool) start(ctx context.Context) (*Instance, error) { return p.startLane(ctx, false) } +func (p *Pool) start(ctx context.Context) (*Instance, error) { + return p.startLane(ctx, false, config.ResolvedScope{}) +} // installServerHooks wires what a server may ask of mcpx into the options its // session is opened with. It must run before the handshake, where a server @@ -582,13 +604,23 @@ func (p *Pool) subscribeServerEvents(cl *mcpclient.Client) { } // startLane starts an instance; legacy starts it legacy-only, for a legacy -// caller under protocol: follow. -func (p *Pool) startLane(ctx context.Context, legacy bool) (*Instance, error) { +// caller under protocol: follow. rs is the resolved scope the instance +// serves: its root is stored on the instance at creation and read back +// for every restart, never re-resolved (decision 0004 §2). +func (p *Pool) startLane(ctx context.Context, legacy bool, rs config.ResolvedScope) (*Instance, error) { sctx, cancel := context.WithTimeout(ctx, p.cfg.StartTimeout) defer cancel() launched := time.Now() - tr, err := p.dial(sctx) + spawnCwd, cwdSource := SpawnCwd(p.cfg.Cwd, rs.Root) + if !p.cfg.Stdio() { + // No process, no cwd: the root is recorded, but nothing spawns + // anywhere, so the daemon-cwd source is the honest one. + spawnCwd, cwdSource = "", "daemon" + } + execStamp, execIdentity, _ := p.cfg.ExecStateAt(spawnCwd) + + tr, err := p.dial(sctx, rs.Root) if err != nil { return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err) } @@ -628,7 +660,7 @@ func (p *Pool) startLane(ctx context.Context, legacy bool) (*Instance, error) { // transport; going straight there saves the two refused POSTs. if cl, tr, err = p.connectSSE(sctx, tr, opts); err == nil { source = mcpclient.SourceCache - } else if tr, err = p.dial(sctx); err != nil { + } else if tr, err = p.dial(sctx, rs.Root); err != nil { return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err) } } @@ -659,7 +691,7 @@ func (p *Pool) startLane(ctx context.Context, legacy bool) (*Instance, error) { // that hears initialize first -- and the cache is what keeps this // from happening on every start. _ = tr.Close() - if tr, err = p.dial(sctx); err != nil { + if tr, err = p.dial(sctx, rs.Root); err != nil { return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err) } opts.Preference, opts.Cached = mcpclient.ForceLegacy, "" @@ -709,16 +741,26 @@ func (p *Pool) startLane(ctx context.Context, legacy bool) (*Instance, error) { p.mu.Unlock() in := &Instance{ - ID: id, - Client: cl, - transport: tr, - trace: newTraceID("srv"), - startedAt: time.Now(), - lastUsed: time.Now(), - eraSource: source, - legacyLane: legacy, + ID: id, + Client: cl, + transport: tr, + key: rs.Key, + root: rs.Root, + execStamp: execStamp, + execIdentity: execIdentity, + trace: newTraceID("srv"), + startedAt: time.Now(), + lastUsed: time.Now(), + eraSource: source, + legacyLane: legacy, } ref.set(in) + // One line per spawn (decision 0004 §6): which server, serving + // which scope key, rooted where, and where its cwd came from. + lifecycle("server.spawn", map[string]any{ + "server": p.cfg.Name, "instance": in.ID, "key": rs.Key, + "root": rs.Root, "cwd": spawnCwd, "cwdSource": cwdSource, + }) // A replacement instance -- after a restart, a crash, an eviction -- // knows nothing of what its predecessor was subscribed to. p.resubscribe(sctx, in) @@ -726,7 +768,8 @@ func (p *Pool) startLane(ctx context.Context, legacy bool) (*Instance, error) { "server": p.cfg.Name, "instance": in.ID, "pid": in.PID(), "trace": in.trace, "sharing": string(p.cfg.Sharing), "scope": string(p.cfg.Scope), "transport": transportName(p.cfg), - "era": string(cl.Era), "negotiated": cl.Negotiated, "eraSource": source, + "key": rs.Key, "root": rs.Root, "cwdSource": cwdSource, + "era": string(cl.Era), "negotiated": cl.Negotiated, "eraSource": source, // Time to ready, not time to spawn: the event fires after the // handshake has answered, so this is when the server could first // take a call. @@ -876,10 +919,28 @@ func (p *Pool) connectSSE(ctx context.Context, tr mcpclient.Transport, opts mcpc return cl, sse, nil } +// SpawnCwd is the spawn-cwd decision of decision 0004 §3 as a pure +// function: an explicit config cwd wins, then the instance's resolved +// scope root, else unset, so the child inherits the daemon's cwd. +// source names the rule that fired: "config", "scope" or "daemon". +func SpawnCwd(configCwd, root string) (cwd, source string) { + switch { + case configCwd != "": + return configCwd, "config" + case root != "": + return root, "scope" + default: + return "", "daemon" + } +} + // dial creates the transport for one instance. ctx is the caller's // startup context: it bounds any nix: program-spec resolution at spawn, -// so a slow build cannot outlive the startup budget that owns it. -func (p *Pool) dial(ctx context.Context) (mcpclient.Transport, error) { +// so a slow build cannot outlive the startup budget that owns it. root +// is the spawning instance's resolved scope root, stored on the +// instance at creation -- never re-resolved here (decision 0004 §2). +func (p *Pool) dial(ctx context.Context, root string) (mcpclient.Transport, error) { + spawnCwd, _ := SpawnCwd(p.cfg.Cwd, root) auth, err := p.resolveAuth() if err != nil { return nil, err @@ -890,7 +951,7 @@ func (p *Pool) dial(ctx context.Context) (mcpclient.Transport, error) { Command: p.cfg.Command, Args: p.cfg.Args, Env: overlay(overlay(p.cfg.Env, p.runtimeEnv()), auth.Env), - Cwd: p.cfg.Cwd, + Cwd: spawnCwd, InheritEnv: true, Context: ctx, }) @@ -900,7 +961,7 @@ func (p *Pool) dial(ctx context.Context) (mcpclient.Transport, error) { Command: p.cfg.Command, Args: p.cfg.Args, Env: overlay(overlay(p.cfg.Env, p.runtimeEnv()), auth.Env), - Cwd: p.cfg.Cwd, + Cwd: spawnCwd, InheritEnv: true, Context: ctx, }) @@ -1057,7 +1118,7 @@ func (p *Pool) refreshSchemas(ctx context.Context, staleGen *time.Time) ([]mcpcl // for anything narrower it is a throwaway, stopped again below so a // per-session server does not keep a process nobody asked for. key := p.schemaKey() - lease, err := p.Acquire(ctx, key) + lease, err := p.Acquire(ctx, config.ResolvedScope{Key: key}) if err != nil { return p.refreshFailed(staleGen, err) } @@ -1268,13 +1329,13 @@ func (p *Pool) CachedPrompts() []mcpclient.Prompt { } // GetPrompt renders one prompt on a leased instance. -func (p *Pool) GetPrompt(ctx context.Context, sessionKey, name string, args map[string]string) (json.RawMessage, error) { - lease, err := p.Acquire(ctx, sessionKey) +func (p *Pool) GetPrompt(ctx context.Context, rs config.ResolvedScope, name string, args map[string]string) (json.RawMessage, error) { + lease, err := p.Acquire(ctx, rs) if err != nil { return nil, err } defer lease.Release() - cctx, finish := p.upstream(ctx, sessionKey, lease) + cctx, finish := p.upstream(ctx, rs.Key, lease) res, err := lease.Client().GetPrompt(cctx, name, args) return res, finish(err) } @@ -1360,8 +1421,9 @@ func (p *Pool) Preference() mcpclient.Preference { } // Call runs a tool on a leased instance. -func (p *Pool) Call(ctx context.Context, sessionKey, tool string, args any) (json.RawMessage, error) { - lease, err := p.Acquire(ctx, sessionKey) +func (p *Pool) Call(ctx context.Context, rs config.ResolvedScope, tool string, args any) (json.RawMessage, error) { + sessionKey := rs.Key + lease, err := p.Acquire(ctx, rs) if err != nil { return nil, err } @@ -1406,14 +1468,14 @@ func (p *Pool) Call(ctx context.Context, sessionKey, tool string, args any) (jso } // ReadResource reads a resource URI on a leased instance. -func (p *Pool) ReadResource(ctx context.Context, sessionKey, uri string) (json.RawMessage, error) { - lease, err := p.Acquire(ctx, sessionKey) +func (p *Pool) ReadResource(ctx context.Context, rs config.ResolvedScope, uri string) (json.RawMessage, error) { + lease, err := p.Acquire(ctx, rs) if err != nil { return nil, err } defer lease.Release() - cctx, finish := p.upstream(ctx, sessionKey, lease) + cctx, finish := p.upstream(ctx, rs.Key, lease) res, err := lease.Client().ReadResource(cctx, uri) return res, p.replacedErr(lease.inst, finish(err)) } @@ -1475,6 +1537,7 @@ type InstanceStatus struct { PID int `json:"pid,omitempty"` Holders int `json:"holders"` Key string `json:"key,omitempty"` + Root string `json:"root,omitempty"` Calls int64 `json:"calls"` UptimeSec int `json:"uptimeSec"` IdleSec int `json:"idleSec"` @@ -1519,6 +1582,7 @@ func (p *Pool) Status() Status { PID: in.PID(), Holders: in.holders, Key: in.key, + Root: in.root, Calls: in.calls.Load(), UptimeSec: int(now.Sub(in.startedAt).Seconds()), IdleSec: int(now.Sub(in.lastUsed).Seconds()), @@ -1618,11 +1682,13 @@ func (p *Pool) Restart(ctx context.Context, lazy bool) RestartResult { return res } var keys []string + roots := map[string]string{} seen := map[string]bool{} for _, in := range stop { if !seen[in.key] { seen[in.key] = true keys = append(keys, in.key) + roots[in.key] = in.root } } for _, in := range retiring { @@ -1649,7 +1715,7 @@ func (p *Pool) Restart(ctx context.Context, lazy bool) RestartResult { res.Skipped = append(res.Skipped, RestartFailure{Key: key, Error: "owning process has exited"}) continue } - id, err := p.startFor(ctx, key) + id, err := p.startFor(ctx, config.ResolvedScope{Key: key, Root: roots[key]}) if err != nil { res.Failed = append(res.Failed, RestartFailure{Key: key, Error: err.Error()}) continue @@ -1668,8 +1734,8 @@ type RestartFailure struct { // startFor brings up the instance for key and lets it go idle. Acquire, not // start, so capacity, a concurrent caller and a subscription monitor // replacing the same key all converge on one process. -func (p *Pool) startFor(ctx context.Context, key string) (string, error) { - lease, err := p.Acquire(ctx, key) +func (p *Pool) startFor(ctx context.Context, rs config.ResolvedScope) (string, error) { + lease, err := p.Acquire(ctx, rs) if err != nil { return "", err } diff --git a/pkgs/mcpx/internal/pool/pool_test.go b/pkgs/mcpx/internal/pool/pool_test.go index c23918bf8d..a7c0d3298a 100644 --- a/pkgs/mcpx/internal/pool/pool_test.go +++ b/pkgs/mcpx/internal/pool/pool_test.go @@ -40,7 +40,7 @@ func key(t *testing.T, r *config.Resolved, cc config.CallContext) string { // call resolves the key for a call context and dispatches. func call(t *testing.T, p *pool.Pool, r *config.Resolved, cc config.CallContext, tool string, args any) (json.RawMessage, error) { t.Helper() - return p.Call(context.Background(), key(t, r, cc), tool, args) + return p.Call(context.Background(), config.ResolvedScope{Key: key(t, r, cc)}, tool, args) } // textOf pulls the single text block out of a CallToolResult. @@ -105,7 +105,7 @@ func barrier(t *testing.T, p *pool.Pool, key string, n int) { wg.Add(1) go func(i int) { defer wg.Done() - res[i], errs[i] = p.Call(context.Background(), key, "slow", + res[i], errs[i] = p.Call(context.Background(), config.ResolvedScope{Key: key}, "slow", map[string]any{"ms": 10000, "barrier": n}) }(i) } @@ -183,11 +183,11 @@ func TestSessionModeReusesTheSameInstanceWithinASession(t *testing.T) { ctx := context.Background() for i := 0; i < 4; i++ { - if _, err := p.Call(ctx, "sticky", "open", map[string]any{"value": fmt.Sprint(i)}); err != nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: "sticky"}, "open", map[string]any{"value": fmt.Sprint(i)}); err != nil { t.Fatalf("open %d: %v", i, err) } } - res, err := p.Call(ctx, "sticky", "state", map[string]any{}) + res, err := p.Call(ctx, config.ResolvedScope{Key: "sticky"}, "state", map[string]any{}) if err != nil { t.Fatalf("state: %v", err) } @@ -219,7 +219,7 @@ func TestSessionModeRespectsMaxAndQueues(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() session := fmt.Sprintf("s%d", i) - _, errs[i] = p.Call(ctx, session, "slow", map[string]any{"ms": 100}) + _, errs[i] = p.Call(ctx, config.ResolvedScope{Key: session}, "slow", map[string]any{"ms": 100}) p.ReleaseKey(session) }(i) } @@ -240,7 +240,7 @@ func TestReleaseSessionStopsTheInstance(t *testing.T) { defer p.Close() ctx := context.Background() - if _, err := p.Call(ctx, "s1", "echo", map[string]any{"message": "hi"}); err != nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: "s1"}, "echo", map[string]any{"message": "hi"}); err != nil { t.Fatal(err) } if st := p.Status(); st.Live != 1 { @@ -264,7 +264,7 @@ func TestPooledModeRecyclesInstances(t *testing.T) { ctx := context.Background() for i := 0; i < 6; i++ { k := fmt.Sprintf("call:c%d", i) - if _, err := p.Call(ctx, k, "echo", map[string]any{"message": "x"}); err != nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: k}, "echo", map[string]any{"message": "x"}); err != nil { t.Fatalf("call %d: %v", i, err) } if st := p.Status(); st.Live > 2 { @@ -280,7 +280,7 @@ func TestStartFailureIsReportedWithStderr(t *testing.T) { p := pool.New(r) defer p.Close() - _, err := p.Call(context.Background(), "", "echo", map[string]any{"message": "x"}) + _, err := p.Call(context.Background(), config.ResolvedScope{Key: ""}, "echo", map[string]any{"message": "x"}) if err == nil { t.Fatal("expected an error when the server refuses to start") } @@ -297,10 +297,10 @@ func TestStartFailureEntersCooldown(t *testing.T) { defer p.Close() ctx := context.Background() - if _, err := p.Call(ctx, "", "echo", map[string]any{}); err == nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: ""}, "echo", map[string]any{}); err == nil { t.Fatal("first call should fail") } - _, err := p.Call(ctx, "", "echo", map[string]any{}) + _, err := p.Call(ctx, config.ResolvedScope{Key: ""}, "echo", map[string]any{}) if err == nil || !strings.Contains(err.Error(), "cooldown") { t.Fatalf("second call should be short-circuited by cooldown, got: %v", err) } @@ -311,7 +311,7 @@ func TestToolErrorsPropagate(t *testing.T) { p := pool.New(resolved(t, bin, &config.Extras{Sharing: config.SharingShared, Scope: config.ScopeGlobal})) defer p.Close() - res, err := p.Call(context.Background(), "", "boom", map[string]any{}) + res, err := p.Call(context.Background(), config.ResolvedScope{Key: ""}, "boom", map[string]any{}) if err != nil { t.Fatalf("a tool-level error is a valid result, not a transport error: %v", err) } @@ -383,10 +383,10 @@ func TestRestartStopsEverything(t *testing.T) { defer p.Close() ctx := context.Background() - if _, err := p.Call(ctx, "a", "open", map[string]any{"value": "1"}); err != nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: "a"}, "open", map[string]any{"value": "1"}); err != nil { t.Fatal(err) } - if _, err := p.Call(ctx, "b", "open", map[string]any{"value": "2"}); err != nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: "b"}, "open", map[string]any{"value": "2"}); err != nil { t.Fatal(err) } if n := p.Restart(ctx, true).Stopped; n != 2 { @@ -397,7 +397,7 @@ func TestRestartStopsEverything(t *testing.T) { t.Fatalf("%d instances survived restart", st.Live) } // A fresh instance must have no memory of the old state. - res, err := p.Call(ctx, "a", "state", map[string]any{}) + res, err := p.Call(ctx, config.ResolvedScope{Key: "a"}, "state", map[string]any{}) if err != nil { t.Fatal(err) } @@ -415,7 +415,7 @@ func TestRestartReplacesEachInstanceUnderItsKey(t *testing.T) { ctx := context.Background() for _, k := range []string{"session:a", "session:b"} { - if _, err := p.Call(ctx, k, "open", map[string]any{"value": "1"}); err != nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: k}, "open", map[string]any{"value": "1"}); err != nil { t.Fatal(err) } } @@ -437,7 +437,7 @@ func TestRestartReplacesEachInstanceUnderItsKey(t *testing.T) { t.Fatalf("instance %+v is not a fresh replacement for a previous key (before %v)", in, before) } } - got, err := p.Call(ctx, "session:a", "state", map[string]any{}) + got, err := p.Call(ctx, config.ResolvedScope{Key: "session:a"}, "state", map[string]any{}) if err != nil { t.Fatal(err) } @@ -497,7 +497,7 @@ func TestCallTimeoutIsEnforced(t *testing.T) { })) defer p.Close() - _, err := p.Call(context.Background(), "", "slow", map[string]any{"ms": 3000}) + _, err := p.Call(context.Background(), config.ResolvedScope{Key: ""}, "slow", map[string]any{"ms": 3000}) if err == nil { t.Fatal("expected a timeout") } @@ -513,7 +513,7 @@ func TestIdleReaperStopsUnusedInstances(t *testing.T) { })) defer p.Close() - if _, err := p.Call(context.Background(), "s", "echo", map[string]any{"message": "x"}); err != nil { + if _, err := p.Call(context.Background(), config.ResolvedScope{Key: "s"}, "echo", map[string]any{"message": "x"}); err != nil { t.Fatal(err) } time.Sleep(50 * time.Millisecond) @@ -552,7 +552,7 @@ func TestExclusiveSharingSerialisesOneKey(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - _, _ = p.Call(context.Background(), "session:one", "slow", map[string]any{"ms": 150}) + _, _ = p.Call(context.Background(), config.ResolvedScope{Key: "session:one"}, "slow", map[string]any{"ms": 150}) }() } wg.Wait() @@ -576,10 +576,10 @@ func TestDistinctKeysGetDistinctProcesses(t *testing.T) { ctx := context.Background() pids := map[string]bool{} for _, k := range []string{"session:a", "session:b", "session:c"} { - if _, err := p.Call(ctx, k, "open", map[string]any{"value": k}); err != nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: k}, "open", map[string]any{"value": k}); err != nil { t.Fatal(err) } - res, err := p.Call(ctx, k, "state", map[string]any{}) + res, err := p.Call(ctx, config.ResolvedScope{Key: k}, "state", map[string]any{}) if err != nil { t.Fatal(err) } @@ -615,7 +615,7 @@ func TestPidScopedInstanceIsReapedWhenThePidExits(t *testing.T) { } deadPID := dead.Process.Pid - if _, err := p.Call(context.Background(), fmt.Sprintf("pid:%d", deadPID), "echo", + if _, err := p.Call(context.Background(), config.ResolvedScope{Key: fmt.Sprintf("pid:%d", deadPID)}, "echo", map[string]any{"message": "x"}); err != nil { t.Fatal(err) } @@ -635,7 +635,7 @@ func TestPidScopedInstanceSurvivesWhileThePidLives(t *testing.T) { })) defer p.Close() - if _, err := p.Call(context.Background(), fmt.Sprintf("pid:%d", os.Getpid()), "echo", + if _, err := p.Call(context.Background(), config.ResolvedScope{Key: fmt.Sprintf("pid:%d", os.Getpid())}, "echo", map[string]any{"message": "x"}); err != nil { t.Fatal(err) } @@ -653,7 +653,7 @@ func TestReleaseKeyStopsOnlyThatKey(t *testing.T) { ctx := context.Background() for _, k := range []string{"session:a", "session:b"} { - if _, err := p.Call(ctx, k, "echo", map[string]any{"message": "x"}); err != nil { + if _, err := p.Call(ctx, config.ResolvedScope{Key: k}, "echo", map[string]any{"message": "x"}); err != nil { t.Fatal(err) } } diff --git a/pkgs/mcpx/internal/pool/request.go b/pkgs/mcpx/internal/pool/request.go index aae2a6cd6d..a561fb4f19 100644 --- a/pkgs/mcpx/internal/pool/request.go +++ b/pkgs/mcpx/internal/pool/request.go @@ -5,6 +5,7 @@ import ( "encoding/json" "sync/atomic" + "github.com/developing-today/code/pkgs/mcpx/internal/config" "github.com/developing-today/code/pkgs/mcpx/internal/mcpclient" ) @@ -38,8 +39,9 @@ func (r *instanceRef) key() string { // a code-mode host needs, and nothing else could reach the wire at all. That // is why /v1/complete answered from cache with `upstream:false`: not because // the server could not complete, but because no code path existed to ask it. -func (p *Pool) Request(ctx context.Context, sessionKey, method string, params json.RawMessage) (json.RawMessage, error) { - lease, err := p.Acquire(ctx, sessionKey) +func (p *Pool) Request(ctx context.Context, rs config.ResolvedScope, method string, params json.RawMessage) (json.RawMessage, error) { + sessionKey := rs.Key + lease, err := p.Acquire(ctx, rs) if err != nil { return nil, err } @@ -57,8 +59,9 @@ func (p *Pool) Request(ctx context.Context, sessionKey, method string, params js // showing, because a client that cannot tell an empty list from an // unimplemented method shows nothing and the user concludes the feature is // broken. -func (p *Pool) Complete(ctx context.Context, sessionKey string, params json.RawMessage) (json.RawMessage, bool, error) { - lease, err := p.Acquire(ctx, sessionKey) +func (p *Pool) Complete(ctx context.Context, rs config.ResolvedScope, params json.RawMessage) (json.RawMessage, bool, error) { + sessionKey := rs.Key + lease, err := p.Acquire(ctx, rs) if err != nil { return nil, false, err } diff --git a/pkgs/mcpx/internal/pool/self_connection_test.go b/pkgs/mcpx/internal/pool/self_connection_test.go index 5042e8efc9..909c2ac041 100644 --- a/pkgs/mcpx/internal/pool/self_connection_test.go +++ b/pkgs/mcpx/internal/pool/self_connection_test.go @@ -94,7 +94,7 @@ func TestPoolRefusesSelfConnectionByIdentity(t *testing.T) { u := newSelfUpstream(t) p := upstreamPool(t, u.URL) for attempt := 0; attempt < 3; attempt++ { - _, err := p.Acquire(context.Background(), "global") + _, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err == nil { t.Fatalf("attempt %d: self-connection was admitted", attempt) } @@ -160,7 +160,7 @@ func (u *modernSelfUpstream) serve(w http.ResponseWriter, r *http.Request) { func TestPoolRefusesModernSelfConnection(t *testing.T) { u := newModernSelfUpstream(t) p := upstreamPool(t, u.URL) - _, err := p.Acquire(context.Background(), "global") + _, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err == nil || !strings.Contains(err.Error(), "self-connection") { t.Fatalf("modern self-connection: err=%v, want a self-connection refusal", err) } @@ -227,7 +227,7 @@ func TestPoolRefusalDropsCachedSchemas(t *testing.T) { if cached, _, _ := p.CachedSchemas(); len(cached) != 2 { t.Fatalf("seeded cache not in place: %d tools", len(cached)) } - if _, err := p.Acquire(context.Background(), "global"); err == nil { + if _, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}); err == nil { t.Fatal("self-connection was admitted over a seeded cache") } if cached, _, _ := p.CachedSchemas(); len(cached) != 0 { @@ -281,7 +281,7 @@ func newReactiveSelfUpstream(t *testing.T) *reactiveSelfUpstream { func TestPoolRefusesReactiveSelfConnection(t *testing.T) { u := newReactiveSelfUpstream(t) p := upstreamPool(t, u.URL) - _, err := p.Acquire(context.Background(), "global") + _, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err == nil || !strings.Contains(err.Error(), "self-connection") { t.Fatalf("reactive self-connection: err=%v, want a self-connection refusal", err) } @@ -310,7 +310,7 @@ func TestPoolRefusesAdoptedSelfSession(t *testing.T) { if cached, _, _ := p.CachedSchemas(); len(cached) != 0 { t.Fatalf("adopted self session left %d cached tools advertised", len(cached)) } - if _, err := p.Acquire(context.Background(), "global"); err == nil || + if _, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}); err == nil || !strings.Contains(err.Error(), "self-connection") { t.Fatalf("adopted self session was published: err=%v, want a self-connection refusal", err) } @@ -326,7 +326,7 @@ func TestPoolAdmitsDistinctMcpxPeerByInstance(t *testing.T) { pool.OwnInstanceID = "own-instance" defer func() { pool.OwnInstanceID = "" }() p := upstreamPool(t, u.URL) - lease, err := p.Acquire(context.Background(), "global") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err != nil { t.Fatalf("distinct mcpx peer was refused: %v", err) } @@ -342,7 +342,7 @@ func TestPoolRefusesOwnInstanceByIdentity(t *testing.T) { pool.OwnInstanceID = "own-instance" defer func() { pool.OwnInstanceID = "" }() p := upstreamPool(t, u.URL) - _, err := p.Acquire(context.Background(), "global") + _, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err == nil || !strings.Contains(err.Error(), "self-connection") { t.Fatalf("own instance admitted or wrong error: %v", err) } @@ -421,7 +421,7 @@ func TestPoolStdioShimBackingIdentity(t *testing.T) { sameDaemon := newFakeDaemon(t, "daemon-alpha") sameCfg := writeShimConfig(t, sameDaemon.URL) samePool := stdioPool(t, mcpx, sameDaemon.URL, "--config", sameCfg, "serve") - _, err := samePool.Acquire(context.Background(), "global") + _, err := samePool.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err == nil || !strings.Contains(err.Error(), "self-connection") { t.Fatalf("stdio shim backed by same daemon was admitted: err=%v, want self-connection refusal", err) } @@ -432,7 +432,7 @@ func TestPoolStdioShimBackingIdentity(t *testing.T) { diffDaemon := newFakeDaemon(t, "daemon-beta") diffCfg := writeShimConfig(t, diffDaemon.URL) diffPool := stdioPool(t, mcpx, diffDaemon.URL, "--config", diffCfg, "serve") - lease, err := diffPool.Acquire(context.Background(), "global") + lease, err := diffPool.Acquire(context.Background(), config.ResolvedScope{Key: "global"}) if err != nil { t.Fatalf("stdio shim backed by distinct daemon was refused: %v", err) } diff --git a/pkgs/mcpx/internal/pool/shutdown_drain_test.go b/pkgs/mcpx/internal/pool/shutdown_drain_test.go index 4fd5d5c18b..b4cbe27689 100644 --- a/pkgs/mcpx/internal/pool/shutdown_drain_test.go +++ b/pkgs/mcpx/internal/pool/shutdown_drain_test.go @@ -16,7 +16,7 @@ import ( func TestCloseDrainedWithinCutsACallThatNeverReturnsAtTheWindow(t *testing.T) { bin := testsupport.FakeMCPBinary(t) p := pool.New(resolved(t, bin, &config.Extras{Sharing: config.SharingExclusive, Scope: config.ScopeSession, Max: 2})) - lease, err := p.Acquire(context.Background(), "s1") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "s1"}) if err != nil { t.Fatal(err) } @@ -40,7 +40,7 @@ func TestCloseDrainedWithinCutsACallThatNeverReturnsAtTheWindow(t *testing.T) { func TestCloseDrainedWithinLetsACallFinishInsideTheWindow(t *testing.T) { bin := testsupport.FakeMCPBinary(t) p := pool.New(resolved(t, bin, &config.Extras{Sharing: config.SharingExclusive, Scope: config.ScopeSession, Max: 2})) - lease, err := p.Acquire(context.Background(), "s1") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "s1"}) if err != nil { t.Fatal(err) } @@ -62,7 +62,7 @@ func TestCloseDrainedWithinLetsACallFinishInsideTheWindow(t *testing.T) { func TestCloseDrainedWithinZeroCutsAtOnce(t *testing.T) { bin := testsupport.FakeMCPBinary(t) p := pool.New(resolved(t, bin, &config.Extras{Sharing: config.SharingExclusive, Scope: config.ScopeSession, Max: 2})) - lease, err := p.Acquire(context.Background(), "s1") + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "s1"}) if err != nil { t.Fatal(err) } diff --git a/pkgs/mcpx/internal/pool/spawn_cwd_test.go b/pkgs/mcpx/internal/pool/spawn_cwd_test.go new file mode 100644 index 0000000000..9443dd4e1c --- /dev/null +++ b/pkgs/mcpx/internal/pool/spawn_cwd_test.go @@ -0,0 +1,76 @@ +package pool_test + +import ( + "context" + "os" + "path/filepath" + "strconv" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/config" + "github.com/developing-today/code/pkgs/mcpx/internal/pool" + "github.com/developing-today/code/pkgs/mcpx/internal/testsupport" +) + +// Decision 0004 §3: the spawn-cwd decision as a pure function -- +// config cwd beats the resolved scope root beats the daemon cwd. +func TestSpawnCwdDecision(t *testing.T) { + for _, tc := range []struct { + name string + configCwd string + root string + wantCwd string + wantSource string + }{ + {"config beats root", "/cfg", "/root", "/cfg", "config"}, + {"config alone", "/cfg", "", "/cfg", "config"}, + {"root when no config cwd", "", "/root", "/root", "scope"}, + {"daemon fallback", "", "", "", "daemon"}, + } { + t.Run(tc.name, func(t *testing.T) { + cwd, source := pool.SpawnCwd(tc.configCwd, tc.root) + if cwd != tc.wantCwd || source != tc.wantSource { + t.Fatalf("SpawnCwd(%q, %q) = (%q, %q), want (%q, %q)", + tc.configCwd, tc.root, cwd, source, tc.wantCwd, tc.wantSource) + } + }) + } +} + +// Decision 0004 §2/§3/§6 end to end: an instance created with a +// resolved root keeps it in status and spawns in it when the server +// has no config cwd. +func TestInstanceRootAndSpawnCwd(t *testing.T) { + bin := testsupport.FakeMCPBinary(t) + p := pool.New(resolved(t, bin, &config.Extras{Sharing: config.SharingShared, Scope: config.ScopeWorktree})) + defer p.Close() + + root := t.TempDir() + if r, err := filepath.EvalSymlinks(root); err == nil { + root = r + } + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: "worktree:" + root, Root: root}) + if err != nil { + t.Fatalf("acquire: %v", err) + } + defer lease.Release() + + st := p.Status() + if len(st.Instances) != 1 { + t.Fatalf("expected one instance, got %+v", st.Instances) + } + if st.Instances[0].Root != root { + t.Fatalf("status root = %q, want %q", st.Instances[0].Root, root) + } + pid := st.Instances[0].PID + if pid == 0 { + t.Fatal("stdio instance should report a pid") + } + cwd, err := os.Readlink(filepath.Join("/proc", strconv.Itoa(pid), "cwd")) + if err != nil { + t.Skipf("cannot read child cwd: %v", err) + } + if cwd != root { + t.Fatalf("child spawned in %q, want the resolved root %q", cwd, root) + } +} diff --git a/pkgs/mcpx/internal/pool/upstream_session_test.go b/pkgs/mcpx/internal/pool/upstream_session_test.go index 84a1e85664..8ca4dab127 100644 --- a/pkgs/mcpx/internal/pool/upstream_session_test.go +++ b/pkgs/mcpx/internal/pool/upstream_session_test.go @@ -117,7 +117,7 @@ func upstreamPool(t *testing.T, url string) *pool.Pool { func pingThrough(t *testing.T, p *pool.Pool, key string) { t.Helper() - lease, err := p.Acquire(context.Background(), key) + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: key}) if err != nil { t.Fatal(err) } diff --git a/pkgs/mcpx/internal/pool/watch.go b/pkgs/mcpx/internal/pool/watch.go index 01e98c94eb..576059b415 100644 --- a/pkgs/mcpx/internal/pool/watch.go +++ b/pkgs/mcpx/internal/pool/watch.go @@ -4,6 +4,8 @@ import ( "context" "errors" "sync" + + "github.com/developing-today/code/pkgs/mcpx/internal/config" ) // Resource subscriptions, upstream. @@ -28,9 +30,10 @@ import ( var ErrNotSubscribable = errors.New("the server does not declare resources.subscribe") // Watch subscribes to updates for uri on this server until release is -// called. key is the scope key the instance is resolved under. -func (p *Pool) Watch(ctx context.Context, key, uri string) (release func(), err error) { - lease, err := p.Acquire(ctx, key) +// called. rs is the resolved scope the instance is resolved under. +func (p *Pool) Watch(ctx context.Context, rs config.ResolvedScope, uri string) (release func(), err error) { + key := rs.Key + lease, err := p.Acquire(ctx, rs) if err != nil { return nil, err } @@ -44,6 +47,7 @@ func (p *Pool) Watch(ctx context.Context, key, uri string) (release func(), err } p.watched[uri]++ p.watchKey = key + p.watchRoot = rs.Root p.watchMu.Unlock() if err := p.subscribeOn(ctx, lease.inst, uri); err != nil { p.unwatch(uri) @@ -146,6 +150,7 @@ func (p *Pool) monitor(in *Instance) { p.watchMu.Lock() wanted := len(p.watched) > 0 key := p.watchKey + root := p.watchRoot p.watchMu.Unlock() if closed || !wanted { return @@ -153,7 +158,7 @@ func (p *Pool) monitor(in *Instance) { // Acquire starts the replacement, and start() subscribes it. A failure // here is the pool's ordinary start failure, recorded as lastErr; the // next caller that reaches this server retries it and resubscribes. - lease, err := p.Acquire(context.Background(), key) + lease, err := p.Acquire(context.Background(), config.ResolvedScope{Key: key, Root: root}) if err == nil { lease.Release() } diff --git a/pkgs/mcpx/internal/pool/watch_test.go b/pkgs/mcpx/internal/pool/watch_test.go index 8c54670883..426a8565f8 100644 --- a/pkgs/mcpx/internal/pool/watch_test.go +++ b/pkgs/mcpx/internal/pool/watch_test.go @@ -69,11 +69,11 @@ func eventually(t *testing.T, what string, ok func() bool) { func TestWatchCountsSubscribersPerURI(t *testing.T) { p, log := subscribing(t) ctx := context.Background() - a, err := p.Watch(ctx, "global", "/abs/doc") + a, err := p.Watch(ctx, config.ResolvedScope{Key: "global"}, "/abs/doc") if err != nil { t.Fatal(err) } - b, err := p.Watch(ctx, "global", "/abs/doc") + b, err := p.Watch(ctx, config.ResolvedScope{Key: "global"}, "/abs/doc") if err != nil { t.Fatal(err) } @@ -98,7 +98,7 @@ func TestWatchRefusesAServerWithoutSubscribe(t *testing.T) { bin := testsupport.FakeMCPBinary(t) p := pool.New(resolved(t, bin, &config.Extras{Sharing: config.SharingShared, Scope: config.ScopeGlobal})) defer p.Close() - if _, err := p.Watch(context.Background(), "global", "demo://greeting"); !errors.Is(err, pool.ErrNotSubscribable) { + if _, err := p.Watch(context.Background(), config.ResolvedScope{Key: "global"}, "demo://greeting"); !errors.Is(err, pool.ErrNotSubscribable) { t.Fatalf("got %v", err) } if len(p.Watching()) != 0 { @@ -108,7 +108,7 @@ func TestWatchRefusesAServerWithoutSubscribe(t *testing.T) { func TestWatchResubscribesAReplacementInstance(t *testing.T) { p, log := subscribing(t) - release, err := p.Watch(context.Background(), "global", "demo://greeting") + release, err := p.Watch(context.Background(), config.ResolvedScope{Key: "global"}, "demo://greeting") if err != nil { t.Fatal(err) } @@ -127,7 +127,7 @@ func TestWatchResubscribesAReplacementInstance(t *testing.T) { func TestAWatchedInstanceIsNotIdle(t *testing.T) { p, _ := subscribing(t) - release, err := p.Watch(context.Background(), "global", "demo://greeting") + release, err := p.Watch(context.Background(), config.ResolvedScope{Key: "global"}, "demo://greeting") if err != nil { t.Fatal(err) }