diff --git a/backend/eslint.config.js b/backend/eslint.config.js index 76cb27e9..f0084db6 100644 --- a/backend/eslint.config.js +++ b/backend/eslint.config.js @@ -24,7 +24,7 @@ export default defineConfig([ rules: { 'no-console': ['warn', { allow: ['warn', 'error'] }], '@typescript-eslint/no-explicit-any': 'warn', - '@typescript-eslint/no-unused-vars': 'warn', + '@typescript-eslint/no-unused-vars': 'error', 'no-useless-escape': 'warn', }, }, diff --git a/backend/src/services/skills.ts b/backend/src/services/skills.ts new file mode 100644 index 00000000..f7e499da --- /dev/null +++ b/backend/src/services/skills.ts @@ -0,0 +1,369 @@ +import os from 'os' +import path from 'path' +import type { Database } from 'bun:sqlite' +import type { SkillFileInfo, SkillScope, CreateSkillRequest, UpdateSkillRequest } from '@opencode-manager/shared' +import { SKILL_NAME_REGEX } from '@opencode-manager/shared' +import { getRepoById } from '../db/queries' +import { ensureDirectoryExists, fileExists, readFileContent, writeFileContent, deletePath, listDirectory } from './file-operations' +import { logger } from '../utils/logger' + +const GLOBAL_SKILLS_PATH = path.join(os.homedir(), '.config', 'opencode', 'skills') + +interface ParsedSkillFile { + frontmatter: { + name: string + description: string + license?: string + compatibility?: string + metadata?: Record + } + body: string +} + +function parseSkillFile(content: string): ParsedSkillFile { + const firstDelim = content.indexOf('---') + if (firstDelim === -1) { + throw new Error('Invalid SKILL.md format: missing frontmatter delimiters') + } + const afterFirst = firstDelim + 3 + const secondDelim = content.indexOf('\n---', afterFirst) + if (secondDelim === -1) { + throw new Error('Invalid SKILL.md format: missing closing frontmatter delimiter') + } + const frontmatterStr = content.substring(afterFirst, secondDelim).trim() + const afterSecond = secondDelim + 4 + const body = content.substring(afterSecond).trim() + + const frontmatter: Record = {} + const lines = frontmatterStr.split('\n') + + let currentKey: string | null = null + const metadataObj: Record = {} + + for (const line of lines) { + const trimmedLine = line.trim() + if (!trimmedLine) continue + + const kvMatch = trimmedLine.match(/^([^:]+):\s*(.*)$/) + if (kvMatch) { + const key = kvMatch[1]?.trim() + const value = kvMatch[2]?.trim() + + if (key === 'metadata') { + currentKey = 'metadata' + continue + } + + if (key && value !== undefined) { + frontmatter[key] = value + currentKey = null + } + } else if (currentKey === 'metadata' && trimmedLine) { + const metaMatch = trimmedLine.match(/^\s*([^:]+):\s*(.*)$/) + if (metaMatch) { + const metaKey = metaMatch[1]?.trim() + const metaValue = metaMatch[2]?.trim() + if (metaKey && metaValue !== undefined) { + metadataObj[metaKey] = metaValue + } + } + } + } + + if (Object.keys(metadataObj).length > 0) { + frontmatter.metadata = metadataObj + } + + return { + frontmatter: { + name: frontmatter.name as string || '', + description: frontmatter.description as string || '', + license: frontmatter.license as string | undefined, + compatibility: frontmatter.compatibility as string | undefined, + metadata: frontmatter.metadata as Record | undefined, + }, + body, + } +} + +function generateSkillFrontmatter( + name: string, + description: string, + license?: string, + compatibility?: string, + metadata?: Record +): string { + let frontmatter = `name: ${name}\ndescription: ${description}` + + if (license) { + frontmatter += `\nlicense: ${license}` + } + + if (compatibility) { + frontmatter += `\ncompatibility: ${compatibility}` + } + + if (metadata && Object.keys(metadata).length > 0) { + frontmatter += '\nmetadata:' + for (const [key, value] of Object.entries(metadata)) { + frontmatter += `\n ${key}: ${value}` + } + } + + return frontmatter +} + +function getSkillDirectoryPath(db: Database, scope: SkillScope, repoId?: number): string { + if (scope === 'global') { + return GLOBAL_SKILLS_PATH + } + + if (!repoId) { + throw new Error('repoId is required for project-scoped skills') + } + + const repo = getRepoById(db, repoId) + if (!repo) { + throw new Error(`Repository with id ${repoId} not found`) + } + + return path.join(repo.fullPath, '.opencode', 'skills') +} + +function validateSkillName(name: string): void { + if (!SKILL_NAME_REGEX.test(name)) { + throw new Error('Invalid skill name. Must be lowercase alphanumeric with hyphens only.') + } +} + +function getSkillFilePath(db: Database, scope: SkillScope, name: string, repoId?: number): string { + validateSkillName(name) + const skillsDir = getSkillDirectoryPath(db, scope, repoId) + return path.join(skillsDir, name, 'SKILL.md') +} + +export async function listManagedSkills(db: Database, repoId?: number): Promise { + const skills: SkillFileInfo[] = [] + + const globalSkillsDir = GLOBAL_SKILLS_PATH + const globalSkillsExist = await fileExists(globalSkillsDir) + + if (globalSkillsExist) { + const entries = await listDirectory(globalSkillsDir) + for (const entry of entries) { + if (entry.isDirectory) { + const skillPath = path.join(entry.path, 'SKILL.md') + const skillExists = await fileExists(skillPath) + if (skillExists) { + const skillInfo = await readSkillFile(db, 'global', entry.name) + if (skillInfo) { + skills.push(skillInfo) + } + } + } + } + } + + if (repoId) { + const repo = getRepoById(db, repoId) + if (repo) { + const projectSkillsDir = path.join(repo.fullPath, '.opencode', 'skills') + const projectSkillsExist = await fileExists(projectSkillsDir) + + if (projectSkillsExist) { + const entries = await listDirectory(projectSkillsDir) + for (const entry of entries) { + if (entry.isDirectory) { + const skillPath = path.join(entry.path, 'SKILL.md') + const skillExists = await fileExists(skillPath) + if (skillExists) { + const skillInfo = await readSkillFile(db, 'project', entry.name, repoId) + if (skillInfo) { + skills.push(skillInfo) + } + } + } + } + } + } + } + + return skills +} + +export async function getSkill( + db: Database, + name: string, + scope: SkillScope, + repoId?: number +): Promise { + const skillPath = getSkillFilePath(db, scope, name, repoId) + const exists = await fileExists(skillPath) + + if (!exists) { + throw new Error(`Skill "${name}" not found in ${scope} scope`) + } + + const skillInfo = await readSkillFile(db, scope, name, repoId) + if (!skillInfo) { + throw new Error(`Failed to read skill "${name}"`) + } + + return skillInfo +} + +async function readSkillFile( + db: Database, + scope: SkillScope, + name: string, + repoId?: number +): Promise { + try { + const skillPath = getSkillFilePath(db, scope, name, repoId) + const content = await readFileContent(skillPath) + const parsed = parseSkillFile(content) + + const repo = repoId ? getRepoById(db, repoId) : null + + return { + name: parsed.frontmatter.name, + description: parsed.frontmatter.description, + body: parsed.body, + license: parsed.frontmatter.license, + compatibility: parsed.frontmatter.compatibility, + metadata: parsed.frontmatter.metadata, + scope, + location: skillPath, + repoId: scope === 'project' ? repoId : undefined, + repoName: repo?.localPath, + } + } catch (error) { + logger.error(`Failed to read skill ${name}:`, error) + return null + } +} + +export async function createSkill( + db: Database, + input: CreateSkillRequest +): Promise { + const { name, description, body, license, compatibility, metadata, scope, repoId } = input + + const skillPath = getSkillFilePath(db, scope, name, repoId) + const exists = await fileExists(skillPath) + + if (exists) { + throw new Error(`Skill "${name}" already exists in ${scope} scope`) + } + + const skillDir = path.dirname(skillPath) + await ensureDirectoryExists(skillDir) + + const frontmatter = generateSkillFrontmatter( + name, + description, + license, + compatibility, + metadata + ) + + const content = `---\n${frontmatter}\n---\n${body}` + + await writeFileContent(skillPath, content) + logger.info(`Created skill "${name}" at ${skillPath}`) + + const repo = repoId ? getRepoById(db, repoId) : null + + return { + name, + description, + body, + license, + compatibility, + metadata, + scope, + location: skillPath, + repoId: scope === 'project' ? repoId : undefined, + repoName: repo?.localPath, + } +} + +export async function updateSkill( + db: Database, + name: string, + scope: SkillScope, + input: UpdateSkillRequest, + repoId?: number +): Promise { + const skillPath = getSkillFilePath(db, scope, name, repoId) + const exists = await fileExists(skillPath) + + if (!exists) { + throw new Error(`Skill "${name}" not found in ${scope} scope`) + } + + const existingContent = await readFileContent(skillPath) + const parsed = parseSkillFile(existingContent) + + const resolveField = (field: T | null | undefined, existing: T | undefined): T | undefined => { + if (field === null) return undefined + if (field === undefined) return existing + return field + } + + const updatedFrontmatter = { + name: parsed.frontmatter.name, + description: input.description ?? parsed.frontmatter.description, + license: resolveField(input.license, parsed.frontmatter.license), + compatibility: resolveField(input.compatibility, parsed.frontmatter.compatibility), + metadata: resolveField(input.metadata, parsed.frontmatter.metadata), + } + + const updatedBody = input.body ?? parsed.body + + const frontmatter = generateSkillFrontmatter( + updatedFrontmatter.name, + updatedFrontmatter.description, + updatedFrontmatter.license, + updatedFrontmatter.compatibility, + updatedFrontmatter.metadata + ) + + const content = `---\n${frontmatter}\n---\n${updatedBody}` + + await writeFileContent(skillPath, content) + logger.info(`Updated skill "${name}" at ${skillPath}`) + + const repo = repoId ? getRepoById(db, repoId) : null + + return { + name: updatedFrontmatter.name, + description: updatedFrontmatter.description, + body: updatedBody, + license: updatedFrontmatter.license, + compatibility: updatedFrontmatter.compatibility, + metadata: updatedFrontmatter.metadata, + scope, + location: skillPath, + repoId: scope === 'project' ? repoId : undefined, + repoName: repo?.localPath, + } +} + +export async function deleteSkill( + db: Database, + name: string, + scope: SkillScope, + repoId?: number +): Promise { + const skillPath = getSkillFilePath(db, scope, name, repoId) + const exists = await fileExists(skillPath) + + if (!exists) { + throw new Error(`Skill "${name}" not found in ${scope} scope`) + } + + const skillDir = path.dirname(skillPath) + await deletePath(skillDir) + logger.info(`Deleted skill "${name}" from ${skillDir}`) +} diff --git a/backend/test/services/skills.test.ts b/backend/test/services/skills.test.ts new file mode 100644 index 00000000..530d7d41 --- /dev/null +++ b/backend/test/services/skills.test.ts @@ -0,0 +1,277 @@ +import { describe, expect, test, beforeEach, afterEach } from 'vitest' +import { join } from 'path' +import { tmpdir } from 'os' +import { mkdtemp, rm } from 'fs/promises' + +describe('SkillService', () => { + let tempDir: string + let originalHome: string + + beforeEach(async () => { + tempDir = await mkdtemp(join(tmpdir(), 'skills-test-')) + originalHome = process.env.HOME || '' + process.env.HOME = tempDir + }) + + afterEach(async () => { + await rm(tempDir, { recursive: true, force: true }) + if (originalHome) { + process.env.HOME = originalHome + } + }) + + const mockDb = null as unknown as any + + test('generates correct YAML frontmatter format', async () => { + const { createSkill } = await import('../../src/services/skills') + const input = { + name: `test-skill-${Date.now()}`, + description: 'A test skill', + body: '## Test Body\n\nContent here', + scope: 'global' as const, + license: 'MIT', + compatibility: 'opencode', + metadata: { key: 'value' }, + } + + const result = await createSkill(mockDb, input) + + expect(result.name).toBe(input.name) + expect(result.description).toBe('A test skill') + expect(result.body).toBe('## Test Body\n\nContent here') + expect(result.license).toBe('MIT') + expect(result.compatibility).toBe('opencode') + expect(result.metadata).toEqual({ key: 'value' }) + }) + + test('parses frontmatter and body correctly', async () => { + const { createSkill, getSkill } = await import('../../src/services/skills') + const name = `parse-test-${Date.now()}` + const input = { + name, + description: 'Test description', + body: '## Body\n\nSome content', + scope: 'global' as const, + } + + await createSkill(mockDb, input) + const skill = await getSkill(mockDb, name, 'global') + + expect(skill.name).toBe(name) + expect(skill.description).toBe('Test description') + expect(skill.body).toBe('## Body\n\nSome content') + }) + + test('accepts valid skill names', async () => { + const { createSkill } = await import('../../src/services/skills') + const validNames = ['my-skill', 'a', 'skill-1-2', 'test123', 'a-b-c'] + + for (const name of validNames) { + const input = { + name: `${name}-${Date.now()}`, + description: 'Test', + body: 'Body', + scope: 'global' as const, + } + + await expect(createSkill(mockDb, input)).resolves.toBeDefined() + } + }) + + test('rejects invalid skill names', async () => { + const { createSkill } = await import('../../src/services/skills') + const invalidNames = ['My-Skill', '--bad', 'bad-', 'has spaces', 'has_underscore', 'has.dot', 'UPPERCASE'] + + for (const name of invalidNames) { + const input = { + name: `${name}-${Date.now()}`, + description: 'Test', + body: 'Body', + scope: 'global' as const, + } + + await expect(createSkill(mockDb, input)).rejects.toThrow('Invalid skill name') + } + }) + + test('creates skill file at correct path', async () => { + const { createSkill } = await import('../../src/services/skills') + const name = `new-skill-${Date.now()}` + const input = { + name, + description: 'A new skill', + body: 'Skill body content', + scope: 'global' as const, + } + + const result = await createSkill(mockDb, input) + + expect(result.name).toBe(name) + expect(result.scope).toBe('global') + expect(result.location).toContain(`${name}/SKILL.md`) + }) + + test('throws error on duplicate name', async () => { + const { createSkill } = await import('../../src/services/skills') + const name = `duplicate-${Date.now()}` + const input = { + name, + description: 'First', + body: 'Body', + scope: 'global' as const, + } + + await createSkill(mockDb, input) + + const duplicate = { + name, + description: 'Second', + body: 'Body', + scope: 'global' as const, + } + + await expect(createSkill(mockDb, duplicate)).rejects.toThrow('already exists') + }) + + test('reads skill correctly', async () => { + const { createSkill, getSkill } = await import('../../src/services/skills') + const name = `read-test-${Date.now()}` + const input = { + name, + description: 'Read test description', + body: 'Read test body', + scope: 'global' as const, + license: 'Apache-2.0', + } + + await createSkill(mockDb, input) + const skill = await getSkill(mockDb, name, 'global') + + expect(skill.name).toBe(name) + expect(skill.description).toBe('Read test description') + expect(skill.body).toBe('Read test body') + expect(skill.license).toBe('Apache-2.0') + }) + + test('throws error for missing skill', async () => { + const { getSkill } = await import('../../src/services/skills') + await expect(getSkill(mockDb, 'nonexistent', 'global')).rejects.toThrow('not found') + }) + + test('updates only changed fields', async () => { + const { createSkill, updateSkill } = await import('../../src/services/skills') + const name = `update-test-${Date.now()}` + const input = { + name, + description: 'Original description', + body: 'Original body', + scope: 'global' as const, + license: 'MIT', + } + + await createSkill(mockDb, input) + + const updated = await updateSkill( + mockDb, + name, + 'global', + { description: 'Updated description' }, + undefined + ) + + expect(updated.description).toBe('Updated description') + expect(updated.body).toBe('Original body') + expect(updated.license).toBe('MIT') + }) + + test('throws error for missing skill on update', async () => { + const { updateSkill } = await import('../../src/services/skills') + await expect( + updateSkill(mockDb, 'nonexistent', 'global', { description: 'Test' }, undefined) + ).rejects.toThrow('not found') + }) + + test('deletes skill directory', async () => { + const { createSkill, deleteSkill, getSkill } = await import('../../src/services/skills') + const name = `delete-test-${Date.now()}` + const input = { + name, + description: 'To be deleted', + body: 'Body', + scope: 'global' as const, + } + + await createSkill(mockDb, input) + await deleteSkill(mockDb, name, 'global') + + await expect(getSkill(mockDb, name, 'global')).rejects.toThrow('not found') + }) + + test('throws error for missing skill on delete', async () => { + const { deleteSkill } = await import('../../src/services/skills') + await expect(deleteSkill(mockDb, 'nonexistent', 'global')).rejects.toThrow('not found') + }) + + test('lists global skills', async () => { + const { createSkill, listManagedSkills, deleteSkill } = await import('../../src/services/skills') + const name1 = `list-test-1-${Date.now()}` + const name2 = `list-test-2-${Date.now()}` + + try { + await createSkill(mockDb, { + name: name1, + description: 'Test 1', + body: 'Body', + scope: 'global' as const, + }) + + await createSkill(mockDb, { + name: name2, + description: 'Test 2', + body: 'Body', + scope: 'global' as const, + }) + + const skills = await listManagedSkills(mockDb) + + const createdSkills = skills.filter(s => [name1, name2].includes(s.name)) + expect(createdSkills.length).toBe(2) + expect(createdSkills.map(s => s.name)).toEqual( + expect.arrayContaining([name1, name2]) + ) + } finally { + await deleteSkill(mockDb, name1, 'global').catch(() => {}) + await deleteSkill(mockDb, name2, 'global').catch(() => {}) + } + }) + + test('should handle body content containing --- (horizontal rules)', async () => { + const { createSkill, getSkill, deleteSkill } = await import('../../src/services/skills') + const name = `hr-test-${Date.now()}` + + const bodyWithHR = `This is the skill body. + +--- + +This is after a horizontal rule. + +--- + +Another section.` + + await createSkill(mockDb, { + name, + description: 'Test horizontal rules in body', + body: bodyWithHR, + scope: 'global' as const, + }) + + const skill = await getSkill(mockDb, name, 'global') + expect(skill).not.toBeNull() + expect(skill!.body).toContain('---') + expect(skill!.body).toContain('This is after a horizontal rule.') + expect(skill!.body).toContain('Another section.') + + await deleteSkill(mockDb, name, 'global') + }) +}) diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js index 79d339c2..926b5140 100644 --- a/frontend/eslint.config.js +++ b/frontend/eslint.config.js @@ -55,7 +55,7 @@ export default defineConfig([ rules: { '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-empty-function': 'off', - '@typescript-eslint/no-unused-vars': ['warn', { + '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' }], diff --git a/frontend/src/components/settings/SkillDialog.tsx b/frontend/src/components/settings/SkillDialog.tsx new file mode 100644 index 00000000..5f035597 --- /dev/null +++ b/frontend/src/components/settings/SkillDialog.tsx @@ -0,0 +1,288 @@ +import { useForm } from 'react-hook-form' +import { zodResolver } from '@hookform/resolvers/zod' +import { z } from 'zod' +import { useEffect, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form' +import { Textarea } from '@/components/ui/textarea' +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' +import type { SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope } from '@opencode-manager/shared' +import type { Repo } from '@/api/types' +import { listRepos } from '@/api/repos' +import { useQuery } from '@tanstack/react-query' + +const skillFormSchema = z.object({ + name: z.string() + .min(1, 'Skill name is required') + .max(64, 'Skill name must be 64 characters or less') + .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Must be lowercase letters, numbers, and hyphens only'), + description: z.string().min(1, 'Description is required').max(1024, 'Description must be 1024 characters or less'), + body: z.string().min(1, 'Skill body is required'), + scope: z.enum(['global', 'project']), + license: z.string().optional(), + compatibility: z.string().optional(), + metadata: z.record(z.string(), z.string()).optional(), +}) + +type SkillFormValues = z.infer + +interface SkillDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + onSubmit: (data: CreateSkillRequest | (UpdateSkillRequest & { name: string; scope: SkillScope; repoId?: number })) => void + editingSkill?: SkillFileInfo | null +} + +export function SkillDialog({ open, onOpenChange, onSubmit, editingSkill }: SkillDialogProps) { + const { data: repos = [] } = useQuery({ + queryKey: ['repos'], + queryFn: listRepos, + enabled: open, + staleTime: 5 * 60 * 1000, + }) + + const [selectedRepoId, setSelectedRepoId] = useState(undefined) + + const getDefaultValues = (skill?: SkillFileInfo | null): SkillFormValues => { + return { + name: skill?.name || '', + description: skill?.description || '', + body: skill?.body || '', + scope: skill?.scope || 'global', + license: skill?.license || '', + compatibility: skill?.compatibility || '', + metadata: skill?.metadata || {}, + } + } + + const form = useForm({ + resolver: zodResolver(skillFormSchema), + defaultValues: getDefaultValues(editingSkill) + }) + + useEffect(() => { + if (open) { + form.reset(getDefaultValues(editingSkill)) + if (editingSkill?.repoId) { + setSelectedRepoId(editingSkill.repoId) + } + } + }, [open, editingSkill, form]) + + const handleSubmit = (values: SkillFormValues) => { + if (!editingSkill && values.scope === 'project' && !selectedRepoId) { + form.setError('scope', { message: 'Please select a repository for project-scoped skills' }) + return + } + + if (editingSkill) { + onSubmit({ + name: editingSkill.name, + scope: editingSkill.scope, + repoId: editingSkill.scope === 'project' ? editingSkill.repoId : undefined, + description: values.description, + body: values.body, + license: values.license || undefined, + compatibility: values.compatibility || undefined, + metadata: Object.keys(values.metadata || {}).length > 0 ? values.metadata : undefined, + }) + } else { + onSubmit({ + name: values.name, + description: values.description, + body: values.body, + scope: values.scope, + repoId: values.scope === 'project' ? selectedRepoId : undefined, + license: values.license || undefined, + compatibility: values.compatibility || undefined, + metadata: Object.keys(values.metadata || {}).length > 0 ? values.metadata : undefined, + }) + } + form.reset() + onOpenChange(false) + } + + const handleOpenChange = (isOpen: boolean) => { + if (!isOpen) { + form.reset() + } + onOpenChange(isOpen) + } + + const scope = form.watch('scope') + + return ( + + + + {editingSkill ? 'Edit Skill' : 'Create Skill'} + + +
+
+
+ ( + + Skill Name + + + + + Use lowercase letters, numbers, and hyphens only + + + + )} + /> + + ( + + Description + +