xonecas.io
64875
Mc

mini-coder / commit cfb9c9c

feat: implement Phase 2 — skills discovery and system prompt assembly

xonecas2026-04-05 cfb9c9c5c5411933a6a4543ec7bcad4e120e9f67 parent 9d9012e

4 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.

src/prompt.test.ts+370−0
@@ -0,0 +1,370 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join, resolve } from "node:path";
5+import type { GitState } from "./git.ts";
6+import {
7+ buildSystemPrompt,
8+ discoverAgentsMd,
9+ formatGitLine,
10+} from "./prompt.ts";
11+import type { Skill } from "./skills.ts";
12+
13+// ---------------------------------------------------------------------------
14+// Helpers
15+// ---------------------------------------------------------------------------
16+
17+let tmp: string;
18+
19+beforeEach(() => {
20+ tmp = mkdtempSync(join(tmpdir(), "mc-prompt-"));
21+});
22+
23+afterEach(() => {
24+ rmSync(tmp, { recursive: true, force: true });
25+});
26+
27+// ---------------------------------------------------------------------------
28+// discoverAgentsMd
29+// ---------------------------------------------------------------------------
30+
31+describe("discoverAgentsMd", () => {
32+ test("finds AGENTS.md walking from cwd to scan root", () => {
33+ writeFileSync(join(tmp, "AGENTS.md"), "Root instructions");
34+ mkdirSync(join(tmp, "src"), { recursive: true });
35+ writeFileSync(join(tmp, "src", "AGENTS.md"), "Src instructions");
36+
37+ const cwd = join(tmp, "src");
38+ const root = resolve(tmp);
39+ const files = discoverAgentsMd(cwd, root);
40+
41+ // Should be ordered root-to-leaf
42+ expect(files).toHaveLength(2);
43+ expect(files[0]!.path).toBe(join(tmp, "AGENTS.md"));
44+ expect(files[0]!.content).toBe("Root instructions");
45+ expect(files[1]!.path).toBe(join(tmp, "src", "AGENTS.md"));
46+ expect(files[1]!.content).toBe("Src instructions");
47+ });
48+
49+ test("returns empty array when no files found", () => {
50+ const files = discoverAgentsMd(tmp, resolve(tmp));
51+ expect(files).toEqual([]);
52+ });
53+
54+ test("checks globalAgentsDir for global agent instructions", () => {
55+ const globalDir = join(tmp, "global-agents");
56+ mkdirSync(globalDir, { recursive: true });
57+ writeFileSync(join(globalDir, "AGENTS.md"), "Global instructions");
58+
59+ writeFileSync(join(tmp, "AGENTS.md"), "Project instructions");
60+
61+ const files = discoverAgentsMd(tmp, resolve(tmp), globalDir);
62+
63+ // Global instructions come first (general → specific)
64+ expect(files).toHaveLength(2);
65+ expect(files[0]!.content).toBe("Global instructions");
66+ expect(files[1]!.content).toBe("Project instructions");
67+ });
68+
69+ test("does not walk above the scan root", () => {
70+ const parent = join(tmp, "parent");
71+ const child = join(parent, "child");
72+ mkdirSync(child, { recursive: true });
73+
74+ // Put AGENTS.md above scan root — should NOT be found
75+ writeFileSync(join(tmp, "AGENTS.md"), "Above root");
76+ // Put AGENTS.md at scan root — should be found
77+ writeFileSync(join(parent, "AGENTS.md"), "At root");
78+
79+ const files = discoverAgentsMd(child, resolve(parent));
80+ expect(files).toHaveLength(1);
81+ expect(files[0]!.content).toBe("At root");
82+ });
83+
84+ test("orders files root-to-leaf (general → specific)", () => {
85+ const deep = join(tmp, "a", "b", "c");
86+ mkdirSync(deep, { recursive: true });
87+
88+ writeFileSync(join(tmp, "AGENTS.md"), "level-0");
89+ writeFileSync(join(tmp, "a", "AGENTS.md"), "level-1");
90+ writeFileSync(join(tmp, "a", "b", "AGENTS.md"), "level-2");
91+
92+ const files = discoverAgentsMd(join(tmp, "a", "b"), resolve(tmp));
93+ expect(files).toHaveLength(3);
94+ expect(files[0]!.content).toBe("level-0");
95+ expect(files[1]!.content).toBe("level-1");
96+ expect(files[2]!.content).toBe("level-2");
97+ });
98+});
99+
100+// ---------------------------------------------------------------------------
101+// formatGitLine
102+// ---------------------------------------------------------------------------
103+
104+describe("formatGitLine", () => {
105+ test("formats full git state", () => {
106+ const state: GitState = {
107+ root: "/repo",
108+ branch: "main",
109+ staged: 3,
110+ modified: 1,
111+ untracked: 2,
112+ ahead: 5,
113+ behind: 2,
114+ };
115+
116+ const line = formatGitLine(state);
117+ expect(line).toBe(
118+ "Git: branch main | 3 staged, 1 modified, 2 untracked | +5 −2 vs origin/main",
119+ );
120+ });
121+
122+ test("omits staged/modified/untracked when all zero", () => {
123+ const state: GitState = {
124+ root: "/repo",
125+ branch: "main",
126+ staged: 0,
127+ modified: 0,
128+ untracked: 0,
129+ ahead: 0,
130+ behind: 0,
131+ };
132+
133+ const line = formatGitLine(state);
134+ expect(line).toBe("Git: branch main");
135+ });
136+
137+ test("omits fields that are zero", () => {
138+ const state: GitState = {
139+ root: "/repo",
140+ branch: "feature",
141+ staged: 0,
142+ modified: 2,
143+ untracked: 0,
144+ ahead: 0,
145+ behind: 0,
146+ };
147+
148+ const line = formatGitLine(state);
149+ expect(line).toBe("Git: branch feature | 2 modified");
150+ });
151+
152+ test("omits ahead/behind when both zero", () => {
153+ const state: GitState = {
154+ root: "/repo",
155+ branch: "dev",
156+ staged: 1,
157+ modified: 0,
158+ untracked: 0,
159+ ahead: 0,
160+ behind: 0,
161+ };
162+
163+ const line = formatGitLine(state);
164+ expect(line).toBe("Git: branch dev | 1 staged");
165+ });
166+
167+ test("shows only ahead when behind is zero", () => {
168+ const state: GitState = {
169+ root: "/repo",
170+ branch: "main",
171+ staged: 0,
172+ modified: 0,
173+ untracked: 0,
174+ ahead: 3,
175+ behind: 0,
176+ };
177+
178+ const line = formatGitLine(state);
179+ expect(line).toBe("Git: branch main | +3 vs origin/main");
180+ });
181+
182+ test("shows only behind when ahead is zero", () => {
183+ const state: GitState = {
184+ root: "/repo",
185+ branch: "main",
186+ staged: 0,
187+ modified: 0,
188+ untracked: 0,
189+ ahead: 0,
190+ behind: 4,
191+ };
192+
193+ const line = formatGitLine(state);
194+ expect(line).toBe("Git: branch main | −4 vs origin/main");
195+ });
196+});
197+
198+// ---------------------------------------------------------------------------
199+// buildSystemPrompt
200+// ---------------------------------------------------------------------------
201+
202+describe("buildSystemPrompt", () => {
203+ test("includes base instructions", () => {
204+ const prompt = buildSystemPrompt({
205+ cwd: "/home/user/project",
206+ date: "2026-04-05",
207+ });
208+
209+ expect(prompt).toContain("You are mini-coder");
210+ expect(prompt).toContain("# Role");
211+ expect(prompt).toContain("# Tools");
212+ expect(prompt).toContain("# Code quality");
213+ expect(prompt).toContain("# Editing discipline");
214+ expect(prompt).toContain("# Communication");
215+ expect(prompt).toContain("# Persistence");
216+ });
217+
218+ test("includes session footer with date and cwd", () => {
219+ const prompt = buildSystemPrompt({
220+ cwd: "/home/user/project",
221+ date: "2026-04-05",
222+ });
223+
224+ expect(prompt).toContain("Current date: 2026-04-05");
225+ expect(prompt).toContain("Current working directory: /home/user/project");
226+ });
227+
228+ test("includes git line when git state provided", () => {
229+ const prompt = buildSystemPrompt({
230+ cwd: "/home/user/project",
231+ date: "2026-04-05",
232+ git: {
233+ root: "/home/user/project",
234+ branch: "main",
235+ staged: 3,
236+ modified: 1,
237+ untracked: 2,
238+ ahead: 5,
239+ behind: 2,
240+ },
241+ });
242+
243+ expect(prompt).toContain("Git: branch main");
244+ });
245+
246+ test("omits git line when git state is null", () => {
247+ const prompt = buildSystemPrompt({
248+ cwd: "/tmp/no-repo",
249+ date: "2026-04-05",
250+ git: null,
251+ });
252+
253+ expect(prompt).not.toContain("Git:");
254+ });
255+
256+ test("includes AGENTS.md content when provided", () => {
257+ const prompt = buildSystemPrompt({
258+ cwd: "/project",
259+ date: "2026-04-05",
260+ agentsMd: [
261+ {
262+ path: "/project/AGENTS.md",
263+ content: "Always use TypeScript strict mode.",
264+ },
265+ ],
266+ });
267+
268+ expect(prompt).toContain("# Project Context");
269+ expect(prompt).toContain("## /project/AGENTS.md");
270+ expect(prompt).toContain("Always use TypeScript strict mode.");
271+ });
272+
273+ test("includes multiple AGENTS.md files in order", () => {
274+ const prompt = buildSystemPrompt({
275+ cwd: "/project/src",
276+ date: "2026-04-05",
277+ agentsMd: [
278+ { path: "/project/AGENTS.md", content: "Root rules" },
279+ { path: "/project/src/AGENTS.md", content: "Src rules" },
280+ ],
281+ });
282+
283+ const rootIdx = prompt.indexOf("Root rules");
284+ const srcIdx = prompt.indexOf("Src rules");
285+ expect(rootIdx).toBeGreaterThan(-1);
286+ expect(srcIdx).toBeGreaterThan(rootIdx);
287+ });
288+
289+ test("includes skill catalog when skills provided", () => {
290+ const skills: Skill[] = [
291+ {
292+ name: "deploy",
293+ description: "Deploy the app.",
294+ path: "/project/.agents/skills/deploy/SKILL.md",
295+ },
296+ ];
297+
298+ const prompt = buildSystemPrompt({
299+ cwd: "/project",
300+ date: "2026-04-05",
301+ skills,
302+ });
303+
304+ expect(prompt).toContain("<available_skills>");
305+ expect(prompt).toContain("<name>deploy</name>");
306+ });
307+
308+ test("includes plugin suffixes when provided", () => {
309+ const prompt = buildSystemPrompt({
310+ cwd: "/project",
311+ date: "2026-04-05",
312+ pluginSuffixes: [
313+ "MCP server connected: github",
314+ "Custom tool: jira-query",
315+ ],
316+ });
317+
318+ expect(prompt).toContain("MCP server connected: github");
319+ expect(prompt).toContain("Custom tool: jira-query");
320+ });
321+
322+ test("assembly order: base → agents.md → skills → plugins → footer", () => {
323+ const skills: Skill[] = [
324+ {
325+ name: "test",
326+ description: "Test skill.",
327+ path: "/path/SKILL.md",
328+ },
329+ ];
330+
331+ const prompt = buildSystemPrompt({
332+ cwd: "/project",
333+ date: "2026-04-05",
334+ agentsMd: [{ path: "/project/AGENTS.md", content: "Project rules" }],
335+ skills,
336+ pluginSuffixes: ["Plugin context here"],
337+ git: {
338+ root: "/project",
339+ branch: "main",
340+ staged: 0,
341+ modified: 0,
342+ untracked: 0,
343+ ahead: 0,
344+ behind: 0,
345+ },
346+ });
347+
348+ // Verify ordering
349+ const baseIdx = prompt.indexOf("You are mini-coder");
350+ const agentsIdx = prompt.indexOf("Project rules");
351+ const skillsIdx = prompt.indexOf("<available_skills>");
352+ const pluginIdx = prompt.indexOf("Plugin context here");
353+ const footerIdx = prompt.indexOf("Current date:");
354+
355+ expect(baseIdx).toBeGreaterThan(-1);
356+ expect(agentsIdx).toBeGreaterThan(baseIdx);
357+ expect(skillsIdx).toBeGreaterThan(agentsIdx);
358+ expect(pluginIdx).toBeGreaterThan(skillsIdx);
359+ expect(footerIdx).toBeGreaterThan(pluginIdx);
360+ });
361+
362+ test("does not mention readImage in base instructions", () => {
363+ const prompt = buildSystemPrompt({
364+ cwd: "/project",
365+ date: "2026-04-05",
366+ });
367+
368+ expect(prompt).not.toContain("readImage");
369+ });
370+});
src/prompt.ts+261−0
@@ -0,0 +1,261 @@
1+/**
2+ * System prompt construction.
3+ *
4+ * Assembles the full system prompt from static base instructions and
5+ * dynamic context: AGENTS.md files, skill catalog, plugin suffixes,
6+ * and a session footer with date, CWD, and git state.
7+ *
8+ * @module
9+ */
10+
11+import { existsSync, readFileSync } from "node:fs";
12+import { dirname, join, resolve } from "node:path";
13+import type { GitState } from "./git.ts";
14+import { buildSkillCatalog, type Skill } from "./skills.ts";
15+
16+// ---------------------------------------------------------------------------
17+// Types
18+// ---------------------------------------------------------------------------
19+
20+/** A discovered AGENTS.md file with its content. */
21+export interface AgentsMdFile {
22+ /** Absolute path to the file. */
23+ path: string;
24+ /** Raw file content. */
25+ content: string;
26+}
27+
28+/** Options for building the system prompt. */
29+export interface BuildSystemPromptOpts {
30+ /** Current working directory. */
31+ cwd: string;
32+ /** Current date string (YYYY-MM-DD). */
33+ date: string;
34+ /** Git repository state, or `null`/`undefined` if not in a repo. */
35+ git?: GitState | null;
36+ /** Discovered AGENTS.md files, ordered root-to-leaf. */
37+ agentsMd?: AgentsMdFile[];
38+ /** Discovered agent skills. */
39+ skills?: Skill[];
40+ /** Plugin system prompt suffixes. */
41+ pluginSuffixes?: string[];
42+}
43+
44+// ---------------------------------------------------------------------------
45+// AGENTS.md discovery
46+// ---------------------------------------------------------------------------
47+
48+/** File name to look for during the AGENTS.md walk. */
49+const AGENT_FILENAME = "AGENTS.md";
50+
51+/**
52+ * Walk from `cwd` up to `scanRoot`, collecting AGENTS.md files.
53+ *
54+ * Also checks `globalAgentsDir` for global agent instructions when provided.
55+ * Results are ordered root-to-leaf (general → specific), with global
56+ * instructions first when present.
57+ *
58+ * @param cwd - Starting directory for the walk.
59+ * @param scanRoot - Uppermost directory to include in the walk.
60+ * @param globalAgentsDir - Optional directory for global agent instructions (e.g. `~/.agents/`).
61+ * @returns Array of {@link AgentsMdFile} records, ordered general → specific.
62+ */
63+export function discoverAgentsMd(
64+ cwd: string,
65+ scanRoot: string,
66+ globalAgentsDir?: string,
67+): AgentsMdFile[] {
68+ const root = resolve(scanRoot);
69+ const start = resolve(cwd);
70+
71+ // Collect directories from scanRoot to cwd
72+ const dirs: string[] = [];
73+ let current = start;
74+ while (true) {
75+ dirs.push(current);
76+ if (current === root) break;
77+ const parent = dirname(current);
78+ // Safety: stop if we can't go higher (e.g., filesystem root)
79+ if (parent === current) break;
80+ current = parent;
81+ }
82+
83+ // Reverse so we go root-to-leaf
84+ dirs.reverse();
85+
86+ // Collect files from the global agents dir first
87+ const files: AgentsMdFile[] = [];
88+
89+ if (globalAgentsDir) {
90+ const filePath = join(globalAgentsDir, AGENT_FILENAME);
91+ if (existsSync(filePath)) {
92+ files.push({
93+ path: filePath,
94+ content: readFileSync(filePath, "utf-8"),
95+ });
96+ }
97+ }
98+
99+ // Walk from root to cwd
100+ for (const dir of dirs) {
101+ const filePath = join(dir, AGENT_FILENAME);
102+ if (existsSync(filePath)) {
103+ files.push({
104+ path: filePath,
105+ content: readFileSync(filePath, "utf-8"),
106+ });
107+ }
108+ }
109+
110+ return files;
111+}
112+
113+// ---------------------------------------------------------------------------
114+// Git line formatting
115+// ---------------------------------------------------------------------------
116+
117+/**
118+ * Format a git state snapshot into a single-line string for the session footer.
119+ *
120+ * Fields are omitted when their values are zero. The git line format:
121+ * `Git: branch main | 3 staged, 1 modified, 2 untracked | +5 −2 vs origin/main`
122+ *
123+ * @param state - The git state to format.
124+ * @returns Formatted git status line.
125+ */
126+export function formatGitLine(state: GitState): string {
127+ const parts: string[] = [`Git: branch ${state.branch}`];
128+
129+ // Working tree counts
130+ const counts: string[] = [];
131+ if (state.staged > 0) counts.push(`${state.staged} staged`);
132+ if (state.modified > 0) counts.push(`${state.modified} modified`);
133+ if (state.untracked > 0) counts.push(`${state.untracked} untracked`);
134+ if (counts.length > 0) parts.push(counts.join(", "));
135+
136+ // Ahead/behind
137+ if (state.ahead > 0 || state.behind > 0) {
138+ const ab: string[] = [];
139+ if (state.ahead > 0) ab.push(`+${state.ahead}`);
140+ if (state.behind > 0) ab.push(`\u2212${state.behind}`);
141+ parts.push(`${ab.join(" ")} vs origin/${state.branch}`);
142+ }
143+
144+ return parts.join(" | ");
145+}
146+
147+// ---------------------------------------------------------------------------
148+// Base instructions
149+// ---------------------------------------------------------------------------
150+
151+const BASE_INSTRUCTIONS = `You are mini-coder, a coding agent running in the user's terminal.
152+
153+# Role
154+
155+You are an autonomous, senior-level coding assistant. When the user gives a direction, proactively gather context, plan, implement, and verify without waiting for additional prompts at each step. Bias toward action: make reasonable assumptions and deliver working code rather than asking clarifying questions, unless you are genuinely blocked.
156+
157+# Tools
158+
159+You have these core tools:
160+
161+- \`shell\` — run commands in the user's shell. Use this to explore the codebase (rg, find, ls, cat), run tests, build, git, and any other command. Prefer \`rg\` over \`grep\` for speed.
162+- \`edit\` — make exact-text replacements in files. Provide the file path, the exact text to find, and the replacement text. The old text must match exactly one location in the file. To create a new file, use an empty old text and the full file content as new text.
163+
164+You may also have additional tools provided by plugins. Use them when they match the task.
165+
166+Workflow: **inspect with shell → mutate with edit → verify with shell**.
167+
168+# Code quality
169+
170+- Conform to the codebase's existing conventions: patterns, naming, formatting, language idioms.
171+- Write correct, clear, minimal code. Don't over-engineer, don't add abstractions for hypothetical futures.
172+- Reuse before creating. Search for existing helpers before writing new ones.
173+- Tight error handling: no broad try/catch, no silent failures, no swallowed errors.
174+- Keep type safety. Avoid \`any\` casts. Use proper types and guards.
175+- Only add comments where the logic isn't self-evident.
176+
177+# Editing discipline
178+
179+- Read enough context before editing. Batch logical changes together rather than making many small edits.
180+- Never revert changes you didn't make unless explicitly asked.
181+- Never use destructive git commands (reset --hard, checkout --, clean -fd) unless the user requests it.
182+- Default to ASCII. Only use non-ASCII characters when the file already uses them or there's clear justification.
183+
184+# Exploring the codebase
185+
186+- Think first: before any tool call, decide all files and information you need.
187+- Batch reads: if you need multiple files, read them together in parallel rather than one at a time.
188+- Only make sequential calls when a later call genuinely depends on an earlier result.
189+
190+# Communication
191+
192+- Be concise. Friendly coding teammate tone.
193+- After making changes: lead with a quick explanation of what changed and why, then suggest logical next steps if any.
194+- Don't dump large file contents you've written — reference file paths.
195+- When suggesting multiple options, use numbered lists so the user can reply with a number.
196+- If asked for a review, focus on bugs, risks, regressions, and missing tests. Findings first, ordered by severity.
197+
198+# Persistence
199+
200+- Carry work through to completion within the current turn. Don't stop at analysis or partial fixes.
201+- If you encounter an error, diagnose and fix it rather than reporting it and stopping.
202+- Avoid excessive looping: if you're re-reading or re-editing the same files without progress, stop and ask the user.`;
203+
204+// ---------------------------------------------------------------------------
205+// System prompt assembly
206+// ---------------------------------------------------------------------------
207+
208+/**
209+ * Build the full system prompt.
210+ *
211+ * Assembly order:
212+ * 1. Base instructions (static)
213+ * 2. AGENTS.md content (project-specific)
214+ * 3. Skills catalog (XML)
215+ * 4. Plugin suffixes
216+ * 5. Session footer (date, CWD, git)
217+ *
218+ * @param opts - Prompt construction options.
219+ * @returns The assembled system prompt string.
220+ */
221+export function buildSystemPrompt(opts: BuildSystemPromptOpts): string {
222+ const sections: string[] = [BASE_INSTRUCTIONS];
223+
224+ // 2. AGENTS.md content
225+ if (opts.agentsMd && opts.agentsMd.length > 0) {
226+ const agentsSection = [
227+ "\n# Project Context\n",
228+ "Project-specific instructions and guidelines:\n",
229+ ];
230+ for (const file of opts.agentsMd) {
231+ agentsSection.push(`## ${file.path}\n`);
232+ agentsSection.push(file.content);
233+ agentsSection.push("");
234+ }
235+ sections.push(agentsSection.join("\n"));
236+ }
237+
238+ // 3. Skills catalog
239+ if (opts.skills && opts.skills.length > 0) {
240+ const catalog = buildSkillCatalog(opts.skills);
241+ if (catalog) sections.push(catalog);
242+ }
243+
244+ // 4. Plugin suffixes
245+ if (opts.pluginSuffixes) {
246+ for (const suffix of opts.pluginSuffixes) {
247+ sections.push(suffix);
248+ }
249+ }
250+
251+ // 5. Session footer
252+ const footer: string[] = [];
253+ footer.push(`Current date: ${opts.date}`);
254+ footer.push(`Current working directory: ${opts.cwd}`);
255+ if (opts.git) {
256+ footer.push(formatGitLine(opts.git));
257+ }
258+ sections.push(footer.join("\n"));
259+
260+ return sections.join("\n");
261+}
src/skills.test.ts+270−0
@@ -0,0 +1,270 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { buildSkillCatalog, discoverSkills, type Skill } from "./skills.ts";
6+
7+// ---------------------------------------------------------------------------
8+// Helpers
9+// ---------------------------------------------------------------------------
10+
11+let tmp: string;
12+
13+beforeEach(() => {
14+ tmp = mkdtempSync(join(tmpdir(), "mc-skills-"));
15+});
16+
17+afterEach(() => {
18+ rmSync(tmp, { recursive: true, force: true });
19+});
20+
21+/** Create a SKILL.md file in a skill directory. */
22+function writeSkill(basePath: string, name: string, content: string): string {
23+ const dir = join(basePath, name);
24+ mkdirSync(dir, { recursive: true });
25+ const path = join(dir, "SKILL.md");
26+ writeFileSync(path, content);
27+ return path;
28+}
29+
30+// ---------------------------------------------------------------------------
31+// discoverSkills
32+// ---------------------------------------------------------------------------
33+
34+describe("discoverSkills", () => {
35+ test("discovers skills from a single scan path", () => {
36+ writeSkill(
37+ tmp,
38+ "code-review",
39+ [
40+ "---",
41+ "name: code-review",
42+ 'description: "Review code for bugs."',
43+ "---",
44+ "",
45+ "# Code Review",
46+ "Do a review.",
47+ ].join("\n"),
48+ );
49+
50+ const skills = discoverSkills([tmp]);
51+ expect(skills).toHaveLength(1);
52+ expect(skills[0]!.name).toBe("code-review");
53+ expect(skills[0]!.description).toBe("Review code for bugs.");
54+ expect(skills[0]!.path).toBe(join(tmp, "code-review", "SKILL.md"));
55+ });
56+
57+ test("discovers skills from multiple scan paths", () => {
58+ const path1 = join(tmp, "scan1");
59+ const path2 = join(tmp, "scan2");
60+ writeSkill(
61+ path1,
62+ "skill-a",
63+ ["---", "name: skill-a", "description: First skill", "---"].join("\n"),
64+ );
65+ writeSkill(
66+ path2,
67+ "skill-b",
68+ ["---", "name: skill-b", "description: Second skill", "---"].join("\n"),
69+ );
70+
71+ const skills = discoverSkills([path1, path2]);
72+ expect(skills).toHaveLength(2);
73+ const names = skills.map((s) => s.name);
74+ expect(names).toContain("skill-a");
75+ expect(names).toContain("skill-b");
76+ });
77+
78+ test("project-level skill overrides user-level on name collision", () => {
79+ // Earlier paths in the array have higher priority (project-level first)
80+ const project = join(tmp, "project");
81+ const user = join(tmp, "user");
82+ writeSkill(
83+ project,
84+ "deploy",
85+ ["---", "name: deploy", "description: Project deploy", "---"].join("\n"),
86+ );
87+ writeSkill(
88+ user,
89+ "deploy",
90+ ["---", "name: deploy", "description: User deploy", "---"].join("\n"),
91+ );
92+
93+ const skills = discoverSkills([project, user]);
94+ expect(skills).toHaveLength(1);
95+ expect(skills[0]!.description).toBe("Project deploy");
96+ expect(skills[0]!.path).toBe(join(project, "deploy", "SKILL.md"));
97+ });
98+
99+ test("ignores directories without SKILL.md", () => {
100+ mkdirSync(join(tmp, "no-skill"), { recursive: true });
101+ writeFileSync(join(tmp, "no-skill", "README.md"), "not a skill");
102+ writeSkill(
103+ tmp,
104+ "real-skill",
105+ ["---", "name: real-skill", "description: A real skill", "---"].join(
106+ "\n",
107+ ),
108+ );
109+
110+ const skills = discoverSkills([tmp]);
111+ expect(skills).toHaveLength(1);
112+ expect(skills[0]!.name).toBe("real-skill");
113+ });
114+
115+ test("returns empty array when scan paths do not exist", () => {
116+ const skills = discoverSkills([join(tmp, "nonexistent")]);
117+ expect(skills).toEqual([]);
118+ });
119+
120+ test("returns empty array when scan path has no skill dirs", () => {
121+ mkdirSync(join(tmp, "empty"), { recursive: true });
122+ const skills = discoverSkills([join(tmp, "empty")]);
123+ expect(skills).toEqual([]);
124+ });
125+
126+ test("uses directory name as fallback when frontmatter name is missing", () => {
127+ writeSkill(
128+ tmp,
129+ "my-tool",
130+ [
131+ "---",
132+ "description: A tool without a name field",
133+ "---",
134+ "",
135+ "# My Tool",
136+ ].join("\n"),
137+ );
138+
139+ const skills = discoverSkills([tmp]);
140+ expect(skills).toHaveLength(1);
141+ expect(skills[0]!.name).toBe("my-tool");
142+ expect(skills[0]!.description).toBe("A tool without a name field");
143+ });
144+
145+ test("uses directory name when no frontmatter exists", () => {
146+ writeSkill(
147+ tmp,
148+ "bare-skill",
149+ "# Bare Skill\n\nJust content, no frontmatter.\n",
150+ );
151+
152+ const skills = discoverSkills([tmp]);
153+ expect(skills).toHaveLength(1);
154+ expect(skills[0]!.name).toBe("bare-skill");
155+ expect(skills[0]!.description).toBe("");
156+ });
157+
158+ test("uses empty description when frontmatter has no description", () => {
159+ writeSkill(
160+ tmp,
161+ "nodesc",
162+ ["---", "name: nodesc", "---", "", "Content only."].join("\n"),
163+ );
164+
165+ const skills = discoverSkills([tmp]);
166+ expect(skills).toHaveLength(1);
167+ expect(skills[0]!.name).toBe("nodesc");
168+ expect(skills[0]!.description).toBe("");
169+ });
170+
171+ test("handles multi-line description in frontmatter", () => {
172+ writeSkill(
173+ tmp,
174+ "multiline",
175+ [
176+ "---",
177+ "name: multiline",
178+ "description: >",
179+ " A skill with a multi-line",
180+ " description that folds.",
181+ "---",
182+ ].join("\n"),
183+ );
184+
185+ const skills = discoverSkills([tmp]);
186+ expect(skills).toHaveLength(1);
187+ expect(skills[0]!.description).toContain("multi-line");
188+ expect(skills[0]!.description).toContain("description that folds.");
189+ });
190+
191+ test("strips quotes from frontmatter values", () => {
192+ writeSkill(
193+ tmp,
194+ "quoted",
195+ [
196+ "---",
197+ 'name: "quoted-name"',
198+ "description: 'A quoted description'",
199+ "---",
200+ ].join("\n"),
201+ );
202+
203+ const skills = discoverSkills([tmp]);
204+ expect(skills).toHaveLength(1);
205+ expect(skills[0]!.name).toBe("quoted-name");
206+ expect(skills[0]!.description).toBe("A quoted description");
207+ });
208+});
209+
210+// ---------------------------------------------------------------------------
211+// buildSkillCatalog
212+// ---------------------------------------------------------------------------
213+
214+describe("buildSkillCatalog", () => {
215+ test("returns empty string when no skills", () => {
216+ expect(buildSkillCatalog([])).toBe("");
217+ });
218+
219+ test("generates XML catalog with skill entries", () => {
220+ const skills: Skill[] = [
221+ {
222+ name: "code-review",
223+ description: "Review code for bugs.",
224+ path: "/project/.agents/skills/code-review/SKILL.md",
225+ },
226+ {
227+ name: "deploy",
228+ description: "Deploy the app.",
229+ path: "/home/user/.agents/skills/deploy/SKILL.md",
230+ },
231+ ];
232+
233+ const catalog = buildSkillCatalog(skills);
234+
235+ // Verify overall structure
236+ expect(catalog).toContain("<available_skills>");
237+ expect(catalog).toContain("</available_skills>");
238+
239+ // Verify individual skill entries
240+ expect(catalog).toContain("<name>code-review</name>");
241+ expect(catalog).toContain(
242+ "<description>Review code for bugs.</description>",
243+ );
244+ expect(catalog).toContain(
245+ "<location>/project/.agents/skills/code-review/SKILL.md</location>",
246+ );
247+
248+ expect(catalog).toContain("<name>deploy</name>");
249+ expect(catalog).toContain("<description>Deploy the app.</description>");
250+ expect(catalog).toContain(
251+ "<location>/home/user/.agents/skills/deploy/SKILL.md</location>",
252+ );
253+ });
254+
255+ test("includes the preamble text", () => {
256+ const skills: Skill[] = [
257+ {
258+ name: "test",
259+ description: "A test skill.",
260+ path: "/path/to/SKILL.md",
261+ },
262+ ];
263+
264+ const catalog = buildSkillCatalog(skills);
265+ expect(catalog).toContain(
266+ "The following skills provide specialized instructions",
267+ );
268+ expect(catalog).toContain("resolve it against the skill directory");
269+ });
270+});
src/skills.ts+215−0
@@ -0,0 +1,215 @@
1+/**
2+ * Agent Skills (agentskills.io) discovery, parsing, and catalog generation.
3+ *
4+ * Scans configured directories for `SKILL.md` files, extracts YAML
5+ * frontmatter (name, description), resolves name collisions (earlier
6+ * scan paths win), and generates an XML catalog string for inclusion
7+ * in the system prompt.
8+ *
9+ * @module
10+ */
11+
12+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
13+import { join } from "node:path";
14+
15+// ---------------------------------------------------------------------------
16+// Types
17+// ---------------------------------------------------------------------------
18+
19+/**
20+ * A discovered agent skill.
21+ *
22+ * Represents a single SKILL.md file that has been parsed and is ready
23+ * for inclusion in the system prompt catalog.
24+ */
25+export interface Skill {
26+ /** Skill name (from frontmatter or directory name fallback). */
27+ name: string;
28+ /** Skill description (from frontmatter, empty if absent). */
29+ description: string;
30+ /** Absolute path to the SKILL.md file. */
31+ path: string;
32+}
33+
34+// ---------------------------------------------------------------------------
35+// Frontmatter parsing
36+// ---------------------------------------------------------------------------
37+
38+/**
39+ * Parse YAML frontmatter from a SKILL.md file's content.
40+ *
41+ * Handles simple key-value pairs, quoted strings, and YAML folded
42+ * scalars (`>`). Does not use a full YAML parser — just enough to
43+ * extract `name` and `description`.
44+ *
45+ * @param content - Raw file content.
46+ * @returns Extracted name and description (both may be undefined).
47+ */
48+function parseFrontmatter(content: string): {
49+ name: string | undefined;
50+ description: string | undefined;
51+} {
52+ // Frontmatter must start with ---
53+ if (!content.startsWith("---")) {
54+ return { name: undefined, description: undefined };
55+ }
56+
57+ const endIdx = content.indexOf("\n---", 3);
58+ if (endIdx === -1) {
59+ return { name: undefined, description: undefined };
60+ }
61+
62+ const frontmatter = content.slice(4, endIdx); // skip opening "---\n"
63+ const lines = frontmatter.split("\n");
64+
65+ let name: string | undefined;
66+ let description: string | undefined;
67+
68+ for (let i = 0; i < lines.length; i++) {
69+ const line = lines[i]!;
70+
71+ const colonIdx = line.indexOf(":");
72+ if (colonIdx === -1) continue;
73+
74+ const key = line.slice(0, colonIdx).trim();
75+ const value = line.slice(colonIdx + 1).trim();
76+
77+ if (key === "name") {
78+ name = stripQuotes(value);
79+ } else if (key === "description") {
80+ // Handle folded scalar (>)
81+ if (value === ">") {
82+ const folded: string[] = [];
83+ for (let j = i + 1; j < lines.length; j++) {
84+ const nextLine = lines[j]!;
85+ // Continuation lines must be indented
86+ if (
87+ nextLine.length > 0 &&
88+ (nextLine[0] === " " || nextLine[0] === "\t")
89+ ) {
90+ folded.push(nextLine.trim());
91+ } else {
92+ break;
93+ }
94+ }
95+ description = folded.join(" ");
Cut short: this commit's diff is over 1000 lines.