diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 5302923a0..ff8faf010 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -35,7 +35,7 @@ Pi's extensions and packages. | Skills a repository or folder added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). A git repository on another host has no such list: when `git ls-remote` gives its ref a head, `findNewGit` reads the fetch the check shares (`fetcher`), once per head while its finds are kept (`gitLooked`), and offers the skills under `newBase` with the address as the library has it, `.git` and all, so an Add keeps the same `repo@ref`. A folder the user added linked skills from is kept as `folder:` in `SeenSkills` (`offered`, at install), which is also how the library knows which folder to look in again: `findNewFolder` reads it as Add from folder does and offers a skill folder there the library doesn't link, hasn't offered, and has no skill by that name of; a folder that can't be read keeps what was found. `View.CheckFolders` (`addedFromFolders`, which reads no folder) puts Check for updates on the page with only linked skills, and makes `checkDue` true. A check never adds or writes a skill: each is offered, and one the user removed or set aside isn't offered again. A folder added before this kept no `folder:` key and is looked in only once the user adds from it again (refeccd on Discord; `TestCheckSkillsFindsNewInGitRepo`, `TestCheckSkillsFindsNewInFolder`, `skill-new-in-repo.test.cjs`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) | | Skill groups | The page groups skills by `SkillView.Repo`, the repository each came from (`tracer.repoOf`): its GitHub source, CC Switch's `Origin`, `From`, the skills CLI's lock or the git checkout a linked folder is in. That checkout is the one git finds (`provider.GitAt` in `gitRepoOf`): an empty `.git` between the skill and its checkout is passed over, as git passes it over, and a `.git` file that names no repository (a worktree left behind) is none (#3675, `TestSkillRepoTraced`). A lock entry of `sourceType: well-known` (a site's kit at its `/.well-known/agent-skills/`) is grouped by its `sourceBaseUrl` as host/path (`wellKnownBase`), not by each skill's own `sourceUrl`: Feishu's lark-* skills are one group and Fish Audio's another, while two kits under one host with different base URLs stay apart. An older entry with no base URL takes the part of its `sourceUrl` before `/.well-known/`, and one with neither is grouped by its `sourceUrl` as before. Such a kit is never fetched from GitHub by Group again, even when it reads like owner/repo (a GitHub owner has no dot), and its heading's link opens the site (#1862, `TestWellKnownKitGrouped`). `From` is written when a repository is probed (installing from it again, `noteFrom`): for a skill with the very same `SKILL.md`, and for one traced to nowhere by a name the repository has when the library has others from there, since a pack added a while ago is mostly older copies edited there since (White Immortal on Discord: 20 of mattpocock/skills' 38). Group again (`RegroupSkills`, `POST /api/library/skills/regroup`) fetches each GitHub repository the skills are traced to and does the same; it fails only when none could be fetched. A skill traced to another repository is never moved. A group's (or part's, or the Select bar's) agent chips count, give and take only the skills magpie decides for each agent: one kept in `~/.agents/skills` is in `SkillView.Always` for the agents that read that folder themselves, so a chip's `agents-some` for such an agent leaves it out, its tooltip and the status after a click say how many it still reads itself, and an agent that reads every one of them itself has a lit, locked chip as the row's is, which sends nothing (`groupChips` in plugins/library/client.js). The heading says how many of its skills are in `~/.agents/skills`. A row's locked chip is lit with a lock on its corner, not greyed like a chip that can't be given the skill (#1862, `skill-group-shared.test.cjs`). Collapse all / Expand all, beside the sort, folds or opens every group the list shows at once (`foldAllButton`): without a filter it sets each group's kept fold (`magpie.libSkillFolds`), as a click on each heading would; while filtering, only the groups the filter shows, till the filter changes (`unfiltered`), leaving the kept folds alone. It reads Collapse all while any shown group is open, is hidden with fewer than two groups (A→Z, or a filter one group matches), leaves a part's own fold as it is and sends nothing (#1862, `skill-fold-all.test.cjs`). A group's, part's, project's or agent's heading opened or folded stays where it was clicked, its rows coming in below it (jinpwng on X, `library-group-steady.test.cjs`). | [`skill_from.go`](../../internal/library/skill_from.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | | Skill updates | A skill from GitHub (`kind: github`, a market install among them) keeps the commit it was fetched at and `Hash`, the hash of its files as fetched. `CheckSkills` asks GitHub for each one's last commit and keeps the result in memory; `View.CheckDue` says none was checked since magpie started, or not for `checkEvery` (12 hours), and the page then checks by itself as the skills open (#1449). `editState` says a skill was changed here when the library's folder no longer hashes to `Hash` (`.DS_Store` aside), or an agent's copy was edited since its mark and not yet taken in; the view's `edited` says so. What installing a skill's dependencies or running it writes in its folder is no change (`fromInstall`: `node_modules`, `.venv`, `venv`, `__pycache__`, `.pytest_cache`, `.mypy_cache`, `.ruff_cache` folders, `*.pyc`/`*.pyo`, and `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lock`, `bun.lockb`, `uv.lock` written again; ggbr on Discord): `Own` is the hash of the files as fetched leaving those aside (`ownHash`), and `onlyInstalled` compares the folder with it, or for a skill fetched before `Own` was kept with `Hash` (so a lock file the install wrote again still reads as changed until its next update). An update carries those entries over to the version fetched where it has none of its own (`carryInstalled`), so they aren't installed again. `UpdateSkill` refuses such a skill with `*EditedError` unless told to replace it (the page's own Update asks first; the CLI takes `--replace-edits`), and `UpdateSkills`/`UpdateSomeSkills` leave it as it is, in `Unupdated`. A replaced version that was changed, or that can't be told (no `Hash`), is moved to the backups (`keepReplaced`). Skills the skills CLI manages (`npx skills`, `~/.agents/.skill-lock.json`, or `$XDG_STATE_HOME/skills/.skill-lock.json` when that is set, both read with the XDG one winning) are only grouped: the CLI updates them (`npx skills update`). A linked folder, a skill imported from an agent and a `From`-only skill have no remote to check; one CC Switch installed (`Origin`) can be updated by hand but isn't checked. A skill from another git repository (`kind: git`) keeps the repository's head commit it was fetched at in `Commit`, and `Hash`. A check runs `git ls-remote` for the ref (`gitRemoteHead`): the same head is current; another one is fetched shallowly, once per repository and ref in a check, and the skill's folder hashed, so a commit that left the skill as it was is current and its head is kept as `Commit` (`checkGitSkill`). Its `*EditedError` and the page's Changed here, Update and the question before replacing a change name that repository, not GitHub (`editedError`, `skill-git-source.test.cjs`). New skills in such a repository are found from its fetch (`findNewGit`, above); Group again, icons and the market are GitHub's only. A skill whose source was read whole and no longer has its folder or `SKILL.md` was removed there (`goneFrom`; スライム on Discord): `UpdateSkill` returns `*GoneError`, `UpdateSkills`/`UpdateSomeSkills` list it in `Result.Gone`, not `Unupdated`, and a check gives it status `gone`. Each records `Skill.Gone` (the view's `gone`), cleared when a check or an update finds it there again. A fetch that failed, a skill left out of a fetch as too big (`leftOutAt`) and a folder that can't be read are unknown, never gone. Nothing is taken out by itself: `RemoveGoneSkills` (`POST /api/library/skills/remove-gone`, `magpie library skill rm --gone [--yes]`, the TUI's `d` on the row) takes the ones named, or every one marked, as `RemoveSkills` does, folders to the backups, and keeps one found in its source again. The page tags such a row Removed upstream with no Update, says them apart from failures after Update all, and offers Clean up N in the group's heading (in the bar with one group), which asks first, naming each one and which was changed here (`confirmRemoveGone`, `skill-gone.test.cjs`). Updates by themselves (`AutoUpdateSkills` in library.json, this computer's own; 0xYaCo on X): off by default; on, `KeepSkillsCurrent` (a `gateway.WhileServing` loop) runs `AutoUpdateTick` two minutes after the gateway starts and hourly after, which, every `checkEvery`, runs `CheckSkills` and `UpdateSomeSkills` on the skills it found at `update`, so everything above holds: one changed here stays in `Unupdated` and keeps its Update button, one removed there is only marked, a replaced version that was changed goes to the backups. Updated names and a new error are logged. Set by the Skills tab's Update by themselves switch under the list, shown while a skill comes from GitHub or git (`skillAutoPart`, `POST /api/library/skills/auto-update` with `on`), and `magpie library skill auto-update on\|off` (`TestAutoUpdateSkills`, `skill-auto-update.test.cjs`). | [`skill_changed.go`](../../internal/library/skill_changed.go), [`skillcheck.go`](../../internal/library/skillcheck.go), [`skillgit.go`](../../internal/library/skillgit.go), [`skills.go`](../../internal/library/skills.go) | -| Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. A session-start hook can be narrowed to some starts (#5604, NEKO-CwC: re-inject a file after compaction alone), one or more of `HookStarts` (startup, resume, clear, compact, fork, Claude Code's words) joined by `|`; `startMatcher` writes each agent's own matcher for them. Claude Code and Codex take the starts as written (Codex reads a `|` list as exact names). Gemini CLI has startup, resume and clear only and compares its matcher whole, so it takes one of them. Grok has `new` (startup and /clear) and `load` (resume), so it takes exactly one of those groups. Cursor's sessionStart takes no matcher. Starts an agent doesn't have are dropped, and one that has all that are left is given the hook whole. An agent that can't run it at exactly the starts picked is refused with why, as for any other per-agent limit: never widened to every start, which would run it at the starts the user narrowed away (a fork per subagent), nor written with a matcher it never matches. The written matcher is in `Applied.Hooks`, so an agent's own edit of the entry is still theirs. `HookAgentView.Starts` lists the matchers each agent takes, and the editor's At which starts app menu greys the chips of those that can't. A bundle carrying a narrowed hook to a magpie before this writes it whole. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), DeepSeek Harness `$DSH_HOME/magpie-hooks.json` (Claude Code's shape under dsh's tool names, `bash|pwsh` and `write|edit|str_replace_editor`; the events its bridge runs, `dshHookEvents`; `dsh_hooks.go`: every profile gets the plugin `@deepseek-ai/dsh-hooks-claude-code` and `@deepseek-ai/dsh-hook-protocol` installed at dsh's own version with `dsh plugin --profile add` (a failed install is said, retried after ten minutes, and writes no row: dsh leaves out a row whose plugin isn't there, and a deny hook would then allow what it was set to stop), then one marked `magpie-hooks` insert row naming the file; a row of the user's for that plugin is left alone and said; the last hook taken out takes the rows out; session-start can't be narrowed there; real dsh 0.2.2-rc.5 denied a `bash` call through it, @eiyuuzaki2333 on X), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.]]` array tables with a `[[hooks..hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). | [`hooks.go`](../../internal/library/hooks.go) | +| Hooks | A `Hook` (#1790) is a command, an event, an optional matcher, a timeout and the agents ticked for it. Its optional `Description` (#2011) says what it is for in any language, since its name is letters, digits, - and _: one line of at most `maxHookDescription` (200) characters, shown under the name; only library.json keeps it, and no agent is given it. Its event is portable (`HookEvents`: turn-end, after-tool, before-tool, prompt, session-start, each under the agent's own name) or an agent's own (`"codex:PermissionRequest"`), which only that agent is given. A portable tool event can be narrowed to shell or edit tools, each agent's own tool names for them. A session-start hook can be narrowed to some starts (#5604, NEKO-CwC: re-inject a file after compaction alone), one or more of `HookStarts` (startup, resume, clear, compact, fork, Claude Code's words) joined by `|`; `startMatcher` writes each agent's own matcher for them. Claude Code and Codex take the starts as written (Codex reads a `|` list as exact names). Gemini CLI has startup, resume and clear only and compares its matcher whole, so it takes one of them. Grok has `new` (startup and /clear) and `load` (resume), so it takes exactly one of those groups. Cursor's sessionStart takes no matcher. Starts an agent doesn't have are dropped, and one that has all that are left is given the hook whole. An agent that can't run it at exactly the starts picked is refused with why, as for any other per-agent limit: never widened to every start, which would run it at the starts the user narrowed away (a fork per subagent), nor written with a matcher it never matches. The written matcher is in `Applied.Hooks`, so an agent's own edit of the entry is still theirs. `HookAgentView.Starts` lists the matchers each agent takes, and the editor's At which starts app menu greys the chips of those that can't. A bundle carrying a narrowed hook to a magpie before this writes it whole. `syncHooks` writes each into the agent's own file and shape (`hookSpecOf`): Claude Code `/settings.json`, Codex `hooks.json` beside its config.toml, Gemini CLI `~/.gemini/settings.json` (timeout in ms), Cursor `~/.cursor/hooks.json` (flat entries, `version: 1`), DeepSeek Harness `$DSH_HOME/magpie-hooks.json` (Claude Code's shape under dsh's tool names, `bash|pwsh` and `write|edit|str_replace_editor`; the events its bridge runs, `dshHookEvents`; `dsh_hooks.go`: every profile gets the plugin `@deepseek-ai/dsh-hooks-claude-code` and `@deepseek-ai/dsh-hook-protocol` installed at dsh's own version with `dsh plugin --profile add` (a failed install is said, retried after ten minutes, and writes no row: dsh leaves out a row whose plugin isn't there, and a deny hook would then allow what it was set to stop), then one marked `magpie-hooks` insert row naming the file; a row of the user's for that plugin is left alone and said; the last hook taken out takes the rows out; session-start can't be narrowed there; real dsh 0.2.2-rc.5 denied a `bash` call through it, @eiyuuzaki2333 on X), and Grok Build `~/.grok/config.toml` and Grok App `agent-home/config.toml` as `[[hooks.]]` array tables with a `[[hooks..hooks]]` child. Grok Build and Grok App run the one CLI, so a `grok:` own event goes to both (`sameHookFamily`). Every other agent, and an agent in WSL, is refused with why, and the page greys its chip with that reason. The page also says when an agent has every hook turned off (`hooksOff`: Claude Code's `disableAllHooks`, Gemini's `hooksConfig.enabled`, Codex's `[features] hooks`). An entry of an agent's hooks file that no `Applied.Hooks` record claims is the agent's own, as the user or another tool wrote it (@InkCoalW on X), and `View.FoundHooks` lists it (`foundHooksOf`), keyed by agent, event, canonical entry and which of the same entries it is. dsh's file is magpie's and isn't read, and RTK's own (`rtk hook …`, `Own: "rtk"`) is the RTK tab's, which the page doesn't list. Bring in (`ImportHooks`, `POST /api/library/hooks/import`) is offered only when a library hook written back the way magpie writes it (`sp.entry`) comes out as the very entry: a portable event first, else the agent's own. A group of several commands (`why: several`), a hook that isn't a command (`type`) and one with a key the library has no field for, such as `async` (`shape`), are removable only, since magpie's next write would change them. Brought in, the entry stays as written and is recorded as magpie's, so unticking takes it out like any hook magpie wrote; one the same as a library hook ticks the agent for that hook. Remove (`RemoveFoundHooks`, `POST /api/library/hooks/remove-found`) runs `hookWrite` with the found entries as records to drop. The file (and Codex's config.toml, whose trust moves with the groups after) goes to the backups first, the rest of the file stays, and a count read back afterwards must have one fewer of each entry. A key no longer in the file is an error, not a no-op (`TestFoundHooks*`). | [`hooks.go`](../../internal/library/hooks.go) | | Variables | An `EnvVar` (paopao_baobao on X) is a name, a value and the agents ticked for it (`internal/library/env.go`). Claude Code gets it in `settings.json`'s `env`, Codex in `config.toml`'s `[shell_environment_policy.set]` (`envFile`, `writeEnv`); an agent with no such setting is greyed on the tab, saying why. `syncEnv` records what it wrote in `Applied.Env` and never overrides the user: a name the file already sets to another value is left as it is and reported as a problem on the row (`env:`), and a recorded value the user changed in the file is theirs from then on (the record is dropped, a removal or a turn-off leaves it). Turning an agent off or removing the variable takes out only the recorded, unchanged value. Codex's spelling is respected: a `set` sub-table or an inline `set = {…}` is edited, a dotted spelling is refused with `left as it is`. An unreadable or wrongly typed file is an error, never empty, and nothing is written. Names are `[A-Za-z_][A-Za-z0-9_]*`, at most 128, values at most 8192 bytes. Variables are carried with the library (see below). Tests: `TestEnvWrittenAndTakenOut`, `TestEnvNeverOverridesTheUsers`, `TestEnvValueChanged`, `TestEnvCodexInlineSet`, `TestEnvUnreadableFileLeftAlone`, `TestEnvChecked`, `library-env.test.cjs`. | | Subagents | A `Subagent` (#2283) is a name (lowercase letters, digits and -), a one-line description, a prompt, and the library's skills and MCP servers it uses, given to the agents ticked for it. `syncSubagents` writes it as a file of its own in each agent's user-level folder, in that agent's format (`subagentSpecOf`): Markdown with YAML front matter in `~/.claude/agents` (with `skills` and `mcpServers`), `~/.factory/droids` (with `mcpServers`), `~/.config/opencode/agents` (`mode: subagent`), `~/.gemini/agents`, `~/.qwen/agents`, `~/.grok/agents`, `~/.cursor/agents` and `~/.copilot/agents` (`.agent.md`); a TOML role (`name`, `description`, `model` when set, `developer_instructions`) in `$CODEX_HOME/agents`. Skills and servers are named only where the agent's file can name them, and only those the library has. A subagent's optional `Model` (a model or routing group of Codex's list, `subagentModels` in `/api/library`) is written only into Codex's role (luckymanjc on Discord): the role file is a config layer, and Codex lays its `model` over the one its lead names in spawn_agent (`apply_spawn_agent_role` after `apply_requested_spawn_agent_model_overrides` in codex-rs `core/src/agent/child_config.rs`), so the subagent's requests carry it and the gateway routes them as any other. Codex's subagent model on the Agents page (`CodexSubagentModel`), when set, still rewrites every subagent's request, and the editor says so. Without one, a Codex subagent runs on the model its lead names, else the lead's own. The page lists, per agent, whether it binds skills, servers and a model (`SubagentAgentView`), names the agents that run a subagent on their own pick, and greys out an agent that takes none. | [`subagents.go`](../../internal/library/subagents.go) | | Subagents from a repository | The Subagents tab's find line (CHENGJIAHEGOXIS on X: msitarzewski/agency-agents) takes what the skill installer does, owner/repo, a GitHub or GitLab link to the repository, a folder or a file in it, any git address, or a folder here, and fetches it the same way (`fetchSourceRoot`, shared with `resolvePluginRoot`; `tooBig` refuses a whole repository too big to download and asks for its folder's link). `ProbeSubagents` lists each Markdown file with front matter that has a description (`readSubagentAt`): its name is the slug of `name` (`subagentName`), else the file's own name when it sits in an `agents` or `droids` folder; its description is folded to one line of at most 1000 characters; the body is the prompt. Every other key (`color`, `emoji`, `vibe`, `tools`, `author`, `model`, …) is dropped, a Codex TOML role is not read, and a skill's folder (one with a SKILL.md) and `.git`, `.github`, `node_modules` are skipped. Of two files with one name the shallower is taken and the other is listed in `Left` with why, as is one `Subagent.check` refuses (a reserved name). `ImportSubagents` (`POST /api/library/subagents/probe`, then `subagents/import` with `source`, `paths`, `agents`) adds the picked ones for the agents ticked, recording where each came from (`From`, a `Source` with the file's path) and the hash of its description and prompt as imported (`FromHash`). Imported again, from the repository's link or a folder's or a file's, a subagent from the same file is `have` when it is the same, `update` when upstream changed and the library's still matches `FromHash` (its description and prompt are replaced, its agents, skills, servers and model kept), and `edited` when the user changed it here (`SaveSubagent` keeps `From`; it is left as it is). A name the library has for another subagent is never written over: the import takes the next free `name-N`. A carried library carries `From`. The page lists what was found to pick from, with Select all, a filter past eight, a tag for each state and the files left out (`TestSubagentsFromAgencyAgents`, `TestSubagentImportLeavesTheUsersOwn`, `TestSubagentImportAgainUpdates`, `TestSubagentsFromAFolder`, `library-subagents-import.test.cjs`; the fixture is agency-agents' own files in `testdata/agency-agents`). | [`subagent_import.go`](../../internal/library/subagent_import.go), [`plugin.go`](../../internal/library/plugin.go), [`plugins/library/client.js`](../../internal/gui/assets/plugins/library/client.js) | @@ -134,7 +134,8 @@ go test -tags nogui ./internal/library -run 'TestCommand' go test -tags nogui ./internal/library -run 'TestRule' go test -tags nogui ./internal/library -run 'TestSubagentFile|TestSubagentOwnFile' node --test internal/gui/tests/library-rules.test.cjs -go test -tags nogui ./internal/library -run 'TestProjectPlugin|TestHook' +go test -tags nogui ./internal/library -run 'TestProjectPlugin|TestHook|TestFoundHooks' +node --test internal/gui/tests/library-found-hooks.test.cjs node --test internal/gui/tests/project-plugins.test.cjs go test -tags nogui ./internal/library -run 'TestSkillOffHere|TestLocalServerNotCarried|TestPutKeepsLocalServer|TestPutSameNameAsLocal|TestServerHere' go test -tags nogui ./internal/backup -run 'TestRestoreKeepsLocalServer|TestBackupFileCarriesSubagents|TestBackupFileCarriesHooks' diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index d7140b8e3..0bd00cd60 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -4843,6 +4843,14 @@ magpie.plugin("library", (ctx) => { after.append(button(t("+ Add hook"), "", () => editHook(null))); body.append(after); } + // the hooks the agents run that magpie didn't give them, as the user or + // another tool wrote them (@InkCoalW on X); RTK's are the RTK tab's + const found = agentless() ? [] : (lib.foundHooks || []).filter((f) => !f.own); + if (found.length) { + const rh = el("div", "row-head lib-foundhookhead"); + rh.append(el("span", "label", t("In your agents")), el("span", "grow"), el("span", "note", t("not in the library — bring one in to manage it here"))); + body.append(rh, foldedFound("hooks", found.map(foundHookRow))); + } const given = (id) => hooks.some((h) => h.agents?.includes(id)); for (const a of all) { const ha = hookAgentOf(a.id); @@ -4879,6 +4887,60 @@ magpie.plugin("library", (ctx) => { return row; } + // One hook of an agent's own file: when it runs, what it runs, and where + // it is written. + function foundHookLabel(f) { return f.matcher ? f.event + " · " + f.matcher : f.event; } + + function foundHookRow(f) { + const row = el("div", "row lib-row lib-found lib-foundhook"); + const who = el("div", "who"); + who.append(el("div", "name mono", foundHookLabel(f))); + const line = f.commands.join(" ; "); + const cmd = el("div", "sub mono lib-hookcmd", line); + cmd.title = line; + who.append(cmd); + const src = el("div", "lib-src"); + src.append(pathLink(f.file)); + who.append(src); + const have = el("div", "lib-have"); + const a = agentOf(f.agent); + if (a) { const i = agentIcon(a.icon); i.title = a.name; have.append(i); } + row.append(glyph(GLYPH.hook), who, have); + const b = button(t("Bring in"), "action", () => change("hooks/import", { names: [f.key] }, t("{name} is in the library now", { name: f.hook.name }))); + if (f.hook) { + b.title = f.joins ? t("It is {name} of the library: {agent} is ticked for it", { name: f.joins, agent: a?.name || f.agent }) + : t("Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others", { name: f.hook.name, agent: a?.name || f.agent }); + } else { + // a group of several, a prompt or an agent hook, or a key the + // library has no field for: magpie would change it on its next write + b.disabled = true; + b.title = f.why === "several" ? t("It runs several commands: the library keeps a hook as one command") + : f.why === "type" ? t("It isn't a command: the library keeps command hooks") + : t("It has settings the library doesn't keep: bringing it in would change it"); + } + const rm = button("", "lib-icon danger", () => confirmRemoveFoundHook(f)); + rm.append(svg(GLYPH.trash, 13, 1.4)); + rm.title = t("Remove"); + row.append(b, rm); + return row; + } + + function confirmRemoveFoundHook(f) { + const ed = el("div", "editor lib-editor"); + const head = el("div", "ehead"); + head.append(glyph(GLYPH.trash), el("b", "", t("Remove this {event} hook?", { event: foundHookLabel(f) }))); + ed.append(head); + const cmd = el("p", "lib-confirm mono", f.commands.join(" ; ")); + ed.append(cmd); + ed.append(el("p", "lib-confirm", t("It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.", { file: tilde(f.file) }))); + const bar = el("div", "bar"); + const go = button(t("Remove"), "primary danger-fill", async () => { if (await change("hooks/remove-found", { names: [f.key] }, t("Hook removed"))) closeLibModal(true); }); + bar.append(el("span", "grow"), button(t("Cancel"), "", closeLibModal), go); + ed.append(bar); + modal = { save: () => go.click() }; + openLib(ed); + } + function editHook(h) { const all = hookAgents(); const d = h ? { name: h.name, description: h.description || "", event: h.event, matcher: h.matcher || "", command: h.command, timeout: h.timeout || 0, agents: [...(h.agents || [])] } diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index e8aa9afeb..49a593a30 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -1166,6 +1166,14 @@ magpie.strings({ "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 已知的项目指令文件。", + "It is {name} of the library: {agent} is ticked for it": "它就是资源库里的 {name}:已为 {agent} 勾选", + "Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others": "以 {name} 留在资源库中:{agent} 照常运行它,你也可以把它给其他 Agent", + "It runs several commands: the library keeps a hook as one command": "它运行多条命令:资源库里的钩子只保存一条命令", + "It isn't a command: the library keeps command hooks": "它不是命令:资源库只保存命令钩子", + "It has settings the library doesn't keep: bringing it in would change it": "它有资源库不保存的设置:导入会改动它", + "Remove this {event} hook?": "删除这个 {event} 钩子?", + "It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.": "它会从 {file} 中移除,文件其余部分保持不变。改动前文件会先复制到 magpie 的备份中,可以从那里恢复。", + "Hook removed": "钩子已删除", }, "zh-TW": { "project scope": "專案範圍", @@ -2332,6 +2340,14 @@ magpie.strings({ "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 已知的專案指令檔案。", + "It is {name} of the library: {agent} is ticked for it": "它就是資源庫裡的 {name}:已為 {agent} 勾選", + "Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others": "以 {name} 留在資源庫中:{agent} 照常執行它,你也可以把它給其他 Agent", + "It runs several commands: the library keeps a hook as one command": "它執行多條命令:資源庫裡的鉤子只保存一條命令", + "It isn't a command: the library keeps command hooks": "它不是命令:資源庫只保存命令鉤子", + "It has settings the library doesn't keep: bringing it in would change it": "它有資源庫不保存的設定:匯入會改動它", + "Remove this {event} hook?": "刪除這個 {event} 鉤子?", + "It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.": "它會從 {file} 中移除,檔案其餘部分保持不變。改動前檔案會先複製到 magpie 的備份中,可以從那裡還原。", + "Hook removed": "鉤子已刪除", }, ja: { "project scope": "プロジェクトの範囲", @@ -3498,6 +3514,14 @@ magpie.strings({ "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 が把握しているプロジェクトの指示ファイルを読みません。", + "It is {name} of the library: {agent} is ticked for it": "ライブラリの {name} と同じです:{agent} にチェックが入ります", + "Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others": "{name} としてライブラリに残します:{agent} は引き続き実行し、他のエージェントにも渡せます", + "It runs several commands: the library keeps a hook as one command": "複数のコマンドを実行します:ライブラリのフックはコマンド 1 つだけを保持します", + "It isn't a command: the library keeps command hooks": "コマンドではありません:ライブラリはコマンドのフックを保持します", + "It has settings the library doesn't keep: bringing it in would change it": "ライブラリが保持しない設定があります:取り込むと変わってしまいます", + "Remove this {event} hook?": "この {event} フックを削除しますか?", + "It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.": "{file} から取り除かれ、ファイルの他の部分はそのままです。変更前にファイルは magpie のバックアップにコピーされ、そこから元に戻せます。", + "Hook removed": "フックを削除しました", }, de: { "project scope": "Projektbereich", @@ -4664,5 +4688,13 @@ magpie.strings({ "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.", + "It is {name} of the library: {agent} is ticked for it": "Er ist {name} aus der Bibliothek: {agent} wird dafür angehakt", + "Keeps it in the library as {name}: {agent} goes on running it, and you can give it to the others": "Behält ihn als {name} in der Bibliothek: {agent} führt ihn weiter aus, und du kannst ihn den anderen geben", + "It runs several commands: the library keeps a hook as one command": "Er führt mehrere Befehle aus: die Bibliothek hält einen Hook als einen Befehl", + "It isn't a command: the library keeps command hooks": "Er ist kein Befehl: die Bibliothek hält Befehls-Hooks", + "It has settings the library doesn't keep: bringing it in would change it": "Er hat Einstellungen, die die Bibliothek nicht hält: Übernehmen würde ihn ändern", + "Remove this {event} hook?": "Diesen {event}-Hook entfernen?", + "It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.": "Er wird aus {file} entfernt, der Rest der Datei bleibt, wie er ist. Die Datei wird vorher in magpies Sicherungen kopiert, von wo sie sich zurückholen lässt.", + "Hook removed": "Hook entfernt", }, }); diff --git a/internal/gui/library.go b/internal/gui/library.go index 902e1da67..294e1b6a4 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -164,6 +164,9 @@ func revealable(v *library.View) []string { for _, s := range v.FoundSkills { out = append(out, s.Link, s.Shared) } + for _, h := range v.FoundHooks { + out = append(out, h.File) + } for _, s := range v.Subagents { // the file it is kept in, to edit it in if s.Path != "" { @@ -833,6 +836,13 @@ func libraryRoutes(mux *http.ServeMux, w Windows) { res, err = library.RemoveHooks([]string{in.Name}) case "hooks/remove-all": res, err = library.RemoveHooks(in.Names) + case "hooks/import": + // hooks the agents run that magpie didn't give them, by + // their keys (@InkCoalW on X) + res, err = library.ImportHooks(in.Names) + case "hooks/remove-found": + // out of the agents' own files, each copied to the backups first + res, err = library.RemoveFoundHooks(in.Names) case "plugins/install": res, err = library.InstallPlugins(in.Source, in.Names, in.Agents) case "plugins/agents": diff --git a/internal/gui/tests/library-found-hooks.test.cjs b/internal/gui/tests/library-found-hooks.test.cjs new file mode 100644 index 000000000..f65388d61 --- /dev/null +++ b/internal/gui/tests/library-found-hooks.test.cjs @@ -0,0 +1,154 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// @InkCoalW on X: read and manage the hooks an agent already runs, and +// clean them up. The Hooks tab lists them "In your agents", under the +// library's own: each with its event and matcher, its command, its agent +// and the file it is in. Bring in posts hooks/import with its key; one +// the library can't keep as written (two commands, a prompt hook) has +// Bring in greyed, saying why, and can still be removed. Remove asks +// first, says the file is copied to the backups, and posts +// hooks/remove-found. RTK's own hooks are the RTK tab's and aren't listed. +// With no hooks in the library the list is still there, under the empty +// state. In en, zh, zh-TW, ja and de, at 440px wide: no sideways scroll. +// 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 { strings } = require("./strings.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/ink"; +const agent = (id, name) => ({ id, name, icon: "", skills: `${HOME}/.${id}/skills`, mcp: `${HOME}/.${id}/mcp.json` }); +const HOOK_AGENTS = [ + { id: "claude", file: `${HOME}/.claude/settings.json`, events: ["PreToolUse", "PostToolUse", "Notification", "Stop"] }, + { id: "codex", file: `${HOME}/.codex/hooks.json`, events: ["PreToolUse", "PostToolUse", "Stop"] }, +]; +const FOUND = () => [ + { key: "k-say", agent: "claude", event: "Stop", commands: ["say done"], file: `${HOME}/.claude/settings.json`, hook: { name: "say", event: "turn-end", command: "say done", agents: ["claude"] } }, + { key: "k-two", agent: "codex", event: "PostToolUse", matcher: "Bash", commands: ["lint-a", "lint-b"], file: `${HOME}/.codex/hooks.json`, why: "several" }, + { key: "k-rtk", agent: "claude", event: "PreToolUse", matcher: "Bash", commands: ["rtk hook claude"], file: `${HOME}/.claude/settings.json`, own: "rtk" }, +]; +const lib = (state) => ({ + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [agent("claude", "Claude Code"), agent("codex", "Codex")], + instructions: { agents: [] }, servers: [], skills: [], foundServers: [], projects: [], foundSkills: [], problems: [], + hooks: state.hooks, hookAgents: HOOK_AGENTS, foundHooks: state.found, +}); + +let I18N; +function tr(lang, key, vars = {}) { + let s = key; + if (lang !== "en") { + assert.equal(typeof I18N[lang][key], "string", `${lang} has no ${JSON.stringify(key)}`); + s = I18N[lang][key]; + } + return s.replace(/\{(\w+)\}/g, (m, k) => (k in vars ? String(vars[k]) : m)); +} + +function server(lang, state, posts) { + return async (route) => { + const req = route.request(), url = new URL(req.url()); + const json = (data) => route.fulfill({ json: data }); + 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 json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/library") return json(lib(state)); + if (url.pathname.startsWith("/api/library/") && req.method() === "POST" && !url.pathname.endsWith("/reveal")) { + const body = req.postDataJSON(), what = url.pathname.replace("/api/library/", ""); + posts.push({ what, body }); + if (what === "hooks/import") { + const f = state.found.find((x) => body.names.includes(x.key)); + state.hooks = [...state.hooks, f.hook]; + state.found = state.found.filter((x) => !body.names.includes(x.key)); + } + if (what === "hooks/remove-found") state.found = state.found.filter((x) => !body.names.includes(x.key)); + return json({ ...lib(state), result: { changed: ["claude"] } }); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], gateway: { running: true } }); + if (url.pathname.startsWith("/api/")) return json({}); + if (url.host !== "magpie.test") return route.fulfill({ status: 404, body: "" }); + 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)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const sideways = (page) => page.evaluate(() => { + const over = []; + const w = document.documentElement.clientWidth; + if (document.documentElement.scrollWidth > w) over.push("page " + document.documentElement.scrollWidth); + const v = document.querySelector("#view-library"); + if (v.scrollWidth > v.clientWidth + 1) over.push("library " + v.scrollWidth + ">" + v.clientWidth); + for (const e of document.querySelectorAll("#view-library .lib-foundhookhead > *, #view-library .lib-foundhook, #view-library .lib-foundhook *, #modal .lib-editor *")) { + const r = e.getBoundingClientRect(); + if (r.width && (r.right > w + 0.5 || r.left < -0.5)) over.push((e.className || e.tagName) + " " + Math.round(r.left) + "–" + Math.round(r.right)); + } + return over; +}); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the hooks the agents run that magpie didn't give them", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + I18N = strings().I18N; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + await t.test(lang, async () => { + const w = (key, vars) => tr(lang, key, vars); + const state = { hooks: [], found: FOUND() }; + const posts = [], errors = []; + const ctx = await browser.newContext({ viewport: { width: 440, height: 1000 }, reducedMotion: "reduce" }); + 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, state, posts)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const rows = page.locator("#view-library .lib-foundhook"); + await rows.first().waitFor(); + + // the library has none: the found ones are listed under the empty state + assert.equal(await page.locator("#view-library .lib-foundhookhead .label").textContent(), w("In your agents")); + assert.equal(await rows.count(), 2, "RTK's own hook isn't listed"); + const say = rows.filter({ hasText: "say done" }); + assert.equal((await say.locator(".name").textContent()).trim(), "Stop"); + assert.equal((await say.locator(".lib-path").textContent()).trim(), "~/.claude/settings.json"); + assert.equal(await say.locator(".lib-have [title]").getAttribute("title"), "Claude Code"); + const two = rows.filter({ hasText: "lint-a ; lint-b" }); + assert.equal((await two.locator(".name").textContent()).trim(), "PostToolUse · Bash"); + const twoIn = two.getByRole("button", { name: w("Bring in"), exact: true }); + assert(await twoIn.isDisabled(), "one the library can't keep as written can't be brought in"); + assert.equal(await twoIn.getAttribute("title"), w("It runs several commands: the library keeps a hook as one command")); + assert.deepEqual(await sideways(page), [], "nothing sideways at 440"); + + // removing asks first, says where the backup goes, and posts the key + await two.locator("button.lib-icon.danger").click(); + const modal = page.locator("#modal"); + await modal.locator(".ehead b").waitFor(); + assert.equal(await modal.locator(".ehead b").textContent(), w("Remove this {event} hook?", { event: "PostToolUse · Bash" })); + assert(await modal.getByText(w("It is taken out of {file}, and the rest of the file stays as it is. The file is copied to magpie's backups first, where it can be put back.", { file: "~/.codex/hooks.json" })).isVisible()); + assert.deepEqual(await sideways(page), [], "the dialog fits at 440"); + assert.equal(posts.length, 0, "nothing posted before the confirm"); + await modal.getByRole("button", { name: w("Remove"), exact: true }).click(); + await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-foundhook").length === 1); + assert.deepEqual(posts.at(-1), { what: "hooks/remove-found", body: { names: ["k-two"] } }); + + // bringing one in posts its key, and it is the library's after + await say.getByRole("button", { name: w("Bring in"), exact: true }).click(); + await page.waitForFunction(() => !document.querySelector("#view-library .lib-foundhook")); + assert.deepEqual(posts.at(-1), { what: "hooks/import", body: { names: ["k-say"] } }); + assert.equal(await page.locator("#view-library .lib-hook .name").first().textContent(), "say"); + assert.equal(await page.locator("#view-library .lib-foundhookhead").count(), 0, "with none found, no heading"); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/library/hooks_found.go b/internal/library/hooks_found.go new file mode 100644 index 000000000..c9501a98d --- /dev/null +++ b/internal/library/hooks_found.go @@ -0,0 +1,488 @@ +package library + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "path/filepath" + "slices" + "strconv" + "strings" + + "github.com/pelletier/go-toml/v2" + "github.com/tidwall/gjson" +) + +// Hooks the agents run that magpie didn't give them (@InkCoalW on X: read +// and manage the hooks an agent already uses, and clean them up): an entry +// in an agent's own hooks file that no record of magpie's claims, as the +// user or another tool wrote it. The Hooks tab lists them under "In your +// agents", as the MCP and Skills tabs list the servers and skills the +// agents have of their own. One can be brought into the library, from then +// on magpie's like any hook it wrote (unticked, edited, given to the other +// agents), or taken out of the agent's file, the file copied to the backups +// first, so Backups puts it back. + +// FoundHook is one entry of an agent's hooks file that magpie didn't write. +type FoundHook struct { + // Key names the entry for ImportHooks and RemoveFoundHooks: the agent, + // its event, the entry's text and which of the same entries it is + Key string `json:"key"` + Agent string `json:"agent"` + // Event is the agent's own name for it ("PostToolUse") + Event string `json:"event"` + Matcher string `json:"matcher,omitempty"` + // Commands are what it runs: a group can hold several, and a handler + // that isn't a command is named by its type, "(prompt)" + Commands []string `json:"commands"` + // Timeout in seconds, when the entry sets one + Timeout int `json:"timeout,omitempty"` + File string `json:"file"` + // Hook is what bringing it in makes it; nil when the library can't + // keep it as it is written (Why: "several", "type" or "shape"), and + // then it can only be removed + Hook *Hook `json:"hook,omitempty"` + Why string `json:"why,omitempty"` + // Joins is the library hook it is the same as, for another agent: + // bringing it in ticks this agent for that hook + Joins string `json:"joins,omitempty"` + // Own: written by a tool magpie runs from another tab ("rtk", RTK's + // installer), which takes it out there; the page doesn't list it + Own string `json:"own,omitempty"` + + entry json.RawMessage + canon string // the entry written one way, as the records compare it +} + +// foundOwner is the tool of magpie's another tab that writes a hook with +// this command: RTK's installer writes "rtk hook " (rtk.go), Gemini's +// as rtk-hook-gemini. +func foundOwner(cmds []string) string { + for _, c := range cmds { + if strings.Contains(c, "rtk hook ") || strings.Contains(c, "rtk-hook-") { + return "rtk" + } + } + return "" +} + +// foundHooksOf lists the hooks of these agents that no record of magpie's +// claims. A file that can't be read is left out: what it holds is unknown, +// and it is said on the library's hooks where it matters. +func foundHooksOf(l *Library, targets []*Target) []FoundHook { + out := []FoundHook{} + for _, t := range targets { + if t.Gone || t.Agent.ID == "dsh" { + // dsh's magpie-hooks.json is magpie's own file, every entry of it + continue + } + sp, _ := hookSpecOf(t) + if sp == nil { + continue + } + evs, lists, err := hookLists(sp) + if err != nil { + continue + } + claimed := map[string]map[int]bool{} + for _, rec := range l.applied(t.Agent.ID).Hooks { + c := canonical(rec.Entry) + for i, e := range lists[rec.Event] { + if !claimed[rec.Event][i] && canonical(e) == c { + if claimed[rec.Event] == nil { + claimed[rec.Event] = map[int]bool{} + } + claimed[rec.Event][i] = true + break + } + } + } + for _, ev := range evs { + seen := map[string]int{} + for i, e := range lists[ev] { + if claimed[ev][i] { + continue + } + c := canonical(e) + n := seen[c] + seen[c]++ + f := foundHook(l, t.Agent.ID, sp, ev, e) + f.Key, f.canon = foundKey(t.Agent.ID, ev, c, n), c + out = append(out, f) + } + } + } + return out +} + +func foundKey(agent, ev, canon string, n int) string { + s := sha256.Sum256([]byte(agent + "\x00" + ev + "\x00" + canon + "\x00" + strconv.Itoa(n))) + return hex.EncodeToString(s[:8]) +} + +// hookLists is every event's list in the agent's hooks file, the events in +// the file's order. +func hookLists(sp *hookSpec) ([]string, map[string][]json.RawMessage, error) { + lists := map[string][]json.RawMessage{} + var evs []string + if sp.toml { + for _, ev := range sp.native { + x, err := grokHookBlocks(sp.path, ev) + if err != nil { + return nil, nil, err + } + if len(x) > 0 { + evs = append(evs, ev) + lists[ev] = x + } + } + return evs, lists, nil + } + doc, err := readHooksFile(sp.path) + if err != nil || doc == nil { + return nil, lists, err + } + var failed error + gjson.GetBytes(doc, "hooks").ForEach(func(k, v gjson.Result) bool { + if !v.IsArray() { + return true // not a list of hooks: nothing the agent runs, left as it is + } + var list []json.RawMessage + if err := json.Unmarshal([]byte(v.Raw), &list); err != nil { + failed = err + return false + } + evs = append(evs, k.String()) + lists[k.String()] = list + return true + }) + return evs, lists, failed +} + +// foundHook reads one entry: what it runs, and the library hook it would +// be, checked by writing that hook back the way magpie writes it: only an +// entry that comes out the same is brought in, so nothing of the user's +// (a second command, async, a status message) is lost on the next write. +func foundHook(l *Library, id string, sp *hookSpec, ev string, e json.RawMessage) FoundHook { + f := FoundHook{Agent: id, Event: ev, File: sp.path, Commands: []string{}, entry: e} + var group map[string]any + if sp.toml { + blk, _ := grokBlockText(e) + var doc map[string]any + if toml.Unmarshal([]byte(blk), &doc) == nil { + hs, _ := doc["hooks"].(map[string]any) + list, _ := hs[ev].([]any) + if len(list) == 1 { + group, _ = list[0].(map[string]any) + } + } + } else { + _ = json.Unmarshal(e, &group) + } + var handlers []map[string]any + if sp.flat { + if group != nil { + handlers = []map[string]any{group} + } + } else if group != nil { + hs, _ := group["hooks"].([]any) + for _, h := range hs { + if m, ok := h.(map[string]any); ok { + handlers = append(handlers, m) + } + } + } + if group != nil { + f.Matcher, _ = group["matcher"].(string) + } + why := "" + for _, h := range handlers { + typ, _ := h["type"].(string) + cmd, _ := h["command"].(string) + if (typ == "" || typ == "command") && cmd != "" { + f.Commands = append(f.Commands, cmd) + } else { + if typ == "" { + typ = "?" + } + f.Commands = append(f.Commands, "("+typ+")") + why = "type" + } + } + if len(handlers) == 1 { + f.Timeout = numberOf(handlers[0]["timeout"]) + if sp.ms { + f.Timeout /= 1000 + } + } + f.Own = foundOwner(f.Commands) + switch { + case why != "": + case len(handlers) != 1: + why = "several" + default: + if h := adoptable(id, sp, ev, e, f.Matcher, f.Commands[0], numberOf(handlers[0]["timeout"])); h != nil { + f.Hook = h + for _, x := range l.Hooks { + if x.Event == h.Event && x.Matcher == h.Matcher && x.Command == h.Command && x.Timeout == h.Timeout && hookTakes(x, id) { + f.Joins = x.Name + h.Name = x.Name + break + } + } + if f.Joins == "" { + h.Name = freeHookName(l, h.Command) + } + } else { + why = "shape" + } + } + f.Why = why + return f +} + +func numberOf(v any) int { + switch n := v.(type) { + case float64: + return int(n) + case int64: + return int(n) + } + return 0 +} + +// adoptable is the library hook entry e is, under event ev of the agent, or +// nil when no hook magpie writes comes out as e: a portable one when its +// event and matcher are the portable one's, else the agent's own event as +// written. +func adoptable(id string, sp *hookSpec, ev string, e json.RawMessage, matcher, cmd string, timeout int) *Hook { + if sp.ms { + if timeout%1000 != 0 { + return nil + } + timeout /= 1000 + } + var tries []Hook + for _, p := range HookEvents { + if sp.events[p] != ev { + continue + } + switch { + case matcher == "": + tries = append(tries, Hook{Event: p}) + case slices.Contains(toolEvents, p): + for _, k := range HookTools { + if sp.tools[k] == matcher { + tries = append(tries, Hook{Event: p, Matcher: k}) + } + } + case p == "session-start": + tries = append(tries, Hook{Event: p, Matcher: matcher}) + if g := grokStarts[matcher]; g != nil { + tries = append(tries, Hook{Event: p, Matcher: strings.Join(g, "|")}) + } + } + } + if slices.Contains(sp.native, ev) { + tries = append(tries, Hook{Event: id + ":" + ev, Matcher: matcher}) + } + want := canonical(e) + for _, h := range tries { + h.Name, h.Command, h.Timeout, h.Agents = "found", cmd, timeout, []string{id} + if h.check() != nil || !hookTakes(&h, id) { + continue + } + if canonical(sp.entry(&h, ev)) == want { + return &h + } + } + return nil +} + +// freeHookName is a name for a hook running cmd that the library doesn't +// have yet: the program it runs, "say" for "say done". +func freeHookName(l *Library, cmd string) string { + base := "hook" + for _, w := range strings.Fields(cmd) { + if strings.Contains(w, "=") && !strings.ContainsAny(w, "/\\") { + continue // FOO=1 before the program + } + w = strings.Trim(w, `"'`) + w = filepath.Base(strings.ReplaceAll(w, `\`, "/")) + w = strings.TrimSuffix(w, filepath.Ext(w)) + var b strings.Builder + for _, r := range strings.ToLower(w) { + if r < 128 && (r == '-' || r == '_' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9') { + b.WriteRune(r) + } + } + if s := strings.Trim(b.String(), "-_"); s != "" { + base = s + } + break + } + if len(base) > 40 { + base = base[:40] + } + name := base + for n := 2; l.hook(name) != nil; n++ { + name = base + "-" + strconv.Itoa(n) + } + return name +} + +func pickFound(found []FoundHook, keys []string) ([]FoundHook, error) { + if len(keys) == 0 { + return nil, errors.New("no hooks named") + } + var out []FoundHook + for _, k := range slices.Compact(slices.Sorted(slices.Values(keys))) { + i := slices.IndexFunc(found, func(f FoundHook) bool { return f.Key == k }) + if i < 0 { + return nil, errors.New("that hook is no longer in the agent's file: it changed since the page was drawn") + } + out = append(out, found[i]) + } + return out, nil +} + +// ImportHooks brings the hooks named into the library: each is the +// library's from then on, given to the agent it was found in, the entry +// there left exactly as it is. One the same as a library hook given to +// other agents ticks this agent for that hook. +func ImportHooks(keys []string) (*Result, error) { + return change(func(l *Library) error { + found, err := pickFound(foundHooksOf(l, Targets()), keys) + if err != nil { + return err + } + for _, f := range found { + if f.Hook == nil { + return fmt.Errorf("magpie can't keep %s's %s hook as it is written: it can only be removed", f.Agent, f.Event) + } + // the same hook in the library, one brought in a moment ago + // from another agent too, takes this agent as well + var h *Hook + for _, x := range l.Hooks { + if x.Event == f.Hook.Event && x.Matcher == f.Hook.Matcher && x.Command == f.Hook.Command && x.Timeout == f.Hook.Timeout && hookTakes(x, f.Agent) { + h = x + break + } + } + if h == nil { + c := *f.Hook + c.Name = freeHookName(l, c.Command) + h = &c + l.Hooks = append(l.Hooks, h) + } + h.Agents = orNone(slices.Compact(slices.Sorted(slices.Values(append(slices.Clone(h.Agents), f.Agent))))) + a := l.applied(f.Agent) + a.Hooks = append(a.Hooks, HookEntry{Name: h.Name, Event: f.Event, Entry: f.entry}) + } + return nil + }) +} + +// foundSentinel names the record of a found hook being taken out, which +// no library hook can be called. +const foundSentinel = "\x00found" + +// RemoveFoundHooks takes the hooks named out of their agents' files, each +// file copied to the backups first: Backups puts one back. The rest of +// each file stays as it is, and Codex's trust of the hooks after one moves +// with them. +func RemoveFoundHooks(keys []string) (*Result, error) { + return change(func(l *Library) error { + all := foundHooksOf(l, Targets()) + found, err := pickFound(all, keys) + if err != nil { + return err + } + b := l.kept + if b == nil { + b = newBackups() + l.kept = b + } + byAgent := map[string][]FoundHook{} + for _, f := range found { + byAgent[f.Agent] = append(byAgent[f.Agent], f) + } + for _, id := range slices.Sorted(func(yield func(string) bool) { + for k := range byAgent { + if !yield(k) { + return + } + } + }) { + t := targetByID(id) + if t == nil { + return fmt.Errorf("%s isn't here", id) + } + sp, why := hookSpecOf(t) + if sp == nil { + return errors.New(why) + } + a := l.applied(id) + var want []*Hook + for _, h := range l.Hooks { + if slices.Contains(h.Agents, id) { + want = append(want, h) + } + } + recs := slices.Clone(a.Hooks) + for _, f := range byAgent[id] { + recs = append(recs, HookEntry{Name: foundSentinel, Event: f.Event, Entry: f.entry}) + } + // a failure of the found entries' own, or of the whole file, + // stops it; a library hook's own (an event the agent lacks) is + // the sync's to say + var failed, first error + w := &hookWrite{id: id, sp: sp, want: want, recs: recs, gone: t.Gone, + keep: func(path string) error { return b.keep(id, path) }, + fail: func(what string, err error) { + if first == nil { + first = err + } + if failed == nil && (what == "hooks" || what == "hook:"+foundSentinel) { + failed = err + } + }} + if id == "codex" { + w.rekeyCfg = filepath.Join(codexDir(), "config.toml") + } + got, _, ok := w.run() + if !ok { + if failed == nil { + failed = first + } + if failed == nil { + failed = fmt.Errorf("%s couldn't be written", sp.path) + } + return fmt.Errorf("%s: %w", t.Agent.Name, failed) + } + if failed != nil { + return fmt.Errorf("%s: %w", t.Agent.Name, failed) + } + a.Hooks = slices.DeleteFunc(got, func(r HookEntry) bool { return r.Name == foundSentinel }) + } + // read back: as many of each entry as there were, less those taken + // out, or the one left is said, not reported gone + count := func(fs []FoundHook) map[string]int { + m := map[string]int{} + for _, f := range fs { + m[f.Agent+"\x00"+f.Event+"\x00"+f.canon]++ + } + return m + } + before, after, gone := count(all), count(foundHooksOf(l, Targets())), count(found) + for _, f := range found { + k := f.Agent + "\x00" + f.Event + "\x00" + f.canon + if after[k] > before[k]-gone[k] { + return fmt.Errorf("the %s hook is still in %s", f.Event, f.File) + } + } + return nil + }) +} diff --git a/internal/library/hooks_found_test.go b/internal/library/hooks_found_test.go new file mode 100644 index 000000000..5dd37efa3 --- /dev/null +++ b/internal/library/hooks_found_test.go @@ -0,0 +1,252 @@ +package library + +import ( + "io/fs" + "os" + "path/filepath" + "strings" + "testing" +) + +func foundHooks(t *testing.T) []FoundHook { + t.Helper() + v, err := Read(nil) + if err != nil { + t.Fatal(err) + } + return v.FoundHooks +} + +func foundBy(fs []FoundHook, agent, cmd string) *FoundHook { + for i := range fs { + if fs[i].Agent == agent && strings.Join(fs[i].Commands, "\n") == cmd { + return &fs[i] + } + } + return nil +} + +// keptCopies is the copies of a file named base in magpie's backups. +func keptCopies(t *testing.T, base string) []string { + t.Helper() + var out []string + filepath.WalkDir(BackupDir(), func(p string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() && filepath.Base(p) == base { + b, _ := os.ReadFile(p) + out = append(out, string(b)) + } + return nil + }) + return out +} + +// The hooks an agent already runs that magpie didn't give it are listed +// (@InkCoalW on X), each as what it runs and where; the ones magpie wrote +// aren't, nor are RTK's (the RTK tab's), and one the library can't keep as +// written is said so, to be removed only. +func TestFoundHooksListed(t *testing.T) { + h := sandbox(t) + settings := filepath.Join(h, ".claude/settings.json") + write(t, settings, `{ + // the user's own + "model": "opus", + "hooks": { + "Stop": [ + {"hooks": [{"type": "command", "command": "say done", "timeout": 5}]}, + {"hooks": [{"type": "command", "command": "bg-job", "async": true}]} + ], + "PostToolUse": [ + {"matcher": "Edit|Write|MultiEdit", "hooks": [{"type": "command", "command": "prettier --write ."}]}, + {"matcher": "Bash", "hooks": [{"type": "command", "command": "a"}, {"type": "command", "command": "b"}]} + ], + "PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "rtk hook claude"}]}], + "Notification": [{"hooks": [{"type": "prompt", "prompt": "is it done?"}]}] + } +} +`) + write(t, filepath.Join(h, ".codex/hooks.json"), `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"/usr/local/bin/notify-me.sh --loud"}]}]}}`) + ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "bark", Agents: []string{"claude"}})) + + fs := foundHooks(t) + if f := foundBy(fs, "claude", "bark"); f != nil { + t.Errorf("the hook magpie wrote is listed as found: %+v", f) + } + say := foundBy(fs, "claude", "say done") + if say == nil || say.Event != "Stop" || say.Timeout != 5 || say.File != settings || say.Hook == nil || + say.Hook.Event != "turn-end" || say.Hook.Name != "say" || say.Hook.Timeout != 5 { + t.Fatalf("say done: %+v (%+v)", say, fs) + } + if f := foundBy(fs, "claude", "prettier --write ."); f == nil || f.Hook == nil || f.Hook.Event != "after-tool" || f.Hook.Matcher != "edit" { + t.Errorf("prettier, a portable after-tool on edit: %+v", f) + } + if f := foundBy(fs, "claude", "a\nb"); f == nil || f.Hook != nil || f.Why != "several" || f.Matcher != "Bash" { + t.Errorf("a group of two commands: %+v", f) + } + // async isn't a thing a library hook has: brought in, the next write + // would drop it + if f := foundBy(fs, "claude", "bg-job"); f == nil || f.Hook != nil || f.Why != "shape" { + t.Errorf("an async hook: %+v", f) + } + if f := foundBy(fs, "claude", "(prompt)"); f == nil || f.Hook != nil || f.Why != "type" { + t.Errorf("a prompt hook: %+v", f) + } + if f := foundBy(fs, "claude", "rtk hook claude"); f == nil || f.Own != "rtk" { + t.Errorf("RTK's hook: %+v", f) + } + if f := foundBy(fs, "codex", "/usr/local/bin/notify-me.sh --loud"); f == nil || f.Hook == nil || f.Hook.Name != "notify-me" { + t.Errorf("codex's: %+v", f) + } + keys := map[string]bool{} + for _, f := range fs { + if keys[f.Key] || f.Key == "" { + t.Errorf("key %q twice or empty", f.Key) + } + keys[f.Key] = true + } +} + +// Brought into the library, a found hook is magpie's like one it wrote: +// the entry stays as it is, given to the other agents it lands in their +// files, and unticked it comes out of the file it was found in, the user's +// other hooks left. One the same as a library hook joins it. +func TestFoundHooksBroughtIn(t *testing.T) { + h := sandbox(t) + settings := filepath.Join(h, ".claude/settings.json") + mine := `{"model":"opus","hooks":{"Stop":[{"hooks":[{"type":"command","command":"say done"}]}],"Notification":[{"hooks":[{"type":"command","command":"keep-me"}]}]}}` + write(t, settings, mine) + codexHooks := filepath.Join(h, ".codex/hooks.json") + write(t, codexHooks, `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"say done"}]}]}}`) + + fs := foundHooks(t) + cl, cx := foundBy(fs, "claude", "say done"), foundBy(fs, "codex", "say done") + if cl == nil || cx == nil { + t.Fatalf("found: %+v", fs) + } + ok(t)(ImportHooks([]string{cl.Key, cx.Key})) + if got := read(t, settings); got != mine { + t.Errorf("bringing it in changed the file:\n%s", got) + } + v, _ := Read(nil) + if len(v.Hooks) != 1 || v.Hooks[0].Name != "say" || v.Hooks[0].Event != "turn-end" || strings.Join(v.Hooks[0].Agents, ",") != "claude,codex" { + t.Fatalf("library hooks: %+v", v.Hooks) + } + if f := foundBy(v.FoundHooks, "claude", "say done"); f != nil { + t.Errorf("still found after it was brought in: %+v", f) + } + if f := foundBy(v.FoundHooks, "claude", "keep-me"); f == nil { + t.Errorf("the one not brought in is no longer found") + } + // given to Gemini too, it lands there + ok(t)(HookAgents("say", []string{"claude", "codex", "gemini"})) + if got := hooksOf(t, filepath.Join(h, ".gemini/settings.json"), "AfterAgent"); len(got) != 1 || !strings.Contains(got[0], "say done") { + t.Errorf("gemini AfterAgent: %v", got) + } + // unticked for Claude, it comes out of the file it was found in alone + ok(t)(HookAgents("say", []string{"codex", "gemini"})) + if got := hooksOf(t, settings, "Stop"); len(got) != 0 { + t.Errorf("claude Stop after unticking: %v", got) + } + if got := hooksOf(t, settings, "Notification"); len(got) != 1 { + t.Errorf("the user's other hook went: %v", got) + } +} + +// Removed, a found hook comes out of its agent's file and nothing else +// does: the user's other hooks, their comments and settings stay, the +// file is copied to the backups first, and Codex's trust of the hooks +// after it moves with them. +func TestFoundHooksRemoved(t *testing.T) { + h := sandbox(t) + settings := filepath.Join(h, ".claude/settings.json") + before := `{ + // the user's own + "model": "opus", + "hooks": { + "Stop": [ + {"hooks": [{"type": "command", "command": "old-thing"}]}, + {"hooks": [{"type": "command", "command": "say done"}]} + ] + } +} +` + write(t, settings, before) + ok(t)(SaveHook("", Hook{Name: "bark", Event: "turn-end", Command: "bark", Agents: []string{"claude", "codex"}})) + codexHooks := filepath.Join(h, ".codex/hooks.json") + cfg := filepath.Join(h, ".codex/config.toml") + // the user's two of their own, the first to go, after magpie's: the + // second's trust moves to the first's place + write(t, codexHooks, `{"hooks":{"Stop":[{"hooks":[{"command":"bark","type":"command"}]},{"hooks":[{"type":"command","command":"gone-soon"}]},{"hooks":[{"type":"command","command":"mine"}]}]}}`) + key := func(g int) string { return codexKey(codexHooks + ":stop:" + string(rune('0'+g)) + ":0") } + write(t, cfg, "model = \"gpt-5\"\n\n[hooks.state]\n\n[hooks.state."+key(1)+"]\ntrusted_hash = \"sha256:aaa\"\n\n[hooks.state."+key(2)+"]\ntrusted_hash = \"sha256:bbb\"\n") + + fs := foundHooks(t) + old, gone := foundBy(fs, "claude", "old-thing"), foundBy(fs, "codex", "gone-soon") + if old == nil || gone == nil { + t.Fatalf("found: %+v", fs) + } + ok(t)(RemoveFoundHooks([]string{old.Key, gone.Key})) + + got := read(t, settings) + if !strings.Contains(got, "// the user's own") || !strings.Contains(got, `"model": "opus"`) || strings.Contains(got, "old-thing") || !strings.Contains(got, "say done") { + t.Errorf("claude's settings after:\n%s", got) + } + if s := hooksOf(t, settings, "Stop"); len(s) != 2 || !strings.Contains(s[1], `"bark"`) { + t.Errorf("claude Stop after (say done, then magpie's bark): %v", s) + } + if b := keptCopies(t, "settings.json"); len(b) == 0 || !strings.Contains(strings.Join(b, ""), "old-thing") { + t.Errorf("claude's settings weren't backed up first: %q", b) + } + if s := hooksOf(t, codexHooks, "Stop"); len(s) != 2 || !strings.Contains(s[0], "bark") || !strings.Contains(s[1], "mine") { + t.Errorf("codex Stop after: %v", s) + } + if b := keptCopies(t, "hooks.json"); len(b) == 0 || !strings.Contains(strings.Join(b, ""), "gone-soon") { + t.Errorf("codex's hooks weren't backed up first: %q", b) + } + if c, want := read(t, cfg), "model = \"gpt-5\"\n\n[hooks.state]\n\n[hooks.state."+key(1)+"]\ntrusted_hash = \"sha256:bbb\"\n"; c != want { + t.Errorf("codex config.toml after:\n%s\nwant:\n%s", c, want) + } + // magpie's own hook is magpie's still: unticking it takes it out + ok(t)(RemoveHooks([]string{"bark"})) + if s := hooksOf(t, settings, "Stop"); len(s) != 1 || !strings.Contains(s[0], "say done") { + t.Errorf("claude Stop after bark went: %v", s) + } + // a key the file no longer has is said, not taken as done + if _, err := RemoveFoundHooks([]string{old.Key}); err == nil { + t.Errorf("a found hook gone already was removed again without a word") + } +} + +// Of two entries the same, removing one leaves the other; a Grok block +// comes out of its config.toml alone. +func TestFoundHooksTwinsAndGrok(t *testing.T) { + h := sandbox(t) + settings := filepath.Join(h, ".claude/settings.json") + write(t, settings, `{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"twin"}]},{"hooks":[{"type":"command","command":"twin"}]}]}}`) + build := filepath.Join(h, ".grok/config.toml") + write(t, build, "model = \"grok-4.7\"\n\n[[hooks.Stop]]\n [[hooks.Stop.hooks]]\n type = \"command\"\n command = \"say grok done\"\n\n[[hooks.Stop]]\n [[hooks.Stop.hooks]]\n type = \"command\"\n command = \"stays\"\n") + + fs := foundHooks(t) + var twins []FoundHook + for _, f := range fs { + if f.Agent == "claude" { + twins = append(twins, f) + } + } + if len(twins) != 2 || twins[0].Key == twins[1].Key { + t.Fatalf("twins: %+v", twins) + } + g := foundBy(fs, "grok", "say grok done") + if g == nil || g.Hook == nil || g.Hook.Event != "turn-end" { + t.Fatalf("grok: %+v", fs) + } + ok(t)(RemoveFoundHooks([]string{twins[1].Key, g.Key})) + if s := hooksOf(t, settings, "Stop"); len(s) != 1 { + t.Errorf("claude Stop after one twin went: %v", s) + } + if b := grokBlocks(t, build, "Stop"); len(b) != 1 || !strings.Contains(b[0], "stays") { + t.Errorf("grok Stop after: %q", b) + } + if s := read(t, build); !strings.HasPrefix(s, "model = \"grok-4.7\"\n") { + t.Errorf("grok config after:\n%s", s) + } +} diff --git a/internal/library/sync.go b/internal/library/sync.go index d6bd25a55..2d52351f6 100644 --- a/internal/library/sync.go +++ b/internal/library/sync.go @@ -558,6 +558,9 @@ type View struct { Rules []RuleView `json:"rules"` RuleAgents []RuleAgentView `json:"ruleAgents"` FoundServers []Found `json:"foundServers"` + // FoundHooks are the hooks the agents run that magpie didn't give + // them (hooks_found.go) + FoundHooks []FoundHook `json:"foundHooks"` // Plugins are the plugins kept as one item each (plugin.go) Plugins []PluginView `json:"plugins"` Skills []SkillView `json:"skills"` @@ -869,6 +872,7 @@ func readView(problems []Problem, glance bool) (*View, error) { for i := range v.FoundServers { v.FoundServers[i].Icon = serverIcon(l, v.FoundServers[i].Server) } + v.FoundHooks = foundHooksOf(l, targets) v.NewSkills = newSkills(l) v.CheckFolders = l.addedFromFolders() v.Projects = projectViews(l, problems)