Files
magpie/internal/library/project_git.go
T
yetone 87b3af7653 library: a project turns a global MCP server or skill off, out of git, and its worktrees follow (WhyULose0 on X)
WhyULose0 asked for MCP servers and skills per project: a global set every
project inherits, each project that set ± items (a global one turned off
for one project too), one place to tick for every agent, nothing written
into the project's git, the router running a shared server once, and a
new git worktree following its main project.

What was there: projects could add skills and servers (Library → a
project's card), the MCP router ran each server once, but a project could
not turn a global item off, magpie wrote its entries into the project's
.gitignore (a tracked file), and a worktree got nothing.

What changed:
- Turning a global item off in one project (ProjectServerOff,
  ProjectSkillsOff; POST /api/library/projects/server-off, skill-off),
  done the way each agent reads a folder: Claude Code's record of the
  project in ~/.claude.json (disabledMcpServers; magpie takes out only
  names it put there), Codex's project .codex/config.toml
  ([mcp_servers.X] enabled = false, only for a server in Codex's own
  config), Claude Code's skillOverrides "off" in the project's
  .claude/settings.local.json.
- With the router on, a project that adds or turns off a routed server
  gives Claude Code (local scope in its project record) and Codex (project
  config) the hub at /mcp/magpie/hub/<agent>~<projectKey>; hubServers
  serves that address the project's set, each server still started once.
  gateway.HubAgentOf cuts the key off for the log, errors and on-demand.
- Out of git: entries go to the repository's info/exclude (one block per
  project, shared by every worktree); the .gitignore is left as the user
  wrote it, and a block an older magpie wrote there is taken out. A folder
  git-inited later gets its block on the next KeepLinked.
- Worktrees: the project's folder in each worktree of its repository gets
  the same skills, servers and offs, found on KeepLinked, let go when
  removed.
- GUI: a project's card lights each agent that has an item from the
  Library; a click turns it off (or back on) in that project. An agent that
  can't take an off (Gemini CLI etc., or a skill that goes through the
  skill router) stays lit and says why. The Skills menu ticks inherited
  skills; unticking turns one off. zh, zh-TW, ja, de.

Limits, per agent:
- Offs only for Claude Code (servers and skills) and Codex (servers).
  Codex reads the project config only in a trusted project.
- A skill reached through the skill router can't be turned off in one
  project.
- Claude Code keys its record by the repository's main top folder, so a
  project in a subfolder turns its server offs on repo-wide.

Run (mote's SSH refused every try today, kex reset; every run went to
the WSL box through wsl-run, linux, at load 60 to 80 from other runs):
- go test -tags nogui ./internal/library: ok at this head. At the base
  before (4a9142ccd) TestEveryAgentInLibrary was red on main's own
  avibe/obsidian, fixed upstream since.
- go test -tags nogui ./internal/gateway ./internal/gui, one rebase back:
  gateway ok; gui ok but for TestSetAnswersWhileDevinAndProvidersHang
  (a set waited 37s; #1375, numbers added there). An earlier run had one
  TestMiddlewareThroughGateway red (the reply's first delta skipped a
  middleware's onEvent; nothing here touches middleware), 5 of 5 alone,
  filed as #5955.
- go vet: linux (-tags nogui) and windows clean; darwin (-tags nogui,
  cross from linux, no cgo) clean but for internal/gui's
  traywindows_darwin_test.go, which needs trayImagePNG from a
  darwin && cgo file, untouched here.
- gofmt -l: clean
- GUI, chromium + webkit: project-*, i18n-* and library-* 4 wide, then
  each red file alone at this head. Alone, all pass, project-scope
  included, but for library-mcp-copy-config ja chromium (#5941) and
  library-browser-setup (#5974); both are red the same way at origin/main
  without this change (40ca0c88d and 6bac8f8a5). library-all webkit
  (#4967) was red alone before the rebase, also at 40ca0c88d.

At 82a8acb09 (this change on 065ca02c2): go vet -tags nogui ./...
clean, ./internal/library ok, project-* and i18n-* GUI 32 of 32. Then rebased over b2b83d4f9's four commits (lessons,
gateway plugin models through a remote, a plugin hook test, agent auto
mode), none of them in a file this change touches.

Broken by hand, each red:
- Claude offs not written: TestProjectServerOff (no record)
- Codex offs not written: TestProjectServerOff (codex project config)
- hubServers ignoring a project's offs: TestProjectSetThroughRouter
- skill offs not written: TestProjectSkillOff
- worktrees not listed: TestProjectWorktreeFollows
- writeExclude a no-op: TestProjectServerOff, TestProjectKeptOutOfGitByExclude,
  TestProjectOutsideGit
- every chip click sent to the add path: project-scope.test.cjs

Not tried: a real Claude Code or Codex run in a project with an off (the
record and table shapes are read from Claude Code 2.1.316's and Codex's
config code, not watched working); darwin (mote down), Windows runs;
a real `git worktree add` (the test writes git's worktree files by hand).
2026-11-10 22:39:29 +08:00

222 lines
6.0 KiB
Go

package library
import (
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"github.com/yetone/magpie/internal/edit"
)
// A project in a git repository keeps what magpie places in it out of git
// through the repository's own info/exclude, which git reads beside the
// .gitignore and which is never committed (gitignore(5)): nothing of
// magpie's goes into the project's history, its .gitignore included. The
// file is shared by the repository's worktrees, each reading it against
// its own top folder, so one block of lines keeps a project's entries out
// of git in every worktree.
// gitWhere is where the project's repository is: Top, the worktree's top
// folder the project is in; Common, the repository's .git folder that
// every worktree shares (info/exclude, worktrees/).
type gitWhere struct {
Top, Common string
}
// gitOf is the repository dir is in, by the nearest .git above it: a
// folder (the main worktree's), or a file naming the worktree's own
// folder under the main .git (git worktree add), whose commondir names
// the shared one. ok is false outside a repository.
func gitOf(dir string) (gitWhere, bool) {
for d := dir; ; {
g := filepath.Join(d, ".git")
if fi, err := os.Stat(g); err == nil {
if fi.IsDir() {
return gitWhere{Top: d, Common: g}, true
}
if own, ok := gitdirOf(g); ok {
common := own
if b, err := os.ReadFile(filepath.Join(own, "commondir")); err == nil {
c := strings.TrimSpace(string(b))
if !filepath.IsAbs(c) {
c = filepath.Join(own, c)
}
common = filepath.Clean(c)
}
return gitWhere{Top: d, Common: common}, true
}
}
up := filepath.Dir(d)
if up == d {
return gitWhere{}, false
}
d = up
}
}
// gitdirOf is the folder a .git file names ("gitdir: <path>").
func gitdirOf(file string) (string, bool) {
b, err := os.ReadFile(file)
if err != nil {
return "", false
}
line, _, _ := strings.Cut(string(b), "\n")
g, ok := strings.CutPrefix(strings.TrimSpace(line), "gitdir:")
if !ok {
return "", false
}
g = strings.TrimSpace(g)
if !filepath.IsAbs(g) {
g = filepath.Join(filepath.Dir(file), g)
}
return filepath.Clean(g), true
}
// mainTop is the main worktree's top folder: the folder the shared .git is
// in. "" for a bare repository's worktrees, which have no main one.
func (g gitWhere) mainTop() string {
if filepath.Base(g.Common) != ".git" {
return ""
}
return filepath.Dir(g.Common)
}
// tops are the top folders of every worktree of the repository that is on
// disk, the main one first, as git lists them in <common>/worktrees/*/gitdir.
func (g gitWhere) tops() []string {
var out []string
if m := g.mainTop(); m != "" {
out = append(out, m)
}
es, _ := os.ReadDir(filepath.Join(g.Common, "worktrees"))
var more []string
for _, e := range es {
b, err := os.ReadFile(filepath.Join(g.Common, "worktrees", e.Name(), "gitdir"))
if err != nil {
continue
}
p := strings.TrimSpace(string(b))
if p == "" {
continue
}
if !filepath.IsAbs(p) {
p = filepath.Join(g.Common, "worktrees", e.Name(), p)
}
top := filepath.Dir(filepath.Clean(p))
if fi, err := os.Stat(top); err == nil && fi.IsDir() && !slices.Contains(out, top) && !slices.Contains(more, top) {
more = append(more, top)
}
}
sort.Strings(more)
return append(out, more...)
}
// treeDirs are the project's folder in each other worktree of its
// repository that has it: the same folder under each worktree's top.
func (p *Project) treeDirs() []string {
g, ok := gitOf(p.Dir)
if !ok {
return nil
}
rel, err := filepath.Rel(g.Top, p.Dir)
if err != nil {
return nil
}
var out []string
for _, top := range g.tops() {
if top == g.Top || realDir(top) == realDir(g.Top) {
continue
}
d := filepath.Join(top, rel)
if fi, err := os.Stat(d); err == nil && fi.IsDir() {
out = append(out, d)
}
}
return out
}
// projectKey is the short name a project is known to the router by: the
// hub's address for its agents ends in it (HubProjectSep).
func projectKey(dir string) string {
h := sha256.Sum256([]byte(filepath.Clean(dir)))
return hex.EncodeToString(h[:6])
}
// excludeBegin is the first of the lines magpie keeps a project's entries
// between in info/exclude, one block per project (several can share a
// repository); ignoreEnd ends it.
func excludeBegin(dir string) string {
return "# >>> magpie: library items placed in " + filepath.ToSlash(dir) + " (magpie adds and removes these lines) >>>"
}
// writeExclude keeps the repository's info/exclude listing the entries
// magpie placed in the project, relative to its worktree's top, between
// the project's two lines; every other line is git's or the user's.
func (p *Project) writeExclude(g gitWhere, entries []string) error {
f := filepath.Join(g.Common, "info", "exclude")
b, err := os.ReadFile(f)
if err != nil && !os.IsNotExist(err) {
return err
}
rel, err := filepath.Rel(g.Top, p.Dir)
if err != nil {
return err
}
pre := "/"
if rel = filepath.ToSlash(rel); rel != "." {
pre += rel + "/"
}
nl := "\n"
if strings.Contains(string(b), "\r\n") {
nl = "\r\n"
}
begin := excludeBegin(p.Dir)
rest := stripBlock(strings.ReplaceAll(string(b), "\r\n", "\n"), begin)
out := rest
if len(entries) > 0 {
sort.Strings(entries)
if out != "" {
out += "\n"
}
out += begin + "\n"
for _, e := range slices.Compact(entries) {
out += pre + e + "\n"
}
out += ignoreEnd + "\n"
}
out = strings.ReplaceAll(out, "\n", nl)
if out == string(b) {
return nil
}
if err := os.MkdirAll(filepath.Dir(f), 0o755); err != nil {
return err
}
return edit.WriteAtomic(f, []byte(out))
}
// stripBlock is s without the lines from begin to ignoreEnd, and the blank
// line left before them.
func stripBlock(s, begin string) string {
var out []string
in := false
for _, line := range strings.Split(s, "\n") {
switch t := strings.TrimSpace(line); {
case t == begin:
in = true
case in && t == ignoreEnd:
in = false
case !in:
out = append(out, line)
}
}
r := strings.TrimRight(strings.Join(out, "\n"), "\n")
if r != "" {
r += "\n"
}
return r
}