xonecas.io
64875
Mc

mini-coder / commit 4004169

feat: implement skill auto-discovery with progressive skill loading

xonecas2026-03-13 4004169bdaad3ce31741b847ff4c15f3cda343ed parent 9e717a5

15 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

SKILLS_IMPLEMENTATION_PLAN.md+167−0
@@ -0,0 +1,167 @@
1+# Skills Auto-Discovery + Progressive Disclosure — Implementation Plan
2+
3+## Goal
4+Implement skills behavior aligned with Claude Code/OpenCode expectations:
5+- Auto-discovered skills from supported directories
6+- Progressive disclosure (metadata first, full content on demand)
7+- Agent-accessible skill loading at runtime
8+- Backward-compatible explicit `@skill` usage
9+
10+## Scope
11+In scope:
12+- Skill discovery/indexing
13+- Runtime skill loading mechanism/tooling
14+- Prompt/context integration changes
15+- Validation rules and conflict handling
16+- Tests and docs updates
17+
18+Out of scope (for this iteration):
19+- Remote skill registries / marketplace install flows
20+- Full plugin packaging workflows
21+- New UI beyond existing `/help` and completion paths
22+
23+---
24+
25+## Phase 1 — Data model split (metadata index vs full content)
26+
27+### Changes
28+1. Introduce explicit types:
29+ - `SkillMeta` (name, description, source, root path, file path)
30+ - `SkillRecord` / loader output that can resolve full content lazily
31+2. Refactor `src/cli/skills.ts`:
32+ - `loadSkillsIndex(cwd, homeDir?) => Map<string, SkillMeta>`
33+ - `loadSkillContent(name, cwd, homeDir?) => { name, content, source } | null`
34+3. Keep existing `loadSkills` temporarily as compatibility shim, then migrate callsites.
35+
36+### Acceptance criteria
37+- Reading skill metadata does not read all `SKILL.md` bodies into memory.
38+- Existing command/help/completion behavior still works.
39+
40+---
41+
42+## Phase 2 — Discovery parity (auto-discovery + walk-up)
43+
44+### Changes
45+1. Extend discovery in `src/cli/load-markdown-configs.ts`:
46+ - Walk upward from `cwd` to git worktree root for local dirs.
47+ - Collect from each level:
48+ - `.agents/skills/*/SKILL.md`
49+ - `.claude/skills/*/SKILL.md`
50+ - Continue loading global dirs:
51+ - `~/.agents/skills/*/SKILL.md`
52+ - `~/.claude/skills/*/SKILL.md`
53+2. Define deterministic precedence:
54+ - Nearest local path wins over farther ancestor
55+ - Local wins over global
56+ - At same scope/path level, `.agents` wins over `.claude`
57+3. Retain conflict warnings where appropriate.
58+
59+### Acceptance criteria
60+- Skills in parent directories are discoverable.
61+- Precedence is deterministic and covered by tests.
62+
63+---
64+
65+## Phase 3 — Progressive disclosure runtime path
66+
67+### Changes
68+1. Add agent-facing skill loader tool (or equivalent internal tool contract) in `src/tools/`:
69+ - `listSkills` (metadata only)
70+ - `readSkill` / `loadSkill` (full `SKILL.md` for a single skill)
71+2. Expose available skill metadata to the model with minimal token footprint.
72+3. Ensure full skill content is loaded only when:
73+ - the model explicitly requests it via tool, or
74+ - the user explicitly references `@skill-name`.
75+4. Route `@skill-name` expansion through same resolver used by runtime loader.
76+
77+### Acceptance criteria
78+- Normal turns do not include all skill bodies.
79+- Skill body appears only after explicit load trigger.
80+- `@skill-name` remains functional.
81+
82+---
83+
84+## Phase 4 — Validation + compatibility policy
85+
86+### Changes
87+1. Add validation for skill frontmatter:
88+ - `name` required
89+ - `description` required
90+ - name format constraints (lowercase alnum + hyphen, length bounds)
91+2. Validation policy:
92+ - Invalid skills are skipped with clear warnings.
93+ - Unknown frontmatter fields are tolerated.
94+3. Optional: introduce strict mode flag if needed for incremental rollout.
95+
96+### Acceptance criteria
97+- Invalid skills do not crash loading.
98+- Validation behavior is deterministic and tested.
99+
100+---
101+
102+## Phase 5 — UX and docs alignment
103+
104+### Changes
105+1. Update CLI help output to reflect skill auto-discovery and on-demand loading semantics.
106+2. Update docs (`docs/skills.md`) to describe:
107+ - discovery locations + walk-up behavior
108+ - precedence rules
109+ - progressive disclosure
110+ - validation constraints
111+3. Keep examples for explicit `@skill` usage and tab completion.
112+
113+### Acceptance criteria
114+- Docs match real runtime behavior.
115+- `/help` and completion output stay accurate.
116+
117+---
118+
119+## Testing Plan
120+
121+Add/extend tests in:
122+- `src/cli/skills.test.ts`
123+- `src/cli/input.test.ts` (completion and visibility)
124+- new/updated tests for loader precedence and walk-up behavior
125+- tool tests for `listSkills`/`readSkill`
126+
127+Required scenarios:
128+1. Walk-up discovery from nested cwd.
129+2. Precedence matrix (nearest local > ancestor local > global; `.agents` > `.claude`).
130+3. Metadata-only listing does not require full body reads.
131+4. On-demand content load returns exact raw `SKILL.md`.
132+5. `@skill` expansion remains correct and unified with loader.
133+6. Invalid skill frontmatter handling.
134+
135+Verification command:
136+- `bun run jscpd && bun run knip && bun run typecheck && bun run format && bun run lint && bun run test`
137+
138+---
139+
140+## Rollout Strategy
141+
142+1. Land Phases 1–2 behind compatibility-preserving interfaces.
143+2. Land Phase 3 with both explicit (`@skill`) and runtime tool path enabled.
144+3. Enable strict validation policy (Phase 4) once tests and docs are complete.
145+4. Final docs/help cleanup and full QA pass.
146+
147+---
148+
149+## Risks and Mitigations
150+
151+- **Risk:** Behavior drift for users relying on permissive frontmatter.
152+ - **Mitigation:** Start with warning-based skipping and clear error messages.
153+- **Risk:** Token/context regression from accidental eager loading.
154+ - **Mitigation:** Add tests asserting no eager full-body skill injection.
155+- **Risk:** Discovery order confusion in monorepos.
156+ - **Mitigation:** Document precedence and cover with explicit tests.
157+
158+---
159+
160+## Done Definition
161+
162+Complete when:
163+- Skills are auto-discovered with walk-up + global support.
164+- Model receives metadata catalog, not full bodies by default.
165+- Full skill content is loaded only on demand.
166+- `@skill` works through unified loader path.
167+- Validation, tests, and docs are all aligned and passing.
TODO.md+20−7
@@ -1,23 +1,36 @@
11 # TODO
22
3-- Normalize the different models reasoning output. Trim excessive whitespace safely, ensure it renders uniquely. Should have a more structured output so it's noticeable that is reasoning and not a normal response. Enable the markdown rendering for it.
43 - Improve our autocomplete via TAB. it should work on all commands and parameters. When the user uses tab assume it's a file path autocompletion.
54 - Tool hooks output prints inline with spinner
65 - When the user uses /new reset the terminal and clear the history, print the banner again
76 - Review our markdown renderer. Let's make it render the raw markdown, but syntax highlited
87 - add a spinner state showing the user when the undo snapshotting is happening
8+- Structuted output when a skill is auto loaded for the agent
99
1010 ---
1111
12-# Lean and mean idea
12+## Skills auto discovery and progressive disclosure
1313
14-CLI vs MCP is the hot debate. I've testing a lot with different coding editors and I want to make feature branch that removes the subagent tool. Then simplify our read/write tools, streamline their usage based on usage history. Then update the mini-coder skill to teach how to use "subagents" by calling another mc via shell, and general tool guidelines (don't bloat context with large outputs, dont read more than needed, etc...). Also review our exa tools for improvements. Overall this allows the …
14+We need to make sure we implement skills according to the community expectations, same behaviour as claude code or opencode.
1515
16-Why this is good in my opinion:
16+let's do some research and understand what needs to be done.
1717
18-- Way less code, much less bug surface, faster.
19-- Less tool implementation, simpler structured output logic
20-- Raw, simple and makes mini-coder closer to it's intented coding prompt vision (as oposed to an interactive coding agent with TUI)
18+---
19+
20+## Lean and mean idea
21+
22+Drop the suabgent tool completly, prefer using the shell tool to mimic the subagent behaviour. Ensure we still support our subagents features like commands in new processes and subagent types. Update the mini-coder skill to be a guide explaining how to use mc via shell tool. Revise our cli interface to ensure support
23+Drop glob and grep tools. the agents can use shell for these.
24+Drop the read and write tools, we will need to revise the shell structured output to identify when we need to show diffs.
25+Do an extensive pass to cleanup tests, dead code and anything else that might have been related to our removals.
26+
27+---
28+
29+## UI Audit
30+
31+Our output is currently not in a good spot, with weird newlines and inconsistent whitespace separation between tool calls, tool responses, and assistant response.
32+
33+Audit our output to make sure it's refactored to the new tools and working correctly and performant and ensure propper whitespace.
2134
2235 ---
2336
docs/skills.md+47−42
@@ -1,28 +1,48 @@
11 # Skills
22
3-A skill is a reusable instruction file injected inline into your prompt.
4-Use `@skill-name` to load it — the content is inserted into the message
5-before it's sent to the LLM.
3+Skills are reusable instruction files discovered automatically from local and global directories.
64
7-> **Skills are never auto-loaded.** They must be explicitly referenced
8-> with `@skill-name` in your prompt. Nothing is injected automatically.
5+- The model sees **skill metadata only** by default (name, description, source).
6+- Full `SKILL.md` content is loaded **on demand**:
7+ - when explicitly requested with the runtime skill tools (`listSkills` / `readSkill`), or
8+ - when you reference `@skill-name` in your prompt.
99
10-## Where to put them
10+## Discovery locations
1111
12-Each skill is a folder containing a `SKILL.md`:
12+Skills live in folders containing `SKILL.md`:
1313
1414 | Location | Scope |
1515 |---|---|
16-| `.agents/skills/<name>/SKILL.md` | Current repo only |
17-| `~/.agents/skills/<name>/SKILL.md` | All projects (global) |
18-| `.claude/skills/<name>/SKILL.md` | Current repo only (Claude-compatible) |
19-| `~/.claude/skills/<name>/SKILL.md` | All projects (global, Claude-compatible) |
16+| `.agents/skills/<name>/SKILL.md` | Local |
17+| `.claude/skills/<name>/SKILL.md` | Local (Claude-compatible) |
18+| `~/.agents/skills/<name>/SKILL.md` | Global |
19+| `~/.claude/skills/<name>/SKILL.md` | Global (Claude-compatible) |
2020
21-Local skills override global ones with the same name. At the same scope, `.agents` wins over `.claude`.
21+Local discovery walks up from the current working directory to the git worktree root.
2222
23-## Create a skill
23+## Precedence rules
24+
25+If multiple skills share the same `name`, precedence is deterministic:
26+
27+1. Nearest local directory wins over farther ancestor directories.
28+2. Any local skill wins over global.
29+3. At the same scope/path level, `.agents` wins over `.claude`.
30+
31+## Frontmatter validation
32+
33+`SKILL.md` frontmatter must include:
2434
25-The folder name becomes the skill name (unless overridden by `name:` in frontmatter).
35+- `name` (required)
36+- `description` (required)
37+
38+`name` constraints:
39+
40+- lowercase alphanumeric and hyphen format (`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
41+- 1–64 characters
42+
43+Invalid skills are skipped with warnings. Unknown frontmatter fields are allowed.
44+
45+## Create a skill
2646
2747 `.agents/skills/conventional-commits/SKILL.md`:
2848
@@ -34,40 +54,25 @@ description: Conventional commit message format rules
3454
3555 # Conventional Commits
3656
37-All commit messages must follow this format:
38-
39- <type>(<scope>): <short summary>
40-
41-Types: feat, fix, docs, refactor, test, chore
42-- Summary is lowercase, no period at the end
43-- Breaking changes: add `!` after type, e.g. `feat!:`
44-- Body is optional, wrapped at 72 chars
57+Use:
58+<type>(<scope>): <short summary>
4559 ```
4660
47-Then in the REPL:
61+## Use a skill explicitly
4862
49-```
63+```text
5064 @conventional-commits write a commit message for my staged changes
5165 ```
5266
53-The skill content is wrapped in `<skill name="…">…</skill>` tags and
54-included in the message sent to the LLM.
55-
56-## Frontmatter fields
57-
58-| Field | Required | Description |
59-|---|---|---|
60-| `name` | No | Skill name for `@` reference. Defaults to folder name. |
61-| `description` | No | Shown in `/help`. Defaults to name. |
62-
63-## Tab completion
64-
65-Type `@` and press `Tab` to autocomplete skill names alongside agents and files.
66-
67-## Listing skills
67+`@skill-name` injects the raw skill body wrapped as:
6868
69+```xml
70+<skill name="conventional-commits">
71+...
72+</skill>
6973 ```
70-/help
71-```
7274
73-Skills are listed in yellow, tagged `(local)` or `(global)`.
75+## Tab completion and help
76+
77+- Type `@` then `Tab` to complete skill names.
78+- Run `/help` to list discovered skills with `(local)` / `(global)` tags.
src/agent/system-prompt.test.ts+42−0
@@ -182,4 +182,46 @@ describe("buildSystemPrompt", () => {
182182 );
183183 expect(prompt).not.toContain("# Project context");
184184 });
185+
186+ it("includes skill metadata guidance when skills are discoverable", () => {
187+ const skillDir = join(tmpDir, ".agents", "skills", "deploy");
188+ mkdirSync(skillDir, { recursive: true });
189+ writeFileSync(
190+ join(skillDir, "SKILL.md"),
191+ "---\nname: deploy\ndescription: Deploy safely\n---\n\n# Deploy\nDetailed body",
192+ );
193+
194+ const prompt = buildSystemPrompt(
195+ "mock",
196+ tmpDir,
197+ undefined,
198+ undefined,
199+ fakeHome,
200+ );
201+ expect(prompt).toContain("# Available skills (metadata only)");
202+ expect(prompt).toContain(
203+ "Use `listSkills` to browse and `readSkill` to load one SKILL.md on demand.",
204+ );
205+ expect(prompt).toContain("- deploy: Deploy safely (local)");
206+ expect(prompt).not.toContain("Detailed body");
207+ });
208+
209+ it("includes globally discovered skill metadata when homeDir is provided", () => {
210+ const skillDir = join(fakeHome, ".agents", "skills", "release");
211+ mkdirSync(skillDir, { recursive: true });
212+ writeFileSync(
213+ join(skillDir, "SKILL.md"),
214+ "---\nname: release\ndescription: Ship releases\n---\n\nRelease body",
215+ );
216+
217+ const prompt = buildSystemPrompt(
218+ "mock",
219+ tmpDir,
220+ undefined,
221+ undefined,
222+ fakeHome,
223+ );
224+ expect(prompt).toContain("- release: Ship releases (global)");
225+ expect(prompt).not.toContain("Release body");
226+ });
185227 });
src/agent/system-prompt.ts+11−0
@@ -2,6 +2,7 @@ import { existsSync, readFileSync } from "node:fs";
22 import { homedir } from "node:os";
33 import { join } from "node:path";
44 import { tildePath } from "../cli/output.ts";
5+import { loadSkillsIndex } from "../cli/skills.ts";
56
67 function tryReadFile(p: string): string | null {
78 if (!existsSync(p)) return null;
@@ -115,6 +116,16 @@ Guidelines:
115116 }
116117 }
117118
119+ const skills = Array.from(loadSkillsIndex(cwd, homeDir).values());
120+ if (skills.length > 0) {
121+ prompt += "\n\n# Available skills (metadata only)";
122+ prompt +=
123+ "\nUse `listSkills` to browse and `readSkill` to load one SKILL.md on demand.\n";
124+ for (const skill of skills) {
125+ prompt += `\n- ${skill.name}: ${skill.description} (${skill.source})`;
126+ }
127+ }
128+
118129 if (isSubagent) {
119130 prompt += `\n\n${SUBAGENT_DELEGATION}`;
120131 }
src/agent/tools.test.ts+25−1
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { hashLine } from "../tools/hashline.ts";
6-import { buildToolSet } from "./tools.ts";
6+import { buildReadOnlyToolSet, buildToolSet } from "./tools.ts";
77
88 let cwd = "";
99
@@ -101,3 +101,27 @@ describe("buildToolSet write hooks", () => {
101101 expect(result).not.toHaveProperty("_before");
102102 });
103103 });
104+
105+describe("skills tools registration", () => {
106+ test("includes listSkills and readSkill in full tool set", () => {
107+ const names = buildToolSet({
108+ cwd,
109+ runSubagent: async () => ({
110+ result: "ok",
111+ inputTokens: 0,
112+ outputTokens: 0,
113+ }),
114+ onHook: () => {},
115+ availableAgents: new Map(),
116+ }).map((tool) => tool.name);
117+
118+ expect(names).toContain("listSkills");
119+ expect(names).toContain("readSkill");
120+ });
121+
122+ test("includes listSkills and readSkill in read-only tool set", () => {
123+ const names = buildReadOnlyToolSet({ cwd }).map((tool) => tool.name);
124+ expect(names).toContain("listSkills");
125+ expect(names).toContain("readSkill");
126+ });
127+});
src/agent/tools.ts+5−0
@@ -25,6 +25,7 @@ import type { ReplaceToolOutput } from "../tools/replace.ts";
2525 import { replaceTool } from "../tools/replace.ts";
2626 import type { ShellOutput } from "../tools/shell.ts";
2727 import { shellTool } from "../tools/shell.ts";
28+import { listSkillsTool, readSkillTool } from "../tools/skills.ts";
2829 import { createSubagentTool, type SubagentOutput } from "../tools/subagent.ts";
2930 import {
3031 finalizeWriteResult,
@@ -165,6 +166,8 @@ export function buildToolSet(opts: {
165166 (_, input) => hookEnvForRead(input, cwd),
166167 onHook,
167168 ) as ToolDef,
169+ withCwdDefault(listSkillsTool as ToolDef, cwd),
170+ withCwdDefault(readSkillTool as ToolDef, cwd),
168171 // Write: create/overwrite, replace/delete, insert
169172 withHooks(
170173 withCwdDefault(
@@ -233,6 +236,8 @@ export function buildReadOnlyToolSet(opts: { cwd: string }): ToolDef[] {
233236 withCwdDefault(globTool as ToolDef, cwd),
234237 withCwdDefault(grepTool as ToolDef, cwd),
235238 withCwdDefault(readTool as ToolDef, cwd),
239+ withCwdDefault(listSkillsTool as ToolDef, cwd),
240+ withCwdDefault(readSkillTool as ToolDef, cwd),
236241 ];
237242
238243 if (process.env.EXA_API_KEY) {
src/cli/commands.ts+8−4
@@ -17,7 +17,7 @@ import { watchForCancel } from "./input.ts";
1717 import { renderMarkdown } from "./markdown.ts";
1818 import { PREFIX, write, writeln } from "./output.ts";
1919
20-import { loadSkills } from "./skills.ts";
20+import { loadSkillsIndex } from "./skills.ts";
2121
2222 // ─── Types ────────────────────────────────────────────────────────────────────
2323
@@ -619,10 +619,14 @@ function handleHelp(
619619 }
620620
621621 // Show skills
622- const skills = loadSkills(ctx.cwd);
622+ const skills = loadSkillsIndex(ctx.cwd);
623623 if (skills.size > 0) {
624624 writeln();
625- writeln(c.dim(" skills (~/.agents/skills/ or .agents/skills/):"));
625+ writeln(
626+ c.dim(
627+ " skills (walk-up local .agents/.claude/skills + global ~/.agents/skills ~/.claude/skills):",
628+ ),
629+ );
626630 for (const skill of skills.values()) {
627631 const tag =
628632 skill.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
@@ -637,7 +641,7 @@ function handleHelp(
637641 ` ${c.green("@agent".padEnd(26))} ${c.dim("run prompt through a custom agent (Tab to complete)")}`,
638642 );
639643 writeln(
640- ` ${c.green("@skill".padEnd(26))} ${c.dim("inject skill instructions into prompt (Tab to complete)")}`,
644+ ` ${c.green("@skill".padEnd(26))} ${c.dim("load a skill body on demand into the prompt (Tab to complete)")}`,
641645 );
642646 writeln(
643647 ` ${c.green("@file".padEnd(26))} ${c.dim("inject file contents into prompt (Tab to complete)")}`,
src/cli/file-refs.test.ts+35−0
@@ -0,0 +1,35 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { join } from "node:path";
4+import { resolveFileRefs } from "./file-refs.ts";
5+
6+describe("resolveFileRefs skill expansion", () => {
7+ let cwd: string;
8+
9+ beforeEach(() => {
10+ cwd = mkdtempSync("/tmp/mc-file-refs-test-");
11+ const skillDir = join(cwd, ".agents", "skills", "deploy");
12+ mkdirSync(skillDir, { recursive: true });
13+ writeFileSync(
14+ join(skillDir, "SKILL.md"),
15+ "---\nname: deploy\ndescription: Deploy steps\n---\n\nStep 1\nStep 2",
16+ );
17+ });
18+
19+ afterEach(() => {
20+ rmSync(cwd, { recursive: true, force: true });
21+ });
22+
23+ test("expands @skill references with raw SKILL.md content", async () => {
24+ const out = await resolveFileRefs("run @deploy now", cwd);
25+ expect(out.images).toEqual([]);
26+ expect(out.text).toContain('<skill name="deploy">');
27+ expect(out.text).toContain("name: deploy");
28+ expect(out.text).toContain("Step 2");
29+ });
30+
31+ test("leaves unknown @refs untouched", async () => {
32+ const out = await resolveFileRefs("run @missing now", cwd);
33+ expect(out.text).toBe("run @missing now");
34+ });
35+});
src/cli/file-refs.ts+13−5
@@ -4,7 +4,7 @@ import {
44 isImageFilename,
55 loadImageFile,
66 } from "./image-types.ts";
7-import { loadSkills } from "./skills.ts";
7+import { loadSkillContentFromMeta, loadSkillsIndex } from "./skills.ts";
88
99 export async function resolveFileRefs(
1010 text: string,
@@ -15,15 +15,23 @@ export async function resolveFileRefs(
1515 const matches = [...text.matchAll(atPattern)];
1616 const images: ImageAttachment[] = [];
1717
18- const skills = loadSkills(cwd);
18+ const skills = loadSkillsIndex(cwd);
19+ const loadedSkills = new Map<string, string>();
1920
2021 for (const match of [...matches].reverse()) {
2122 const ref = match[1];
2223 if (!ref) continue;
2324
24- const skill = skills.get(ref);
25- if (skill) {
26- const replacement = `<skill name="${skill.name}">\n${skill.content}\n</skill>`;
25+ const skillMeta = skills.get(ref);
26+ if (skillMeta) {
27+ let content = loadedSkills.get(skillMeta.name);
28+ if (!content) {
29+ const loaded = loadSkillContentFromMeta(skillMeta);
30+ if (!loaded) continue;
31+ content = loaded.content;
32+ loadedSkills.set(skillMeta.name, content);
33+ }
34+ const replacement = `<skill name="${skillMeta.name}">\n${content}\n</skill>`;
2735 result =
2836 result.slice(0, match.index) +
2937 replacement +
src/cli/input.ts+2−2
@@ -7,7 +7,7 @@ import {
77 isImageFilename,
88 loadImageFile,
99 } from "./image-types.ts";
10-import { loadSkills } from "./skills.ts";
10+import { loadSkillsIndex } from "./skills.ts";
1111 import { terminal } from "./terminal-io.ts";
1212
1313 // ─── ANSI escape sequences ────────────────────────────────────────────────────
@@ -66,7 +66,7 @@ async function getAtCompletions(
6666 const MAX = 10;
6767
6868 // Skills: @<skill-name>
69- const skills = loadSkills(cwd);
69+ const skills = loadSkillsIndex(cwd);
7070 for (const [name] of skills) {
7171 if (results.length >= MAX) break;
7272 if (name.includes(query)) results.push(`@${name}`);
src/cli/skills.test.ts+161−44
@@ -2,83 +2,200 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5-import { loadSkills } from "./skills.ts";
5+import { loadSkillContent, loadSkills, loadSkillsIndex } from "./skills.ts";
6+import { terminal } from "./terminal-io.ts";
67
7-describe("loadSkills", () => {
8+const originalStdoutWrite = terminal.stdoutWrite.bind(terminal);
9+
10+describe("skills loader", () => {
811 let dir: string;
12+ let fakeHome: string;
13+ let stdout = "";
914
1015 beforeEach(() => {
1116 dir = mkdtempSync(join(tmpdir(), "mc-skills-test-"));
17+ fakeHome = mkdtempSync(join(tmpdir(), "mc-skills-home-test-"));
18+ stdout = "";
19+ terminal.stdoutWrite = (chunk: string) => {
20+ stdout += chunk;
21+ };
1222 });
1323
1424 afterEach(() => {
25+ terminal.stdoutWrite = originalStdoutWrite;
1526 rmSync(dir, { recursive: true, force: true });
27+ rmSync(fakeHome, { recursive: true, force: true });
1628 });
1729
18- function writeSkill(root: string, folderName: string, content: string): void {
19- const skillDir = join(root, ".agents", "skills", folderName);
30+ function writeSkill(
31+ root: string,
32+ conventionDir: ".agents" | ".claude",
33+ folderName: string,
34+ content: string,
35+ ): void {
36+ const skillDir = join(root, conventionDir, "skills", folderName);
2037 mkdirSync(skillDir, { recursive: true });
2138 writeFileSync(join(skillDir, "SKILL.md"), content);
2239 }
2340
24- test("returns empty map when no .agents/skills dir exists", () => {
25- expect(loadSkills(dir).size).toBe(0);
41+ test("returns empty map when no skills directories exist", () => {
42+ expect(loadSkillsIndex(dir, fakeHome).size).toBe(0);
2643 });
2744
28- test("loads a skill with name and description from frontmatter", () => {
45+ test("loads metadata from index and reads full content on demand", () => {
46+ const raw =
47+ "---\nname: test-skill\ndescription: Test description\n---\n\nDo the thing.";
48+ writeSkill(dir, ".agents", "test-skill", raw);
49+
50+ const index = loadSkillsIndex(dir, fakeHome);
51+ expect(index.get("test-skill")?.description).toBe("Test description");
52+ expect(index.get("test-skill")?.source).toBe("local");
53+ expect(loadSkillContent("test-skill", dir, fakeHome)?.content).toBe(raw);
54+ });
55+
56+ test("discovers skills from parent directories when cwd is nested", () => {
2957 writeSkill(
3058 dir,
31- "git-release",
32- "---\nname: git-release\ndescription: Create consistent releases\n---\n\n# Instructions\nUse conventional commits.",
59+ ".agents",
60+ "root-skill",
61+ "---\nname: root-skill\ndescription: Found via walk-up\n---\nBody",
3362 );
34- const skills = loadSkills(dir);
35- const skill = skills.get("git-release");
36- expect(skill?.name).toBe("git-release");
37- expect(skill?.description).toBe("Create consistent releases");
38- expect(skill?.content).toContain("Use conventional commits.");
39- expect(skill?.source).toBe("local");
40- });
63+ const nested = join(dir, "packages", "service", "src");
64+ mkdirSync(join(dir, ".git"), { recursive: true });
65+ mkdirSync(nested, { recursive: true });
4166
42- test("falls back to folder name when frontmatter has no name", () => {
43- writeSkill(dir, "my-skill", "---\ndescription: A skill\n---\nContent.");
44- const skills = loadSkills(dir);
45- // key is name from frontmatter or folder name
46- expect(skills.get("my-skill")?.name).toBe("my-skill");
67+ const index = loadSkillsIndex(nested, fakeHome);
68+ expect(index.get("root-skill")?.description).toBe("Found via walk-up");
4769 });
4870
49- test("falls back to name as description when frontmatter has none", () => {
50- writeSkill(dir, "no-desc", "---\nname: no-desc\n---\nContent.");
51- expect(loadSkills(dir).get("no-desc")?.description).toBe("no-desc");
71+ test("does not traverse past cwd when outside a git repository", () => {
72+ const nested = join(dir, "pkg", "src");
73+ mkdirSync(nested, { recursive: true });
74+ writeSkill(
75+ dir,
76+ ".agents",
77+ "parent-skill",
78+ "---\nname: parent-skill\ndescription: should not be discovered\n---\nBody",
79+ );
80+
81+ const index = loadSkillsIndex(nested, fakeHome);
82+ expect(index.has("parent-skill")).toBe(false);
5283 });
5384
54- test("skill content includes the raw SKILL.md text", () => {
55- const raw =
56- "---\nname: test-skill\ndescription: Test\n---\n\nDo the thing.";
57- writeSkill(dir, "test-skill", raw);
58- expect(loadSkills(dir).get("test-skill")?.content).toBe(raw);
85+ test("applies precedence: nearest local > ancestor local > global and .agents > .claude", () => {
86+ const nestedRoot = join(dir, "apps", "api");
87+ const cwd = join(nestedRoot, "src");
88+ mkdirSync(cwd, { recursive: true });
89+ mkdirSync(join(dir, ".git"), { recursive: true });
90+
91+ writeSkill(
92+ fakeHome,
93+ ".claude",
94+ "deploy",
95+ "---\nname: deploy\ndescription: global claude\n---\ncontent",
96+ );
97+ writeSkill(
98+ fakeHome,
99+ ".agents",
100+ "deploy",
101+ "---\nname: deploy\ndescription: global agents\n---\ncontent",
102+ );
103+ writeSkill(
104+ dir,
105+ ".claude",
106+ "deploy",
107+ "---\nname: deploy\ndescription: ancestor claude\n---\ncontent",
108+ );
109+ writeSkill(
110+ dir,
111+ ".agents",
112+ "deploy",
113+ "---\nname: deploy\ndescription: ancestor agents\n---\ncontent",
114+ );
115+ writeSkill(
116+ nestedRoot,
117+ ".claude",
118+ "deploy",
119+ "---\nname: deploy\ndescription: nearest claude\n---\ncontent",
120+ );
121+ writeSkill(
122+ nestedRoot,
123+ ".agents",
124+ "deploy",
125+ "---\nname: deploy\ndescription: nearest agents\n---\ncontent",
126+ );
127+
128+ const index = loadSkillsIndex(cwd, fakeHome);
129+ const deploy = index.get("deploy");
130+ expect(deploy?.description).toBe("nearest agents");
131+ expect(deploy?.source).toBe("local");
132+ expect(deploy?.rootPath).toBe(nestedRoot);
59133 });
60134
61- test("ignores entries without a SKILL.md", () => {
62- const skillDir = join(dir, ".agents", "skills", "empty-folder");
63- mkdirSync(skillDir, { recursive: true });
64- expect(loadSkills(dir).size).toBe(0);
135+ test("conflict warnings use frontmatter skill names, not folder names", () => {
136+ writeSkill(
137+ dir,
138+ ".claude",
139+ "claude-folder",
140+ "---\nname: same-skill\ndescription: from claude\n---\ncontent",
141+ );
142+ writeSkill(
143+ dir,
144+ ".agents",
145+ "agents-folder",
146+ "---\nname: same-skill\ndescription: from agents\n---\ncontent",
147+ );
148+
149+ loadSkillsIndex(dir, fakeHome);
150+ expect(stdout).toContain("conflicting skills in local .agents and .claude");
151+ expect(stdout).toContain("same-skill");
152+ expect(stdout).not.toContain("agents-folder");
153+ expect(stdout).not.toContain("claude-folder");
65154 });
66155
67- test("ignores non-directory entries in skills dir", () => {
68- const skillsDir = join(dir, ".agents", "skills");
69- mkdirSync(skillsDir, { recursive: true });
70- writeFileSync(join(skillsDir, "not-a-dir.md"), "stuff");
71- expect(loadSkills(dir).size).toBe(0);
156+ test("skips invalid skills but tolerates unknown frontmatter fields", () => {
157+ writeSkill(
158+ dir,
159+ ".agents",
160+ "missing-name",
161+ "---\ndescription: Missing name\n---\ncontent",
162+ );
163+ writeSkill(
164+ dir,
165+ ".agents",
166+ "missing-description",
167+ "---\nname: missing-description\n---\ncontent",
168+ );
169+ writeSkill(
170+ dir,
171+ ".agents",
172+ "bad-format",
173+ "---\nname: Bad_Name\ndescription: bad\n---\ncontent",
174+ );
175+ writeSkill(
176+ dir,
177+ ".agents",
178+ "valid-skill",
179+ "---\nname: valid-skill\ndescription: valid\nowner: team\n---\ncontent",
180+ );
181+
182+ const index = loadSkillsIndex(dir, fakeHome);
183+ expect(index.has("missing-name")).toBe(false);
184+ expect(index.has("missing-description")).toBe(false);
185+ expect(index.has("Bad_Name")).toBe(false);
186+ expect(index.get("valid-skill")?.description).toBe("valid");
72187 });
73188
74- test("local skill overrides global with same name", () => {
189+ test("compatibility loadSkills still returns full records", () => {
75190 writeSkill(
76191 dir,
77- "git-release",
78- "---\nname: git-release\ndescription: local version\n---\nLocal content.",
192+ ".agents",
193+ "compat-skill",
194+ "---\nname: compat-skill\ndescription: compat\n---\ncompat body",
79195 );
80- const skills = loadSkills(dir);
81- expect(skills.get("git-release")?.description).toBe("local version");
82- expect(skills.get("git-release")?.source).toBe("local");
196+
197+ const skills = loadSkills(dir, fakeHome);
198+ expect(skills.get("compat-skill")?.description).toBe("compat");
199+ expect(skills.get("compat-skill")?.content).toContain("compat body");
83200 });
84201 });
src/cli/skills.ts+291−22
@@ -1,31 +1,300 @@
1-// ─── Types ────────────────────────────────────────────────────────────────────
1+import {
2+ closeSync,
3+ existsSync,
4+ openSync,
5+ readdirSync,
6+ readFileSync,
7+ readSync,
8+ statSync,
9+} from "node:fs";
10+import { homedir } from "node:os";
11+import { dirname, join, resolve } from "node:path";
12+import { warnConventionConflicts } from "./config-conflicts.ts";
13+import { G, writeln } from "./output.ts";
214
3-import { loadMarkdownConfigs } from "./load-markdown-configs.ts";
4-
5-interface Skill {
15+export interface SkillMeta {
616 name: string;
717 description: string;
8- /** Full content of the SKILL.md (frontmatter + body) */
18+ source: "global" | "local";
19+ rootPath: string;
20+ filePath: string;
21+}
22+
23+interface SkillRecord extends SkillMeta {
24+ content: string;
25+}
26+
27+export interface LoadedSkillContent {
28+ name: string;
929 content: string;
10- /** "global" (~/.agents/) or "local" (./.agents/) — local wins on conflict */
1130 source: "global" | "local";
1231 }
1332
14-// ─── Load all skills (global + local, local wins) ────────────────────────────
15-
16-export function loadSkills(cwd: string, homeDir?: string): Map<string, Skill> {
17- return loadMarkdownConfigs<Skill>({
18- type: "skills",
19- strategy: "nested",
20- nestedFileName: "SKILL.md",
21- cwd,
22- homeDir,
23- includeClaudeDirs: true,
24- mapConfig: ({ name, meta, raw, source }) => ({
25- name,
26- description: meta.description ?? name,
27- content: raw,
33+const MAX_FRONTMATTER_BYTES = 64 * 1024;
34+const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
35+const MIN_SKILL_NAME_LENGTH = 1;
36+const MAX_SKILL_NAME_LENGTH = 64;
37+const warnedInvalidSkills = new Set<string>();
38+
39+type SkillCandidate = {
40+ folderName: string;
41+ filePath: string;
42+ rootPath: string;
43+ source: "global" | "local";
44+ frontmatter?: SkillFrontmatter;
45+};
46+
47+type SkillFrontmatter = {
48+ name?: string;
49+ description?: string;
50+};
51+
52+function parseSkillFrontmatter(filePath: string): SkillFrontmatter {
53+ let fd: number | null = null;
54+ try {
55+ fd = openSync(filePath, "r");
56+ const chunk = Buffer.allocUnsafe(MAX_FRONTMATTER_BYTES);
57+ const bytesRead = readSync(fd, chunk, 0, MAX_FRONTMATTER_BYTES, 0);
58+ const text = chunk.toString("utf8", 0, bytesRead);
59+ const lines = text.split("\n");
60+ if ((lines[0] ?? "").trim() !== "---") return {};
61+
62+ const meta: SkillFrontmatter = {};
63+ for (let i = 1; i < lines.length; i++) {
64+ const line = (lines[i] ?? "").replace(/\r$/, "");
65+ if (line.trim() === "---") break;
66+ const colon = line.indexOf(":");
67+ if (colon === -1) continue;
68+ const key = line.slice(0, colon).trim();
69+ const value = line
70+ .slice(colon + 1)
71+ .trim()
72+ .replace(/^["']|["']$/g, "");
73+ if (key === "name") meta.name = value;
74+ if (key === "description") meta.description = value;
75+ }
76+ return meta;
77+ } catch {
78+ return {};
79+ } finally {
80+ if (fd !== null) closeSync(fd);
81+ }
82+}
83+
84+function getCandidateFrontmatter(candidate: SkillCandidate): SkillFrontmatter {
85+ if (!candidate.frontmatter) {
86+ candidate.frontmatter = parseSkillFrontmatter(candidate.filePath);
87+ }
88+ return candidate.frontmatter;
89+}
90+
91+function candidateConflictName(candidate: SkillCandidate): string {
92+ return (
93+ getCandidateFrontmatter(candidate).name?.trim() || candidate.folderName
94+ );
95+}
96+
97+function findGitBoundary(cwd: string): string | null {
98+ let current = resolve(cwd);
99+ while (true) {
100+ if (existsSync(join(current, ".git"))) return current;
101+ const parent = dirname(current);
102+ if (parent === current) return null;
103+ current = parent;
104+ }
105+}
106+
107+function localSearchRoots(cwd: string): string[] {
108+ const start = resolve(cwd);
109+ const stop = findGitBoundary(start);
110+ if (!stop) return [start];
111+ const roots: string[] = [];
112+ let current = start;
113+ while (true) {
114+ roots.push(current);
115+ if (current === stop) break;
116+ const parent = dirname(current);
117+ if (parent === current) break;
118+ current = parent;
119+ }
120+ return roots;
121+}
122+
123+function listSkillCandidates(
124+ skillsDir: string,
125+ source: "global" | "local",
126+ rootPath: string,
127+): SkillCandidate[] {
128+ if (!existsSync(skillsDir)) return [];
129+ let entries: string[];
130+ try {
131+ entries = readdirSync(skillsDir).sort((a, b) => a.localeCompare(b));
132+ } catch {
133+ return [];
134+ }
135+ const candidates: SkillCandidate[] = [];
136+ for (const entry of entries) {
137+ const skillDir = join(skillsDir, entry);
138+ try {
139+ if (!statSync(skillDir).isDirectory()) continue;
140+ } catch {
141+ continue;
142+ }
143+ const filePath = join(skillDir, "SKILL.md");
144+ if (!existsSync(filePath)) continue;
Cut short: this commit's diff is over 1000 lines.
src/tools/skills.test.ts+43−0
Cut short: this commit's diff is over 1000 lines.
src/tools/skills.ts+50−0
Cut short: this commit's diff is over 1000 lines.