Files
magpie/internal/cli/library_project_test.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

281 lines
9.4 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"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/yetone/magpie/internal/agentenv"
"github.com/yetone/magpie/internal/library"
"github.com/yetone/magpie/internal/testenv"
)
// projectSandbox is a sandbox HOME with Claude Code and Codex installed,
// a library with the skills pdf, docx and xlsx given to no agent, and a
// project folder app, the folder the test runs in.
func projectSandbox(t *testing.T) (proj string) {
t.Helper()
h := t.TempDir()
for k, v := range map[string]string{"HOME": h, "USERPROFILE": h, "XDG_CONFIG_HOME": filepath.Join(h, ".config"), "XDG_STATE_HOME": "", "APPDATA": "", "LOCALAPPDATA": "", "PATH": filepath.Join(h, "bin")} {
t.Setenv(k, v)
}
for _, k := range agentenv.Vars {
t.Setenv(k, "")
}
put := func(p, s string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(s), 0o644); err != nil {
t.Fatal(err)
}
}
for _, n := range []string{"claude", "codex"} {
testenv.Program(t, filepath.Join(h, "bin", n), "#!/bin/sh\n")
put(filepath.Join(h, "bin", n+".exe"), "")
}
put(filepath.Join(h, ".claude/settings.json"), "")
put(filepath.Join(h, ".codex/config.toml"), "")
src := filepath.Join(h, "src")
for _, n := range []string{"pdf", "docx", "xlsx"} {
put(filepath.Join(src, n, "SKILL.md"), "---\nname: "+n+"\ndescription: "+n+"\n---\n")
}
if _, err := library.InstallSkills(src, []string{"pdf", "docx", "xlsx"}, []string{}); err != nil {
t.Fatal(err)
}
work := t.TempDir()
proj = filepath.Join(work, "app")
put(filepath.Join(proj, ".gitignore"), "node_modules/\n")
if p, err := filepath.EvalSymlinks(proj); err == nil {
proj = p
}
t.Chdir(proj)
return proj
}
func projectOut(t *testing.T, args ...string) (string, error) {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stdout
os.Stdout = w
done := make(chan string)
go func() { b, _ := io.ReadAll(r); done <- string(b) }()
err = libraryCmd(append([]string{"library", "project"}, args...))
w.Close()
os.Stdout = old
out := <-done
r.Close()
return out, err
}
func linkTo(t *testing.T, p, name string) bool {
t.Helper()
if _, err := os.Stat(filepath.Join(p, "SKILL.md")); err != nil {
return false
}
if runtime.GOOS == "windows" {
return true // a junction, or a copy where none can be made
}
target, err := os.Readlink(p)
return err == nil && filepath.Base(target) == name
}
// magpie library project … (#5193, Sephiro_Lan on X): a folder added, given
// skills, a skill's agents changed and the skills taken away from a
// terminal, written as the window's Library › Projects page writes them:
// links in the folders the agents read, the project's .gitignore left as
// it is.
func TestLibraryProjectCmd(t *testing.T) {
proj := projectSandbox(t)
must := func(args ...string) string {
t.Helper()
out, err := projectOut(t, args...)
if err != nil {
t.Fatalf("library project %v: %v\n%s", args, err, out)
}
return out
}
refused := func(args ...string) {
t.Helper()
if out, err := projectOut(t, args...); err == nil {
t.Errorf("library project %v was taken:\n%s", args, out)
}
}
refused("skill", "add", ".", "pdf") // not a project yet
must("add", ".")
refused("add", ".") // a project already
refused("add", proj, "--force") // an unknown flag
refused("add", "--force") // not a folder
refused("nope") // an unknown command
refused("skill", "nope", ".", "pdf")
if out := must(); !strings.Contains(out, "app") || !strings.Contains(out, "no skills yet") {
t.Errorf("list:\n%s", out)
}
// with no agents=, every agent here that reads a project's skills
must("skill", "add", ".", "pdf", "docx")
for _, e := range []string{".claude/skills/pdf", ".agents/skills/pdf", ".claude/skills/docx", ".agents/skills/docx"} {
if !linkTo(t, filepath.Join(proj, e), filepath.Base(e)) {
t.Errorf("%s isn't a link to the library's", e)
}
}
if b, _ := os.ReadFile(filepath.Join(proj, ".gitignore")); string(b) != "node_modules/\n" {
t.Errorf(".gitignore:\n%s", b)
}
refused("skill", "add", ".", "nope") // no such skill
refused("skill", "add", ".", "xlsx", "agents=zz") // no such agent
refused("skill", "add", ".", "xlsx", "--yes") // an unknown flag
// a folder there that isn't magpie's is left as it is, and said
own := filepath.Join(proj, ".claude/skills/xlsx")
if err := os.MkdirAll(own, 0o755); err != nil {
t.Fatal(err)
}
out, err := projectOut(t, "skill", "add", ".", "xlsx", "agents=claude")
if err == nil || !strings.Contains(out, "xlsx") || !strings.Contains(out, "isn't magpie's") {
t.Errorf("a folder of the user's in the way: %v\n%s", err, out)
}
if fi, err := os.Lstat(own); err != nil || !fi.IsDir() {
t.Errorf("the user's folder was touched: %v", err)
}
// the same as the page's chips: codex alone
must("skill", "agents", ".", "pdf", "codex")
if _, err := os.Lstat(filepath.Join(proj, ".claude/skills/pdf")); !os.IsNotExist(err) {
t.Errorf(".claude/skills/pdf is still there: %v", err)
}
var v library.ProjectView
if err := json.Unmarshal([]byte(must("skills", ".", "--json")), &v); err != nil {
t.Fatal(err)
}
if strings.Join(v.Skills["pdf"], ",") != "codex" || strings.Join(v.Skills["docx"], ",") != "claude,codex" {
t.Errorf("skills: %+v", v.Skills)
}
refused("skill", "rm", ".", "nope") // not the project's
must("skill", "rm", ".", "pdf", "docx", "xlsx")
for _, e := range []string{".agents", ".claude/skills/pdf", ".claude/skills/docx"} {
if _, err := os.Lstat(filepath.Join(proj, e)); !os.IsNotExist(err) {
t.Errorf("%s is still there: %v", e, err)
}
}
if fi, err := os.Lstat(own); err != nil || !fi.IsDir() {
t.Errorf("the user's folder was taken: %v", err)
}
// copies in place of links
must("copy", ".", "on")
must("skill", "add", ".", "pdf", "agents=codex")
if fi, err := os.Lstat(filepath.Join(proj, ".agents/skills/pdf")); err != nil || !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
t.Errorf("not a copy: %v", err)
}
refused("copy", ".", "maybe")
must("rm", ".")
if _, err := os.Lstat(filepath.Join(proj, ".agents")); !os.IsNotExist(err) {
t.Errorf(".agents is still there: %v", err)
}
if b, _ := os.ReadFile(filepath.Join(proj, ".gitignore")); string(b) != "node_modules/\n" {
t.Errorf(".gitignore after: %q", b)
}
refused("rm", ".")
}
// --keep-files takes the project off the list and leaves what magpie
// placed there, as the page's "keep its skills" box does.
func TestLibraryProjectRmKeep(t *testing.T) {
proj := projectSandbox(t)
for _, args := range [][]string{{"add", proj}, {"skill", "add", proj, "pdf", "agents=claude"}, {"rm", proj, "--keep-files"}} {
if out, err := projectOut(t, args...); err != nil {
t.Fatalf("%v: %v\n%s", args, err, out)
}
}
if !linkTo(t, filepath.Join(proj, ".claude/skills/pdf"), "pdf") {
t.Error("--keep-files took the skill out")
}
if dir, _ := library.ProjectAt(proj); dir != "" {
t.Error("still a project")
}
}
func TestLibraryProjectHelp(t *testing.T) {
for _, args := range [][]string{{"library", "project", "--help"}, {"library", "projects", "-h"}} {
if !helpAsked(args) || !strings.Contains(helpFor(args), "project skill add <dir>") {
t.Errorf("%v: %q", args, helpFor(args))
}
}
if !strings.Contains(helpFor([]string{"library", "--help"}), "magpie library project") {
t.Error("library's usage doesn't name project")
}
}
// magpie library project instructions … (VictorHong1022 on X): a
// project's own instructions set from a terminal go, between magpie's two
// lines, into the file each agent reads in the project, the user's own
// text there untouched, first to every agent here that reads one (the
// shared instructions are on for none); an agent with no such file is
// refused, and none takes them out.
func TestLibraryProjectInstructionsCmd(t *testing.T) {
proj := projectSandbox(t)
must := func(args ...string) string {
t.Helper()
out, err := projectOut(t, args...)
if err != nil {
t.Fatalf("library project %v: %v\n%s", args, err, out)
}
return out
}
read := func(rel string) string {
t.Helper()
b, err := os.ReadFile(filepath.Join(proj, rel))
if err != nil {
t.Fatalf("%s: %v", rel, err)
}
return string(b)
}
if err := os.WriteFile(filepath.Join(proj, "CLAUDE.md"), []byte("Mine.\n"), 0o644); err != nil {
t.Fatal(err)
}
must("add", ".")
if out := must("instructions", "."); !strings.Contains(out, "No instructions") {
t.Errorf("show:\n%s", out)
}
must("instructions", ".", "text", "Use", "pnpm", "here.")
part := "<!-- magpie:begin · written by magpie from its Library -->\nUse pnpm here.\n<!-- magpie:end -->\n"
if got := read("CLAUDE.md"); got != "Mine.\n\n"+part {
t.Errorf("CLAUDE.md = %q", got)
}
if got := read("AGENTS.md"); got != part {
t.Errorf("AGENTS.md = %q", got)
}
var v struct {
Agents []string `json:"agents"`
Files []string `json:"files"`
}
if err := json.Unmarshal([]byte(must("instructions", ".", "--json")), &v); err != nil {
t.Fatal(err)
}
if strings.Join(v.Agents, ",") != "claude,codex" || strings.Join(v.Files, ",") != "AGENTS.md,CLAUDE.md" {
t.Errorf("--json: %+v", v)
}
if out, err := projectOut(t, "instructions", ".", "agents", "zed"); err == nil {
t.Errorf("zed was taken:\n%s", out)
}
must("instructions", ".", "agents", "none")
if got := read("CLAUDE.md"); got != "Mine.\n" {
t.Errorf("CLAUDE.md after none = %q", got)
}
if _, err := os.Stat(filepath.Join(proj, "AGENTS.md")); !os.IsNotExist(err) {
t.Errorf("AGENTS.md is still there: %v", err)
}
}