diff --git a/pkgs/mcpx/docs/parity.md b/pkgs/mcpx/docs/parity.md index 07b99ffe7b..309a3313b0 100644 --- a/pkgs/mcpx/docs/parity.md +++ b/pkgs/mcpx/docs/parity.md @@ -137,7 +137,7 @@ that reaches none says why: those are decisions, not gaps. | `completion` | – | Text about the binary, produced by the binary. | | `config` | – | Reads the configuration files on the caller's search path; `settings` is the running daemon's view. | | `daemon` | – | Starts a daemon, which a daemon's own API cannot do. | -| `daemons` | – | Reads every daemon's info file on this machine; one daemon cannot see the others. | +| `daemons` | – | Reads every daemon's info file on this machine; one daemon cannot see the others. Daemons with their own state directory mirror their record into the default one, and records whose process is gone are pruned. | | `dashboard` | `dashboard` | | | `diagnose` | `diagnose` | | | `doctor` | – | Checks this machine: binaries on PATH, permissions, configuration files. | diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index 5227fa247c..8c484a5639 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -44,6 +44,9 @@ type App struct { machineOutput bool // inlineStop shuts down an in-process daemon when the command ends. inlineStop func() + // warnedPathsConfig records that the paths.config file-entry warning + // has been shown, so adoptSettings does not repeat it per command. + warnedPathsConfig bool // connected records that the ladder has been walked for this command. connected bool // ladder is how the connection was made, for doctor and --json output. @@ -1531,17 +1534,48 @@ func (a *App) CmdStop(ctx context.Context, args []string) error { return nil } +// daemonListing pairs a daemon record with the state directory it was +// found in, so the caller can build a client for exactly that daemon. +type daemonListing struct { + paths daemon.Paths + info daemon.Info +} + +// allDaemons returns every daemon record on this machine: the caller's +// state directory plus the default one, where daemons with a state +// directory of their own mirror their records (#278). Stale records -- +// the process is gone, so nothing is listening -- are pruned from disk +// and left out. Records are deduped by socket, since a mirrored record +// and its primary describe the same daemon. +func (a *App) allDaemons() []daemonListing { + var out []daemonListing + seen := map[string]bool{} + for _, dir := range daemon.DaemonSearchDirs(a.Paths.State) { + p := daemon.Paths{State: dir} + p.PruneStale() + for _, info := range p.ListDaemons() { + if seen[info.Socket] { + continue + } + seen[info.Socket] = true + out = append(out, daemonListing{paths: p, info: info}) + } + } + return out +} + // stopAll shuts down every daemon recorded in the state directory. Each // config gets its own daemon, so this is the way to clear them all after // working across many repos. func (a *App) stopAll(ctx context.Context) error { - infos := a.Paths.ListDaemons() - if len(infos) == 0 { + listings := a.allDaemons() + if len(listings) == 0 { fmt.Println("no daemons running") return nil } stopped := 0 - for _, info := range infos { + for _, listing := range listings { + info := listing.info p := a.Paths p.Socket = info.Socket c := NewClient(p, info.ConfigPath) @@ -1591,7 +1625,7 @@ func waitUntilStarted(ctx context.Context, c *Client) error { // CmdDaemons lists every daemon this user has running. func (a *App) CmdDaemons(ctx context.Context, args []string) error { - infos := a.Paths.ListDaemons() + listings := a.allDaemons() type row struct { PID int `json:"pid"` Config string `json:"config"` @@ -1599,8 +1633,9 @@ func (a *App) CmdDaemons(ctx context.Context, args []string) error { Started string `json:"startedAt"` } var rows []row - for _, info := range infos { - p := a.Paths + for _, listing := range listings { + info := listing.info + p := listing.paths p.Socket = info.Socket c := NewClient(p, info.ConfigPath) rows = append(rows, row{ diff --git a/pkgs/mcpx/internal/cli/manual.go b/pkgs/mcpx/internal/cli/manual.go index 608433d298..26eac92cc3 100644 --- a/pkgs/mcpx/internal/cli/manual.go +++ b/pkgs/mcpx/internal/cli/manual.go @@ -134,7 +134,7 @@ func handCommands() []Command { Local: "Manages embedded agent skills.", Usage: "[list|install] [--agent ] [--to ]", Summary: "list or install embedded mcpx agent skills", - Detail: "Lists available agent skills embedded with mcpx or installs them into the target agent configuration.", + Detail: "Lists available agent skills embedded with mcpx or installs them into the target agent configuration.", }, { Name: "recipes", Group: "running", @@ -237,7 +237,9 @@ func handCommands() []Command { }, { Name: "daemons", Group: "daemon", - Local: "Reads every daemon's info file on this machine; one daemon cannot see the others.", + Local: "Reads every daemon's info file on this machine; one daemon cannot see the others. " + + "Daemons with their own state directory mirror their record into the default one, " + + "and records whose process is gone are pruned.", Summary: "list every mcpx daemon on this machine", }, { diff --git a/pkgs/mcpx/internal/cli/root.go b/pkgs/mcpx/internal/cli/root.go index 606583c4fe..11d1cda6c0 100644 --- a/pkgs/mcpx/internal/cli/root.go +++ b/pkgs/mcpx/internal/cli/root.go @@ -205,6 +205,32 @@ func (a *App) adoptSettings() { } else if dir := set.String("paths.cache"); dir != "" { a.Paths = daemon.PathsAt(a.Paths.State, dir) } + a.warnPathsConfigFile(set) +} + +// warnPathsConfigFile warns when a paths.config entry names a file. +// +// The entries are directories that are searched for configuration files, +// so pointing one at a file -- a natural reading of --paths-config -- is +// silently ignored and the default configuration loads instead (#278). +// Naming the file directly is what MCPX_CONFIG and --config are for, so +// say so rather than leaving the user to debug a configuration that was +// never read. +func (a *App) warnPathsConfigFile(set *settings.Set) { + if a.warnedPathsConfig { + return + } + for _, entry := range set.List("paths.config") { + if st, err := os.Stat(entry); err == nil && !st.IsDir() { + fmt.Fprintf(os.Stderr, + "mcpx: warning: paths.config entry %q is a file; entries are "+ + "directories searched for config files, so it is ignored. "+ + "To use that file directly, pass --config %s or set MCPX_CONFIG.\n", + entry, entry) + a.warnedPathsConfig = true + return + } + } } // adoptSpec installs the MCP revision policy (spec.precedence, spec.first, diff --git a/pkgs/mcpx/internal/daemon/paths.go b/pkgs/mcpx/internal/daemon/paths.go index 18cd9f7882..5107bc2985 100644 --- a/pkgs/mcpx/internal/daemon/paths.go +++ b/pkgs/mcpx/internal/daemon/paths.go @@ -6,10 +6,12 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "fmt" "os" "path/filepath" "strings" + "syscall" ) // Paths resolves the on-disk locations mcpx uses. @@ -225,6 +227,104 @@ func ContentFingerprint(paths []string) string { return hex.EncodeToString(h.Sum(nil))[:12] } +// DefaultStateDir is the state directory a daemon uses when nobody asked +// for another one: XDG_STATE_HOME/mcpx, or ~/.local/state/mcpx. It ignores +// MCPX_STATE_DIR and paths.state on purpose -- it is the one location every +// invocation can compute, which is what makes it usable as the place custom +// state directories mirror their daemon records into (#278). +func DefaultStateDir() string { + home, _ := os.UserHomeDir() + return firstNonEmpty( + envJoin("XDG_STATE_HOME", "mcpx"), + filepath.Join(home, ".local", "state", "mcpx"), + ) +} + +// DaemonSearchDirs is where `mcpx daemons` looks for daemon records: the +// caller's own state directory, plus the default one. A daemon started +// with its own state directory mirrors its record into the default +// directory (see WriteInfo), so the second entry is what makes the listing +// cover the whole machine rather than only the caller's directory. +func DaemonSearchDirs(primary string) []string { + out := []string{primary} + if d := DefaultStateDir(); d != "" && d != primary { + out = append(out, d) + } + return out +} + +// ProcessAlive reports whether pid names a process that still exists. +// Signal 0 probes without delivering anything; EPERM means the process is +// there but owned by somebody else, which is still alive. +func ProcessAlive(pid int) bool { + if pid <= 0 { + return false + } + proc, err := os.FindProcess(pid) + if err != nil { + return false + } + err = proc.Signal(syscall.Signal(0)) + return err == nil || errors.Is(err, syscall.EPERM) +} + +// PruneStale removes this state directory's daemon records whose process +// is gone, and returns what it removed. A daemon that exits cleanly +// removes its own record; one that is killed or crashes cannot, and +// without pruning its record is listed forever (#278). Records with no +// PID recorded are kept: there is nothing to check them against. +func (p Paths) PruneStale() []Info { + entries, err := os.ReadDir(p.State) + if err != nil { + return nil + } + var out []Info + for _, e := range entries { + name := e.Name() + if !strings.HasPrefix(name, "daemon") || !strings.HasSuffix(name, ".json") { + continue + } + path := filepath.Join(p.State, name) + b, err := os.ReadFile(path) + if err != nil { + continue + } + var i Info + if json.Unmarshal(b, &i) != nil || i.PID == 0 || ProcessAlive(i.PID) { + continue + } + if err := os.Remove(path); err == nil { + out = append(out, i) + } + } + return out +} + +// mirrorInfoPath is where a daemon in a custom state directory also +// publishes its record: the default state directory, under a name keyed +// by its own directory so two custom directories cannot collide and a +// custom record cannot shadow the default directory's own daemon for the +// same configuration. Empty when this directory is the default one. +func (p Paths) mirrorInfoPath() string { + def := DefaultStateDir() + if def == "" || p.State == "" || p.State == def || p.Info == "" { + return "" + } + sum := sha256.Sum256([]byte(p.State)) + return filepath.Join(def, "daemon-x"+hex.EncodeToString(sum[:])[:12]+"-"+filepath.Base(p.Info)) +} + +// RemoveInfo removes the daemon record, including its mirror in the +// default state directory when there is one. +func (p Paths) RemoveInfo() { + if p.Info != "" { + _ = os.Remove(p.Info) + } + if m := p.mirrorInfoPath(); m != "" { + _ = os.Remove(m) + } +} + // ListDaemons returns the info records of every daemon in this state dir. func (p Paths) ListDaemons() []Info { entries, err := os.ReadDir(p.State) @@ -281,6 +381,13 @@ type Info struct { } // WriteInfo publishes the daemon record atomically. +// +// A daemon in a custom state directory also mirrors the record into the +// default state directory (#278): `mcpx daemons` promises every daemon on +// the machine, and a listing that only reads the caller's own directory +// can never see it. The mirror is best-effort -- the primary record is +// authoritative, and a daemon must not fail to start because a listing +// convenience could not be written. func (p Paths) WriteInfo(i Info) error { b, err := json.MarshalIndent(i, "", " ") if err != nil { @@ -290,7 +397,18 @@ func (p Paths) WriteInfo(i Info) error { if err := os.WriteFile(tmp, b, 0o600); err != nil { return err } - return os.Rename(tmp, p.Info) + if err := os.Rename(tmp, p.Info); err != nil { + return err + } + if m := p.mirrorInfoPath(); m != "" { + if err := os.MkdirAll(filepath.Dir(m), 0o700); err == nil { + mtmp := m + ".tmp" + if os.WriteFile(mtmp, b, 0o600) == nil { + _ = os.Rename(mtmp, m) + } + } + } + return nil } // ReadInfo loads the daemon record, if any. diff --git a/pkgs/mcpx/internal/daemon/paths_test.go b/pkgs/mcpx/internal/daemon/paths_test.go index d4e59935c3..5aeedab61b 100644 --- a/pkgs/mcpx/internal/daemon/paths_test.go +++ b/pkgs/mcpx/internal/daemon/paths_test.go @@ -1,7 +1,9 @@ package daemon_test import ( + "encoding/json" "os" + "os/exec" "path/filepath" "strings" "testing" @@ -170,3 +172,114 @@ func TestTheDaemonKeyIsTheFileSetNotTheContents(t *testing.T) { t.Errorf("a different path with the same contents kept the key: %+v", elsewhere) } } + +// deadPID returns the pid of a process that has exited and been reaped, so +// nothing can be listening on its behalf any more. +func deadPID(t *testing.T) int { + t.Helper() + cmd := exec.Command("true") + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + pid := cmd.Process.Pid + if err := cmd.Wait(); err != nil { + t.Fatal(err) + } + return pid +} + +func writeInfoFile(t *testing.T, dir, name string, info daemon.Info) { + t.Helper() + b, err := json.Marshal(info) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, name), b, 0o600); err != nil { + t.Fatal(err) + } +} + +func TestProcessAlive(t *testing.T) { + if !daemon.ProcessAlive(os.Getpid()) { + t.Error("this process should be alive") + } + if daemon.ProcessAlive(deadPID(t)) { + t.Error("a reaped process should not be alive") + } + if daemon.ProcessAlive(0) || daemon.ProcessAlive(-1) { + t.Error("a non-positive pid is never a live daemon") + } +} + +// #278: a daemon that was killed leaves its record behind, and the record +// was listed forever with RUNNING false. +func TestPruneStaleRemovesRecordsWhoseProcessIsGone(t *testing.T) { + dir := t.TempDir() + dead := deadPID(t) + writeInfoFile(t, dir, "daemon-dead.json", daemon.Info{ + PID: dead, Socket: filepath.Join(dir, "daemon-dead.sock"), + ConfigPath: "/dead/.mcpx.json", + }) + writeInfoFile(t, dir, "daemon-live.json", daemon.Info{ + PID: os.Getpid(), Socket: filepath.Join(dir, "daemon-live.sock"), + ConfigPath: "/live/.mcpx.json", + }) + // A record with no pid has nothing to check against and is kept. + writeInfoFile(t, dir, "daemon-nopid.json", daemon.Info{ + Socket: filepath.Join(dir, "daemon-nopid.sock"), + }) + + p := daemon.Paths{State: dir} + pruned := p.PruneStale() + if len(pruned) != 1 || pruned[0].PID != dead { + t.Fatalf("pruned = %+v, want only pid %d", pruned, dead) + } + if _, err := os.Stat(filepath.Join(dir, "daemon-dead.json")); !os.IsNotExist(err) { + t.Errorf("dead record should be removed from disk: %v", err) + } + got := p.ListDaemons() + if len(got) != 2 { + t.Fatalf("ListDaemons after prune = %d records, want the live and pid-less ones", len(got)) + } +} + +// #278: a daemon started with its own state directory never appeared in +// `mcpx daemons`, whose help promises every daemon on the machine. It +// mirrors its record into the default state directory, which the listing +// searches as well. +func TestWriteInfoMirrorsIntoTheDefaultStateDir(t *testing.T) { + xdg := t.TempDir() + t.Setenv("XDG_STATE_HOME", xdg) + def := daemon.DefaultStateDir() + if def != filepath.Join(xdg, "mcpx") { + t.Fatalf("DefaultStateDir = %q, want the XDG location", def) + } + custom := t.TempDir() + p := daemon.Paths{State: custom, Info: filepath.Join(custom, "daemon-abc.json")} + info := daemon.Info{ + PID: os.Getpid(), Socket: filepath.Join(custom, "daemon-abc.sock"), + ConfigPath: "/proj/.mcpx.json", + } + if err := p.WriteInfo(info); err != nil { + t.Fatal(err) + } + got := daemon.Paths{State: def}.ListDaemons() + if len(got) != 1 || got[0].Socket != info.Socket { + t.Fatalf("default dir listing = %+v, want the mirrored record", got) + } + if dirs := daemon.DaemonSearchDirs(custom); len(dirs) != 2 || dirs[0] != custom || dirs[1] != def { + t.Errorf("DaemonSearchDirs(custom) = %v, want [custom default]", dirs) + } + if dirs := daemon.DaemonSearchDirs(def); len(dirs) != 1 { + t.Errorf("DaemonSearchDirs(default) = %v, want no duplicate", dirs) + } + + p.RemoveInfo() + if _, err := os.Stat(p.Info); !os.IsNotExist(err) { + t.Errorf("primary record should be removed: %v", err) + } + remaining := daemon.Paths{State: def}.ListDaemons() + if len(remaining) != 0 { + t.Errorf("mirror should be removed too, still listed: %+v", remaining) + } +} diff --git a/pkgs/mcpx/internal/daemon/server.go b/pkgs/mcpx/internal/daemon/server.go index 3231be7dde..0a349a0266 100644 --- a/pkgs/mcpx/internal/daemon/server.go +++ b/pkgs/mcpx/internal/daemon/server.go @@ -485,7 +485,7 @@ func (s *Server) shutdown() error { _ = s.tokenStore.Close() } _ = os.Remove(s.paths.Socket) - _ = os.Remove(s.paths.Info) + s.paths.RemoveInfo() s.logger.Printf("stopped") return nil } @@ -1155,7 +1155,7 @@ func (s *Server) handleDaemonRestart(w http.ResponseWriter, _ *http.Request) { _ = os.Remove(s.paths.Socket) } if s.paths.Info != "" { - _ = os.Remove(s.paths.Info) + s.paths.RemoveInfo() } if s.logger != nil { s.logger.Printf("re-executing daemon: %s", execPath) diff --git a/pkgs/mcpx/internal/settings/consumed_test.go b/pkgs/mcpx/internal/settings/consumed_test.go index f1e48672fc..1da2d3abab 100644 --- a/pkgs/mcpx/internal/settings/consumed_test.go +++ b/pkgs/mcpx/internal/settings/consumed_test.go @@ -72,13 +72,11 @@ var readViaHelper = regexp.MustCompile( // the reason. An entry here is a claim somebody has to defend in review; // there is deliberately no way to silence this test in bulk. var unreadAllowed = map[string]string{ - // This entry used to say the setting was "read by config.SearchPath from - // MCPX_PATHS_CONFIG directly". Nothing reads MCPX_PATHS_CONFIG; the - // search path honours MCPX_CONFIG, which is paths.configFile below. - "paths.config": "circular by construction (#5): the config search path is " + - "what produces the settings, so the settings cannot decide it. It is " + - "declared so that `mcpx config --schema` names the thing. Nothing reads " + - "it yet -- not MCPX_PATHS_CONFIG, not --paths-config -- which #5 owns.", + // paths.config used to be listed here as circular by construction + // (#5): the search path produces the settings, so the settings cannot + // decide it. It is read now -- cli.adoptSettings warns when an entry + // names a file instead of a directory (#278) -- so it no longer + // belongs on this list. Deciding the search path itself remains #5's. "paths.configFile": "a bootstrap setting: it names the file the settings are " + "read from, so config.SearchPathFrom reads MCPX_CONFIG before any Set " + "exists, and the global --config reaches App.ConfigPath the same way.", diff --git a/treefmt.toml b/treefmt.toml index 10e990057f..89022cb283 100755 --- a/treefmt.toml +++ b/treefmt.toml @@ -3,9 +3,10 @@ # Exclude pkgs/id/ — it has its own treefmt/formatter [global] excludes = [ - "pkgs/id/**", # has its own treefmt/formatter - "pkgs/dht/**", # WIP package with syntax errors - ".opencode/**", # managed by opencode, may have permission issues + "pkgs/id/**", # has its own treefmt/formatter + "pkgs/dht/**", # WIP package with syntax errors + ".opencode/**", # managed by opencode, may have permission issues + "pkgs/mcpx/docs/parity.md", # generated; TestParityDocumentIsCurrent compares it byte-for-byte with the generator, so prettier's table padding can never be applied ] # [formatter.]