Files
magpie/internal/cli/library_project_cli.go
T
yetone ae94571d70 library: a project's own instructions, in the file each agent reads
@VictorHong1022 on X asked to manage AGENTS.md per project beside a
project's skills, so the shared instructions keep only general rules.

A project in the Library now has instructions of its own (the
Instructions tab, expand a project; `magpie library project
instructions <dir>`). magpie writes them into the project file each
picked agent reads there, by that agent's own name for it: Claude Code
CLAUDE.md (or .claude/CLAUDE.md when that is the one there), Codex and
pi their override first, Gemini GEMINI.md (or its context.fileName),
Qwen QWEN.md, CodeBuddy CODEBUDDY.md, the rest AGENTS.md. magpie owns
only a marked part (<!-- magpie:begin … --> to <!-- magpie:end -->):
the user's own text around it is kept byte for byte, CRLF included, a
hand edit of magpie's part stays until the project's text changes, a
file magpie made is listed in the repo's .git/info/exclude and removed
when emptied, and an agent's user-wide instructions file is refused.
Worktrees of the project follow it. A first text goes to the agents
the shared instructions are on for, else every agent here that reads a
project file. Problems show as the project's "instructions" problem.

Tested:
- internal/library: 8 new tests (block kept around user text, CRLF,
  hand edit kept, made file excluded and removed, renamed files,
  global file refused, worktrees). Four broken by hand, each red.
- internal/cli: TestLibraryProjectInstructionsCmd; red with the
  default agents dropped.
- GUI: project-instructions.test.cjs, en and zh, chromium and webkit,
  6 of 6. Red when Goose (no project file) was offered, and red when
  the defaults ignored the agents the instructions are on for.
- Real use on mote: the built binary, sandbox HOME and project. add,
  text, agents; CLAUDE.md kept CRLF with the part appended; AGENTS.md
  and GEMINI.md made and excluded; the user-wide CLAUDE.md untouched;
  zed refused; an edited part survived `library sync`; `agents none`
  put CLAUDE.md back byte for byte, removed the made files and
  emptied the exclude block.
- Full Go suite (go test ./... -timeout 45m) on mote: 103 packages ok,
  gofmt clean, go vet darwin, linux (nogui) and windows rc=0, at this
  change on origin/main 873b1f7d5.
- At dbb7230ae (rebased on d4af0ca4f), on mote: gofmt clean; go vet
  darwin, linux (nogui) and windows rc=0; go test internal/library,
  internal/cli, internal/gui and internal/testenv ok; node --test
  site/*.test.mjs 133 of 133. Not the whole Go suite again: of the
  commits that came in, only backup_cmd.go and main.go in internal/cli
  touch a package this change does, and its tests pass.
- The 89 Library GUI files (library-*, lib-*, project-*, skill-proj*,
  i18n-keys) at dbb7230ae on mote, both engines: 1868 of 1876. Red:
  library-open-again's 6 at 1100px, red alone at origin/main 28f27e07b
  too (#6751); library-new-skill's chromium en 420 timed out waiting for
  "taken" under the parallel run and passed alone at this head.
- Rebased again on 28f27e07b (three commits, one internal/cli test):
  go test internal/cli and internal/library ok on mote, and
  docs-index.mjs leaves the generated site files unchanged.
- Site: node docs-index.mjs regenerated llms-full, search and
  docs-index.sums at the rebased head; node --test site/*.test.mjs
  133 of 133.
- Full GUI suite (make test-ui, both engines) on mote at 873b1f7d5's
  rebase, beside other sessions' runs at load up to ~100: 28532 tests,
  1156 red in 133 files, none of them project-instructions. 115 files
  are #6975's, red at origin/main. Run alone at this change and at
  origin/main 8e1534f5f, the other 18 give the same result at both:
  16 green, name-suffix-remote red (#5147), library-env red. Recorded
  on #6975.

Not tried: a real Cursor, Copilot or Gemini session reading the files;
the library tests on Windows or Linux (cross vet only). Cursor and
Copilot read both CLAUDE.md and AGENTS.md, so picking Claude Code and
them together can show them the text twice.
2026-11-17 23:37:54 +08:00

577 lines
17 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cli
import (
"encoding/json"
"fmt"
"io"
"os"
"slices"
"sort"
"strings"
"github.com/yetone/magpie/internal/library"
)
const libraryProjectUsage = `magpie library project [--json] the projects (Library › Projects) and the skills each has
magpie library project add <dir> add a folder whose agents can be given library skills
magpie library project rm <dir> [--keep-files] take it off; --keep-files leaves what magpie put there, yours from then on
magpie library project skills <dir> [--json] its skills, for which agents, and where each is placed
magpie library project skill add <dir> <skill…> [agents=a,b…] give it skills: by default for the agents its skills
are for already, or, with none yet, every agent here that reads a project's skills
magpie library project skill rm <dir> <skill…> take skills out of it
magpie library project skill agents <dir> <skill> <a,b…|none> the agents it has the skill for
magpie library project copy <dir> on|off copies of its skills in place of links to the library's
magpie library project instructions <dir> [--json] its own instructions, the agents they're for and the files
magpie library project instructions <dir> text <text…>|--file <f>|- set them ("" takes them out); written, between
magpie's two marker lines, into the project file each agent reads: by default for
the agents the shared instructions are on for, else every agent here that reads one
magpie library project instructions <dir> agents <a,b…|none> the agents whose project file they're written into
<dir> may be relative, or "." for the folder you're in. A skill that couldn't be
placed (a folder there that isn't magpie's is left as it is) is named, and the
command exits with status 1.
`
// libraryProjectCmd is magpie library project …: the window's Library ›
// Projects page from a terminal (#5193), through the same library calls
// its page makes.
func libraryProjectCmd(args []string) error {
usage := func() error { return fmt.Errorf("usage:\n %s", libraryProjectUsage) }
if len(args) == 0 || len(args) == 1 && (args[0] == "list" || args[0] == "--json") || len(args) == 2 && args[0] == "list" && args[1] == "--json" {
return listProjects("", slices.Contains(args, "--json"))
}
switch sub, rest := args[0], args[1:]; sub {
case "help", "-h", "--help":
fmt.Print(" " + libraryProjectUsage)
return nil
case "add":
if len(rest) != 1 || strings.HasPrefix(rest[0], "-") {
return usage()
}
dir, err := library.ProjectPath(rest[0])
if err != nil {
return err
}
if _, err := library.AddProject(dir); err != nil {
return err
}
fmt.Println(green.Render("✓"), dir, "is a project")
fmt.Println(muted.Render(" magpie library project skill add " + quoteArg(dir) + " <skill…> gives it skills"))
return nil
case "rm", "remove":
keep := false
var dirs []string
for _, a := range rest {
switch {
case a == "--keep-files":
keep = true
case strings.HasPrefix(a, "-"):
return usage()
default:
dirs = append(dirs, a)
}
}
if len(dirs) != 1 {
return usage()
}
dir, err := projectDir(dirs[0])
if err != nil {
return err
}
if _, err := library.RemoveProject(dir, keep); err != nil {
return err
}
// what couldn't be taken out keeps the project listed
if p, _ := library.ProjectAt(dir); p != "" {
return fmt.Errorf("%s stays a project: magpie couldn't take everything it placed out of it (magpie library project skills %s)", dir, quoteArg(dir))
}
if keep {
fmt.Println(green.Render("✓"), dir, "is no project now; what magpie put there is left as it is")
} else {
fmt.Println(green.Render("✓"), dir, "is no project now; what magpie put there is taken out")
}
return nil
case "skills":
asJSON := slices.Contains(rest, "--json")
rest = slices.DeleteFunc(slices.Clone(rest), func(a string) bool { return a == "--json" })
if len(rest) != 1 || strings.HasPrefix(rest[0], "-") {
return usage()
}
dir, err := projectDir(rest[0])
if err != nil {
return err
}
return listProjects(dir, asJSON)
case "copy":
if len(rest) != 2 || strings.HasPrefix(rest[0], "-") || rest[1] != "on" && rest[1] != "off" {
return usage()
}
dir, err := projectDir(rest[0])
if err != nil {
return err
}
res, err := library.ProjectCopy(dir, rest[1] == "on")
if err != nil {
return err
}
if err := projectOutcome(dir, nil, res); err != nil {
return err
}
if rest[1] == "on" {
fmt.Println(green.Render("✓"), dir, "gets copies of its skills, made again whenever the library's skill changes")
} else {
fmt.Println(green.Render("✓"), dir, "gets links to the library's skills")
}
return nil
case "skill":
if len(rest) == 0 {
return usage()
}
return projectSkillCmd(rest[0], rest[1:], usage)
case "instructions", "instr":
return projectInstrCmd(rest, usage)
}
return fmt.Errorf("no library project command %q\n %s", args[0], libraryProjectUsage)
}
func projectSkillCmd(verb string, rest []string, usage func() error) error {
if len(rest) < 2 || strings.HasPrefix(rest[0], "-") {
return usage()
}
dir, err := projectDir(rest[0])
if err != nil {
return err
}
v, err := library.Read(nil)
if err != nil {
return err
}
p := projectView(v, dir)
if p == nil {
return fmt.Errorf("%s isn't a project", dir)
}
switch verb {
case "add":
var names, agents []string
given := false
for _, a := range rest[1:] {
if s, ok := strings.CutPrefix(a, "agents="); ok {
if agents, err = projectAgents(s); err != nil {
return err
}
given = true
continue
}
if strings.HasPrefix(a, "-") {
return usage()
}
names = addOnce(names, a)
}
if len(names) == 0 {
return usage()
}
if !given {
agents = defaultProjectAgents(v, p)
}
if len(agents) == 0 {
return fmt.Errorf("no agent here reads a project's skills: name them with agents=a,b…")
}
res, err := library.ProjectSkills(dir, names, agents)
if err != nil {
return err
}
return projectOutcome(dir, names, res)
case "rm", "remove":
var names []string
for _, a := range rest[1:] {
if strings.HasPrefix(a, "-") {
return usage()
}
if _, ok := p.Skills[a]; !ok {
return fmt.Errorf("%s has no skill %s", dir, a)
}
names = addOnce(names, a)
}
res, err := library.ProjectSkills(dir, names, nil)
if err != nil {
return err
}
if err := projectOutcome(dir, nil, res); err != nil {
return err
}
fmt.Println(green.Render("✓"), strings.Join(names, ", "), "taken out of", dir)
return nil
case "agents":
if len(rest) != 3 || strings.HasPrefix(rest[1], "-") || strings.HasPrefix(rest[2], "-") {
return usage()
}
agents, err := projectAgents(rest[2])
if err != nil {
return err
}
res, err := library.ProjectSkill(dir, rest[1], agents)
if err != nil {
return err
}
if len(agents) == 0 {
if err := projectOutcome(dir, nil, res); err != nil {
return err
}
fmt.Println(green.Render("✓"), rest[1], "taken out of", dir)
return nil
}
return projectOutcome(dir, []string{rest[1]}, res)
}
return fmt.Errorf("no library project skill command %q\n %s", verb, libraryProjectUsage)
}
// addOnce adds s to a list once, in the order given.
func addOnce(list []string, s string) []string {
if slices.Contains(list, s) {
return list
}
return append(list, s)
}
// projectDir is the listed folder of the project typed, or why there's none.
func projectDir(typed string) (string, error) {
dir, err := library.ProjectAt(typed)
if err != nil {
return "", err
}
if dir == "" {
abs, _ := library.ProjectPath(typed)
return "", fmt.Errorf("%s isn't a project: magpie library project add %s adds it", abs, quoteArg(abs))
}
return dir, nil
}
// projectAgents is a comma list of agents (none for no agent), each by its
// id, refused when magpie knows of no folder it reads a project's skills
// from.
func projectAgents(s string) ([]string, error) {
ids, err := libraryAgents(s, "skills")
if err != nil {
return nil, err
}
for _, id := range ids {
if library.ProjectSkillsDir(id) == "" {
return nil, fmt.Errorf("magpie knows of no folder %s reads a project's skills from", id)
}
}
return ids, nil
}
// defaultProjectAgents is who a skill added with no agents= is for, as on
// the page's Skills menu: the agents the project's skills are for already,
// or, in a project with none yet, every agent here that reads a project's
// skills.
func defaultProjectAgents(v *library.View, p *library.ProjectView) []string {
var all []string
for _, a := range v.Agents {
if a.ProjectSkills != "" && !a.Gone && !a.Unseen {
all = append(all, a.ID)
}
}
var used []string
for _, ids := range p.Skills {
for _, id := range ids {
if slices.Contains(all, id) && !slices.Contains(used, id) {
used = append(used, id)
}
}
}
if len(used) > 0 {
sort.Strings(used)
return used
}
var out []string
for _, a := range v.Agents {
if slices.Contains(all, a.ID) && a.Asleep == "" {
out = append(out, a.ID)
}
}
return out
}
func projectView(v *library.View, dir string) *library.ProjectView {
for i := range v.Projects {
if v.Projects[i].Dir == dir {
return &v.Projects[i]
}
}
return nil
}
// projectOutcome says, for each skill named, where it was placed or why
// it wasn't, and the project's own problem; one not placed is an error,
// for a script to tell "installed" from "left as it is" by the status.
func projectOutcome(dir string, names []string, res *library.Result) error {
v, err := library.Read(res.Problems)
if err != nil {
return err
}
p := projectView(v, dir)
if p == nil {
return fmt.Errorf("%s isn't a project", dir)
}
if why := p.Problems[""]; why != "" {
fmt.Println(amber.Render("!"), dir+":", why)
}
var unplaced []string
for _, n := range names {
placed, why := skillPlaces(p, n)
if why != "" {
unplaced = append(unplaced, n)
fmt.Println(amber.Render("!"), n, muted.Render("not placed:"), why)
continue
}
fmt.Println(green.Render("✓"), n, "→", strings.Join(p.Skills[n], ", "), muted.Render(strings.Join(placed, " ")))
}
if len(unplaced) > 0 {
return fmt.Errorf("%s not placed in %s", strings.Join(unplaced, ", "), dir)
}
return nil
}
// skillPlaces are the entries of a project's skill magpie placed, and,
// for one its agents should have and don't, why.
func skillPlaces(p *library.ProjectView, name string) (placed []string, why string) {
want := map[string]bool{}
for _, id := range p.Skills[name] {
if d := library.ProjectSkillsDir(id); d != "" {
want[d+"/"+name] = true
}
}
for e := range want {
if slices.Contains(p.Placed, e) {
placed = append(placed, e)
}
}
sort.Strings(placed)
if why = p.Problems[name]; why == "" && len(placed) < len(want) {
why = "not in the project (magpie library sync says why)"
}
return placed, why
}
// listProjects prints the projects, or one, with their skills.
func listProjects(dir string, asJSON bool) error {
v, err := library.Read(nil)
if err != nil {
return err
}
ps := v.Projects
if dir != "" {
p := projectView(v, dir)
if p == nil {
return fmt.Errorf("%s isn't a project", dir)
}
ps = []library.ProjectView{*p}
}
if asJSON {
e := json.NewEncoder(os.Stdout)
e.SetIndent("", " ")
if dir != "" {
return e.Encode(ps[0])
}
return e.Encode(ps)
}
if len(ps) == 0 {
fmt.Println(muted.Render("No projects yet · magpie library project add <dir>"))
return nil
}
for _, p := range ps {
head := bold.Render(p.Name) + " " + muted.Render(p.Dir)
if p.Missing {
head += " " + amber.Render("(the folder is gone)")
} else if p.Copy {
head += " " + muted.Render("(copies)")
}
fmt.Println(head)
names := make([]string, 0, len(p.Skills))
for n := range p.Skills {
names = append(names, n)
}
sort.Strings(names)
if len(names) == 0 {
fmt.Println(" ", muted.Render("no skills yet · magpie library project skill add "+quoteArg(p.Dir)+" <skill…>"))
}
for _, n := range names {
placed, why := skillPlaces(&p, n)
if why != "" {
fmt.Printf(" %s %s → %s %s\n", amber.Render("!"), bold.Render(n), strings.Join(p.Skills[n], ", "), muted.Render(why))
continue
}
fmt.Printf(" %s → %s %s\n", bold.Render(n), strings.Join(p.Skills[n], ", "), muted.Render(strings.Join(placed, " ")))
}
}
return nil
}
// quoteArg is a path as a shell takes it back.
func quoteArg(s string) string {
if s != "" && !strings.ContainsAny(s, " \t'\"$`\\!*?[]{}()&;|<>#~") {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// projectInstrCmd is magpie library project instructions …: the project's
// own instructions, as the Instructions page's project card sets them.
func projectInstrCmd(rest []string, usage func() error) error {
asJSON := slices.Contains(rest, "--json")
rest = slices.DeleteFunc(slices.Clone(rest), func(a string) bool { return a == "--json" })
if len(rest) == 0 || strings.HasPrefix(rest[0], "-") {
return usage()
}
dir, err := projectDir(rest[0])
if err != nil {
return err
}
if len(rest) == 1 {
return showProjectInstr(dir, asJSON)
}
var c library.ProjectInstr
switch rest[1] {
case "text":
var text string
switch args := rest[2:]; {
case len(args) == 1 && args[0] == "-":
b, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
text = string(b)
case len(args) == 2 && args[0] == "--file":
b, err := os.ReadFile(args[1])
if err != nil {
return err
}
text = string(b)
case len(args) > 0 && !strings.HasPrefix(args[0], "-"):
text = strings.Join(args, " ")
default:
return usage()
}
c.Text = &text
// the first text a project gets goes to the agents the shared
// instructions are on for, as the page's card does it
v, err := library.Read(nil)
if err != nil {
return err
}
if p := projectView(v, dir); p != nil && len(p.InstrAgents) == 0 && strings.TrimSpace(text) != "" {
ids := defaultInstrAgents(v)
if len(ids) == 0 {
return fmt.Errorf("no agent here reads a project's instructions file magpie knows of")
}
c.Agents = &ids
}
case "agents":
if len(rest) != 3 {
return usage()
}
ids, err := projectInstrAgents(rest[2])
if err != nil {
return err
}
c.Agents = &ids
default:
return usage()
}
res, err := library.ProjectInstructions(dir, c)
if err != nil {
return err
}
v, err := library.Read(res.Problems)
if err != nil {
return err
}
p := projectView(v, dir)
if p == nil {
return fmt.Errorf("%s isn't a project", dir)
}
if why := p.Problems["instructions"]; why != "" {
return fmt.Errorf("%s: %s", dir, why)
}
if p.Instr == "" || len(p.InstrAgents) == 0 {
fmt.Println(green.Render("✓"), dir, "has no instructions of its own in its files now")
return nil
}
fmt.Println(green.Render("✓"), dir, "→", strings.Join(p.InstrAgents, ", "), muted.Render(strings.Join(p.InstrFiles, " ")))
return nil
}
func showProjectInstr(dir string, asJSON bool) error {
v, err := library.Read(nil)
if err != nil {
return err
}
p := projectView(v, dir)
if p == nil {
return fmt.Errorf("%s isn't a project", dir)
}
if asJSON {
e := json.NewEncoder(os.Stdout)
e.SetIndent("", " ")
return e.Encode(map[string]any{"dir": p.Dir, "text": p.Instr, "agents": p.InstrAgents, "files": p.InstrFiles})
}
if p.Instr == "" {
fmt.Println(muted.Render("No instructions of its own · magpie library project instructions " + quoteArg(dir) + " text <text…>"))
return nil
}
if len(p.InstrAgents) == 0 {
fmt.Println(muted.Render("for no agent · magpie library project instructions " + quoteArg(dir) + " agents <a,b…>"))
} else {
fmt.Println(bold.Render(strings.Join(p.InstrAgents, ", ")), muted.Render(strings.Join(p.InstrFiles, " ")))
}
if why := p.Problems["instructions"]; why != "" {
fmt.Println(amber.Render("!"), why)
}
fmt.Println(p.Instr)
return nil
}
// projectInstrAgents is a comma list of agents (none for no agent), each
// by its id or name, refused when magpie knows of no file it reads a
// project's instructions from.
func projectInstrAgents(s string) ([]string, error) {
out := []string{}
for _, a := range agentList(s) {
id := strings.ToLower(a)
if library.ProjectInstrFile(id) == "" {
if t, err := library.Takes(a, "skills"); err == nil {
id = t
}
}
if library.ProjectInstrFile(id) == "" {
return nil, fmt.Errorf("magpie knows of no file %s reads a project's instructions from", a)
}
out = addOnce(out, id)
}
return out, nil
}
// defaultInstrAgents is who a project's first instructions are for: the
// agents here that read a project's instructions and have the shared ones
// on, else every one of them here.
func defaultInstrAgents(v *library.View) []string {
var all, on []string
for _, a := range v.Agents {
if a.ProjectInstructions != "" && !a.Gone && !a.Unseen && a.Asleep == "" {
all = append(all, a.ID)
}
}
if v.Instructions != nil {
for _, a := range v.Instructions.Agents {
if a.On && slices.Contains(all, a.Agent) {
on = append(on, a.Agent)
}
}
}
if len(on) > 0 {
return on
}
return all
}