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.
This commit is contained in:
yetone
2026-11-17 23:37:54 +08:00
parent 28f27e07b7
commit ae94571d70
20 changed files with 1116 additions and 24 deletions
File diff suppressed because one or more lines are too long
+167
View File
@@ -3,6 +3,7 @@ package cli
import (
"encoding/json"
"fmt"
"io"
"os"
"slices"
"sort"
@@ -20,6 +21,11 @@ const libraryProjectUsage = `magpie library project [--json] the projects (
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.
@@ -121,6 +127,8 @@ func libraryProjectCmd(args []string) error {
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)
}
@@ -407,3 +415,162 @@ func quoteArg(s string) string {
}
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
}
+61
View File
@@ -217,3 +217,64 @@ func TestLibraryProjectHelp(t *testing.T) {
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)
}
}
+91 -11
View File
@@ -23,6 +23,7 @@ magpie.plugin("library", (ctx) => {
let addingSet = false; // a new set being named
let removingSet = null; // a set whose Remove was clicked once
const extras = {}; // agent → its own additions as typed, while not saved
const projTexts = {}; // project dir → its own instructions as typed, while not saved
const open = new Set(); // agents whose instructions row is open
let probe = null; // skills found at a source: { source, candidates, pick:Set, agents:Set }
let probing = false;
@@ -2459,8 +2460,11 @@ magpie.plugin("library", (ctx) => {
for (const [id, v] of Object.entries(texts)) if (setOf(id) && v !== setOf(id).text) out[id] = v;
return out;
}
function unsavedProjects() {
return Object.entries(projTexts).filter(([dir, v]) => { const p = lib.projects.find((x) => x.dir === dir); return p && v !== (p.instr || ""); });
}
function dirty() {
if (Object.keys(unsavedTexts()).length) return true;
if (Object.keys(unsavedTexts()).length || unsavedProjects().length) return true;
return Object.entries(extras).some(([id, v]) => v !== (lib.instructions.agents.find((a) => a.agent === id)?.extra || ""));
}
@@ -2471,18 +2475,33 @@ magpie.plugin("library", (ctx) => {
const ex = {};
for (const [id, v] of Object.entries(extras)) if (v !== (lib.instructions.agents.find((a) => a.agent === id)?.extra || "")) ex[id] = v;
if (Object.keys(ex).length) c.extra = ex;
if (!Object.keys(c).length) return;
if (await change("instructions/save", c)) {
const projs = unsavedProjects();
if (!Object.keys(c).length && !projs.length) return;
if (Object.keys(c).length && await change("instructions/save", c)) {
for (const k of Object.keys(texts)) delete texts[k];
for (const k of Object.keys(extras)) delete extras[k];
render();
}
// a project's own: its first text goes to the agents the shared
// instructions are on for, as a project's first skill does
for (const [dir, v] of projs) {
const p = lib.projects.find((x) => x.dir === dir);
if (!p) continue;
const body = { dir, instr: v };
let agents = p.instrAgents || [];
if (!agents.length && v.trim()) agents = body.agents = projectInstrDefaults();
const done = !v.trim() ? t("{name}'s instructions are taken out of its files", { name: p.name })
: agents.length ? t("{name}'s instructions are in its files for {agents}", { name: p.name, agents: agents.map(nameOf).join(", ") })
: t("{name}'s instructions are saved — pick the agents that read them", { name: p.name });
if (await change("projects/instructions", body, done)) { delete projTexts[dir]; render(); }
}
}
async function discard(force = false) {
if (force !== true && dirty() && !(await confirmDiscard())) return;
if (force === true) { memOpen = null; memDraft = null; }
for (const k of Object.keys(texts)) delete texts[k];
for (const k of Object.keys(extras)) delete extras[k];
for (const k of Object.keys(projTexts)) delete projTexts[k];
render();
}
@@ -2527,6 +2546,9 @@ magpie.plugin("library", (ctx) => {
const skip = shownAgents().filter((a) => !a.instructions && !a.asleep);
if (skip.length) body.append(el("p", "lib-aside", t(skip.length > 1 ? "{agents} keep no user-wide instructions file." : "{agents} keeps no user-wide instructions file.", { agents: skip.map((a) => a.name).join(", ") })));
body.append(...asleepAsides(rows.filter((a) => a.asleep)));
// a project's own, so the shared ones keep what holds everywhere
// (VictorHong1022 on X), as a project has skills of its own
if (!agentless()) renderProjects(body, "instructions");
body.append(bar);
}
@@ -6715,12 +6737,14 @@ magpie.plugin("library", (ctx) => {
function renderProjects(body, kind) {
const rh = el("div", "row-head");
rh.append(el("span", "label", kind === "skills" ? t("Project skills") : kind === "subagents" ? t("Project subagents") : t("Project servers")), el("span", "grow"));
rh.append(el("span", "label", kind === "skills" ? t("Project skills") : kind === "subagents" ? t("Project subagents") : kind === "instructions" ? t("Project instructions") : t("Project servers")), el("span", "grow"));
if (!addingProject) rh.append(button(t("Add a project"), "action lib-updall", () => { addingProject = { dir: "" }; render(); }));
body.append(rh);
if (addingProject) body.append(addProjectCard(kind));
if (!lib.projects.length && !addingProject) {
body.append(el("p", "lib-aside", kind === "subagents"
body.append(el("p", "lib-aside", kind === "instructions"
? t("Give a project instructions of its own: magpie writes them into the AGENTS.md, CLAUDE.md or the like each agent reads there, leaving the rest of each file as it is.")
: kind === "subagents"
? t("Give a project's agents some of these subagents as the project's own: magpie writes them into its .claude/agents and the like, and keeps them out of git.")
: kind === "mcp"
? t("Give a project's agents some of these servers as the project's own: magpie writes them into its {files}, leaving the rest of each file as it is.", { files: projectFiles() })
@@ -6769,7 +6793,7 @@ magpie.plugin("library", (ctx) => {
addingProject = null;
const p = lib.projects.find((x) => !was.has(x.dir));
if (p) openProjects.add(p.dir);
status(kind === "subagents" ? t("{name} added — pick the subagents it gets", { name: p?.name || dir }) : kind === "mcp" ? t("{name} added — pick the servers it gets", { name: p?.name || dir }) : t("{name} added — pick the skills it gets", { name: p?.name || dir }), "ok");
status(kind === "instructions" ? t("{name} added — write its instructions", { name: p?.name || dir }) : kind === "subagents" ? t("{name} added — pick the subagents it gets", { name: p?.name || dir }) : kind === "mcp" ? t("{name} added — pick the servers it gets", { name: p?.name || dir }) : t("{name} added — pick the skills it gets", { name: p?.name || dir }), "ok");
} catch (e) {
a.busy = false;
a.error = e.message;
@@ -6780,21 +6804,29 @@ magpie.plugin("library", (ctx) => {
}
function projectCard(p, kind) {
const mcp = kind === "mcp", sub = kind === "subagents";
const mcp = kind === "mcp", sub = kind === "subagents", ins = kind === "instructions";
const card = el("div", "list lib-card lib-project" + (p.missing ? " missing" : ""));
const isOpen = openProjects.has(p.dir);
const head = el("div", "row lib-row click lib-projhead" + (isOpen ? " open" : ""));
const who = el("div", "who");
const nm = el("div", "name", p.name);
if (p.missing) nm.append(tag(t("Folder is gone"), "warn"));
else if (p.copy && !mcp && !sub) nm.append(tag(t("Copies"), ""));
else if (p.copy && !mcp && !sub && !ins) nm.append(tag(t("Copies"), ""));
who.append(nm);
const src = el("div", "lib-src");
src.append(pathLink(p.dir));
who.append(src);
const names = Object.keys((sub ? p.subagents : mcp ? p.servers : p.skills) || {}).sort();
const pills = el("div", "lib-tags");
if (!isOpen) {
if (!isOpen && ins) {
const first = (projTexts[p.dir] ?? p.instr ?? "").split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "") || "";
if (!first) pills.append(tag(t("No instructions yet"), "lib-unchecked"));
else {
pills.append(tag(first.length > 40 ? first.slice(0, 39) + "…" : first, "lib-dot"));
if (!(p.instrAgents || []).length) pills.append(tag(t("For no agent"), "lib-unchecked"));
if (projTexts[p.dir] !== undefined && projTexts[p.dir] !== (p.instr || "")) pills.append(tag(t("Not saved yet"), "warn"));
}
} else if (!isOpen) {
for (const n of names.slice(0, 4)) pills.append(tag(n, "lib-dot"));
if (names.length > 4) pills.append(tag("+" + (names.length - 4), ""));
if (!names.length) pills.append(tag(sub ? t("No subagents yet") : mcp ? t("No servers yet") : t("No skills yet"), "lib-unchecked"));
@@ -6808,12 +6840,13 @@ magpie.plugin("library", (ctx) => {
chev.append(svg(CHEV_R, 11, 1.7));
head.append(glyph(GLYPH.folder), who, pills, acts, chev);
head.onclick = () => { isOpen ? openProjects.delete(p.dir) : openProjects.add(p.dir); projectShown.delete(p.dir); render(); };
head.title = sub ? (isOpen ? t("Hide its subagents") : t("Pick the subagents it gets")) : mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets");
head.title = ins ? (isOpen ? t("Hide its instructions") : t("Write its instructions")) : sub ? (isOpen ? t("Hide its subagents") : t("Pick the subagents it gets")) : mcp ? (isOpen ? t("Hide its servers") : t("Pick the servers it gets")) : isOpen ? t("Hide its skills") : t("Pick the skills it gets");
card.append(head);
if (p.problems?.[""]) card.append(el("div", "lib-err", p.problems[""]));
if (!isOpen) return card;
if (mcp) return projectServers(p, card);
if (sub) return projectSubagents(p, card);
if (ins) return projectInstructions(p, card);
const opts = el("div", "lib-projopts");
const copy = toggle(p.copy, t("Copy files instead of linking"), (on) =>
@@ -7039,6 +7072,53 @@ magpie.plugin("library", (ctx) => {
return card;
}
// The agents a project's first instructions are for: those here that
// read a project's instructions file and have the shared ones on, else
// every one of them here.
function projectInstrDefaults() {
const all = shownAgents().filter((a) => a.projectInstructions && !a.gone && !a.unseen && !a.asleep);
const on = all.filter((a) => (lib.instructions?.agents || []).some((x) => x.agent === a.id && x.on));
return (on.length ? on : all).map((a) => a.id);
}
// The project's card, open on the Instructions tab: its own text, saved
// with the page's Save, and the chips of the agents whose project file
// it is written into.
function projectInstructions(p, card) {
const det = el("div", "lib-detail lib-projinstr");
det.dataset.detail = "proj:" + p.dir;
const problem = p.problems?.instructions;
if (problem) det.append(el("div", "lib-err", problem));
const ta = el("textarea", "lib-text small");
ta.dataset.lib = "projinstr:" + p.dir;
ta.spellcheck = false;
ta.value = projTexts[p.dir] ?? p.instr ?? "";
ta.placeholder = t("What only this project needs — its stack, how to run its tests, what not to touch…");
ta.oninput = () => { projTexts[p.dir] = ta.value; renderSaveBars(); };
ta.onkeydown = (e) => { e.stopPropagation(); if ((e.metaKey || e.ctrlKey) && e.key === "s") { e.preventDefault(); saveInstructions(); } };
autosize(ta, 110);
det.append(ta);
const all = shownAgents().filter((a) => a.projectInstructions);
const on = (p.instrAgents || []).filter((id) => all.some((a) => a.id === id));
// an agent reading the same file as one that has them has them too
const via = (a) => { const o = on.find((id) => agentOf(id)?.projectInstructions === a.projectInstructions); return o ? nameOf(o) : ""; };
const say = (next) => next.length
? t("{name}'s instructions are in its files for {agents}", { name: p.name, agents: next.map(nameOf).join(", ") })
: t("{name}'s instructions are taken out of its files", { name: p.name });
const row = el("div", "row lib-row lib-projskill lib-projinstr-agents");
const w = el("div", "who");
const files = p.instrFiles?.length ? p.instrFiles : [...new Set(all.filter((a) => on.includes(a.id)).map((a) => a.projectInstructions))];
w.append(el("div", "sub", files.join(", ")));
row.append(w, agentChips(all, on, projectChange("projects/instructions", p.dir, "", say), { via }));
det.append(row);
det.onclick = (e) => e.stopPropagation();
card.append(det);
card.append(el("p", "lib-aside lib-projfoot", t("Written between two marker lines in the file each agent reads in the project — the rest of the file stays yours. A file magpie makes is kept out of git, its .gitignore untouched.")));
const skip = shownAgents().filter((a) => a.instructions && !a.projectInstructions);
if (skip.length) card.append(el("p", "lib-aside lib-projfoot", t("{agents} reads no project instructions file magpie knows of.", { agents: skip.map((a) => a.name).join(", ") })));
return card;
}
function confirmRemoveProject(p) {
const ed = el("div", "editor lib-editor");
const head = el("div", "ehead");
@@ -7048,7 +7128,7 @@ magpie.plugin("library", (ctx) => {
ed.append(say);
// #514: skills or servers given to a project once are often to stay
// there; magpie can forget the project and leave them as they are
const has = p.placed?.length || Object.values(p.wrote || {}).some((x) => x.length);
const has = p.placed?.length || p.instrFiles?.length || Object.values(p.wrote || {}).some((x) => x.length);
const keep = el("input");
keep.type = "checkbox";
const tell = () => {
@@ -1081,6 +1081,19 @@ magpie.strings({
"It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "它会连同技能、MCP 服务器、hooks 和子代理一起从资源库移除,也会从它们所在的智能体中取出。",
"Open the plugin {name}": "打开插件 {name}",
"{name} read again from its source": "已重新从来源读取 {name}",
"Project instructions": "项目指令",
"Give a project instructions of its own: magpie writes them into the AGENTS.md, CLAUDE.md or the like each agent reads there, leaving the rest of each file as it is.": "给项目单独的指令:magpie 把它写进每个智能体在项目里读取的 AGENTS.md、CLAUDE.md 等文件,文件里的其他内容保持不变。",
"{name} added — write its instructions": "已添加 {name} — 写下它的指令",
"No instructions yet": "还没有指令",
"For no agent": "未给任何智能体",
"Hide its instructions": "收起指令",
"Write its instructions": "编写它的指令",
"{name}'s instructions are taken out of its files": "已从 {name} 的文件中取出它的指令",
"{name}'s instructions are in its files for {agents}": "{name} 的指令已写入 {agents} 读取的文件",
"{name}'s instructions are saved — pick the agents that read them": "已保存 {name} 的指令 — 选择读取它们的智能体",
"What only this project needs — its stack, how to run its tests, what not to touch…": "只有这个项目需要的 — 技术栈、怎么跑测试、哪些不要动…",
"Written between two marker lines in the file each agent reads in the project — the rest of the file stays yours. A file magpie makes is kept out of git, its .gitignore untouched.": "写在每个智能体在项目里读取的文件的两行标记之间 — 文件其余部分仍归你。magpie 新建的文件不会进入 git,.gitignore 不会被改动。",
"{agents} reads no project instructions file magpie knows of.": "{agents} 没有 magpie 已知的项目指令文件。",
},
"zh-TW": {
"Put back in {agents}": "放回 {agents}",
@@ -2162,6 +2175,19 @@ magpie.strings({
"It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "它會連同技能、MCP 伺服器、hooks 和子代理一起從資源庫移除,也會從它們所在的代理中取出。",
"Open the plugin {name}": "開啟外掛 {name}",
"{name} read again from its source": "已重新從來源讀取 {name}",
"Project instructions": "專案指令",
"Give a project instructions of its own: magpie writes them into the AGENTS.md, CLAUDE.md or the like each agent reads there, leaving the rest of each file as it is.": "給專案獨立的指令:magpie 把它寫進每個智能體在專案裡讀取的 AGENTS.md、CLAUDE.md 等檔案,檔案裡的其他內容保持不變。",
"{name} added — write its instructions": "已新增 {name} — 寫下它的指令",
"No instructions yet": "還沒有指令",
"For no agent": "未給任何智能體",
"Hide its instructions": "收起指令",
"Write its instructions": "編寫它的指令",
"{name}'s instructions are taken out of its files": "已從 {name} 的檔案中取出它的指令",
"{name}'s instructions are in its files for {agents}": "{name} 的指令已寫入 {agents} 讀取的檔案",
"{name}'s instructions are saved — pick the agents that read them": "已儲存 {name} 的指令 — 選擇讀取它們的智能體",
"What only this project needs — its stack, how to run its tests, what not to touch…": "只有這個專案需要的 — 技術棧、怎麼跑測試、哪些不要動…",
"Written between two marker lines in the file each agent reads in the project — the rest of the file stays yours. A file magpie makes is kept out of git, its .gitignore untouched.": "寫在每個智能體在專案裡讀取的檔案的兩行標記之間 — 檔案其餘部分仍歸你。magpie 新建的檔案不會進入 git,.gitignore 不會被改動。",
"{agents} reads no project instructions file magpie knows of.": "{agents} 沒有 magpie 已知的專案指令檔案。",
},
ja: {
"Put back in {agents}": "{agents} に戻す",
@@ -3243,6 +3269,19 @@ magpie.strings({
"It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "スキル、MCP サーバー、フック、サブエージェントごとライブラリから削除され、渡されていたエージェントからも外されます。",
"Open the plugin {name}": "プラグイン {name} を開く",
"{name} read again from its source": "{name} をソースから読み直しました",
"Project instructions": "プロジェクトの指示",
"Give a project instructions of its own: magpie writes them into the AGENTS.md, CLAUDE.md or the like each agent reads there, leaving the rest of each file as it is.": "プロジェクト専用の指示を書けます:magpie は各エージェントがそのプロジェクトで読む AGENTS.md や CLAUDE.md などに書き込み、ファイルの他の部分はそのまま残します。",
"{name} added — write its instructions": "{name} を追加しました — 指示を書いてください",
"No instructions yet": "まだ指示がありません",
"For no agent": "どのエージェントにも未設定",
"Hide its instructions": "指示を閉じる",
"Write its instructions": "指示を書く",
"{name}'s instructions are taken out of its files": "{name} のファイルから指示を取り除きました",
"{name}'s instructions are in its files for {agents}": "{name} の指示を {agents} が読むファイルに書き込みました",
"{name}'s instructions are saved — pick the agents that read them": "{name} の指示を保存しました — 読むエージェントを選んでください",
"What only this project needs — its stack, how to run its tests, what not to touch…": "このプロジェクトだけに必要なこと — 技術スタック、テストの実行方法、触れてはいけないもの…",
"Written between two marker lines in the file each agent reads in the project — the rest of the file stays yours. A file magpie makes is kept out of git, its .gitignore untouched.": "各エージェントがプロジェクトで読むファイルの 2 行のマーカーの間に書き込みます — ファイルの他の部分はあなたのものです。magpie が作ったファイルは git から除外され、.gitignore は変更しません。",
"{agents} reads no project instructions file magpie knows of.": "{agents} は magpie が把握しているプロジェクトの指示ファイルを読みません。",
},
de: {
"Put back in {agents}": "Zurück zu {agents}",
@@ -4324,5 +4363,18 @@ magpie.strings({
"It will be removed from the library, with its skills, MCP servers, hooks and subagents, and from the agents they were given to.": "Es wird samt Skills, MCP-Servern, Hooks und Subagenten aus der Bibliothek und aus den Agenten entfernt, denen sie gegeben wurden.",
"Open the plugin {name}": "Plugin {name} öffnen",
"{name} read again from its source": "{name} wurde erneut aus der Quelle gelesen",
"Project instructions": "Projekt-Anweisungen",
"Give a project instructions of its own: magpie writes them into the AGENTS.md, CLAUDE.md or the like each agent reads there, leaving the rest of each file as it is.": "Gib einem Projekt eigene Anweisungen: magpie schreibt sie in die AGENTS.md, CLAUDE.md oder Ähnliches, die jeder Agent dort liest, und lässt den Rest jeder Datei unverändert.",
"{name} added — write its instructions": "{name} hinzugefügt — schreib seine Anweisungen",
"No instructions yet": "Noch keine Anweisungen",
"For no agent": "Für keinen Agenten",
"Hide its instructions": "Anweisungen ausblenden",
"Write its instructions": "Anweisungen schreiben",
"{name}'s instructions are taken out of its files": "Die Anweisungen von {name} sind aus seinen Dateien entfernt",
"{name}'s instructions are in its files for {agents}": "Die Anweisungen von {name} stehen in seinen Dateien für {agents}",
"{name}'s instructions are saved — pick the agents that read them": "Die Anweisungen von {name} sind gespeichert — wähle die Agenten, die sie lesen",
"What only this project needs — its stack, how to run its tests, what not to touch…": "Was nur dieses Projekt braucht — sein Stack, wie seine Tests laufen, was nicht angefasst wird…",
"Written between two marker lines in the file each agent reads in the project — the rest of the file stays yours. A file magpie makes is kept out of git, its .gitignore untouched.": "Zwischen zwei Markierungszeilen in die Datei geschrieben, die jeder Agent im Projekt liest — der Rest der Datei bleibt deiner. Eine Datei, die magpie anlegt, bleibt aus git heraus, ihre .gitignore unberührt.",
"{agents} reads no project instructions file magpie knows of.": "{agents} liest keine Projekt-Anweisungsdatei, die magpie kennt.",
},
});
+8
View File
@@ -719,6 +719,7 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
ID string // a market server's, or a market skill's in its repository
Values map[string]string // what a market server needs
Dir string // a project's folder
Instr *string `json:"instr"` // a project's own instructions (projects/instructions)
Copy bool // a project gets copies, not links
Keep bool // a project removed keeps what magpie put in it
On bool // every skill or server given to the agents, or taken from them
@@ -926,6 +927,13 @@ func libraryRoutes(mux *http.ServeMux, w Windows) {
res, err = library.ProjectSkillsOff(in.Dir, oneOrMore(in.Name, in.Names), in.Agents)
case "projects/copy":
res, err = library.ProjectCopy(in.Dir, in.Copy)
case "projects/instructions":
// the text, the agents (sent as [] for none), or both
c := library.ProjectInstr{Text: in.Instr}
if in.Agents != nil {
c.Agents = &in.Agents
}
res, err = library.ProjectInstructions(in.Dir, c)
case "all/sync":
res, err = library.Sync()
default:
@@ -0,0 +1,144 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// (VictorHong1022 on X) The Instructions tab lists the projects under the
// shared instructions: a card opens to the project's own text and chips for
// the agents that read a project's instructions file. The page's Save sends
// the text, to the agents the shared instructions are on for when the
// project has none yet; a chip sends the project's agents. An agent with no
// project file has no chip. The clicks scroll nothing; in English and
// Chinese. No backend: the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const HOME = "/Users/emo";
const DIR = HOME + "/code/app";
const agent = (id, name, more = {}) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json`, instructions: `${HOME}/.${id}/AGENTS.md`, ...more });
const lib = (pr) => ({
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
agents: [
agent("claude", "Claude Code", { projectInstructions: "CLAUDE.md" }),
agent("codex", "Codex", { projectInstructions: "AGENTS.md" }),
agent("cursor", "Cursor", { projectInstructions: "AGENTS.md" }),
agent("goose", "Goose"),
],
instructions: {
shared: "Be brief.",
sets: [{ id: "default", name: "", text: "Be brief.", active: true }],
agents: [
{ agent: "claude", name: "Claude Code", icon: "", path: `${HOME}/.claude/CLAUDE.md`, on: true, extra: "", own: 0 },
{ agent: "codex", name: "Codex", icon: "", path: `${HOME}/.codex/AGENTS.md`, on: false, extra: "", own: 0 },
],
},
servers: [], subagents: [], skills: [], foundServers: [], foundSkills: [],
projects: [{ dir: DIR, name: "app", copy: false, skills: {}, placed: [], servers: {}, subagents: {}, wrote: {}, ...pr }],
});
function server(lang, posts) {
let pr = { instr: "", instrAgents: [], instrFiles: [] };
return async (route) => {
const req = route.request(), url = new URL(req.url());
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } });
if (url.pathname === "/api/library") return route.fulfill({ json: lib(pr) });
if (url.pathname === "/api/library/projects/instructions") {
const b = req.postDataJSON();
posts.push(b);
pr = { ...pr };
if (b.instr !== undefined) pr.instr = b.instr;
if (b.agents) pr.instrAgents = b.agents;
pr.instrFiles = [...new Set(pr.instrAgents.map((id) => (id === "claude" ? "CLAUDE.md" : "AGENTS.md")))].sort();
return route.fulfill({ json: { ...lib(pr), result: { changed: [], problems: [] } } });
}
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const scrolled = (page) => page.evaluate(() => [window.scrollX, window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop || e.scrollLeft).map((e) => `${e.className}:${e.scrollTop},${e.scrollLeft}`)].join(" "));
const press = async (page, loc) => {
const b = await loc.boundingBox();
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
};
const chip = async (page, loc) => {
const a = await loc.boundingBox();
await page.mouse.move(a.x + a.width / 2, a.y + a.height / 2);
await page.waitForTimeout(350);
await press(page, loc);
};
const words = {
en: { head: "Project instructions", none: "No instructions yet", saved: "app's instructions are in its files for Claude Code", on: "app's instructions are in its files for Claude Code, Codex" },
zh: { head: "项目指令", none: "还没有指令", saved: "app 的指令已写入 Claude Code 读取的文件", on: "app 的指令已写入 Claude Code, Codex 读取的文件" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": a project's own instructions", async (t) => {
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const errors = [];
t.after(async () => {
if (errors.length) console.log(errors);
await browser.close();
});
for (const lang of ["en", "zh"]) {
await t.test(lang, async () => {
const w = words[lang], posts = [];
const ctx = await browser.newContext({ viewport: { width: 860, height: 1000 } });
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "instructions"); } catch {} });
const page = await ctx.newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posts));
await page.goto("http://magpie.test/");
await page.locator('button[data-view="library"]').click();
const card = page.locator("#view-library .lib-project");
await card.waitFor();
assert.equal((await card.locator(".lib-tags").textContent()).trim(), w.none);
assert.ok((await page.locator("#view-library .row-head .label").allTextContents()).includes(w.head));
await card.locator(".lib-projhead").scrollIntoViewIfNeeded();
const before = await scrolled(page);
await press(page, card.locator(".lib-projhead"));
const ta = card.locator("textarea.lib-text");
await ta.waitFor();
assert.deepEqual(await card.locator(".lib-ag").evaluateAll((cs) => cs.map((c) => c.dataset.agent)), ["claude", "codex", "cursor"], "Goose reads no project file");
assert.equal(await card.locator(".lib-ag.on").count(), 0);
const bar = page.locator("#view-library .lib-savebar");
assert.equal(await bar.isHidden(), true);
await ta.fill("Use pnpm here.");
await bar.waitFor();
// the page's Save: to the agents the shared instructions are on for
await press(page, bar.locator("button.primary"));
await page.waitForFunction((s) => document.querySelector("#status").textContent.trim() === s, w.saved);
await page.waitForFunction(() => document.querySelectorAll('#view-library .lib-project .lib-ag.on[data-agent="claude"]').length === 1);
assert.equal(await bar.isHidden(), true);
assert.equal(await card.locator(".lib-projinstr-agents .sub").textContent(), "CLAUDE.md");
// Cursor reads Codex's AGENTS.md: through it, once Codex has it
await chip(page, card.locator('.lib-ag[data-agent="codex"]'));
await page.waitForFunction((s) => document.querySelector("#status").textContent.trim() === s, w.on);
await page.waitForFunction(() => document.querySelector('#view-library .lib-project .lib-ag[data-agent="cursor"]')?.classList.contains("via"));
assert.equal(await card.locator(".lib-projinstr-agents .sub").textContent(), "AGENTS.md, CLAUDE.md");
assert.deepEqual(posts, [{ dir: DIR, instr: "Use pnpm here.", agents: ["claude"] }, { dir: DIR, name: "", agents: ["claude", "codex"] }]);
assert.equal(await scrolled(page), before, "the clicks scroll nothing");
// closed, the card shows the text's first line
await press(page, card.locator(".lib-projhead"));
await page.waitForFunction(() => document.querySelector("#view-library .lib-project .lib-tags")?.textContent.includes("Use pnpm here."));
assert.deepEqual(errors, []);
await ctx.close();
});
}
});
}
+304
View File
@@ -0,0 +1,304 @@
package library
import (
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"github.com/yetone/magpie/internal/edit"
)
// A project can be given instructions of its own (VictorHong1022 on X), so
// the user-wide ones keep only what holds everywhere: written into the
// file each picked agent reads a project's instructions from, between the
// same two marker lines the user-wide part has (instructions.go). The rest
// of the file is the user's and is never touched; turned off, the part
// comes out, and a file magpie made goes once nothing is left in it.
//
// The names each agent reads, in a project's folder, the first one there
// being the one it reads (and the first name the one made when none is):
//
// Claude Code CLAUDE.md, .claude/CLAUDE.md code.claude.com/docs/en/memory
// Codex AGENTS.override.md over AGENTS.md Codex docs, AGENTS.md discovery
// Pi AGENTS.override.md, AGENTS.md, AGENTS.MD, CLAUDE.md, CLAUDE.MD
// (loadContextFileFromDir, @earendil-works/pi-coding-agent)
// OpenCode AGENTS.md, else CLAUDE.md session/instruction.ts
// Gemini CLI GEMINI.md, or its settings' context.fileName
// Qwen Code QWEN.md, or its settings' context.fileName
// Qoder AGENTS.md, or its settings' context.fileName
// CodeBuddy CODEBUDDY.md
// Cursor, Copilot CLI, Kimi Code, Droid, Crush, Grok Build, Cline,
// Command Code and Goose read AGENTS.md at the project's root.
//
// A file several picked agents read is written once.
var projectInstrNames = map[string][]string{
"claude": {"CLAUDE.md", ".claude/CLAUDE.md"},
"codex": {"AGENTS.md", "AGENTS.override.md"},
"pi": {"AGENTS.md", "AGENTS.override.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"},
"opencode": {"AGENTS.md", "CLAUDE.md"},
"gemini": {"GEMINI.md"},
"qwen": {"QWEN.md"},
"qoder": {"AGENTS.md"},
"qoder-cn": {"AGENTS.md"},
"codebuddy": {"CODEBUDDY.md"},
"cursor": {"AGENTS.md"},
"copilot": {"AGENTS.md"},
"kimi": {"AGENTS.md"},
"droid": {"AGENTS.md"},
"crush": {"AGENTS.md"},
"grok": {"AGENTS.md"},
"cline": {"AGENTS.md"},
"commandcode": {"AGENTS.md"},
"goose": {"AGENTS.md"},
}
// the order an agent looks for its names in, where that isn't the order
// above (whose first is the one made): an override is read in place of
// AGENTS.md when it is there
var projectInstrOrder = map[string][]string{
"codex": {"AGENTS.override.md", "AGENTS.md"},
"pi": {"AGENTS.override.md", "AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD"},
}
// ProjectInstrFile is the file, in a project, an agent reads the
// project's instructions from when there is none yet: "" for one magpie
// can't give a project's instructions to.
func ProjectInstrFile(agentID string) string {
if n := projectInstrNames[agentID]; len(n) > 0 {
return n[0]
}
return ""
}
// projectInstrRel is the file, relative to dir, agent id reads the
// project's instructions from there: the first of its names there is,
// else the first. renamed is the name its settings' context.fileName
// gives (Gemini CLI, Qwen Code, Qoder), "" for none.
func projectInstrRel(dir, id, renamed string) string {
names := projectInstrNames[id]
if renamed != "" {
return filepath.ToSlash(renamed)
}
if len(names) == 0 {
return ""
}
order := projectInstrOrder[id]
if order == nil {
order = names
}
for _, n := range order {
if fi, err := os.Stat(filepath.Join(dir, filepath.FromSlash(n))); err == nil && !fi.IsDir() {
return n
}
}
return names[0]
}
// projectInstrRenames are, for the picked agents whose settings can name
// their instructions file, the name there; found only when one is picked,
// as finding the agents looks through every agent's folders.
func projectInstrRenames(agents []string) map[string]string {
out := map[string]string{}
if !slices.ContainsFunc(agents, func(id string) bool {
return id == "gemini" || id == "qwen" || id == "qoder" || id == "qoder-cn"
}) {
return out
}
for _, t := range everyTarget() {
id := t.Agent.ID
if !slices.Contains(agents, id) || t.Instructions == "" {
continue
}
settings := t.Agent.Path
if id == "gemini" && t.MCP != nil {
settings = t.MCP.Path
}
def := ProjectInstrFile(id)
if n := contextFile(settings, def); n != def {
out[id] = n
}
}
return out
}
// InstrFile is a project file magpie wrote the project's instructions
// into: the hash of the part as written, and whether magpie made the file.
type InstrFile struct {
Path string `json:"path"`
Hash string `json:"hash"`
Made bool `json:"made,omitempty"`
}
// syncProjectInstr writes the project's instructions into the file of
// each agent picked for them, and takes them out of a file no longer
// wanted. A part the user edited in the file is left alone until the
// project's text changes; one taken out of the file is written again.
func (l *Library) syncProjectInstr(p *Project, fail func(what string, err error)) {
text := strings.TrimSpace(strings.ReplaceAll(p.Instr, "\r\n", "\n"))
wanted := map[string]bool{}
if text != "" {
renames := projectInstrRenames(p.InstrAgents)
for _, id := range p.InstrAgents {
if rel := projectInstrRel(p.Dir, id, renames[id]); rel != "" {
wanted[rel] = true
}
}
}
rec := map[string]InstrFile{}
for _, f := range p.InstrFiles {
rec[f.Path] = f
}
var globals map[string]bool // the agents' user-wide files, found once
var kept []InstrFile
// what's no longer wanted: magpie's part out, and a file it made away
// once nothing of the user's is in it
for _, f := range p.InstrFiles {
if wanted[f.Path] {
continue
}
abs := filepath.Join(p.Dir, filepath.FromSlash(f.Path))
raw, err := os.ReadFile(abs)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
fail("instructions", err)
kept = append(kept, f)
continue
}
file := string(raw)
if _, _, _, ok := split(file); !ok {
continue // the user took it out themselves
}
rest := own(strings.ReplaceAll(file, "\r\n", "\n"))
if rest == "" && f.Made {
err = os.Remove(abs)
} else {
err = edit.WriteAtomic(abs, []byte(withEnds(withBlock(file, ""), file)))
}
if err != nil {
fail("instructions", err)
kept = append(kept, f)
}
}
for _, rel := range slices.Sorted(func(yield func(string) bool) {
for r := range wanted {
if !yield(r) {
return
}
}
}) {
abs := filepath.Join(p.Dir, filepath.FromSlash(rel))
r, had := rec[rel]
if globals == nil {
globals = l.globalInstrFiles()
}
if globals[realBelow(abs)] {
fail("instructions", fmt.Errorf("%s is an agent's user-wide instructions file, which magpie writes from the shared instructions: it's left as it is", rel))
if had {
kept = append(kept, r)
}
continue
}
raw, err := os.ReadFile(abs)
made := r.Made
switch {
case errors.Is(err, os.ErrNotExist):
made = !had || r.Made
case err != nil:
fail("instructions", err)
if had {
kept = append(kept, r)
}
continue
}
file := string(raw)
_, have, _, ok := split(file)
switch {
case ok && have == text:
kept = append(kept, InstrFile{Path: rel, Hash: hash(text), Made: made})
continue
case ok && had && hash(have) != r.Hash && hash(text) == r.Hash:
// edited in the file since, and the project's text hasn't
// changed: the user's edit stays until it does
kept = append(kept, r)
continue
}
if raw == nil {
if err := p.mkdirs(filepath.Dir(abs)); err != nil {
fail("instructions", err)
continue
}
}
if err := edit.WriteAtomic(abs, []byte(withEnds(withBlock(file, text), file))); err != nil {
fail("instructions", err)
if had {
kept = append(kept, r)
}
continue
}
kept = append(kept, InstrFile{Path: rel, Hash: hash(text), Made: made})
}
slices.SortFunc(kept, func(x, y InstrFile) int { return strings.Compare(x.Path, y.Path) })
p.InstrFiles = kept
}
// withEnds gives next the line ends the file it was made from has: a
// file of the user's written with CRLF keeps them.
func withEnds(next, file string) string {
if strings.Contains(file, "\r\n") {
return strings.ReplaceAll(next, "\n", "\r\n")
}
return next
}
// globalInstrFiles are, links followed, the agents' user-wide
// instructions files and the file the shared set is kept in: a project
// file that is one of them (a project at the home folder, or a file
// linked to one) would have the project's part and the shared one fight
// over the same lines, so it is left alone.
func (l *Library) globalInstrFiles() map[string]bool {
out := map[string]bool{realBelow(l.sharedPath()): true}
for _, t := range everyTarget() {
if t.Instructions != "" {
out[realBelow(t.Instructions)] = true
}
}
return out
}
// ProjectInstr is a change to a project's instructions: its text, the
// agents it is written for, or both; nil leaves that as it is.
type ProjectInstr struct {
Text *string
Agents *[]string
}
// ProjectInstructions sets a project's own instructions, and the agents
// whose project file they are written into; no agents, or no text, takes
// them out of the project's files.
func ProjectInstructions(dir string, c ProjectInstr) (*Result, error) {
return change(func(l *Library) error {
p := l.project(dir)
if p == nil {
return fmt.Errorf("no project %s", dir)
}
if c.Agents != nil {
var ids []string
for _, id := range *c.Agents {
if ProjectInstrFile(id) == "" {
return fmt.Errorf("magpie knows of no file %s reads a project's instructions from", id)
}
ids = set(ids, id, true)
}
p.InstrAgents = ids
}
if c.Text != nil {
p.Instr = strings.TrimSpace(strings.ReplaceAll(*c.Text, "\r\n", "\n"))
}
return nil
})
}
@@ -0,0 +1,242 @@
package library
import (
"os"
"path/filepath"
"strings"
"testing"
)
func instrProject(t *testing.T) (h, dir string) {
h = sandbox(t)
dir = filepath.Join(t.TempDir(), "app")
gitInit(t, dir)
ok(t)(AddProject(dir))
return
}
func setInstr(t *testing.T, dir, text string, agents ...string) *Result {
t.Helper()
c := ProjectInstr{Text: &text}
if agents != nil {
c.Agents = &agents
}
return ok(t)(ProjectInstructions(dir, c))
}
func block(text string) string { return blockBegin + "\n" + text + "\n" + blockEnd }
// A project's own instructions (VictorHong1022 on X) go into the file each
// picked agent reads in the project, between magpie's two lines, the
// user's own text in it untouched; turned off, the file is as it was, and
// one magpie made is gone. The agents' user-wide files are not touched.
func TestProjectInstructionsEachAgentsFile(t *testing.T) {
h, dir := instrProject(t)
mine := "# Mine\n\nRun make test.\n"
write(t, filepath.Join(dir, "CLAUDE.md"), mine)
setInstr(t, dir, "Use pnpm here.", "claude", "codex", "gemini", "cursor")
if got, want := read(t, filepath.Join(dir, "CLAUDE.md")), "# Mine\n\nRun make test.\n\n"+block("Use pnpm here.")+"\n"; got != want {
t.Errorf("CLAUDE.md = %q, want %q", got, want)
}
for _, f := range []string{"AGENTS.md", "GEMINI.md"} {
if got, want := read(t, filepath.Join(dir, f)), block("Use pnpm here.")+"\n"; got != want {
t.Errorf("%s = %q, want %q", f, got, want)
}
}
for _, f := range []string{".claude/CLAUDE.md", ".codex/AGENTS.md", ".gemini/GEMINI.md"} {
gone(t, filepath.Join(h, f))
}
// what magpie made is kept out of git; the user's CLAUDE.md is git's
g, _ := gitOf(dir)
ex := read(t, filepath.Join(g.Common, "info", "exclude"))
for _, f := range []string{"/AGENTS.md\n", "/GEMINI.md\n"} {
if !strings.Contains(ex, f) {
t.Errorf("%s isn't in info/exclude:\n%s", f, ex)
}
}
if strings.Contains(ex, "/CLAUDE.md") {
t.Errorf("the user's CLAUDE.md is in info/exclude:\n%s", ex)
}
view := instrView(t)
var pv *ProjectView
for i := range view.Projects {
if view.Projects[i].Dir == dir {
pv = &view.Projects[i]
}
}
if pv == nil || pv.Instr != "Use pnpm here." || strings.Join(pv.InstrFiles, ",") != "AGENTS.md,CLAUDE.md,GEMINI.md" {
t.Errorf("view: %+v", pv)
}
// a text changed reaches every file
setInstr(t, dir, "Use bun here.")
for _, f := range []string{"CLAUDE.md", "AGENTS.md", "GEMINI.md"} {
if got := read(t, filepath.Join(dir, f)); !strings.Contains(got, block("Use bun here.")) || strings.Contains(got, "pnpm") {
t.Errorf("%s = %q", f, got)
}
}
// an agent dropped takes its file's part out, the others' stay
setInstr(t, dir, "Use bun here.", "claude", "codex", "cursor")
gone(t, filepath.Join(dir, "GEMINI.md"))
// off: the user's file as it was, the made one gone
ok(t)(ProjectInstructions(dir, ProjectInstr{Agents: &[]string{}}))
if got := read(t, filepath.Join(dir, "CLAUDE.md")); got != mine {
t.Errorf("CLAUDE.md after off = %q, want %q", got, mine)
}
gone(t, filepath.Join(dir, "AGENTS.md"))
if ex := read(t, filepath.Join(g.Common, "info", "exclude")); strings.Contains(ex, "/AGENTS.md") {
t.Errorf("info/exclude still lists AGENTS.md:\n%s", ex)
}
}
func instrView(t *testing.T) *View {
t.Helper()
v, err := Read(nil)
if err != nil {
t.Fatal(err)
}
return v
}
// magpie's part edited in the file is the user's until the project's text
// changes; a part, or a file, the user took out is written again; text
// the user added to a file magpie made keeps the file when turned off.
func TestProjectInstructionsLeaveTheUsersEdits(t *testing.T) {
_, dir := instrProject(t)
setInstr(t, dir, "One.", "codex")
f := filepath.Join(dir, "AGENTS.md")
edited := "# Theirs\n\n" + block("One, edited.") + "\n"
write(t, f, edited)
ok(t)(Sync())
if got := read(t, f); got != edited {
t.Errorf("an edited part was written over: %q", got)
}
setInstr(t, dir, "Two.")
if got, want := read(t, f), "# Theirs\n\n"+block("Two.")+"\n"; got != want {
t.Errorf("AGENTS.md = %q, want %q", got, want)
}
if err := os.Remove(f); err != nil {
t.Fatal(err)
}
ok(t)(Sync())
if got, want := read(t, f), block("Two.")+"\n"; got != want {
t.Errorf("a deleted file came back as %q, want %q", got, want)
}
write(t, f, "Mine too.\n\n"+block("Two.")+"\n")
ok(t)(ProjectInstructions(dir, ProjectInstr{Agents: &[]string{}}))
if got := read(t, f); got != "Mine too.\n" {
t.Errorf("AGENTS.md after off = %q", got)
}
}
// Codex and Pi read AGENTS.override.md in place of AGENTS.md when it is
// there, Claude Code .claude/CLAUDE.md when it has no CLAUDE.md at the
// root, and Gemini CLI the name its settings give: the file each agent
// really reads is the one written.
func TestProjectInstructionsTheFileTheAgentReads(t *testing.T) {
h, dir := instrProject(t)
write(t, filepath.Join(dir, "AGENTS.override.md"), "Override.\n")
write(t, filepath.Join(dir, ".claude", "CLAUDE.md"), "Hidden.\n")
write(t, filepath.Join(h, ".gemini", "settings.json"), `{"context": {"fileName": ["CONTEXT.md", "GEMINI.md"]}}`)
setInstr(t, dir, "Here.", "codex", "claude", "gemini")
if got := read(t, filepath.Join(dir, "AGENTS.override.md")); got != "Override.\n\n"+block("Here.")+"\n" {
t.Errorf("AGENTS.override.md = %q", got)
}
if got := read(t, filepath.Join(dir, ".claude", "CLAUDE.md")); got != "Hidden.\n\n"+block("Here.")+"\n" {
t.Errorf(".claude/CLAUDE.md = %q", got)
}
if got := read(t, filepath.Join(dir, "CONTEXT.md")); got != block("Here.")+"\n" {
t.Errorf("CONTEXT.md = %q", got)
}
for _, f := range []string{"AGENTS.md", "CLAUDE.md", "GEMINI.md"} {
gone(t, filepath.Join(dir, f))
}
}
// A file of the user's written with CRLF keeps its line ends.
func TestProjectInstructionsKeepCRLF(t *testing.T) {
_, dir := instrProject(t)
f := filepath.Join(dir, "AGENTS.md")
write(t, f, "Mine.\r\nMore.\r\n")
setInstr(t, dir, "Here.", "codex")
if got, want := read(t, f), "Mine.\r\nMore.\r\n\r\n"+strings.ReplaceAll(block("Here."), "\n", "\r\n")+"\r\n"; got != want {
t.Errorf("AGENTS.md = %q, want %q", got, want)
}
ok(t)(ProjectInstructions(dir, ProjectInstr{Agents: &[]string{}}))
if got := read(t, f); got != "Mine.\r\nMore.\r\n" {
t.Errorf("AGENTS.md after off = %q", got)
}
}
// A project file that is, links followed, an agent's user-wide
// instructions file is left alone and said so: the shared part and the
// project's would fight over the same lines.
func TestProjectInstructionsNeverAnAgentsOwnFile(t *testing.T) {
h, dir := instrProject(t)
global := filepath.Join(h, ".claude", "CLAUDE.md")
write(t, global, "Global.\n")
if err := os.Symlink(global, filepath.Join(dir, "CLAUDE.md")); err != nil {
t.Skip("no symlinks here:", err)
}
text := "Here."
res, err := ProjectInstructions(dir, ProjectInstr{Text: &text, Agents: &[]string{"claude"}})
if err != nil {
t.Fatal(err)
}
if len(res.Problems) != 1 || res.Problems[0].What != "project:instructions" {
t.Errorf("problems: %+v", res.Problems)
}
if got := read(t, global); got != "Global.\n" {
t.Errorf("the user-wide CLAUDE.md = %q", got)
}
}
// A project removed takes its instructions out of its files.
func TestRemoveProjectTakesItsInstructionsOut(t *testing.T) {
_, dir := instrProject(t)
write(t, filepath.Join(dir, "CLAUDE.md"), "Mine.\n")
setInstr(t, dir, "Here.", "claude", "codex")
ok(t)(RemoveProject(dir, false))
if got := read(t, filepath.Join(dir, "CLAUDE.md")); got != "Mine.\n" {
t.Errorf("CLAUDE.md = %q", got)
}
gone(t, filepath.Join(dir, "AGENTS.md"))
for _, p := range instrView(t).Projects {
if p.Dir == dir {
t.Errorf("still a project: %+v", p)
}
}
}
// An agent magpie knows no project file of is refused.
func TestProjectInstructionsUnknownAgent(t *testing.T) {
_, dir := instrProject(t)
if _, err := ProjectInstructions(dir, ProjectInstr{Agents: &[]string{"dsh"}}); err == nil {
t.Error("dsh was taken")
}
}
// A project's instructions follow it into the repository's other git
// worktrees, as its skills and subagents do, and come out with it.
func TestProjectInstructionsFollowWorktrees(t *testing.T) {
_, dir := instrProject(t)
setInstr(t, dir, "Here.", "claude")
// git worktree add ../app-wt
wt := filepath.Join(filepath.Dir(dir), "app-wt")
own := filepath.Join(dir, ".git", "worktrees", "app-wt")
write(t, filepath.Join(wt, ".git"), "gitdir: "+own+"\n")
write(t, filepath.Join(own, "gitdir"), filepath.Join(wt, ".git")+"\n")
write(t, filepath.Join(own, "commondir"), "../..\n")
write(t, filepath.Join(wt, "CLAUDE.md"), "The branch's own.\n")
keepProjectTrees()
f := filepath.Join(wt, "CLAUDE.md")
if got := read(t, f); got != "The branch's own.\n\n"+block("Here.")+"\n" {
t.Fatalf("the worktree's CLAUDE.md = %q", got)
}
ok(t)(ProjectInstructions(dir, ProjectInstr{Agents: &[]string{}}))
if got := read(t, f); got != "The branch's own.\n" {
t.Errorf("the worktree's CLAUDE.md after off = %q", got)
}
}
+11 -2
View File
@@ -449,6 +449,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) {
t = &Project{Dir: d}
}
t.Copy, t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = p.Copy, p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents
t.Instr, t.InstrAgents = p.Instr, p.InstrAgents
l.syncFolder(t, res, hubs)
trees = append(trees, t)
}
@@ -462,6 +463,7 @@ func (l *Library) syncTrees(p *Project, res *Result, hubs map[string]*Server) {
// no longer one of the repository's worktrees, or no longer the
// project's: what magpie put there comes out
t.Skills, t.Servers, t.ServersOff, t.SkillsOff, t.Subagents = nil, nil, nil, nil, nil
t.Instr, t.InstrAgents = "", nil
l.syncFolder(t, res, nil)
if t.holds() {
trees = append(trees, t)
@@ -484,7 +486,7 @@ func (p *Project) tree(dir string) *Project {
// holds says whether magpie has anything of its own in the folder still.
func (p *Project) holds() bool {
return len(p.Placed) > 0 || len(p.Wrote) > 0 || len(p.CodexOff) > 0 || len(p.Overrides) > 0 || len(p.MadeFiles) > 0 || len(p.AgentFiles) > 0
return len(p.Placed) > 0 || len(p.Wrote) > 0 || len(p.CodexOff) > 0 || len(p.Overrides) > 0 || len(p.MadeFiles) > 0 || len(p.AgentFiles) > 0 || len(p.InstrFiles) > 0
}
// ignored are the files and folders of the project magpie put there, which
@@ -494,6 +496,13 @@ func (p *Project) ignored() []string {
for _, f := range p.AgentFiles {
out = append(out, f.Path)
}
// a file magpie made for the project's instructions; one of the
// user's, in git or not, stays as git has it
for _, f := range p.InstrFiles {
if f.Made {
out = append(out, f.Path)
}
}
return out
}
@@ -512,7 +521,7 @@ func (l *Library) treesChanged() bool {
}
}
}
if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff)+len(p.Subagents) == 0 && len(p.Trees) == 0 {
if len(p.Skills)+len(p.Servers)+len(p.ServersOff)+len(p.SkillsOff)+len(p.Subagents)+len(p.InstrAgents) == 0 && len(p.Trees) == 0 {
continue
}
dirs := p.treeDirs()
+19 -3
View File
@@ -65,6 +65,12 @@ type Project struct {
// (project_subagents.go)
Subagents map[string][]string `json:"subagents,omitempty"`
AgentFiles []SubagentFile `json:"agentFiles,omitempty"`
// Instr is the project's own instructions, InstrAgents the agents
// whose project file they're written into, InstrFiles the files
// magpie wrote them in (project_instructions.go)
Instr string `json:"instr,omitempty"`
InstrAgents []string `json:"instrAgents,omitempty"`
InstrFiles []InstrFile `json:"instrFiles,omitempty"`
}
// projectSkillsDirs is where, in a project, each agent reads skills of its
@@ -139,7 +145,7 @@ func (l *Library) syncProjects(res *Result) {
func (l *Library) syncProject(p *Project, res *Result) {
if fi, err := os.Stat(p.Dir); err != nil || !fi.IsDir() {
if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.Subagents) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.holds() {
if len(p.Skills) > 0 || len(p.Servers) > 0 || len(p.Subagents) > 0 || len(p.ServersOff) > 0 || len(p.SkillsOff) > 0 || p.Instr != "" && len(p.InstrAgents) > 0 || p.holds() {
res.Problems = append(res.Problems, Problem{Agent: p.Dir, What: "project:", Error: "the folder is gone"})
}
return
@@ -222,6 +228,7 @@ func (l *Library) syncFolder(p *Project, res *Result, hubs map[string]*Server) {
})
l.syncSkillsOff(p, fail)
l.syncProjectSubagents(p, func(what string, err error) { fail(what, err) })
l.syncProjectInstr(p, fail)
p.tidy()
}
@@ -478,7 +485,7 @@ func RemoveProject(dir string, keep bool) (*Result, error) {
l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p })
return nil
}
p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents = nil, nil, nil, nil, nil
p.Skills, p.Servers, p.ServersOff, p.SkillsOff, p.Subagents, p.InstrAgents = nil, nil, nil, nil, nil, nil
l.syncProject(p, &Result{})
if !p.holds() && p.Claude == nil && !slices.ContainsFunc(p.Trees, (*Project).holds) {
l.Projects = slices.DeleteFunc(l.Projects, func(x *Project) bool { return x == p })
@@ -567,7 +574,12 @@ type ProjectView struct {
Subagents map[string][]string `json:"subagents"`
// AgentFiles are the project's files magpie wrote for them
AgentFiles []string `json:"agentFiles"`
Missing bool `json:"missing,omitempty"` // the folder is gone
// Instr is the project's own instructions, InstrAgents the agents
// they're for, InstrFiles the project's files magpie wrote them in
Instr string `json:"instr"`
InstrAgents []string `json:"instrAgents"`
InstrFiles []string `json:"instrFiles"`
Missing bool `json:"missing,omitempty"` // the folder is gone
// Problems are, by skill ("" for the project's own), what couldn't be done
Problems map[string]string `json:"problems,omitempty"`
}
@@ -597,6 +609,10 @@ func projectViews(l *Library, problems []Problem) []ProjectView {
for _, f := range p.AgentFiles {
v.AgentFiles = append(v.AgentFiles, f.Path)
}
v.Instr, v.InstrAgents, v.InstrFiles = p.Instr, append([]string{}, p.InstrAgents...), []string{}
for _, f := range p.InstrFiles {
v.InstrFiles = append(v.InstrFiles, f.Path)
}
v.Subagents = map[string][]string{}
for k, a := range p.Subagents {
v.Subagents[k] = append([]string{}, a...)
+5 -1
View File
@@ -410,6 +410,9 @@ type AgentView struct {
ProjectMCP string `json:"projectMCP,omitempty"`
// ProjectSubagents is the folder in a project it reads subagents from
ProjectSubagents string `json:"projectSubagents,omitempty"`
// ProjectInstructions is the file in a project it reads the
// project's instructions from, when there is none yet
ProjectInstructions string `json:"projectInstructions,omitempty"`
// ProjectNoSSE: its project file can't take a server over SSE
ProjectNoSSE bool `json:"projectNoSSE,omitempty"`
// ProjectOff and ProjectSkillOff: a server, or a skill, it has from
@@ -664,7 +667,8 @@ func readView(problems []Problem, glance bool) (*View, error) {
for _, t := range targets {
av := AgentView{ID: t.Agent.ID, Name: t.Agent.Name, Icon: t.Agent.Icon, Instructions: t.Instructions, Skills: t.Skills,
SkillsAlso: t.SkillsAlso, Note: t.Note, MCPVia: t.MCPVia, ProjectSkills: ProjectSkillsDir(t.Agent.ID), ProjectMCP: ProjectMCPFile(t.Agent.ID), ProjectSubagents: ProjectSubagentsDir(t.Agent.ID),
ProjectOff: slices.Contains(projectOffAgents, t.Agent.ID), ProjectSkillOff: slices.Contains(projectSkillOffAgents, t.Agent.ID),
ProjectInstructions: ProjectInstrFile(t.Agent.ID),
ProjectOff: slices.Contains(projectOffAgents, t.Agent.ID), ProjectSkillOff: slices.Contains(projectSkillOffAgents, t.Agent.ID),
ProjectNoSSE: ProjectNoSSE(t.Agent.ID)}
if t.Skills != "" {
_, av.HowOwn = l.SkillHow[t.Agent.ID]
+3 -3
View File
@@ -105,7 +105,7 @@ f063a06ffc57785ad0f8f40f0b2f0bd2ae897ec9d6f290cf664bae2e12d899ed docs/ja/intent
216bfc5137a07a2f47a4445162a6f0f8605046dddefd2a0e9c1968a00cf76083 docs/ja/kimi.html
7f139f661cad0b7ff8acd6e2e4148237216b4c223bcf279a3f5964102f336453 docs/ja/kirocrew.html
55c3001c02482eaad8e0a0ece371516e52598e3d0456784708ad933f0213d592 docs/ja/kun.html
be51abe5b918ea4e1e275e4776791d5bc402e55ea11a841196a8bb2efcdeac8b docs/ja/library.html
2cddcb558b777dc2b20703206b660232a6b87598b25e175558997eacbbbbb9ec docs/ja/library.html
4c58e158e2e08c7f6e21b210cc07140d1732a9cffb75643f47e6ba313389ec77 docs/ja/local-models.html
4d665a14ad50a99e6a035a6b8217a67feac0541623244f71daff2e2ce6297a00 docs/ja/lody.html
9bea8e6efdb7f57ce75fd89c239d2829af4222b1bb9917e823c1ba102e05fdb2 docs/ja/longcat.html
@@ -180,7 +180,7 @@ bd1bbb7cb5d18c5958e28af7844566ddcb918501fe8ec31a137c56e22a6f1217 docs/ja/zed.ht
3f176491b08d04e75d4630249f7fa2f556f1d82024569518c4d240874c203dcc docs/kimi.html
0db9fb9853f999f132b5692f5e258e65cc04ec615898cf4c3cefdc99954cc9c0 docs/kirocrew.html
a3f7d9b772d9f1734afec293578d79f26e49dd1f28a2f0f1ae206b6138165b82 docs/kun.html
3663415946fe429f15eecd47322d674c7b6ad0cbf2f8832ea37ad02ebb22626c docs/library.html
3f1f014d0c1b60a48f8df576effccbe9eecd2a235855f85f23975fad89dfaa0a docs/library.html
f83bd40947cc12cac5e7477e91f5531328872f6459e8ee1e31b6d2f190095e77 docs/local-models.html
bd548638edd3756c4331ee720516e2f0de897f57e691c8a78a1d414110c3bf2d docs/lody.html
eaad977724db5b88137e9be4c1734ba9065a4d45dbba3354490a876c79d55313 docs/longcat.html
@@ -305,7 +305,7 @@ cdf908b0b929ab8d1d9f6d6b8d9c745c04a3002971c45ac39dbe2ca52481e3e9 docs/zh/kimi-c
cd10106676ecee5e68bcc8b191d9f2bccdc3a51f3d3afe903ab81f717a8385a1 docs/zh/kimi.html
6eb969eb23705b0f1bc3f2ca7f4001098481c61a4267c2fab7089b2778f27112 docs/zh/kirocrew.html
20b5825bdeead2876f205a495b3c84ff0becba191875765e2c53cfd1eb3075fe docs/zh/kun.html
ec8c736fb97e65cf2f54b230f2cb538d96ebfb451beb010c872043f7bca5ef80 docs/zh/library.html
ae704fe7a6aaf74c1ecbe2aab1efc86db51c73424d71518baf567a28f9502b3c docs/zh/library.html
02f33da03f589c855c0963c41c384aa5157958c63de9333cd55d33f20b906379 docs/zh/local-models.html
16be660a0d387ebcde497f1bdc2f645fae8158ae81592670ddffa80ed5060d12 docs/zh/lody.html
37549abe83acef720dffbc8a085227084556b0ad8ae543ad4f2ee71023a1afcc docs/zh/longcat.html
+1
View File
@@ -298,6 +298,7 @@ magpie library sync # エージェントに書き直す</pre>
<li>置き換えるものは先にバックアップに入ります。</li>
</ul>
<p>プロジェクトにもスキルと MCP サーバーを渡せます。プロジェクト自身のフォルダ(<code>.claude/skills</code>、<code>.agents/skills</code>、<code>.mcp.json</code>、<code>.codex/config.toml</code> など)に置かれます。ターミナルからは、<code>magpie library project add .</code> で今いるフォルダを追加し、<code>magpie library project skill add . pdf docx</code> でスキルを渡し、<code>magpie library project skill rm . pdf</code> で外し、<code>magpie library project skills .</code> で一覧できます。</p>
<p>プロジェクトには専用の指示も持たせられるので、全体の指示にはどこでも通じるルールだけを残せます。指示ページで共有テキストの下にあるプロジェクトを開き、そのプロジェクトだけに必要なことを書きます。magpie はそれを、各エージェントがそのプロジェクトで読むファイルの 2 行のマーカーの間に書き込みます。Claude Code は <code>CLAUDE.md</code>、Codex や Cursor など多くは <code>AGENTS.md</code>、Gemini CLI は <code>GEMINI.md</code> です。ファイルの残りはあなたのものです。magpie が作ったファイルは git に入らず、エージェントをオフにするとその部分は取り除かれます。ターミナルからは <code>magpie library project instructions . text "ここでは pnpm を使う。"</code>、そして <code>… agents claude,codex</code> または <code>… agents none</code>。</p>
</article>
</main>
+1
View File
@@ -298,6 +298,7 @@ magpie library sync # write it into the agents again</pre>
<li>Anything it replaces goes to the backups first.</li>
</ul>
<p>Projects can get skills and MCP servers too, in the project’s own folders (such as <code>.claude/skills</code>, <code>.agents/skills</code>, <code>.mcp.json</code> or <code>.codex/config.toml</code>). From a terminal, <code>magpie library project add .</code> adds the folder you are in, <code>magpie library project skill add . pdf docx</code> gives it skills, <code>magpie library project skill rm . pdf</code> takes one away, and <code>magpie library project skills .</code> lists them.</p>
<p>A project can have instructions of its own as well, so your shared instructions keep only what holds everywhere. On the Instructions page, open a project under the shared text and write what only it needs. magpie puts it between its two marker lines in the file each agent reads in that project: <code>CLAUDE.md</code> for Claude Code, <code>AGENTS.md</code> for Codex, Cursor and most others, <code>GEMINI.md</code> for Gemini CLI. The rest of the file stays yours. A file magpie makes is kept out of git, and turning an agent off takes its part out again. From a terminal: <code>magpie library project instructions . text "Use pnpm here."</code>, and <code>… agents claude,codex</code> or <code>… agents none</code>.</p>
</article>
</main>
+1
View File
@@ -298,6 +298,7 @@ magpie library sync # 重新写进各个 Agent</pre>
<li>被替换的内容都会先进备份。</li>
</ul>
<p>项目也可以拿到技能和 MCP 服务器,放在项目自己的目录里(比如 <code>.claude/skills</code>、<code>.agents/skills</code>、<code>.mcp.json</code> 或 <code>.codex/config.toml</code>)。在终端里,<code>magpie library project add .</code> 添加当前目录,<code>magpie library project skill add . pdf docx</code> 给它技能,<code>magpie library project skill rm . pdf</code> 拿走一个,<code>magpie library project skills .</code> 列出它的技能。</p>
<p>项目也可以有自己的指令,这样全局指令只留下处处适用的规则。在指令页,展开共享指令下面的项目,写下只有它需要的内容。magpie 会把它写进每个智能体在该项目里读取的文件,放在两行标记之间:Claude Code 是 <code>CLAUDE.md</code>,Codex、Cursor 和多数智能体是 <code>AGENTS.md</code>,Gemini CLI 是 <code>GEMINI.md</code>。文件其余内容仍归你。magpie 新建的文件不会进入 git,关掉某个智能体时它那一段会被拿掉。在终端里:<code>magpie library project instructions . text "这里用 pnpm。"</code>,以及 <code>… agents claude,codex</code> 或 <code>… agents none</code>。</p>
</article>
</main>
+2
View File
@@ -10527,6 +10527,8 @@ The card shows how many tokens billion-context saved, in its own count: the net
Projects can get skills and MCP servers too, in the project’s own folders (such as `.claude/skills`, `.agents/skills`, `.mcp.json` or `.codex/config.toml`). From a terminal, `magpie library project add .` adds the folder you are in, `magpie library project skill add . pdf docx` gives it skills, `magpie library project skill rm . pdf` takes one away, and `magpie library project skills .` lists them.
A project can have instructions of its own as well, so your shared instructions keep only what holds everywhere. On the Instructions page, open a project under the shared text and write what only it needs. magpie puts it between its two marker lines in the file each agent reads in that project: `CLAUDE.md` for Claude Code, `AGENTS.md` for Codex, Cursor and most others, `GEMINI.md` for Gemini CLI. The rest of the file stays yours. A file magpie makes is kept out of git, and turning an agent off takes its part out again. From a terminal: `magpie library project instructions . text "Use pnpm here."`, and `… agents claude,codex` or `… agents none`.
---
Source: https://usemagpie.ai/docs/mcp-router
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long