library: a project's own resources are listed apart from what magpie placed, with a source in the CLI's --json (#7245, #7247)
ProjectView.Own reads, per kind, what the folder's own files already give agents and magpie didn't write: skills in the skills folders, servers in each agent's project MCP file (name and transport only, never URL, args or env), hooks in .claude/settings.json, settings.local.json and .codex/hooks.json (an entry is magpie's when it equals a HookRecs entry), and subagent files whose hash isn't in AgentFiles. Read-only: a link out of the folder or a file that can't be read is left out. The cards show them under "Project's own", no chips. `magpie library project server|hook|subagent <dir> --json` gains `items`, each with source "magpie" or "project"; the old maps stay as they were. Not done: Claude plugins, Pi packages and instructions are not read as the project's own yet; the cards have no "Assigned by MagPie" heading, the chips already say it. Run on mote: gofmt, go vet library, cli, gui; go test ./internal/library and ./internal/cli (whole packages, ok); new TestProjectOwnResources and the CLI source check; GUI project-own (new), project-hooks, project-servers, project-skills-*, project-plugins, i18n-keys in both engines, then every library-* and project-* file once: library-bar-more went red in that run and green alone (load, not filed: it did not touch this change). Not tried: a real project with hundreds of skills (the read is on every state poll of a project folder).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -230,7 +230,7 @@ func (k projectKind) list(typed string, asJSON bool) error {
|
||||
}
|
||||
have := k.of(p)
|
||||
if asJSON {
|
||||
return printJSON(map[string]any{"dir": p.Dir, "name": p.Name, k.plural: have})
|
||||
return printJSON(map[string]any{"dir": p.Dir, "name": p.Name, k.plural: have, "items": k.items(p)})
|
||||
}
|
||||
names := make([]string, 0, len(have))
|
||||
for n := range have {
|
||||
@@ -244,7 +244,44 @@ func (k projectKind) list(typed string, asJSON bool) error {
|
||||
for _, n := range names {
|
||||
fmt.Printf(" %s → %s\n", bold.Render(n), strings.Join(have[n], ", "))
|
||||
}
|
||||
if own := p.Own[k.plural]; len(own) > 0 {
|
||||
fmt.Println(" ", muted.Render("the project's own, read-only:"))
|
||||
for _, r := range own {
|
||||
fmt.Printf(" %s %s\n", r.Name, muted.Render(strings.TrimSpace(r.Event+" "+r.Path)))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// projectItem is one row of a project's list, with where it comes from:
|
||||
// source "magpie" for what magpie placed (agents says for whom), "project"
|
||||
// for what the project's own files give (read-only, #7247).
|
||||
type projectItem struct {
|
||||
Name string `json:"name"`
|
||||
Source string `json:"source"`
|
||||
Agents []string `json:"agents,omitempty"`
|
||||
Agent string `json:"agent,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Event string `json:"event,omitempty"`
|
||||
Transport string `json:"transport,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
func (k projectKind) items(p *library.ProjectView) []projectItem {
|
||||
have := k.of(p)
|
||||
names := make([]string, 0, len(have))
|
||||
for n := range have {
|
||||
names = append(names, n)
|
||||
}
|
||||
sort.Strings(names)
|
||||
out := []projectItem{}
|
||||
for _, n := range names {
|
||||
out = append(out, projectItem{Name: n, Source: "magpie", Agents: have[n]})
|
||||
}
|
||||
for _, r := range p.Own[k.plural] {
|
||||
out = append(out, projectItem{Name: r.Name, Source: "project", Agent: r.Agent, Path: r.Path, Event: r.Event, Transport: r.Transport, Description: r.Description})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var _ = os.Stdout
|
||||
|
||||
@@ -404,6 +404,20 @@ func TestLibraryProjectHookCmd(t *testing.T) {
|
||||
if out := must("hook", "."); !strings.Contains(out, "bark") || !strings.Contains(out, "codex") {
|
||||
t.Errorf("list:\n%s", out)
|
||||
}
|
||||
// each row says where it comes from (#7247): magpie's bark, the project's echo mine
|
||||
var listed struct {
|
||||
Items []struct{ Name, Source, Path string }
|
||||
}
|
||||
if err := json.Unmarshal([]byte(must("hook", ".", "--json")), &listed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := map[string]string{}
|
||||
for _, it := range listed.Items {
|
||||
src[it.Name] = it.Source
|
||||
}
|
||||
if src["bark"] != "magpie" || src["echo mine"] != "project" || len(src) != 2 {
|
||||
t.Errorf("sources: %+v", listed.Items)
|
||||
}
|
||||
must("hook", "agents", ".", "bark", "codex")
|
||||
if got := read(".claude/settings.local.json"); strings.Contains(got, "say bark") || !strings.Contains(got, "echo mine") {
|
||||
t.Errorf("claude after agents:\n%s", got)
|
||||
|
||||
@@ -7165,10 +7165,10 @@ magpie.plugin("library", (ctx) => {
|
||||
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 (mcp) return projectOwn(p, "servers", projectServers(p, card));
|
||||
if (sub) return projectOwn(p, "subagents", projectSubagents(p, card));
|
||||
if (plg) return projectPlugins(p, card);
|
||||
if (hk) return projectHooks(p, card);
|
||||
if (hk) return projectOwn(p, "hooks", projectHooks(p, card));
|
||||
if (ins) return projectInstructions(p, card);
|
||||
|
||||
const opts = el("div", "lib-projopts");
|
||||
@@ -7211,6 +7211,29 @@ magpie.plugin("library", (ctx) => {
|
||||
card.append(el("p", "lib-aside lib-projfoot", t("Placed in {dirs} of the project and kept out of git, its .gitignore untouched. A folder there that isn't magpie's is left as it is.", { dirs: dirs.join(", ") })));
|
||||
const skip = shownAgents().filter((a) => a.skills && !a.projectSkills);
|
||||
if (skip.length) card.append(el("p", "lib-aside lib-projfoot", t("{agents} reads no project skills folder magpie knows of.", { agents: skip.map((a) => a.name).join(", ") })));
|
||||
return projectOwn(p, "skills", card);
|
||||
}
|
||||
|
||||
// What the project's own files already give agents, apart from what magpie
|
||||
// placed (#7245): read-only rows under a heading, no chips, nothing here
|
||||
// changes or takes them away.
|
||||
function projectOwn(p, key, card) {
|
||||
const rows = p.own?.[key] || [];
|
||||
if (!rows.length) return card;
|
||||
const box = el("div", "lib-projown");
|
||||
box.append(el("div", "lib-projownhead", t("Project's own")));
|
||||
for (const r of rows) {
|
||||
const row = el("div", "row lib-row lib-projskill lib-projownrow");
|
||||
const w = el("div", "who");
|
||||
w.append(el("div", "name mono", r.name));
|
||||
const line = [r.event, r.transport, r.path].filter(Boolean).join(" · ");
|
||||
const sub = el("div", "sub mono", line);
|
||||
sub.title = r.description || line;
|
||||
w.append(sub);
|
||||
row.append(glyph(GLYPH.folder), w);
|
||||
box.append(row);
|
||||
}
|
||||
card.append(box);
|
||||
return card;
|
||||
}
|
||||
|
||||
|
||||
@@ -798,6 +798,7 @@ magpie.strings({
|
||||
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、服务器和子代理放在项目自己的那些位置,hooks 写进 .claude/settings.local.json 和 .codex/hooks.json。那里不是 magpie 写的文件、你改过的条目,都保持原样。",
|
||||
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的项目里运行项目的 hooks,并且要先在 /hooks 中审阅。",
|
||||
"Project hooks": "项目 Hooks",
|
||||
"Project's own": "项目自带",
|
||||
"No hooks yet": "还没有 Hook",
|
||||
"Hide its hooks": "收起它的 Hook",
|
||||
"Pick the hooks it gets": "选择它用的 Hook",
|
||||
@@ -1953,6 +1954,7 @@ magpie.strings({
|
||||
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "它的技能、伺服器和子代理放在專案自己的那些位置,hooks 寫進 .claude/settings.local.json 和 .codex/hooks.json。那裡不是 magpie 寫的檔案、你改過的條目,都保持原樣。",
|
||||
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex 只在你信任的專案裡執行專案的 hooks,並且要先在 /hooks 中審閱。",
|
||||
"Project hooks": "專案 Hooks",
|
||||
"Project's own": "專案自帶",
|
||||
"No hooks yet": "還沒有 Hook",
|
||||
"Hide its hooks": "收起它的 Hook",
|
||||
"Pick the hooks it gets": "選擇它用的 Hook",
|
||||
@@ -3099,6 +3101,7 @@ magpie.strings({
|
||||
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "スキル、サーバー、サブエージェントはプロジェクト自身のものと同じ場所に、フックは .claude/settings.local.json と .codex/hooks.json に書き込まれます。magpie のものではないファイルや、あなたが変更した項目はそのまま残ります。",
|
||||
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex は信頼したプロジェクトでのみ、/hooks で確認した後にプロジェクトのフックを実行します。",
|
||||
"Project hooks": "プロジェクトのフック",
|
||||
"Project's own": "プロジェクト自身のもの",
|
||||
"No hooks yet": "フックはまだありません",
|
||||
"Hide its hooks": "フックを閉じる",
|
||||
"Pick the hooks it gets": "渡すフックを選ぶ",
|
||||
@@ -4250,6 +4253,7 @@ magpie.strings({
|
||||
"Its skills, servers and subagents go where the project's own do, and its hooks into .claude/settings.local.json and .codex/hooks.json. A file there that isn't magpie's, or an entry you changed, is left as it is.": "Skills, Server und Subagenten kommen dorthin, wo die eigenen des Projekts liegen, Hooks in .claude/settings.local.json und .codex/hooks.json. Eine Datei dort, die nicht von magpie ist, oder ein Eintrag, den du geändert hast, bleibt, wie er ist.",
|
||||
"Codex runs a project's hooks only in a project you trust, once you've reviewed them in /hooks.": "Codex führt die Hooks eines Projekts nur in einem Projekt aus, dem du vertraust, und erst, nachdem du sie in /hooks geprüft hast.",
|
||||
"Project hooks": "Projekt-Hooks",
|
||||
"Project's own": "Eigene des Projekts",
|
||||
"No hooks yet": "Noch keine Hooks",
|
||||
"Hide its hooks": "Hooks ausblenden",
|
||||
"Pick the hooks it gets": "Hooks auswählen",
|
||||
|
||||
@@ -697,6 +697,9 @@ input.lib-setname:focus { border-color: var(--accent); box-shadow: 0 0 0 3px col
|
||||
.lib-project .lib-projskill { border-top: 1px solid var(--line-2); }
|
||||
.lib-projfoot { margin: 0; padding: 8px 12px 10px 49px; border-top: 1px solid var(--line-2); }
|
||||
.lib-projfoot + .lib-projfoot { border-top: 0; padding-top: 0; }
|
||||
.lib-projown { border-top: 1px solid var(--line-2); }
|
||||
.lib-projownhead { padding: 8px 12px 2px 49px; font-size: 11px; color: var(--muted); }
|
||||
.lib-projownrow { opacity: .8; }
|
||||
|
||||
/* the library's skills: a card for each GitHub repository they came from,
|
||||
and one for those on this computer, folded to its heading line */
|
||||
|
||||
@@ -88,7 +88,7 @@ const words = {
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": a project turns on a plugin Claude Code has installed", async (t) => {
|
||||
test(engine + ": a project turns a library hook on for the agents that read a project hooks file", async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
const errors = [];
|
||||
t.after(async () => {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// (#7245, jinpwng on X) A project's card lists what its own files already give
|
||||
// agents under "Project's own", read-only: no chips, nothing posted. 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`, ...more });
|
||||
const plugin = (name, more) => ({ name, version: "1.0.0", description: "", agents: [], skills: [], mcp: [], hooks: [], subagents: [], ...more });
|
||||
const lib = (given) => ({
|
||||
dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME,
|
||||
agents: [
|
||||
agent("claude", "Claude Code", { projectSkills: ".claude/skills", projectMCP: ".mcp.json", projectSubagents: ".claude/agents", projectHooks: ".claude/settings.local.json" }),
|
||||
agent("codex", "Codex", { projectMCP: ".codex/config.toml", projectSubagents: ".codex/agents", projectHooks: ".codex/hooks.json" }),
|
||||
agent("pi", "Pi", { projectSkills: ".agents/skills", projectMCP: ".pi/mcp.json" }),
|
||||
agent("goose", "Goose"),
|
||||
],
|
||||
instructions: { agents: [] }, servers: [], subagents: [], skills: [], foundServers: [], foundSkills: [],
|
||||
hooks: [{ name: "bark", event: "turn-end", command: "say bark", agents: [] }], hookAgents: [{ id: "claude", file: `${HOME}/.claude/settings.json`, events: ["Stop"] }, { id: "codex", file: `${HOME}/.codex/hooks.json`, events: ["Stop"] }], plugins: [], claudeInstalled: [{ id: "fmt@acme", on: false }, { id: "lint@acme", on: true }],
|
||||
projects: [{ dir: DIR, name: "app", copy: false, skills: {}, placed: [], servers: {}, subagents: {}, plugins: {}, hooks: given, wrote: {}, own: { hooks: [{ name: "echo mine", path: ".claude/settings.json", agent: "claude", event: "Stop" }] } }],
|
||||
});
|
||||
|
||||
function server(lang, posts) {
|
||||
let given = {};
|
||||
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(given) });
|
||||
if (url.pathname === "/api/library/projects/hooks") {
|
||||
const b = req.postDataJSON();
|
||||
posts.push(b);
|
||||
if (posts.hold) await posts.hold;
|
||||
given = { ...given, [b.name]: b.agents };
|
||||
if (!b.agents.length) delete given[b.name];
|
||||
return route.fulfill({ json: { ...lib(given), result: { changed: [], problems: [] } } });
|
||||
}
|
||||
if (url.pathname === "/api/library/native") return route.fulfill({ json: [] });
|
||||
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(" "));
|
||||
// a click where the element is, as the reader's: Playwright's own click
|
||||
// first scrolls it into view
|
||||
const press = async (page, loc) => {
|
||||
const b = await loc.boundingBox();
|
||||
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
|
||||
};
|
||||
// a chip: the chips fan out under the pointer first, as a reader's hand
|
||||
// does, and the chip is pressed where it is then
|
||||
// (a render after the last write may replace it under the pointer, so it
|
||||
// is found again until it stays)
|
||||
const box = async (loc) => {
|
||||
for (;;) {
|
||||
await loc.waitFor({ state: "visible" });
|
||||
const b = await loc.boundingBox();
|
||||
if (b) return b;
|
||||
}
|
||||
};
|
||||
const chip = async (page, loc) => {
|
||||
const a = await box(loc);
|
||||
await page.mouse.move(a.x + a.width / 2, a.y + a.height / 2);
|
||||
await page.waitForTimeout(350);
|
||||
const b = await box(loc);
|
||||
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
|
||||
};
|
||||
|
||||
|
||||
const words = { en: "Project's own", zh: "项目自带" };
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": what the project's own files give is listed read-only", async (t) => {
|
||||
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 posts = [];
|
||||
const ctx = await browser.newContext({ viewport: { width: 860, height: 700 } });
|
||||
await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "hooks"); } 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-projownrow").count(), 0, "closed card");
|
||||
await press(page, card.locator(".lib-projhead"));
|
||||
const own = card.locator(".lib-projownrow");
|
||||
await own.waitFor();
|
||||
assert.equal((await card.locator(".lib-projownhead").textContent()).trim(), words[lang]);
|
||||
assert.match(await own.textContent(), /echo mine/);
|
||||
assert.match(await own.textContent(), /Stop · \.claude\/settings\.json/);
|
||||
assert.equal(await own.locator(".lib-ag, button").count(), 0, "a read-only row has no chips");
|
||||
await press(page, own);
|
||||
assert.deepEqual(posts, []);
|
||||
await ctx.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// OwnResource is something the project's own files already give an agent,
|
||||
// that magpie didn't place (#7245, #7247): shown read-only, never changed
|
||||
// or taken away. Credentials never go in it: a server's URL, arguments and
|
||||
// environment stay in the project's file, only its transport is read.
|
||||
type OwnResource struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
Agent string `json:"agent,omitempty"`
|
||||
Event string `json:"event,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Transport string `json:"transport,omitempty"`
|
||||
}
|
||||
|
||||
// ownResources reads, by kind (skills, servers, hooks, subagents), what the
|
||||
// project's folder has that magpie didn't write. A file it can't read or a
|
||||
// link out of the folder is left out: unknown, never a wrong list.
|
||||
func (p *Project) ownResources() map[string][]OwnResource {
|
||||
out := map[string][]OwnResource{}
|
||||
var dirs []string
|
||||
for _, rel := range projectSkillsDirs {
|
||||
if !slices.Contains(dirs, rel) {
|
||||
dirs = append(dirs, rel)
|
||||
}
|
||||
}
|
||||
sort.Strings(dirs)
|
||||
for _, rel := range dirs {
|
||||
out["skills"] = append(out["skills"], p.ownSkills(rel)...)
|
||||
}
|
||||
ids := make([]string, 0, len(projectMCPFiles))
|
||||
for id := range projectMCPFiles {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
seen := map[string]bool{}
|
||||
for _, id := range ids {
|
||||
rel, format := p.mcpRel(id)
|
||||
if seen[rel] {
|
||||
continue
|
||||
}
|
||||
seen[rel] = true
|
||||
out["servers"] = append(out["servers"], p.ownServers(id, rel, format)...)
|
||||
}
|
||||
for _, id := range []string{"claude", "codex"} {
|
||||
out["hooks"] = append(out["hooks"], p.ownHooks(id)...)
|
||||
}
|
||||
ids = ids[:0]
|
||||
for id := range projectSubagentDirs {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
for _, id := range ids {
|
||||
out["subagents"] = append(out["subagents"], p.ownSubagents(id)...)
|
||||
}
|
||||
for k, rows := range out {
|
||||
if len(rows) == 0 {
|
||||
delete(out, k)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (p *Project) ownSkills(rel string) []OwnResource {
|
||||
dir := filepath.Join(p.Dir, filepath.FromSlash(rel))
|
||||
if p.inside(dir) != nil {
|
||||
return nil
|
||||
}
|
||||
var out []OwnResource
|
||||
entries, _ := os.ReadDir(dir)
|
||||
for _, e := range entries {
|
||||
path := rel + "/" + e.Name()
|
||||
abs := filepath.Join(dir, e.Name())
|
||||
if slices.Contains(p.Placed, path) || ours(abs, e.Name()) || p.inside(abs) != nil {
|
||||
continue
|
||||
}
|
||||
if m, ok := readMeta(abs); ok {
|
||||
name := e.Name()
|
||||
if m.Name != "" {
|
||||
name = m.Name
|
||||
}
|
||||
out = append(out, OwnResource{Name: name, Path: path, Description: m.Description})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (p *Project) ownServers(id, rel string, format mcpFormat) []OwnResource {
|
||||
abs := filepath.Join(p.Dir, filepath.FromSlash(rel))
|
||||
if p.inside(abs) != nil || !exists(abs) {
|
||||
return nil
|
||||
}
|
||||
f := &mcpFile{Path: abs, Format: format}
|
||||
entries, err := f.entries()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []OwnResource
|
||||
for name, entry := range entries {
|
||||
if slices.Contains(p.Wrote[rel], name) || id == "codex" && slices.Contains(p.CodexOff, name) {
|
||||
continue
|
||||
}
|
||||
row := OwnResource{Name: name, Path: rel, Agent: id}
|
||||
if s, ok := f.decode(name, entry); ok {
|
||||
row.Transport = s.Transport
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out
|
||||
}
|
||||
|
||||
func (p *Project) ownHooks(id string) []OwnResource {
|
||||
rels := []string{projectHookFiles[id]}
|
||||
if id == "claude" {
|
||||
rels = []string{".claude/settings.json", projectHookFiles[id]}
|
||||
}
|
||||
var out []OwnResource
|
||||
for _, rel := range rels {
|
||||
abs := filepath.Join(p.Dir, filepath.FromSlash(rel))
|
||||
if p.inside(abs) != nil || !exists(abs) {
|
||||
continue
|
||||
}
|
||||
doc, err := readHooksFile(abs)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
events := gjson.GetBytes(doc, "hooks").Map()
|
||||
names := make([]string, 0, len(events))
|
||||
for ev := range events {
|
||||
names = append(names, ev)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, ev := range names {
|
||||
list, err := hookList(doc, abs, ev)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, raw := range list {
|
||||
if p.wroteHook(id, ev, raw) {
|
||||
continue
|
||||
}
|
||||
for _, c := range ownHookCommands(raw) {
|
||||
out = append(out, OwnResource{Name: c, Path: rel, Agent: id, Event: ev})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// wroteHook is whether raw is an entry magpie wrote, byte for byte.
|
||||
func (p *Project) wroteHook(id, ev string, raw json.RawMessage) bool {
|
||||
return slices.ContainsFunc(p.HookRecs[id], func(r HookEntry) bool {
|
||||
return r.Event == ev && sameEntry(r.Entry, raw)
|
||||
})
|
||||
}
|
||||
|
||||
func sameEntry(a, b json.RawMessage) bool {
|
||||
var x, y bytes.Buffer
|
||||
if json.Compact(&x, a) != nil || json.Compact(&y, b) != nil {
|
||||
return false
|
||||
}
|
||||
return bytes.Equal(x.Bytes(), y.Bytes())
|
||||
}
|
||||
|
||||
// ownHookCommands are the commands an entry runs: its own, or those of the
|
||||
// group it holds (Claude Code's { matcher, hooks: [...] }).
|
||||
func ownHookCommands(raw json.RawMessage) []string {
|
||||
var e struct {
|
||||
Command string `json:"command"`
|
||||
Hooks []struct {
|
||||
Command string `json:"command"`
|
||||
} `json:"hooks"`
|
||||
}
|
||||
if json.Unmarshal(raw, &e) != nil {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
if e.Command != "" {
|
||||
out = append(out, e.Command)
|
||||
}
|
||||
for _, h := range e.Hooks {
|
||||
if h.Command != "" {
|
||||
out = append(out, h.Command)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (p *Project) ownSubagents(id string) []OwnResource {
|
||||
sp := projectSubagentSpec(p, id)
|
||||
if sp == nil || p.inside(sp.dir) != nil {
|
||||
return nil
|
||||
}
|
||||
var out []OwnResource
|
||||
entries, _ := os.ReadDir(sp.dir)
|
||||
for _, e := range entries {
|
||||
if e.IsDir() || !strings.HasSuffix(e.Name(), sp.ext) {
|
||||
continue
|
||||
}
|
||||
abs := filepath.Join(sp.dir, e.Name())
|
||||
rel := p.rel(abs)
|
||||
body, err := os.ReadFile(abs)
|
||||
if err != nil || slices.ContainsFunc(p.AgentFiles, func(f SubagentFile) bool {
|
||||
return f.Path == rel && f.Hash == subagentHash(body)
|
||||
}) {
|
||||
continue
|
||||
}
|
||||
m := parseMeta(body)
|
||||
name := m.Name
|
||||
if name == "" {
|
||||
name = strings.TrimSuffix(e.Name(), sp.ext)
|
||||
}
|
||||
out = append(out, OwnResource{Name: name, Path: rel, Agent: id, Description: m.Description})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package library
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -258,3 +260,37 @@ func TestProjectOneHookPerAgent(t *testing.T) {
|
||||
t.Errorf("view after removal: %+v", v.Projects[0].Hooks)
|
||||
}
|
||||
}
|
||||
|
||||
// What the project's own files give agents is listed apart from what magpie
|
||||
// placed, read-only (#7245, #7247): a hook, server, skill and subagent the
|
||||
// folder had before, and none of magpie's.
|
||||
func TestProjectOwnResources(t *testing.T) {
|
||||
_, a, _ := pluginProjects(t)
|
||||
ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "say bark", Agents: []string{}}))
|
||||
write(t, filepath.Join(a, ".claude/settings.json"), `{"hooks": {"Stop": [{"hooks": [{"type": "command", "command": "echo shared"}]}]}}`)
|
||||
write(t, filepath.Join(a, ".claude/settings.local.json"), `{"hooks": {"Stop": [{"hooks": [{"type": "command", "command": "echo mine"}]}]}}`)
|
||||
write(t, filepath.Join(a, ".mcp.json"), `{"mcpServers": {"theirs": {"url": "https://x.test/mcp?key=SECRET"}}}`)
|
||||
write(t, filepath.Join(a, ".claude/skills/own/SKILL.md"), "---\nname: own\ndescription: Mine.\n---\nbody\n")
|
||||
write(t, filepath.Join(a, ".claude/agents/rev.md"), "---\nname: rev\ndescription: Reviews.\n---\nbody\n")
|
||||
ok(t)(ProjectHooks(a, []string{"bark"}, []string{"claude"}))
|
||||
own := View0(t).Projects[0].Own
|
||||
var hooks []string
|
||||
for _, r := range own["hooks"] {
|
||||
hooks = append(hooks, r.Name)
|
||||
}
|
||||
if !slices.Equal(hooks, []string{"echo shared", "echo mine"}) {
|
||||
t.Errorf("own hooks %v (magpie's say bark must not be one)", hooks)
|
||||
}
|
||||
if len(own["servers"]) != 1 || own["servers"][0].Name != "theirs" || own["servers"][0].Transport != "http" {
|
||||
t.Errorf("own servers %+v", own["servers"])
|
||||
}
|
||||
if b, _ := json.Marshal(own); strings.Contains(string(b), "SECRET") {
|
||||
t.Errorf("a credential went in the view: %s", b)
|
||||
}
|
||||
if len(own["skills"]) != 1 || own["skills"][0].Name != "own" || own["skills"][0].Description != "Mine." {
|
||||
t.Errorf("own skills %+v", own["skills"])
|
||||
}
|
||||
if len(own["subagents"]) != 1 || own["subagents"][0].Name != "rev" {
|
||||
t.Errorf("own subagents %+v", own["subagents"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -658,8 +658,12 @@ type ProjectView struct {
|
||||
ClaudePlugins []string `json:"claudePlugins"`
|
||||
// Hooks are the library's hooks the project has on their own, for
|
||||
// the agents given
|
||||
Hooks map[string][]string `json:"hooks"`
|
||||
Missing bool `json:"missing,omitempty"` // the folder is gone
|
||||
Hooks map[string][]string `json:"hooks"`
|
||||
// Own are, by kind (skills, servers, hooks, subagents), what the
|
||||
// project's own files already give agents and magpie didn't place:
|
||||
// read-only (#7245)
|
||||
Own map[string][]OwnResource `json:"own,omitempty"`
|
||||
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"`
|
||||
}
|
||||
@@ -711,6 +715,8 @@ func projectViews(l *Library, problems []Problem) []ProjectView {
|
||||
}
|
||||
if fi, err := os.Stat(p.Dir); err != nil || !fi.IsDir() {
|
||||
v.Missing = true
|
||||
} else {
|
||||
v.Own = p.ownResources()
|
||||
}
|
||||
for _, x := range problems {
|
||||
if x.Agent == p.Dir {
|
||||
|
||||
Reference in New Issue
Block a user