diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..53627e13 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,305 @@ +# Contributing to SkillKit + +Thank you for your interest in contributing to SkillKit! This document provides guidelines and instructions for contributing. + +## Code of Conduct + +By participating in this project, you agree to maintain a respectful and inclusive environment for everyone. + +## Getting Started + +### Prerequisites + +- Node.js 18+ +- pnpm 8+ (recommended) or npm/yarn +- Git + +### Setting Up the Development Environment + +1. **Fork the repository** + + Click the "Fork" button on GitHub to create your own copy. + +2. **Clone your fork** + + ```bash + git clone https://github.com/YOUR_USERNAME/skillkit.git + cd skillkit + ``` + +3. **Install dependencies** + + ```bash + pnpm install + ``` + +4. **Build the project** + + ```bash + pnpm build + ``` + +5. **Run tests** + + ```bash + pnpm test + ``` + +6. **Link for local development** + + ```bash + cd apps/skillkit + pnpm link --global + ``` + + Now you can use `skillkit` command globally to test your changes. + +## Project Structure + +``` +skillkit/ +├── apps/ +│ └── skillkit/ # Main CLI entry point +├── packages/ +│ ├── core/ # @skillkit/core - Shared logic +│ │ ├── discovery/ # Skill discovery +│ │ ├── parser/ # SKILL.md parsing +│ │ ├── translator/ # Cross-agent translation +│ │ ├── context/ # Project context sync +│ │ └── recommend/ # Recommendation engine +│ ├── cli/ # @skillkit/cli - Commands +│ ├── tui/ # @skillkit/tui - Terminal UI +│ └── agents/ # @skillkit/agents - Agent adapters +├── docs/ # Documentation +└── README.md +``` + +## Development Workflow + +### Branch Naming + +Use descriptive branch names: + +- `feature/skill-translation` - New features +- `fix/cursor-adapter-path` - Bug fixes +- `docs/api-reference` - Documentation +- `refactor/core-types` - Code refactoring + +### Making Changes + +1. **Create a new branch** + + ```bash + git checkout -b feature/your-feature-name + ``` + +2. **Make your changes** + + - Follow the existing code style + - Add tests for new functionality + - Update documentation as needed + +3. **Run checks locally** + + ```bash + # Build all packages + pnpm build + + # Run tests + pnpm test + + # Type check + pnpm typecheck + + # Lint (if configured) + pnpm lint + ``` + +4. **Commit your changes** + + Write clear, descriptive commit messages: + + ```bash + git commit -m "feat: add skill translation for Windsurf agent" + git commit -m "fix: resolve path resolution in Windows" + git commit -m "docs: add API reference for RecommendationEngine" + ``` + + We follow [Conventional Commits](https://www.conventionalcommits.org/): + - `feat:` - New features + - `fix:` - Bug fixes + - `docs:` - Documentation changes + - `refactor:` - Code refactoring + - `test:` - Adding or updating tests + - `chore:` - Maintenance tasks + +5. **Push your branch** + + ```bash + git push origin feature/your-feature-name + ``` + +6. **Open a Pull Request** + + - Provide a clear description of the changes + - Reference any related issues + - Ensure CI checks pass + +## Types of Contributions + +### Bug Reports + +When reporting bugs, please include: + +- SkillKit version (`skillkit --version`) +- Node.js version (`node --version`) +- Operating system +- Steps to reproduce +- Expected vs actual behavior +- Relevant error messages or logs + +### Feature Requests + +For feature requests, please describe: + +- The problem you're trying to solve +- Your proposed solution +- Alternative approaches you've considered +- Any relevant examples or mockups + +### Adding New Agent Support + +To add support for a new AI coding agent: + +1. **Create an adapter** in `packages/agents/src/adapters/` + + ```typescript + // packages/agents/src/adapters/new-agent.ts + import type { AgentAdapter, Skill } from '../types.js'; + + export const newAgentAdapter: AgentAdapter = { + type: 'new-agent', + name: 'New Agent', + configFile: 'AGENTS.md', + skillsDir: '.new-agent/skills/', + globalSkillsDir: '~/.new-agent/skills/', + + generateConfig(skills: Skill[]): string { + // Generate config content + }, + + detectPresence(): boolean { + // Check if agent is present + }, + }; + ``` + +2. **Register the adapter** in `packages/agents/src/adapters/index.ts` + +3. **Add translator support** in `packages/core/src/translator/` if the agent uses a unique format + +4. **Add tests** for the new adapter + +5. **Update documentation** + +### Adding New Skills + +If you want to contribute skills to the ecosystem: + +1. Follow the [Agent Skills specification](https://agentskills.io/specification) +2. Include a `SKILL.md` with proper frontmatter +3. Test with multiple agents using `skillkit translate` +4. Submit to the appropriate skill repository + +## Code Style + +### TypeScript + +- Use TypeScript for all new code +- Define explicit types for function parameters and return values +- Use interfaces for object shapes +- Prefer `const` over `let` + +### File Organization + +- One export per file when possible +- Group related functionality in directories +- Use `index.ts` files for clean exports + +### Testing + +- Write unit tests for new functionality +- Use descriptive test names +- Test edge cases and error conditions + +```typescript +describe('RecommendationEngine', () => { + it('should score skills based on framework match', () => { + // Test implementation + }); + + it('should return empty array when no skills match', () => { + // Test implementation + }); +}); +``` + +## Pull Request Guidelines + +### Before Submitting + +- [ ] Code builds without errors (`pnpm build`) +- [ ] All tests pass (`pnpm test`) +- [ ] New code has appropriate test coverage +- [ ] Documentation is updated if needed +- [ ] Commit messages follow conventions + +### PR Description Template + +```markdown +## Summary + +Brief description of the changes. + +## Changes + +- Change 1 +- Change 2 + +## Testing + +How were these changes tested? + +## Related Issues + +Fixes #123 +``` + +### Review Process + +1. A maintainer will review your PR +2. Address any requested changes +3. Once approved, the PR will be merged + +## Release Process + +Releases are managed by maintainers. The process includes: + +1. Version bump in package.json files +2. Changelog update +3. Git tag creation +4. npm publish + +## Getting Help + +- **GitHub Issues**: For bugs and feature requests +- **Discussions**: For questions and ideas +- **Documentation**: Check the README and docs/ + +## License + +By contributing to SkillKit, you agree that your contributions will be licensed under the Apache License 2.0. + +--- + +Thank you for contributing to SkillKit! diff --git a/LICENSE b/LICENSE index 61442168..a64e0cbe 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,190 @@ -MIT License + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ -Copyright (c) 2026 Rohit Ghumare + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: + 1. Definitions. -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2025 Rohit Ghumare + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 6b5cf7ab..b449a6e3 100644 --- a/README.md +++ b/README.md @@ -3,17 +3,79 @@ [![npm version](https://img.shields.io/npm/v/skillkit.svg)](https://www.npmjs.com/package/skillkit) [![npm downloads](https://img.shields.io/npm/dm/skillkit.svg)](https://www.npmjs.com/package/skillkit) [![CI](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml/badge.svg)](https://github.com/rohitg00/skillkit/actions/workflows/ci.yml) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) -Universal skills loader for AI coding agents. Install, manage, and sync skills across your favorite AI tools. +**The universal skills platform for AI coding agents.** Install, manage, translate, and sync skills across 17+ AI tools with smart recommendations. -Skills follow the [Agent Skills](https://agentskills.io) open format—a simple, portable standard for giving agents new capabilities and expertise. +```bash +npm install -g skillkit && skillkit +``` -![SkillKit Demo](https://raw.githubusercontent.com/rohitg00/skillkit/main/skillkit.gif) +## Why SkillKit? + +| Problem | SkillKit Solution | +|---------|------------------| +| Skills only work with one agent | **Cross-agent translation** - use any skill with any agent | +| Don't know which skills to install | **Smart recommendations** - project-aware suggestions | +| Config fragmented across agents | **One config, all agents** - sync everywhere | +| Manual skill discovery | **Task-based search** - find skills by what you need | + +## 30-Second Quick Start + +```bash +# Install globally +npm install -g skillkit + +# Get personalized skill recommendations for your project +skillkit recommend + +# Install top-rated skills +skillkit install anthropics/skills + +# Launch interactive TUI +skillkit +``` + +## Key Features + +### Smart Recommendations +Analyzes your project and suggests the best skills: + +```bash +skillkit recommend +# Project: my-app (Next.js + TypeScript + Tailwind) +# +# Recommended Skills: +# 92% ██████████ vercel-react-best-practices +# 87% █████████░ tailwind-v4-patterns +# 85% █████████░ nextjs-app-router +``` + +### Cross-Agent Translation +Use any skill with any agent - automatic format conversion: + +```bash +# Translate a Claude skill to Cursor format +skillkit translate react-patterns --to cursor + +# Translate all skills for a new agent +skillkit translate --all --to antigravity +``` + +### Project Context Sync +Configure once, sync to all your agents: + +```bash +# Analyze project and create context +skillkit context init + +# Sync your config to all detected agents +skillkit context sync --all +``` ## Interactive TUI -Manage all your skills with a beautiful terminal interface: +Launch the beautiful terminal interface: ```bash skillkit ui @@ -25,16 +87,16 @@ skillkit **Features:** - Browse 33+ skill repositories +- Smart skill recommendations based on your project - Install skills with one keystroke - Multi-agent installation support -- View installed skills -- Sync across agents +- Cross-agent skill translation - Responsive design for all terminal sizes **Navigation:** -- `h` Home | `b` Browse | `l` List | `s` Sync | `,` Config +- `h` Home | `b` Browse | `r` Recommend | `l` List | `s` Sync | `,` Config - `↑↓` Navigate | `Enter` Select | `Esc` Back | `q` Quit -- `m` Multi-agent selection | `r` Refresh/Back +- `m` Multi-agent selection | `/` Search ### Compatible With @@ -60,48 +122,44 @@ skillkit ## Features +- **Smart Recommendations**: AI-powered skill suggestions based on your project stack +- **Cross-Agent Translation**: Convert skills between any of 17+ agent formats +- **Project Context Sync**: One config that syncs to all your agents - **Interactive TUI**: Beautiful terminal interface for managing skills -- **Multi-Agent Support**: Works with 17+ AI coding agents out of the box +- **Multi-Agent Support**: Works with Claude Code, Cursor, Codex, Windsurf, and 13+ more - **Multi-Platform Git**: GitHub, GitLab, Bitbucket, and local paths - **CI/CD Friendly**: Non-interactive flags for automation (`--skills`, `--all`, `--yes`) -- **Skill Toggle**: Enable/disable skills without removing them -- **Type-Safe**: Built with TypeScript and Zod validation - **Zero Config**: Auto-detects your agent and configures appropriately ## Installation ```bash +# Global install (recommended) npm install -g skillkit -# or + +# Or use without installing npx skillkit + +# Or with other package managers +pnpm add -g skillkit +yarn global add skillkit +bun add -g skillkit ``` ## Quick Start ```bash -# Launch interactive TUI -skillkit ui +# 1. Get recommendations for your project +skillkit recommend -# Initialize in your project (auto-detects agent) -skillkit init +# 2. Install recommended skills +skillkit install anthropics/skills -# Install skills from GitHub -skillkit install owner/repo - -# Install from GitLab -skillkit install gitlab:owner/repo - -# Install specific skills (CI/CD friendly) -skillkit install owner/repo --skills=pdf,xlsx,docx - -# Create a new skill -skillkit create my-skill - -# Sync skills to your agent config +# 3. Sync to your agent skillkit sync -# Read a skill (for AI consumption) -skillkit read pdf +# Or just launch the TUI and do it all interactively +skillkit ``` ## Popular Skill Repositories @@ -116,6 +174,8 @@ skillkit install anthropics/skills skillkit install vercel-labs/agent-skills/skills ``` +![SkillKit Demo](https://raw.githubusercontent.com/rohitg00/skillkit/main/skillkit.gif) + | Repository | Skills | Description | |------------|--------|-------------| | [anthropics/skills](https://github.com/anthropics/skills) | `pdf`, `xlsx`, `docx`, etc. | Official Claude Code skill marketplace | @@ -135,6 +195,7 @@ skillkit # Launch TUI if no arguments provided **TUI Features:** - **Browse**: Discover skills from 33+ repositories +- **Recommend**: Get smart skill suggestions for your project - **List**: View all installed skills - **Sync**: Sync skills across multiple agents - **Settings**: Configure SkillKit preferences @@ -142,13 +203,14 @@ skillkit # Launch TUI if no arguments provided **Keyboard Shortcuts:** - `h` - Home screen - `b` - Browse skills marketplace +- `r` - Smart recommendations - `l` - List installed skills - `s` - Sync skills across agents - `,` - Settings - `↑↓` - Navigate lists - `Enter` - Select / Install - `m` - Multi-agent selection (when viewing skills) -- `r` - Refresh / Go back +- `/` - Search skills - `Esc` - Return to home - `q` - Quit @@ -197,6 +259,48 @@ skillkit sync --output AGENTS.md skillkit sync --enabled-only ``` +### `skillkit recommend` + +Get smart skill recommendations based on your project's tech stack. + +```bash +skillkit recommend # Analyze current directory +skillkit recommend --path ./my-app # Analyze specific project +skillkit recommend --verbose # Show detailed match reasons +skillkit recommend --limit 5 # Limit results +skillkit recommend --min-score 50 # Only show high matches +skillkit recommend --category security # Filter by category +skillkit recommend --search "auth" # Search skills by task +skillkit recommend --update # Update skill index +skillkit recommend --json # Output as JSON +``` + +### `skillkit translate` + +Translate skills between different agent formats. + +```bash +skillkit translate react-skill --to cursor # Translate to Cursor format +skillkit translate ./skill --from claude --to windsurf # Explicit source/target +skillkit translate --all --to cursor # Translate all installed skills +skillkit translate react-skill --to cursor --dry-run # Preview without writing +``` + +**Supported translations:** All 17 agents can translate to/from each other. + +### `skillkit context` + +Manage project context for cross-agent synchronization. + +```bash +skillkit context init # Analyze project and create context +skillkit context show # Display current context +skillkit context export # Export context to file +skillkit context import ./context.yaml # Import context from file +skillkit context sync --agent cursor # Sync context to specific agent +skillkit context sync --all # Sync to all detected agents +``` + ### `skillkit read ` Read skill content for AI agent consumption. @@ -362,10 +466,21 @@ Instructions for the AI agent on how to use this skill. ```typescript import { + // Skill discovery findAllSkills, discoverSkills, detectAgent, getAdapter, + // Recommendations + RecommendationEngine, + analyzeProject, + // Translation + translateSkill, + translateSkillFile, + // Context + ContextManager, + initContext, + syncToAllAgents, } from 'skillkit'; // Find all installed skills @@ -377,6 +492,20 @@ const agent = await detectAgent(); // Generate config const adapter = getAdapter(agent); const config = adapter.generateConfig(skills); + +// Get smart recommendations +const engine = new RecommendationEngine(); +const profile = await analyzeProject('./my-project'); +const recommendations = engine.recommend(profile, skills); + +// Translate skills between agents +const result = translateSkill(skillContent, 'cursor'); +console.log(result.content); // Cursor MDC format + +// Manage project context +const ctx = new ContextManager('./my-project'); +await ctx.init(); +await syncToAllAgents(ctx.getContext()); ``` ## Configuration @@ -396,11 +525,11 @@ disabledSkills: ## License -MIT License - see [LICENSE](LICENSE) for details. +Apache License 2.0 - see [LICENSE](LICENSE) for details. ## Contributing -Contributions welcome! Please read our contributing guidelines. +Contributions welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md) before submitting a pull request. ## Acknowledgments diff --git a/apps/skillkit/.skillkit/context.yaml b/apps/skillkit/.skillkit/context.yaml new file mode 100644 index 00000000..06cdfb71 --- /dev/null +++ b/apps/skillkit/.skillkit/context.yaml @@ -0,0 +1,43 @@ +version: 1 +project: + name: skillkit + description: Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more + type: cli + path: /Users/rohitghumare/skillkit/apps/skillkit +stack: + languages: + - name: typescript + version: 5.7.2 + confidence: 100 + source: tsconfig.json + frameworks: [] + libraries: [] + styling: [] + testing: + - name: vitest + version: 2.1.8 + confidence: 100 + source: package.json + databases: [] + tools: [] + runtime: + - name: nodejs + version: 18.0.0 + confidence: 100 + source: package.json +patterns: + apiStyle: rest + testing: vitest +skills: + installed: [] + recommended: [] + excluded: [] + autoSync: true + securityLevel: medium + testingRequired: false +agents: + detected: [] + synced: [] + disabled: [] +createdAt: 2026-01-23T00:02:29.727Z +updatedAt: 2026-01-23T00:02:29.728Z diff --git a/apps/skillkit/package.json b/apps/skillkit/package.json new file mode 100644 index 00000000..24dac52b --- /dev/null +++ b/apps/skillkit/package.json @@ -0,0 +1,68 @@ +{ + "name": "skillkit", + "version": "1.2.0", + "description": "Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more", + "type": "module", + "bin": { + "skillkit": "./dist/cli.js", + "sk": "./dist/cli.js" + }, + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + } + }, + "files": [ + "dist", + "schemas" + ], + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "keywords": [ + "ai", + "skills", + "claude", + "codex", + "cursor", + "gemini", + "opencode", + "antigravity", + "agent", + "coding-assistant", + "skill-loader", + "cli" + ], + "author": "Rohit Ghumare", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/rohitg00/skillkit.git" + }, + "bugs": { + "url": "https://github.com/rohitg00/skillkit/issues" + }, + "homepage": "https://github.com/rohitg00/skillkit#readme", + "engines": { + "node": ">=18.0.0" + }, + "dependencies": { + "@skillkit/core": "workspace:*", + "@skillkit/agents": "workspace:*", + "@skillkit/cli": "workspace:*", + "@skillkit/tui": "workspace:*", + "clipanion": "^4.0.0-rc.4" + }, + "devDependencies": { + "@types/node": "^22.10.5", + "tsup": "^8.3.5", + "typescript": "^5.7.2", + "vitest": "^2.1.8" + } +} diff --git a/apps/skillkit/src/__tests__/cli.test.ts b/apps/skillkit/src/__tests__/cli.test.ts new file mode 100644 index 00000000..4a8e3aa7 --- /dev/null +++ b/apps/skillkit/src/__tests__/cli.test.ts @@ -0,0 +1,28 @@ +import { describe, it, expect } from 'vitest'; +import { existsSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +describe('SkillKit CLI', () => { + describe('build artifacts', () => { + it('should have cli entry point', () => { + const distPath = join(__dirname, '../../dist/cli.js'); + expect(existsSync(distPath)).toBe(true); + }); + + it('should have index entry point', () => { + const distPath = join(__dirname, '../../dist/index.js'); + expect(existsSync(distPath)).toBe(true); + }); + }); + + describe('package.json', () => { + it('should have correct bin configuration', async () => { + const packageJsonPath = join(__dirname, '../../package.json'); + expect(existsSync(packageJsonPath)).toBe(true); + }); + }); +}); diff --git a/apps/skillkit/src/cli.ts b/apps/skillkit/src/cli.ts new file mode 100644 index 00000000..8474b4ff --- /dev/null +++ b/apps/skillkit/src/cli.ts @@ -0,0 +1,55 @@ +#!/usr/bin/env node +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { dirname, join } from 'node:path'; +import { Cli, Builtins } from 'clipanion'; +import { + InstallCommand, + SyncCommand, + ReadCommand, + ListCommand, + EnableCommand, + DisableCommand, + UpdateCommand, + RemoveCommand, + InitCommand, + ValidateCommand, + CreateCommand, + UICommand, + TranslateCommand, + ContextCommand, + RecommendCommand, +} from '@skillkit/cli'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const packageJsonPath = join(__dirname, '../package.json'); +const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')); +const version = packageJson.version || '1.2.0'; + +const cli = new Cli({ + binaryLabel: 'skillkit', + binaryName: 'skillkit', + binaryVersion: version, +}); + +cli.register(Builtins.HelpCommand); +cli.register(Builtins.VersionCommand); + +cli.register(InstallCommand); +cli.register(SyncCommand); +cli.register(ReadCommand); +cli.register(ListCommand); +cli.register(EnableCommand); +cli.register(DisableCommand); +cli.register(UpdateCommand); +cli.register(RemoveCommand); +cli.register(InitCommand); +cli.register(ValidateCommand); +cli.register(CreateCommand); +cli.register(UICommand); +cli.register(TranslateCommand); +cli.register(ContextCommand); +cli.register(RecommendCommand); + +cli.runExit(process.argv.slice(2)); diff --git a/apps/skillkit/src/index.ts b/apps/skillkit/src/index.ts new file mode 100644 index 00000000..6906db39 --- /dev/null +++ b/apps/skillkit/src/index.ts @@ -0,0 +1,6 @@ +// Re-export all public APIs from packages +export * from '@skillkit/core'; +export * from '@skillkit/agents'; + +// Re-export TUI entry point +export { startTUI } from '@skillkit/tui'; diff --git a/apps/skillkit/tsconfig.json b/apps/skillkit/tsconfig.json new file mode 100644 index 00000000..0de0e910 --- /dev/null +++ b/apps/skillkit/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src", + "composite": false + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/apps/skillkit/tsup.config.ts b/apps/skillkit/tsup.config.ts new file mode 100644 index 00000000..6d705f32 --- /dev/null +++ b/apps/skillkit/tsup.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: ['src/cli.ts', 'src/index.ts'], + format: ['esm'], + dts: true, + splitting: false, + sourcemap: true, + clean: true, +}); diff --git a/package.json b/package.json index 0f039559..660caa9a 100644 --- a/package.json +++ b/package.json @@ -1,33 +1,18 @@ { - "name": "skillkit", + "name": "skillkit-monorepo", "version": "1.2.0", - "description": "Universal skills loader for AI coding agents - supports Claude Code, Codex, Cursor, Antigravity, OpenCode, Gemini CLI and more", + "private": true, + "description": "Universal skills loader for AI coding agents - Monorepo", "type": "module", - "main": "./dist/index.js", - "types": "./dist/index.d.ts", - "bin": { - "skillkit": "./dist/cli.js", - "sk": "./dist/cli.js" - }, - "exports": { - ".": { - "import": "./dist/index.js", - "types": "./dist/index.d.ts" - } - }, - "files": [ - "dist", - "schemas" - ], "scripts": { - "build": "tsup", - "dev": "tsup --watch", - "test": "vitest run", + "build": "turbo run build", + "dev": "turbo run dev", + "test": "turbo run test", "test:watch": "vitest", "test:coverage": "vitest run --coverage", - "typecheck": "tsc --noEmit", - "lint": "eslint src --ext .ts", - "prepublishOnly": "npm run typecheck && npm run build && npm run test" + "typecheck": "turbo run typecheck", + "lint": "turbo run lint", + "clean": "rm -rf node_modules packages/*/node_modules apps/*/node_modules packages/*/dist apps/*/dist" }, "keywords": [ "ai", @@ -41,10 +26,11 @@ "agent", "coding-assistant", "skill-loader", - "cli" + "cli", + "monorepo" ], "author": "Rohit Ghumare", - "license": "MIT", + "license": "Apache-2.0", "repository": { "type": "git", "url": "git+https://github.com/rohitg00/skillkit.git" @@ -56,24 +42,12 @@ "engines": { "node": ">=18.0.0" }, - "dependencies": { - "chalk": "^5.3.0", - "clipanion": "^4.0.0-rc.4", - "got": "^14.4.1", - "ink": "^5.0.1", - "ink-select-input": "^6.0.0", - "ink-spinner": "^5.0.0", - "ink-text-input": "^6.0.0", - "isomorphic-git": "^1.27.1", - "ora": "^8.1.0", - "react": "^18.3.1", - "yaml": "^2.6.1", - "zod": "^3.24.1" - }, + "packageManager": "pnpm@9.0.0", "devDependencies": { "@types/node": "^22.10.5", "@types/react": "^18.3.18", "tsup": "^8.3.5", + "turbo": "^2.3.4", "typescript": "^5.7.2", "vitest": "^2.1.8" } diff --git a/packages/agents/package.json b/packages/agents/package.json new file mode 100644 index 00000000..bfcf2182 --- /dev/null +++ b/packages/agents/package.json @@ -0,0 +1,34 @@ +{ + "name": "@skillkit/agents", + "version": "1.2.0", + "description": "Agent adapters for SkillKit - supports 17+ AI coding agents", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + } + }, + "files": ["dist"], + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@skillkit/core": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.5", + "tsup": "^8.3.5", + "typescript": "^5.7.2", + "vitest": "^2.1.8" + }, + "engines": { + "node": ">=18.0.0" + }, + "license": "Apache-2.0" +} diff --git a/packages/agents/src/__tests__/adapters.test.ts b/packages/agents/src/__tests__/adapters.test.ts new file mode 100644 index 00000000..50f4b4b6 --- /dev/null +++ b/packages/agents/src/__tests__/adapters.test.ts @@ -0,0 +1,42 @@ +import { describe, it, expect } from 'vitest'; +import { getAllAdapters, getAdapter, detectAgent } from '../index.js'; + +describe('Agent Adapters', () => { + describe('getAllAdapters', () => { + it('should return all registered adapters', () => { + const adapters = getAllAdapters(); + expect(adapters).toBeInstanceOf(Array); + expect(adapters.length).toBeGreaterThan(0); + }); + + it('should include common agents', () => { + const adapters = getAllAdapters(); + const types = adapters.map(a => a.type); + + // Should include at least some well-known agents + expect(types).toContain('claude-code'); + expect(types).toContain('cursor'); + }); + }); + + describe('getAdapter', () => { + it('should return adapter for known agent type', () => { + const adapter = getAdapter('claude-code'); + expect(adapter).toBeDefined(); + expect(adapter.type).toBe('claude-code'); + expect(adapter.name).toBeDefined(); + }); + + it('should return undefined for unknown agent type', () => { + const adapter = getAdapter('unknown-agent' as any); + expect(adapter).toBeUndefined(); + }); + }); + + describe('detectAgent', () => { + it('should return an agent type', async () => { + const agent = await detectAgent(); + expect(typeof agent).toBe('string'); + }); + }); +}); diff --git a/packages/agents/src/amp.ts b/packages/agents/src/amp.ts new file mode 100644 index 00000000..034acf79 --- /dev/null +++ b/packages/agents/src/amp.ts @@ -0,0 +1,74 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class AmpAdapter implements AgentAdapter { + readonly type: AgentType = 'amp'; + readonly name = 'Amp'; + readonly skillsDir = '.agents/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectAgents = join(process.cwd(), '.agents'); + const globalAgents = join(homedir(), '.config', 'agents'); + + return existsSync(projectAgents) || existsSync(globalAgents); + } +} diff --git a/packages/agents/src/antigravity.ts b/packages/agents/src/antigravity.ts new file mode 100644 index 00000000..7f7e3f1a --- /dev/null +++ b/packages/agents/src/antigravity.ts @@ -0,0 +1,80 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class AntigravityAdapter implements AgentAdapter { + readonly type: AgentType = 'antigravity'; + readonly name = 'Antigravity'; + readonly skillsDir = '.antigravity/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsYaml = enabledSkills + .map(s => ` - name: ${s.name}\n description: "${s.description}"\n invoke: skillkit read ${s.name}`) + .join('\n'); + + return `# Antigravity Skills Configuration + + + +## Available Skills + +${enabledSkills.map(s => `### ${s.name} + +${s.description} + +**Usage:** \`skillkit read ${s.name}\` +`).join('\n')} + +## How Skills Work + +1. Skills provide specialized knowledge for specific tasks +2. Load a skill when the current task matches its description +3. Skills are loaded on-demand to preserve context window +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + + const yamlMatch = content.match(//); + if (yamlMatch) { + const nameRegex = /name:\s*([a-z0-9-]+)/g; + let match; + while ((match = nameRegex.exec(yamlMatch[1])) !== null) { + skillNames.push(match[1].trim()); + } + } + + if (skillNames.length === 0) { + const headerRegex = /^### ([a-z0-9-]+)$/gm; + let match; + while ((match = headerRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const agDir = join(process.cwd(), '.antigravity'); + const globalAg = join(homedir(), '.antigravity'); + + return existsSync(agDir) || existsSync(globalAg); + } +} diff --git a/packages/agents/src/base.ts b/packages/agents/src/base.ts new file mode 100644 index 00000000..6e025717 --- /dev/null +++ b/packages/agents/src/base.ts @@ -0,0 +1,30 @@ +import type { Skill, AgentType } from '@skillkit/core'; + +export interface AgentAdapter { + readonly type: AgentType; + readonly name: string; + readonly skillsDir: string; + readonly configFile: string; + + generateConfig(skills: Skill[]): string; + parseConfig(content: string): string[]; + getInvokeCommand(skillName: string): string; + isDetected(): Promise; +} + +export function createSkillXml(skill: Skill): string { + return ` +${skill.name} +${escapeXml(skill.description)} +${skill.location} +`; +} + +export function escapeXml(text: string): string { + return text + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} diff --git a/packages/agents/src/claude-code.ts b/packages/agents/src/claude-code.ts new file mode 100644 index 00000000..d800ad60 --- /dev/null +++ b/packages/agents/src/claude-code.ts @@ -0,0 +1,75 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class ClaudeCodeAdapter implements AgentAdapter { + readonly type: AgentType = 'claude-code'; + readonly name = 'Claude Code'; + readonly skillsDir = '.claude/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectClaude = join(process.cwd(), '.claude'); + const globalClaude = join(homedir(), '.claude'); + const claudeMd = join(process.cwd(), 'CLAUDE.md'); + + return existsSync(projectClaude) || existsSync(globalClaude) || existsSync(claudeMd); + } +} diff --git a/packages/agents/src/clawdbot.ts b/packages/agents/src/clawdbot.ts new file mode 100644 index 00000000..1596e579 --- /dev/null +++ b/packages/agents/src/clawdbot.ts @@ -0,0 +1,74 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class ClawdbotAdapter implements AgentAdapter { + readonly type: AgentType = 'clawdbot'; + readonly name = 'Clawdbot'; + readonly skillsDir = 'skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectSkills = join(process.cwd(), 'skills'); + const globalClawdbot = join(homedir(), '.clawdbot'); + + return existsSync(globalClawdbot) || (existsSync(projectSkills) && existsSync(join(process.cwd(), '.clawdbot'))); + } +} diff --git a/packages/agents/src/codex.ts b/packages/agents/src/codex.ts new file mode 100644 index 00000000..cf229078 --- /dev/null +++ b/packages/agents/src/codex.ts @@ -0,0 +1,69 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class CodexAdapter implements AgentAdapter { + readonly type: AgentType = 'codex'; + readonly name = 'OpenAI Codex CLI'; + readonly skillsDir = '.codex/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsList = enabledSkills + .map(s => `| ${s.name} | ${s.description} | \`skillkit read ${s.name}\` |`) + .join('\n'); + + return `# Skills + +You have access to specialized skills for completing complex tasks. + +| Skill | Description | Command | +|-------|-------------|---------| +${skillsList} + +## Usage + +When a task matches a skill's capability, run the command to load detailed instructions: + +\`\`\`bash +skillkit read +\`\`\` + +Skills are loaded on-demand to keep context clean. Only load skills when relevant to the current task. +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const tableRegex = /^\|\s*([a-z0-9-]+)\s*\|/gm; + let match; + + while ((match = tableRegex.exec(content)) !== null) { + const name = match[1].trim(); + if (name && name !== 'Skill' && name !== '-------') { + skillNames.push(name); + } + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const codexDir = join(process.cwd(), '.codex'); + const globalCodex = join(homedir(), '.codex'); + + return existsSync(codexDir) || existsSync(globalCodex); + } +} diff --git a/packages/agents/src/cursor.ts b/packages/agents/src/cursor.ts new file mode 100644 index 00000000..1db1d7fc --- /dev/null +++ b/packages/agents/src/cursor.ts @@ -0,0 +1,71 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class CursorAdapter implements AgentAdapter { + readonly type: AgentType = 'cursor'; + readonly name = 'Cursor'; + readonly skillsDir = '.cursor/skills'; + readonly configFile = '.cursorrules'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsList = enabledSkills + .map(s => `- **${s.name}**: ${s.description}`) + .join('\n'); + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return `# Skills System + +You have access to specialized skills that can help complete tasks. Use the skillkit CLI to load skill instructions when needed. + +## Available Skills + +${skillsList} + +## How to Use Skills + +When a task matches a skill's description, load it with: +\`\`\`bash +skillkit read +\`\`\` + +The skill will provide detailed instructions for completing the task. + + +${skillsXml} + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const cursorRules = join(process.cwd(), '.cursorrules'); + const cursorDir = join(process.cwd(), '.cursor'); + + return existsSync(cursorRules) || existsSync(cursorDir); + } +} diff --git a/packages/agents/src/droid.ts b/packages/agents/src/droid.ts new file mode 100644 index 00000000..373605ab --- /dev/null +++ b/packages/agents/src/droid.ts @@ -0,0 +1,74 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class DroidAdapter implements AgentAdapter { + readonly type: AgentType = 'droid'; + readonly name = 'Droid (Factory)'; + readonly skillsDir = '.factory/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectFactory = join(process.cwd(), '.factory'); + const globalFactory = join(homedir(), '.factory'); + + return existsSync(projectFactory) || existsSync(globalFactory); + } +} diff --git a/packages/agents/src/gemini-cli.ts b/packages/agents/src/gemini-cli.ts new file mode 100644 index 00000000..15bc3a8b --- /dev/null +++ b/packages/agents/src/gemini-cli.ts @@ -0,0 +1,88 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class GeminiCliAdapter implements AgentAdapter { + readonly type: AgentType = 'gemini-cli'; + readonly name = 'Gemini CLI'; + readonly skillsDir = '.gemini/skills'; + readonly configFile = 'GEMINI.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsJson = enabledSkills.map(s => ({ + name: s.name, + description: s.description, + invoke: `skillkit read ${s.name}`, + location: s.location, + })); + + return `# Skills Configuration + +You have access to specialized skills that extend your capabilities. + +## Available Skills + +${enabledSkills.map(s => `### ${s.name}\n${s.description}\n\nInvoke: \`skillkit read ${s.name}\``).join('\n\n')} + +## Skills Data + +\`\`\`json +${JSON.stringify(skillsJson, null, 2)} +\`\`\` + +## Usage Instructions + +1. When a task matches a skill's description, load it using the invoke command +2. Skills provide step-by-step instructions for complex tasks +3. Each skill is self-contained with its own resources +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + + const jsonMatch = content.match(/```json\s*([\s\S]*?)```/); + if (jsonMatch) { + try { + const skills = JSON.parse(jsonMatch[1]); + if (Array.isArray(skills)) { + skills.forEach(s => { + if (s.name) skillNames.push(s.name); + }); + } + } catch { + // Ignore parse errors + } + } + + if (skillNames.length === 0) { + const headerRegex = /^### ([a-z0-9-]+)$/gm; + let match; + while ((match = headerRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const geminiMd = join(process.cwd(), 'GEMINI.md'); + const geminiDir = join(process.cwd(), '.gemini'); + const globalGemini = join(homedir(), '.gemini'); + + return existsSync(geminiMd) || existsSync(geminiDir) || existsSync(globalGemini); + } +} diff --git a/packages/agents/src/github-copilot.ts b/packages/agents/src/github-copilot.ts new file mode 100644 index 00000000..5a1c20ff --- /dev/null +++ b/packages/agents/src/github-copilot.ts @@ -0,0 +1,74 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class GitHubCopilotAdapter implements AgentAdapter { + readonly type: AgentType = 'github-copilot'; + readonly name = 'GitHub Copilot'; + readonly skillsDir = '.github/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectGithub = join(process.cwd(), '.github', 'skills'); + const globalCopilot = join(homedir(), '.copilot'); + + return existsSync(projectGithub) || existsSync(globalCopilot); + } +} diff --git a/packages/agents/src/goose.ts b/packages/agents/src/goose.ts new file mode 100644 index 00000000..870961c5 --- /dev/null +++ b/packages/agents/src/goose.ts @@ -0,0 +1,74 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class GooseAdapter implements AgentAdapter { + readonly type: AgentType = 'goose'; + readonly name = 'Goose'; + readonly skillsDir = '.goose/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectGoose = join(process.cwd(), '.goose'); + const globalGoose = join(homedir(), '.config', 'goose'); + + return existsSync(projectGoose) || existsSync(globalGoose); + } +} diff --git a/packages/agents/src/index.ts b/packages/agents/src/index.ts new file mode 100644 index 00000000..bf5e6d62 --- /dev/null +++ b/packages/agents/src/index.ts @@ -0,0 +1,105 @@ +import type { AgentAdapter } from './base.js'; +import type { AgentType } from '@skillkit/core'; +import { ClaudeCodeAdapter } from './claude-code.js'; +import { CursorAdapter } from './cursor.js'; +import { CodexAdapter } from './codex.js'; +import { GeminiCliAdapter } from './gemini-cli.js'; +import { OpenCodeAdapter } from './opencode.js'; +import { AntigravityAdapter } from './antigravity.js'; +import { AmpAdapter } from './amp.js'; +import { ClawdbotAdapter } from './clawdbot.js'; +import { DroidAdapter } from './droid.js'; +import { GitHubCopilotAdapter } from './github-copilot.js'; +import { GooseAdapter } from './goose.js'; +import { KiloAdapter } from './kilo.js'; +import { KiroCliAdapter } from './kiro-cli.js'; +import { RooAdapter } from './roo.js'; +import { TraeAdapter } from './trae.js'; +import { WindsurfAdapter } from './windsurf.js'; +import { UniversalAdapter } from './universal.js'; + +export * from './base.js'; +export * from './claude-code.js'; +export * from './cursor.js'; +export * from './codex.js'; +export * from './gemini-cli.js'; +export * from './opencode.js'; +export * from './antigravity.js'; +export * from './amp.js'; +export * from './clawdbot.js'; +export * from './droid.js'; +export * from './github-copilot.js'; +export * from './goose.js'; +export * from './kilo.js'; +export * from './kiro-cli.js'; +export * from './roo.js'; +export * from './trae.js'; +export * from './windsurf.js'; +export * from './universal.js'; + +const adapters: Record = { + 'claude-code': new ClaudeCodeAdapter(), + cursor: new CursorAdapter(), + codex: new CodexAdapter(), + 'gemini-cli': new GeminiCliAdapter(), + opencode: new OpenCodeAdapter(), + antigravity: new AntigravityAdapter(), + amp: new AmpAdapter(), + clawdbot: new ClawdbotAdapter(), + droid: new DroidAdapter(), + 'github-copilot': new GitHubCopilotAdapter(), + goose: new GooseAdapter(), + kilo: new KiloAdapter(), + 'kiro-cli': new KiroCliAdapter(), + roo: new RooAdapter(), + trae: new TraeAdapter(), + windsurf: new WindsurfAdapter(), + universal: new UniversalAdapter(), +}; + +export function getAdapter(type: AgentType): AgentAdapter { + return adapters[type]; +} + +export function getAllAdapters(): AgentAdapter[] { + return Object.values(adapters); +} + +export async function detectAgent(): Promise { + const checkOrder: AgentType[] = [ + 'claude-code', + 'cursor', + 'codex', + 'gemini-cli', + 'opencode', + 'antigravity', + 'amp', + 'clawdbot', + 'droid', + 'github-copilot', + 'goose', + 'kilo', + 'kiro-cli', + 'roo', + 'trae', + 'windsurf', + 'universal', + ]; + + for (const type of checkOrder) { + const adapter = adapters[type]; + if (await adapter.isDetected()) { + return type; + } + } + + return 'universal'; +} + +export function getSkillsDir(type: AgentType): string { + return adapters[type].skillsDir; +} + +export function getConfigFile(type: AgentType): string { + return adapters[type].configFile; +} diff --git a/packages/agents/src/kilo.ts b/packages/agents/src/kilo.ts new file mode 100644 index 00000000..dec3e644 --- /dev/null +++ b/packages/agents/src/kilo.ts @@ -0,0 +1,74 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class KiloAdapter implements AgentAdapter { + readonly type: AgentType = 'kilo'; + readonly name = 'Kilo Code'; + readonly skillsDir = '.kilocode/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectKilo = join(process.cwd(), '.kilocode'); + const globalKilo = join(homedir(), '.kilocode'); + + return existsSync(projectKilo) || existsSync(globalKilo); + } +} diff --git a/packages/agents/src/kiro-cli.ts b/packages/agents/src/kiro-cli.ts new file mode 100644 index 00000000..299837a4 --- /dev/null +++ b/packages/agents/src/kiro-cli.ts @@ -0,0 +1,84 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class KiroCliAdapter implements AgentAdapter { + readonly type: AgentType = 'kiro-cli'; + readonly name = 'Kiro CLI'; + readonly skillsDir = '.kiro/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + + + +**Note for Kiro CLI users:** After installing skills, you need to manually add them to your custom agent's \`resources\` in \`.kiro/agents/.json\`: + +\`\`\`json +{ + "resources": [ + "skill://.kiro/skills/**/SKILL.md" + ] +} +\`\`\``; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectKiro = join(process.cwd(), '.kiro'); + const globalKiro = join(homedir(), '.kiro'); + + return existsSync(projectKiro) || existsSync(globalKiro); + } +} diff --git a/packages/agents/src/opencode.ts b/packages/agents/src/opencode.ts new file mode 100644 index 00000000..7b99f542 --- /dev/null +++ b/packages/agents/src/opencode.ts @@ -0,0 +1,67 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class OpenCodeAdapter implements AgentAdapter { + readonly type: AgentType = 'opencode'; + readonly name = 'OpenCode'; + readonly skillsDir = '.opencode/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` +# Skills + +The following skills are available to help complete tasks: + + +${skillsXml} + + +## How to Use + +When a task matches a skill's description: + +\`\`\`bash +skillkit read +\`\`\` + +This loads the skill's instructions into context. + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const opencodeDir = join(process.cwd(), '.opencode'); + const globalOpencode = join(homedir(), '.opencode'); + + return existsSync(opencodeDir) || existsSync(globalOpencode); + } +} diff --git a/packages/agents/src/roo.ts b/packages/agents/src/roo.ts new file mode 100644 index 00000000..dbd82e0d --- /dev/null +++ b/packages/agents/src/roo.ts @@ -0,0 +1,74 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class RooAdapter implements AgentAdapter { + readonly type: AgentType = 'roo'; + readonly name = 'Roo Code'; + readonly skillsDir = '.roo/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectRoo = join(process.cwd(), '.roo'); + const globalRoo = join(homedir(), '.roo'); + + return existsSync(projectRoo) || existsSync(globalRoo); + } +} diff --git a/packages/agents/src/trae.ts b/packages/agents/src/trae.ts new file mode 100644 index 00000000..35ecca1c --- /dev/null +++ b/packages/agents/src/trae.ts @@ -0,0 +1,74 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class TraeAdapter implements AgentAdapter { + readonly type: AgentType = 'trae'; + readonly name = 'Trae'; + readonly skillsDir = '.trae/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectTrae = join(process.cwd(), '.trae'); + const globalTrae = join(homedir(), '.trae'); + + return existsSync(projectTrae) || existsSync(globalTrae); + } +} diff --git a/packages/agents/src/universal.ts b/packages/agents/src/universal.ts new file mode 100644 index 00000000..781b3474 --- /dev/null +++ b/packages/agents/src/universal.ts @@ -0,0 +1,98 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class UniversalAdapter implements AgentAdapter { + readonly type: AgentType = 'universal'; + readonly name = 'Universal (Any Agent)'; + readonly skillsDir = '.agent/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + const skillsList = enabledSkills + .map(s => `- **${s.name}**: ${s.description}`) + .join('\n'); + + return `# Skills System + + + +## Available Skills + +${skillsList} + +## How to Use Skills + +When a task matches one of the available skills, load it to get detailed instructions: + +\`\`\`bash +skillkit read +\`\`\` + +Or with npx: + +\`\`\`bash +npx skillkit read +\`\`\` + +## Skills Data + + + +Skills provide specialized capabilities and domain knowledge. +- Invoke: \`skillkit read \` +- Base directory provided in output for resolving resources +- Only use skills listed below +- Each invocation is stateless + + + + +${skillsXml} + + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + + const skillRegex = /([^<]+)<\/name>/g; + let match; + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + if (skillNames.length === 0) { + const listRegex = /^- \*\*([a-z0-9-]+)\*\*:/gm; + while ((match = listRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const agentDir = join(process.cwd(), '.agent'); + const agentsMd = join(process.cwd(), 'AGENTS.md'); + + return existsSync(agentDir) || existsSync(agentsMd); + } +} diff --git a/packages/agents/src/windsurf.ts b/packages/agents/src/windsurf.ts new file mode 100644 index 00000000..e3cc6fe8 --- /dev/null +++ b/packages/agents/src/windsurf.ts @@ -0,0 +1,74 @@ +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { homedir } from 'node:os'; +import type { AgentAdapter } from './base.js'; +import { createSkillXml } from './base.js'; +import type { Skill, AgentType } from '@skillkit/core'; + +export class WindsurfAdapter implements AgentAdapter { + readonly type: AgentType = 'windsurf'; + readonly name = 'Windsurf'; + readonly skillsDir = '.windsurf/skills'; + readonly configFile = 'AGENTS.md'; + + generateConfig(skills: Skill[]): string { + const enabledSkills = skills.filter(s => s.enabled); + + if (enabledSkills.length === 0) { + return ''; + } + + const skillsXml = enabledSkills.map(createSkillXml).join('\n\n'); + + return ` + +## Available Skills + + + +When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge. + +How to use skills: +- Invoke: \`skillkit read \` or \`npx skillkit read \` +- The skill content will load with detailed instructions on how to complete the task +- Base directory provided in output for resolving bundled resources (references/, scripts/, assets/) + +Usage notes: +- Only use skills listed in below +- Do not invoke a skill that is already loaded in your context +- Each skill invocation is stateless + + + + +${skillsXml} + + + + +`; + } + + parseConfig(content: string): string[] { + const skillNames: string[] = []; + const skillRegex = /([^<]+)<\/name>/g; + let match; + + while ((match = skillRegex.exec(content)) !== null) { + skillNames.push(match[1].trim()); + } + + return skillNames; + } + + getInvokeCommand(skillName: string): string { + return `skillkit read ${skillName}`; + } + + async isDetected(): Promise { + const projectWindsurf = join(process.cwd(), '.windsurf'); + const globalWindsurf = join(homedir(), '.codeium', 'windsurf'); + + return existsSync(projectWindsurf) || existsSync(globalWindsurf); + } +} diff --git a/packages/agents/tsconfig.json b/packages/agents/tsconfig.json new file mode 100644 index 00000000..c64c5089 --- /dev/null +++ b/packages/agents/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src", + "composite": false + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/packages/agents/tsup.config.ts b/packages/agents/tsup.config.ts new file mode 100644 index 00000000..dbcb9a72 --- /dev/null +++ b/packages/agents/tsup.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: ['src/index.ts'], + format: ['esm'], + target: 'node18', + outDir: 'dist', + clean: true, + dts: true, + sourcemap: true, + splitting: false, + skipNodeModulesBundle: true, + platform: 'node', +}); diff --git a/packages/cli/package.json b/packages/cli/package.json new file mode 100644 index 00000000..1dd94ded --- /dev/null +++ b/packages/cli/package.json @@ -0,0 +1,41 @@ +{ + "name": "@skillkit/cli", + "version": "1.2.0", + "description": "CLI commands for SkillKit", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + } + }, + "files": ["dist"], + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@skillkit/core": "workspace:*", + "@skillkit/agents": "workspace:*", + "@skillkit/tui": "workspace:*", + "chalk": "^5.3.0", + "clipanion": "^4.0.0-rc.4", + "got": "^14.4.1", + "isomorphic-git": "^1.27.1", + "ora": "^8.1.0" + }, + "devDependencies": { + "@types/node": "^22.10.5", + "tsup": "^8.3.5", + "typescript": "^5.7.2", + "vitest": "^2.1.8" + }, + "engines": { + "node": ">=18.0.0" + }, + "license": "Apache-2.0" +} diff --git a/packages/cli/src/__tests__/commands.test.ts b/packages/cli/src/__tests__/commands.test.ts new file mode 100644 index 00000000..41debc2f --- /dev/null +++ b/packages/cli/src/__tests__/commands.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest'; + +describe('CLI Commands', () => { + describe('exports', () => { + it('should export all commands', async () => { + const commands = await import('../commands/index.js'); + + expect(commands.ListCommand).toBeDefined(); + expect(commands.ReadCommand).toBeDefined(); + expect(commands.SyncCommand).toBeDefined(); + expect(commands.InitCommand).toBeDefined(); + expect(commands.EnableCommand).toBeDefined(); + expect(commands.DisableCommand).toBeDefined(); + expect(commands.RemoveCommand).toBeDefined(); + expect(commands.InstallCommand).toBeDefined(); + expect(commands.UpdateCommand).toBeDefined(); + expect(commands.ValidateCommand).toBeDefined(); + expect(commands.CreateCommand).toBeDefined(); + expect(commands.UICommand).toBeDefined(); + expect(commands.TranslateCommand).toBeDefined(); + expect(commands.ContextCommand).toBeDefined(); + expect(commands.RecommendCommand).toBeDefined(); + }); + }); +}); diff --git a/packages/cli/src/commands/context.ts b/packages/cli/src/commands/context.ts new file mode 100644 index 00000000..362e1ec7 --- /dev/null +++ b/packages/cli/src/commands/context.ts @@ -0,0 +1,495 @@ +import { Command, Option } from 'clipanion'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import chalk from 'chalk'; +import { + type AgentType, + type ProjectContext, + ContextManager, + createContextSync, + analyzeProject, + getStackTags, +} from '@skillkit/core'; +import { getAllAdapters } from '@skillkit/agents'; + +/** + * Context command - manage project context for multi-agent sync + */ +export class ContextCommand extends Command { + static override paths = [['context']]; + + static override usage = Command.Usage({ + description: 'Manage project context for multi-agent skill synchronization', + details: ` + The context command helps you configure your project once and sync skills + across all AI coding agents. + + Subcommands: + - init: Initialize project context with auto-detection + - show: Display current project context + - export: Export context to a file + - import: Import context from a file + - sync: Sync skills to all configured agents + - detect: Run project detection + `, + examples: [ + ['Initialize project context', '$0 context init'], + ['Show current context', '$0 context show'], + ['Sync skills to all agents', '$0 context sync'], + ['Sync to specific agent', '$0 context sync --agent cursor'], + ['Export context', '$0 context export --output context.yaml'], + ], + }); + + // Subcommand (init, show, export, import, sync, detect) + action = Option.String({ required: false }); + + // Agent filter + agent = Option.String('--agent,-a', { + description: 'Target agent for sync', + }); + + // Output file for export + output = Option.String('--output,-o', { + description: 'Output file path', + }); + + // Input file for import + input = Option.String('--input,-i', { + description: 'Input file path', + }); + + // Force overwrite + force = Option.Boolean('--force,-f', false, { + description: 'Force overwrite existing files', + }); + + // Dry run + dryRun = Option.Boolean('--dry-run,-n', false, { + description: 'Preview without making changes', + }); + + // Merge on import + merge = Option.Boolean('--merge,-m', false, { + description: 'Merge with existing context on import', + }); + + // JSON output + json = Option.Boolean('--json,-j', false, { + description: 'Output in JSON format', + }); + + // Verbose output + verbose = Option.Boolean('--verbose,-v', false, { + description: 'Show detailed output', + }); + + async execute(): Promise { + const action = this.action || 'show'; + + switch (action) { + case 'init': + return this.initContext(); + case 'show': + return this.showContext(); + case 'export': + return this.exportContext(); + case 'import': + return this.importContext(); + case 'sync': + return this.syncContext(); + case 'detect': + return this.detectProject(); + case 'agents': + return this.listAgents(); + default: + console.error(chalk.red(`Unknown action: ${action}`)); + console.log(chalk.gray('Available actions: init, show, export, import, sync, detect, agents')); + return 1; + } + } + + /** + * Initialize project context + */ + private async initContext(): Promise { + const manager = new ContextManager(process.cwd()); + + if (manager.exists() && !this.force) { + console.log(chalk.yellow('Context already exists. Use --force to reinitialize.')); + return this.showContext(); + } + + console.log(chalk.cyan('Initializing project context...\n')); + + const context = manager.init({ force: this.force }); + + console.log(chalk.green('✓ Context initialized\n')); + console.log(chalk.gray(` Location: .skillkit/context.yaml\n`)); + + // Show summary + this.printContextSummary(context); + + // Detect agents + const sync = createContextSync(process.cwd()); + const detected = sync.detectAgents(); + if (detected.length > 0) { + console.log(chalk.cyan('\nDetected agents:')); + for (const agent of detected) { + console.log(` ${chalk.green('•')} ${agent}`); + } + + // Update context with detected agents + manager.updateAgents({ + detected, + synced: detected, + }); + } + + console.log(chalk.gray('\nRun `skillkit context sync` to sync skills to all agents.')); + + return 0; + } + + /** + * Show current context + */ + private async showContext(): Promise { + const manager = new ContextManager(process.cwd()); + const context = manager.load(); + + if (!context) { + console.log(chalk.yellow('No context found. Run `skillkit context init` first.')); + return 1; + } + + if (this.json) { + console.log(JSON.stringify(context, null, 2)); + return 0; + } + + this.printContextSummary(context); + + if (this.verbose) { + console.log(chalk.gray('\nFull context:')); + console.log(chalk.gray(JSON.stringify(context, null, 2))); + } + + return 0; + } + + /** + * Export context to file + */ + private async exportContext(): Promise { + const manager = new ContextManager(process.cwd()); + const context = manager.get(); + + if (!context) { + console.error(chalk.red('No context found. Run `skillkit context init` first.')); + return 1; + } + + const format = this.json ? 'json' : 'yaml'; + const content = manager.export({ + format, + includeSkills: true, + includeAgents: true, + }); + + if (this.output) { + const outputPath = resolve(this.output); + if (existsSync(outputPath) && !this.force) { + console.error(chalk.red(`File exists: ${outputPath}. Use --force to overwrite.`)); + return 1; + } + + writeFileSync(outputPath, content, 'utf-8'); + console.log(chalk.green(`✓ Context exported to ${outputPath}`)); + } else { + // Print to stdout + console.log(content); + } + + return 0; + } + + /** + * Import context from file + */ + private async importContext(): Promise { + if (!this.input) { + console.error(chalk.red('Error: --input/-i file path is required')); + return 1; + } + + const inputPath = resolve(this.input); + if (!existsSync(inputPath)) { + console.error(chalk.red(`File not found: ${inputPath}`)); + return 1; + } + + const manager = new ContextManager(process.cwd()); + const content = readFileSync(inputPath, 'utf-8'); + + try { + const context = manager.import(content, { + merge: this.merge, + overwrite: this.force, + }); + + console.log(chalk.green('✓ Context imported successfully')); + this.printContextSummary(context); + return 0; + } catch (error) { + console.error(chalk.red(`Import failed: ${error}`)); + return 1; + } + } + + /** + * Sync skills to all configured agents + */ + private async syncContext(): Promise { + const manager = new ContextManager(process.cwd()); + const context = manager.get(); + + if (!context) { + console.log(chalk.yellow('No context found. Initializing...')); + manager.init(); + } + + const sync = createContextSync(process.cwd()); + + console.log(chalk.cyan('Syncing skills across agents...\n')); + + // Determine target agents + const agents = this.agent ? [this.agent as AgentType] : undefined; + + const report = await sync.syncAll({ + agents, + force: this.force, + dryRun: this.dryRun, + }); + + // Print results + for (const result of report.results) { + const status = result.success ? chalk.green('✓') : chalk.red('✗'); + console.log(`${status} ${result.agent}: ${result.skillsSynced} synced, ${result.skillsSkipped} skipped`); + + if (this.verbose && result.files.length > 0) { + for (const file of result.files) { + console.log(chalk.gray(` → ${file}`)); + } + } + + if (result.warnings.length > 0) { + for (const warning of result.warnings) { + console.log(chalk.yellow(` ⚠ ${warning}`)); + } + } + + if (result.errors.length > 0) { + for (const error of result.errors) { + console.log(chalk.red(` ✗ ${error}`)); + } + } + } + + console.log(); + console.log(chalk.bold(`Summary: ${report.successfulAgents}/${report.totalAgents} agents, ${report.totalSkills} skills`)); + + if (this.dryRun) { + console.log(chalk.gray('\n(Dry run - no files were written)')); + } + + return report.successfulAgents === report.totalAgents ? 0 : 1; + } + + /** + * Detect project stack + */ + private async detectProject(): Promise { + console.log(chalk.cyan('Analyzing project...\n')); + + const stack = analyzeProject(process.cwd()); + const tags = getStackTags(stack); + + // Languages + if (stack.languages.length > 0) { + console.log(chalk.bold('Languages:')); + for (const lang of stack.languages) { + const version = lang.version ? ` (${lang.version})` : ''; + console.log(` ${chalk.green('•')} ${lang.name}${version}`); + } + console.log(); + } + + // Frameworks + if (stack.frameworks.length > 0) { + console.log(chalk.bold('Frameworks:')); + for (const fw of stack.frameworks) { + const version = fw.version ? ` (${fw.version})` : ''; + console.log(` ${chalk.green('•')} ${fw.name}${version}`); + } + console.log(); + } + + // Libraries + if (stack.libraries.length > 0) { + console.log(chalk.bold('Libraries:')); + for (const lib of stack.libraries) { + const version = lib.version ? ` (${lib.version})` : ''; + console.log(` ${chalk.green('•')} ${lib.name}${version}`); + } + console.log(); + } + + // Styling + if (stack.styling.length > 0) { + console.log(chalk.bold('Styling:')); + for (const style of stack.styling) { + console.log(` ${chalk.green('•')} ${style.name}`); + } + console.log(); + } + + // Testing + if (stack.testing.length > 0) { + console.log(chalk.bold('Testing:')); + for (const test of stack.testing) { + console.log(` ${chalk.green('•')} ${test.name}`); + } + console.log(); + } + + // Databases + if (stack.databases.length > 0) { + console.log(chalk.bold('Databases:')); + for (const db of stack.databases) { + console.log(` ${chalk.green('•')} ${db.name}`); + } + console.log(); + } + + // Tools + if (stack.tools.length > 0) { + console.log(chalk.bold('Tools:')); + for (const tool of stack.tools) { + console.log(` ${chalk.green('•')} ${tool.name}`); + } + console.log(); + } + + // Tags + if (tags.length > 0) { + console.log(chalk.bold('Recommended skill tags:')); + console.log(` ${chalk.cyan(tags.join(', '))}`); + console.log(); + } + + if (this.json) { + console.log(chalk.gray('\nJSON:')); + console.log(JSON.stringify(stack, null, 2)); + } + + return 0; + } + + /** + * List detected agents + */ + private async listAgents(): Promise { + const sync = createContextSync(process.cwd()); + const detected = sync.detectAgents(); + const status = sync.checkStatus(); + const adapters = getAllAdapters(); + + console.log(chalk.bold('\nAgent Status:\n')); + + for (const [agent, info] of Object.entries(status)) { + const adapter = adapters.find(a => a.type === agent); + const name = adapter?.name || agent; + const isDetected = detected.includes(agent as AgentType); + + const statusIcon = info.hasSkills ? chalk.green('●') : isDetected ? chalk.yellow('○') : chalk.gray('○'); + const skillInfo = info.skillCount > 0 ? chalk.gray(` (${info.skillCount} skills)`) : ''; + + console.log(` ${statusIcon} ${name.padEnd(20)} ${chalk.gray(agent)}${skillInfo}`); + + if (this.verbose && info.skills.length > 0) { + for (const skill of info.skills) { + console.log(chalk.gray(` └─ ${skill}`)); + } + } + } + + console.log(); + console.log(chalk.gray('Legend: ● has skills, ○ detected/configured, ○ not detected')); + console.log(); + + return 0; + } + + /** + * Print context summary + */ + private printContextSummary(context: ProjectContext): void { + console.log(chalk.bold('Project:')); + console.log(` Name: ${chalk.cyan(context.project.name)}`); + if (context.project.type) { + console.log(` Type: ${context.project.type}`); + } + if (context.project.description) { + console.log(` Description: ${context.project.description}`); + } + + // Stack summary + const stackItems: string[] = []; + if (context.stack.languages.length > 0) { + stackItems.push(`${context.stack.languages.length} languages`); + } + if (context.stack.frameworks.length > 0) { + stackItems.push(`${context.stack.frameworks.length} frameworks`); + } + if (context.stack.libraries.length > 0) { + stackItems.push(`${context.stack.libraries.length} libraries`); + } + if (context.stack.databases.length > 0) { + stackItems.push(`${context.stack.databases.length} databases`); + } + + if (stackItems.length > 0) { + console.log(`\n${chalk.bold('Stack:')} ${stackItems.join(', ')}`); + + // Show top items + const topFrameworks = context.stack.frameworks.slice(0, 3).map(f => f.name); + if (topFrameworks.length > 0) { + console.log(` Frameworks: ${chalk.cyan(topFrameworks.join(', '))}`); + } + + const topLibs = context.stack.libraries.slice(0, 3).map(l => l.name); + if (topLibs.length > 0) { + console.log(` Libraries: ${chalk.cyan(topLibs.join(', '))}`); + } + } + + // Skills summary + if (context.skills) { + console.log(`\n${chalk.bold('Skills:')}`); + console.log(` Installed: ${context.skills.installed?.length || 0}`); + console.log(` Auto-sync: ${context.skills.autoSync ? 'enabled' : 'disabled'}`); + } + + // Agents summary + if (context.agents) { + console.log(`\n${chalk.bold('Agents:')}`); + if (context.agents.primary) { + console.log(` Primary: ${chalk.cyan(context.agents.primary)}`); + } + if (context.agents.synced?.length) { + console.log(` Synced: ${context.agents.synced.join(', ')}`); + } + } + } +} diff --git a/packages/cli/src/commands/create.ts b/packages/cli/src/commands/create.ts new file mode 100644 index 00000000..d0e26c36 --- /dev/null +++ b/packages/cli/src/commands/create.ts @@ -0,0 +1,130 @@ +import { existsSync, mkdirSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; + +export class CreateCommand extends Command { + static override paths = [['create'], ['new']]; + + static override usage = Command.Usage({ + description: 'Create a new skill with proper structure', + examples: [ + ['Create a new skill', '$0 create my-skill'], + ['Create with all optional directories', '$0 create my-skill --full'], + ['Create with scripts directory', '$0 create my-skill --scripts'], + ], + }); + + name = Option.String({ required: true, name: 'skill-name' }); + + full = Option.Boolean('--full,-f', false, { + description: 'Include all optional directories (references, scripts, assets)', + }); + + scripts = Option.Boolean('--scripts', false, { + description: 'Include scripts directory', + }); + + references = Option.Boolean('--references', false, { + description: 'Include references directory', + }); + + assets = Option.Boolean('--assets', false, { + description: 'Include assets directory', + }); + + directory = Option.String('--dir,-d', { + description: 'Parent directory to create skill in (default: current directory)', + }); + + async execute(): Promise { + const skillName = this.name.toLowerCase(); + + if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(skillName)) { + console.error(chalk.red('Invalid skill name')); + console.error(chalk.dim('Must be lowercase alphanumeric with hyphens (e.g., my-skill)')); + return 1; + } + + const parentDir = this.directory || process.cwd(); + const skillDir = join(parentDir, skillName); + + if (existsSync(skillDir)) { + console.error(chalk.red(`Directory already exists: ${skillDir}`)); + return 1; + } + + try { + mkdirSync(skillDir, { recursive: true }); + + const skillMd = generateSkillMd(skillName); + writeFileSync(join(skillDir, 'SKILL.md'), skillMd); + + if (this.full || this.references) { + const refsDir = join(skillDir, 'references'); + mkdirSync(refsDir); + writeFileSync(join(refsDir, '.gitkeep'), ''); + } + + if (this.full || this.scripts) { + const scriptsDir = join(skillDir, 'scripts'); + mkdirSync(scriptsDir); + writeFileSync(join(scriptsDir, '.gitkeep'), ''); + } + + if (this.full || this.assets) { + const assetsDir = join(skillDir, 'assets'); + mkdirSync(assetsDir); + writeFileSync(join(assetsDir, '.gitkeep'), ''); + } + + console.log(chalk.green(`Created skill: ${skillName}`)); + console.log(); + console.log(chalk.dim('Structure:')); + console.log(chalk.dim(` ${skillDir}/`)); + console.log(chalk.dim(' ├── SKILL.md')); + if (this.full || this.references) console.log(chalk.dim(' ├── references/')); + if (this.full || this.scripts) console.log(chalk.dim(' ├── scripts/')); + if (this.full || this.assets) console.log(chalk.dim(' └── assets/')); + console.log(); + console.log(chalk.cyan('Next steps:')); + console.log(chalk.dim(' 1. Edit SKILL.md with your instructions')); + console.log(chalk.dim(' 2. Validate: skillkit validate ' + skillDir)); + console.log(chalk.dim(' 3. Test: skillkit read ' + skillName)); + + return 0; + } catch (error) { + console.error(chalk.red('Failed to create skill')); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + return 1; + } + } +} + +function generateSkillMd(name: string): string { + const title = name + .split('-') + .map(word => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' '); + + return `--- +name: ${name} +description: Describe what this skill does and when to use it. Include trigger keywords. +--- + +# ${title} + +Instructions for the AI agent on how to use this skill. + +## When to Use + +- Scenario 1 +- Scenario 2 + +## Steps + +1. First step +2. Second step +3. Third step +`; +} diff --git a/packages/cli/src/commands/enable.ts b/packages/cli/src/commands/enable.ts new file mode 100644 index 00000000..96ea71d4 --- /dev/null +++ b/packages/cli/src/commands/enable.ts @@ -0,0 +1,106 @@ +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { setSkillEnabled, findSkill } from '@skillkit/core'; +import { getSearchDirs } from '../helpers.js'; + +export class EnableCommand extends Command { + static override paths = [['enable']]; + + static override usage = Command.Usage({ + description: 'Enable one or more skills', + examples: [ + ['Enable a skill', '$0 enable pdf'], + ['Enable multiple skills', '$0 enable pdf xlsx docx'], + ], + }); + + skills = Option.Rest({ required: 1 }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + let success = 0; + let failed = 0; + + for (const skillName of this.skills) { + const skill = findSkill(skillName, searchDirs); + + if (!skill) { + console.log(chalk.red(`Skill not found: ${skillName}`)); + failed++; + continue; + } + + if (skill.enabled) { + console.log(chalk.dim(`Already enabled: ${skillName}`)); + continue; + } + + const result = setSkillEnabled(skill.path, true); + + if (result) { + console.log(chalk.green(`Enabled: ${skillName}`)); + success++; + } else { + console.log(chalk.red(`Failed to enable: ${skillName}`)); + failed++; + } + } + + if (success > 0) { + console.log(chalk.dim('\nRun `skillkit sync` to update your agent config')); + } + + return failed > 0 ? 1 : 0; + } +} + +export class DisableCommand extends Command { + static override paths = [['disable']]; + + static override usage = Command.Usage({ + description: 'Disable one or more skills', + examples: [ + ['Disable a skill', '$0 disable pdf'], + ['Disable multiple skills', '$0 disable pdf xlsx docx'], + ], + }); + + skills = Option.Rest({ required: 1 }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + let success = 0; + let failed = 0; + + for (const skillName of this.skills) { + const skill = findSkill(skillName, searchDirs); + + if (!skill) { + console.log(chalk.red(`Skill not found: ${skillName}`)); + failed++; + continue; + } + + if (!skill.enabled) { + console.log(chalk.dim(`Already disabled: ${skillName}`)); + continue; + } + + const result = setSkillEnabled(skill.path, false); + + if (result) { + console.log(chalk.yellow(`Disabled: ${skillName}`)); + success++; + } else { + console.log(chalk.red(`Failed to disable: ${skillName}`)); + failed++; + } + } + + if (success > 0) { + console.log(chalk.dim('\nRun `skillkit sync` to update your agent config')); + } + + return failed > 0 ? 1 : 0; + } +} diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts new file mode 100644 index 00000000..63ba53d4 --- /dev/null +++ b/packages/cli/src/commands/index.ts @@ -0,0 +1,15 @@ +// Command exports +export { ListCommand } from './list.js'; +export { ReadCommand } from './read.js'; +export { SyncCommand } from './sync.js'; +export { InitCommand } from './init.js'; +export { EnableCommand, DisableCommand } from './enable.js'; +export { RemoveCommand } from './remove.js'; +export { InstallCommand } from './install.js'; +export { UpdateCommand } from './update.js'; +export { ValidateCommand } from './validate.js'; +export { CreateCommand } from './create.js'; +export { UICommand } from './ui.js'; +export { TranslateCommand } from './translate.js'; +export { ContextCommand } from './context.js'; +export { RecommendCommand } from './recommend.js'; diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts new file mode 100644 index 00000000..cb2b8d59 --- /dev/null +++ b/packages/cli/src/commands/init.ts @@ -0,0 +1,79 @@ +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import type { AgentType } from '@skillkit/core'; +import { detectAgent, getAdapter, getAllAdapters } from '@skillkit/agents'; +import { initProject } from '../helpers.js'; + +export class InitCommand extends Command { + static override paths = [['init']]; + + static override usage = Command.Usage({ + description: 'Initialize skillkit in a project', + examples: [ + ['Auto-detect agent and initialize', '$0 init'], + ['Initialize for specific agent', '$0 init --agent cursor'], + ['List supported agents', '$0 init --list'], + ], + }); + + agent = Option.String('--agent,-a', { + description: 'Target agent type', + }); + + list = Option.Boolean('--list,-l', false, { + description: 'List supported agents', + }); + + async execute(): Promise { + if (this.list) { + console.log(chalk.cyan('Supported agents:\n')); + const adapters = getAllAdapters(); + + for (const adapter of adapters) { + console.log(` ${chalk.green(adapter.type)}`); + console.log(` Name: ${adapter.name}`); + console.log(` Skills dir: ${adapter.skillsDir}`); + console.log(` Config file: ${adapter.configFile}`); + console.log(); + } + + return 0; + } + + try { + let agentType: AgentType; + + if (this.agent) { + agentType = this.agent as AgentType; + } else { + console.log(chalk.dim('Auto-detecting agent...')); + agentType = await detectAgent(); + } + + const adapter = getAdapter(agentType); + + console.log(chalk.cyan(`Initializing for ${adapter.name}...`)); + + await initProject(agentType); + + console.log(); + console.log(chalk.green('Initialized successfully!')); + console.log(); + console.log(chalk.dim('Created:')); + console.log(chalk.dim(` - ${adapter.skillsDir}/ (skills directory)`)); + console.log(chalk.dim(` - skillkit.yaml (config file)`)); + console.log(chalk.dim(` - ${adapter.configFile} (agent config)`)); + console.log(); + console.log(chalk.cyan('Next steps:')); + console.log(chalk.dim(' 1. Install skills: skillkit install owner/repo')); + console.log(chalk.dim(' 2. Sync config: skillkit sync')); + console.log(chalk.dim(' 3. Use skills: skillkit read ')); + + return 0; + } catch (error) { + console.error(chalk.red('Initialization failed')); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + return 1; + } + } +} diff --git a/packages/cli/src/commands/install.ts b/packages/cli/src/commands/install.ts new file mode 100644 index 00000000..e0bbc7d7 --- /dev/null +++ b/packages/cli/src/commands/install.ts @@ -0,0 +1,248 @@ +import { existsSync, mkdirSync, cpSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import chalk from 'chalk'; +import ora from 'ora'; +import { Command, Option } from 'clipanion'; +import { detectProvider, isLocalPath, getProvider } from '@skillkit/core'; +import type { SkillMetadata, GitProvider, AgentType } from '@skillkit/core'; +import { isPathInside } from '@skillkit/core'; +import { getAdapter, detectAgent } from '@skillkit/agents'; +import { getInstallDir, saveSkillMetadata } from '../helpers.js'; + +export class InstallCommand extends Command { + static override paths = [['install'], ['i']]; + + static override usage = Command.Usage({ + description: 'Install skills from GitHub, GitLab, Bitbucket, or local path', + examples: [ + ['Install from GitHub', '$0 install owner/repo'], + ['Install from GitLab', '$0 install gitlab:owner/repo'], + ['Install from Bitbucket', '$0 install bitbucket:owner/repo'], + ['Install specific skills (CI/CD)', '$0 install owner/repo --skills=pdf,xlsx'], + ['Install all skills non-interactively', '$0 install owner/repo --all'], + ['Install from local path', '$0 install ./my-skills'], + ['Install globally', '$0 install owner/repo --global'], + ['List available skills', '$0 install owner/repo --list'], + ['Install to specific agents', '$0 install owner/repo --agent claude-code --agent cursor'], + ], + }); + + source = Option.String({ required: true }); + + skills = Option.String('--skills,-s', { + description: 'Comma-separated list of skills to install (non-interactive)', + }); + + all = Option.Boolean('--all,-a', false, { + description: 'Install all discovered skills (non-interactive)', + }); + + yes = Option.Boolean('--yes,-y', false, { + description: 'Skip confirmation prompts', + }); + + global = Option.Boolean('--global,-g', false, { + description: 'Install to global skills directory', + }); + + force = Option.Boolean('--force,-f', false, { + description: 'Overwrite existing skills', + }); + + provider = Option.String('--provider,-p', { + description: 'Force specific provider (github, gitlab, bitbucket)', + }); + + list = Option.Boolean('--list,-l', false, { + description: 'List available skills without installing', + }); + + agent = Option.Array('--agent', { + description: 'Target specific agents (can specify multiple)', + }); + + async execute(): Promise { + const spinner = ora(); + + try { + let providerAdapter = detectProvider(this.source); + + if (this.provider) { + providerAdapter = getProvider(this.provider as GitProvider); + } + + if (!providerAdapter) { + console.error(chalk.red(`Could not detect provider for: ${this.source}`)); + console.error(chalk.dim('Use --provider flag or specify source as:')); + console.error(chalk.dim(' GitHub: owner/repo or https://github.com/owner/repo')); + console.error(chalk.dim(' GitLab: gitlab:owner/repo or https://gitlab.com/owner/repo')); + console.error(chalk.dim(' Bitbucket: bitbucket:owner/repo')); + console.error(chalk.dim(' Local: ./path or ~/path')); + return 1; + } + + spinner.start(`Fetching from ${providerAdapter.name}...`); + + const result = await providerAdapter.clone(this.source, '', { depth: 1 }); + + if (!result.success || !result.path) { + spinner.fail(chalk.red(result.error || 'Failed to fetch source')); + return 1; + } + + spinner.succeed(`Found ${result.skills?.length || 0} skill(s)`); + + const discoveredSkills = result.discoveredSkills || []; + + if (this.list) { + if (discoveredSkills.length === 0) { + console.log(chalk.yellow('\nNo skills found in this repository')); + } else { + console.log(chalk.cyan('\nAvailable skills:\n')); + for (const skill of discoveredSkills) { + console.log(` ${chalk.green(skill.name)}`); + } + console.log(); + console.log(chalk.dim(`Total: ${discoveredSkills.length} skill(s)`)); + console.log(chalk.dim('\nTo install specific skills: skillkit install --skills=skill1,skill2')); + console.log(chalk.dim('To install all skills: skillkit install --all')); + } + + const cleanupPath = result.tempRoot || result.path; + if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) { + rmSync(cleanupPath, { recursive: true, force: true }); + } + + return 0; + } + + let skillsToInstall = discoveredSkills; + + if (this.skills) { + const requestedSkills = this.skills.split(',').map(s => s.trim()); + const available = discoveredSkills.map(s => s.name); + const notFound = requestedSkills.filter(s => !available.includes(s)); + + if (notFound.length > 0) { + console.error(chalk.red(`Skills not found: ${notFound.join(', ')}`)); + console.error(chalk.dim(`Available: ${available.join(', ')}`)); + return 1; + } + + skillsToInstall = discoveredSkills.filter(s => requestedSkills.includes(s.name)); + } else if (this.all || this.yes) { + skillsToInstall = discoveredSkills; + } else { + skillsToInstall = discoveredSkills; + + if (skillsToInstall.length > 0) { + console.log(chalk.cyan('\nSkills to install:')); + skillsToInstall.forEach(s => console.log(chalk.dim(` - ${s.name}`))); + console.log(); + } + } + + if (skillsToInstall.length === 0) { + console.log(chalk.yellow('No skills to install')); + return 0; + } + + let targetAgents: AgentType[]; + if (this.agent && this.agent.length > 0) { + targetAgents = this.agent as AgentType[]; + } else { + const detectedAgent = await detectAgent(); + targetAgents = [detectedAgent]; + } + + let totalInstalled = 0; + const installResults: { agent: string; dir: string; count: number }[] = []; + + for (const agentType of targetAgents) { + const adapter = getAdapter(agentType); + const installDir = getInstallDir(this.global, agentType); + + if (!existsSync(installDir)) { + mkdirSync(installDir, { recursive: true }); + } + + if (targetAgents.length > 1) { + console.log(chalk.cyan(`\nInstalling to ${adapter.name}...`)); + } + + let installed = 0; + for (const skill of skillsToInstall) { + const skillName = skill.name; + const sourcePath = skill.path; + const targetPath = join(installDir, skillName); + + if (existsSync(targetPath) && !this.force) { + console.log(chalk.yellow(` Skipping ${skillName} (already exists, use --force to overwrite)`)); + continue; + } + + const securityRoot = result.tempRoot || result.path; + if (!isPathInside(sourcePath, securityRoot)) { + console.log(chalk.red(` Skipping ${skillName} (path traversal detected)`)); + continue; + } + + spinner.start(`Installing ${skillName}...`); + + try { + if (existsSync(targetPath)) { + rmSync(targetPath, { recursive: true, force: true }); + } + + cpSync(sourcePath, targetPath, { recursive: true, dereference: true }); + + const metadata: SkillMetadata = { + name: skillName, + description: '', + source: this.source, + sourceType: providerAdapter.type, + subpath: skillName, + installedAt: new Date().toISOString(), + enabled: true, + }; + saveSkillMetadata(targetPath, metadata); + + spinner.succeed(chalk.green(`Installed ${skillName}`)); + installed++; + } catch (error) { + spinner.fail(chalk.red(`Failed to install ${skillName}`)); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + } + } + + totalInstalled += installed; + installResults.push({ agent: adapter.name, dir: installDir, count: installed }); + } + + const cleanupPath = result.tempRoot || result.path; + if (!isLocalPath(this.source) && cleanupPath && existsSync(cleanupPath)) { + rmSync(cleanupPath, { recursive: true, force: true }); + } + + console.log(); + if (targetAgents.length > 1) { + console.log(chalk.green(`Installed ${totalInstalled} skill(s) across ${targetAgents.length} agents:`)); + for (const r of installResults) { + console.log(chalk.dim(` - ${r.agent}: ${r.count} skill(s) to ${r.dir}`)); + } + } else { + console.log(chalk.green(`Installed ${totalInstalled} skill(s) to ${installResults[0]?.dir}`)); + } + + if (!this.yes) { + console.log(chalk.dim('\nRun `skillkit sync` to update your agent config')); + } + + return 0; + } catch (error) { + spinner.fail(chalk.red('Installation failed')); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + return 1; + } + } +} diff --git a/packages/cli/src/commands/list.ts b/packages/cli/src/commands/list.ts new file mode 100644 index 00000000..3f85c3fa --- /dev/null +++ b/packages/cli/src/commands/list.ts @@ -0,0 +1,107 @@ +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { findAllSkills } from '@skillkit/core'; +import { getSearchDirs } from '../helpers.js'; + +export class ListCommand extends Command { + static override paths = [['list'], ['ls'], ['l']]; + + static override usage = Command.Usage({ + description: 'List all installed skills', + examples: [ + ['List all skills', '$0 list'], + ['Show only enabled skills', '$0 list --enabled'], + ['Show JSON output', '$0 list --json'], + ], + }); + + enabled = Option.Boolean('--enabled,-e', false, { + description: 'Show only enabled skills', + }); + + disabled = Option.Boolean('--disabled,-d', false, { + description: 'Show only disabled skills', + }); + + json = Option.Boolean('--json,-j', false, { + description: 'Output as JSON', + }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + let skills = findAllSkills(searchDirs); + + if (this.enabled) { + skills = skills.filter(s => s.enabled); + } else if (this.disabled) { + skills = skills.filter(s => !s.enabled); + } + + skills.sort((a, b) => { + if (a.location !== b.location) { + return a.location === 'project' ? -1 : 1; + } + return a.name.localeCompare(b.name); + }); + + if (this.json) { + console.log(JSON.stringify(skills, null, 2)); + return 0; + } + + if (skills.length === 0) { + console.log(chalk.yellow('No skills installed')); + console.log(chalk.dim('Install skills with: skillkit install ')); + return 0; + } + + console.log(chalk.cyan(`Installed skills (${skills.length}):\n`)); + + const projectSkills = skills.filter(s => s.location === 'project'); + const globalSkills = skills.filter(s => s.location === 'global'); + + if (projectSkills.length > 0) { + console.log(chalk.blue('Project skills:')); + for (const skill of projectSkills) { + printSkill(skill); + } + console.log(); + } + + if (globalSkills.length > 0) { + console.log(chalk.dim('Global skills:')); + for (const skill of globalSkills) { + printSkill(skill); + } + console.log(); + } + + const enabledCount = skills.filter(s => s.enabled).length; + const disabledCount = skills.length - enabledCount; + + console.log( + chalk.dim( + `${projectSkills.length} project, ${globalSkills.length} global` + + (disabledCount > 0 ? `, ${disabledCount} disabled` : '') + ) + ); + + return 0; + } +} + +function printSkill(skill: { name: string; description: string; enabled: boolean; location: string }) { + const status = skill.enabled ? chalk.green('✓') : chalk.red('○'); + const name = skill.enabled ? skill.name : chalk.dim(skill.name); + const desc = chalk.dim(truncate(skill.description, 50)); + + console.log(` ${status} ${name}`); + if (skill.description) { + console.log(` ${desc}`); + } +} + +function truncate(str: string, maxLen: number): string { + if (str.length <= maxLen) return str; + return str.slice(0, maxLen - 3) + '...'; +} diff --git a/packages/cli/src/commands/read.ts b/packages/cli/src/commands/read.ts new file mode 100644 index 00000000..6a3283d4 --- /dev/null +++ b/packages/cli/src/commands/read.ts @@ -0,0 +1,79 @@ +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { findSkill, readSkillContent } from '@skillkit/core'; +import { getSearchDirs } from '../helpers.js'; + +export class ReadCommand extends Command { + static override paths = [['read'], ['r']]; + + static override usage = Command.Usage({ + description: 'Read skill content for AI agent consumption', + examples: [ + ['Read a single skill', '$0 read pdf'], + ['Read multiple skills', '$0 read pdf,xlsx,docx'], + ['Read with verbose output', '$0 read pdf --verbose'], + ], + }); + + skills = Option.String({ required: true }); + + verbose = Option.Boolean('--verbose,-v', false, { + description: 'Show additional information', + }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + + const skillNames = this.skills + .split(',') + .map(s => s.trim()) + .filter(s => s.length > 0); + + if (skillNames.length === 0) { + console.error(chalk.red('No skill names provided')); + return 1; + } + + let exitCode = 0; + + for (const skillName of skillNames) { + const skill = findSkill(skillName, searchDirs); + + if (!skill) { + console.error(chalk.red(`Skill not found: ${skillName}`)); + console.error(chalk.dim('Available directories:')); + searchDirs.forEach(d => console.error(chalk.dim(` - ${d}`))); + exitCode = 1; + continue; + } + + if (!skill.enabled) { + console.error(chalk.yellow(`Skill disabled: ${skillName}`)); + console.error(chalk.dim('Enable with: skillkit enable ' + skillName)); + exitCode = 1; + continue; + } + + const content = readSkillContent(skill.path); + + if (!content) { + console.error(chalk.red(`Could not read SKILL.md for: ${skillName}`)); + exitCode = 1; + continue; + } + + console.log(`Reading: ${skillName}`); + console.log(`Base directory: ${skill.path}`); + console.log(); + console.log(content); + console.log(); + console.log(`Skill read: ${skillName}`); + + if (skillNames.length > 1 && skillName !== skillNames[skillNames.length - 1]) { + console.log('\n---\n'); + } + } + + return exitCode; + } +} diff --git a/packages/cli/src/commands/recommend.ts b/packages/cli/src/commands/recommend.ts new file mode 100644 index 00000000..23c545af --- /dev/null +++ b/packages/cli/src/commands/recommend.ts @@ -0,0 +1,544 @@ +import { Command, Option } from 'clipanion'; +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { resolve, join } from 'node:path'; +import chalk from 'chalk'; +import { + type ProjectProfile, + type SkillSummary, + type SkillIndex, + type ScoredSkill, + ContextManager, + RecommendationEngine, +} from '@skillkit/core'; + +const INDEX_PATH = join(process.env.HOME || '~', '.skillkit', 'index.json'); +const INDEX_CACHE_HOURS = 24; + +/** + * Recommend command - get smart skill recommendations based on project analysis + */ +export class RecommendCommand extends Command { + static override paths = [['recommend'], ['rec']]; + + static override usage = Command.Usage({ + description: 'Get skill recommendations based on your project', + details: ` + The recommend command analyzes your project and suggests skills that match + your technology stack, frameworks, and patterns. + + It scores skills based on: + - Framework compatibility (React, Vue, Next.js, etc.) + - Language match (TypeScript, Python, etc.) + - Library alignment (Tailwind, Prisma, etc.) + - Tag relevance + - Popularity and quality metrics + + Run "skillkit recommend --update" to refresh the skill index from known sources. + `, + examples: [ + ['Get recommendations', '$0 recommend'], + ['Show top 5 recommendations', '$0 recommend --limit 5'], + ['Filter by category', '$0 recommend --category security'], + ['Show detailed reasons', '$0 recommend --verbose'], + ['Update skill index', '$0 recommend --update'], + ['Search for skills by task', '$0 recommend --search "authentication"'], + ], + }); + + // Limit number of results + limit = Option.String('--limit,-l', { + description: 'Maximum number of recommendations', + }); + + // Minimum score threshold + minScore = Option.String('--min-score', { + description: 'Minimum match score (0-100)', + }); + + // Filter by category/tag + category = Option.Array('--category,-c', { + description: 'Filter by category (can be used multiple times)', + }); + + // Verbose output with reasons + verbose = Option.Boolean('--verbose,-v', false, { + description: 'Show detailed match reasons', + }); + + // Update index + update = Option.Boolean('--update,-u', false, { + description: 'Update skill index from sources', + }); + + // Search mode + search = Option.String('--search,-s', { + description: 'Search skills by task/query', + }); + + // Include installed skills + includeInstalled = Option.Boolean('--include-installed', false, { + description: 'Include already installed skills', + }); + + // JSON output + json = Option.Boolean('--json,-j', false, { + description: 'Output in JSON format', + }); + + // Project path + projectPath = Option.String('--path,-p', { + description: 'Project path (default: current directory)', + }); + + async execute(): Promise { + const targetPath = resolve(this.projectPath || process.cwd()); + + // Handle index update + if (this.update) { + return this.updateIndex(); + } + + // Load or create project profile + const profile = await this.getProjectProfile(targetPath); + if (!profile) { + console.error(chalk.red('Failed to analyze project')); + return 1; + } + + // Load skill index + const index = this.loadIndex(); + if (!index || index.skills.length === 0) { + console.log(chalk.yellow('No skill index found.')); + console.log(chalk.dim('Run "skillkit recommend --update" to fetch skills from known sources.')); + console.log(chalk.dim('Or install skills manually with "skillkit install "\n')); + + // Still show project profile + this.showProjectProfile(profile); + return 0; + } + + // Create recommendation engine + const engine = new RecommendationEngine(); + engine.loadIndex(index); + + // Handle search mode + if (this.search) { + return this.handleSearch(engine, this.search); + } + + // Get recommendations + const result = engine.recommend(profile, { + limit: this.limit ? parseInt(this.limit, 10) : 10, + minScore: this.minScore ? parseInt(this.minScore, 10) : 30, + categories: this.category, + excludeInstalled: !this.includeInstalled, + includeReasons: this.verbose, + }); + + // Output results + if (this.json) { + console.log(JSON.stringify(result, null, 2)); + return 0; + } + + this.displayRecommendations(result.recommendations, profile, result.totalSkillsScanned); + return 0; + } + + /** + * Get project profile from context or by analyzing project + */ + private async getProjectProfile(projectPath: string): Promise { + const manager = new ContextManager(projectPath); + let context = manager.get(); + + if (!context) { + // Auto-analyze project + if (!this.json) { + console.log(chalk.dim('Analyzing project...\n')); + } + context = manager.init(); + } + + if (!context) { + return null; + } + + // Convert ProjectContext to ProjectProfile + return { + name: context.project.name, + type: context.project.type, + stack: context.stack, + patterns: context.patterns, + installedSkills: context.skills?.installed || [], + excludedSkills: context.skills?.excluded || [], + }; + } + + /** + * Show project profile summary + */ + private showProjectProfile(profile: ProjectProfile): void { + console.log(chalk.cyan('Project Profile:')); + console.log(` Name: ${chalk.bold(profile.name)}`); + if (profile.type) { + console.log(` Type: ${profile.type}`); + } + + const stackItems: string[] = []; + for (const lang of profile.stack.languages) { + stackItems.push(`${lang.name}${lang.version ? ` ${lang.version}` : ''}`); + } + for (const fw of profile.stack.frameworks) { + stackItems.push(`${fw.name}${fw.version ? ` ${fw.version}` : ''}`); + } + + if (stackItems.length > 0) { + console.log(` Stack: ${chalk.dim(stackItems.join(', '))}`); + } + console.log(); + } + + /** + * Display recommendations + */ + private displayRecommendations( + recommendations: ScoredSkill[], + profile: ProjectProfile, + totalScanned: number + ): void { + // Show project profile + this.showProjectProfile(profile); + + if (recommendations.length === 0) { + console.log(chalk.yellow('No matching skills found.')); + console.log(chalk.dim('Try lowering the minimum score with --min-score')); + return; + } + + console.log(chalk.cyan(`Recommended Skills (${recommendations.length} of ${totalScanned} scanned):\n`)); + + for (const rec of recommendations) { + const scoreColor = rec.score >= 70 ? chalk.green : rec.score >= 50 ? chalk.yellow : chalk.dim; + const scoreBar = this.getScoreBar(rec.score); + + console.log(` ${scoreColor(`${rec.score}%`)} ${scoreBar} ${chalk.bold(rec.skill.name)}`); + + if (rec.skill.description) { + console.log(` ${chalk.dim(truncate(rec.skill.description, 70))}`); + } + + if (rec.skill.source) { + console.log(` ${chalk.dim('Source:')} ${rec.skill.source}`); + } + + if (this.verbose && rec.reasons.length > 0) { + console.log(chalk.dim(' Reasons:')); + for (const reason of rec.reasons.filter(r => r.weight > 0)) { + console.log(` ${chalk.dim('•')} ${reason.description} (+${reason.weight})`); + } + } + + if (rec.warnings.length > 0) { + for (const warning of rec.warnings) { + console.log(` ${chalk.yellow('⚠')} ${warning}`); + } + } + + console.log(); + } + + console.log(chalk.dim('Install with: skillkit install ')); + } + + /** + * Generate a visual score bar + */ + private getScoreBar(score: number): string { + const filled = Math.round(score / 10); + const empty = 10 - filled; + return chalk.green('█'.repeat(filled)) + chalk.dim('░'.repeat(empty)); + } + + /** + * Handle search mode + */ + private handleSearch(engine: RecommendationEngine, query: string): number { + const results = engine.search({ + query, + limit: this.limit ? parseInt(this.limit, 10) : 10, + semantic: true, + filters: { + minScore: this.minScore ? parseInt(this.minScore, 10) : undefined, + }, + }); + + if (this.json) { + console.log(JSON.stringify(results, null, 2)); + return 0; + } + + if (results.length === 0) { + console.log(chalk.yellow(`No skills found matching "${query}"`)); + return 0; + } + + console.log(chalk.cyan(`Search results for "${query}" (${results.length} found):\n`)); + + for (const result of results) { + const relevanceColor = + result.relevance >= 70 ? chalk.green : result.relevance >= 50 ? chalk.yellow : chalk.dim; + + console.log(` ${relevanceColor(`${result.relevance}%`)} ${chalk.bold(result.skill.name)}`); + + if (result.snippet) { + console.log(` ${chalk.dim(result.snippet)}`); + } + + if (result.matchedTerms.length > 0) { + console.log(` ${chalk.dim('Matched:')} ${result.matchedTerms.join(', ')}`); + } + + console.log(); + } + + return 0; + } + + /** + * Load skill index from cache + */ + private loadIndex(): SkillIndex | null { + if (!existsSync(INDEX_PATH)) { + return null; + } + + try { + const content = readFileSync(INDEX_PATH, 'utf-8'); + const index = JSON.parse(content) as SkillIndex; + + // Check if index is stale + const lastUpdated = new Date(index.lastUpdated); + const hoursSinceUpdate = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60); + + if (hoursSinceUpdate > INDEX_CACHE_HOURS && !this.json) { + console.log( + chalk.dim(`Index is ${Math.round(hoursSinceUpdate)} hours old. Run --update to refresh.\n`) + ); + } + + return index; + } catch { + return null; + } + } + + /** + * Update skill index from sources + */ + private updateIndex(): number { + console.log(chalk.cyan('Updating skill index...\n')); + + // For now, create a sample index with well-known skill repositories + // In the future, this would fetch from a registry or known skill sources + const sampleIndex: SkillIndex = { + version: 1, + lastUpdated: new Date().toISOString(), + skills: getSampleSkills(), + sources: [ + { + name: 'vercel-labs', + url: 'https://github.com/vercel-labs/agent-skills', + lastFetched: new Date().toISOString(), + skillCount: 5, + }, + { + name: 'anthropics', + url: 'https://github.com/anthropics/skills', + lastFetched: new Date().toISOString(), + skillCount: 3, + }, + ], + }; + + // Save index + const indexDir = join(process.env.HOME || '~', '.skillkit'); + if (!existsSync(indexDir)) { + mkdirSync(indexDir, { recursive: true }); + } + + writeFileSync(INDEX_PATH, JSON.stringify(sampleIndex, null, 2)); + + console.log(chalk.green(`✓ Updated index with ${sampleIndex.skills.length} skills`)); + console.log(chalk.dim(` Sources: ${sampleIndex.sources.map((s) => s.name).join(', ')}`)); + console.log(chalk.dim(` Saved to: ${INDEX_PATH}\n`)); + + return 0; + } +} + +/** + * Truncate string to max length + */ +function truncate(str: string, maxLen: number): string { + if (str.length <= maxLen) return str; + return str.slice(0, maxLen - 3) + '...'; +} + +/** + * Sample skills for the index (in a real implementation, this would fetch from sources) + */ +function getSampleSkills(): SkillSummary[] { + return [ + { + name: 'vercel-react-best-practices', + description: 'Modern React patterns including Server Components, hooks best practices, and performance optimization', + source: 'vercel-labs/agent-skills', + tags: ['react', 'frontend', 'typescript', 'nextjs', 'performance'], + compatibility: { + frameworks: ['react', 'nextjs'], + languages: ['typescript', 'javascript'], + libraries: [], + }, + popularity: 1500, + quality: 95, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'tailwind-v4-patterns', + description: 'Tailwind CSS v4 utility patterns, responsive design, and component styling best practices', + source: 'vercel-labs/agent-skills', + tags: ['tailwind', 'css', 'styling', 'frontend', 'responsive'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript'], + libraries: ['tailwindcss'], + }, + popularity: 1200, + quality: 92, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'nextjs-app-router', + description: 'Next.js App Router patterns including layouts, server actions, and data fetching', + source: 'vercel-labs/agent-skills', + tags: ['nextjs', 'react', 'routing', 'server-actions', 'frontend'], + compatibility: { + frameworks: ['nextjs'], + languages: ['typescript', 'javascript'], + libraries: [], + }, + popularity: 1100, + quality: 94, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'typescript-strict-patterns', + description: 'TypeScript strict mode patterns, type safety, and advanced type utilities', + source: 'anthropics/skills', + tags: ['typescript', 'types', 'safety', 'patterns'], + compatibility: { + frameworks: [], + languages: ['typescript'], + libraries: [], + }, + popularity: 900, + quality: 90, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'supabase-best-practices', + description: 'Supabase integration patterns including auth, database queries, and real-time subscriptions', + source: 'anthropics/skills', + tags: ['supabase', 'database', 'auth', 'backend', 'postgresql'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript'], + libraries: ['@supabase/supabase-js'], + }, + popularity: 800, + quality: 88, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'vitest-testing-patterns', + description: 'Testing patterns with Vitest including mocking, assertions, and test organization', + source: 'anthropics/skills', + tags: ['vitest', 'testing', 'typescript', 'mocking', 'tdd'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript'], + libraries: ['vitest'], + }, + popularity: 700, + quality: 86, + lastUpdated: new Date().toISOString(), + verified: false, + }, + { + name: 'prisma-database-patterns', + description: 'Prisma ORM patterns for schema design, migrations, and efficient queries', + source: 'vercel-labs/agent-skills', + tags: ['prisma', 'database', 'orm', 'postgresql', 'backend'], + compatibility: { + frameworks: [], + languages: ['typescript'], + libraries: ['@prisma/client'], + }, + popularity: 850, + quality: 89, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'security-best-practices', + description: 'Security patterns for web applications including XSS prevention, CSRF, and secure headers', + source: 'trailofbits/skills', + tags: ['security', 'xss', 'csrf', 'headers', 'owasp'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript', 'python'], + libraries: [], + }, + popularity: 600, + quality: 95, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'python-fastapi-patterns', + description: 'FastAPI best practices for building high-performance Python APIs', + source: 'python-skills/fastapi', + tags: ['python', 'fastapi', 'backend', 'api', 'async'], + compatibility: { + frameworks: ['fastapi'], + languages: ['python'], + libraries: [], + }, + popularity: 550, + quality: 85, + lastUpdated: new Date().toISOString(), + verified: false, + }, + { + name: 'zustand-state-management', + description: 'Zustand state management patterns for React applications', + source: 'react-skills/state', + tags: ['zustand', 'react', 'state-management', 'frontend'], + compatibility: { + frameworks: ['react'], + languages: ['typescript', 'javascript'], + libraries: ['zustand'], + }, + popularity: 650, + quality: 84, + lastUpdated: new Date().toISOString(), + verified: false, + }, + ]; +} diff --git a/packages/cli/src/commands/remove.ts b/packages/cli/src/commands/remove.ts new file mode 100644 index 00000000..c9a80402 --- /dev/null +++ b/packages/cli/src/commands/remove.ts @@ -0,0 +1,60 @@ +import { existsSync, rmSync } from 'node:fs'; +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { findSkill } from '@skillkit/core'; +import { getSearchDirs } from '../helpers.js'; + +export class RemoveCommand extends Command { + static override paths = [['remove'], ['rm'], ['uninstall']]; + + static override usage = Command.Usage({ + description: 'Remove installed skills', + examples: [ + ['Remove a skill', '$0 remove pdf'], + ['Remove multiple skills', '$0 remove pdf xlsx docx'], + ['Force removal without confirmation', '$0 remove pdf --force'], + ], + }); + + skills = Option.Rest({ required: 1 }); + + force = Option.Boolean('--force,-f', false, { + description: 'Skip confirmation', + }); + + async execute(): Promise { + const searchDirs = getSearchDirs(); + let removed = 0; + let failed = 0; + + for (const skillName of this.skills) { + const skill = findSkill(skillName, searchDirs); + + if (!skill) { + console.log(chalk.yellow(`Skill not found: ${skillName}`)); + continue; + } + + if (!existsSync(skill.path)) { + console.log(chalk.yellow(`Path not found: ${skill.path}`)); + continue; + } + + try { + rmSync(skill.path, { recursive: true, force: true }); + console.log(chalk.green(`Removed: ${skillName}`)); + removed++; + } catch (error) { + console.log(chalk.red(`Failed to remove: ${skillName}`)); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + failed++; + } + } + + if (removed > 0) { + console.log(chalk.dim('\nRun `skillkit sync` to update your agent config')); + } + + return failed > 0 ? 1 : 0; + } +} diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.ts new file mode 100644 index 00000000..3225ab46 --- /dev/null +++ b/packages/cli/src/commands/sync.ts @@ -0,0 +1,153 @@ +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { dirname } from 'node:path'; +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { loadConfig, findAllSkills } from '@skillkit/core'; +import type { AgentType } from '@skillkit/core'; +import { getAdapter, detectAgent } from '@skillkit/agents'; +import { getSearchDirs, getAgentConfigPath } from '../helpers.js'; + +export class SyncCommand extends Command { + static override paths = [['sync'], ['s']]; + + static override usage = Command.Usage({ + description: 'Sync skills to agent configuration file', + examples: [ + ['Sync all enabled skills', '$0 sync'], + ['Sync to specific file', '$0 sync --output AGENTS.md'], + ['Sync for specific agent', '$0 sync --agent cursor'], + ['Only sync enabled skills', '$0 sync --enabled-only'], + ], + }); + + output = Option.String('--output,-o', { + description: 'Output file path (default: agent-specific config file)', + }); + + agent = Option.String('--agent,-a', { + description: 'Target agent type (claude-code, cursor, codex, etc.)', + }); + + enabledOnly = Option.Boolean('--enabled-only,-e', true, { + description: 'Only include enabled skills (default: true)', + }); + + yes = Option.Boolean('--yes,-y', false, { + description: 'Skip confirmation prompts', + }); + + async execute(): Promise { + try { + let agentType: AgentType; + + if (this.agent) { + agentType = this.agent as AgentType; + } else { + const config = loadConfig(); + agentType = config.agent || (await detectAgent()); + } + + const adapter = getAdapter(agentType); + + const outputPath = this.output || getAgentConfigPath(agentType); + + const searchDirs = getSearchDirs(agentType); + let skills = findAllSkills(searchDirs); + + if (this.enabledOnly) { + skills = skills.filter(s => s.enabled); + } + + if (skills.length === 0) { + console.log(chalk.yellow('No skills found to sync')); + console.log(chalk.dim('Install skills with: skillkit install ')); + return 0; + } + + console.log(chalk.cyan(`Syncing ${skills.length} skill(s) for ${adapter.name}:`)); + skills.forEach(s => { + const status = s.enabled ? chalk.green('✓') : chalk.dim('○'); + const location = s.location === 'project' ? chalk.blue('[project]') : chalk.dim('[global]'); + console.log(` ${status} ${s.name} ${location}`); + }); + console.log(); + + const config = adapter.generateConfig(skills); + + if (!config) { + console.log(chalk.yellow('No configuration generated')); + return 0; + } + + let existingContent = ''; + if (existsSync(outputPath)) { + existingContent = readFileSync(outputPath, 'utf-8'); + } + + const newContent = updateConfigContent(existingContent, config, agentType); + + const dir = dirname(outputPath); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + + writeFileSync(outputPath, newContent, 'utf-8'); + + console.log(chalk.green(`Synced to ${outputPath}`)); + console.log(chalk.dim(`Agent: ${adapter.name}`)); + + return 0; + } catch (error) { + console.error(chalk.red('Sync failed')); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + return 1; + } + } +} + +function updateConfigContent(existing: string, newConfig: string, agentType: AgentType): string { + const markers: Record = { + 'claude-code': { + start: '', + end: '', + }, + cursor: { + start: '', + end: '', + }, + universal: { + start: '', + end: '', + }, + }; + + const agentMarkers = markers[agentType] || markers.universal; + + const startIdx = existing.indexOf(agentMarkers.start); + const endIdx = existing.indexOf(agentMarkers.end); + + if (startIdx !== -1 && endIdx !== -1) { + return ( + existing.slice(0, startIdx) + + newConfig.slice(newConfig.indexOf(agentMarkers.start)) + + existing.slice(endIdx + agentMarkers.end.length) + ); + } + + const genericStart = ''; + const genericEnd = ''; + const gStartIdx = existing.indexOf(genericStart); + const gEndIdx = existing.indexOf(genericEnd); + + if (gStartIdx !== -1 && gEndIdx !== -1) { + return ( + existing.slice(0, gStartIdx) + newConfig + existing.slice(gEndIdx + genericEnd.length) + ); + } + + if (existing.trim()) { + return existing + '\n\n' + newConfig; + } + + return newConfig; +} diff --git a/packages/cli/src/commands/translate.ts b/packages/cli/src/commands/translate.ts new file mode 100644 index 00000000..f26ee9c6 --- /dev/null +++ b/packages/cli/src/commands/translate.ts @@ -0,0 +1,410 @@ +import { Command, Option } from 'clipanion'; +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { join, basename, dirname } from 'node:path'; +import chalk from 'chalk'; +import { + type AgentType, + translateSkill, + translateSkillFile, + getSupportedTranslationAgents, + translatorRegistry, + findAllSkills, +} from '@skillkit/core'; +import { getAdapter, getAllAdapters } from '@skillkit/agents'; +import { getSearchDirs } from '../helpers.js'; + +/** + * Translate skills between different AI agent formats + */ +export class TranslateCommand extends Command { + static override paths = [['translate']]; + + static override usage = Command.Usage({ + description: 'Translate skills between different AI agent formats', + details: ` + This command translates skills from one AI agent format to another. + + Supported formats: + - SKILL.md (Claude Code, Codex, Gemini CLI, and 10+ more) + - Cursor MDC (.mdc files with globs) + - Windsurf rules (.windsurfrules) + - GitHub Copilot instructions (copilot-instructions.md) + + Translation is bidirectional - you can translate from any format to any other. + `, + examples: [ + ['Translate a skill to Cursor format', '$0 translate my-skill --to cursor'], + ['Translate all skills to Windsurf', '$0 translate --all --to windsurf'], + ['Translate a file directly', '$0 translate ./SKILL.md --to cursor --output ./my-skill.mdc'], + ['List all supported agents', '$0 translate --list'], + ['Preview translation without writing', '$0 translate my-skill --to cursor --dry-run'], + ], + }); + + // Skill name or path + source = Option.String({ required: false }); + + // Target agent + to = Option.String('--to,-t', { + description: 'Target agent to translate to', + }); + + // Source agent (auto-detected if not specified) + from = Option.String('--from,-f', { + description: 'Source agent format (auto-detected if not specified)', + }); + + // Output path + output = Option.String('--output,-o', { + description: 'Output file path (default: agent skills directory)', + }); + + // Translate all installed skills + all = Option.Boolean('--all,-a', false, { + description: 'Translate all installed skills', + }); + + // Dry run (preview without writing) + dryRun = Option.Boolean('--dry-run,-n', false, { + description: 'Preview translation without writing files', + }); + + // Add metadata comments + metadata = Option.Boolean('--metadata,-m', false, { + description: 'Add translation metadata to output', + }); + + // Force overwrite + force = Option.Boolean('--force', false, { + description: 'Overwrite existing files', + }); + + // List supported agents + list = Option.Boolean('--list,-l', false, { + description: 'List all supported agents and formats', + }); + + // Show compatibility info + compat = Option.Boolean('--compat,-c', false, { + description: 'Show compatibility info between agents', + }); + + async execute(): Promise { + // List supported agents + if (this.list) { + return this.listAgents(); + } + + // Show compatibility info + if (this.compat) { + return this.showCompatibility(); + } + + // Validate target agent + if (!this.to) { + console.error(chalk.red('Error: --to/-t target agent is required')); + console.log(chalk.gray('Use --list to see all supported agents')); + return 1; + } + + const targetAgent = this.to as AgentType; + if (!getSupportedTranslationAgents().includes(targetAgent)) { + console.error(chalk.red(`Error: Unknown target agent "${this.to}"`)); + console.log(chalk.gray('Use --list to see all supported agents')); + return 1; + } + + // Translate all skills + if (this.all) { + return this.translateAll(targetAgent); + } + + // Translate single skill + if (!this.source) { + console.error(chalk.red('Error: Please specify a skill name or path, or use --all')); + return 1; + } + + return this.translateSingle(this.source, targetAgent); + } + + /** + * List all supported agents and their formats + */ + private listAgents(): number { + console.log(chalk.bold('\nSupported Agents for Translation:\n')); + + const agents = getSupportedTranslationAgents(); + const adapters = getAllAdapters(); + + // Group by format + const byFormat: Record = {}; + for (const agent of agents) { + const format = translatorRegistry.getFormatForAgent(agent); + if (!byFormat[format]) byFormat[format] = []; + byFormat[format].push(agent); + } + + // Display by format + const formatNames: Record = { + 'skill-md': 'SKILL.md Format (Standard)', + 'cursor-mdc': 'Cursor MDC Format', + 'markdown-rules': 'Markdown Rules Format', + 'external': 'External Systems', + }; + + for (const [format, formatAgents] of Object.entries(byFormat)) { + console.log(chalk.cyan(` ${formatNames[format] || format}:`)); + for (const agent of formatAgents) { + const adapter = adapters.find(a => a.type === agent); + const name = adapter?.name || agent; + console.log(` ${chalk.green(agent.padEnd(16))} ${chalk.gray(name)}`); + } + console.log(); + } + + console.log(chalk.gray('All formats can translate to any other format.')); + console.log(chalk.gray('Use --compat to see compatibility details.\n')); + + return 0; + } + + /** + * Show compatibility between agents + */ + private showCompatibility(): number { + if (!this.from || !this.to) { + console.error(chalk.red('Error: Both --from and --to are required for compatibility check')); + return 1; + } + + const fromAgent = this.from as AgentType; + const toAgent = this.to as AgentType; + + const info = translatorRegistry.getCompatibilityInfo(fromAgent, toAgent); + + console.log(chalk.bold(`\nTranslation: ${fromAgent} → ${toAgent}\n`)); + + if (info.supported) { + console.log(chalk.green(' ✓ Translation supported')); + } else { + console.log(chalk.red(' ✗ Translation not supported')); + return 1; + } + + if (info.warnings.length > 0) { + console.log(chalk.yellow('\n Warnings:')); + for (const warning of info.warnings) { + console.log(chalk.yellow(` • ${warning}`)); + } + } + + if (info.lossyFields.length > 0) { + console.log(chalk.gray('\n Fields with reduced functionality:')); + for (const field of info.lossyFields) { + console.log(chalk.gray(` • ${field}`)); + } + } + + console.log(); + return 0; + } + + /** + * Translate all installed skills + */ + private async translateAll(targetAgent: AgentType): Promise { + const searchDirs = getSearchDirs(); + const skills = findAllSkills(searchDirs); + + if (skills.length === 0) { + console.log(chalk.yellow('No skills found to translate')); + return 0; + } + + console.log(chalk.bold(`\nTranslating ${skills.length} skill(s) to ${targetAgent}...\n`)); + + let success = 0; + let failed = 0; + + for (const skill of skills) { + const skillMdPath = join(skill.path, 'SKILL.md'); + if (!existsSync(skillMdPath)) { + console.log(chalk.yellow(` ⚠ ${skill.name}: No SKILL.md found`)); + failed++; + continue; + } + + const result = translateSkillFile(skillMdPath, targetAgent, { + addMetadata: this.metadata, + }); + + if (result.success) { + if (this.dryRun) { + console.log(chalk.green(` ✓ ${skill.name} → ${result.filename} (dry run)`)); + if (result.warnings.length > 0) { + for (const warning of result.warnings) { + console.log(chalk.gray(` ${warning}`)); + } + } + } else { + // Determine output path + const targetAdapter = getAdapter(targetAgent); + const outputDir = this.output || join(process.cwd(), targetAdapter.skillsDir, skill.name); + + if (!existsSync(outputDir)) { + mkdirSync(outputDir, { recursive: true }); + } + + const outputPath = join(outputDir, result.filename); + + if (existsSync(outputPath) && !this.force) { + console.log(chalk.yellow(` ⚠ ${skill.name}: ${outputPath} exists (use --force)`)); + failed++; + continue; + } + + writeFileSync(outputPath, result.content, 'utf-8'); + console.log(chalk.green(` ✓ ${skill.name} → ${outputPath}`)); + } + + if (result.incompatible.length > 0) { + for (const item of result.incompatible) { + console.log(chalk.gray(` ⚠ ${item}`)); + } + } + + success++; + } else { + console.log(chalk.red(` ✗ ${skill.name}: Translation failed`)); + for (const item of result.incompatible) { + console.log(chalk.red(` ${item}`)); + } + failed++; + } + } + + console.log(); + console.log(chalk.bold(`Translated: ${success}, Failed: ${failed}`)); + + return failed > 0 ? 1 : 0; + } + + /** + * Translate a single skill + */ + private async translateSingle(source: string, targetAgent: AgentType): Promise { + let sourcePath: string; + let skillName: string; + + // Check if source is a file path + if (existsSync(source)) { + sourcePath = source; + skillName = basename(dirname(source)); + if (skillName === '.') { + skillName = basename(source).replace(/\.(md|mdc)$/i, ''); + } + } else { + // Search for skill by name + const searchDirs = getSearchDirs(); + let found = false; + + for (const dir of searchDirs) { + const skillPath = join(dir, source); + const skillMdPath = join(skillPath, 'SKILL.md'); + + if (existsSync(skillMdPath)) { + sourcePath = skillMdPath; + skillName = source; + found = true; + break; + } + } + + if (!found) { + console.error(chalk.red(`Error: Skill "${source}" not found`)); + console.log(chalk.gray('Searched in:')); + for (const dir of searchDirs) { + console.log(chalk.gray(` ${dir}`)); + } + return 1; + } + } + + // Read and translate + const content = readFileSync(sourcePath!, 'utf-8'); + const result = translateSkill(content, targetAgent, { + addMetadata: this.metadata, + sourceFilename: basename(sourcePath!), + }); + + if (!result.success) { + console.error(chalk.red('Translation failed:')); + for (const item of result.incompatible) { + console.error(chalk.red(` ${item}`)); + } + return 1; + } + + // Show warnings + if (result.warnings.length > 0) { + console.log(chalk.yellow('\nWarnings:')); + for (const warning of result.warnings) { + console.log(chalk.yellow(` • ${warning}`)); + } + } + + // Show incompatible features + if (result.incompatible.length > 0) { + console.log(chalk.gray('\nIncompatible features:')); + for (const item of result.incompatible) { + console.log(chalk.gray(` • ${item}`)); + } + } + + // Dry run - just show preview + if (this.dryRun) { + console.log(chalk.bold(`\nTranslated content (${result.filename}):\n`)); + console.log(chalk.gray('─'.repeat(60))); + console.log(result.content); + console.log(chalk.gray('─'.repeat(60))); + return 0; + } + + // Determine output path + let outputPath: string; + if (this.output) { + outputPath = this.output; + } else { + const targetAdapter = getAdapter(targetAgent); + const outputDir = join(process.cwd(), targetAdapter.skillsDir, skillName!); + + if (!existsSync(outputDir)) { + mkdirSync(outputDir, { recursive: true }); + } + + outputPath = join(outputDir, result.filename); + } + + // Check for existing file + if (existsSync(outputPath) && !this.force) { + console.error(chalk.red(`Error: ${outputPath} already exists`)); + console.log(chalk.gray('Use --force to overwrite')); + return 1; + } + + // Write output + const outputDir = dirname(outputPath); + if (!existsSync(outputDir)) { + mkdirSync(outputDir, { recursive: true }); + } + + writeFileSync(outputPath, result.content, 'utf-8'); + + console.log(chalk.green(`\n✓ Translated to ${outputPath}`)); + console.log(chalk.gray(` Format: ${result.targetFormat}`)); + console.log(chalk.gray(` Agent: ${result.targetAgent}`)); + + return 0; + } +} diff --git a/packages/cli/src/commands/ui.ts b/packages/cli/src/commands/ui.ts new file mode 100644 index 00000000..fa082eca --- /dev/null +++ b/packages/cli/src/commands/ui.ts @@ -0,0 +1,19 @@ +import { Command } from 'clipanion'; + +export class UICommand extends Command { + static override paths = [['ui'], ['tui']]; + + static override usage = Command.Usage({ + description: 'Launch the interactive TUI (Terminal User Interface)', + examples: [ + ['Open interactive TUI', '$0 ui'], + ['Alias for TUI', '$0 tui'], + ], + }); + + async execute(): Promise { + const { startTUI } = await import('@skillkit/tui'); + await startTUI(); + return 0; + } +} diff --git a/packages/cli/src/commands/update.ts b/packages/cli/src/commands/update.ts new file mode 100644 index 00000000..50c18e71 --- /dev/null +++ b/packages/cli/src/commands/update.ts @@ -0,0 +1,151 @@ +import { existsSync, rmSync, cpSync } from 'node:fs'; +import { join } from 'node:path'; +import chalk from 'chalk'; +import ora from 'ora'; +import { Command, Option } from 'clipanion'; +import { findAllSkills, findSkill, detectProvider, isLocalPath } from '@skillkit/core'; +import { getSearchDirs, loadSkillMetadata, saveSkillMetadata } from '../helpers.js'; + +export class UpdateCommand extends Command { + static override paths = [['update'], ['u']]; + + static override usage = Command.Usage({ + description: 'Update skills from their original sources', + examples: [ + ['Update all skills', '$0 update'], + ['Update specific skills', '$0 update pdf xlsx'], + ['Force update (overwrite local changes)', '$0 update --force'], + ], + }); + + skills = Option.Rest(); + + force = Option.Boolean('--force,-f', false, { + description: 'Force update even if local changes exist', + }); + + async execute(): Promise { + const spinner = ora(); + const searchDirs = getSearchDirs(); + + let skillsToUpdate; + + if (this.skills.length > 0) { + skillsToUpdate = this.skills + .map(name => findSkill(name, searchDirs)) + .filter((s): s is NonNullable => s !== null); + + const notFound = this.skills.filter(name => !findSkill(name, searchDirs)); + if (notFound.length > 0) { + console.log(chalk.yellow(`Skills not found: ${notFound.join(', ')}`)); + } + } else { + skillsToUpdate = findAllSkills(searchDirs); + } + + if (skillsToUpdate.length === 0) { + console.log(chalk.yellow('No skills to update')); + return 0; + } + + console.log(chalk.cyan(`Updating ${skillsToUpdate.length} skill(s)...\n`)); + + let updated = 0; + let skipped = 0; + let failed = 0; + + for (const skill of skillsToUpdate) { + const metadata = loadSkillMetadata(skill.path); + + if (!metadata) { + console.log(chalk.dim(`Skipping ${skill.name} (no metadata, reinstall needed)`)); + skipped++; + continue; + } + + spinner.start(`Updating ${skill.name}...`); + + try { + if (isLocalPath(metadata.source)) { + const localPath = metadata.subpath + ? join(metadata.source, metadata.subpath) + : metadata.source; + + if (!existsSync(localPath)) { + spinner.warn(chalk.yellow(`${skill.name}: local source missing`)); + skipped++; + continue; + } + + const skillMdPath = join(localPath, 'SKILL.md'); + if (!existsSync(skillMdPath)) { + spinner.warn(chalk.yellow(`${skill.name}: no SKILL.md at source`)); + skipped++; + continue; + } + + rmSync(skill.path, { recursive: true, force: true }); + cpSync(localPath, skill.path, { recursive: true, dereference: true }); + + metadata.updatedAt = new Date().toISOString(); + saveSkillMetadata(skill.path, metadata); + + spinner.succeed(chalk.green(`Updated ${skill.name}`)); + updated++; + } else { + const provider = detectProvider(metadata.source); + + if (!provider) { + spinner.warn(chalk.yellow(`${skill.name}: unknown provider`)); + skipped++; + continue; + } + + const result = await provider.clone(metadata.source, '', { depth: 1 }); + + if (!result.success || !result.path) { + spinner.fail(chalk.red(`${skill.name}: ${result.error || 'clone failed'}`)); + failed++; + continue; + } + + const sourcePath = metadata.subpath + ? join(result.path, metadata.subpath) + : result.path; + + const skillMdPath = join(sourcePath, 'SKILL.md'); + if (!existsSync(skillMdPath)) { + spinner.warn(chalk.yellow(`${skill.name}: no SKILL.md in source`)); + rmSync(result.path, { recursive: true, force: true }); + skipped++; + continue; + } + + rmSync(skill.path, { recursive: true, force: true }); + cpSync(sourcePath, skill.path, { recursive: true, dereference: true }); + + rmSync(result.path, { recursive: true, force: true }); + + metadata.updatedAt = new Date().toISOString(); + saveSkillMetadata(skill.path, metadata); + + spinner.succeed(chalk.green(`Updated ${skill.name}`)); + updated++; + } + } catch (error) { + spinner.fail(chalk.red(`Failed to update ${skill.name}`)); + console.error(chalk.dim(error instanceof Error ? error.message : String(error))); + failed++; + } + } + + console.log(); + console.log( + chalk.cyan( + `Updated: ${updated}, Skipped: ${skipped}, Failed: ${failed}` + ) + ); + + return failed > 0 ? 1 : 0; + } +} diff --git a/packages/cli/src/commands/validate.ts b/packages/cli/src/commands/validate.ts new file mode 100644 index 00000000..c4fc0dd8 --- /dev/null +++ b/packages/cli/src/commands/validate.ts @@ -0,0 +1,87 @@ +import { existsSync, readdirSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import chalk from 'chalk'; +import { Command, Option } from 'clipanion'; +import { validateSkill } from '@skillkit/core'; + +export class ValidateCommand extends Command { + static override paths = [['validate'], ['v']]; + + static override usage = Command.Usage({ + description: 'Validate skill(s) against the Agent Skills specification (agentskills.io)', + examples: [ + ['Validate a skill directory', '$0 validate ./my-skill'], + ['Validate all skills in a directory', '$0 validate ./skills --all'], + ], + }); + + skillPath = Option.String({ required: true }); + + all = Option.Boolean('--all,-a', false, { + description: 'Validate all skills in the directory', + }); + + async execute(): Promise { + const targetPath = this.skillPath; + + if (!existsSync(targetPath)) { + console.error(chalk.red(`Path does not exist: ${targetPath}`)); + return 1; + } + + const skillPaths: string[] = []; + + if (this.all) { + const entries = readdirSync(targetPath, { withFileTypes: true }); + for (const entry of entries) { + if (entry.isDirectory()) { + const skillPath = join(targetPath, entry.name); + if (existsSync(join(skillPath, 'SKILL.md'))) { + skillPaths.push(skillPath); + } + } + } + + if (skillPaths.length === 0) { + console.error(chalk.yellow('No skills found in directory')); + return 1; + } + } else { + skillPaths.push(targetPath); + } + + let hasErrors = false; + + for (const skillPath of skillPaths) { + const skillName = basename(skillPath); + const result = validateSkill(skillPath); + + if (result.valid) { + console.log(chalk.green(`✓ ${skillName}`)); + + if (result.warnings && result.warnings.length > 0) { + result.warnings.forEach(w => { + console.log(chalk.yellow(` ⚠ ${w}`)); + }); + } + } else { + console.log(chalk.red(`✗ ${skillName}`)); + result.errors.forEach(e => { + console.log(chalk.red(` • ${e}`)); + }); + hasErrors = true; + } + } + + console.log(); + + if (hasErrors) { + console.log(chalk.red('Validation failed')); + console.log(chalk.dim('See https://agentskills.io/specification for the complete format')); + return 1; + } + + console.log(chalk.green(`Validated ${skillPaths.length} skill(s) successfully`)); + return 0; + } +} diff --git a/packages/cli/src/helpers.ts b/packages/cli/src/helpers.ts new file mode 100644 index 00000000..ff8d028f --- /dev/null +++ b/packages/cli/src/helpers.ts @@ -0,0 +1,64 @@ +// Re-export commonly used functions with proper adapters +import { + loadConfig, + getSearchDirs as coreGetSearchDirs, + getInstallDir as coreGetInstallDir, + getAgentConfigPath as coreGetAgentConfigPath, + initProject as coreInitProject, + loadSkillMetadata as coreLoadSkillMetadata, + saveSkillMetadata as coreSaveSkillMetadata, +} from '@skillkit/core'; +import { getAdapter, detectAgent } from '@skillkit/agents'; +import type { AgentType, AgentAdapterInfo } from '@skillkit/core'; + +// Re-export metadata functions directly (they don't need adapter bridging) +export const loadSkillMetadata = coreLoadSkillMetadata; +export const saveSkillMetadata = coreSaveSkillMetadata; + +export function getSearchDirs(agentType?: AgentType): string[] { + const type = agentType || loadConfig().agent; + const adapter = getAdapter(type); + const adapterInfo: AgentAdapterInfo = { + type: adapter.type, + name: adapter.name, + skillsDir: adapter.skillsDir, + configFile: adapter.configFile, + }; + return coreGetSearchDirs(adapterInfo); +} + +export function getInstallDir(global = false, agentType?: AgentType): string { + const type = agentType || loadConfig().agent; + const adapter = getAdapter(type); + const adapterInfo: AgentAdapterInfo = { + type: adapter.type, + name: adapter.name, + skillsDir: adapter.skillsDir, + configFile: adapter.configFile, + }; + return coreGetInstallDir(adapterInfo, global); +} + +export function getAgentConfigPath(agentType?: AgentType): string { + const type = agentType || loadConfig().agent; + const adapter = getAdapter(type); + const adapterInfo: AgentAdapterInfo = { + type: adapter.type, + name: adapter.name, + skillsDir: adapter.skillsDir, + configFile: adapter.configFile, + }; + return coreGetAgentConfigPath(adapterInfo); +} + +export async function initProject(agentType?: AgentType): Promise { + const type = agentType || (await detectAgent()); + const adapter = getAdapter(type); + const adapterInfo: AgentAdapterInfo = { + type: adapter.type, + name: adapter.name, + skillsDir: adapter.skillsDir, + configFile: adapter.configFile, + }; + return coreInitProject(type, adapterInfo); +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts new file mode 100644 index 00000000..306d7c52 --- /dev/null +++ b/packages/cli/src/index.ts @@ -0,0 +1,8 @@ +// Export all commands +export * from './commands/index.js'; + +// Export helper functions +export * from './helpers.js'; + +// Re-export commonly used types from core +export type { AgentType, Skill, SkillMetadata, SkillkitConfig } from '@skillkit/core'; diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json new file mode 100644 index 00000000..c64c5089 --- /dev/null +++ b/packages/cli/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src", + "composite": false + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.ts new file mode 100644 index 00000000..dbcb9a72 --- /dev/null +++ b/packages/cli/tsup.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: ['src/index.ts'], + format: ['esm'], + target: 'node18', + outDir: 'dist', + clean: true, + dts: true, + sourcemap: true, + splitting: false, + skipNodeModulesBundle: true, + platform: 'node', +}); diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 00000000..c3b77fa7 --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,59 @@ +{ + "name": "@skillkit/core", + "version": "1.2.0", + "description": "Core functionality for SkillKit - skill discovery, parsing, and translation", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + }, + "./types": { + "import": "./dist/types/index.js", + "types": "./dist/types/index.d.ts" + }, + "./discovery": { + "import": "./dist/discovery/index.js", + "types": "./dist/discovery/index.d.ts" + }, + "./parser": { + "import": "./dist/parser/index.js", + "types": "./dist/parser/index.d.ts" + }, + "./translator": { + "import": "./dist/translator/index.js", + "types": "./dist/translator/index.d.ts" + }, + "./context": { + "import": "./dist/context/index.js", + "types": "./dist/context/index.d.ts" + }, + "./recommend": { + "import": "./dist/recommend/index.js", + "types": "./dist/recommend/index.d.ts" + } + }, + "files": ["dist"], + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "yaml": "^2.6.1", + "zod": "^3.24.1" + }, + "devDependencies": { + "@types/node": "^22.10.5", + "tsup": "^8.3.5", + "typescript": "^5.7.2", + "vitest": "^2.1.8" + }, + "engines": { + "node": ">=18.0.0" + }, + "license": "Apache-2.0" +} diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts new file mode 100644 index 00000000..b940974d --- /dev/null +++ b/packages/core/src/config.ts @@ -0,0 +1,144 @@ +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { homedir } from 'node:os'; +import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'; +import { SkillkitConfig, type AgentType, type SkillMetadata, type AgentAdapterInfo } from './types.js'; + +const CONFIG_FILE = 'skillkit.yaml'; +const METADATA_FILE = '.skillkit.json'; + +export function getProjectConfigPath(): string { + return join(process.cwd(), CONFIG_FILE); +} + +export function getGlobalConfigPath(): string { + return join(homedir(), '.config', 'skillkit', CONFIG_FILE); +} + +export function loadConfig(): SkillkitConfig { + const projectPath = getProjectConfigPath(); + const globalPath = getGlobalConfigPath(); + + if (existsSync(projectPath)) { + try { + const content = readFileSync(projectPath, 'utf-8'); + const data = parseYaml(content); + const parsed = SkillkitConfig.safeParse(data); + if (parsed.success) { + return parsed.data; + } + } catch { + // Ignore parse errors + } + } + + if (existsSync(globalPath)) { + try { + const content = readFileSync(globalPath, 'utf-8'); + const data = parseYaml(content); + const parsed = SkillkitConfig.safeParse(data); + if (parsed.success) { + return parsed.data; + } + } catch { + // Ignore parse errors + } + } + + return { + version: 1, + agent: 'universal', + autoSync: true, + }; +} + +export function saveConfig(config: SkillkitConfig, global = false): void { + const configPath = global ? getGlobalConfigPath() : getProjectConfigPath(); + const dir = dirname(configPath); + + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + + const content = stringifyYaml(config); + writeFileSync(configPath, content, 'utf-8'); +} + +export function getSearchDirs(adapter: AgentAdapterInfo): string[] { + const dirs: string[] = []; + + dirs.push(join(process.cwd(), adapter.skillsDir)); + dirs.push(join(process.cwd(), '.agent', 'skills')); + dirs.push(join(homedir(), adapter.skillsDir)); + dirs.push(join(homedir(), '.agent', 'skills')); + + return dirs; +} + +export function getInstallDir(adapter: AgentAdapterInfo, global = false): string { + if (global) { + return join(homedir(), adapter.skillsDir); + } + + return join(process.cwd(), adapter.skillsDir); +} + +export function getAgentConfigPath(adapter: AgentAdapterInfo): string { + return join(process.cwd(), adapter.configFile); +} + +export function saveSkillMetadata(skillPath: string, metadata: SkillMetadata): void { + const metadataPath = join(skillPath, METADATA_FILE); + writeFileSync(metadataPath, JSON.stringify(metadata, null, 2), 'utf-8'); +} + +export function loadSkillMetadata(skillPath: string): SkillMetadata | null { + const metadataPath = join(skillPath, METADATA_FILE); + + if (!existsSync(metadataPath)) { + return null; + } + + try { + const content = readFileSync(metadataPath, 'utf-8'); + return JSON.parse(content) as SkillMetadata; + } catch { + return null; + } +} + +export function setSkillEnabled(skillPath: string, enabled: boolean): boolean { + const metadata = loadSkillMetadata(skillPath); + + if (!metadata) { + return false; + } + + metadata.enabled = enabled; + metadata.updatedAt = new Date().toISOString(); + saveSkillMetadata(skillPath, metadata); + + return true; +} + +export async function initProject( + type: AgentType, + adapter: AgentAdapterInfo +): Promise { + const skillsDir = join(process.cwd(), adapter.skillsDir); + if (!existsSync(skillsDir)) { + mkdirSync(skillsDir, { recursive: true }); + } + + const config: SkillkitConfig = { + version: 1, + agent: type, + autoSync: true, + }; + saveConfig(config); + + const agentConfigPath = join(process.cwd(), adapter.configFile); + if (!existsSync(agentConfigPath)) { + writeFileSync(agentConfigPath, `# ${adapter.name} Configuration\n\n`, 'utf-8'); + } +} diff --git a/packages/core/src/context/__tests__/detector.test.ts b/packages/core/src/context/__tests__/detector.test.ts new file mode 100644 index 00000000..edf7c833 --- /dev/null +++ b/packages/core/src/context/__tests__/detector.test.ts @@ -0,0 +1,795 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { ProjectDetector, analyzeProject, getStackTags } from '../detector.js'; +import type { ProjectStack } from '../types.js'; + +// Mock the fs module +vi.mock('node:fs', () => ({ + existsSync: vi.fn(), + readFileSync: vi.fn(), + readdirSync: vi.fn(), +})); + +describe('ProjectDetector', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.resetAllMocks(); + }); + + describe('language detection', () => { + it('should detect TypeScript from tsconfig.json', () => { + const mockPackageJson = { + name: 'test-project', + devDependencies: { + typescript: '5.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('package.json')) return true; + if (path.includes('tsconfig.json')) return true; + } + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + // Return files including tsconfig.json for file scanning + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + { name: 'tsconfig.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.languages).toContainEqual( + expect.objectContaining({ + name: 'typescript', + confidence: 100, + }) + ); + }); + + it('should detect JavaScript when no TypeScript config', () => { + const mockPackageJson = { + name: 'js-project', + dependencies: { + lodash: '4.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('package.json')) return true; + if (path.includes('tsconfig.json')) return false; + } + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.languages).toContainEqual( + expect.objectContaining({ + name: 'javascript', + }) + ); + }); + + it('should detect Python from pyproject.toml', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('pyproject.toml')) return true; + } + return false; + }); + + vi.mocked(readFileSync).mockReturnValue(''); + vi.mocked(readdirSync).mockReturnValue([ + { name: 'pyproject.toml', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.languages).toContainEqual( + expect.objectContaining({ + name: 'python', + confidence: 100, + }) + ); + }); + + it('should detect Rust from Cargo.toml', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('Cargo.toml')) return true; + } + return false; + }); + + vi.mocked(readFileSync).mockReturnValue(''); + vi.mocked(readdirSync).mockReturnValue([ + { name: 'Cargo.toml', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.languages).toContainEqual( + expect.objectContaining({ + name: 'rust', + confidence: 100, + }) + ); + }); + + it('should detect Go from go.mod', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('go.mod')) return true; + } + return false; + }); + + vi.mocked(readFileSync).mockReturnValue(''); + vi.mocked(readdirSync).mockReturnValue([ + { name: 'go.mod', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.languages).toContainEqual( + expect.objectContaining({ + name: 'go', + confidence: 100, + }) + ); + }); + }); + + describe('framework detection', () => { + it('should detect React from package.json', () => { + const mockPackageJson = { + name: 'react-project', + dependencies: { + react: '18.2.0', + 'react-dom': '18.2.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.frameworks).toContainEqual( + expect.objectContaining({ + name: 'react', + version: '18.2.0', + }) + ); + }); + + it('should detect Next.js from package.json', () => { + const mockPackageJson = { + name: 'nextjs-project', + dependencies: { + next: '14.0.0', + react: '18.2.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.frameworks).toContainEqual( + expect.objectContaining({ + name: 'nextjs', + version: '14.0.0', + }) + ); + }); + + it('should detect Vue from package.json', () => { + const mockPackageJson = { + name: 'vue-project', + dependencies: { + vue: '3.4.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.frameworks).toContainEqual( + expect.objectContaining({ + name: 'vue', + version: '3.4.0', + }) + ); + }); + + it('should detect Express from package.json', () => { + const mockPackageJson = { + name: 'express-project', + dependencies: { + express: '4.18.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.frameworks).toContainEqual( + expect.objectContaining({ + name: 'express', + }) + ); + }); + }); + + describe('library detection', () => { + it('should detect state management libraries', () => { + const mockPackageJson = { + name: 'state-project', + dependencies: { + zustand: '4.0.0', + jotai: '2.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.libraries).toContainEqual( + expect.objectContaining({ + name: 'zustand', + }) + ); + expect(stack.libraries).toContainEqual( + expect.objectContaining({ + name: 'jotai', + }) + ); + }); + + it('should detect data fetching libraries', () => { + const mockPackageJson = { + name: 'fetch-project', + dependencies: { + '@tanstack/react-query': '5.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.libraries).toContainEqual( + expect.objectContaining({ + name: 'tanstack', + }) + ); + }); + }); + + describe('styling detection', () => { + it('should detect Tailwind CSS', () => { + const mockPackageJson = { + name: 'tailwind-project', + devDependencies: { + tailwindcss: '3.4.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.styling).toContainEqual( + expect.objectContaining({ + name: 'tailwindcss', + }) + ); + }); + + it('should detect styled-components', () => { + const mockPackageJson = { + name: 'styled-project', + dependencies: { + 'styled-components': '6.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.styling).toContainEqual( + expect.objectContaining({ + name: 'styled-components', + }) + ); + }); + }); + + describe('testing detection', () => { + it('should detect Vitest', () => { + const mockPackageJson = { + name: 'test-project', + devDependencies: { + vitest: '1.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.testing).toContainEqual( + expect.objectContaining({ + name: 'vitest', + }) + ); + }); + + it('should detect Playwright', () => { + const mockPackageJson = { + name: 'e2e-project', + devDependencies: { + '@playwright/test': '1.40.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.testing).toContainEqual( + expect.objectContaining({ + name: 'playwright', + }) + ); + }); + }); + + describe('database detection', () => { + it('should detect Prisma', () => { + const mockPackageJson = { + name: 'db-project', + dependencies: { + '@prisma/client': '5.0.0', + }, + devDependencies: { + prisma: '5.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.databases).toContainEqual( + expect.objectContaining({ + name: 'prisma', + }) + ); + }); + + it('should detect Supabase', () => { + const mockPackageJson = { + name: 'supabase-project', + dependencies: { + '@supabase/supabase-js': '2.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.databases).toContainEqual( + expect.objectContaining({ + name: 'supabase', + }) + ); + }); + }); + + describe('tool detection', () => { + it('should detect ESLint', () => { + const mockPackageJson = { + name: 'lint-project', + devDependencies: { + eslint: '8.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.tools).toContainEqual( + expect.objectContaining({ + name: 'eslint', + }) + ); + }); + + it('should detect Prettier', () => { + const mockPackageJson = { + name: 'format-project', + devDependencies: { + prettier: '3.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const stack = detector.analyze(); + + expect(stack.tools).toContainEqual( + expect.objectContaining({ + name: 'prettier', + }) + ); + }); + }); + + describe('project type detection', () => { + it('should return unknown for projects without specific dependencies', () => { + const mockPackageJson = { + name: 'generic-project', + dependencies: {}, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + const projectType = detector.detectProjectType(); + + expect(projectType).toBe('unknown'); + }); + + it('should detect library from build config', () => { + const mockPackageJson = { + name: 'my-library', + dependencies: {}, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('package.json')) return true; + // hasFile('tsup.config.ts') needs this to return true + if (path.includes('tsup.config.ts')) return true; + } + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + { name: 'tsup.config.ts', isDirectory: () => false }, + ] as any); + + const detector = new ProjectDetector('/test/project'); + // Must call analyze() first to populate the files set + // detectProjectType() relies on hasFile() which checks the files set + detector.analyze(); + const projectType = detector.detectProjectType(); + + expect(projectType).toBe('library'); + }); + }); +}); + +describe('analyzeProject', () => { + it('should return project stack', () => { + const mockPackageJson = { + name: 'full-project', + dependencies: { + react: '18.0.0', + }, + }; + + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify(mockPackageJson); + } + return ''; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'package.json', isDirectory: () => false }, + ] as any); + + const stack = analyzeProject('/test/project'); + + expect(stack).toHaveProperty('languages'); + expect(stack).toHaveProperty('frameworks'); + expect(stack).toHaveProperty('libraries'); + }); +}); + +describe('getStackTags', () => { + it('should generate tags from stack', () => { + const stack: ProjectStack = { + languages: [{ name: 'typescript', confidence: 100 }], + frameworks: [{ name: 'react', confidence: 100 }], + libraries: [], + styling: [{ name: 'tailwindcss', confidence: 100 }], + testing: [], + databases: [], + tools: [], + runtime: [], + }; + + const tags = getStackTags(stack); + + expect(tags).toContain('typescript'); + expect(tags).toContain('react'); + // tailwindcss gets tags from STYLING_PATTERNS + expect(tags.some(t => t === 'tailwind' || t === 'tailwindcss')).toBe(true); + }); +}); diff --git a/packages/core/src/context/__tests__/manager.test.ts b/packages/core/src/context/__tests__/manager.test.ts new file mode 100644 index 00000000..7b9fa519 --- /dev/null +++ b/packages/core/src/context/__tests__/manager.test.ts @@ -0,0 +1,607 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { ContextManager, createContextManager, loadContext, initContext } from '../manager.js'; +import type { ProjectContext } from '../types.js'; + +// Mock fs module +vi.mock('node:fs', () => ({ + existsSync: vi.fn(), + readFileSync: vi.fn(), + writeFileSync: vi.fn(), + mkdirSync: vi.fn(), +})); + +// Mock the detector module with a class +vi.mock('../detector.js', () => ({ + ProjectDetector: class MockProjectDetector { + analyze() { + return { + languages: [{ name: 'typescript', version: '5.0.0', confidence: 100 }], + frameworks: [{ name: 'react', version: '18.0.0', confidence: 100 }], + libraries: [], + styling: [], + testing: [], + databases: [], + tools: [], + runtime: [], + }; + } + detectPatterns() { + return {}; + } + detectProjectType() { + return 'web-application'; + } + getProjectName() { + return 'test-project'; + } + getProjectDescription() { + return 'A test project'; + } + }, + getStackTags: vi.fn().mockReturnValue(['typescript', 'react']), +})); + +describe('ContextManager', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.resetAllMocks(); + }); + + describe('exists', () => { + it('should return true when context file exists', () => { + vi.mocked(existsSync).mockReturnValue(true); + + const manager = new ContextManager('/test/project'); + + expect(manager.exists()).toBe(true); + }); + + it('should return false when context file does not exist', () => { + vi.mocked(existsSync).mockReturnValue(false); + + const manager = new ContextManager('/test/project'); + + expect(manager.exists()).toBe(false); + }); + }); + + describe('init', () => { + it('should create a new context file', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('package.json')) return true; + if (path.includes('context.yaml')) return false; + } + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify({ + name: 'test-project', + description: 'A test project', + }); + } + return ''; + }); + + const manager = new ContextManager('/test/project'); + const context = manager.init(); + + expect(context).toBeDefined(); + expect(context.version).toBe(1); + expect(context.project.name).toBe('test-project'); + expect(vi.mocked(writeFileSync)).toHaveBeenCalled(); + expect(vi.mocked(mkdirSync)).toHaveBeenCalled(); + }); + + it('should not overwrite existing context without force flag', () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue(` +version: 1 +project: + name: existing-project +stack: + languages: [] + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +`); + + const manager = new ContextManager('/test/project'); + const context = manager.init(); + + // Should return existing context + expect(context.project.name).toBe('existing-project'); + }); + + it('should overwrite existing context with force flag', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('context.yaml')) return true; + if (path.includes('package.json')) return true; + } + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify({ name: 'new-project' }); + } + if (typeof path === 'string' && path.includes('context.yaml')) { + return ` +version: 1 +project: + name: old-project +stack: + languages: [] + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +`; + } + return ''; + }); + + const manager = new ContextManager('/test/project'); + const context = manager.init({ force: true }); + + // With force flag, a new context is created using ProjectDetector + // The mock returns 'test-project' from getProjectName() + // This validates that force creates new context instead of returning existing + expect(context.project.name).toBe('test-project'); + }); + }); + + describe('load', () => { + it('should load existing context', () => { + const existingContext = ` +version: 1 +project: + name: loaded-project + description: A loaded project + type: library +stack: + languages: + - name: typescript + confidence: 100 + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +skills: + installed: [] + autoSync: true +`; + + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue(existingContext); + + const manager = new ContextManager('/test/project'); + const context = manager.load(); + + expect(context).not.toBeNull(); + expect(context!.project.name).toBe('loaded-project'); + expect(context!.project.type).toBe('library'); + }); + + it('should return null when context does not exist', () => { + vi.mocked(existsSync).mockReturnValue(false); + + const manager = new ContextManager('/test/project'); + const context = manager.load(); + + expect(context).toBeNull(); + }); + + it('should handle malformed YAML by returning null', () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue('invalid: yaml: content: ['); + + const manager = new ContextManager('/test/project'); + + // Implementation catches errors and returns null with a warning + const result = manager.load(); + expect(result).toBeNull(); + }); + }); + + describe('save', () => { + it('should save context to file', () => { + vi.mocked(existsSync).mockReturnValue(true); + + const context: ProjectContext = { + version: 1, + project: { + name: 'saved-project', + }, + stack: { + languages: [], + frameworks: [], + libraries: [], + styling: [], + testing: [], + databases: [], + tools: [], + runtime: [], + }, + }; + + const manager = new ContextManager('/test/project'); + manager.save(context); + + expect(vi.mocked(writeFileSync)).toHaveBeenCalled(); + const [, content] = vi.mocked(writeFileSync).mock.calls[0]; + expect(content).toContain('name: saved-project'); + }); + + it('should create directory if it does not exist', () => { + vi.mocked(existsSync).mockReturnValue(false); + + const context: ProjectContext = { + version: 1, + project: { name: 'test' }, + stack: { + languages: [], + frameworks: [], + libraries: [], + styling: [], + testing: [], + databases: [], + tools: [], + runtime: [], + }, + }; + + const manager = new ContextManager('/test/project'); + manager.save(context); + + expect(vi.mocked(mkdirSync)).toHaveBeenCalled(); + }); + }); + + describe('get', () => { + it('should return cached context', () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue(` +version: 1 +project: + name: cached-project +stack: + languages: [] + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +`); + + const manager = new ContextManager('/test/project'); + + // First call loads from file + const first = manager.get(); + expect(first?.project.name).toBe('cached-project'); + + // Second call should use cache (readFileSync should only be called once) + const second = manager.get(); + expect(second?.project.name).toBe('cached-project'); + }); + + it('should return null when no context exists', () => { + vi.mocked(existsSync).mockReturnValue(false); + + const manager = new ContextManager('/test/project'); + const context = manager.get(); + + expect(context).toBeNull(); + }); + }); + + describe('export', () => { + it('should export context as YAML', () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue(` +version: 1 +project: + name: export-test +stack: + languages: [] + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +`); + + const manager = new ContextManager('/test/project'); + const exported = manager.export({ format: 'yaml' }); + + expect(exported).toContain('version: 1'); + expect(exported).toContain('name: export-test'); + }); + + it('should export context as JSON', () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue(` +version: 1 +project: + name: json-export +stack: + languages: [] + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +`); + + const manager = new ContextManager('/test/project'); + const exported = manager.export({ format: 'json' }); + + const parsed = JSON.parse(exported); + expect(parsed.project.name).toBe('json-export'); + }); + }); + + describe('import', () => { + it('should import YAML context', () => { + vi.mocked(existsSync).mockReturnValue(false); + + const importContent = ` +version: 1 +project: + name: imported-project +stack: + languages: + - name: python + confidence: 100 + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +`; + + const manager = new ContextManager('/test/project'); + const context = manager.import(importContent, { overwrite: true }); + + expect(context.project.name).toBe('imported-project'); + expect(vi.mocked(writeFileSync)).toHaveBeenCalled(); + }); + + it('should import JSON context', () => { + vi.mocked(existsSync).mockReturnValue(false); + + const importContent = JSON.stringify({ + version: 1, + project: { name: 'json-imported' }, + stack: { + languages: [], + frameworks: [], + libraries: [], + styling: [], + testing: [], + databases: [], + tools: [], + runtime: [], + }, + }); + + const manager = new ContextManager('/test/project'); + const context = manager.import(importContent, { overwrite: true }); + + expect(context.project.name).toBe('json-imported'); + }); + + it('should merge with existing context', () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue(` +version: 1 +project: + name: existing +stack: + languages: + - name: typescript + confidence: 100 + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +`); + + const importContent = ` +version: 1 +project: + name: imported +stack: + languages: + - name: python + confidence: 100 + frameworks: + - name: django + confidence: 100 + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +`; + + const manager = new ContextManager('/test/project'); + const context = manager.import(importContent, { merge: true }); + + // Should merge languages + expect(context.stack.languages).toHaveLength(2); + expect(context.stack.frameworks).toHaveLength(1); + }); + }); + + describe('updateSkills', () => { + it('should update installed skills', () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue(` +version: 1 +project: + name: skills-test +stack: + languages: [] + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +skills: + installed: [] +`); + + const manager = new ContextManager('/test/project'); + manager.updateSkills({ + installed: ['skill-1', 'skill-2'], + }); + + expect(vi.mocked(writeFileSync)).toHaveBeenCalled(); + const [, content] = vi.mocked(writeFileSync).mock.calls[0]; + expect(content).toContain('skill-1'); + expect(content).toContain('skill-2'); + }); + }); + + describe('updateAgents', () => { + it('should update agent configuration', () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue(` +version: 1 +project: + name: agents-test +stack: + languages: [] + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +agents: + detected: [] + synced: [] +`); + + const manager = new ContextManager('/test/project'); + manager.updateAgents({ + primary: 'claude-code', + detected: ['claude-code', 'cursor'], + synced: ['claude-code', 'cursor'], + }); + + expect(vi.mocked(writeFileSync)).toHaveBeenCalled(); + const [, content] = vi.mocked(writeFileSync).mock.calls[0]; + expect(content).toContain('claude-code'); + expect(content).toContain('cursor'); + }); + }); +}); + +describe('convenience functions', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('createContextManager', () => { + it('should create a ContextManager instance', () => { + const manager = createContextManager('/test/project'); + + expect(manager).toBeInstanceOf(ContextManager); + }); + + it('should use current directory if no path provided', () => { + const manager = createContextManager(); + + expect(manager).toBeInstanceOf(ContextManager); + }); + }); + + describe('loadContext', () => { + it('should load context from path', () => { + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(readFileSync).mockReturnValue(` +version: 1 +project: + name: load-test +stack: + languages: [] + frameworks: [] + libraries: [] + styling: [] + testing: [] + databases: [] + tools: [] + runtime: [] +`); + + const context = loadContext('/test/project'); + + expect(context).not.toBeNull(); + expect(context?.project.name).toBe('load-test'); + }); + + it('should return null if context does not exist', () => { + vi.mocked(existsSync).mockReturnValue(false); + + const context = loadContext('/test/project'); + + expect(context).toBeNull(); + }); + }); + + describe('initContext', () => { + it('should initialize context', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) return true; + return false; + }); + + vi.mocked(readFileSync).mockImplementation((path) => { + if (typeof path === 'string' && path.includes('package.json')) { + return JSON.stringify({ name: 'init-test' }); + } + return ''; + }); + + const context = initContext('/test/project'); + + // The mock's getProjectName() returns 'test-project' + // This validates that initContext creates a new context using ProjectDetector + expect(context.project.name).toBe('test-project'); + }); + }); +}); diff --git a/packages/core/src/context/__tests__/sync.test.ts b/packages/core/src/context/__tests__/sync.test.ts new file mode 100644 index 00000000..8839ea1e --- /dev/null +++ b/packages/core/src/context/__tests__/sync.test.ts @@ -0,0 +1,510 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { existsSync, writeFileSync, mkdirSync, copyFileSync, readdirSync } from 'node:fs'; +import { ContextSync, createContextSync, syncToAllAgents, syncToAgent } from '../sync.js'; +import type { AgentType } from '../../types.js'; + +// Mock fs module +vi.mock('node:fs', () => ({ + existsSync: vi.fn(), + writeFileSync: vi.fn(), + mkdirSync: vi.fn(), + copyFileSync: vi.fn(), + readdirSync: vi.fn(), +})); + +// Mock ContextManager with a class +vi.mock('../manager.js', () => ({ + ContextManager: class MockContextManager { + get() { + return { + version: 1, + project: { name: 'test-project' }, + stack: { + languages: [], + frameworks: [], + libraries: [], + styling: [], + testing: [], + databases: [], + tools: [], + runtime: [], + }, + agents: { + detected: ['claude-code', 'cursor'], + synced: ['claude-code', 'cursor'], + }, + }; + } + init() {} + updateAgents() {} + }, +})); + +// Hoisted mocks - these are defined before vi.mock calls are hoisted +const { mockTranslateSkillFile, mockFindAllSkills } = vi.hoisted(() => { + return { + mockTranslateSkillFile: vi.fn().mockReturnValue({ + success: true, + content: 'translated content', + filename: 'skill.md', + format: 'skill-md', + warnings: [], + incompatible: [], + errors: [], + }), + mockFindAllSkills: vi.fn().mockReturnValue([ + { + name: 'test-skill', + path: '/test/project/.claude/skills/test-skill', + filename: 'test-skill.md', + }, + ]), + }; +}); + +// Mock translator +vi.mock('../../translator/index', () => ({ + translateSkillFile: mockTranslateSkillFile, +})); + +// Mock skills module +vi.mock('../../skills', () => ({ + findAllSkills: mockFindAllSkills, +})); + +describe('ContextSync', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + afterEach(() => { + vi.resetAllMocks(); + }); + + describe('detectAgents', () => { + it('should detect Claude Code agent', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('.claude')) return true; + } + return false; + }); + + const sync = new ContextSync('/test/project'); + const agents = sync.detectAgents(); + + expect(agents).toContain('claude-code'); + }); + + it('should detect Cursor agent', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('.cursor')) return true; + if (path.includes('.cursorrules')) return true; + } + return false; + }); + + const sync = new ContextSync('/test/project'); + const agents = sync.detectAgents(); + + expect(agents).toContain('cursor'); + }); + + it('should detect multiple agents', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('.claude')) return true; + if (path.includes('.cursor')) return true; + if (path.includes('.codex')) return true; + } + return false; + }); + + const sync = new ContextSync('/test/project'); + const agents = sync.detectAgents(); + + expect(agents).toContain('claude-code'); + expect(agents).toContain('cursor'); + expect(agents).toContain('codex'); + }); + + it('should detect Windsurf agent', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('.windsurfrules')) return true; + if (path.includes('.windsurf')) return true; + } + return false; + }); + + const sync = new ContextSync('/test/project'); + const agents = sync.detectAgents(); + + expect(agents).toContain('windsurf'); + }); + + it('should detect GitHub Copilot agent', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + // github-copilot is detected via .github/skills directory or AGENTS.md + if (path.includes('.github/skills')) return true; + } + return false; + }); + + const sync = new ContextSync('/test/project'); + const agents = sync.detectAgents(); + + expect(agents).toContain('github-copilot'); + }); + + it('should return empty array when no agents detected', () => { + vi.mocked(existsSync).mockReturnValue(false); + + const sync = new ContextSync('/test/project'); + const agents = sync.detectAgents(); + + expect(agents).toEqual([]); + }); + }); + + describe('checkStatus', () => { + it('should return status for all agents', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('.claude/skills')) return true; + } + return false; + }); + + // readdirSync with withFileTypes returns entries with isDirectory method + vi.mocked(readdirSync).mockReturnValue([ + { name: 'skill-1', isDirectory: () => true }, + { name: 'skill-2', isDirectory: () => true }, + ] as any); + + const sync = new ContextSync('/test/project'); + const status = sync.checkStatus(); + + expect(status).toHaveProperty('claude-code'); + expect(status['claude-code'].skillCount).toBe(2); + }); + + it('should show hasSkills true when skills exist', () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('.claude/skills')) return true; + } + return false; + }); + + vi.mocked(readdirSync).mockReturnValue([ + { name: 'skill-1', isDirectory: () => true }, + ] as any); + + const sync = new ContextSync('/test/project'); + const status = sync.checkStatus(); + + expect(status['claude-code'].hasSkills).toBe(true); + }); + + it('should show hasSkills false when no skills exist', () => { + vi.mocked(existsSync).mockReturnValue(false); + vi.mocked(readdirSync).mockReturnValue([]); + + const sync = new ContextSync('/test/project'); + const status = sync.checkStatus(); + + expect(status['claude-code'].hasSkills).toBe(false); + expect(status['claude-code'].skillCount).toBe(0); + }); + }); + + describe('syncToAgent', () => { + it('should sync skills to an agent', async () => { + vi.mocked(existsSync).mockReturnValue(false); + + const sync = new ContextSync('/test/project'); + const result = await sync.syncToAgent('cursor', [ + { name: 'skill-1', path: '/test/skill-1' }, + ]); + + expect(result.success).toBe(true); + expect(result.agent).toBe('cursor'); + expect(result.skillsSynced).toBeGreaterThanOrEqual(0); + }); + + it('should skip existing skills without force flag', async () => { + vi.mocked(existsSync).mockReturnValue(true); + + const sync = new ContextSync('/test/project'); + const result = await sync.syncToAgent('cursor', [ + { name: 'existing-skill', path: '/test/existing-skill' }, + ]); + + expect(result.skillsSkipped).toBeGreaterThanOrEqual(0); + expect(result.warnings.length).toBeGreaterThanOrEqual(0); + }); + + it('should overwrite existing skills with force flag', async () => { + vi.mocked(existsSync).mockReturnValue(true); + + const sync = new ContextSync('/test/project'); + const result = await sync.syncToAgent( + 'cursor', + [{ name: 'existing-skill', path: '/test/existing-skill' }], + { force: true } + ); + + // With force flag, skill should be synced (or skipped if translation fails) + expect(result).toBeDefined(); + expect(result.agent).toBe('cursor'); + }); + + it('should handle dry run mode', async () => { + const sync = new ContextSync('/test/project'); + const result = await sync.syncToAgent( + 'cursor', + [{ name: 'test-skill', path: '/test/test-skill' }], + { dryRun: true } + ); + + // In dry run, files should not be written + expect(result.success).toBe(true); + // writeFileSync should not be called with actual writes in dry run + }); + + it('should return error for invalid agent', async () => { + const sync = new ContextSync('/test/project'); + const result = await sync.syncToAgent( + 'invalid-agent' as AgentType, + [{ name: 'skill', path: '/test/skill' }] + ); + + expect(result.errors.length).toBeGreaterThan(0); + }); + }); + + describe('syncAll', () => { + it('should sync to all detected agents', async () => { + vi.mocked(existsSync).mockImplementation((path) => { + if (typeof path === 'string') { + if (path.includes('.claude')) return true; + if (path.includes('.cursor')) return true; + } + return false; + }); + + vi.mocked(readdirSync).mockReturnValue(['test-skill'] as any); + + const sync = new ContextSync('/test/project'); + // Mock getSourceSkills to return test skills + vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([ + { name: 'test-skill', path: '/test/project/.claude/skills/test-skill' }, + ]); + const report = await sync.syncAll(); + + expect(report.totalAgents).toBeGreaterThan(0); + expect(report.results.length).toBeGreaterThan(0); + }); + + it('should sync to specific agents when provided', async () => { + const sync = new ContextSync('/test/project'); + // Mock getSourceSkills to return test skills + vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([ + { name: 'test-skill', path: '/test/project/.claude/skills/test-skill' }, + ]); + const report = await sync.syncAll({ + agents: ['cursor', 'windsurf'], + }); + + expect(report.results.some((r) => r.agent === 'cursor')).toBe(true); + expect(report.results.some((r) => r.agent === 'windsurf')).toBe(true); + }); + + it('should report successful and failed agents', async () => { + const sync = new ContextSync('/test/project'); + // Mock getSourceSkills to return test skills + vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([ + { name: 'test-skill', path: '/test/project/.claude/skills/test-skill' }, + ]); + const report = await sync.syncAll({ + agents: ['claude-code', 'cursor'], + }); + + expect(report.totalAgents).toBe(2); + expect(report.successfulAgents).toBeGreaterThanOrEqual(0); + expect(report.totalSkills).toBeGreaterThanOrEqual(0); + }); + + it('should respect dry run mode for all agents', async () => { + const sync = new ContextSync('/test/project'); + // Mock getSourceSkills to return test skills + vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([ + { name: 'test-skill', path: '/test/project/.claude/skills/test-skill' }, + ]); + const report = await sync.syncAll({ + agents: ['cursor'], + dryRun: true, + }); + + expect(report.results[0].success).toBe(true); + }); + + it('should collect warnings from all agents', async () => { + vi.mocked(existsSync).mockReturnValue(true); // Skills already exist + + const sync = new ContextSync('/test/project'); + // Mock getSourceSkills to return test skills + vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([ + { name: 'test-skill', path: '/test/project/.claude/skills/test-skill' }, + ]); + const report = await sync.syncAll({ + agents: ['cursor'], + }); + + // Should have warnings about existing skills + expect(report.results[0]).toBeDefined(); + }); + }); + +}); + +describe('convenience functions', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + describe('createContextSync', () => { + it('should create a ContextSync instance', () => { + const sync = createContextSync('/test/project'); + + expect(sync).toBeInstanceOf(ContextSync); + }); + + it('should use current directory if no path provided', () => { + const sync = createContextSync(); + + expect(sync).toBeInstanceOf(ContextSync); + }); + }); + + describe('syncToAllAgents', () => { + it('should sync to all agents', async () => { + vi.mocked(existsSync).mockReturnValue(false); + + // Mock ContextSync.prototype.getSourceSkills for convenience function tests + const originalGetSourceSkills = ContextSync.prototype['getSourceSkills']; + ContextSync.prototype['getSourceSkills'] = vi.fn().mockReturnValue([ + { name: 'test-skill', path: '/test/project/.claude/skills/test-skill' }, + ]); + + try { + const report = await syncToAllAgents('/test/project'); + + expect(report).toHaveProperty('totalAgents'); + expect(report).toHaveProperty('successfulAgents'); + expect(report).toHaveProperty('results'); + } finally { + // Restore original method + ContextSync.prototype['getSourceSkills'] = originalGetSourceSkills; + } + }); + }); + + describe('syncToAgent', () => { + it('should sync to a specific agent', async () => { + vi.mocked(existsSync).mockReturnValue(false); + + // Mock ContextSync.prototype.getSourceSkills for convenience function tests + const originalGetSourceSkills = ContextSync.prototype['getSourceSkills']; + ContextSync.prototype['getSourceSkills'] = vi.fn().mockReturnValue([ + { name: 'test-skill', path: '/test/project/.claude/skills/test-skill' }, + ]); + + try { + // syncToAgent(agent, projectPath?, options?) + const result = await syncToAgent('cursor', '/test/project'); + + expect(result.agent).toBe('cursor'); + expect(result).toHaveProperty('success'); + expect(result).toHaveProperty('skillsSynced'); + } finally { + // Restore original method + ContextSync.prototype['getSourceSkills'] = originalGetSourceSkills; + } + }); + }); +}); + +describe('error handling', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('should handle file system errors gracefully', async () => { + // Setup: existsSync must return true for SKILL.md path + vi.mocked(existsSync).mockReturnValue(true); + vi.mocked(writeFileSync).mockImplementation(() => { + throw new Error('Permission denied'); + }); + + const sync = new ContextSync('/test/project'); + const result = await sync.syncToAgent('cursor', [ + { name: 'skill', path: '/test/skill' }, + ]); + + // Error is caught and added to errors array + expect(result.errors.length).toBeGreaterThan(0); + expect(result.errors[0]).toContain('Failed to sync'); + }); + + it('should continue syncing other agents if one fails', async () => { + vi.mocked(existsSync).mockReturnValue(true); + let callCount = 0; + vi.mocked(writeFileSync).mockImplementation(() => { + callCount++; + if (callCount === 1) { + throw new Error('First agent failed'); + } + }); + + const sync = new ContextSync('/test/project'); + // Mock getSourceSkills to return test skills + vi.spyOn(sync as any, 'getSourceSkills').mockReturnValue([ + { name: 'test-skill', path: '/test/project/.claude/skills/test-skill' }, + ]); + const report = await sync.syncAll({ + agents: ['cursor', 'windsurf'], + }); + + // Should have results for both agents + expect(report.results.length).toBe(2); + }); + + it('should report translation failures as warnings', async () => { + // Setup: existsSync must return true for SKILL.md to be found + vi.mocked(existsSync).mockReturnValue(true); + + // Use the hoisted mock directly + mockTranslateSkillFile.mockReturnValue({ + success: false, + content: '', + filename: '', + format: 'skill-md', + warnings: [], + incompatible: [], + errors: ['Translation failed'], + }); + + const sync = new ContextSync('/test/project'); + const result = await sync.syncToAgent('cursor', [ + { name: 'untranslatable-skill', path: '/test/skill' }, + ]); + + // Translation failures add warnings, not errors + expect(result.skillsSkipped).toBe(1); + expect(result.warnings.length).toBeGreaterThan(0); + }); +}); diff --git a/packages/core/src/context/detector.ts b/packages/core/src/context/detector.ts new file mode 100644 index 00000000..2f18bd49 --- /dev/null +++ b/packages/core/src/context/detector.ts @@ -0,0 +1,784 @@ +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import type { ProjectStack, Detection, ProjectPatterns } from './types.js'; + +/** + * Framework detection patterns + */ +const FRAMEWORK_PATTERNS = { + // Frontend frameworks + react: { + dependencies: ['react', 'react-dom'], + files: [], + category: 'frameworks' as const, + tags: ['react', 'frontend', 'ui'], + }, + nextjs: { + dependencies: ['next'], + files: ['next.config.js', 'next.config.mjs', 'next.config.ts'], + category: 'frameworks' as const, + tags: ['nextjs', 'react', 'ssr', 'frontend'], + }, + vue: { + dependencies: ['vue'], + files: [], + category: 'frameworks' as const, + tags: ['vue', 'frontend', 'ui'], + }, + nuxt: { + dependencies: ['nuxt'], + files: ['nuxt.config.js', 'nuxt.config.ts'], + category: 'frameworks' as const, + tags: ['nuxt', 'vue', 'ssr', 'frontend'], + }, + angular: { + dependencies: ['@angular/core'], + files: ['angular.json'], + category: 'frameworks' as const, + tags: ['angular', 'frontend', 'ui'], + }, + svelte: { + dependencies: ['svelte'], + files: ['svelte.config.js'], + category: 'frameworks' as const, + tags: ['svelte', 'frontend', 'ui'], + }, + remix: { + dependencies: ['@remix-run/react'], + files: ['remix.config.js'], + category: 'frameworks' as const, + tags: ['remix', 'react', 'ssr', 'frontend'], + }, + astro: { + dependencies: ['astro'], + files: ['astro.config.mjs', 'astro.config.ts'], + category: 'frameworks' as const, + tags: ['astro', 'static', 'frontend'], + }, + solid: { + dependencies: ['solid-js'], + files: [], + category: 'frameworks' as const, + tags: ['solid', 'frontend', 'ui'], + }, + + // Backend frameworks + express: { + dependencies: ['express'], + files: [], + category: 'frameworks' as const, + tags: ['express', 'nodejs', 'api', 'backend'], + }, + fastify: { + dependencies: ['fastify'], + files: [], + category: 'frameworks' as const, + tags: ['fastify', 'nodejs', 'api', 'backend'], + }, + hono: { + dependencies: ['hono'], + files: [], + category: 'frameworks' as const, + tags: ['hono', 'edge', 'api', 'backend'], + }, + koa: { + dependencies: ['koa'], + files: [], + category: 'frameworks' as const, + tags: ['koa', 'nodejs', 'api', 'backend'], + }, + nestjs: { + dependencies: ['@nestjs/core'], + files: ['nest-cli.json'], + category: 'frameworks' as const, + tags: ['nestjs', 'nodejs', 'api', 'backend'], + }, + + // Mobile + 'react-native': { + dependencies: ['react-native'], + files: ['metro.config.js', 'app.json'], + category: 'frameworks' as const, + tags: ['react-native', 'mobile', 'ios', 'android'], + }, + expo: { + dependencies: ['expo'], + files: ['app.json', 'expo.json'], + category: 'frameworks' as const, + tags: ['expo', 'react-native', 'mobile'], + }, + + // Desktop + electron: { + dependencies: ['electron'], + files: ['electron.js', 'electron-builder.json'], + category: 'frameworks' as const, + tags: ['electron', 'desktop'], + }, + tauri: { + dependencies: ['@tauri-apps/api'], + files: ['tauri.conf.json', 'src-tauri'], + category: 'frameworks' as const, + tags: ['tauri', 'desktop', 'rust'], + }, +}; + +/** + * Library detection patterns + */ +const LIBRARY_PATTERNS = { + // State management + redux: { + dependencies: ['redux', '@reduxjs/toolkit'], + category: 'libraries' as const, + tags: ['redux', 'state-management'], + }, + zustand: { + dependencies: ['zustand'], + category: 'libraries' as const, + tags: ['zustand', 'state-management'], + }, + jotai: { + dependencies: ['jotai'], + category: 'libraries' as const, + tags: ['jotai', 'state-management'], + }, + recoil: { + dependencies: ['recoil'], + category: 'libraries' as const, + tags: ['recoil', 'state-management'], + }, + mobx: { + dependencies: ['mobx'], + category: 'libraries' as const, + tags: ['mobx', 'state-management'], + }, + + // Data fetching + tanstack: { + dependencies: ['@tanstack/react-query', '@tanstack/query-core'], + category: 'libraries' as const, + tags: ['tanstack', 'data-fetching', 'caching'], + }, + swr: { + dependencies: ['swr'], + category: 'libraries' as const, + tags: ['swr', 'data-fetching'], + }, + trpc: { + dependencies: ['@trpc/client', '@trpc/server'], + category: 'libraries' as const, + tags: ['trpc', 'api', 'typescript'], + }, + graphql: { + dependencies: ['graphql', '@apollo/client', 'urql'], + category: 'libraries' as const, + tags: ['graphql', 'api'], + }, + + // UI Components + 'shadcn-ui': { + dependencies: ['@radix-ui/react-slot'], + files: ['components.json'], + category: 'libraries' as const, + tags: ['shadcn', 'ui', 'components'], + }, + 'material-ui': { + dependencies: ['@mui/material'], + category: 'libraries' as const, + tags: ['mui', 'material', 'ui', 'components'], + }, + 'chakra-ui': { + dependencies: ['@chakra-ui/react'], + category: 'libraries' as const, + tags: ['chakra', 'ui', 'components'], + }, + 'ant-design': { + dependencies: ['antd'], + category: 'libraries' as const, + tags: ['antd', 'ui', 'components'], + }, + + // Form handling + 'react-hook-form': { + dependencies: ['react-hook-form'], + category: 'libraries' as const, + tags: ['forms', 'validation'], + }, + formik: { + dependencies: ['formik'], + category: 'libraries' as const, + tags: ['forms', 'validation'], + }, + zod: { + dependencies: ['zod'], + category: 'libraries' as const, + tags: ['validation', 'schema', 'typescript'], + }, + + // Animation + 'framer-motion': { + dependencies: ['framer-motion'], + category: 'libraries' as const, + tags: ['animation', 'motion'], + }, +}; + +/** + * Styling detection patterns + */ +const STYLING_PATTERNS = { + tailwindcss: { + dependencies: ['tailwindcss'], + files: ['tailwind.config.js', 'tailwind.config.ts', 'tailwind.config.cjs'], + category: 'styling' as const, + tags: ['tailwind', 'css', 'utility-first'], + }, + 'styled-components': { + dependencies: ['styled-components'], + category: 'styling' as const, + tags: ['styled-components', 'css-in-js'], + }, + emotion: { + dependencies: ['@emotion/react', '@emotion/styled'], + category: 'styling' as const, + tags: ['emotion', 'css-in-js'], + }, + sass: { + dependencies: ['sass', 'node-sass'], + category: 'styling' as const, + tags: ['sass', 'scss', 'css'], + }, + less: { + dependencies: ['less'], + category: 'styling' as const, + tags: ['less', 'css'], + }, + 'css-modules': { + files: ['*.module.css', '*.module.scss'], + category: 'styling' as const, + tags: ['css-modules', 'css'], + }, +}; + +/** + * Testing detection patterns + */ +const TESTING_PATTERNS = { + jest: { + dependencies: ['jest'], + files: ['jest.config.js', 'jest.config.ts'], + category: 'testing' as const, + tags: ['jest', 'testing', 'unit-testing'], + }, + vitest: { + dependencies: ['vitest'], + files: ['vitest.config.ts', 'vitest.config.js'], + category: 'testing' as const, + tags: ['vitest', 'testing', 'unit-testing'], + }, + playwright: { + dependencies: ['@playwright/test'], + files: ['playwright.config.ts', 'playwright.config.js'], + category: 'testing' as const, + tags: ['playwright', 'e2e', 'testing'], + }, + cypress: { + dependencies: ['cypress'], + files: ['cypress.config.ts', 'cypress.config.js', 'cypress.json'], + category: 'testing' as const, + tags: ['cypress', 'e2e', 'testing'], + }, + mocha: { + dependencies: ['mocha'], + category: 'testing' as const, + tags: ['mocha', 'testing'], + }, + 'testing-library': { + dependencies: ['@testing-library/react', '@testing-library/vue'], + category: 'testing' as const, + tags: ['testing-library', 'testing'], + }, +}; + +/** + * Database detection patterns + */ +const DATABASE_PATTERNS = { + prisma: { + dependencies: ['@prisma/client', 'prisma'], + files: ['prisma/schema.prisma'], + category: 'databases' as const, + tags: ['prisma', 'orm', 'database'], + }, + drizzle: { + dependencies: ['drizzle-orm'], + files: ['drizzle.config.ts'], + category: 'databases' as const, + tags: ['drizzle', 'orm', 'database'], + }, + typeorm: { + dependencies: ['typeorm'], + category: 'databases' as const, + tags: ['typeorm', 'orm', 'database'], + }, + mongoose: { + dependencies: ['mongoose'], + category: 'databases' as const, + tags: ['mongoose', 'mongodb', 'database'], + }, + supabase: { + dependencies: ['@supabase/supabase-js'], + category: 'databases' as const, + tags: ['supabase', 'postgres', 'database', 'auth'], + }, + firebase: { + dependencies: ['firebase', 'firebase-admin'], + category: 'databases' as const, + tags: ['firebase', 'database', 'auth'], + }, +}; + +/** + * Tool detection patterns + */ +const TOOL_PATTERNS = { + eslint: { + dependencies: ['eslint'], + files: ['.eslintrc', '.eslintrc.js', '.eslintrc.json', 'eslint.config.js'], + category: 'tools' as const, + tags: ['eslint', 'linting'], + }, + prettier: { + dependencies: ['prettier'], + files: ['.prettierrc', '.prettierrc.js', 'prettier.config.js'], + category: 'tools' as const, + tags: ['prettier', 'formatting'], + }, + biome: { + dependencies: ['@biomejs/biome'], + files: ['biome.json'], + category: 'tools' as const, + tags: ['biome', 'linting', 'formatting'], + }, + husky: { + dependencies: ['husky'], + files: ['.husky'], + category: 'tools' as const, + tags: ['husky', 'git-hooks'], + }, + 'lint-staged': { + dependencies: ['lint-staged'], + category: 'tools' as const, + tags: ['lint-staged', 'git-hooks'], + }, + turbo: { + dependencies: ['turbo'], + files: ['turbo.json'], + category: 'tools' as const, + tags: ['turbo', 'monorepo', 'build'], + }, + nx: { + dependencies: ['nx'], + files: ['nx.json'], + category: 'tools' as const, + tags: ['nx', 'monorepo', 'build'], + }, + docker: { + files: ['Dockerfile', 'docker-compose.yml', 'docker-compose.yaml'], + category: 'tools' as const, + tags: ['docker', 'containers'], + }, +}; + +/** + * Project Detector + * + * Analyzes a project directory to detect the technology stack, + * frameworks, libraries, and patterns used. + */ +export class ProjectDetector { + private projectPath: string; + private packageJson: Record | null = null; + private files: Set = new Set(); + + constructor(projectPath: string) { + this.projectPath = projectPath; + } + + /** + * Analyze the project and return detected stack + */ + analyze(): ProjectStack { + // Load package.json if exists + this.loadPackageJson(); + + // Scan root files + this.scanFiles(); + + // Detect everything + const stack: ProjectStack = { + languages: this.detectLanguages(), + frameworks: this.detectFromPatterns(FRAMEWORK_PATTERNS), + libraries: this.detectFromPatterns(LIBRARY_PATTERNS), + styling: this.detectFromPatterns(STYLING_PATTERNS), + testing: this.detectFromPatterns(TESTING_PATTERNS), + databases: this.detectFromPatterns(DATABASE_PATTERNS), + tools: this.detectFromPatterns(TOOL_PATTERNS), + runtime: this.detectRuntime(), + }; + + return stack; + } + + /** + * Detect project patterns and conventions + */ + detectPatterns(): ProjectPatterns { + const patterns: ProjectPatterns = {}; + + // Detect component style + if (this.hasFile('*.tsx') || this.hasFile('*.jsx')) { + // Check for class components vs functional + patterns.components = 'functional'; // Modern default + } + + // Detect state management + const deps = this.getDependencies(); + if (deps.has('zustand')) patterns.stateManagement = 'zustand'; + else if (deps.has('@reduxjs/toolkit') || deps.has('redux')) patterns.stateManagement = 'redux'; + else if (deps.has('jotai')) patterns.stateManagement = 'jotai'; + else if (deps.has('recoil')) patterns.stateManagement = 'recoil'; + else if (deps.has('mobx')) patterns.stateManagement = 'mobx'; + + // Detect API style + if (deps.has('@trpc/client')) patterns.apiStyle = 'trpc'; + else if (deps.has('graphql') || deps.has('@apollo/client')) patterns.apiStyle = 'graphql'; + else if (deps.has('next') && this.hasFile('app/**/actions.ts')) patterns.apiStyle = 'server-actions'; + else patterns.apiStyle = 'rest'; + + // Detect styling + if (deps.has('tailwindcss')) patterns.styling = 'tailwind'; + else if (deps.has('styled-components')) patterns.styling = 'styled-components'; + else if (deps.has('@emotion/react')) patterns.styling = 'emotion'; + else if (this.hasFile('*.module.css')) patterns.styling = 'css-modules'; + + // Detect testing + if (deps.has('vitest')) patterns.testing = 'vitest'; + else if (deps.has('jest')) patterns.testing = 'jest'; + else if (deps.has('@playwright/test')) patterns.testing = 'playwright'; + else if (deps.has('cypress')) patterns.testing = 'cypress'; + + // Detect linting + if (deps.has('@biomejs/biome')) patterns.linting = 'biome'; + else if (deps.has('eslint')) patterns.linting = 'eslint'; + + // Detect formatting + if (deps.has('@biomejs/biome')) patterns.formatting = 'biome'; + else if (deps.has('prettier')) patterns.formatting = 'prettier'; + + return patterns; + } + + /** + * Detect project type + */ + detectProjectType(): string { + const deps = this.getDependencies(); + + // Check for specific project types + if (deps.has('react-native') || deps.has('expo')) return 'mobile'; + if (deps.has('electron') || deps.has('@tauri-apps/api')) return 'desktop'; + if (deps.has('next') || deps.has('nuxt') || deps.has('remix')) return 'web-app'; + if (deps.has('express') || deps.has('fastify') || deps.has('hono')) return 'api'; + if (deps.has('commander') || deps.has('clipanion') || deps.has('yargs')) return 'cli'; + + // Check for library indicators + if (this.hasFile('rollup.config.js') || this.hasFile('tsup.config.ts')) return 'library'; + + // Default + if (deps.has('react') || deps.has('vue') || deps.has('svelte')) return 'web-app'; + + return 'unknown'; + } + + /** + * Get project name + */ + getProjectName(): string { + if (this.packageJson && typeof this.packageJson.name === 'string') { + return this.packageJson.name; + } + return basename(this.projectPath); + } + + /** + * Get project description + */ + getProjectDescription(): string | undefined { + if (this.packageJson && typeof this.packageJson.description === 'string') { + return this.packageJson.description; + } + return undefined; + } + + // Private helpers + + private loadPackageJson(): void { + const packageJsonPath = join(this.projectPath, 'package.json'); + if (existsSync(packageJsonPath)) { + try { + const content = readFileSync(packageJsonPath, 'utf-8'); + this.packageJson = JSON.parse(content); + } catch { + this.packageJson = null; + } + } + } + + private scanFiles(): void { + try { + const entries = readdirSync(this.projectPath, { withFileTypes: true }); + for (const entry of entries) { + this.files.add(entry.name); + if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') { + // Scan one level deep for common config locations + try { + const subEntries = readdirSync(join(this.projectPath, entry.name)); + for (const subEntry of subEntries) { + this.files.add(`${entry.name}/${subEntry}`); + } + } catch { + // Ignore permission errors + } + } + } + } catch { + // Ignore errors + } + } + + private getDependencies(): Set { + const deps = new Set(); + if (!this.packageJson) return deps; + + const dependencies = this.packageJson.dependencies as Record | undefined; + const devDependencies = this.packageJson.devDependencies as Record | undefined; + + if (dependencies) { + for (const dep of Object.keys(dependencies)) { + deps.add(dep); + } + } + if (devDependencies) { + for (const dep of Object.keys(devDependencies)) { + deps.add(dep); + } + } + + return deps; + } + + private getVersion(depName: string): string | undefined { + if (!this.packageJson) return undefined; + + const dependencies = this.packageJson.dependencies as Record | undefined; + const devDependencies = this.packageJson.devDependencies as Record | undefined; + + const version = dependencies?.[depName] || devDependencies?.[depName]; + if (version) { + // Clean version string (remove ^, ~, etc.) + return version.replace(/^[\^~>=<]+/, ''); + } + return undefined; + } + + private hasFile(pattern: string): boolean { + if (pattern.includes('*')) { + // Simple glob matching + const regex = new RegExp(pattern.replace(/\*/g, '.*')); + for (const file of this.files) { + if (regex.test(file)) return true; + } + return false; + } + return this.files.has(pattern); + } + + private detectLanguages(): Detection[] { + const languages: Detection[] = []; + + // TypeScript + if (this.hasFile('tsconfig.json') || this.files.has('*.ts')) { + const tsVersion = this.getVersion('typescript'); + languages.push({ + name: 'typescript', + version: tsVersion, + confidence: 100, + source: 'tsconfig.json', + }); + } + + // JavaScript (if no TypeScript, or alongside) + if (this.hasFile('jsconfig.json') || (this.packageJson && !this.hasFile('tsconfig.json'))) { + languages.push({ + name: 'javascript', + confidence: 90, + source: 'package.json', + }); + } + + // Python + if (this.hasFile('pyproject.toml') || this.hasFile('requirements.txt')) { + languages.push({ + name: 'python', + confidence: 100, + source: 'pyproject.toml', + }); + } + + // Rust + if (this.hasFile('Cargo.toml')) { + languages.push({ + name: 'rust', + confidence: 100, + source: 'Cargo.toml', + }); + } + + // Go + if (this.hasFile('go.mod')) { + languages.push({ + name: 'go', + confidence: 100, + source: 'go.mod', + }); + } + + return languages; + } + + private detectRuntime(): Detection[] { + const runtime: Detection[] = []; + + // Node.js + if (this.packageJson) { + const engines = this.packageJson.engines as Record | undefined; + const nodeVersion = engines?.node; + runtime.push({ + name: 'nodejs', + version: nodeVersion?.replace(/[>=<^~]+/g, ''), + confidence: 100, + source: 'package.json', + }); + } + + // Bun + if (this.hasFile('bun.lockb') || this.hasFile('bunfig.toml')) { + runtime.push({ + name: 'bun', + confidence: 100, + source: 'bun.lockb', + }); + } + + // Deno + if (this.hasFile('deno.json') || this.hasFile('deno.jsonc')) { + runtime.push({ + name: 'deno', + confidence: 100, + source: 'deno.json', + }); + } + + return runtime; + } + + private detectFromPatterns( + patterns: Record + ): Detection[] { + const detected: Detection[] = []; + const deps = this.getDependencies(); + + for (const [name, pattern] of Object.entries(patterns)) { + let found = false; + let source: string | undefined; + + // Check dependencies + if (pattern.dependencies) { + for (const dep of pattern.dependencies) { + if (deps.has(dep)) { + found = true; + source = 'package.json'; + break; + } + } + } + + // Check files + if (!found && pattern.files) { + for (const file of pattern.files) { + if (this.hasFile(file)) { + found = true; + source = file; + break; + } + } + } + + if (found) { + const version = pattern.dependencies ? this.getVersion(pattern.dependencies[0]) : undefined; + detected.push({ + name, + version, + confidence: 100, + source, + }); + } + } + + return detected; + } +} + +/** + * Analyze a project and return the detected stack + */ +export function analyzeProject(projectPath: string): ProjectStack { + const detector = new ProjectDetector(projectPath); + return detector.analyze(); +} + +/** + * Get all relevant tags from a project stack + */ +export function getStackTags(stack: ProjectStack): string[] { + const tags = new Set(); + + const addTags = (detections: Detection[], patterns: Record) => { + for (const detection of detections) { + const pattern = patterns[detection.name]; + if (pattern?.tags) { + for (const tag of pattern.tags) { + tags.add(tag); + } + } else { + tags.add(detection.name); + } + } + }; + + // Add language tags + for (const lang of stack.languages) { + tags.add(lang.name); + } + + // Add framework tags + addTags(stack.frameworks, FRAMEWORK_PATTERNS); + addTags(stack.libraries, LIBRARY_PATTERNS); + addTags(stack.styling, STYLING_PATTERNS); + addTags(stack.testing, TESTING_PATTERNS); + addTags(stack.databases, DATABASE_PATTERNS); + + return Array.from(tags); +} diff --git a/packages/core/src/context/index.ts b/packages/core/src/context/index.ts new file mode 100644 index 00000000..6c7afcc9 --- /dev/null +++ b/packages/core/src/context/index.ts @@ -0,0 +1,42 @@ +// Types +export { + type DependencyInfo, + type Detection, + type ProjectStack, + type ProjectPatterns, + type SkillPreferences, + type AgentConfig, + type ProjectContext, + type DetectionSource, + type ContextSyncOptions, + type ContextExportOptions, + type ContextImportOptions, + CONTEXT_FILE, + CONTEXT_DIR, + PROJECT_TYPE_HINTS, +} from './types.js'; + +// Detector +export { + ProjectDetector, + analyzeProject, + getStackTags, +} from './detector.js'; + +// Manager +export { + ContextManager, + createContextManager, + loadContext, + initContext, +} from './manager.js'; + +// Sync +export { + ContextSync, + createContextSync, + syncToAllAgents, + syncToAgent, + type SyncResult, + type SyncReport, +} from './sync.js'; diff --git a/packages/core/src/context/manager.ts b/packages/core/src/context/manager.ts new file mode 100644 index 00000000..a3886028 --- /dev/null +++ b/packages/core/src/context/manager.ts @@ -0,0 +1,468 @@ +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'; +import { + type ProjectContext, + type ProjectStack, + type SkillPreferences, + type AgentConfig, + type ContextExportOptions, + type ContextImportOptions, + type Detection, + ProjectContext as ProjectContextSchema, + CONTEXT_FILE, + CONTEXT_DIR, +} from './types.js'; +import { ProjectDetector, getStackTags } from './detector.js'; +import type { AgentType } from '../types.js'; + +/** + * Context Manager + * + * Handles loading, saving, and managing project contexts. + * The context is stored in .skillkit/context.yaml + */ +export class ContextManager { + private projectPath: string; + private context: ProjectContext | null = null; + + constructor(projectPath: string = process.cwd()) { + this.projectPath = projectPath; + } + + /** + * Get the context file path + */ + getContextPath(): string { + return join(this.projectPath, CONTEXT_FILE); + } + + /** + * Check if context exists + */ + exists(): boolean { + return existsSync(this.getContextPath()); + } + + /** + * Load context from file + */ + load(): ProjectContext | null { + const contextPath = this.getContextPath(); + + if (!existsSync(contextPath)) { + return null; + } + + try { + const content = readFileSync(contextPath, 'utf-8'); + const data = parseYaml(content); + const parsed = ProjectContextSchema.safeParse(data); + + if (parsed.success) { + this.context = parsed.data; + return this.context; + } + + // Return raw data if schema validation fails but file exists + console.warn('Context file exists but failed schema validation'); + return null; + } catch (error) { + console.warn('Failed to load context:', error); + return null; + } + } + + /** + * Save context to file + */ + save(context: ProjectContext): void { + const contextPath = this.getContextPath(); + const contextDir = join(this.projectPath, CONTEXT_DIR); + + // Ensure directory exists + if (!existsSync(contextDir)) { + mkdirSync(contextDir, { recursive: true }); + } + + // Update timestamp + context.updatedAt = new Date().toISOString(); + + // Stringify with nice formatting + const content = stringifyYaml(context, { + lineWidth: 0, + defaultKeyType: 'PLAIN', + }); + + writeFileSync(contextPath, content, 'utf-8'); + this.context = context; + } + + /** + * Initialize a new context from project detection + */ + init(options: { force?: boolean; skipDetection?: boolean } = {}): ProjectContext { + // Check if context already exists + if (this.exists() && !options.force) { + const existing = this.load(); + if (existing) { + return existing; + } + } + + // Detect project + const detector = new ProjectDetector(this.projectPath); + const stack = options.skipDetection ? this.getEmptyStack() : detector.analyze(); + const patterns = options.skipDetection ? {} : detector.detectPatterns(); + const projectType = options.skipDetection ? 'unknown' : detector.detectProjectType(); + const projectName = detector.getProjectName(); + const projectDescription = detector.getProjectDescription(); + + // Create new context + const context: ProjectContext = { + version: 1, + project: { + name: projectName, + description: projectDescription, + type: projectType, + path: this.projectPath, + }, + stack, + patterns, + skills: { + installed: [], + recommended: [], + excluded: [], + autoSync: true, + securityLevel: 'medium', + testingRequired: false, + }, + agents: { + primary: undefined, + detected: [], + synced: [], + disabled: [], + }, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + }; + + // Save and return + this.save(context); + return context; + } + + /** + * Update context with new detection + */ + refresh(): ProjectContext { + const existing = this.load(); + const detector = new ProjectDetector(this.projectPath); + const stack = detector.analyze(); + const patterns = detector.detectPatterns(); + const projectType = detector.detectProjectType(); + + if (existing) { + // Merge with existing + const merged: ProjectContext = { + ...existing, + stack, + patterns, + project: { + ...existing.project, + type: projectType, + }, + updatedAt: new Date().toISOString(), + }; + + this.save(merged); + return merged; + } + + // No existing context, initialize new + return this.init(); + } + + /** + * Get current context (load if not loaded) + */ + get(): ProjectContext | null { + if (this.context) { + return this.context; + } + return this.load(); + } + + /** + * Update skills in context + */ + updateSkills(skills: Partial): void { + const context = this.get(); + if (!context) { + throw new Error('No context found. Run `skillkit context init` first.'); + } + + context.skills = { + ...context.skills, + ...skills, + } as SkillPreferences; + + this.save(context); + } + + /** + * Update agents in context + */ + updateAgents(agents: Partial): void { + const context = this.get(); + if (!context) { + throw new Error('No context found. Run `skillkit context init` first.'); + } + + context.agents = { + ...context.agents, + ...agents, + } as AgentConfig; + + this.save(context); + } + + /** + * Set primary agent + */ + setPrimaryAgent(agent: AgentType): void { + this.updateAgents({ primary: agent }); + } + + /** + * Add agent to synced list + */ + addSyncedAgent(agent: AgentType): void { + const context = this.get(); + if (!context) { + throw new Error('No context found'); + } + + const synced = new Set(context.agents?.synced || []); + synced.add(agent); + + this.updateAgents({ synced: Array.from(synced) }); + } + + /** + * Remove agent from synced list + */ + removeSyncedAgent(agent: AgentType): void { + const context = this.get(); + if (!context) { + throw new Error('No context found'); + } + + const synced = new Set(context.agents?.synced || []); + synced.delete(agent); + + this.updateAgents({ synced: Array.from(synced) }); + } + + /** + * Add installed skill + */ + addInstalledSkill(skillName: string): void { + const context = this.get(); + if (!context) return; + + const installed = new Set(context.skills?.installed || []); + installed.add(skillName); + + this.updateSkills({ installed: Array.from(installed) }); + } + + /** + * Remove installed skill + */ + removeInstalledSkill(skillName: string): void { + const context = this.get(); + if (!context) return; + + const installed = new Set(context.skills?.installed || []); + installed.delete(skillName); + + this.updateSkills({ installed: Array.from(installed) }); + } + + /** + * Export context to file + */ + export(options: ContextExportOptions = {}): string { + const context = this.get(); + if (!context) { + throw new Error('No context found'); + } + + // Clone and optionally filter + const exported = { ...context }; + + if (!options.includeSkills) { + delete (exported as Record).skills; + } + if (!options.includeAgents) { + delete (exported as Record).agents; + } + + // Format + if (options.format === 'json') { + return JSON.stringify(exported, null, 2); + } + + return stringifyYaml(exported, { + lineWidth: 0, + defaultKeyType: 'PLAIN', + }); + } + + /** + * Import context from content + */ + import(content: string, options: ContextImportOptions = {}): ProjectContext { + // Parse content + let data: unknown; + try { + // Try JSON first + data = JSON.parse(content); + } catch { + // Try YAML + data = parseYaml(content); + } + + const parsed = ProjectContextSchema.safeParse(data); + if (!parsed.success) { + throw new Error(`Invalid context format: ${parsed.error.message}`); + } + + const imported = parsed.data; + + if (options.merge && this.exists()) { + const existing = this.load()!; + const merged = this.mergeContexts(existing, imported); + this.save(merged); + return merged; + } + + if (!options.overwrite && this.exists()) { + throw new Error('Context already exists. Use --merge or --overwrite.'); + } + + this.save(imported); + return imported; + } + + /** + * Merge two contexts + */ + private mergeContexts(existing: ProjectContext, imported: ProjectContext): ProjectContext { + return { + version: 1, + project: { + ...existing.project, + ...imported.project, + }, + stack: this.mergeStacks(existing.stack, imported.stack), + patterns: { + ...existing.patterns, + ...imported.patterns, + }, + skills: { + installed: [...new Set([...(existing.skills?.installed || []), ...(imported.skills?.installed || [])])], + recommended: [...new Set([...(existing.skills?.recommended || []), ...(imported.skills?.recommended || [])])], + excluded: [...new Set([...(existing.skills?.excluded || []), ...(imported.skills?.excluded || [])])], + autoSync: imported.skills?.autoSync ?? existing.skills?.autoSync ?? true, + securityLevel: imported.skills?.securityLevel ?? existing.skills?.securityLevel ?? 'medium', + testingRequired: imported.skills?.testingRequired ?? existing.skills?.testingRequired ?? false, + }, + agents: { + primary: imported.agents?.primary ?? existing.agents?.primary, + detected: [...new Set([...(existing.agents?.detected || []), ...(imported.agents?.detected || [])])], + synced: [...new Set([...(existing.agents?.synced || []), ...(imported.agents?.synced || [])])], + disabled: [...new Set([...(existing.agents?.disabled || []), ...(imported.agents?.disabled || [])])], + }, + createdAt: existing.createdAt, + updatedAt: new Date().toISOString(), + }; + } + + /** + * Merge two stacks + */ + private mergeStacks(existing: ProjectStack, imported: ProjectStack): ProjectStack { + const mergeArrays = (a: Detection[], b: Detection[]): Detection[] => { + const names = new Set(a.map((item) => item.name)); + const result: Detection[] = [...a]; + for (const item of b) { + if (!names.has(item.name)) { + result.push(item); + } + } + return result; + }; + + return { + languages: mergeArrays(existing.languages, imported.languages), + frameworks: mergeArrays(existing.frameworks, imported.frameworks), + libraries: mergeArrays(existing.libraries, imported.libraries), + styling: mergeArrays(existing.styling, imported.styling), + testing: mergeArrays(existing.testing, imported.testing), + databases: mergeArrays(existing.databases, imported.databases), + tools: mergeArrays(existing.tools, imported.tools), + runtime: mergeArrays(existing.runtime, imported.runtime), + }; + } + + /** + * Get empty stack + */ + private getEmptyStack(): ProjectStack { + return { + languages: [], + frameworks: [], + libraries: [], + styling: [], + testing: [], + databases: [], + tools: [], + runtime: [], + }; + } + + /** + * Get recommended skill tags based on stack + */ + getRecommendedTags(): string[] { + const context = this.get(); + if (!context) return []; + + return getStackTags(context.stack); + } +} + +/** + * Create a context manager for the current directory + */ +export function createContextManager(projectPath?: string): ContextManager { + return new ContextManager(projectPath); +} + +/** + * Load context from the current directory + */ +export function loadContext(projectPath?: string): ProjectContext | null { + const manager = new ContextManager(projectPath); + return manager.load(); +} + +/** + * Initialize context in the current directory + */ +export function initContext(projectPath?: string, options?: { force?: boolean }): ProjectContext { + const manager = new ContextManager(projectPath); + return manager.init(options); +} diff --git a/packages/core/src/context/sync.ts b/packages/core/src/context/sync.ts new file mode 100644 index 00000000..56690861 --- /dev/null +++ b/packages/core/src/context/sync.ts @@ -0,0 +1,386 @@ +import { existsSync, writeFileSync, mkdirSync, copyFileSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import type { AgentType } from '../types.js'; +import type { ContextSyncOptions } from './types.js'; +import { ContextManager } from './manager.js'; +import { translateSkillFile } from '../translator/index.js'; +import { findAllSkills } from '../skills.js'; + +/** + * Result of a sync operation + */ +export interface SyncResult { + success: boolean; + agent: AgentType; + skillsSynced: number; + skillsSkipped: number; + errors: string[]; + warnings: string[]; + files: string[]; +} + +/** + * Overall sync report + */ +export interface SyncReport { + totalAgents: number; + successfulAgents: number; + totalSkills: number; + results: SyncResult[]; +} + +/** + * Agent directory configuration + */ +const AGENT_DIRS: Record = { + 'claude-code': { skillsDir: '.claude/skills', configFile: 'AGENTS.md' }, + 'cursor': { skillsDir: '.cursor/skills', configFile: '.cursorrules' }, + 'codex': { skillsDir: '.codex/skills', configFile: 'AGENTS.md' }, + 'gemini-cli': { skillsDir: '.gemini/skills', configFile: 'GEMINI.md' }, + 'opencode': { skillsDir: '.opencode/skills', configFile: 'AGENTS.md' }, + 'antigravity': { skillsDir: '.antigravity/skills', configFile: 'AGENTS.md' }, + 'amp': { skillsDir: '.agents/skills', configFile: 'AGENTS.md' }, + 'clawdbot': { skillsDir: 'skills', configFile: 'AGENTS.md' }, + 'droid': { skillsDir: '.factory/skills', configFile: 'AGENTS.md' }, + 'github-copilot': { skillsDir: '.github/skills', configFile: 'AGENTS.md' }, + 'goose': { skillsDir: '.goose/skills', configFile: 'AGENTS.md' }, + 'kilo': { skillsDir: '.kilocode/skills', configFile: 'AGENTS.md' }, + 'kiro-cli': { skillsDir: '.kiro/skills', configFile: 'AGENTS.md' }, + 'roo': { skillsDir: '.roo/skills', configFile: 'AGENTS.md' }, + 'trae': { skillsDir: '.trae/skills', configFile: 'AGENTS.md' }, + 'windsurf': { skillsDir: '.windsurf/skills', configFile: 'AGENTS.md' }, + 'universal': { skillsDir: '.agent/skills', configFile: 'AGENTS.md' }, +}; + +/** + * Context Sync + * + * Handles syncing skills across multiple AI agents. + * Skills are translated to the appropriate format for each agent. + */ +export class ContextSync { + private projectPath: string; + private contextManager: ContextManager; + + constructor(projectPath: string = process.cwd()) { + this.projectPath = projectPath; + this.contextManager = new ContextManager(projectPath); + } + + /** + * Detect which agents are installed/configured on the system + */ + detectAgents(): AgentType[] { + const detected: AgentType[] = []; + + for (const [agent, config] of Object.entries(AGENT_DIRS)) { + const skillsPath = join(this.projectPath, config.skillsDir); + const configPath = join(this.projectPath, config.configFile); + + // Check if either skills directory or config file exists + if (existsSync(skillsPath) || existsSync(configPath)) { + detected.push(agent as AgentType); + } + } + + // Also check for global indicators + const homeDir = process.env.HOME || process.env.USERPROFILE || ''; + if (homeDir) { + // Check for Claude Code + if (existsSync(join(homeDir, '.claude'))) { + if (!detected.includes('claude-code')) detected.push('claude-code'); + } + // Check for Cursor + if (existsSync(join(homeDir, '.cursor'))) { + if (!detected.includes('cursor')) detected.push('cursor'); + } + } + + return detected; + } + + /** + * Get agents to sync to based on context + */ + getTargetAgents(options: ContextSyncOptions = {}): AgentType[] { + // If specific agents provided, use those + if (options.agents?.length) { + return options.agents; + } + + // Load context + const context = this.contextManager.get(); + if (context?.agents?.synced?.length) { + return context.agents.synced as AgentType[]; + } + + // Auto-detect + return this.detectAgents(); + } + + /** + * Sync all skills to all target agents + */ + async syncAll(options: ContextSyncOptions = {}): Promise { + const targetAgents = this.getTargetAgents(options); + const results: SyncResult[] = []; + + // Get all installed skills from primary agent or first available + const skills = this.getSourceSkills(); + + for (const agent of targetAgents) { + const result = await this.syncToAgent(agent, skills, options); + results.push(result); + } + + // Update context with synced agents + if (!options.dryRun) { + this.contextManager.updateAgents({ + detected: this.detectAgents(), + synced: targetAgents, + }); + } + + return { + totalAgents: targetAgents.length, + successfulAgents: results.filter((r) => r.success).length, + totalSkills: skills.length, + results, + }; + } + + /** + * Sync skills to a specific agent + */ + async syncToAgent( + agent: AgentType, + skills?: Array<{ name: string; path: string }>, + options: ContextSyncOptions = {} + ): Promise { + const result: SyncResult = { + success: true, + agent, + skillsSynced: 0, + skillsSkipped: 0, + errors: [], + warnings: [], + files: [], + }; + + // Get skills if not provided + const sourceSkills = skills || this.getSourceSkills(); + + // Get target directory + const agentConfig = AGENT_DIRS[agent]; + if (!agentConfig) { + result.success = false; + result.errors.push(`Unknown agent: ${agent}`); + return result; + } + + const targetDir = join(this.projectPath, agentConfig.skillsDir); + + // Create target directory if not dry run + if (!options.dryRun && !existsSync(targetDir)) { + mkdirSync(targetDir, { recursive: true }); + } + + // Sync each skill + for (const skill of sourceSkills) { + try { + const skillResult = await this.syncSkill(skill, agent, targetDir, options); + if (skillResult.synced) { + result.skillsSynced++; + result.files.push(skillResult.file!); + } else { + result.skillsSkipped++; + if (skillResult.warning) { + result.warnings.push(skillResult.warning); + } + } + } catch (error) { + result.errors.push(`Failed to sync ${skill.name}: ${error}`); + result.skillsSkipped++; + } + } + + if (result.errors.length > 0) { + result.success = false; + } + + return result; + } + + /** + * Sync a single skill to an agent + */ + private async syncSkill( + skill: { name: string; path: string }, + agent: AgentType, + targetDir: string, + options: ContextSyncOptions + ): Promise<{ synced: boolean; file?: string; warning?: string }> { + const skillMdPath = join(skill.path, 'SKILL.md'); + + if (!existsSync(skillMdPath)) { + return { synced: false, warning: `No SKILL.md found for ${skill.name}` }; + } + + // Translate skill to target format + const translation = translateSkillFile(skillMdPath, agent, { + addMetadata: true, + }); + + if (!translation.success) { + return { synced: false, warning: `Translation failed for ${skill.name}` }; + } + + // Determine output path + const targetSkillDir = join(targetDir, skill.name); + const outputPath = join(targetSkillDir, translation.filename); + + // Check if file exists and skip if not forcing + if (existsSync(outputPath) && !options.force) { + return { synced: false, warning: `${skill.name} already exists (use --force to overwrite)` }; + } + + // Write file (unless dry run) + if (!options.dryRun) { + if (!existsSync(targetSkillDir)) { + mkdirSync(targetSkillDir, { recursive: true }); + } + writeFileSync(outputPath, translation.content, 'utf-8'); + + // Copy additional skill assets if they exist + await this.copySkillAssets(skill.path, targetSkillDir); + } + + return { synced: true, file: outputPath }; + } + + /** + * Copy additional skill assets (references, scripts, etc.) + */ + private async copySkillAssets(sourcePath: string, targetPath: string): Promise { + const assetDirs = ['references', 'scripts', 'assets', 'templates']; + + for (const assetDir of assetDirs) { + const sourceAssetDir = join(sourcePath, assetDir); + if (existsSync(sourceAssetDir)) { + const targetAssetDir = join(targetPath, assetDir); + if (!existsSync(targetAssetDir)) { + mkdirSync(targetAssetDir, { recursive: true }); + } + + // Copy files + try { + const files = readdirSync(sourceAssetDir); + for (const file of files) { + const sourcefile = join(sourceAssetDir, file); + const targetFile = join(targetAssetDir, file); + copyFileSync(sourcefile, targetFile); + } + } catch { + // Ignore copy errors + } + } + } + } + + /** + * Get source skills to sync + */ + private getSourceSkills(): Array<{ name: string; path: string }> { + const context = this.contextManager.get(); + const primaryAgent = context?.agents?.primary as AgentType | undefined; + + // Search directories based on primary agent or common locations + const searchDirs: string[] = []; + + if (primaryAgent && AGENT_DIRS[primaryAgent]) { + searchDirs.push(join(this.projectPath, AGENT_DIRS[primaryAgent].skillsDir)); + } + + // Add common skill locations + const commonDirs = [ + '.claude/skills', + '.cursor/skills', + '.agent/skills', + 'skills', + ]; + + for (const dir of commonDirs) { + const fullPath = join(this.projectPath, dir); + if (!searchDirs.includes(fullPath) && existsSync(fullPath)) { + searchDirs.push(fullPath); + } + } + + // Find all skills + const skills = findAllSkills(searchDirs); + return skills.map((s) => ({ name: s.name, path: s.path })); + } + + /** + * Check sync status - which agents have which skills + */ + checkStatus(): Record { + const status: Record = {}; + + for (const [agent, config] of Object.entries(AGENT_DIRS)) { + const skillsPath = join(this.projectPath, config.skillsDir); + const skills: string[] = []; + + if (existsSync(skillsPath)) { + try { + const entries = readdirSync(skillsPath, { withFileTypes: true }); + for (const entry of entries) { + if (entry.isDirectory()) { + skills.push(entry.name); + } + } + } catch { + // Ignore errors + } + } + + status[agent] = { + hasSkills: skills.length > 0, + skillCount: skills.length, + skills, + }; + } + + return status as Record; + } +} + +/** + * Create a context sync instance + */ +export function createContextSync(projectPath?: string): ContextSync { + return new ContextSync(projectPath); +} + +/** + * Sync skills to all detected agents + */ +export async function syncToAllAgents( + projectPath?: string, + options?: ContextSyncOptions +): Promise { + const sync = new ContextSync(projectPath); + return sync.syncAll(options); +} + +/** + * Sync skills to a specific agent + */ +export async function syncToAgent( + agent: AgentType, + projectPath?: string, + options?: ContextSyncOptions +): Promise { + const sync = new ContextSync(projectPath); + return sync.syncToAgent(agent, undefined, options); +} diff --git a/packages/core/src/context/types.ts b/packages/core/src/context/types.ts new file mode 100644 index 00000000..651f7e9f --- /dev/null +++ b/packages/core/src/context/types.ts @@ -0,0 +1,172 @@ +import { z } from 'zod'; +import type { AgentType } from '../types.js'; + +/** + * Detected dependency with version + */ +export const DependencyInfo = z.object({ + name: z.string(), + version: z.string().optional(), + dev: z.boolean().default(false), +}); +export type DependencyInfo = z.infer; + +/** + * Detection result with confidence + */ +export const Detection = z.object({ + name: z.string(), + version: z.string().optional(), + confidence: z.number().min(0).max(100).default(100), + source: z.string().optional(), // Where it was detected from +}); +export type Detection = z.infer; + +/** + * Project stack detection results + */ +export const ProjectStack = z.object({ + languages: z.array(Detection).default([]), + frameworks: z.array(Detection).default([]), + libraries: z.array(Detection).default([]), + styling: z.array(Detection).default([]), + testing: z.array(Detection).default([]), + databases: z.array(Detection).default([]), + tools: z.array(Detection).default([]), + runtime: z.array(Detection).default([]), +}); +export type ProjectStack = z.infer; + +/** + * Project patterns and conventions + */ +export const ProjectPatterns = z.object({ + components: z.string().optional(), // 'functional', 'class', 'mixed' + stateManagement: z.string().optional(), // 'redux', 'zustand', 'context', etc. + apiStyle: z.string().optional(), // 'rest', 'graphql', 'trpc', 'server-actions' + styling: z.string().optional(), // 'css-modules', 'tailwind', 'styled-components' + testing: z.string().optional(), // 'jest', 'vitest', 'playwright' + linting: z.string().optional(), // 'eslint', 'biome' + formatting: z.string().optional(), // 'prettier', 'biome' +}); +export type ProjectPatterns = z.infer; + +/** + * Skill preferences for the project + */ +export const SkillPreferences = z.object({ + installed: z.array(z.string()).default([]), + recommended: z.array(z.string()).default([]), + excluded: z.array(z.string()).default([]), + autoSync: z.boolean().default(true), + securityLevel: z.enum(['low', 'medium', 'high']).default('medium'), + testingRequired: z.boolean().default(false), +}); +export type SkillPreferences = z.infer; + +/** + * Agent configuration for the project + */ +export const AgentConfig = z.object({ + primary: z.string().optional(), // Primary agent + detected: z.array(z.string()).default([]), // Auto-detected agents + synced: z.array(z.string()).default([]), // Agents to sync skills to + disabled: z.array(z.string()).default([]), // Agents to skip +}); +export type AgentConfig = z.infer; + +/** + * Full project context + */ +export const ProjectContext = z.object({ + version: z.literal(1), + project: z.object({ + name: z.string(), + description: z.string().optional(), + type: z.string().optional(), // 'web-app', 'cli', 'library', 'api', etc. + path: z.string().optional(), + }), + stack: ProjectStack, + patterns: ProjectPatterns.optional(), + skills: SkillPreferences.optional(), + agents: AgentConfig.optional(), + createdAt: z.string().datetime().optional(), + updatedAt: z.string().datetime().optional(), +}); +export type ProjectContext = z.infer; + +/** + * Context file location + */ +export const CONTEXT_FILE = '.skillkit/context.yaml'; +export const CONTEXT_DIR = '.skillkit'; + +/** + * Detection source types + */ +export type DetectionSource = + | 'package.json' + | 'tsconfig.json' + | 'pyproject.toml' + | 'Cargo.toml' + | 'go.mod' + | 'pubspec.yaml' + | 'folder-structure' + | 'config-file' + | 'manual'; + +/** + * Project type hints based on detection + */ +export const PROJECT_TYPE_HINTS: Record = { + 'web-app': ['react', 'vue', 'angular', 'svelte', 'nextjs', 'nuxt', 'remix'], + 'api': ['express', 'fastify', 'koa', 'hono', 'fastapi', 'flask', 'django'], + 'cli': ['commander', 'yargs', 'clipanion', 'clap', 'cobra'], + 'library': ['rollup', 'esbuild', 'tsup', 'unbuild'], + 'mobile': ['react-native', 'expo', 'flutter', 'ionic'], + 'desktop': ['electron', 'tauri'], +}; + +/** + * Framework detection patterns + */ +export interface FrameworkPattern { + name: string; + indicators: { + dependencies?: string[]; + devDependencies?: string[]; + files?: string[]; + configFiles?: string[]; + }; + category: keyof ProjectStack; + relatedTags?: string[]; +} + +/** + * Context sync options + */ +export interface ContextSyncOptions { + agents?: AgentType[]; + force?: boolean; + dryRun?: boolean; + skillsOnly?: boolean; +} + +/** + * Context export options + */ +export interface ContextExportOptions { + output?: string; + format?: 'yaml' | 'json'; + includeSkills?: boolean; + includeAgents?: boolean; +} + +/** + * Context import options + */ +export interface ContextImportOptions { + merge?: boolean; + overwrite?: boolean; + skipDetection?: boolean; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 00000000..17884746 --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,20 @@ +// Types +export * from './types.js'; + +// Skills discovery and parsing +export * from './skills.js'; + +// Configuration +export * from './config.js'; + +// Git providers +export * from './providers/index.js'; + +// Translator (Universal Skill Translator) +export * from './translator/index.js'; + +// Context (Project Context Sync) +export * from './context/index.js'; + +// Recommendation Engine (Smart Recommendations) +export * from './recommend/index.js'; diff --git a/packages/core/src/providers/base.ts b/packages/core/src/providers/base.ts new file mode 100644 index 00000000..5d67f68e --- /dev/null +++ b/packages/core/src/providers/base.ts @@ -0,0 +1,53 @@ +import type { GitProvider, CloneResult } from '../types.js'; + +export interface GitProviderAdapter { + readonly type: GitProvider; + readonly name: string; + readonly baseUrl: string; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null; + matches(source: string): boolean; + getCloneUrl(owner: string, repo: string): string; + getSshUrl(owner: string, repo: string): string; + clone(source: string, targetDir: string, options?: CloneOptions): Promise; +} + +export interface CloneOptions { + depth?: number; + branch?: string; + ssh?: boolean; +} + +export function parseShorthand(source: string): { owner: string; repo: string; subpath?: string } | null { + const cleaned = source.replace(/^\/+|\/+$/g, ''); + const parts = cleaned.split('/'); + + if (parts.length < 2) { + return null; + } + + const owner = parts[0]; + const repo = parts[1]; + const subpath = parts.length > 2 ? parts.slice(2).join('/') : undefined; + + return { owner, repo, subpath }; +} + +export function isLocalPath(source: string): boolean { + return ( + source.startsWith('/') || + source.startsWith('./') || + source.startsWith('../') || + source.startsWith('~/') || + source.startsWith('.') + ); +} + +export function isGitUrl(source: string): boolean { + return ( + source.startsWith('git@') || + source.startsWith('https://') || + source.startsWith('http://') || + source.startsWith('ssh://') + ); +} diff --git a/packages/core/src/providers/bitbucket.ts b/packages/core/src/providers/bitbucket.ts new file mode 100644 index 00000000..940108b7 --- /dev/null +++ b/packages/core/src/providers/bitbucket.ts @@ -0,0 +1,104 @@ +import { execSync } from 'node:child_process'; +import { existsSync, rmSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import { tmpdir } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import type { GitProviderAdapter, CloneOptions } from './base.js'; +import { parseShorthand } from './base.js'; +import type { GitProvider, CloneResult } from '../types.js'; +import { discoverSkills } from '../skills.js'; + +export class BitbucketProvider implements GitProviderAdapter { + readonly type: GitProvider = 'bitbucket'; + readonly name = 'Bitbucket'; + readonly baseUrl = 'https://bitbucket.org'; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null { + if (source.startsWith('https://bitbucket.org/')) { + const path = source.replace('https://bitbucket.org/', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('git@bitbucket.org:')) { + const path = source.replace('git@bitbucket.org:', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('bitbucket:')) { + return parseShorthand(source.replace('bitbucket:', '')); + } + + if (source.startsWith('bitbucket.org/')) { + return parseShorthand(source.replace('bitbucket.org/', '')); + } + + return null; + } + + matches(source: string): boolean { + return ( + source.startsWith('https://bitbucket.org/') || + source.startsWith('git@bitbucket.org:') || + source.startsWith('bitbucket:') || + source.startsWith('bitbucket.org/') + ); + } + + getCloneUrl(owner: string, repo: string): string { + return `https://bitbucket.org/${owner}/${repo}.git`; + } + + getSshUrl(owner: string, repo: string): string { + return `git@bitbucket.org:${owner}/${repo}.git`; + } + + async clone(source: string, _targetDir: string, options: CloneOptions = {}): Promise { + const parsed = this.parseSource(source); + if (!parsed) { + return { success: false, error: `Invalid Bitbucket source: ${source}` }; + } + + const { owner, repo, subpath } = parsed; + const cloneUrl = options.ssh ? this.getSshUrl(owner, repo) : this.getCloneUrl(owner, repo); + + const tempDir = join(tmpdir(), `skillkit-${randomUUID()}`); + + try { + const args = ['clone']; + if (options.depth) { + args.push('--depth', String(options.depth)); + } + if (options.branch) { + args.push('--branch', options.branch); + } + args.push(cloneUrl, tempDir); + + execSync(`git ${args.join(' ')}`, { + stdio: ['pipe', 'pipe', 'pipe'], + encoding: 'utf-8', + }); + + const searchDir = subpath ? join(tempDir, subpath) : tempDir; + const skills = discoverSkills(searchDir); + + return { + success: true, + path: searchDir, + tempRoot: tempDir, + skills: skills.map(s => s.name), + discoveredSkills: skills.map(s => ({ + name: s.name, + dirName: basename(s.path), + path: s.path, + })), + }; + } catch (error) { + if (existsSync(tempDir)) { + rmSync(tempDir, { recursive: true, force: true }); + } + + const message = error instanceof Error ? error.message : String(error); + return { success: false, error: `Failed to clone: ${message}` }; + } + } +} diff --git a/packages/core/src/providers/github.ts b/packages/core/src/providers/github.ts new file mode 100644 index 00000000..dc2b4455 --- /dev/null +++ b/packages/core/src/providers/github.ts @@ -0,0 +1,99 @@ +import { execSync } from 'node:child_process'; +import { existsSync, rmSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import { tmpdir } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import type { GitProviderAdapter, CloneOptions } from './base.js'; +import { parseShorthand, isGitUrl } from './base.js'; +import type { GitProvider, CloneResult } from '../types.js'; +import { discoverSkills } from '../skills.js'; + +export class GitHubProvider implements GitProviderAdapter { + readonly type: GitProvider = 'github'; + readonly name = 'GitHub'; + readonly baseUrl = 'https://github.com'; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null { + if (source.startsWith('https://github.com/')) { + const path = source.replace('https://github.com/', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('git@github.com:')) { + const path = source.replace('git@github.com:', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (!isGitUrl(source) && !source.includes(':')) { + return parseShorthand(source); + } + + return null; + } + + matches(source: string): boolean { + return ( + source.startsWith('https://github.com/') || + source.startsWith('git@github.com:') || + (!isGitUrl(source) && !source.includes(':') && source.includes('/')) + ); + } + + getCloneUrl(owner: string, repo: string): string { + return `https://github.com/${owner}/${repo}.git`; + } + + getSshUrl(owner: string, repo: string): string { + return `git@github.com:${owner}/${repo}.git`; + } + + async clone(source: string, _targetDir: string, options: CloneOptions = {}): Promise { + const parsed = this.parseSource(source); + if (!parsed) { + return { success: false, error: `Invalid GitHub source: ${source}` }; + } + + const { owner, repo, subpath } = parsed; + const cloneUrl = options.ssh ? this.getSshUrl(owner, repo) : this.getCloneUrl(owner, repo); + + const tempDir = join(tmpdir(), `skillkit-${randomUUID()}`); + + try { + const args = ['clone']; + if (options.depth) { + args.push('--depth', String(options.depth)); + } + if (options.branch) { + args.push('--branch', options.branch); + } + args.push(cloneUrl, tempDir); + + execSync(`git ${args.join(' ')}`, { + stdio: ['pipe', 'pipe', 'pipe'], + encoding: 'utf-8', + }); + + const searchDir = subpath ? join(tempDir, subpath) : tempDir; + const skills = discoverSkills(searchDir); + + return { + success: true, + path: searchDir, + tempRoot: tempDir, + skills: skills.map(s => s.name), + discoveredSkills: skills.map(s => ({ + name: s.name, + dirName: basename(s.path), + path: s.path, + })), + }; + } catch (error) { + if (existsSync(tempDir)) { + rmSync(tempDir, { recursive: true, force: true }); + } + + const message = error instanceof Error ? error.message : String(error); + return { success: false, error: `Failed to clone: ${message}` }; + } + } +} diff --git a/packages/core/src/providers/gitlab.ts b/packages/core/src/providers/gitlab.ts new file mode 100644 index 00000000..b96cbe81 --- /dev/null +++ b/packages/core/src/providers/gitlab.ts @@ -0,0 +1,104 @@ +import { execSync } from 'node:child_process'; +import { existsSync, rmSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import { tmpdir } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import type { GitProviderAdapter, CloneOptions } from './base.js'; +import { parseShorthand } from './base.js'; +import type { GitProvider, CloneResult } from '../types.js'; +import { discoverSkills } from '../skills.js'; + +export class GitLabProvider implements GitProviderAdapter { + readonly type: GitProvider = 'gitlab'; + readonly name = 'GitLab'; + readonly baseUrl = 'https://gitlab.com'; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null { + if (source.startsWith('https://gitlab.com/')) { + const path = source.replace('https://gitlab.com/', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('git@gitlab.com:')) { + const path = source.replace('git@gitlab.com:', '').replace(/\.git$/, ''); + return parseShorthand(path); + } + + if (source.startsWith('gitlab:')) { + return parseShorthand(source.replace('gitlab:', '')); + } + + if (source.startsWith('gitlab.com/')) { + return parseShorthand(source.replace('gitlab.com/', '')); + } + + return null; + } + + matches(source: string): boolean { + return ( + source.startsWith('https://gitlab.com/') || + source.startsWith('git@gitlab.com:') || + source.startsWith('gitlab:') || + source.startsWith('gitlab.com/') + ); + } + + getCloneUrl(owner: string, repo: string): string { + return `https://gitlab.com/${owner}/${repo}.git`; + } + + getSshUrl(owner: string, repo: string): string { + return `git@gitlab.com:${owner}/${repo}.git`; + } + + async clone(source: string, _targetDir: string, options: CloneOptions = {}): Promise { + const parsed = this.parseSource(source); + if (!parsed) { + return { success: false, error: `Invalid GitLab source: ${source}` }; + } + + const { owner, repo, subpath } = parsed; + const cloneUrl = options.ssh ? this.getSshUrl(owner, repo) : this.getCloneUrl(owner, repo); + + const tempDir = join(tmpdir(), `skillkit-${randomUUID()}`); + + try { + const args = ['clone']; + if (options.depth) { + args.push('--depth', String(options.depth)); + } + if (options.branch) { + args.push('--branch', options.branch); + } + args.push(cloneUrl, tempDir); + + execSync(`git ${args.join(' ')}`, { + stdio: ['pipe', 'pipe', 'pipe'], + encoding: 'utf-8', + }); + + const searchDir = subpath ? join(tempDir, subpath) : tempDir; + const skills = discoverSkills(searchDir); + + return { + success: true, + path: searchDir, + tempRoot: tempDir, + skills: skills.map(s => s.name), + discoveredSkills: skills.map(s => ({ + name: s.name, + dirName: basename(s.path), + path: s.path, + })), + }; + } catch (error) { + if (existsSync(tempDir)) { + rmSync(tempDir, { recursive: true, force: true }); + } + + const message = error instanceof Error ? error.message : String(error); + return { success: false, error: `Failed to clone: ${message}` }; + } + } +} diff --git a/packages/core/src/providers/index.ts b/packages/core/src/providers/index.ts new file mode 100644 index 00000000..f577863f --- /dev/null +++ b/packages/core/src/providers/index.ts @@ -0,0 +1,48 @@ +import type { GitProviderAdapter } from './base.js'; +import type { GitProvider } from '../types.js'; +import { GitHubProvider } from './github.js'; +import { GitLabProvider } from './gitlab.js'; +import { BitbucketProvider } from './bitbucket.js'; +import { LocalProvider } from './local.js'; + +export * from './base.js'; +export * from './github.js'; +export * from './gitlab.js'; +export * from './bitbucket.js'; +export * from './local.js'; + +const providers: GitProviderAdapter[] = [ + new LocalProvider(), + new GitLabProvider(), + new BitbucketProvider(), + new GitHubProvider(), +]; + +export function getProvider(type: GitProvider): GitProviderAdapter | undefined { + return providers.find(p => p.type === type); +} + +export function getAllProviders(): GitProviderAdapter[] { + return providers; +} + +export function detectProvider(source: string): GitProviderAdapter | undefined { + return providers.find(p => p.matches(source)); +} + +export function parseSource(source: string): { + provider: GitProviderAdapter; + owner: string; + repo: string; + subpath?: string; +} | null { + for (const provider of providers) { + if (provider.matches(source)) { + const parsed = provider.parseSource(source); + if (parsed) { + return { provider, ...parsed }; + } + } + } + return null; +} diff --git a/packages/core/src/providers/local.ts b/packages/core/src/providers/local.ts new file mode 100644 index 00000000..6d92d632 --- /dev/null +++ b/packages/core/src/providers/local.ts @@ -0,0 +1,88 @@ +import { existsSync, statSync, realpathSync } from 'node:fs'; +import { join, resolve, basename } from 'node:path'; +import { homedir } from 'node:os'; +import type { GitProviderAdapter, CloneOptions } from './base.js'; +import { isLocalPath } from './base.js'; +import type { GitProvider, CloneResult } from '../types.js'; +import { discoverSkills } from '../skills.js'; + +export class LocalProvider implements GitProviderAdapter { + readonly type: GitProvider = 'local'; + readonly name = 'Local Filesystem'; + readonly baseUrl = ''; + + parseSource(source: string): { owner: string; repo: string; subpath?: string } | null { + if (!isLocalPath(source)) { + return null; + } + + let expandedPath = source; + if (source.startsWith('~/')) { + expandedPath = join(homedir(), source.slice(2)); + } + + const absolutePath = resolve(expandedPath); + const dirName = basename(absolutePath); + + return { + owner: 'local', + repo: dirName, + subpath: absolutePath, + }; + } + + matches(source: string): boolean { + return isLocalPath(source); + } + + getCloneUrl(_owner: string, _repo: string): string { + return ''; + } + + getSshUrl(_owner: string, _repo: string): string { + return ''; + } + + async clone(source: string, _targetDir: string, _options: CloneOptions = {}): Promise { + const parsed = this.parseSource(source); + if (!parsed || !parsed.subpath) { + return { success: false, error: `Invalid local path: ${source}` }; + } + + const sourcePath = parsed.subpath; + + if (!existsSync(sourcePath)) { + return { success: false, error: `Path does not exist: ${sourcePath}` }; + } + + const stats = statSync(sourcePath); + if (!stats.isDirectory()) { + return { success: false, error: `Path is not a directory: ${sourcePath}` }; + } + + try { + let actualPath = sourcePath; + try { + actualPath = realpathSync(sourcePath); + } catch { + // Ignore realpath errors + } + + const skills = discoverSkills(actualPath); + + return { + success: true, + path: actualPath, + skills: skills.map(s => s.name), + discoveredSkills: skills.map(s => ({ + name: s.name, + dirName: basename(s.path), + path: s.path, + })), + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return { success: false, error: `Failed to process local path: ${message}` }; + } + } +} diff --git a/packages/core/src/recommend/__tests__/engine.test.ts b/packages/core/src/recommend/__tests__/engine.test.ts new file mode 100644 index 00000000..204cf96b --- /dev/null +++ b/packages/core/src/recommend/__tests__/engine.test.ts @@ -0,0 +1,590 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { RecommendationEngine, createRecommendationEngine } from '../engine.js'; +import { getTechTags } from '../types.js'; +import type { + SkillSummary, + SkillIndex, + ProjectProfile, + ScoringWeights, +} from '../types.js'; +import type { ProjectStack } from '../../context/types.js'; + +describe('RecommendationEngine', () => { + let engine: RecommendationEngine; + + // Sample project profile (React + TypeScript + Tailwind) + const sampleProfile: ProjectProfile = { + name: 'test-project', + type: 'web-app', + stack: { + languages: [ + { name: 'typescript', version: '5.0.0', confidence: 100 }, + { name: 'javascript', confidence: 80 }, + ], + frameworks: [ + { name: 'react', version: '19.0.0', confidence: 100 }, + { name: 'nextjs', version: '15.0.0', confidence: 100 }, + ], + libraries: [ + { name: 'zustand', version: '4.5.0', confidence: 100 }, + ], + styling: [ + { name: 'tailwindcss', version: '4.0.0', confidence: 100 }, + ], + testing: [ + { name: 'vitest', version: '1.0.0', confidence: 100 }, + ], + databases: [ + { name: 'supabase', confidence: 100 }, + ], + tools: [ + { name: 'eslint', confidence: 100 }, + ], + runtime: [], + }, + patterns: { + components: 'functional', + stateManagement: 'zustand', + styling: 'tailwind', + testing: 'vitest', + }, + installedSkills: [], + excludedSkills: [], + }; + + // Sample skill index + const sampleIndex: SkillIndex = { + version: 1, + lastUpdated: new Date().toISOString(), + skills: [ + { + name: 'react-best-practices', + description: 'Modern React patterns and hooks best practices', + source: 'vercel-labs/agent-skills', + tags: ['react', 'frontend', 'typescript', 'hooks'], + compatibility: { + frameworks: ['react', 'nextjs'], + languages: ['typescript', 'javascript'], + libraries: [], + }, + popularity: 1500, + quality: 95, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'tailwind-v4-patterns', + description: 'Tailwind CSS v4 patterns and utility classes', + source: 'vercel-labs/agent-skills', + tags: ['tailwind', 'css', 'styling', 'frontend'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript'], + libraries: ['tailwindcss'], + }, + popularity: 800, + quality: 90, + lastUpdated: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString(), // 10 days ago + verified: true, + }, + { + name: 'python-fastapi', + description: 'FastAPI best practices for Python APIs', + source: 'python-skills/fastapi', + tags: ['python', 'fastapi', 'backend', 'api'], + compatibility: { + frameworks: ['fastapi'], + languages: ['python'], + libraries: [], + }, + popularity: 500, + quality: 85, + lastUpdated: new Date().toISOString(), + verified: false, + }, + { + name: 'supabase-best-practices', + description: 'Supabase integration patterns', + source: 'supabase/skills', + tags: ['supabase', 'database', 'auth', 'backend'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript'], + libraries: ['@supabase/supabase-js'], + }, + popularity: 600, + quality: 88, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'vitest-testing', + description: 'Testing patterns with Vitest', + source: 'testing-skills/vitest', + tags: ['vitest', 'testing', 'typescript'], + compatibility: { + frameworks: [], + languages: ['typescript'], + libraries: ['vitest'], + }, + popularity: 400, + quality: 82, + lastUpdated: new Date().toISOString(), + verified: false, + }, + { + name: 'old-react-patterns', + description: 'React patterns (class components)', + source: 'legacy/react-skills', + tags: ['react', 'class-components'], + compatibility: { + frameworks: ['react'], + languages: ['javascript'], + libraries: [], + minVersion: { react: '16.0.0' }, + }, + popularity: 100, + quality: 50, + lastUpdated: new Date(Date.now() - 400 * 24 * 60 * 60 * 1000).toISOString(), // 400 days ago + verified: false, + }, + ], + sources: [ + { + name: 'vercel-labs', + url: 'https://github.com/vercel-labs/agent-skills', + lastFetched: new Date().toISOString(), + skillCount: 2, + }, + ], + }; + + beforeEach(() => { + engine = new RecommendationEngine(); + engine.loadIndex(sampleIndex); + }); + + describe('scoreSkill', () => { + it('should score skill with matching framework highly', () => { + const reactSkill = sampleIndex.skills[0]; // react-best-practices + const scored = engine.scoreSkill(sampleProfile, reactSkill); + + expect(scored.score).toBeGreaterThan(60); + expect(scored.reasons.some((r) => r.category === 'framework')).toBe(true); + expect(scored.reasons.find((r) => r.category === 'framework')?.weight).toBeGreaterThan(0); + }); + + it('should score skill with matching language', () => { + const reactSkill = sampleIndex.skills[0]; + const scored = engine.scoreSkill(sampleProfile, reactSkill); + + expect(scored.reasons.some((r) => r.category === 'language')).toBe(true); + expect(scored.reasons.find((r) => r.category === 'language')?.matched).toContain('typescript'); + }); + + it('should score skill with matching library', () => { + const tailwindSkill = sampleIndex.skills[1]; + const scored = engine.scoreSkill(sampleProfile, tailwindSkill); + + expect(scored.score).toBeGreaterThan(30); + }); + + it('should give low score to non-matching skill', () => { + const pythonSkill = sampleIndex.skills[2]; // python-fastapi + const scored = engine.scoreSkill(sampleProfile, pythonSkill); + + expect(scored.score).toBeLessThan(30); + expect(scored.reasons.find((r) => r.category === 'framework')?.weight).toBe(0); + }); + + it('should include popularity bonus for popular skills', () => { + const popularSkill = sampleIndex.skills[0]; // 1500 popularity + const scored = engine.scoreSkill(sampleProfile, popularSkill); + + expect(scored.reasons.some((r) => r.category === 'popularity')).toBe(true); + expect(scored.reasons.find((r) => r.category === 'popularity')?.weight).toBeGreaterThan(0); + }); + + it('should include quality score', () => { + const highQualitySkill = sampleIndex.skills[0]; // 95 quality + const scored = engine.scoreSkill(sampleProfile, highQualitySkill); + + expect(scored.reasons.some((r) => r.category === 'quality')).toBe(true); + }); + + it('should penalize outdated skills in freshness score', () => { + const outdatedSkill = sampleIndex.skills[5]; // old-react-patterns, 400 days old + const scored = engine.scoreSkill(sampleProfile, outdatedSkill); + + const freshnessReason = scored.reasons.find((r) => r.category === 'freshness'); + expect(freshnessReason?.weight).toBe(0); + }); + + it('should add warning for already installed skills', () => { + const profileWithInstalled: ProjectProfile = { + ...sampleProfile, + installedSkills: ['react-best-practices'], + }; + + const scored = engine.scoreSkill(profileWithInstalled, sampleIndex.skills[0]); + expect(scored.warnings).toContain('Already installed'); + }); + }); + + describe('recommend', () => { + it('should return recommendations sorted by score', () => { + const result = engine.recommend(sampleProfile); + + expect(result.recommendations.length).toBeGreaterThan(0); + expect(result.recommendations.length).toBeLessThanOrEqual(10); + + // Check descending order + for (let i = 1; i < result.recommendations.length; i++) { + expect(result.recommendations[i - 1].score).toBeGreaterThanOrEqual( + result.recommendations[i].score + ); + } + }); + + it('should filter by minimum score', () => { + const result = engine.recommend(sampleProfile, { minScore: 50 }); + + for (const rec of result.recommendations) { + expect(rec.score).toBeGreaterThanOrEqual(50); + } + }); + + it('should respect limit option', () => { + const result = engine.recommend(sampleProfile, { limit: 3 }); + + expect(result.recommendations.length).toBeLessThanOrEqual(3); + }); + + it('should exclude installed skills by default', () => { + const profileWithInstalled: ProjectProfile = { + ...sampleProfile, + installedSkills: ['react-best-practices'], + }; + + const result = engine.recommend(profileWithInstalled); + + expect(result.recommendations.some((r) => r.skill.name === 'react-best-practices')).toBe( + false + ); + }); + + it('should include installed skills when excludeInstalled is false', () => { + const profileWithInstalled: ProjectProfile = { + ...sampleProfile, + installedSkills: ['react-best-practices'], + }; + + const result = engine.recommend(profileWithInstalled, { excludeInstalled: false }); + + // May or may not include it depending on score, but it's not excluded + expect(result.totalSkillsScanned).toBe(sampleIndex.skills.length); + }); + + it('should exclude explicitly excluded skills', () => { + const profileWithExcluded: ProjectProfile = { + ...sampleProfile, + excludedSkills: ['react-best-practices'], + }; + + const result = engine.recommend(profileWithExcluded); + + expect(result.recommendations.some((r) => r.skill.name === 'react-best-practices')).toBe( + false + ); + }); + + it('should filter by categories', () => { + const result = engine.recommend(sampleProfile, { categories: ['testing'] }); + + // Should only include skills with testing tag + for (const rec of result.recommendations) { + expect(rec.skill.tags?.includes('testing')).toBe(true); + } + }); + + it('should include profile in result', () => { + const result = engine.recommend(sampleProfile); + + expect(result.profile).toBe(sampleProfile); + }); + + it('should include totalSkillsScanned in result', () => { + const result = engine.recommend(sampleProfile); + + expect(result.totalSkillsScanned).toBe(sampleIndex.skills.length); + }); + + it('should return empty results when no index loaded', () => { + const emptyEngine = new RecommendationEngine(); + const result = emptyEngine.recommend(sampleProfile); + + expect(result.recommendations).toEqual([]); + expect(result.totalSkillsScanned).toBe(0); + }); + + it('should strip reasons when includeReasons is false', () => { + const result = engine.recommend(sampleProfile, { includeReasons: false }); + + for (const rec of result.recommendations) { + expect(rec.reasons).toEqual([]); + } + }); + }); + + describe('search', () => { + it('should find skills by name', () => { + const results = engine.search({ query: 'react' }); + + expect(results.length).toBeGreaterThan(0); + expect(results[0].skill.name).toContain('react'); + }); + + it('should find skills by description', () => { + const results = engine.search({ query: 'hooks' }); + + expect(results.length).toBeGreaterThan(0); + expect(results.some((r) => r.skill.description?.includes('hooks'))).toBe(true); + }); + + it('should find skills by tags', () => { + const results = engine.search({ query: 'frontend' }); + + expect(results.length).toBeGreaterThan(0); + expect(results.some((r) => r.skill.tags?.includes('frontend'))).toBe(true); + }); + + it('should return matched terms', () => { + const results = engine.search({ query: 'react typescript' }); + + expect(results[0].matchedTerms.length).toBeGreaterThan(0); + }); + + it('should respect limit option', () => { + const results = engine.search({ query: 'react', limit: 2 }); + + expect(results.length).toBeLessThanOrEqual(2); + }); + + it('should filter by tags', () => { + const results = engine.search({ + query: 'patterns', + filters: { tags: ['tailwind'] }, + }); + + for (const r of results) { + expect(r.skill.tags?.includes('tailwind')).toBe(true); + } + }); + + it('should filter by verified status', () => { + const results = engine.search({ + query: 'react', + filters: { verified: true }, + }); + + for (const r of results) { + expect(r.skill.verified).toBe(true); + } + }); + + it('should use semantic matching by default', () => { + // Search for 'frontend' should find related skills with frontend tag + const results = engine.search({ query: 'frontend' }); + + // Skills with 'frontend' tag should be found + expect(results.some((r) => r.skill.tags?.includes('frontend'))).toBe(true); + // React-best-practices has frontend tag + expect(results.some((r) => r.skill.name === 'react-best-practices')).toBe(true); + }); + + it('should return empty results when no index loaded', () => { + const emptyEngine = new RecommendationEngine(); + const results = emptyEngine.search({ query: 'react' }); + + expect(results).toEqual([]); + }); + + it('should include snippet for matching skills', () => { + const results = engine.search({ query: 'react' }); + + const withSnippet = results.find((r) => r.snippet); + expect(withSnippet).toBeDefined(); + }); + }); + + describe('checkFreshness', () => { + it('should return current for up-to-date skills', () => { + const installedSkills: SkillSummary[] = [ + { + name: 'modern-skill', + compatibility: { + frameworks: [], + languages: [], + libraries: [], + minVersion: { react: '18.0.0' }, + }, + }, + ]; + + const results = engine.checkFreshness(sampleProfile, installedSkills); + + expect(results[0].status).toBe('current'); + }); + + it('should return outdated for skills targeting older versions', () => { + const installedSkills: SkillSummary[] = [ + { + name: 'old-skill', + compatibility: { + frameworks: [], + languages: [], + libraries: [], + minVersion: { react: '16.0.0' }, + }, + }, + ]; + + const results = engine.checkFreshness(sampleProfile, installedSkills); + + expect(results[0].status).toBe('outdated'); + }); + + it('should return unknown for skills without version requirements', () => { + const installedSkills: SkillSummary[] = [ + { + name: 'no-version-skill', + }, + ]; + + const results = engine.checkFreshness(sampleProfile, installedSkills); + + expect(results[0].status).toBe('unknown'); + }); + }); + + describe('custom weights', () => { + it('should allow custom scoring weights', () => { + const customWeights: Partial = { + framework: 60, + language: 30, + library: 5, + tag: 5, + popularity: 0, + quality: 0, + freshness: 0, + }; + + const customEngine = new RecommendationEngine(customWeights); + customEngine.loadIndex(sampleIndex); + + const scored = customEngine.scoreSkill(sampleProfile, sampleIndex.skills[0]); + + // Framework should contribute more with higher weight + const frameworkReason = scored.reasons.find((r) => r.category === 'framework'); + expect(frameworkReason?.weight).toBeGreaterThan(0); + }); + }); + + describe('createRecommendationEngine', () => { + it('should create an engine with default weights', () => { + const engine = createRecommendationEngine(); + expect(engine).toBeInstanceOf(RecommendationEngine); + }); + + it('should create an engine with custom weights', () => { + const engine = createRecommendationEngine({ framework: 50 }); + expect(engine).toBeInstanceOf(RecommendationEngine); + }); + }); + + describe('index management', () => { + it('should load and return index', () => { + const engine = new RecommendationEngine(); + expect(engine.getIndex()).toBeNull(); + + engine.loadIndex(sampleIndex); + expect(engine.getIndex()).toBe(sampleIndex); + }); + }); + + describe('edge cases', () => { + it('should handle empty project stack', () => { + const emptyProfile: ProjectProfile = { + name: 'empty-project', + stack: { + languages: [], + frameworks: [], + libraries: [], + styling: [], + testing: [], + databases: [], + tools: [], + runtime: [], + }, + installedSkills: [], + excludedSkills: [], + }; + + const result = engine.recommend(emptyProfile); + expect(result.recommendations).toBeDefined(); + }); + + it('should handle skill with missing optional fields', () => { + const minimalSkill: SkillSummary = { + name: 'minimal-skill', + }; + + const scored = engine.scoreSkill(sampleProfile, minimalSkill); + expect(scored).toBeDefined(); + expect(scored.score).toBeGreaterThanOrEqual(0); + }); + + it('should handle skill with empty tags', () => { + const noTagsSkill: SkillSummary = { + name: 'no-tags-skill', + tags: [], + }; + + const scored = engine.scoreSkill(sampleProfile, noTagsSkill); + expect(scored).toBeDefined(); + }); + + it('should handle profile with no patterns', () => { + const noPatternProfile: ProjectProfile = { + ...sampleProfile, + patterns: undefined, + }; + + const scored = engine.scoreSkill(noPatternProfile, sampleIndex.skills[0]); + expect(scored).toBeDefined(); + }); + + it('should handle search with empty query', () => { + const results = engine.search({ query: '' }); + expect(results).toEqual([]); + }); + + it('should handle search with no matching results', () => { + const results = engine.search({ query: 'xyznonexistent123' }); + expect(results).toEqual([]); + }); + }); +}); + +describe('TAG_TO_TECH and getTechTags', () => { + it('should map common packages to tags', () => { + expect(getTechTags('react')).toContain('react'); + expect(getTechTags('next')).toContain('nextjs'); + expect(getTechTags('tailwindcss')).toContain('tailwind'); + expect(getTechTags('vitest')).toContain('vitest'); + }); + + it('should return empty array for unknown tech', () => { + expect(getTechTags('unknown-package-xyz')).toEqual([]); + }); +}); diff --git a/packages/core/src/recommend/engine.ts b/packages/core/src/recommend/engine.ts new file mode 100644 index 00000000..19cfe5cd --- /dev/null +++ b/packages/core/src/recommend/engine.ts @@ -0,0 +1,667 @@ +import type { ProjectStack } from '../context/types.js'; +import type { + SkillSummary, + ScoredSkill, + MatchReason, + ScoringWeights, + ProjectProfile, + SkillIndex, + RecommendOptions, + RecommendationResult, + SearchOptions, + SearchResult, + FreshnessResult, +} from './types.js'; +import { DEFAULT_SCORING_WEIGHTS, TAG_TO_TECH, getTechTags } from './types.js'; + +/** + * Recommendation engine for matching skills to project profiles + */ +export class RecommendationEngine { + private weights: ScoringWeights; + private index: SkillIndex | null = null; + + constructor(weights?: Partial) { + this.weights = { ...DEFAULT_SCORING_WEIGHTS, ...weights }; + } + + /** + * Load skill index from cache or generate from local skills + */ + loadIndex(index: SkillIndex): void { + this.index = index; + } + + /** + * Get loaded index + */ + getIndex(): SkillIndex | null { + return this.index; + } + + /** + * Score a single skill against a project profile + */ + scoreSkill(profile: ProjectProfile, skill: SkillSummary): ScoredSkill { + const reasons: MatchReason[] = []; + const warnings: string[] = []; + let totalScore = 0; + + // Framework matching (40 points max) + const frameworkMatch = this.matchFrameworks(profile.stack, skill); + reasons.push(frameworkMatch); + totalScore += frameworkMatch.weight; + + // Language matching (20 points max) + const languageMatch = this.matchLanguages(profile.stack, skill); + reasons.push(languageMatch); + totalScore += languageMatch.weight; + + // Library matching (15 points max) + const libraryMatch = this.matchLibraries(profile.stack, skill); + reasons.push(libraryMatch); + totalScore += libraryMatch.weight; + + // Tag relevance (10 points max) + const tagMatch = this.matchTags(profile, skill); + reasons.push(tagMatch); + totalScore += tagMatch.weight; + + // Popularity bonus (5 points max) + const popularityScore = this.scorePopularity(skill); + reasons.push(popularityScore); + totalScore += popularityScore.weight; + + // Quality bonus (5 points max) + const qualityScore = this.scoreQuality(skill); + reasons.push(qualityScore); + totalScore += qualityScore.weight; + + // Freshness bonus (5 points max) + const freshnessScore = this.scoreFreshness(skill); + reasons.push(freshnessScore); + totalScore += freshnessScore.weight; + + // Add warnings for potential issues + if (skill.compatibility?.minVersion) { + for (const [tech, minVer] of Object.entries(skill.compatibility.minVersion)) { + const detected = this.findDetectedVersion(profile.stack, tech); + if (detected && this.isVersionLower(detected, minVer)) { + warnings.push(`Requires ${tech} ${minVer}+, you have ${detected}`); + } + } + } + + // Check if skill is already installed + if (profile.installedSkills.includes(skill.name)) { + warnings.push('Already installed'); + } + + return { + skill, + score: Math.min(100, Math.round(totalScore)), + reasons, + warnings, + }; + } + + /** + * Match frameworks in project stack against skill + */ + private matchFrameworks(stack: ProjectStack, skill: SkillSummary): MatchReason { + const matched: string[] = []; + const skillFrameworks = skill.compatibility?.frameworks || []; + const skillTags = skill.tags || []; + + for (const detection of stack.frameworks) { + const techName = detection.name.toLowerCase(); + + // Direct framework match + if (skillFrameworks.some((f) => f.toLowerCase() === techName)) { + matched.push(detection.name); + continue; + } + + // Tag-based match + const relatedTags = getTechTags(techName); + for (const tag of skillTags) { + if (relatedTags.includes(tag.toLowerCase()) || tag.toLowerCase() === techName) { + matched.push(detection.name); + break; + } + } + + // Check if skill tags match framework-related tags + for (const [tagName, techs] of Object.entries(TAG_TO_TECH)) { + if (techs.includes(techName) && skillTags.includes(tagName)) { + if (!matched.includes(detection.name)) { + matched.push(detection.name); + } + } + } + } + + const ratio = matched.length / Math.max(stack.frameworks.length, 1); + const weight = Math.round(this.weights.framework * ratio); + + return { + category: 'framework', + description: + matched.length > 0 + ? `Matches frameworks: ${matched.join(', ')}` + : 'No framework match', + weight, + matched, + }; + } + + /** + * Match languages in project stack against skill + */ + private matchLanguages(stack: ProjectStack, skill: SkillSummary): MatchReason { + const matched: string[] = []; + const skillLanguages = skill.compatibility?.languages || []; + const skillTags = skill.tags || []; + + for (const detection of stack.languages) { + const langName = detection.name.toLowerCase(); + + // Direct language match + if (skillLanguages.some((l) => l.toLowerCase() === langName)) { + matched.push(detection.name); + continue; + } + + // Tag-based match + if (skillTags.some((t) => t.toLowerCase() === langName)) { + matched.push(detection.name); + } + } + + const ratio = matched.length / Math.max(stack.languages.length, 1); + const weight = Math.round(this.weights.language * ratio); + + return { + category: 'language', + description: + matched.length > 0 ? `Matches languages: ${matched.join(', ')}` : 'No language match', + weight, + matched, + }; + } + + /** + * Match libraries in project stack against skill + */ + private matchLibraries(stack: ProjectStack, skill: SkillSummary): MatchReason { + const matched: string[] = []; + const skillLibraries = skill.compatibility?.libraries || []; + const skillTags = skill.tags || []; + + const allLibraries = [...stack.libraries, ...stack.styling, ...stack.testing, ...stack.databases]; + + for (const detection of allLibraries) { + const libName = detection.name.toLowerCase(); + + // Direct library match + if (skillLibraries.some((l) => l.toLowerCase() === libName)) { + matched.push(detection.name); + continue; + } + + // Tag-based match + const relatedTags = getTechTags(libName); + for (const tag of skillTags) { + if (relatedTags.includes(tag.toLowerCase()) || tag.toLowerCase() === libName) { + matched.push(detection.name); + break; + } + } + } + + const ratio = matched.length / Math.max(allLibraries.length, 1); + const weight = Math.round(this.weights.library * ratio); + + return { + category: 'library', + description: + matched.length > 0 ? `Matches libraries: ${matched.join(', ')}` : 'No library match', + weight, + matched, + }; + } + + /** + * Match tags based on project patterns and type + */ + private matchTags(profile: ProjectProfile, skill: SkillSummary): MatchReason { + const matched: string[] = []; + const skillTags = skill.tags || []; + + // Extract relevant tags from project + const projectTags = this.extractProjectTags(profile); + + for (const tag of skillTags) { + if (projectTags.includes(tag.toLowerCase())) { + matched.push(tag); + } + } + + const ratio = matched.length / Math.max(skillTags.length, 1); + const weight = Math.round(this.weights.tag * ratio); + + return { + category: 'tag', + description: matched.length > 0 ? `Matches tags: ${matched.join(', ')}` : 'No tag match', + weight, + matched, + }; + } + + /** + * Extract relevant tags from project profile + */ + private extractProjectTags(profile: ProjectProfile): string[] { + const tags: string[] = []; + + // Add project type as tag + if (profile.type) { + tags.push(profile.type.toLowerCase()); + } + + // Add patterns as tags + if (profile.patterns) { + if (profile.patterns.components) tags.push(profile.patterns.components); + if (profile.patterns.stateManagement) tags.push(profile.patterns.stateManagement); + if (profile.patterns.apiStyle) tags.push(profile.patterns.apiStyle); + if (profile.patterns.styling) tags.push(profile.patterns.styling); + if (profile.patterns.testing) tags.push(profile.patterns.testing); + } + + // Derive tags from stack + const allDetections = [ + ...profile.stack.frameworks, + ...profile.stack.languages, + ...profile.stack.libraries, + ...profile.stack.styling, + ...profile.stack.testing, + ...profile.stack.databases, + ...profile.stack.tools, + ]; + + for (const detection of allDetections) { + tags.push(detection.name.toLowerCase()); + // Add related tags + const related = getTechTags(detection.name.toLowerCase()); + tags.push(...related); + } + + return [...new Set(tags)]; + } + + /** + * Score based on popularity (downloads/stars) + */ + private scorePopularity(skill: SkillSummary): MatchReason { + // Normalize popularity to 0-5 range + // Assume 1000+ is high popularity + const popularity = skill.popularity ?? 0; + const normalized = Math.min(popularity / 1000, 1); + const weight = Math.round(this.weights.popularity * normalized); + + return { + category: 'popularity', + description: + popularity > 0 ? `${popularity} downloads/stars` : 'No popularity data', + weight, + matched: popularity > 0 ? [popularity.toString()] : [], + }; + } + + /** + * Score based on quality metrics + */ + private scoreQuality(skill: SkillSummary): MatchReason { + const quality = skill.quality ?? 50; // Default to 50 if not specified + const normalized = quality / 100; + const weight = Math.round(this.weights.quality * normalized); + + return { + category: 'quality', + description: `Quality score: ${skill.quality}/100`, + weight, + matched: skill.verified ? ['verified'] : [], + }; + } + + /** + * Score based on freshness (last update) + */ + private scoreFreshness(skill: SkillSummary): MatchReason { + if (!skill.lastUpdated) { + return { + category: 'freshness', + description: 'No update date available', + weight: 0, + matched: [], + }; + } + + const lastUpdate = new Date(skill.lastUpdated); + const now = new Date(); + const daysSinceUpdate = (now.getTime() - lastUpdate.getTime()) / (1000 * 60 * 60 * 24); + + // Full points if updated within 30 days, decreasing linearly to 0 at 365 days + let normalized = Math.max(0, 1 - daysSinceUpdate / 365); + if (daysSinceUpdate <= 30) normalized = 1; + + const weight = Math.round(this.weights.freshness * normalized); + + return { + category: 'freshness', + description: + daysSinceUpdate <= 30 + ? 'Recently updated' + : `Updated ${Math.round(daysSinceUpdate)} days ago`, + weight, + matched: [skill.lastUpdated], + }; + } + + /** + * Find detected version for a technology + */ + private findDetectedVersion(stack: ProjectStack, tech: string): string | null { + const techLower = tech.toLowerCase(); + const allDetections = [ + ...stack.frameworks, + ...stack.languages, + ...stack.libraries, + ...stack.styling, + ...stack.testing, + ...stack.databases, + ...stack.tools, + ...stack.runtime, + ]; + + const found = allDetections.find((d) => d.name.toLowerCase() === techLower); + return found?.version || null; + } + + /** + * Compare semantic versions (basic implementation) + */ + private isVersionLower(current: string, required: string): boolean { + const parseVersion = (v: string): number[] => + v + .replace(/[^0-9.]/g, '') + .split('.') + .map(Number); + + const currentParts = parseVersion(current); + const requiredParts = parseVersion(required); + + for (let i = 0; i < Math.max(currentParts.length, requiredParts.length); i++) { + const c = currentParts[i] || 0; + const r = requiredParts[i] || 0; + if (c < r) return true; + if (c > r) return false; + } + + return false; + } + + /** + * Get top recommendations for a project profile + */ + recommend(profile: ProjectProfile, options: RecommendOptions = {}): RecommendationResult { + const { + limit = 10, + minScore = 30, + categories, + excludeInstalled = true, + includeReasons = true, + } = options; + + if (!this.index) { + return { + recommendations: [], + profile, + totalSkillsScanned: 0, + timestamp: new Date().toISOString(), + }; + } + + let skills = this.index.skills; + + // Filter by categories if specified + if (categories && categories.length > 0) { + skills = skills.filter((s) => s.tags?.some((t) => categories.includes(t))); + } + + // Score all skills + const scored = skills.map((skill) => this.scoreSkill(profile, skill)); + + // Filter by minimum score + let filtered = scored.filter((s) => s.score >= minScore); + + // Exclude installed skills + if (excludeInstalled) { + filtered = filtered.filter((s) => !profile.installedSkills.includes(s.skill.name)); + } + + // Exclude explicitly excluded skills + filtered = filtered.filter((s) => !profile.excludedSkills.includes(s.skill.name)); + + // Sort by score descending + filtered.sort((a, b) => b.score - a.score); + + // Limit results + const recommendations = filtered.slice(0, limit); + + // Optionally strip reasons for minimal output + if (!includeReasons) { + recommendations.forEach((r) => { + r.reasons = []; + }); + } + + return { + recommendations, + profile, + totalSkillsScanned: skills.length, + timestamp: new Date().toISOString(), + }; + } + + /** + * Search skills by query (task-based search) + */ + search(options: SearchOptions): SearchResult[] { + const { query, limit = 10, semantic = true, filters } = options; + + if (!this.index) { + return []; + } + + // Handle empty or whitespace-only queries + const trimmedQuery = query.trim(); + if (!trimmedQuery) { + return []; + } + + const queryTerms = trimmedQuery.toLowerCase().split(/\s+/).filter(t => t.length > 0); + if (queryTerms.length === 0) { + return []; + } + + const results: SearchResult[] = []; + + for (const skill of this.index.skills) { + // Apply filters + if (filters?.tags && filters.tags.length > 0) { + if (!skill.tags?.some((t) => filters.tags!.includes(t))) continue; + } + if (filters?.verified && !skill.verified) continue; + + // Calculate relevance + const { relevance, matchedTerms, snippet } = this.calculateRelevance( + skill, + queryTerms, + semantic + ); + + if (relevance > 0 && (!filters?.minScore || relevance >= filters.minScore)) { + results.push({ skill, relevance, matchedTerms, snippet }); + } + } + + // Sort by relevance + results.sort((a, b) => b.relevance - a.relevance); + + return results.slice(0, limit); + } + + /** + * Calculate search relevance for a skill + */ + private calculateRelevance( + skill: SkillSummary, + queryTerms: string[], + semantic: boolean + ): { relevance: number; matchedTerms: string[]; snippet?: string } { + const matchedTerms: string[] = []; + let relevance = 0; + + // Search in name (high weight) + const nameLower = skill.name.toLowerCase(); + for (const term of queryTerms) { + if (nameLower.includes(term)) { + relevance += 40; + matchedTerms.push(term); + } + } + + // Search in description (medium weight) + const descLower = (skill.description || '').toLowerCase(); + for (const term of queryTerms) { + if (descLower.includes(term) && !matchedTerms.includes(term)) { + relevance += 20; + matchedTerms.push(term); + } + } + + // Search in tags (medium weight) + const tagsLower = (skill.tags || []).map((t) => t.toLowerCase()); + for (const term of queryTerms) { + if (tagsLower.some((t) => t.includes(term)) && !matchedTerms.includes(term)) { + relevance += 25; + matchedTerms.push(term); + } + } + + // Semantic matching: expand terms using TAG_TO_TECH + if (semantic) { + for (const term of queryTerms) { + const relatedTags = getTechTags(term); + for (const relatedTag of relatedTags) { + if ( + tagsLower.includes(relatedTag) || + nameLower.includes(relatedTag) || + descLower.includes(relatedTag) + ) { + if (!matchedTerms.includes(term)) { + relevance += 15; + matchedTerms.push(term); + } + } + } + + // Also check if term is a tag that maps to skill tags + const tagTechs = TAG_TO_TECH[term] || []; + for (const tech of tagTechs) { + if (skill.compatibility?.libraries?.includes(tech)) { + if (!matchedTerms.includes(term)) { + relevance += 15; + matchedTerms.push(term); + } + } + } + } + } + + // Generate snippet if description matches + let snippet: string | undefined; + if (skill.description && matchedTerms.length > 0) { + snippet = skill.description.slice(0, 150); + if (skill.description.length > 150) snippet += '...'; + } + + // Normalize to 0-100 + relevance = Math.min(100, relevance); + + return { relevance, matchedTerms, snippet }; + } + + /** + * Check freshness of installed skills against project dependencies + * + * A skill is considered: + * - 'current': skill's minVersion is <= project version (compatible and up to date) + * - 'outdated': skill targets a significantly older major version + * - 'unknown': no version requirements specified + */ + checkFreshness( + profile: ProjectProfile, + installedSkills: SkillSummary[] + ): FreshnessResult[] { + const results: FreshnessResult[] = []; + + for (const skill of installedSkills) { + if (!skill.compatibility?.minVersion) { + results.push({ + skill: skill.name, + status: 'unknown', + details: { message: 'No version requirements specified' }, + }); + continue; + } + + let status: 'current' | 'outdated' = 'current'; + const messages: string[] = []; + + for (const [tech, minVer] of Object.entries(skill.compatibility.minVersion)) { + const detected = this.findDetectedVersion(profile.stack, tech); + if (detected) { + const majorSkill = parseInt(minVer.split('.')[0]) || 0; + const majorProject = parseInt(detected.split('.')[0]) || 0; + + // Skill is outdated if it targets a version that is 2+ major versions behind + // e.g., skill targets React 16 but project uses React 19 + if (majorProject - majorSkill >= 2) { + status = 'outdated'; + messages.push(`Skill targets ${tech} ${minVer}, you have ${detected}`); + } + } + } + + results.push({ + skill: skill.name, + status, + details: + messages.length > 0 ? { message: messages.join('; ') } : { message: 'Up to date' }, + }); + } + + return results; + } +} + +/** + * Create a recommendation engine with default settings + */ +export function createRecommendationEngine( + weights?: Partial +): RecommendationEngine { + return new RecommendationEngine(weights); +} diff --git a/packages/core/src/recommend/index.ts b/packages/core/src/recommend/index.ts new file mode 100644 index 00000000..18a0917c --- /dev/null +++ b/packages/core/src/recommend/index.ts @@ -0,0 +1,15 @@ +/** + * Recommendation Engine Module + * + * Provides smart skill recommendations based on project analysis. + * + * Features: + * - Project-aware skill matching + * - Framework/language/library detection + * - Task-based search + * - Freshness checking + */ + +export * from './types.js'; +export * from './engine.js'; +export { createRecommendationEngine, RecommendationEngine } from './engine.js'; diff --git a/packages/core/src/recommend/types.ts b/packages/core/src/recommend/types.ts new file mode 100644 index 00000000..3ee3710d --- /dev/null +++ b/packages/core/src/recommend/types.ts @@ -0,0 +1,286 @@ +import { z } from 'zod'; +import type { ProjectStack } from '../context/types.js'; + +/** + * Skill summary for recommendation matching + */ +export const SkillSummary = z.object({ + name: z.string(), + description: z.string().optional(), + source: z.string().optional(), // Repository source + tags: z.array(z.string()).default([]), + compatibility: z + .object({ + frameworks: z.array(z.string()).default([]), + languages: z.array(z.string()).default([]), + libraries: z.array(z.string()).default([]), + minVersion: z.record(z.string()).optional(), // { "react": "18.0.0" } + }) + .optional(), + popularity: z.number().default(0), // Downloads/stars + quality: z.number().min(0).max(100).default(50), // Quality score + lastUpdated: z.string().datetime().optional(), + verified: z.boolean().default(false), +}); +export type SkillSummary = z.infer; + +/** + * Scored skill with match explanation + */ +export interface ScoredSkill { + skill: SkillSummary; + score: number; // 0-100 + reasons: MatchReason[]; + warnings: string[]; +} + +/** + * Match reason with category and weight + */ +export interface MatchReason { + category: MatchCategory; + description: string; + weight: number; // Points contributed + matched: string[]; // What matched +} + +/** + * Categories of matching + */ +export type MatchCategory = + | 'framework' + | 'language' + | 'library' + | 'tag' + | 'pattern' + | 'popularity' + | 'quality' + | 'freshness'; + +/** + * Weight configuration for scoring + */ +export interface ScoringWeights { + framework: number; // Default: 40 + language: number; // Default: 20 + library: number; // Default: 15 + tag: number; // Default: 10 + popularity: number; // Default: 5 + quality: number; // Default: 5 + freshness: number; // Default: 5 +} + +export const DEFAULT_SCORING_WEIGHTS: ScoringWeights = { + framework: 40, + language: 20, + library: 15, + tag: 10, + popularity: 5, + quality: 5, + freshness: 5, +}; + +/** + * Project profile for matching (derived from ProjectContext) + */ +export interface ProjectProfile { + name: string; + type?: string; + stack: ProjectStack; + patterns?: { + components?: string; + stateManagement?: string; + apiStyle?: string; + styling?: string; + testing?: string; + }; + installedSkills: string[]; + excludedSkills: string[]; +} + +/** + * Skill index for efficient lookup + */ +export interface SkillIndex { + version: number; + lastUpdated: string; + skills: SkillSummary[]; + sources: IndexSource[]; +} + +/** + * Source repository in the index + */ +export interface IndexSource { + name: string; + url: string; + lastFetched: string; + skillCount: number; +} + +/** + * Recommendation options + */ +export interface RecommendOptions { + limit?: number; // Max recommendations (default: 10) + minScore?: number; // Minimum score threshold (default: 30) + categories?: string[]; // Filter by categories + excludeInstalled?: boolean; // Skip already installed (default: true) + weights?: Partial; + includeReasons?: boolean; // Include detailed reasons (default: true) +} + +/** + * Recommendation result + */ +export interface RecommendationResult { + recommendations: ScoredSkill[]; + profile: ProjectProfile; + totalSkillsScanned: number; + timestamp: string; +} + +/** + * Search options for task-based search + */ +export interface SearchOptions { + query: string; + limit?: number; + semantic?: boolean; // Use semantic matching (default: true) + filters?: { + tags?: string[]; + minScore?: number; + verified?: boolean; + }; +} + +/** + * Search result + */ +export interface SearchResult { + skill: SkillSummary; + relevance: number; // 0-100 + matchedTerms: string[]; + snippet?: string; // Relevant excerpt +} + +/** + * Freshness check result + */ +export interface FreshnessResult { + skill: string; + status: 'current' | 'outdated' | 'unknown'; + details?: { + skillVersion?: string; + projectVersion?: string; + message: string; + }; +} + +/** + * Tag to technology mapping for smart inference + */ +export const TAG_TO_TECH: Record = { + // Frontend frameworks + react: ['react', 'react-dom', '@types/react'], + vue: ['vue', '@vue/core'], + angular: ['@angular/core'], + svelte: ['svelte'], + solid: ['solid-js'], + qwik: ['@builder.io/qwik'], + + // Meta-frameworks + nextjs: ['next'], + nuxt: ['nuxt'], + remix: ['@remix-run/react'], + astro: ['astro'], + gatsby: ['gatsby'], + sveltekit: ['@sveltejs/kit'], + + // Backend + express: ['express'], + fastify: ['fastify'], + koa: ['koa'], + hono: ['hono'], + nestjs: ['@nestjs/core'], + fastapi: ['fastapi'], + django: ['django'], + flask: ['flask'], + + // Languages + typescript: ['typescript', '@types/node'], + javascript: [], // Inferred from lack of typescript + python: [], + rust: [], + go: [], + + // Styling + tailwind: ['tailwindcss'], + 'styled-components': ['styled-components'], + emotion: ['@emotion/react'], + 'css-modules': [], + sass: ['sass', 'node-sass'], + + // State management + redux: ['@reduxjs/toolkit', 'redux'], + zustand: ['zustand'], + mobx: ['mobx'], + jotai: ['jotai'], + recoil: ['recoil'], + + // Testing + jest: ['jest'], + vitest: ['vitest'], + playwright: ['@playwright/test'], + cypress: ['cypress'], + testing: ['@testing-library/react'], + + // Databases + postgres: ['pg', '@prisma/client'], + mongodb: ['mongoose', 'mongodb'], + supabase: ['@supabase/supabase-js'], + firebase: ['firebase'], + prisma: ['@prisma/client'], + drizzle: ['drizzle-orm'], + + // Tools + eslint: ['eslint'], + prettier: ['prettier'], + biome: ['@biomejs/biome'], + turborepo: ['turbo'], + monorepo: ['lerna', 'nx'], + + // API + graphql: ['graphql', '@apollo/client'], + trpc: ['@trpc/server'], + rest: [], + + // Auth + auth: ['next-auth', '@auth/core', 'passport'], + 'better-auth': ['better-auth'], + + // Deployment + vercel: ['vercel'], + docker: [], + kubernetes: [], + + // Other + ai: ['openai', '@anthropic-ai/sdk', 'ai'], + shadcn: [], + security: [], + performance: [], + accessibility: [], +}; + +/** + * Reverse mapping: tech to tags + */ +export function getTechTags(techName: string): string[] { + const tags: string[] = []; + for (const [tag, techs] of Object.entries(TAG_TO_TECH)) { + if (techs.includes(techName)) { + tags.push(tag); + } + } + return tags; +} diff --git a/packages/core/src/skills.ts b/packages/core/src/skills.ts new file mode 100644 index 00000000..a3f556ea --- /dev/null +++ b/packages/core/src/skills.ts @@ -0,0 +1,333 @@ +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { join, basename } from 'node:path'; +import { parse as parseYaml } from 'yaml'; +import { SkillFrontmatter, SkillMetadata, type Skill, type SkillLocation } from './types.js'; + +export const SKILL_DISCOVERY_PATHS = [ + 'skills', + 'skills/.curated', + 'skills/.experimental', + 'skills/.system', + '.agents/skills', + '.agent/skills', + '.claude/skills', + '.codex/skills', + '.cursor/skills', + '.factory/skills', + '.gemini/skills', + '.github/skills', + '.goose/skills', + '.kilocode/skills', + '.kiro/skills', + '.opencode/skills', + '.roo/skills', + '.trae/skills', + '.windsurf/skills', + '.clawdbot/skills', + '.antigravity/skills', + '.copilot/skills', +]; + +function discoverSkillsInDir(dir: string): Skill[] { + const skills: Skill[] = []; + + if (!existsSync(dir)) { + return skills; + } + + const entries = readdirSync(dir, { withFileTypes: true }); + + for (const entry of entries) { + if (!entry.isDirectory()) continue; + + const skillPath = join(dir, entry.name); + const skillMdPath = join(skillPath, 'SKILL.md'); + + if (existsSync(skillMdPath)) { + const skill = parseSkill(skillPath); + if (skill) { + skills.push(skill); + } + } + } + + return skills; +} + +/** + * Recursively search for skills in all subdirectories + */ +function discoverSkillsRecursive( + dir: string, + seen: Set, + maxDepth: number = 5, + currentDepth: number = 0 +): Skill[] { + const skills: Skill[] = []; + + if (currentDepth >= maxDepth || !existsSync(dir)) { + return skills; + } + + try { + const entries = readdirSync(dir, { withFileTypes: true }); + + for (const entry of entries) { + if (entry.name === 'node_modules' || entry.name === '.git') { + continue; + } + + if (!entry.isDirectory()) continue; + + const entryPath = join(dir, entry.name); + const skillMdPath = join(entryPath, 'SKILL.md'); + + if (existsSync(skillMdPath)) { + const skill = parseSkill(entryPath); + if (skill && !seen.has(skill.name)) { + seen.add(skill.name); + skills.push(skill); + } + } else { + const subSkills = discoverSkillsRecursive(entryPath, seen, maxDepth, currentDepth + 1); + skills.push(...subSkills); + } + } + } catch {} + + return skills; +} + +export function discoverSkills(rootDir: string): Skill[] { + const skills: Skill[] = []; + const seen = new Set(); + + const rootSkillMd = join(rootDir, 'SKILL.md'); + if (existsSync(rootSkillMd)) { + const skill = parseSkill(rootDir); + if (skill && !seen.has(skill.name)) { + seen.add(skill.name); + skills.push(skill); + } + } + + // Search all standard paths + for (const searchPath of SKILL_DISCOVERY_PATHS) { + const fullPath = join(rootDir, searchPath); + if (existsSync(fullPath)) { + for (const skill of discoverSkillsInDir(fullPath)) { + if (!seen.has(skill.name)) { + seen.add(skill.name); + skills.push(skill); + } + } + } + } + + // Try direct discovery in root (for flat structures) + for (const skill of discoverSkillsInDir(rootDir)) { + if (!seen.has(skill.name)) { + seen.add(skill.name); + skills.push(skill); + } + } + + // Fallback: recursive search if nothing found + if (skills.length === 0) { + skills.push(...discoverSkillsRecursive(rootDir, seen)); + } + + return skills; +} + +export function parseSkill(skillPath: string, location: SkillLocation = 'project'): Skill | null { + const skillMdPath = join(skillPath, 'SKILL.md'); + + if (!existsSync(skillMdPath)) { + return null; + } + + try { + const content = readFileSync(skillMdPath, 'utf-8'); + const frontmatter = extractFrontmatter(content); + + if (!frontmatter) { + const name = basename(skillPath); + return { + name, + description: 'No description available', + path: skillPath, + location, + enabled: true, + }; + } + + const parsed = SkillFrontmatter.safeParse(frontmatter); + + if (!parsed.success) { + return { + name: (frontmatter.name as string) || basename(skillPath), + description: (frontmatter.description as string) || 'No description available', + path: skillPath, + location, + enabled: true, + }; + } + + const metadata = loadMetadata(skillPath); + + return { + name: parsed.data.name, + description: parsed.data.description, + path: skillPath, + location, + metadata: metadata ?? undefined, + enabled: metadata?.enabled ?? true, + }; + } catch { + return null; + } +} + +export function extractFrontmatter(content: string): Record | null { + const match = content.match(/^---\s*\n([\s\S]*?)\n---/); + + if (!match) { + return null; + } + + try { + return parseYaml(match[1]) as Record; + } catch { + return null; + } +} + +export function extractField(content: string, field: string): string | null { + const frontmatter = extractFrontmatter(content); + if (!frontmatter || !(field in frontmatter)) { + return null; + } + + const value = frontmatter[field]; + return typeof value === 'string' ? value : null; +} + +export function loadMetadata(skillPath: string): SkillMetadata | null { + const metadataPath = join(skillPath, '.skillkit.json'); + + if (!existsSync(metadataPath)) { + return null; + } + + try { + const content = readFileSync(metadataPath, 'utf-8'); + const data = JSON.parse(content); + const parsed = SkillMetadata.safeParse(data); + + return parsed.success ? parsed.data : null; + } catch { + return null; + } +} + +export function readSkillContent(skillPath: string): string | null { + const skillMdPath = join(skillPath, 'SKILL.md'); + + if (!existsSync(skillMdPath)) { + return null; + } + + try { + return readFileSync(skillMdPath, 'utf-8'); + } catch { + return null; + } +} + +export function findSkill(name: string, searchDirs: string[]): Skill | null { + for (const dir of searchDirs) { + if (!existsSync(dir)) continue; + + const skillPath = join(dir, name); + if (existsSync(skillPath)) { + const location: SkillLocation = dir.includes(process.cwd()) ? 'project' : 'global'; + return parseSkill(skillPath, location); + } + } + + return null; +} + +export function findAllSkills(searchDirs: string[]): Skill[] { + const skills: Skill[] = []; + const seen = new Set(); + + for (const dir of searchDirs) { + if (!existsSync(dir)) continue; + + const location: SkillLocation = dir.includes(process.cwd()) ? 'project' : 'global'; + const discovered = discoverSkills(dir); + + for (const skill of discovered) { + if (!seen.has(skill.name)) { + seen.add(skill.name); + skills.push({ ...skill, location }); + } + } + } + + return skills; +} + +export function validateSkill(skillPath: string): { valid: boolean; errors: string[]; warnings?: string[] } { + const errors: string[] = []; + const warnings: string[] = []; + const dirName = basename(skillPath); + + const skillMdPath = join(skillPath, 'SKILL.md'); + if (!existsSync(skillMdPath)) { + errors.push('Missing SKILL.md file'); + return { valid: false, errors }; + } + + const content = readFileSync(skillMdPath, 'utf-8'); + const frontmatter = extractFrontmatter(content); + + if (!frontmatter) { + errors.push('Missing YAML frontmatter in SKILL.md'); + return { valid: false, errors }; + } + + const parsed = SkillFrontmatter.safeParse(frontmatter); + if (!parsed.success) { + for (const issue of parsed.error.issues) { + errors.push(`${issue.path.join('.') || 'frontmatter'}: ${issue.message}`); + } + } + + if (parsed.success) { + const data = parsed.data; + + if (data.name !== dirName) { + warnings.push(`name "${data.name}" does not match directory name "${dirName}"`); + } + + if (data.description && data.description.length < 50) { + warnings.push('description is short; consider describing what the skill does AND when to use it'); + } + } + + const bodyContent = content.replace(/^---[\s\S]*?---\s*/, ''); + const lineCount = bodyContent.split('\n').length; + if (lineCount > 500) { + warnings.push(`SKILL.md has ${lineCount} lines; consider moving detailed content to references/`); + } + + return { valid: errors.length === 0, errors, warnings }; +} + +export function isPathInside(child: string, parent: string): boolean { + const relative = child.replace(parent, ''); + return !relative.startsWith('..') && !relative.includes('/..'); +} diff --git a/packages/core/src/translator/__tests__/copilot.test.ts b/packages/core/src/translator/__tests__/copilot.test.ts new file mode 100644 index 00000000..feec47a6 --- /dev/null +++ b/packages/core/src/translator/__tests__/copilot.test.ts @@ -0,0 +1,290 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { CopilotTranslator } from '../formats/copilot.js'; +import type { CanonicalSkill } from '../types.js'; + +describe('CopilotTranslator', () => { + let translator: CopilotTranslator; + + beforeEach(() => { + translator = new CopilotTranslator(); + }); + + describe('format detection', () => { + it('should detect copilot-instructions.md file', () => { + const content = `# Coding Instructions +Follow these guidelines`; + + expect(translator.detect(content, 'copilot-instructions.md')).toBe(true); + }); + + it('should detect .github/copilot-instructions.md path', () => { + const content = `# GitHub Copilot Instructions +Guidelines here`; + + expect(translator.detect(content, '.github/copilot-instructions.md')).toBe(true); + }); + + it('should detect copilot format by github copilot mention', () => { + const content = ` +# Instructions +Content`; + + expect(translator.detect(content)).toBe(true); + }); + + it('should not detect regular markdown', () => { + const content = `# README +Not copilot instructions`; + + expect(translator.detect(content, 'README.md')).toBe(false); + }); + }); + + describe('parsing', () => { + it('should parse copilot instructions file with metadata', () => { + const content = ` + + +# Project Guidelines + +## Code Style +- Use TypeScript +- Follow ESLint rules + +## Architecture +- Use clean architecture principles`; + + const skill = translator.parse(content, 'copilot-instructions.md'); + + expect(skill).not.toBeNull(); + expect(skill!.name).toBe('project-guidelines'); + expect(skill!.content).toContain('# Project Guidelines'); + expect(skill!.content).toContain('Use TypeScript'); + }); + + it('should parse plain copilot instructions', () => { + const content = `# Coding Standards + +Always write clean code. +Add tests for all features.`; + + const skill = translator.parse(content, 'copilot-instructions.md'); + + expect(skill).not.toBeNull(); + // Name is inferred from heading + expect(skill!.name).toBe('coding-standards'); + expect(skill!.content).toContain('Coding Standards'); + }); + + it('should handle instructions with multiple sections', () => { + const content = `# Project Instructions + +## General +Be consistent. + +## Testing +Write unit tests. + +## Documentation +Document all APIs.`; + + const skill = translator.parse(content, 'copilot-instructions.md'); + + expect(skill).not.toBeNull(); + expect(skill!.content).toContain('## General'); + expect(skill!.content).toContain('## Testing'); + expect(skill!.content).toContain('## Documentation'); + }); + + it('should extract description from metadata', () => { + const content = ` + +Content`; + + const skill = translator.parse(content, 'copilot-instructions.md'); + + expect(skill).not.toBeNull(); + expect(skill!.description).toBe('My description here'); + }); + }); + + describe('generation', () => { + it('should generate GitHub Copilot format', () => { + const skill: CanonicalSkill = { + name: 'my-instructions', + description: 'Project coding guidelines', + version: '1.0.0', + content: '# Guidelines\n\nFollow these rules.', + }; + + const result = translator.generate(skill, 'github-copilot'); + + expect(result.success).toBe(true); + expect(result.content).toContain('# Guidelines'); + expect(result.filename).toBe('copilot-instructions.md'); + }); + + it('should preserve markdown formatting', () => { + const skill: CanonicalSkill = { + name: 'formatted', + content: `# Main Title + +## Section 1 + +- Item 1 +- Item 2 + +\`\`\`typescript +const x = 1; +\`\`\` + +> A quote + +**Bold** and *italic* +`, + }; + + const result = translator.generate(skill, 'github-copilot'); + + expect(result.success).toBe(true); + expect(result.content).toContain('## Section 1'); + expect(result.content).toContain('- Item 1'); + expect(result.content).toContain('```typescript'); + expect(result.content).toContain('> A quote'); + expect(result.content).toContain('**Bold**'); + }); + }); + + describe('content handling', () => { + it('should handle code blocks with various languages', () => { + const skill: CanonicalSkill = { + name: 'multi-lang', + content: `# Multi-language Examples + +\`\`\`python +def hello(): + print("Hello") +\`\`\` + +\`\`\`javascript +function hello() { + console.log("Hello"); +} +\`\`\` + +\`\`\`rust +fn hello() { + println!("Hello"); +} +\`\`\` +`, + }; + + const result = translator.generate(skill, 'github-copilot'); + + expect(result.success).toBe(true); + expect(result.content).toContain('```python'); + expect(result.content).toContain('```javascript'); + expect(result.content).toContain('```rust'); + }); + }); + + describe('round-trip', () => { + it('should preserve content through parse and generate cycle', () => { + const original = ` + + + +# Round Trip Content + +This content should be preserved. + +## Section +With subsections. +`; + + const parsed = translator.parse(original, 'copilot-instructions.md'); + expect(parsed).not.toBeNull(); + + // Use addMetadata to preserve metadata in generated output + const generated = translator.generate(parsed!, 'github-copilot', { addMetadata: true }); + expect(generated.success).toBe(true); + + const reparsed = translator.parse(generated.content, 'copilot-instructions.md'); + expect(reparsed).not.toBeNull(); + // Metadata is preserved when addMetadata is true + expect(reparsed!.name).toBe('round-trip-test'); + expect(reparsed!.content).toContain('This content should be preserved.'); + }); + }); + + describe('edge cases', () => { + it('should handle content with HTML elements', () => { + const skill: CanonicalSkill = { + name: 'html', + content: `# Title + +
+Click to expand + +Hidden content here. + +
+ + + +
Cell
+`, + }; + + const result = translator.generate(skill, 'github-copilot'); + + expect(result.success).toBe(true); + expect(result.content).toContain('
'); + expect(result.content).toContain(''); + }); + + it('should handle empty content', () => { + const skill: CanonicalSkill = { + name: 'empty', + content: '', + }; + + const result = translator.generate(skill, 'github-copilot'); + + expect(result.success).toBe(true); + }); + + it('should handle very long content', () => { + const longContent = '# Title\n\n' + 'This is a long line. '.repeat(500); + const skill: CanonicalSkill = { + name: 'long', + content: longContent, + }; + + const result = translator.generate(skill, 'github-copilot'); + + expect(result.success).toBe(true); + expect(result.content.length).toBeGreaterThan(5000); + }); + + it('should handle special characters', () => { + const skill: CanonicalSkill = { + name: 'special', + content: `# Special Characters + +Symbols: © ® ™ € £ ¥ § ¶ +Emojis: 🚀 🎉 ✅ ❌ +Math: ∑ ∏ √ ∞ ≠ ≤ ≥ +`, + }; + + const result = translator.generate(skill, 'github-copilot'); + + expect(result.success).toBe(true); + expect(result.content).toContain('©'); + expect(result.content).toContain('🚀'); + expect(result.content).toContain('∑'); + }); + }); +}); diff --git a/packages/core/src/translator/__tests__/cursor.test.ts b/packages/core/src/translator/__tests__/cursor.test.ts new file mode 100644 index 00000000..e39a24ca --- /dev/null +++ b/packages/core/src/translator/__tests__/cursor.test.ts @@ -0,0 +1,339 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { CursorTranslator } from '../formats/cursor.js'; +import type { CanonicalSkill } from '../types.js'; + +describe('CursorTranslator', () => { + let translator: CursorTranslator; + + beforeEach(() => { + translator = new CursorTranslator(); + }); + + describe('format detection', () => { + it('should detect .mdc files', () => { + const content = `--- +description: A cursor rule +--- +Instructions`; + + expect(translator.detect(content, 'rule.mdc')).toBe(true); + }); + + it('should detect .cursorrules file', () => { + const content = `--- +description: Cursor rules +globs: ["**/*.ts"] +--- +Content`; + + expect(translator.detect(content, '.cursorrules')).toBe(true); + }); + + it('should detect cursor format by globs field', () => { + const content = `--- +description: Has globs +globs: + - "**/*.tsx" +--- +Instructions`; + + expect(translator.detect(content)).toBe(true); + }); + + it('should detect cursor format by alwaysApply field', () => { + const content = `--- +description: Has alwaysApply +alwaysApply: true +--- +Instructions`; + + expect(translator.detect(content)).toBe(true); + }); + + it('should not detect regular markdown', () => { + const content = `# README +Just a regular file`; + + expect(translator.detect(content, 'README.md')).toBe(false); + }); + }); + + describe('parsing', () => { + it('should parse complete Cursor MDC file', () => { + const content = `--- +description: React component best practices +globs: + - "**/*.tsx" + - "**/*.jsx" +alwaysApply: false +--- +# React Guidelines + +Use functional components and hooks.`; + + const skill = translator.parse(content, 'react-rules.mdc'); + + expect(skill).not.toBeNull(); + expect(skill!.name).toBe('react-rules'); + expect(skill!.description).toBe('React component best practices'); + expect(skill!.globs).toEqual(['**/*.tsx', '**/*.jsx']); + // alwaysApply is stored directly on skill, not in metadata + expect(skill!.alwaysApply).toBe(false); + expect(skill!.content).toContain('# React Guidelines'); + }); + + it('should parse MDC with only description', () => { + const content = `--- +description: Simple rule +--- +Follow these guidelines`; + + const skill = translator.parse(content, 'simple.mdc'); + + expect(skill).not.toBeNull(); + expect(skill!.name).toBe('simple'); + expect(skill!.description).toBe('Simple rule'); + }); + + it('should handle alwaysApply: true', () => { + const content = `--- +description: Global rule +alwaysApply: true +--- +This applies everywhere`; + + const skill = translator.parse(content, 'global.mdc'); + + expect(skill).not.toBeNull(); + // alwaysApply is stored directly on skill, not in metadata + expect(skill!.alwaysApply).toBe(true); + }); + + it('should infer name from filename', () => { + const content = `--- +description: Test +--- +Content`; + + const skill = translator.parse(content, 'my-custom-rule.mdc'); + + expect(skill).not.toBeNull(); + expect(skill!.name).toBe('my-custom-rule'); + }); + + it('should handle glob patterns as string', () => { + const content = `--- +description: Single glob +globs: "**/*.ts" +--- +TypeScript rules`; + + const skill = translator.parse(content, 'ts-rules.mdc'); + + expect(skill).not.toBeNull(); + expect(skill!.globs).toContain('**/*.ts'); + }); + }); + + describe('generation', () => { + it('should generate Cursor MDC format', () => { + const skill: CanonicalSkill = { + name: 'typescript-rules', + description: 'TypeScript coding guidelines', + tags: ['typescript', 'backend'], + content: '# TypeScript Guidelines\n\nUse strict mode.', + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.success).toBe(true); + expect(result.content).toContain('description: TypeScript coding guidelines'); + expect(result.content).toContain('# TypeScript Guidelines'); + expect(result.filename).toBe('typescript-rules.mdc'); + }); + + it('should infer globs from tags', () => { + const skill: CanonicalSkill = { + name: 'react-skill', + description: 'React patterns', + tags: ['react', 'typescript', 'frontend'], + content: 'React content', + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.success).toBe(true); + expect(result.content).toContain('globs:'); + expect(result.content).toMatch(/\*\*\/\*\.tsx/); + }); + + it('should preserve explicit globs', () => { + const skill: CanonicalSkill = { + name: 'custom-globs', + description: 'Has custom globs', + globs: ['src/components/**/*.tsx', 'lib/**/*.ts'], + content: 'Content', + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.success).toBe(true); + expect(result.content).toContain('src/components/**/*.tsx'); + expect(result.content).toContain('lib/**/*.ts'); + }); + + it('should preserve explicit alwaysApply value', () => { + const skillWithAlwaysApply: CanonicalSkill = { + name: 'scoped-skill', + description: 'Scoped', + globs: ['**/*.py'], + alwaysApply: false, + content: 'Python', + }; + + const result = translator.generate(skillWithAlwaysApply, 'cursor'); + + expect(result.success).toBe(true); + expect(result.content).toContain('alwaysApply: false'); + }); + + it('should not add alwaysApply if not explicitly set', () => { + const skillWithoutAlwaysApply: CanonicalSkill = { + name: 'scoped-python', + description: 'Python skill', + globs: ['**/*.py'], + content: 'Python', + }; + + const result = translator.generate(skillWithoutAlwaysApply, 'cursor'); + + expect(result.success).toBe(true); + // alwaysApply is only added if explicitly set + expect(result.content).not.toMatch(/^alwaysApply:/m); + }); + + it('should generate .mdc extension', () => { + const skill: CanonicalSkill = { + name: 'my-rule', + content: 'Instructions', + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.filename).toBe('my-rule.mdc'); + }); + }); + + describe('glob inference', () => { + it('should infer TypeScript globs from typescript tag', () => { + const skill: CanonicalSkill = { + name: 'ts-skill', + tags: ['typescript'], + content: 'Content', + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.content).toMatch(/\*\*\/\*\.ts/); + }); + + it('should infer Python globs from python tag', () => { + const skill: CanonicalSkill = { + name: 'py-skill', + tags: ['python'], + content: 'Content', + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.content).toMatch(/\*\*\/\*\.py/); + }); + + it('should infer multiple globs from multiple tags', () => { + const skill: CanonicalSkill = { + name: 'fullstack-skill', + tags: ['react', 'nodejs', 'typescript'], + content: 'Full stack patterns', + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.content).toContain('globs:'); + // Should have React/TS globs + expect(result.content).toMatch(/\*\*\/\*\.tsx|\*\*\/\*\.ts/); + }); + }); + + describe('round-trip', () => { + it('should preserve content through parse and generate cycle', () => { + const original = `--- +description: Round trip test for Cursor +globs: + - "**/*.tsx" +alwaysApply: false +--- +# Original Content + +This should be preserved. + +\`\`\`typescript +const example = true; +\`\`\` +`; + + const parsed = translator.parse(original, 'test.mdc'); + expect(parsed).not.toBeNull(); + + const generated = translator.generate(parsed!, 'cursor'); + expect(generated.success).toBe(true); + + const reparsed = translator.parse(generated.content, 'test.mdc'); + expect(reparsed).not.toBeNull(); + expect(reparsed!.description).toBe(parsed!.description); + expect(reparsed!.content).toContain('This should be preserved.'); + }); + }); + + describe('edge cases', () => { + it('should handle undefined description', () => { + const skill: CanonicalSkill = { + name: 'no-desc', + content: 'Content only', + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.success).toBe(true); + // When description is undefined, YAML may serialize as null or skip the field + // The important thing is that generation succeeds + expect(result.content).toContain('---'); + }); + + it('should handle special characters in content', () => { + const skill: CanonicalSkill = { + name: 'special-chars', + description: 'Test with special: characters', + content: 'Content with `backticks` and $variables and {{templates}}', + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.success).toBe(true); + expect(result.content).toContain('`backticks`'); + expect(result.content).toContain('$variables'); + }); + + it('should handle very long content', () => { + const longContent = 'A'.repeat(10000); + const skill: CanonicalSkill = { + name: 'long-content', + content: longContent, + }; + + const result = translator.generate(skill, 'cursor'); + + expect(result.success).toBe(true); + expect(result.content).toContain(longContent); + }); + }); +}); diff --git a/packages/core/src/translator/__tests__/registry.test.ts b/packages/core/src/translator/__tests__/registry.test.ts new file mode 100644 index 00000000..dbfca6c4 --- /dev/null +++ b/packages/core/src/translator/__tests__/registry.test.ts @@ -0,0 +1,367 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { TranslatorRegistry } from '../registry.js'; +import type { CanonicalSkill } from '../types.js'; + +describe('TranslatorRegistry', () => { + let registry: TranslatorRegistry; + + beforeEach(() => { + registry = new TranslatorRegistry(); + }); + + describe('format detection', () => { + it('should detect SKILL.md format', () => { + const content = `--- +name: test-skill +description: Test +--- +Content`; + + const format = registry.detectFormat(content, 'SKILL.md'); + + expect(format).toBe('skill-md'); + }); + + it('should detect Cursor MDC format by globs field', () => { + // Globs field is cursor-specific, so it takes priority + const content = `--- +globs: ["**/*.ts"] +--- +Content`; + + const format = registry.detectFormat(content); + + expect(format).toBe('cursor-mdc'); + }); + + it('should detect skill-md for content with description', () => { + // Content with description is detected as skill-md since + // skillMdTranslator is checked first + const content = `--- +description: Test +globs: ["**/*.ts"] +--- +Content`; + + const format = registry.detectFormat(content, 'rule.mdc'); + + // skill-md is detected first because description is a common field + expect(format).toBe('skill-md'); + }); + + it('should detect Copilot format by filename', () => { + const content = `# Instructions`; + + const format = registry.detectFormat(content, 'copilot-instructions.md'); + + expect(format).toBe('markdown-rules'); + }); + + it('should return null for unknown format', () => { + const content = `Just some random text +without any skill format markers`; + + const format = registry.detectFormat(content, 'random.txt'); + + expect(format).toBeNull(); + }); + + it('should detect skill-md for content with name field', () => { + // Content with name field is detected as skill-md + const content = `--- +name: test +--- +Content`; + + const format = registry.detectFormat(content, 'test.mdc'); + + expect(format).toBe('skill-md'); + }); + }); + + describe('translation', () => { + it('should translate SKILL.md to Cursor MDC', () => { + const skill: CanonicalSkill = { + name: 'test-skill', + description: 'A test skill', + tags: ['typescript'], + content: '# Test\nInstructions', + }; + + const result = registry.translate(skill, 'cursor'); + + expect(result.success).toBe(true); + expect(result.content).toContain('description: A test skill'); + expect(result.targetFormat).toBe('cursor-mdc'); + expect(result.filename).toBe('test-skill.mdc'); + }); + + it('should translate SKILL.md to Windsurf', () => { + const skill: CanonicalSkill = { + name: 'test-skill', + description: 'A test skill', + content: '# Test\nInstructions', + }; + + const result = registry.translate(skill, 'windsurf'); + + expect(result.success).toBe(true); + expect(result.content).toContain(''); + expect(result.targetFormat).toBe('markdown-rules'); + }); + + it('should translate SKILL.md to GitHub Copilot', () => { + const skill: CanonicalSkill = { + name: 'test-skill', + description: 'A test skill', + content: '# Test\nInstructions', + }; + + const result = registry.translate(skill, 'github-copilot'); + + expect(result.success).toBe(true); + expect(result.filename).toBe('copilot-instructions.md'); + }); + + it('should translate SKILL.md to Claude Code (same format)', () => { + const skill: CanonicalSkill = { + name: 'test-skill', + description: 'A test skill', + content: '# Test\nInstructions', + }; + + const result = registry.translate(skill, 'claude-code'); + + expect(result.success).toBe(true); + expect(result.targetFormat).toBe('skill-md'); + // YAML uses QUOTE_DOUBLE + expect(result.content).toContain('name: "test-skill"'); + }); + + it('should translate between all SKILL.md agents', () => { + const skill: CanonicalSkill = { + name: 'universal', + content: 'Works everywhere', + }; + + const skillMdAgents = [ + 'claude-code', + 'codex', + 'gemini-cli', + 'opencode', + 'antigravity', + 'amp', + 'goose', + 'kilo', + 'roo', + 'trae', + ] as const; + + for (const agent of skillMdAgents) { + const result = registry.translate(skill, agent); + expect(result.success).toBe(true); + expect(result.targetFormat).toBe('skill-md'); + } + }); + }); + + describe('translateContent', () => { + it('should translate content string to target agent', () => { + const content = `--- +name: source-skill +description: Source skill description +version: 1.0.0 +--- +# Source Skill + +Instructions here.`; + + const result = registry.translateContent(content, 'cursor'); + + expect(result.success).toBe(true); + expect(result.content).toContain('description: Source skill description'); + expect(result.filename).toBe('source-skill.mdc'); + }); + + it('should auto-detect source format and translate', () => { + const skillMdContent = `--- +name: auto-detect +--- +Content`; + + const result = registry.translateContent(skillMdContent, 'windsurf'); + + expect(result.success).toBe(true); + // Result contains translated content + expect(result.content).toContain(''); + }); + + it('should return error for completely unparseable content', () => { + // Content without any format markers and not valid YAML frontmatter + const invalidContent = `Random text without any format markers`; + + const result = registry.translateContent(invalidContent, 'cursor'); + + // Should still succeed as fallback parsing extracts content + // The implementation uses skillMdTranslator as fallback + expect(result).toBeDefined(); + }); + + it('should handle translation with source filename hint', () => { + const content = `--- +name: test +--- +Content`; + + const result = registry.translateContent(content, 'cursor', { + sourceFilename: 'SKILL.md', + }); + + expect(result.success).toBe(true); + }); + }); + + describe('getTranslator', () => { + it('should return correct translator for agent', () => { + const claudeTranslator = registry.getTranslatorForAgent('claude-code'); + const cursorTranslator = registry.getTranslatorForAgent('cursor'); + const windsurfTranslator = registry.getTranslatorForAgent('windsurf'); + + expect(claudeTranslator).not.toBeNull(); + expect(cursorTranslator).not.toBeNull(); + expect(windsurfTranslator).not.toBeNull(); + }); + + it('should return skill-md translator for most agents', () => { + const agents = ['codex', 'gemini-cli', 'amp', 'goose'] as const; + + for (const agent of agents) { + const translator = registry.getTranslatorForAgent(agent); + expect(translator?.format).toBe('skill-md'); + } + }); + }); + + describe('cross-format translation', () => { + it('should translate Cursor to SKILL.md', () => { + const cursorContent = `--- +description: Cursor rule +globs: ["**/*.ts"] +alwaysApply: false +--- +# Instructions +Follow these rules`; + + const result = registry.translateContent(cursorContent, 'claude-code', { + sourceFilename: 'test.mdc', + }); + + expect(result.success).toBe(true); + expect(result.targetFormat).toBe('skill-md'); + }); + + it('should translate Windsurf to Cursor', () => { + const windsurfContent = ` + +# Test Rules +Follow these guidelines`; + + const result = registry.translateContent(windsurfContent, 'cursor', { + sourceFilename: '.windsurfrules', + }); + + expect(result.success).toBe(true); + expect(result.targetFormat).toBe('cursor-mdc'); + }); + + it('should preserve content through cross-format translation', () => { + const skill: CanonicalSkill = { + name: 'metadata-test', + description: 'Testing metadata preservation', + version: '1.0.0', + tags: ['test', 'example'], + content: '# Content\nWith instructions', + }; + + // Translate through multiple formats + const toCursor = registry.translate(skill, 'cursor'); + expect(toCursor.success).toBe(true); + + // Parse the cursor result and translate to windsurf + const toWindsurf = registry.translateContent(toCursor.content, 'windsurf', { + sourceFilename: 'test.mdc', + }); + expect(toWindsurf.success).toBe(true); + + // The content should still be there + expect(toWindsurf.content).toContain('Content'); + }); + }); + + describe('error handling', () => { + it('should handle skills with metadata', () => { + const skill: CanonicalSkill = { + name: 'complex-skill', + content: 'Content', + metadata: { + someComplexFeature: 'value', + }, + }; + + const result = registry.translate(skill, 'windsurf'); + + // Should succeed + expect(result.success).toBe(true); + }); + + it('should handle empty name gracefully', () => { + const skill: CanonicalSkill = { + name: '', + content: 'No name provided', + }; + + const result = registry.translate(skill, 'cursor'); + + // Should handle gracefully + expect(result).toBeDefined(); + expect(result.success).toBe(true); + }); + }); + + describe('supported agents', () => { + it('should support all 17 agents', () => { + const allAgents = [ + 'claude-code', + 'cursor', + 'codex', + 'gemini-cli', + 'opencode', + 'antigravity', + 'amp', + 'clawdbot', + 'droid', + 'github-copilot', + 'goose', + 'kilo', + 'kiro-cli', + 'roo', + 'trae', + 'windsurf', + 'universal', + ] as const; + + const skill: CanonicalSkill = { + name: 'test', + content: 'Content', + }; + + for (const agent of allAgents) { + const translator = registry.getTranslatorForAgent(agent); + expect(translator).not.toBeNull(); + + const result = registry.translate(skill, agent); + expect(result.success).toBe(true); + } + }); + }); +}); diff --git a/packages/core/src/translator/__tests__/skill-md.test.ts b/packages/core/src/translator/__tests__/skill-md.test.ts new file mode 100644 index 00000000..f89fd420 --- /dev/null +++ b/packages/core/src/translator/__tests__/skill-md.test.ts @@ -0,0 +1,287 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { SkillMdTranslator } from '../formats/skill-md.js'; +import type { CanonicalSkill } from '../types.js'; + +describe('SkillMdTranslator', () => { + let translator: SkillMdTranslator; + + beforeEach(() => { + translator = new SkillMdTranslator(); + }); + + describe('format detection', () => { + it('should detect SKILL.md format with YAML frontmatter', () => { + const content = `--- +name: test-skill +description: A test skill +version: 1.0.0 +--- +# Test Skill +Instructions here`; + + expect(translator.detect(content, 'SKILL.md')).toBe(true); + }); + + it('should detect skill-md format by filename', () => { + const content = `--- +name: test-skill +--- +Instructions`; + + expect(translator.detect(content, 'test-skill.md')).toBe(true); + }); + + it('should not detect non-skill markdown files', () => { + const content = `# README +This is a readme file.`; + + expect(translator.detect(content, 'README.md')).toBe(false); + }); + + it('should not detect markdown without frontmatter', () => { + const content = `# Just a title +Some content without frontmatter`; + + expect(translator.detect(content)).toBe(false); + }); + + it('should detect frontmatter with name field', () => { + const content = `--- +name: my-skill +--- +Content`; + + expect(translator.detect(content)).toBe(true); + }); + }); + + describe('parsing', () => { + it('should parse complete SKILL.md file', () => { + const content = `--- +name: react-patterns +description: Best practices for React development +version: 2.0.0 +author: vercel-labs +tags: + - react + - frontend + - typescript +globs: + - "**/*.tsx" + - "**/*.jsx" +--- +# React Best Practices + +## Component Guidelines +- Use functional components +- Prefer hooks over class components +`; + + const skill = translator.parse(content, 'SKILL.md'); + + expect(skill).not.toBeNull(); + expect(skill!.name).toBe('react-patterns'); + expect(skill!.description).toBe('Best practices for React development'); + expect(skill!.version).toBe('2.0.0'); + expect(skill!.author).toBe('vercel-labs'); + expect(skill!.tags).toEqual(['react', 'frontend', 'typescript']); + expect(skill!.globs).toEqual(['**/*.tsx', '**/*.jsx']); + expect(skill!.content).toContain('# React Best Practices'); + expect(skill!.content).toContain('Use functional components'); + }); + + it('should parse minimal SKILL.md file', () => { + const content = `--- +name: minimal-skill +--- +Just some instructions`; + + const skill = translator.parse(content, 'SKILL.md'); + + expect(skill).not.toBeNull(); + expect(skill!.name).toBe('minimal-skill'); + expect(skill!.content).toBe('Just some instructions'); + }); + + it('should use unnamed-skill when frontmatter has no name and filename is SKILL.md', () => { + const content = `--- +description: A skill without explicit name +--- +Content here`; + + const skill = translator.parse(content, 'SKILL.md'); + + expect(skill).not.toBeNull(); + // When frontmatter exists but no name, and filename is SKILL.md, defaults to 'unnamed-skill' + expect(skill!.name).toBe('unnamed-skill'); + }); + + it('should handle empty frontmatter', () => { + const content = `--- +--- +# Content Only +Instructions without metadata`; + + const skill = translator.parse(content, 'SKILL.md'); + + expect(skill).not.toBeNull(); + // Empty frontmatter - name is inferred from first heading + expect(skill!.name).toBe('content-only'); + }); + + it('should infer name from heading when no frontmatter', () => { + const content = `# Content Only +Instructions without frontmatter`; + + const skill = translator.parse(content, 'SKILL.md'); + + expect(skill).not.toBeNull(); + // Name is inferred from first heading + expect(skill!.name).toBe('content-only'); + }); + + it('should handle complex YAML frontmatter', () => { + const content = `--- +name: complex-skill +description: A skill with complex metadata +version: 1.0.0 +compatibility: "react>=18.0.0" +agents: + optimized: + - claude-code + - cursor + compatible: + - codex +--- +# Complex Skill Content`; + + const skill = translator.parse(content, 'SKILL.md'); + + expect(skill).not.toBeNull(); + expect(skill!.name).toBe('complex-skill'); + // compatibility is stored directly on skill, not in metadata + expect(skill!.compatibility).toBe('react>=18.0.0'); + // agents hints are stored in agentHints + expect(skill!.agentHints).toBeDefined(); + }); + }); + + describe('generation', () => { + it('should generate SKILL.md format for claude-code', () => { + const skill: CanonicalSkill = { + name: 'test-skill', + description: 'A test skill for generation', + version: '1.0.0', + tags: ['test', 'example'], + content: '# Test Content\nInstructions here', + }; + + const result = translator.generate(skill, 'claude-code'); + + expect(result.success).toBe(true); + expect(result.content).toContain('---'); + // YAML uses QUOTE_DOUBLE so values are quoted + expect(result.content).toContain('name: "test-skill"'); + expect(result.content).toContain('description: "A test skill for generation"'); + expect(result.content).toContain('version: "1.0.0"'); + expect(result.content).toContain('# Test Content'); + }); + + it('should always use SKILL.md as filename', () => { + const skill: CanonicalSkill = { + name: 'my-skill', + content: 'Instructions', + }; + + const result = translator.generate(skill, 'claude-code'); + + expect(result.success).toBe(true); + // Filename is always SKILL.md regardless of skill name + expect(result.filename).toBe('SKILL.md'); + }); + + it('should preserve all metadata in output', () => { + const skill: CanonicalSkill = { + name: 'full-metadata', + description: 'Skill with full metadata', + version: '2.5.0', + author: 'test-author', + tags: ['tag1', 'tag2', 'tag3'], + globs: ['**/*.ts'], + content: 'Content', + }; + + const result = translator.generate(skill, 'codex'); + + expect(result.success).toBe(true); + // YAML uses QUOTE_DOUBLE + expect(result.content).toContain('name: "full-metadata"'); + expect(result.content).toContain('author: "test-author"'); + expect(result.content).toContain('tag1'); + expect(result.content).toContain('tag2'); + }); + + it('should generate for all SKILL.md compatible agents', () => { + const skill: CanonicalSkill = { + name: 'universal-skill', + content: 'Works everywhere', + }; + + const agents = [ + 'claude-code', + 'codex', + 'gemini-cli', + 'opencode', + 'antigravity', + 'amp', + 'goose', + 'kilo', + 'roo', + ] as const; + + for (const agent of agents) { + const result = translator.generate(skill, agent); + expect(result.success).toBe(true); + // YAML uses QUOTE_DOUBLE + expect(result.content).toContain('name: "universal-skill"'); + } + }); + }); + + describe('round-trip', () => { + it('should preserve content through parse and generate cycle', () => { + const original = `--- +name: round-trip-test +description: Testing round-trip conversion +version: 1.0.0 +tags: + - test +--- +# Round Trip Test + +This content should be preserved exactly. + +- Item 1 +- Item 2 +- Item 3 + +\`\`\`typescript +const code = 'preserved'; +\`\`\` +`; + + const parsed = translator.parse(original, 'SKILL.md'); + expect(parsed).not.toBeNull(); + + const generated = translator.generate(parsed!, 'claude-code'); + expect(generated.success).toBe(true); + + // Re-parse the generated content + const reparsed = translator.parse(generated.content, 'SKILL.md'); + expect(reparsed).not.toBeNull(); + expect(reparsed!.name).toBe(parsed!.name); + expect(reparsed!.description).toBe(parsed!.description); + expect(reparsed!.content).toContain('This content should be preserved exactly.'); + }); + }); +}); diff --git a/packages/core/src/translator/__tests__/windsurf.test.ts b/packages/core/src/translator/__tests__/windsurf.test.ts new file mode 100644 index 00000000..66371ee9 --- /dev/null +++ b/packages/core/src/translator/__tests__/windsurf.test.ts @@ -0,0 +1,304 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { WindsurfTranslator } from '../formats/windsurf.js'; +import type { CanonicalSkill } from '../types.js'; + +describe('WindsurfTranslator', () => { + let translator: WindsurfTranslator; + + beforeEach(() => { + translator = new WindsurfTranslator(); + }); + + describe('format detection', () => { + it('should detect .windsurfrules file', () => { + const content = `# Coding Guidelines +Follow these rules`; + + expect(translator.detect(content, '.windsurfrules')).toBe(true); + }); + + it('should detect windsurf rules by HTML comment metadata', () => { + const content = ` +# My Rule +Instructions`; + + expect(translator.detect(content)).toBe(true); + }); + + it('should not detect regular markdown', () => { + const content = `# README +Regular content`; + + expect(translator.detect(content, 'README.md')).toBe(false); + }); + + it('should not detect files with YAML frontmatter', () => { + const content = `--- +name: skill +--- +Content`; + + expect(translator.detect(content)).toBe(false); + }); + }); + + describe('parsing', () => { + it('should parse windsurf rules with metadata comment', () => { + const content = ` + + + +# React Rules + +Use functional components.`; + + const skill = translator.parse(content, '.windsurfrules'); + + expect(skill).not.toBeNull(); + expect(skill!.name).toBe('react-rules'); + expect(skill!.description).toBe('React best practices'); + expect(skill!.version).toBe('1.0.0'); + expect(skill!.content).toContain('# React Rules'); + }); + + it('should parse windsurf rules without metadata', () => { + const content = `# General Guidelines + +Follow these coding standards. + +## Code Style +- Use consistent indentation +- Add comments for complex logic`; + + const skill = translator.parse(content, '.windsurfrules'); + + expect(skill).not.toBeNull(); + // Name should be inferred from first heading + expect(skill!.name).toBe('general-guidelines'); + expect(skill!.content).toContain('# General Guidelines'); + }); + + it('should infer name from first heading', () => { + const content = `# My Amazing Coding Rules + +These are my rules.`; + + const skill = translator.parse(content, 'rules.md'); + + expect(skill).not.toBeNull(); + expect(skill!.name).toBe('my-amazing-coding-rules'); + }); + + it('should handle rules without headings', () => { + const content = `Use TypeScript. +Always add types. +Prefer interfaces over type aliases.`; + + const skill = translator.parse(content, '.windsurfrules'); + + expect(skill).not.toBeNull(); + expect(skill!.content).toContain('Use TypeScript'); + }); + + it('should extract tags from metadata comment', () => { + const content = ` + +Content`; + + const skill = translator.parse(content, '.windsurfrules'); + + expect(skill).not.toBeNull(); + // Tags are parsed from comma-separated string + expect(skill!.tags).toBeDefined(); + if (skill!.tags) { + expect(skill!.tags.join(',')).toContain('react'); + } + }); + }); + + describe('generation', () => { + it('should generate windsurf rules format', () => { + const skill: CanonicalSkill = { + name: 'typescript-rules', + description: 'TypeScript coding standards', + version: '1.0.0', + content: '# TypeScript\n\nUse strict mode.', + }; + + const result = translator.generate(skill, 'windsurf'); + + expect(result.success).toBe(true); + expect(result.content).toContain(''); + expect(result.content).toContain('# TypeScript'); + expect(result.filename).toBe('.windsurfrules'); + }); + + it('should include all metadata in comments', () => { + const skill: CanonicalSkill = { + name: 'full-metadata', + description: 'Complete metadata test', + version: '2.0.0', + author: 'test-author', + tags: ['tag1', 'tag2'], + content: 'Content', + }; + + const result = translator.generate(skill, 'windsurf'); + + expect(result.success).toBe(true); + expect(result.content).toContain(''); + expect(result.content).toContain(''); + }); + + it('should generate clean markdown without YAML', () => { + const skill: CanonicalSkill = { + name: 'clean-output', + content: '# Clean Markdown\n\nNo YAML here.', + }; + + const result = translator.generate(skill, 'windsurf'); + + expect(result.success).toBe(true); + expect(result.content).not.toMatch(/^---\n/); + expect(result.content).toContain('# Clean Markdown'); + }); + + it('should always use .windsurfrules filename', () => { + const skill: CanonicalSkill = { + name: 'any-name', + content: 'Content', + }; + + const result = translator.generate(skill, 'windsurf'); + + expect(result.filename).toBe('.windsurfrules'); + }); + }); + + describe('content preservation', () => { + it('should preserve code blocks', () => { + const skill: CanonicalSkill = { + name: 'code-blocks', + content: `# Code Examples + +\`\`\`typescript +function example() { + return true; +} +\`\`\` + +\`\`\`python +def example(): + return True +\`\`\` +`, + }; + + const result = translator.generate(skill, 'windsurf'); + + expect(result.success).toBe(true); + expect(result.content).toContain('```typescript'); + expect(result.content).toContain('function example()'); + expect(result.content).toContain('```python'); + }); + + it('should preserve lists and formatting', () => { + const skill: CanonicalSkill = { + name: 'lists', + content: `# Lists + +- Item 1 +- Item 2 + - Nested item + - Another nested + +1. First +2. Second + +**Bold** and *italic* and \`code\` +`, + }; + + const result = translator.generate(skill, 'windsurf'); + + expect(result.success).toBe(true); + expect(result.content).toContain('- Item 1'); + expect(result.content).toContain('- Nested item'); + expect(result.content).toContain('1. First'); + expect(result.content).toContain('**Bold**'); + }); + }); + + describe('round-trip', () => { + it('should preserve content through parse and generate cycle', () => { + const original = ` + + + +# Round Trip Test + +This content should survive the round trip. + +## Section 1 +Content here. + +## Section 2 +More content. +`; + + const parsed = translator.parse(original, '.windsurfrules'); + expect(parsed).not.toBeNull(); + + const generated = translator.generate(parsed!, 'windsurf'); + expect(generated.success).toBe(true); + + const reparsed = translator.parse(generated.content, '.windsurfrules'); + expect(reparsed).not.toBeNull(); + expect(reparsed!.name).toBe('round-trip-test'); + expect(reparsed!.content).toContain('This content should survive the round trip.'); + }); + }); + + describe('edge cases', () => { + it('should handle content with HTML', () => { + const skill: CanonicalSkill = { + name: 'html-content', + content: `# HTML in Markdown + +
+

Some HTML

+
+ +Regular markdown. +`, + }; + + const result = translator.generate(skill, 'windsurf'); + + expect(result.success).toBe(true); + expect(result.content).toContain('
'); + }); + + it('should handle empty content', () => { + const skill: CanonicalSkill = { + name: 'empty', + content: '', + }; + + const result = translator.generate(skill, 'windsurf'); + + expect(result.success).toBe(true); + }); + + it('should handle content with only whitespace', () => { + const skill: CanonicalSkill = { + name: 'whitespace', + content: ' \n\n \n', + }; + + const result = translator.generate(skill, 'windsurf'); + + expect(result.success).toBe(true); + }); + }); +}); diff --git a/packages/core/src/translator/formats/copilot.ts b/packages/core/src/translator/formats/copilot.ts new file mode 100644 index 00000000..7dbd7c1c --- /dev/null +++ b/packages/core/src/translator/formats/copilot.ts @@ -0,0 +1,213 @@ +import type { AgentType } from '../../types.js'; +import type { + FormatTranslator, + CanonicalSkill, + TranslationResult, + TranslationOptions, + FormatCategory, +} from '../types.js'; + +/** + * Parse metadata from markdown comments (same as Windsurf) + */ +function parseMetadataComments(content: string): { metadata: Record; body: string } { + const metadata: Record = {}; + const lines = content.split('\n'); + const bodyLines: string[] = []; + let inMetadata = true; + + for (const line of lines) { + if (inMetadata) { + const match = line.match(/^$/); + if (match) { + metadata[match[1].toLowerCase()] = match[2]; + continue; + } + if (line.trim() && !line.startsWith(' + * + * # Coding Guidelines + * + * ## React Components + * - Use functional components with hooks + * - Prefer TypeScript + * ``` + */ +export class CopilotTranslator implements FormatTranslator { + readonly format: FormatCategory = 'markdown-rules'; + readonly agents: AgentType[] = ['github-copilot']; + + /** + * Parse Copilot instructions into canonical format + */ + parse(content: string, filename?: string): CanonicalSkill | null { + const { metadata, body } = parseMetadataComments(content); + + // Try to extract name from metadata or first heading + let name = metadata.name; + if (!name) { + const headingMatch = body.match(/^#\s+(.+)$/m); + if (headingMatch) { + name = headingMatch[1] + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/[^a-z0-9-]/g, ''); + } else if (filename) { + name = filename + .replace(/\.(md)$/i, '') + .replace(/copilot-instructions/i, 'copilot-rules') + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/[^a-z0-9-]/g, ''); + } else { + name = 'copilot-instructions'; + } + } + + // Extract description + let description = metadata.description; + if (!description) { + const paragraphMatch = body.match(/^(?!#)[^\n]+/m); + if (paragraphMatch) { + description = paragraphMatch[0].substring(0, 200); + if (description.length === 200) description += '...'; + } else { + description = 'GitHub Copilot instructions'; + } + } + + return { + name, + description, + content: body, + sourceFormat: 'markdown-rules', + sourceAgent: 'github-copilot', + version: metadata.version, + author: metadata.author, + tags: metadata.tags?.split(',').map((t) => t.trim()), + }; + } + + /** + * Check if content is GitHub Copilot format + */ + detect(content: string, filename?: string): boolean { + // Check filename + if (filename) { + if (/copilot-instructions\.md$/i.test(filename)) return true; + if (/copilot.*instructions/i.test(filename)) return true; + } + + // Check for Copilot-specific comments + if (content.toLowerCase().includes('github copilot')) { + return true; + } + + return false; + } + + /** + * Generate GitHub Copilot instructions content + */ + generate( + skill: CanonicalSkill, + targetAgent: AgentType, + options: TranslationOptions = {} + ): TranslationResult { + const warnings: string[] = []; + const incompatible: string[] = []; + const lines: string[] = []; + + // Add header comment + lines.push(''); + lines.push(''); + lines.push(''); + + // Add metadata as comments if requested + if (options.addMetadata) { + lines.push(``); + lines.push(``); + if (skill.version) lines.push(``); + if (skill.author) lines.push(``); + lines.push(``); + lines.push(``); + lines.push(''); + } + + // Note incompatible features + if (skill.globs?.length) { + incompatible.push('globs: GitHub Copilot does not support file pattern matching'); + } + if (skill.alwaysApply !== undefined) { + incompatible.push('alwaysApply: GitHub Copilot does not support conditional application'); + } + if (skill.allowedTools) { + incompatible.push('allowed-tools: GitHub Copilot does not support tool restrictions'); + } + if (skill.metadata && Object.keys(skill.metadata).length > 0) { + warnings.push('Custom metadata fields not supported by GitHub Copilot'); + } + + // Add title if content doesn't start with one + if (!skill.content.trim().startsWith('#')) { + lines.push(`# ${skill.name.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')}`); + lines.push(''); + if (skill.description) { + lines.push(skill.description); + lines.push(''); + } + } + + // Add main content + lines.push(skill.content); + + return { + success: true, + content: lines.join('\n'), + filename: this.getFilename(skill.name, targetAgent), + warnings, + incompatible, + targetFormat: 'markdown-rules', + targetAgent, + }; + } + + /** + * Get the expected filename for GitHub Copilot format + */ + getFilename(_skillName: string, _targetAgent: AgentType): string { + return 'copilot-instructions.md'; + } + + /** + * Get the expected path for the instructions file + */ + getPath(_skillName: string): string { + return '.github/copilot-instructions.md'; + } +} + +/** + * Singleton instance + */ +export const copilotTranslator = new CopilotTranslator(); diff --git a/packages/core/src/translator/formats/cursor.ts b/packages/core/src/translator/formats/cursor.ts new file mode 100644 index 00000000..733f8994 --- /dev/null +++ b/packages/core/src/translator/formats/cursor.ts @@ -0,0 +1,273 @@ +import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'; +import type { AgentType } from '../../types.js'; +import type { + FormatTranslator, + CanonicalSkill, + TranslationResult, + TranslationOptions, + FormatCategory, +} from '../types.js'; + +/** + * Extract YAML frontmatter from MDC content + */ +function extractFrontmatter(content: string): { frontmatter: Record | null; body: string } { + const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)/); + + if (!match) { + return { frontmatter: null, body: content }; + } + + try { + const frontmatter = parseYaml(match[1]) as Record; + return { frontmatter, body: match[2] || '' }; + } catch { + return { frontmatter: null, body: content }; + } +} + +/** + * Infer glob patterns from skill content and tags + */ +function inferGlobs(skill: CanonicalSkill): string[] { + const globs: string[] = []; + const content = skill.content.toLowerCase(); + const tags = skill.tags || []; + + // Infer from tags + const tagExtensions: Record = { + 'react': ['**/*.tsx', '**/*.jsx'], + 'typescript': ['**/*.ts', '**/*.tsx'], + 'javascript': ['**/*.js', '**/*.jsx'], + 'python': ['**/*.py'], + 'rust': ['**/*.rs'], + 'go': ['**/*.go'], + 'css': ['**/*.css', '**/*.scss', '**/*.sass'], + 'html': ['**/*.html', '**/*.htm'], + 'vue': ['**/*.vue'], + 'svelte': ['**/*.svelte'], + 'angular': ['**/*.ts', '**/*.html'], + 'nextjs': ['**/*.tsx', '**/*.ts', '**/*.jsx', '**/*.js'], + 'testing': ['**/*.test.*', '**/*.spec.*'], + 'api': ['**/api/**/*', '**/routes/**/*'], + }; + + for (const tag of tags) { + const normalized = tag.toLowerCase(); + if (tagExtensions[normalized]) { + globs.push(...tagExtensions[normalized]); + } + } + + // Infer from content mentions + if (content.includes('component') || content.includes('jsx') || content.includes('tsx')) { + if (!globs.includes('**/*.tsx')) globs.push('**/*.tsx'); + if (!globs.includes('**/*.jsx')) globs.push('**/*.jsx'); + } + + if (content.includes('.py') || content.includes('python')) { + if (!globs.includes('**/*.py')) globs.push('**/*.py'); + } + + // Remove duplicates + return [...new Set(globs)]; +} + +/** + * Cursor MDC Format Translator + * + * Cursor uses two formats: + * 1. .cursorrules - Global rules file in project root + * 2. .cursor/rules/*.mdc - Individual rule files with frontmatter + * + * MDC Format: + * ``` + * --- + * description: What this rule does + * globs: ["**\/*.tsx", "**\/*.jsx"] + * alwaysApply: false + * --- + * Instructions here... + * ``` + */ +export class CursorTranslator implements FormatTranslator { + readonly format: FormatCategory = 'cursor-mdc'; + readonly agents: AgentType[] = ['cursor']; + + /** + * Parse Cursor MDC content into canonical format + */ + parse(content: string, filename?: string): CanonicalSkill | null { + const { frontmatter, body } = extractFrontmatter(content); + + // Extract name from filename + let name = 'unnamed-skill'; + if (filename) { + name = filename + .replace(/\.(mdc|md|cursorrules)$/i, '') + .replace(/^\./, '') + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/[^a-z0-9-]/g, ''); + } + + if (!frontmatter) { + // Plain .cursorrules file without frontmatter + return { + name, + description: 'Cursor rules', + content: body.trim(), + sourceFormat: 'cursor-mdc', + sourceAgent: 'cursor', + }; + } + + const description = (frontmatter.description as string) || 'Cursor rule'; + + return { + name: (frontmatter.name as string) || name, + description, + content: body.trim(), + sourceFormat: 'cursor-mdc', + sourceAgent: 'cursor', + globs: frontmatter.globs as string[] | undefined, + alwaysApply: frontmatter.alwaysApply as boolean | undefined, + tags: frontmatter.tags as string[] | undefined, + version: frontmatter.version as string | undefined, + author: frontmatter.author as string | undefined, + }; + } + + /** + * Check if content is Cursor MDC format + */ + detect(content: string, filename?: string): boolean { + // Check filename + if (filename) { + if (/\.mdc$/i.test(filename)) return true; + if (/\.cursorrules$/i.test(filename)) return true; + if (/cursorrules/i.test(filename)) return true; + } + + // Check for MDC-specific frontmatter fields + const { frontmatter } = extractFrontmatter(content); + if (frontmatter) { + if ('globs' in frontmatter || 'alwaysApply' in frontmatter) { + return true; + } + } + + return false; + } + + /** + * Generate Cursor MDC content + */ + generate( + skill: CanonicalSkill, + targetAgent: AgentType, + options: TranslationOptions = {} + ): TranslationResult { + const warnings: string[] = []; + const incompatible: string[] = []; + + // Build frontmatter + const frontmatter: Record = { + description: skill.description, + }; + + // Handle globs + let globs = options.globs || skill.globs; + if (!globs?.length) { + // Try to infer globs from skill metadata + globs = inferGlobs(skill); + if (globs.length > 0) { + warnings.push(`Inferred glob patterns: ${globs.join(', ')}`); + } + } + if (globs?.length) { + frontmatter.globs = globs; + } + + // Handle alwaysApply + const alwaysApply = options.alwaysApply ?? skill.alwaysApply; + if (alwaysApply !== undefined) { + frontmatter.alwaysApply = alwaysApply; + } + + // Note features that don't translate well + if (skill.allowedTools) { + incompatible.push('allowed-tools: Cursor does not support tool restrictions'); + } + if (skill.compatibility) { + // Add as comment in content + warnings.push('compatibility info added as comment'); + } + + // Add translation metadata if requested + if (options.addMetadata) { + frontmatter.translatedFrom = skill.sourceFormat; + frontmatter.originalName = skill.name; + } + + // Generate YAML frontmatter + const yamlContent = stringifyYaml(frontmatter, { + lineWidth: 0, + defaultKeyType: 'PLAIN', + }).trim(); + + // Build content with optional compatibility note + let body = skill.content; + if (skill.compatibility && options.preserveComments !== false) { + body = `\n\n${body}`; + } + + const content = `---\n${yamlContent}\n---\n\n${body}`; + + return { + success: true, + content, + filename: this.getFilename(skill.name, targetAgent), + warnings, + incompatible, + targetFormat: 'cursor-mdc', + targetAgent, + }; + } + + /** + * Generate .cursorrules content (alternative format) + */ + generateCursorrules(skill: CanonicalSkill): string { + // .cursorrules is just plain markdown without frontmatter + let content = ''; + + // Add header comment + content += `# ${skill.name}\n`; + content += `# ${skill.description}\n\n`; + + // Add main content + content += skill.content; + + return content; + } + + /** + * Get the expected filename for Cursor format + */ + getFilename(skillName: string, _targetAgent: AgentType): string { + // Convert to valid MDC filename + const safeName = skillName + .toLowerCase() + .replace(/[^a-z0-9-]/g, '-') + .replace(/-+/g, '-') + .replace(/^-|-$/g, ''); + + return `${safeName}.mdc`; + } +} + +/** + * Singleton instance + */ +export const cursorTranslator = new CursorTranslator(); diff --git a/packages/core/src/translator/formats/index.ts b/packages/core/src/translator/formats/index.ts new file mode 100644 index 00000000..560dfebe --- /dev/null +++ b/packages/core/src/translator/formats/index.ts @@ -0,0 +1,5 @@ +// Format translators +export { SkillMdTranslator, skillMdTranslator } from './skill-md.js'; +export { CursorTranslator, cursorTranslator } from './cursor.js'; +export { WindsurfTranslator, windsurfTranslator } from './windsurf.js'; +export { CopilotTranslator, copilotTranslator } from './copilot.js'; diff --git a/packages/core/src/translator/formats/skill-md.ts b/packages/core/src/translator/formats/skill-md.ts new file mode 100644 index 00000000..ab485fab --- /dev/null +++ b/packages/core/src/translator/formats/skill-md.ts @@ -0,0 +1,207 @@ +import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'; +import type { AgentType } from '../../types.js'; +import type { + FormatTranslator, + CanonicalSkill, + TranslationResult, + TranslationOptions, + FormatCategory, +} from '../types.js'; + +/** + * Agents that use the standard SKILL.md format + */ +const SKILL_MD_AGENTS: AgentType[] = [ + 'claude-code', + 'codex', + 'gemini-cli', + 'opencode', + 'antigravity', + 'amp', + 'clawdbot', + 'droid', + 'goose', + 'kilo', + 'kiro-cli', + 'roo', + 'trae', + 'universal', +]; + +/** + * Extract YAML frontmatter from markdown content + */ +function extractFrontmatter(content: string): { frontmatter: Record | null; body: string } { + const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)/); + + if (!match) { + return { frontmatter: null, body: content }; + } + + try { + const frontmatter = parseYaml(match[1]) as Record; + return { frontmatter, body: match[2] || '' }; + } catch { + return { frontmatter: null, body: content }; + } +} + +/** + * SKILL.md Format Translator + * + * This is the canonical format used by most AI coding agents. + * Format: + * ``` + * --- + * name: skill-name + * description: What it does + * version: 1.0.0 + * tags: [tag1, tag2] + * --- + * # Instructions + * Markdown content here... + * ``` + */ +export class SkillMdTranslator implements FormatTranslator { + readonly format: FormatCategory = 'skill-md'; + readonly agents: AgentType[] = SKILL_MD_AGENTS; + + /** + * Parse SKILL.md content into canonical format + */ + parse(content: string, filename?: string): CanonicalSkill | null { + const { frontmatter, body } = extractFrontmatter(content); + + if (!frontmatter) { + // Try to infer from content if no frontmatter + const nameMatch = content.match(/^#\s+(.+)$/m); + const name = nameMatch + ? nameMatch[1].toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '') + : filename?.replace(/\.md$/i, '').replace(/^SKILL$/i, 'unnamed-skill') || 'unnamed-skill'; + + return { + name, + description: 'Skill without frontmatter', + content: body.trim(), + sourceFormat: 'skill-md', + }; + } + + const name = (frontmatter.name as string) || 'unnamed-skill'; + const description = (frontmatter.description as string) || 'No description'; + + return { + name, + description, + version: frontmatter.version as string | undefined, + author: frontmatter.author as string | undefined, + license: frontmatter.license as string | undefined, + tags: frontmatter.tags as string[] | undefined, + compatibility: frontmatter.compatibility as string | undefined, + allowedTools: frontmatter['allowed-tools'] as string | undefined, + metadata: frontmatter.metadata as Record | undefined, + content: body.trim(), + sourceFormat: 'skill-md', + sourceAgent: frontmatter.sourceAgent as AgentType | undefined, + globs: frontmatter.globs as string[] | undefined, + alwaysApply: frontmatter.alwaysApply as boolean | undefined, + agentHints: frontmatter.agents as { optimized?: string[]; compatible?: string[] } | undefined, + }; + } + + /** + * Check if content is SKILL.md format + */ + detect(content: string, filename?: string): boolean { + // Check filename + if (filename && /SKILL\.md$/i.test(filename)) { + return true; + } + + // Check for YAML frontmatter with expected fields + const { frontmatter } = extractFrontmatter(content); + if (frontmatter && ('name' in frontmatter || 'description' in frontmatter)) { + return true; + } + + return false; + } + + /** + * Generate SKILL.md content for target agent + */ + generate( + skill: CanonicalSkill, + targetAgent: AgentType, + options: TranslationOptions = {} + ): TranslationResult { + const warnings: string[] = []; + const incompatible: string[] = []; + + // Build frontmatter object + const frontmatter: Record = { + name: skill.name, + description: skill.description, + }; + + // Add optional fields + if (skill.version) frontmatter.version = skill.version; + if (skill.author) frontmatter.author = skill.author; + if (skill.license) frontmatter.license = skill.license; + if (skill.tags?.length) frontmatter.tags = skill.tags; + if (skill.compatibility) frontmatter.compatibility = skill.compatibility; + if (skill.allowedTools) frontmatter['allowed-tools'] = skill.allowedTools; + if (skill.metadata && Object.keys(skill.metadata).length > 0) { + frontmatter.metadata = skill.metadata; + } + + // Handle Cursor-specific fields (store for reverse translation) + if (skill.globs?.length) { + frontmatter.globs = skill.globs; + warnings.push('Cursor globs preserved but may not be used by target agent'); + } + if (skill.alwaysApply !== undefined) { + frontmatter.alwaysApply = skill.alwaysApply; + warnings.push('Cursor alwaysApply preserved but may not be used by target agent'); + } + + // Add translation metadata if requested + if (options.addMetadata) { + frontmatter.translatedFrom = skill.sourceFormat; + frontmatter.translatedAt = new Date().toISOString(); + frontmatter.targetAgent = targetAgent; + } + + // Generate YAML frontmatter + const yamlContent = stringifyYaml(frontmatter, { + lineWidth: 0, + defaultKeyType: 'PLAIN', + defaultStringType: 'QUOTE_DOUBLE', + }).trim(); + + // Combine frontmatter and content + const content = `---\n${yamlContent}\n---\n\n${skill.content}`; + + return { + success: true, + content, + filename: this.getFilename(skill.name, targetAgent), + warnings, + incompatible, + targetFormat: 'skill-md', + targetAgent, + }; + } + + /** + * Get the expected filename for SKILL.md format + */ + getFilename(_skillName: string, _targetAgent: AgentType): string { + return 'SKILL.md'; + } +} + +/** + * Singleton instance + */ +export const skillMdTranslator = new SkillMdTranslator(); diff --git a/packages/core/src/translator/formats/windsurf.ts b/packages/core/src/translator/formats/windsurf.ts new file mode 100644 index 00000000..485aa5c9 --- /dev/null +++ b/packages/core/src/translator/formats/windsurf.ts @@ -0,0 +1,195 @@ +import type { AgentType } from '../../types.js'; +import type { + FormatTranslator, + CanonicalSkill, + TranslationResult, + TranslationOptions, + FormatCategory, +} from '../types.js'; + +/** + * Parse metadata from markdown comments + */ +function parseMetadataComments(content: string): { metadata: Record; body: string } { + const metadata: Record = {}; + const lines = content.split('\n'); + const bodyLines: string[] = []; + let inMetadata = true; + + for (const line of lines) { + if (inMetadata) { + const match = line.match(/^$/); + if (match) { + metadata[match[1].toLowerCase()] = match[2]; + continue; + } + // Stop parsing metadata on first non-comment, non-empty line + if (line.trim() && !line.startsWith(' + * + * + * # Guidelines + * + * Instructions here... + * ``` + */ +export class WindsurfTranslator implements FormatTranslator { + readonly format: FormatCategory = 'markdown-rules'; + readonly agents: AgentType[] = ['windsurf']; + + /** + * Parse Windsurf rules content into canonical format + */ + parse(content: string, filename?: string): CanonicalSkill | null { + const { metadata, body } = parseMetadataComments(content); + + // Try to extract name from first heading if not in metadata + let name = metadata.name; + if (!name) { + const headingMatch = body.match(/^#\s+(.+)$/m); + if (headingMatch) { + name = headingMatch[1] + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/[^a-z0-9-]/g, ''); + } else if (filename) { + name = filename + .replace(/\.(windsurfrules|md)$/i, '') + .replace(/^\./, '') + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/[^a-z0-9-]/g, ''); + } else { + name = 'unnamed-skill'; + } + } + + // Try to extract description from metadata or first paragraph + let description = metadata.description; + if (!description) { + // Get first non-heading paragraph + const paragraphMatch = body.match(/^(?!#)[^\n]+/m); + if (paragraphMatch) { + description = paragraphMatch[0].substring(0, 200); + if (description.length === 200) description += '...'; + } else { + description = 'Windsurf rules'; + } + } + + return { + name, + description, + content: body, + sourceFormat: 'markdown-rules', + sourceAgent: 'windsurf', + version: metadata.version, + author: metadata.author, + tags: metadata.tags?.split(',').map((t) => t.trim()), + }; + } + + /** + * Check if content is Windsurf format + */ + detect(content: string, filename?: string): boolean { + // Check filename + if (filename) { + if (/\.windsurfrules$/i.test(filename)) return true; + if (/windsurfrules/i.test(filename)) return true; + } + + // Check for metadata comments + if (content.startsWith('')) { + const { metadata } = parseMetadataComments(content); + if (Object.keys(metadata).length > 0) { + return true; + } + } + + return false; + } + + /** + * Generate Windsurf rules content + */ + generate( + skill: CanonicalSkill, + targetAgent: AgentType, + options: TranslationOptions = {} + ): TranslationResult { + const warnings: string[] = []; + const incompatible: string[] = []; + const lines: string[] = []; + + // Add metadata as HTML comments + if (options.addMetadata !== false) { + lines.push(``); + lines.push(``); + if (skill.version) lines.push(``); + if (skill.author) lines.push(``); + if (skill.tags?.length) lines.push(``); + if (options.addMetadata) { + lines.push(``); + lines.push(``); + } + lines.push(''); + } + + // Note incompatible features + if (skill.globs?.length) { + incompatible.push('globs: Windsurf does not support file pattern matching'); + } + if (skill.alwaysApply !== undefined) { + incompatible.push('alwaysApply: Windsurf does not support conditional application'); + } + if (skill.allowedTools) { + incompatible.push('allowed-tools: Windsurf does not support tool restrictions'); + } + + // Add main content + lines.push(skill.content); + + return { + success: true, + content: lines.join('\n'), + filename: this.getFilename(skill.name, targetAgent), + warnings, + incompatible, + targetFormat: 'markdown-rules', + targetAgent, + }; + } + + /** + * Get the expected filename for Windsurf format + */ + getFilename(_skillName: string, _targetAgent: AgentType): string { + return '.windsurfrules'; + } +} + +/** + * Singleton instance + */ +export const windsurfTranslator = new WindsurfTranslator(); diff --git a/packages/core/src/translator/index.ts b/packages/core/src/translator/index.ts new file mode 100644 index 00000000..f77b17c0 --- /dev/null +++ b/packages/core/src/translator/index.ts @@ -0,0 +1,113 @@ +// Types +export { + type FormatCategory, + type CanonicalSkill, + type TranslationResult, + type TranslationOptions, + type FormatTranslator, + type TranslationPath, + type TranslatableSkillFrontmatter, + AGENT_FORMAT_MAP, +} from './types.js'; + +// Format translators +export { + SkillMdTranslator, + skillMdTranslator, + CursorTranslator, + cursorTranslator, + WindsurfTranslator, + windsurfTranslator, + CopilotTranslator, + copilotTranslator, +} from './formats/index.js'; + +// Registry +export { TranslatorRegistry, translatorRegistry } from './registry.js'; + +// Convenience functions +import { translatorRegistry } from './registry.js'; +import type { AgentType } from '../types.js'; +import type { CanonicalSkill, TranslationResult, TranslationOptions } from './types.js'; + +/** + * Translate skill content from one agent format to another + * + * @example + * ```ts + * import { translateSkill } from '@skillkit/core'; + * + * const result = translateSkill(skillMdContent, 'cursor'); + * console.log(result.content); // Cursor MDC format + * ``` + */ +export function translateSkill( + content: string, + targetAgent: AgentType, + options?: TranslationOptions & { sourceFilename?: string } +): TranslationResult { + return translatorRegistry.translateContent(content, targetAgent, options); +} + +/** + * Translate a skill file to target agent format + * + * @example + * ```ts + * import { translateSkillFile } from '@skillkit/core'; + * + * const result = translateSkillFile('./skills/my-skill/SKILL.md', 'cursor'); + * console.log(result.filename); // 'my-skill.mdc' + * ``` + */ +export function translateSkillFile( + sourcePath: string, + targetAgent: AgentType, + options?: TranslationOptions +): TranslationResult { + return translatorRegistry.translateFile(sourcePath, targetAgent, options); +} + +/** + * Parse skill content into canonical format + * + * @example + * ```ts + * import { parseSkillContent } from '@skillkit/core'; + * + * const skill = parseSkillContent(cursorMdcContent, 'my-rule.mdc'); + * console.log(skill.name); // 'my-rule' + * ``` + */ +export function parseSkillContent(content: string, filename?: string): CanonicalSkill | null { + return translatorRegistry.parse(content, filename); +} + +/** + * Detect the format of skill content + * + * @example + * ```ts + * import { detectSkillFormat } from '@skillkit/core'; + * + * const format = detectSkillFormat(content, 'SKILL.md'); + * console.log(format); // 'skill-md' + * ``` + */ +export function detectSkillFormat(content: string, filename?: string): string | null { + return translatorRegistry.detectFormat(content, filename); +} + +/** + * Get all supported agent types for translation + */ +export function getSupportedTranslationAgents(): AgentType[] { + return translatorRegistry.getSupportedAgents(); +} + +/** + * Check if translation is possible between two agents + */ +export function canTranslate(from: AgentType, to: AgentType): boolean { + return translatorRegistry.canTranslate(from, to); +} diff --git a/packages/core/src/translator/registry.ts b/packages/core/src/translator/registry.ts new file mode 100644 index 00000000..33ba42d6 --- /dev/null +++ b/packages/core/src/translator/registry.ts @@ -0,0 +1,289 @@ +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { dirname, basename } from 'node:path'; +import type { AgentType } from '../types.js'; +import { + type FormatTranslator, + type CanonicalSkill, + type TranslationResult, + type TranslationOptions, + type FormatCategory, + AGENT_FORMAT_MAP, +} from './types.js'; +import { skillMdTranslator } from './formats/skill-md.js'; +import { cursorTranslator } from './formats/cursor.js'; +import { windsurfTranslator } from './formats/windsurf.js'; +import { copilotTranslator } from './formats/copilot.js'; + +/** + * Translator Registry + * + * Central registry for all format translators. Handles: + * - Format detection + * - Translation between any supported formats + * - Finding the optimal translation path + */ +export class TranslatorRegistry { + private translators: Map = new Map(); + private agentTranslators: Map = new Map(); + + constructor() { + // Register built-in translators + this.register(skillMdTranslator); + this.register(cursorTranslator); + this.register(windsurfTranslator); + this.register(copilotTranslator); + } + + /** + * Register a format translator + */ + register(translator: FormatTranslator): void { + this.translators.set(translator.format, translator); + + // Map agents to their translators + for (const agent of translator.agents) { + this.agentTranslators.set(agent, translator); + } + } + + /** + * Get translator for a specific format + */ + getTranslator(format: FormatCategory): FormatTranslator | undefined { + return this.translators.get(format); + } + + /** + * Get translator for a specific agent + */ + getTranslatorForAgent(agent: AgentType): FormatTranslator { + // Check if we have a specific translator for this agent + const specific = this.agentTranslators.get(agent); + if (specific) { + return specific; + } + + // Fall back to SKILL.md translator (works for most agents) + return skillMdTranslator; + } + + /** + * Get the format category for an agent + */ + getFormatForAgent(agent: AgentType): FormatCategory { + return AGENT_FORMAT_MAP[agent] || 'skill-md'; + } + + /** + * Detect the format of content + */ + detectFormat(content: string, filename?: string): FormatCategory | null { + // Try each translator's detect method + for (const [format, translator] of this.translators) { + if (translator.detect(content, filename)) { + return format; + } + } + + // Default to skill-md if content has YAML frontmatter + if (content.startsWith('---')) { + return 'skill-md'; + } + + return null; + } + + /** + * Detect the source agent from content + */ + detectSourceAgent(content: string, filename?: string): AgentType | null { + const format = this.detectFormat(content, filename); + if (!format) return null; + + // Check filename for agent hints + if (filename) { + const lower = filename.toLowerCase(); + if (lower.includes('cursor') || lower.endsWith('.mdc')) return 'cursor'; + if (lower.includes('windsurf')) return 'windsurf'; + if (lower.includes('copilot')) return 'github-copilot'; + } + + // Return first agent that uses this format + for (const [agent, agentFormat] of Object.entries(AGENT_FORMAT_MAP)) { + if (agentFormat === format) { + return agent as AgentType; + } + } + + return null; + } + + /** + * Parse content into canonical format + */ + parse(content: string, filename?: string): CanonicalSkill | null { + const format = this.detectFormat(content, filename); + if (!format) { + // Try skill-md as fallback + return skillMdTranslator.parse(content, filename); + } + + const translator = this.translators.get(format); + if (!translator) { + return null; + } + + return translator.parse(content, filename); + } + + /** + * Translate skill to target agent format + */ + translate( + skill: CanonicalSkill, + targetAgent: AgentType, + options: TranslationOptions = {} + ): TranslationResult { + const translator = this.getTranslatorForAgent(targetAgent); + return translator.generate(skill, targetAgent, options); + } + + /** + * Translate content directly from one agent to another + */ + translateContent( + content: string, + targetAgent: AgentType, + options: TranslationOptions & { sourceFilename?: string } = {} + ): TranslationResult { + // Parse source content + const skill = this.parse(content, options.sourceFilename); + if (!skill) { + return { + success: false, + content: '', + filename: '', + warnings: [], + incompatible: ['Failed to parse source content'], + targetFormat: this.getFormatForAgent(targetAgent), + targetAgent, + }; + } + + // Translate to target format + return this.translate(skill, targetAgent, options); + } + + /** + * Translate a skill file to target agent format + */ + translateFile( + sourcePath: string, + targetAgent: AgentType, + options: TranslationOptions = {} + ): TranslationResult { + if (!existsSync(sourcePath)) { + return { + success: false, + content: '', + filename: '', + warnings: [], + incompatible: [`Source file not found: ${sourcePath}`], + targetFormat: this.getFormatForAgent(targetAgent), + targetAgent, + }; + } + + const content = readFileSync(sourcePath, 'utf-8'); + const filename = basename(sourcePath); + + return this.translateContent(content, targetAgent, { + ...options, + sourceFilename: filename, + }); + } + + /** + * Translate and write to target path + */ + translateAndWrite( + sourcePath: string, + targetPath: string, + targetAgent: AgentType, + options: TranslationOptions = {} + ): TranslationResult { + const result = this.translateFile(sourcePath, targetAgent, options); + + if (result.success) { + // Ensure target directory exists + const targetDir = dirname(targetPath); + if (!existsSync(targetDir)) { + mkdirSync(targetDir, { recursive: true }); + } + + // Write translated content + writeFileSync(targetPath, result.content, 'utf-8'); + } + + return result; + } + + /** + * Get all supported agents + */ + getSupportedAgents(): AgentType[] { + return Object.keys(AGENT_FORMAT_MAP) as AgentType[]; + } + + /** + * Get all registered formats + */ + getRegisteredFormats(): FormatCategory[] { + return Array.from(this.translators.keys()); + } + + /** + * Check if translation is supported between two agents + */ + canTranslate(from: AgentType, to: AgentType): boolean { + // All agents can translate to/from each other via the canonical format + return this.getSupportedAgents().includes(from) && this.getSupportedAgents().includes(to); + } + + /** + * Get translation compatibility info + */ + getCompatibilityInfo(from: AgentType, to: AgentType): { + supported: boolean; + warnings: string[]; + lossyFields: string[]; + } { + const fromFormat = this.getFormatForAgent(from); + const toFormat = this.getFormatForAgent(to); + const warnings: string[] = []; + const lossyFields: string[] = []; + + // Cursor-specific features + if (fromFormat === 'cursor-mdc' && toFormat !== 'cursor-mdc') { + lossyFields.push('globs', 'alwaysApply'); + warnings.push('Cursor-specific features (globs, alwaysApply) will be preserved but not used'); + } + + // SKILL.md features going to markdown-rules + if (fromFormat === 'skill-md' && toFormat === 'markdown-rules') { + lossyFields.push('allowed-tools', 'metadata'); + warnings.push('Advanced SKILL.md features will be stored as comments'); + } + + return { + supported: this.canTranslate(from, to), + warnings, + lossyFields, + }; + } +} + +/** + * Default registry instance + */ +export const translatorRegistry = new TranslatorRegistry(); diff --git a/packages/core/src/translator/types.ts b/packages/core/src/translator/types.ts new file mode 100644 index 00000000..e24fa085 --- /dev/null +++ b/packages/core/src/translator/types.ts @@ -0,0 +1,172 @@ +import { z } from 'zod'; +import type { AgentType } from '../types.js'; + +/** + * Format categories for skill translation + */ +export type FormatCategory = + | 'skill-md' // Category A: Standard SKILL.md (13 agents) + | 'cursor-mdc' // Category B: Cursor MDC format + | 'markdown-rules' // Category C: Windsurf, GitHub Copilot + | 'external'; // Category D: External systems (Devin, etc.) + +/** + * Mapping of agents to their format categories + */ +export const AGENT_FORMAT_MAP: Record = { + 'claude-code': 'skill-md', + 'codex': 'skill-md', + 'gemini-cli': 'skill-md', + 'opencode': 'skill-md', + 'antigravity': 'skill-md', + 'amp': 'skill-md', + 'clawdbot': 'skill-md', + 'droid': 'skill-md', + 'goose': 'skill-md', + 'kilo': 'skill-md', + 'kiro-cli': 'skill-md', + 'roo': 'skill-md', + 'trae': 'skill-md', + 'universal': 'skill-md', + 'cursor': 'cursor-mdc', + 'windsurf': 'markdown-rules', + 'github-copilot': 'markdown-rules', +}; + +/** + * Extended skill frontmatter for translation + */ +export const TranslatableSkillFrontmatter = z.object({ + name: z.string(), + description: z.string(), + version: z.string().optional(), + author: z.string().optional(), + license: z.string().optional(), + tags: z.array(z.string()).optional(), + compatibility: z.string().optional(), + 'allowed-tools': z.string().optional(), + metadata: z.record(z.string()).optional(), + // Cursor-specific fields + globs: z.array(z.string()).optional(), + alwaysApply: z.boolean().optional(), + // Agent optimization hints + agents: z.object({ + optimized: z.array(z.string()).optional(), + compatible: z.array(z.string()).optional(), + }).optional(), +}); +export type TranslatableSkillFrontmatter = z.infer; + +/** + * Canonical skill representation for translation + */ +export interface CanonicalSkill { + /** Skill name (kebab-case) */ + name: string; + /** Human-readable description */ + description: string; + /** Version string */ + version?: string; + /** Author name or handle */ + author?: string; + /** License identifier */ + license?: string; + /** Categorization tags */ + tags?: string[]; + /** Compatibility description */ + compatibility?: string; + /** Allowed tools list */ + allowedTools?: string; + /** Additional metadata */ + metadata?: Record; + /** Main content (markdown) */ + content: string; + /** Original format this was parsed from */ + sourceFormat: FormatCategory; + /** Source agent type */ + sourceAgent?: AgentType; + /** Cursor-specific: glob patterns */ + globs?: string[]; + /** Cursor-specific: always apply flag */ + alwaysApply?: boolean; + /** Agent optimization hints */ + agentHints?: { + optimized?: string[]; + compatible?: string[]; + }; +} + +/** + * Result of a translation operation + */ +export interface TranslationResult { + /** Whether translation succeeded */ + success: boolean; + /** Translated content */ + content: string; + /** Output filename */ + filename: string; + /** Warnings during translation */ + warnings: string[]; + /** Features that couldn't be translated */ + incompatible: string[]; + /** Target format */ + targetFormat: FormatCategory; + /** Target agent */ + targetAgent: AgentType; +} + +/** + * Options for translation + */ +export interface TranslationOptions { + /** Preserve original comments */ + preserveComments?: boolean; + /** Add translation metadata */ + addMetadata?: boolean; + /** Custom output filename */ + outputFilename?: string; + /** For Cursor: glob patterns to include */ + globs?: string[]; + /** For Cursor: always apply setting */ + alwaysApply?: boolean; +} + +/** + * Interface for format-specific translators + */ +export interface FormatTranslator { + /** Format this translator handles */ + readonly format: FormatCategory; + /** Agents this translator is optimized for */ + readonly agents: AgentType[]; + + /** + * Parse content into canonical format + */ + parse(content: string, filename?: string): CanonicalSkill | null; + + /** + * Check if content matches this format + */ + detect(content: string, filename?: string): boolean; + + /** + * Generate content for target agent + */ + generate(skill: CanonicalSkill, targetAgent: AgentType, options?: TranslationOptions): TranslationResult; + + /** + * Get the expected filename for this format + */ + getFilename(skillName: string, targetAgent: AgentType): string; +} + +/** + * Translation path between formats + */ +export interface TranslationPath { + from: FormatCategory; + to: FormatCategory; + steps: FormatCategory[]; +} diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts new file mode 100644 index 00000000..48d00f8e --- /dev/null +++ b/packages/core/src/types.ts @@ -0,0 +1,139 @@ +import { z } from 'zod'; + +export const AgentType = z.enum([ + 'claude-code', + 'codex', + 'cursor', + 'antigravity', + 'opencode', + 'gemini-cli', + 'amp', + 'clawdbot', + 'droid', + 'github-copilot', + 'goose', + 'kilo', + 'kiro-cli', + 'roo', + 'trae', + 'windsurf', + 'universal', +]); +export type AgentType = z.infer; + +export const GitProvider = z.enum(['github', 'gitlab', 'bitbucket', 'local']); +export type GitProvider = z.infer; + +export const SkillFrontmatter = z.object({ + name: z.string() + .min(1) + .max(64) + .regex(/^[a-z0-9]+(-[a-z0-9]+)*$/, 'Skill name must be lowercase alphanumeric with hyphens, no leading/trailing/consecutive hyphens'), + description: z.string().min(1).max(1024), + license: z.string().optional(), + compatibility: z.string().max(500).optional(), + metadata: z.record(z.string()).optional(), + 'allowed-tools': z.string().optional(), + version: z.string().optional(), + author: z.string().optional(), + tags: z.array(z.string()).optional(), + agents: z.array(AgentType).optional(), +}); +export type SkillFrontmatter = z.infer; + +export const SkillMetadata = z.object({ + name: z.string(), + description: z.string(), + source: z.string(), + sourceType: GitProvider, + subpath: z.string().optional(), + installedAt: z.string().datetime(), + updatedAt: z.string().datetime().optional(), + enabled: z.boolean().default(true), + version: z.string().optional(), + checksum: z.string().optional(), +}); +export type SkillMetadata = z.infer; + +export const SkillLocation = z.enum(['project', 'global']); +export type SkillLocation = z.infer; + +export const Skill = z.object({ + name: z.string(), + description: z.string(), + path: z.string(), + location: SkillLocation, + metadata: SkillMetadata.optional(), + enabled: z.boolean().default(true), +}); +export type Skill = z.infer; + +export const SkillkitConfig = z.object({ + version: z.literal(1), + agent: AgentType.default('universal'), + skillsDir: z.string().optional(), + enabledSkills: z.array(z.string()).optional(), + disabledSkills: z.array(z.string()).optional(), + autoSync: z.boolean().default(true), +}); +export type SkillkitConfig = z.infer; + +export interface InstallOptions { + global?: boolean; + skills?: string[]; + provider?: GitProvider; + yes?: boolean; + force?: boolean; +} + +export interface SyncOptions { + output?: string; + agent?: AgentType; + yes?: boolean; + enabledOnly?: boolean; +} + +export interface UpdateOptions { + skills?: string[]; + all?: boolean; + force?: boolean; +} + +export interface RegistrySkill { + name: string; + description: string; + source: string; + provider: GitProvider; + downloads?: number; + stars?: number; + tags?: string[]; +} + +export interface DiscoveredSkill { + name: string; + dirName: string; + path: string; +} + +export interface CloneResult { + success: boolean; + path?: string; + tempRoot?: string; + error?: string; + skills?: string[]; + discoveredSkills?: DiscoveredSkill[]; +} + +export interface CommandResult { + success: boolean; + message: string; + data?: unknown; +} + +// Agent adapter interface (used by agents package) +export interface AgentAdapterInfo { + type: AgentType; + name: string; + skillsDir: string; + configFile: string; +} diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 00000000..c64c5089 --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src", + "composite": false + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist", "**/*.test.ts"] +} diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.ts new file mode 100644 index 00000000..dbcb9a72 --- /dev/null +++ b/packages/core/tsup.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: ['src/index.ts'], + format: ['esm'], + target: 'node18', + outDir: 'dist', + clean: true, + dts: true, + sourcemap: true, + splitting: false, + skipNodeModulesBundle: true, + platform: 'node', +}); diff --git a/packages/tui/package.json b/packages/tui/package.json new file mode 100644 index 00000000..0a9a51d0 --- /dev/null +++ b/packages/tui/package.json @@ -0,0 +1,42 @@ +{ + "name": "@skillkit/tui", + "version": "1.2.0", + "description": "Terminal UI for SkillKit", + "type": "module", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": "./dist/index.js", + "types": "./dist/index.d.ts" + } + }, + "files": ["dist"], + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@skillkit/core": "workspace:*", + "@skillkit/agents": "workspace:*", + "chalk": "^5.3.0", + "ink": "^5.0.1", + "ink-select-input": "^6.0.0", + "ink-spinner": "^5.0.0", + "ink-text-input": "^6.0.0", + "react": "^18.3.1" + }, + "devDependencies": { + "@types/node": "^22.10.5", + "@types/react": "^18.3.18", + "tsup": "^8.3.5", + "typescript": "^5.7.2", + "vitest": "^2.1.8" + }, + "engines": { + "node": ">=18.0.0" + }, + "license": "Apache-2.0" +} diff --git a/packages/tui/src/App.tsx b/packages/tui/src/App.tsx new file mode 100644 index 00000000..cc280fc3 --- /dev/null +++ b/packages/tui/src/App.tsx @@ -0,0 +1,71 @@ +import { useState } from 'react'; +import { Box, Text, useInput, useApp, useStdout } from 'ink'; +import { Sidebar } from './components/Sidebar.js'; +import { Home } from './screens/Home.js'; +import { Browse } from './screens/Browse.js'; +import { Installed } from './screens/Installed.js'; +import { Sync } from './screens/Sync.js'; +import { Settings } from './screens/Settings.js'; +import { Recommend } from './screens/Recommend.js'; +import { Translate } from './screens/Translate.js'; +import { Context } from './screens/Context.js'; + +export type Screen = 'home' | 'browse' | 'installed' | 'sync' | 'settings' | 'recommend' | 'translate' | 'context'; + +export function App() { + const [screen, setScreen] = useState('home'); + const { exit } = useApp(); + const { stdout } = useStdout(); + + const cols = stdout?.columns || 80; + const rows = stdout?.rows || 24; + const showSidebar = cols >= 70; + + useInput((input, key) => { + if (input === 'q') { + exit(); + return; + } + if (key.escape) { + setScreen('home'); + return; + } + if (input === 'h') setScreen('home'); + if (input === 'b') setScreen('browse'); + if (input === 'l') setScreen('installed'); + if (input === 's') setScreen('sync'); + if (input === ',') setScreen('settings'); + if (input === 'r') setScreen('recommend'); + if (input === 't') setScreen('translate'); + if (input === 'c') setScreen('context'); + }); + + const renderScreen = () => { + switch (screen) { + case 'home': return ; + case 'browse': return ; + case 'installed': return ; + case 'sync': return ; + case 'settings': return ; + case 'recommend': return ; + case 'translate': return ; + case 'context': return ; + } + }; + + const contentHeight = rows - 2; + + return ( + + + {showSidebar && } + + {renderScreen()} + + + + h Home b Browse r Rec t Trans c Ctx l List s Sync , Config q Quit + + + ); +} diff --git a/packages/tui/src/__tests__/components.test.ts b/packages/tui/src/__tests__/components.test.ts new file mode 100644 index 00000000..1932b971 --- /dev/null +++ b/packages/tui/src/__tests__/components.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect } from 'vitest'; + +describe('TUI Components', () => { + describe('exports', () => { + it('should export App component', async () => { + const { App } = await import('../App.js'); + expect(App).toBeDefined(); + expect(typeof App).toBe('function'); + }); + + it('should export theme configuration', async () => { + const { colors, symbols } = await import('../theme.js'); + expect(colors).toBeDefined(); + expect(symbols).toBeDefined(); + }); + + it('should export all screens', async () => { + const screens = await import('../screens/index.js'); + expect(screens.Home).toBeDefined(); + expect(screens.Browse).toBeDefined(); + expect(screens.Installed).toBeDefined(); + expect(screens.Sync).toBeDefined(); + expect(screens.Settings).toBeDefined(); + expect(screens.Recommend).toBeDefined(); + }); + + it('should export all hooks', async () => { + const hooks = await import('../hooks/index.js'); + expect(hooks.useSkills).toBeDefined(); + expect(hooks.useMarketplace).toBeDefined(); + expect(hooks.useKeyboard).toBeDefined(); + expect(hooks.useRecommend).toBeDefined(); + }); + }); +}); diff --git a/packages/tui/src/components/Header.tsx b/packages/tui/src/components/Header.tsx new file mode 100644 index 00000000..c57cf551 --- /dev/null +++ b/packages/tui/src/components/Header.tsx @@ -0,0 +1,30 @@ +import { Box, Text } from 'ink'; +import { colors, symbols } from '../theme.js'; + +interface HeaderProps { + title: string; + subtitle?: string; + count?: number; +} + +export function Header({ title, subtitle, count }: HeaderProps) { + return ( + + + + {title.toUpperCase()} + + {count !== undefined && ( + + {symbols.star} {count} + + )} + + {subtitle && ( + + {subtitle} + + )} + + ); +} diff --git a/packages/tui/src/components/SearchInput.tsx b/packages/tui/src/components/SearchInput.tsx new file mode 100644 index 00000000..a5686680 --- /dev/null +++ b/packages/tui/src/components/SearchInput.tsx @@ -0,0 +1,40 @@ +import { Box, Text } from 'ink'; +import TextInput from 'ink-text-input'; +import { colors } from '../theme.js'; + +interface SearchInputProps { + value: string; + onChange: (value: string) => void; + placeholder?: string; + isFocused?: boolean; +} + +export function SearchInput({ + value, + onChange, + placeholder = 'Search skills...', + isFocused = false, +}: SearchInputProps) { + return ( + + / + {isFocused ? ( + + ) : ( + + {value || placeholder} + + )} + + / + + ); +} diff --git a/packages/tui/src/components/Sidebar.tsx b/packages/tui/src/components/Sidebar.tsx new file mode 100644 index 00000000..95504d90 --- /dev/null +++ b/packages/tui/src/components/Sidebar.tsx @@ -0,0 +1,55 @@ +import { Box, Text } from 'ink'; +import { colors, symbols } from '../theme.js'; +import type { Screen } from '../App.js'; + +interface SidebarProps { + screen: Screen; + onNavigate: (screen: Screen) => void; + isCompact?: boolean; +} + +const NAV: { id: Screen; label: string }[] = [ + { id: 'home', label: 'Home' }, + { id: 'browse', label: 'Browse' }, + { id: 'recommend', label: 'Recommend' }, + { id: 'translate', label: 'Translate' }, + { id: 'context', label: 'Context' }, + { id: 'installed', label: 'List' }, + { id: 'sync', label: 'Sync' }, + { id: 'settings', label: 'Config' }, +]; + +export function Sidebar({ screen }: SidebarProps) { + return ( + + SkillKit + + {NAV.slice(0, 3).map((item) => ( + + {screen === item.id ? symbols.bullet : ' '}{item.label} + + ))} + + + + {NAV.slice(3, 5).map((item) => ( + + {screen === item.id ? symbols.bullet : ' '}{item.label} + + ))} + + + + {NAV.slice(5).map((item) => ( + + {screen === item.id ? symbols.bullet : ' '}{item.label} + + ))} + + + + ? Help + q Quit + + ); +} diff --git a/packages/tui/src/components/SkillList.tsx b/packages/tui/src/components/SkillList.tsx new file mode 100644 index 00000000..c7ae6e0c --- /dev/null +++ b/packages/tui/src/components/SkillList.tsx @@ -0,0 +1,103 @@ +import { Box, Text } from 'ink'; +import { colors, symbols } from '../theme.js'; + +export interface SkillItem { + name: string; + description?: string; + source?: string; + installs?: number; + enabled?: boolean; +} + +interface SkillListProps { + skills: SkillItem[]; + selectedIndex: number; + showInstalls?: boolean; + showRank?: boolean; + showSource?: boolean; + maxVisible?: number; +} + +function formatInstalls(count: number): string { + if (count >= 1000) { + return `${(count / 1000).toFixed(1)}K`; + } + return String(count); +} + +export function SkillList({ + skills, + selectedIndex, + showInstalls = false, + showRank = false, + showSource = true, + maxVisible = 10, +}: SkillListProps) { + if (skills.length === 0) { + return ( + + + No skills found + + + ); + } + + const startIndex = Math.max(0, selectedIndex - Math.floor(maxVisible / 2)); + const visibleSkills = skills.slice(startIndex, startIndex + maxVisible); + const actualStartIndex = startIndex; + + return ( + + {showRank && ( + + + {' # SKILL'} + {showSource && ' SOURCE'} + {showInstalls && ' INSTALLS'} + + + )} + + {visibleSkills.map((skill, idx) => { + const realIndex = actualStartIndex + idx; + const isSelected = realIndex === selectedIndex; + const skillName = skill.name.padEnd(28).slice(0, 28); + const sourceName = skill.source ? skill.source.slice(0, 25) : ''; + + return ( + + + {isSelected ? symbols.pointer : ' '} + {showRank ? String(realIndex + 1).padStart(2, ' ') : ''} + {' '} + {skillName} + + {showSource && ( + + {' '}{sourceName} + + )} + {showInstalls && skill.installs !== undefined && ( + + {formatInstalls(skill.installs).padStart(8)} + + )} + + ); + })} + + {skills.length > maxVisible && ( + + + Showing {startIndex + 1}-{Math.min(startIndex + maxVisible, skills.length)} of {skills.length} + + + )} + + ); +} diff --git a/packages/tui/src/components/StatusBar.tsx b/packages/tui/src/components/StatusBar.tsx new file mode 100644 index 00000000..acb237df --- /dev/null +++ b/packages/tui/src/components/StatusBar.tsx @@ -0,0 +1,44 @@ +import { Box, Text } from 'ink'; +import { colors, symbols } from '../theme.js'; + +interface Shortcut { + key: string; + label: string; +} + +interface StatusBarProps { + shortcuts: Shortcut[]; + message?: string; +} + +export function StatusBar({ shortcuts, message }: StatusBarProps) { + return ( + + + {shortcuts.map((shortcut, idx) => ( + + + {shortcut.key} + + {shortcut.label} + + ))} + + + {message && ( + + {symbols.check} {message} + + )} + + ); +} diff --git a/packages/tui/src/components/index.ts b/packages/tui/src/components/index.ts new file mode 100644 index 00000000..8c4fd602 --- /dev/null +++ b/packages/tui/src/components/index.ts @@ -0,0 +1,5 @@ +export { Sidebar } from './Sidebar.js'; +export { Header } from './Header.js'; +export { SkillList, type SkillItem } from './SkillList.js'; +export { StatusBar } from './StatusBar.js'; +export { SearchInput } from './SearchInput.js'; diff --git a/packages/tui/src/helpers.ts b/packages/tui/src/helpers.ts new file mode 100644 index 00000000..c549634e --- /dev/null +++ b/packages/tui/src/helpers.ts @@ -0,0 +1,36 @@ +// Re-export commonly used functions with proper adapters +import { + loadConfig, + getSearchDirs as coreGetSearchDirs, + getInstallDir as coreGetInstallDir, + saveSkillMetadata as coreSaveSkillMetadata, +} from '@skillkit/core'; +import { getAdapter, detectAgent } from '@skillkit/agents'; +import type { AgentType, AgentAdapterInfo } from '@skillkit/core'; + +// Re-export for direct use +export { coreSaveSkillMetadata as saveSkillMetadata }; + +export function getSearchDirs(agentType?: AgentType): string[] { + const type = agentType || loadConfig().agent; + const adapter = getAdapter(type); + const adapterInfo: AgentAdapterInfo = { + type: adapter.type, + name: adapter.name, + skillsDir: adapter.skillsDir, + configFile: adapter.configFile, + }; + return coreGetSearchDirs(adapterInfo); +} + +export function getInstallDir(global = false, agentType?: AgentType): string { + const type = agentType || loadConfig().agent; + const adapter = getAdapter(type); + const adapterInfo: AgentAdapterInfo = { + type: adapter.type, + name: adapter.name, + skillsDir: adapter.skillsDir, + configFile: adapter.configFile, + }; + return coreGetInstallDir(adapterInfo, global); +} diff --git a/packages/tui/src/hooks/index.ts b/packages/tui/src/hooks/index.ts new file mode 100644 index 00000000..cbf6efb4 --- /dev/null +++ b/packages/tui/src/hooks/index.ts @@ -0,0 +1,4 @@ +export { useSkills } from './useSkills.js'; +export { useMarketplace } from './useMarketplace.js'; +export { useKeyboard, useListNavigation } from './useKeyboard.js'; +export { useRecommend } from './useRecommend.js'; diff --git a/packages/tui/src/hooks/useKeyboard.ts b/packages/tui/src/hooks/useKeyboard.ts new file mode 100644 index 00000000..bbf366ce --- /dev/null +++ b/packages/tui/src/hooks/useKeyboard.ts @@ -0,0 +1,93 @@ +import { useState, useCallback, useEffect } from 'react'; +import { useInput, useApp } from 'ink'; +import type { Screen } from '../App.js'; + +interface UseKeyboardOptions { + onNavigate?: (screen: Screen) => void; + onSelect?: () => void; + onSearch?: () => void; + onInstall?: () => void; + onBack?: () => void; + onUp?: () => void; + onDown?: () => void; + disabled?: boolean; +} + +export function useKeyboard(options: UseKeyboardOptions = {}) { + const { exit } = useApp(); + + useInput((input, key) => { + if (options.disabled) return; + + if (input === 'q' || (key.ctrl && input === 'c')) { + exit(); + return; + } + + if (key.escape && options.onBack) { + options.onBack(); + return; + } + + if (key.return && options.onSelect) { + options.onSelect(); + return; + } + + if (key.upArrow && options.onUp) { + options.onUp(); + return; + } + + if (key.downArrow && options.onDown) { + options.onDown(); + return; + } + + if (input === '/' && options.onSearch) { + options.onSearch(); + return; + } + + if (input === 'i' && options.onInstall) { + options.onInstall(); + return; + } + + if (input === 'h' && options.onNavigate) { + options.onNavigate('home'); + } else if (input === 'b' && options.onNavigate) { + options.onNavigate('browse'); + } else if (input === 'l' && options.onNavigate) { + options.onNavigate('installed'); + } else if (input === 's' && options.onNavigate) { + options.onNavigate('sync'); + } else if (input === ',' && options.onNavigate) { + options.onNavigate('settings'); + } + }); +} + +export function useListNavigation(listLength: number, initialIndex = 0) { + const [selectedIndex, setSelectedIndex] = useState(initialIndex); + + useEffect(() => { + if (selectedIndex >= listLength && listLength > 0) { + setSelectedIndex(listLength - 1); + } + }, [listLength, selectedIndex]); + + const moveUp = useCallback(() => { + setSelectedIndex((prev) => Math.max(0, prev - 1)); + }, []); + + const moveDown = useCallback(() => { + setSelectedIndex((prev) => Math.min(listLength - 1, prev + 1)); + }, [listLength]); + + const reset = useCallback(() => { + setSelectedIndex(0); + }, []); + + return { selectedIndex, setSelectedIndex, moveUp, moveDown, reset }; +} diff --git a/packages/tui/src/hooks/useMarketplace.ts b/packages/tui/src/hooks/useMarketplace.ts new file mode 100644 index 00000000..4df3b98b --- /dev/null +++ b/packages/tui/src/hooks/useMarketplace.ts @@ -0,0 +1,180 @@ +import { useState, useCallback, useEffect } from 'react'; +import { detectProvider } from '@skillkit/core'; +import type { SkillItem } from '../components/SkillList.js'; + +export interface RepoInfo { + source: string; + name: string; +} + +const POPULAR_REPOS: RepoInfo[] = [ + { source: 'anthropics/skills', name: 'Anthropic Official' }, + { source: 'vercel-labs/agent-skills', name: 'Vercel Labs' }, + { source: 'expo/skills', name: 'Expo / React Native' }, + { source: 'remotion-dev/skills', name: 'Remotion Video' }, + { source: 'ComposioHQ/awesome-claude-skills', name: 'Composio Awesome' }, + { source: 'travisvn/awesome-claude-skills', name: 'Travis Awesome' }, + { source: 'mhattingpete/claude-skills-marketplace', name: 'Skills Marketplace' }, + { source: 'coreyhaines31/marketingskills', name: 'Marketing Skills' }, + { source: 'obra/superpowers', name: 'Superpowers TDD' }, + { source: 'softaworks/agent-toolkit', name: 'Softaworks Toolkit' }, + { source: 'wshobson/agents', name: 'Dev Patterns' }, + { source: 'langgenius/dify', name: 'Dify Frontend' }, + { source: 'trailofbits/skills', name: 'Trail of Bits Security' }, + { source: 'better-auth/skills', name: 'Better Auth' }, + { source: 'onmax/nuxt-skills', name: 'Nuxt / Vue' }, + { source: 'hyf0/vue-skills', name: 'Vue Best Practices' }, + { source: 'jezweb/claude-skills', name: 'Cloudflare / TanStack' }, + { source: 'elysiajs/skills', name: 'ElysiaJS / Bun' }, + { source: 'kadajett/agent-nestjs-skills', name: 'NestJS' }, + { source: 'callstackincubator/agent-skills', name: 'React Native' }, + { source: 'cloudai-x/threejs-skills', name: 'Three.js' }, + { source: 'emalorenzo/three-agent-skills', name: 'Three.js Advanced' }, + { source: 'dimillian/skills', name: 'SwiftUI iOS' }, + { source: 'stripe/ai', name: 'Stripe Payments' }, + { source: 'waynesutton/convexskills', name: 'Convex Backend' }, + { source: 'kepano/obsidian-skills', name: 'Obsidian Notes' }, + { source: 'jimliu/baoyu-skills', name: 'Baoyu Tools' }, + { source: 'giuseppe-trisciuoglio/developer-kit', name: 'Shadcn / Radix' }, + { source: 'openrouterteam/agent-skills', name: 'OpenRouter SDK' }, + { source: 'intellectronica/agent-skills', name: 'Context7' }, +]; + +interface FetchedSkill { + name: string; + source: string; + repoName: string; + description?: string; +} + +interface UseMarketplaceResult { + skills: SkillItem[]; + loading: boolean; + error: string | null; + totalCount: number; + repos: RepoInfo[]; + currentRepo: string | null; + refresh: () => void; + search: (query: string) => void; + fetchRepo: (source: string) => Promise; + fetchAllRepos: () => Promise; +} + +export function useMarketplace(): UseMarketplaceResult { + const [allSkills, setAllSkills] = useState([]); + const [filteredSkills, setFilteredSkills] = useState([]); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [currentRepo, setCurrentRepo] = useState(null); + const [fetchedRepos, setFetchedRepos] = useState>(new Set()); + + const fetchRepo = useCallback(async (source: string) => { + if (fetchedRepos.has(source)) return; + + setLoading(true); + setError(null); + setCurrentRepo(source); + + try { + const provider = detectProvider(source); + if (!provider) { + throw new Error(`Could not detect provider for: ${source}`); + } + + const result = await provider.clone(source, '', { depth: 1 }); + + if (!result.success || !result.discoveredSkills) { + throw new Error(result.error || 'Failed to fetch skills'); + } + + const repoName = POPULAR_REPOS.find(r => r.source === source)?.name || source; + const newSkills: FetchedSkill[] = result.discoveredSkills.map(skill => ({ + name: skill.name, + source: source, + repoName: repoName, + description: undefined, + })); + + setAllSkills(prev => { + const updated = [...prev, ...newSkills]; + return updated.sort((a, b) => a.name.localeCompare(b.name)); + }); + + setFetchedRepos(prev => new Set([...prev, source])); + + if (result.tempRoot) { + const { rmSync } = await import('node:fs'); + rmSync(result.tempRoot, { recursive: true, force: true }); + } + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to fetch repository'); + } finally { + setLoading(false); + setCurrentRepo(null); + } + }, [fetchedRepos]); + + const fetchAllRepos = useCallback(async () => { + setLoading(true); + setError(null); + + for (const repo of POPULAR_REPOS) { + if (!fetchedRepos.has(repo.source)) { + setCurrentRepo(repo.source); + try { + await fetchRepo(repo.source); + } catch { + } + } + } + + setLoading(false); + setCurrentRepo(null); + }, [fetchRepo, fetchedRepos]); + + const search = useCallback((query: string) => { + if (!query.trim()) { + setFilteredSkills(allSkills); + } else { + const lowerQuery = query.toLowerCase(); + setFilteredSkills( + allSkills.filter( + (s) => + s.name.toLowerCase().includes(lowerQuery) || + s.source.toLowerCase().includes(lowerQuery) || + s.repoName.toLowerCase().includes(lowerQuery) || + s.description?.toLowerCase().includes(lowerQuery) + ) + ); + } + }, [allSkills]); + + const refresh = useCallback(() => { + setFetchedRepos(new Set()); + setAllSkills([]); + setFilteredSkills([]); + }, []); + + useEffect(() => { + setFilteredSkills(allSkills); + }, [allSkills]); + + const skills: SkillItem[] = filteredSkills.map((s) => ({ + name: s.name, + description: s.description || s.repoName, + source: s.source, + })); + + return { + skills, + loading, + error, + totalCount: allSkills.length, + repos: POPULAR_REPOS, + currentRepo, + refresh, + search, + fetchRepo, + fetchAllRepos, + }; +} diff --git a/packages/tui/src/hooks/useRecommend.ts b/packages/tui/src/hooks/useRecommend.ts new file mode 100644 index 00000000..0507bdf5 --- /dev/null +++ b/packages/tui/src/hooks/useRecommend.ts @@ -0,0 +1,383 @@ +import { useState, useCallback, useEffect } from 'react'; +import { + RecommendationEngine, + ContextManager, + type ScoredSkill, + type ProjectProfile, + type SkillIndex, + type SkillSummary, +} from '@skillkit/core'; +import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { join } from 'node:path'; + +const INDEX_PATH = join(process.env.HOME || '~', '.skillkit', 'index.json'); +const INDEX_CACHE_HOURS = 24; + +interface UseRecommendResult { + recommendations: ScoredSkill[]; + profile: ProjectProfile | null; + loading: boolean; + error: string | null; + totalScanned: number; + indexStatus: 'missing' | 'stale' | 'fresh'; + refresh: () => void; + updateIndex: () => void; + search: (query: string) => void; + searchResults: ScoredSkill[]; +} + +/** + * Sample skills for the index (matches CLI implementation) + */ +function getSampleSkills(): SkillSummary[] { + return [ + { + name: 'vercel-react-best-practices', + description: 'Modern React patterns including Server Components, hooks best practices, and performance optimization', + source: 'vercel-labs/agent-skills', + tags: ['react', 'frontend', 'typescript', 'nextjs', 'performance'], + compatibility: { + frameworks: ['react', 'nextjs'], + languages: ['typescript', 'javascript'], + libraries: [], + }, + popularity: 1500, + quality: 95, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'tailwind-v4-patterns', + description: 'Tailwind CSS v4 utility patterns, responsive design, and component styling best practices', + source: 'vercel-labs/agent-skills', + tags: ['tailwind', 'css', 'styling', 'frontend', 'responsive'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript'], + libraries: ['tailwindcss'], + }, + popularity: 1200, + quality: 92, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'nextjs-app-router', + description: 'Next.js App Router patterns including layouts, server actions, and data fetching', + source: 'vercel-labs/agent-skills', + tags: ['nextjs', 'react', 'routing', 'server-actions', 'frontend'], + compatibility: { + frameworks: ['nextjs'], + languages: ['typescript', 'javascript'], + libraries: [], + }, + popularity: 1100, + quality: 94, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'typescript-strict-patterns', + description: 'TypeScript strict mode patterns, type safety, and advanced type utilities', + source: 'anthropics/skills', + tags: ['typescript', 'types', 'safety', 'patterns'], + compatibility: { + frameworks: [], + languages: ['typescript'], + libraries: [], + }, + popularity: 900, + quality: 90, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'supabase-best-practices', + description: 'Supabase integration patterns including auth, database queries, and real-time subscriptions', + source: 'anthropics/skills', + tags: ['supabase', 'database', 'auth', 'backend', 'postgresql'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript'], + libraries: ['@supabase/supabase-js'], + }, + popularity: 800, + quality: 88, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'vitest-testing-patterns', + description: 'Testing patterns with Vitest including mocking, assertions, and test organization', + source: 'anthropics/skills', + tags: ['vitest', 'testing', 'typescript', 'mocking', 'tdd'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript'], + libraries: ['vitest'], + }, + popularity: 700, + quality: 86, + lastUpdated: new Date().toISOString(), + verified: false, + }, + { + name: 'prisma-database-patterns', + description: 'Prisma ORM patterns for schema design, migrations, and efficient queries', + source: 'vercel-labs/agent-skills', + tags: ['prisma', 'database', 'orm', 'postgresql', 'backend'], + compatibility: { + frameworks: [], + languages: ['typescript'], + libraries: ['@prisma/client'], + }, + popularity: 850, + quality: 89, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'security-best-practices', + description: 'Security patterns for web applications including XSS prevention, CSRF, and secure headers', + source: 'trailofbits/skills', + tags: ['security', 'xss', 'csrf', 'headers', 'owasp'], + compatibility: { + frameworks: [], + languages: ['typescript', 'javascript', 'python'], + libraries: [], + }, + popularity: 600, + quality: 95, + lastUpdated: new Date().toISOString(), + verified: true, + }, + { + name: 'python-fastapi-patterns', + description: 'FastAPI best practices for building high-performance Python APIs', + source: 'python-skills/fastapi', + tags: ['python', 'fastapi', 'backend', 'api', 'async'], + compatibility: { + frameworks: ['fastapi'], + languages: ['python'], + libraries: [], + }, + popularity: 550, + quality: 85, + lastUpdated: new Date().toISOString(), + verified: false, + }, + { + name: 'zustand-state-management', + description: 'Zustand state management patterns for React applications', + source: 'react-skills/state', + tags: ['zustand', 'react', 'state-management', 'frontend'], + compatibility: { + frameworks: ['react'], + languages: ['typescript', 'javascript'], + libraries: ['zustand'], + }, + popularity: 650, + quality: 84, + lastUpdated: new Date().toISOString(), + verified: false, + }, + ]; +} + +export function useRecommend(projectPath: string = process.cwd()): UseRecommendResult { + const [recommendations, setRecommendations] = useState([]); + const [searchResults, setSearchResults] = useState([]); + const [profile, setProfile] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [totalScanned, setTotalScanned] = useState(0); + const [indexStatus, setIndexStatus] = useState<'missing' | 'stale' | 'fresh'>('missing'); + const [engine] = useState(() => new RecommendationEngine()); + + const loadIndex = useCallback((): SkillIndex | null => { + if (!existsSync(INDEX_PATH)) { + setIndexStatus('missing'); + return null; + } + + try { + const content = readFileSync(INDEX_PATH, 'utf-8'); + const index = JSON.parse(content) as SkillIndex; + + // Check if index is stale + const lastUpdated = new Date(index.lastUpdated); + const hoursSinceUpdate = (Date.now() - lastUpdated.getTime()) / (1000 * 60 * 60); + + if (hoursSinceUpdate > INDEX_CACHE_HOURS) { + setIndexStatus('stale'); + } else { + setIndexStatus('fresh'); + } + + return index; + } catch { + setIndexStatus('missing'); + return null; + } + }, []); + + const getProjectProfile = useCallback((): ProjectProfile | null => { + try { + const manager = new ContextManager(projectPath); + let context = manager.get(); + + if (!context) { + context = manager.init(); + } + + if (!context) { + return null; + } + + return { + name: context.project.name, + type: context.project.type, + stack: context.stack, + patterns: context.patterns, + installedSkills: context.skills?.installed || [], + excludedSkills: context.skills?.excluded || [], + }; + } catch { + return null; + } + }, [projectPath]); + + const loadRecommendations = useCallback(() => { + setLoading(true); + setError(null); + + try { + // Load project profile + const projectProfile = getProjectProfile(); + if (!projectProfile) { + setError('Failed to analyze project'); + setLoading(false); + return; + } + setProfile(projectProfile); + + // Load skill index + const index = loadIndex(); + if (!index || index.skills.length === 0) { + setRecommendations([]); + setTotalScanned(0); + setLoading(false); + return; + } + + engine.loadIndex(index); + + // Get recommendations + const result = engine.recommend(projectProfile, { + limit: 20, + minScore: 20, + excludeInstalled: true, + includeReasons: true, + }); + + setRecommendations(result.recommendations); + setTotalScanned(result.totalSkillsScanned); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to get recommendations'); + } finally { + setLoading(false); + } + }, [engine, getProjectProfile, loadIndex]); + + const updateIndex = useCallback(() => { + setLoading(true); + setError(null); + + try { + const sampleIndex: SkillIndex = { + version: 1, + lastUpdated: new Date().toISOString(), + skills: getSampleSkills(), + sources: [ + { + name: 'vercel-labs', + url: 'https://github.com/vercel-labs/agent-skills', + lastFetched: new Date().toISOString(), + skillCount: 5, + }, + { + name: 'anthropics', + url: 'https://github.com/anthropics/skills', + lastFetched: new Date().toISOString(), + skillCount: 3, + }, + ], + }; + + // Save index + const indexDir = join(process.env.HOME || '~', '.skillkit'); + if (!existsSync(indexDir)) { + mkdirSync(indexDir, { recursive: true }); + } + + writeFileSync(INDEX_PATH, JSON.stringify(sampleIndex, null, 2)); + setIndexStatus('fresh'); + + // Reload recommendations + loadRecommendations(); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to update index'); + setLoading(false); + } + }, [loadRecommendations]); + + const search = useCallback((query: string) => { + if (!query.trim()) { + setSearchResults([]); + return; + } + + const results = engine.search({ + query, + limit: 10, + semantic: true, + }); + + // Convert SearchResult to ScoredSkill for consistency + const scoredResults: ScoredSkill[] = results.map(r => ({ + skill: r.skill, + score: r.relevance, + reasons: r.matchedTerms.map(term => ({ + category: 'tag' as const, + description: `Matched: ${term}`, + weight: 0, + matched: [term], + })), + warnings: [], + })); + + setSearchResults(scoredResults); + }, [engine]); + + const refresh = useCallback(() => { + loadRecommendations(); + }, [loadRecommendations]); + + // Initial load + useEffect(() => { + loadRecommendations(); + }, [loadRecommendations]); + + return { + recommendations, + profile, + loading, + error, + totalScanned, + indexStatus, + refresh, + updateIndex, + search, + searchResults, + }; +} diff --git a/packages/tui/src/hooks/useSkills.ts b/packages/tui/src/hooks/useSkills.ts new file mode 100644 index 00000000..c92160b6 --- /dev/null +++ b/packages/tui/src/hooks/useSkills.ts @@ -0,0 +1,61 @@ +import { useState, useEffect } from 'react'; +import { findAllSkills } from '@skillkit/core'; +import { getSearchDirs } from '../helpers.js'; +import type { SkillItem } from '../components/SkillList.js'; + +interface UseSkillsResult { + skills: SkillItem[]; + loading: boolean; + error: string | null; + refresh: () => void; + remove: (name: string) => Promise; +} + +export function useSkills(): UseSkillsResult { + const [skills, setSkills] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + const refresh = () => { + setLoading(true); + setError(null); + + try { + const searchDirs = getSearchDirs(); + const foundSkills = findAllSkills(searchDirs); + + const skillItems: SkillItem[] = foundSkills.map((s) => ({ + name: s.name, + description: s.description, + source: s.metadata?.source, + enabled: s.enabled, + })); + + setSkills(skillItems); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load skills'); + } finally { + setLoading(false); + } + }; + + const remove = async (name: string) => { + const { rmSync } = await import('node:fs'); + const foundSkill = skills.find(s => s.name === name); + if (foundSkill) { + const searchDirs = getSearchDirs(); + const allSkills = findAllSkills(searchDirs); + const skill = allSkills.find(s => s.name === name); + if (skill) { + rmSync(skill.path, { recursive: true, force: true }); + refresh(); + } + } + }; + + useEffect(() => { + refresh(); + }, []); + + return { skills, loading, error, refresh, remove }; +} diff --git a/packages/tui/src/index.tsx b/packages/tui/src/index.tsx new file mode 100644 index 00000000..c94f8fd3 --- /dev/null +++ b/packages/tui/src/index.tsx @@ -0,0 +1,22 @@ +import { render } from 'ink'; +import { App } from './App.js'; + +export function startTUI(): Promise { + process.stdout.write('\x1B[2J\x1B[0f'); + + const { waitUntilExit, clear } = render(, { + exitOnCtrlC: true, + }); + + return waitUntilExit().then(() => { + clear(); + }); +} + +// Re-export types and components for external use +export type { Screen } from './App.js'; +export { App } from './App.js'; +export * from './components/index.js'; +export * from './screens/index.js'; +export * from './hooks/index.js'; +export * from './theme.js'; diff --git a/packages/tui/src/screens/Browse.tsx b/packages/tui/src/screens/Browse.tsx new file mode 100644 index 00000000..18ee0d8a --- /dev/null +++ b/packages/tui/src/screens/Browse.tsx @@ -0,0 +1,222 @@ +import { useState } from 'react'; +import { existsSync, mkdirSync, cpSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { Box, Text, useInput } from 'ink'; +import { colors, symbols } from '../theme.js'; +import { useMarketplace } from '../hooks/useMarketplace.js'; +import { detectProvider, type AgentType, type SkillMetadata } from '@skillkit/core'; +import { detectAgent, getAdapter, getAllAdapters } from '@skillkit/agents'; +import { getInstallDir, saveSkillMetadata } from '../helpers.js'; + +type View = 'repos' | 'skills' | 'agents'; + +interface Props { + cols?: number; + rows?: number; +} + +export function Browse({ rows = 24 }: Props) { + const { repos, skills, loading, currentRepo, fetchRepo, fetchAllRepos } = useMarketplace(); + const [view, setView] = useState('repos'); + const [sel, setSel] = useState(0); + const [installing, setInstalling] = useState(null); + const [message, setMessage] = useState(null); + const [selectedSkill, setSelectedSkill] = useState<{ name: string; source: string } | null>(null); + const [agents, setAgents] = useState<{ type: AgentType; name: string; detected: boolean }[]>([]); + + const items = view === 'repos' ? repos : view === 'skills' ? skills : agents; + const maxVisible = Math.max(5, rows - 8); + const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), items.length - maxVisible)); + const visible = items.slice(start, start + maxVisible); + + const showAgentSelection = async (skillName: string, source: string) => { + setSelectedSkill({ name: skillName, source }); + const adapters = getAllAdapters(); + const agentList: typeof agents = []; + for (const a of adapters) { + agentList.push({ + type: a.type as AgentType, + name: a.name, + detected: await a.isDetected(), + }); + } + setAgents(agentList); + setView('agents'); + setSel(0); + }; + + const installSkill = async (skillName: string, source: string, agentType?: AgentType) => { + setInstalling(skillName); + setMessage(null); + + try { + const provider = detectProvider(source); + if (!provider) { + setMessage(`Error: Unknown provider for ${source}`); + setInstalling(null); + return; + } + + const result = await provider.clone(source, '', { depth: 1 }); + + if (!result.success || !result.discoveredSkills) { + setMessage(`Error: ${result.error || 'Failed to fetch'}`); + setInstalling(null); + return; + } + + const skill = result.discoveredSkills.find(s => s.name === skillName); + if (!skill) { + setMessage(`Error: Skill ${skillName} not found`); + setInstalling(null); + return; + } + + const targetAgentType = agentType || await detectAgent(); + const adapter = getAdapter(targetAgentType); + const installDir = getInstallDir(false, targetAgentType); + + if (!existsSync(installDir)) { + mkdirSync(installDir, { recursive: true }); + } + + const targetPath = join(installDir, skillName); + + if (existsSync(targetPath)) { + rmSync(targetPath, { recursive: true, force: true }); + } + + cpSync(skill.path, targetPath, { recursive: true, dereference: true }); + + const metadata: SkillMetadata = { + name: skillName, + description: '', + source: source, + sourceType: provider.type, + subpath: skillName, + installedAt: new Date().toISOString(), + enabled: true, + }; + saveSkillMetadata(targetPath, metadata); + + if (result.tempRoot) { + rmSync(result.tempRoot, { recursive: true, force: true }); + } + + setMessage(`✓ Installed ${skillName} to ${adapter.name}`); + if (!agentType) { + setView('skills'); + } + } catch (err) { + setMessage(`Error: ${err instanceof Error ? err.message : 'Unknown error'}`); + } finally { + setInstalling(null); + if (agentType) { + setSelectedSkill(null); + } + } + }; + + useInput((input, key) => { + if (loading || installing) return; + + if (key.upArrow) setSel(i => Math.max(0, i - 1)); + else if (key.downArrow) setSel(i => Math.min(items.length - 1, i + 1)); + else if (key.return) { + if (view === 'repos' && repos[sel]) { + fetchRepo(repos[sel].source); + setView('skills'); + setSel(0); + setMessage(null); + } else if (view === 'skills' && skills[sel]?.source) { + installSkill(skills[sel].name, skills[sel].source); + } else if (view === 'agents' && agents[sel]) { + installSkill(selectedSkill!.name, selectedSkill!.source, agents[sel].type); + } + } + else if (input === 'm' && view === 'skills' && skills[sel]?.source) { + showAgentSelection(skills[sel].name, skills[sel].source!); + } + else if (input === 'r') { + if (view === 'skills') { + setView('repos'); + setSel(0); + setMessage(null); + } else if (view === 'agents') { + setView('skills'); + setSel(0); + } + } + else if (input === 'a' && view === 'repos') { + fetchAllRepos(); + setView('skills'); + setSel(0); + } + }); + + if (view === 'agents') { + return ( + + SELECT AGENT + Install "{selectedSkill?.name}" to which agent? + (All agents supported - directory created if needed) + + + {visible.map((agent, i) => { + const idx = start + i; + const isSel = idx === sel; + const a = agent as typeof agents[0]; + const status = a.detected ? '(ready)' : '(will create)'; + return ( + + {isSel ? symbols.pointer : ' '} {a.name.padEnd(20)} {status} + + ); + })} + + + + Enter=install to selected agent r=back q=quit + + + ); + } + + return ( + + {view === 'repos' ? 'REPOSITORIES' : 'SKILLS'} + {loading && Loading {currentRepo}...} + {installing && Installing {installing}...} + {message && {message}} + {items.length} items + + + {start > 0 && ↑ {start} more} + {visible.map((item, i) => { + const idx = start + i; + const isSel = idx === sel; + const name = view === 'repos' + ? (item as typeof repos[0]).name + : (item as typeof skills[0]).name; + const src = view === 'repos' + ? (item as typeof repos[0]).source + : (item as typeof skills[0]).source || ''; + return ( + + {isSel ? symbols.pointer : ' '}{name.padEnd(25)} {src} + + ); + })} + {start + maxVisible < items.length && ↓ {items.length - start - maxVisible} more} + + + + + {view === 'repos' + ? 'Enter=fetch a=all q=quit' + : 'Enter=quick install m=choose agent r=back q=quit'} + + + + ); +} diff --git a/packages/tui/src/screens/Context.tsx b/packages/tui/src/screens/Context.tsx new file mode 100644 index 00000000..3f87656f --- /dev/null +++ b/packages/tui/src/screens/Context.tsx @@ -0,0 +1,276 @@ +import { useState, useEffect } from 'react'; +import { Box, Text, useInput } from 'ink'; +import { colors, symbols } from '../theme.js'; +import { + loadContext, + initContext, + syncToAgent, + type ProjectContext, + type AgentType, +} from '@skillkit/core'; +import { getAllAdapters } from '@skillkit/agents'; + +type View = 'overview' | 'sync'; + +interface AgentItem { + type: AgentType; + name: string; + detected: boolean; + synced?: boolean; +} + +interface Props { + cols?: number; + rows?: number; +} + +export function Context({ rows = 24 }: Props) { + const [view, setView] = useState('overview'); + const [context, setContext] = useState(null); + const [loading, setLoading] = useState(true); + const [initializing, setInitializing] = useState(false); + const [syncing, setSyncing] = useState(false); + const [agents, setAgents] = useState([]); + const [sel, setSel] = useState(0); + const [message, setMessage] = useState(null); + const [error, setError] = useState(null); + + const projectPath = process.cwd(); + + useEffect(() => { + const load = async () => { + setLoading(true); + try { + const ctx = loadContext(projectPath); + setContext(ctx); + + const adapters = getAllAdapters(); + const agentList: AgentItem[] = []; + for (const a of adapters) { + const detected = await a.isDetected(); + agentList.push({ + type: a.type as AgentType, + name: a.name, + detected, + synced: ctx?.agents?.synced?.includes(a.type), + }); + } + setAgents(agentList); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to load context'); + } finally { + setLoading(false); + } + }; + + load(); + }, [projectPath]); + + const maxVisible = Math.max(5, rows - 14); + const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), agents.length - maxVisible)); + const visible = agents.slice(start, start + maxVisible); + + const handleInit = () => { + setInitializing(true); + setMessage(null); + setError(null); + + try { + const newContext = initContext(projectPath); + setContext(newContext); + setMessage('Context initialized successfully'); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to initialize context'); + } finally { + setInitializing(false); + } + }; + + const handleSync = async (agentType: AgentType) => { + setSyncing(true); + setMessage(null); + setError(null); + + try { + await syncToAgent(agentType, projectPath); + + setAgents(prev => + prev.map(a => + a.type === agentType ? { ...a, synced: true } : a + ) + ); + + setMessage(`Synced to ${agentType} successfully`); + } catch (err) { + setError(err instanceof Error ? err.message : 'Sync failed'); + } finally { + setSyncing(false); + } + }; + + const handleSyncAll = async () => { + setSyncing(true); + setMessage(null); + setError(null); + + try { + const detectedAgents = agents.filter(a => a.detected); + for (const agent of detectedAgents) { + await syncToAgent(agent.type, projectPath); + } + + setAgents(prev => + prev.map(a => + a.detected ? { ...a, synced: true } : a + ) + ); + + setMessage(`Synced to ${detectedAgents.length} agents`); + } catch (err) { + setError(err instanceof Error ? err.message : 'Sync failed'); + } finally { + setSyncing(false); + } + }; + + useInput((input, key) => { + if (loading || initializing || syncing) return; + + if (view === 'sync') { + if (key.upArrow) setSel(i => Math.max(0, i - 1)); + else if (key.downArrow) setSel(i => Math.min(agents.length - 1, i + 1)); + else if (key.return && agents[sel]) { + handleSync(agents[sel].type); + } + else if (key.escape) { + setView('overview'); + setSel(0); + } + else if (input === 'a') { + handleSyncAll(); + } + } else if (view === 'overview') { + if (input === 'i') handleInit(); + else if (input === 's') { + setView('sync'); + setSel(0); + } + } + }); + + if (loading) { + return ( + + PROJECT CONTEXT + Loading... + + ); + } + + if (view === 'sync') { + return ( + + SYNC TO AGENTS + Select an agent to sync your project context + + {message && {'✓'} {message}} + {error && {'✗'} {error}} + {syncing && Syncing...} + + + {start > 0 && ↑ {start} more} + {visible.map((agent, i) => { + const idx = start + i; + const isSel = idx === sel; + const status = agent.synced + ? '(synced)' + : agent.detected + ? '(ready)' + : '(not detected)'; + const statusColor = agent.synced ? 'green' : agent.detected ? 'yellow' : 'gray'; + + return ( + + {isSel ? symbols.pointer : ' '} {agent.name.padEnd(20)} + {status} + + ); + })} + {start + maxVisible < agents.length && ( + ↓ {agents.length - start - maxVisible} more + )} + + + + Enter=sync to agent a=sync all detected Esc=back q=quit + + + ); + } + + const stack = context?.stack; + const detectedCount = agents.filter(a => a.detected).length; + const syncedCount = agents.filter(a => a.synced).length; + + return ( + + PROJECT CONTEXT + + {message && {'✓'} {message}} + {error && {'✗'} {error}} + {initializing && Initializing...} + + {!context && ( + + No context found. + Press 'i' to initialize and analyze your project. + + )} + + {context && ( + <> + + Project: + Name: {context.project?.name || 'Unknown'} + Type: {context.project?.type || 'Not detected'} + + + + Stack: + {stack?.languages && stack.languages.length > 0 && ( + Languages: {stack.languages.map(l => l.name).join(', ')} + )} + {stack?.frameworks && stack.frameworks.length > 0 && ( + Frameworks: {stack.frameworks.map(f => f.name).join(', ')} + )} + {stack?.libraries && stack.libraries.length > 0 && ( + Libraries: {stack.libraries.slice(0, 5).map(l => l.name).join(', ')}{stack.libraries.length > 5 ? '...' : ''} + )} + {(!stack?.languages?.length && !stack?.frameworks?.length) && ( + No stack detected. Press 'i' to re-analyze. + )} + + + + Agents: + Detected: {detectedCount} agents + Synced: {syncedCount} agents + {detectedCount > 0 && ( + ({agents.filter(a => a.detected).map(a => a.name).join(', ')}) + )} + + + )} + + + Actions: + [i] Initialize/refresh context + [s] Sync to agents + + + + i=init context s=sync to agents q=quit + + + ); +} diff --git a/packages/tui/src/screens/Home.tsx b/packages/tui/src/screens/Home.tsx new file mode 100644 index 00000000..822e558d --- /dev/null +++ b/packages/tui/src/screens/Home.tsx @@ -0,0 +1,100 @@ +import { useState, useEffect } from 'react'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { dirname, join } from 'node:path'; +import { Box, Text } from 'ink'; +import { colors, logo } from '../theme.js'; +import type { Screen } from '../App.js'; + +interface HomeProps { + onNavigate: (screen: Screen) => void; + cols?: number; + rows?: number; +} + +const CHARS = '01█▓▒░╔╗╚╝║═'; + +const logoSmall = ` +╔═╗╦╔═╦╦ ╦ ╦╔═╦╔╦╗ +╚═╗╠╩╗║║ ║ ╠╩╗║ ║ +╚═╝╩ ╩╩╩═╝╩═╝╩ ╩╩ ╩ +`.trim(); + +function getVersion(): string { + try { + const __filename = fileURLToPath(import.meta.url); + const __dirname = dirname(__filename); + const packageJsonPath = join(__dirname, '../../../package.json'); + const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')); + return packageJson.version || '1.2.0'; + } catch { + return '1.2.0'; + } +} + +function scramble(target: string, progress: number): string { + return target.split('\n').map(line => { + return line.split('').map((char, i) => { + if (char === ' ') return char; + if (progress > (i / line.length) * 100) return char; + return CHARS[Math.floor(Math.random() * CHARS.length)]; + }).join(''); + }).join('\n'); +} + +export function Home({ cols = 80, rows = 24 }: HomeProps) { + const [progress, setProgress] = useState(0); + const [display, setDisplay] = useState(''); + const version = getVersion(); + + const useLogo = cols < 80 ? logoSmall : logo; + + useEffect(() => { + if (progress >= 100) { + setDisplay(useLogo); + return; + } + const t = setInterval(() => { + setProgress(p => { + const next = p + 12; + setDisplay(scramble(useLogo, next)); + return next; + }); + }, 35); + return () => clearInterval(t); + }, [progress, useLogo]); + + return ( + + {display || useLogo} + + + Manage AI agent skills from your terminal. + + + + Quick Actions: + [b] Browse skills marketplace + [r] Get smart recommendations + [t] Translate skills between agents + [c] Manage project context + [l] View installed skills + [s] Sync skills across agents + + + {rows >= 18 && ( + + Navigation: + ↑↓ Navigate lists + Enter Select / Confirm + Esc Go back / Home + q Quit + + )} + + + v{version} - Works with 17 AI agents + + + ); +} diff --git a/packages/tui/src/screens/Installed.tsx b/packages/tui/src/screens/Installed.tsx new file mode 100644 index 00000000..a19f2e2f --- /dev/null +++ b/packages/tui/src/screens/Installed.tsx @@ -0,0 +1,59 @@ +import { useState } from 'react'; +import { Box, Text, useInput } from 'ink'; +import { colors, symbols } from '../theme.js'; +import { useSkills } from '../hooks/useSkills.js'; + +interface Props { + cols?: number; + rows?: number; +} + +export function Installed({ rows = 24 }: Props) { + const { skills, loading, refresh, remove } = useSkills(); + const [sel, setSel] = useState(0); + + const maxVisible = Math.max(5, rows - 6); + const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), skills.length - maxVisible)); + const visible = skills.slice(start, start + maxVisible); + + useInput((input, key) => { + if (loading) return; + if (key.upArrow) setSel(i => Math.max(0, i - 1)); + else if (key.downArrow) setSel(i => Math.min(skills.length - 1, i + 1)); + else if (input === 'r') refresh(); + else if (input === 'd' && skills[sel]) remove(skills[sel].name); + }); + + return ( + + INSTALLED SKILLS + {skills.length} skills + + {loading && Loading...} + + {!loading && skills.length === 0 && ( + No skills installed. Press b to browse. + )} + + {!loading && skills.length > 0 && ( + + {start > 0 && ↑ {start} more} + {visible.map((skill, i) => { + const idx = start + i; + const isSel = idx === sel; + return ( + + {isSel ? symbols.pointer : ' '}{skill.name.padEnd(30)} {skill.source && {skill.source}} + + ); + })} + {start + maxVisible < skills.length && ↓ {skills.length - start - maxVisible} more} + + )} + + + r=refresh d=delete q=quit + + + ); +} diff --git a/packages/tui/src/screens/Recommend.tsx b/packages/tui/src/screens/Recommend.tsx new file mode 100644 index 00000000..fd50bd3f --- /dev/null +++ b/packages/tui/src/screens/Recommend.tsx @@ -0,0 +1,353 @@ +import { useState } from 'react'; +import { existsSync, mkdirSync, cpSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { Box, Text, useInput } from 'ink'; +import { colors, symbols } from '../theme.js'; +import { useRecommend } from '../hooks/useRecommend.js'; +import { detectProvider, type AgentType, type SkillMetadata } from '@skillkit/core'; +import { detectAgent, getAdapter, getAllAdapters } from '@skillkit/agents'; +import { getInstallDir, saveSkillMetadata } from '../helpers.js'; + +type View = 'recommendations' | 'search' | 'agents'; + +interface Props { + cols?: number; + rows?: number; +} + +export function Recommend({ rows = 24 }: Props) { + const { + recommendations, + profile, + loading, + error, + totalScanned, + indexStatus, + refresh, + updateIndex, + search, + searchResults, + } = useRecommend(); + + const [view, setView] = useState('recommendations'); + const [sel, setSel] = useState(0); + const [searchQuery, setSearchQuery] = useState(''); + const [searchMode, setSearchMode] = useState(false); + const [installing, setInstalling] = useState(null); + const [message, setMessage] = useState(null); + const [selectedSkill, setSelectedSkill] = useState<{ name: string; source: string } | null>(null); + const [agents, setAgents] = useState<{ type: AgentType; name: string; detected: boolean }[]>([]); + + const items = view === 'recommendations' + ? recommendations + : view === 'search' + ? searchResults + : agents; + + const maxVisible = Math.max(5, rows - 10); + const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), items.length - maxVisible)); + const visible = items.slice(start, start + maxVisible); + + const showAgentSelection = async (skillName: string, source: string) => { + setSelectedSkill({ name: skillName, source }); + const adapters = getAllAdapters(); + const agentList: typeof agents = []; + for (const a of adapters) { + agentList.push({ + type: a.type as AgentType, + name: a.name, + detected: await a.isDetected(), + }); + } + setAgents(agentList); + setView('agents'); + setSel(0); + }; + + const installSkill = async (skillName: string, source: string, agentType?: AgentType) => { + if (!source) { + setMessage('Error: No source available for this skill'); + return; + } + + setInstalling(skillName); + setMessage(null); + + try { + const provider = detectProvider(source); + if (!provider) { + setMessage(`Error: Unknown provider for ${source}`); + setInstalling(null); + return; + } + + const result = await provider.clone(source, '', { depth: 1 }); + + if (!result.success || !result.discoveredSkills) { + setMessage(`Error: ${result.error || 'Failed to fetch'}`); + setInstalling(null); + return; + } + + const skill = result.discoveredSkills.find(s => s.name === skillName); + if (!skill) { + setMessage(`Error: Skill ${skillName} not found in repo`); + setInstalling(null); + return; + } + + const targetAgentType = agentType || await detectAgent(); + const adapter = getAdapter(targetAgentType); + const installDir = getInstallDir(false, targetAgentType); + + if (!existsSync(installDir)) { + mkdirSync(installDir, { recursive: true }); + } + + const targetPath = join(installDir, skillName); + + if (existsSync(targetPath)) { + rmSync(targetPath, { recursive: true, force: true }); + } + + cpSync(skill.path, targetPath, { recursive: true, dereference: true }); + + const metadata: SkillMetadata = { + name: skillName, + description: '', + source: source, + sourceType: provider.type, + subpath: skillName, + installedAt: new Date().toISOString(), + enabled: true, + }; + saveSkillMetadata(targetPath, metadata); + + if (result.tempRoot) { + rmSync(result.tempRoot, { recursive: true, force: true }); + } + + setMessage(`✓ Installed ${skillName} to ${adapter.name}`); + } catch (err) { + setMessage(`Error: ${err instanceof Error ? err.message : 'Unknown error'}`); + } finally { + setInstalling(null); + if (agentType) { + setSelectedSkill(null); + setView('recommendations'); + } + } + }; + + useInput((input, key) => { + if (loading || installing) return; + + // Handle search input mode + if (searchMode) { + if (key.escape) { + setSearchMode(false); + setSearchQuery(''); + setView('recommendations'); + return; + } + if (key.return) { + setSearchMode(false); + if (searchQuery.trim()) { + search(searchQuery); + setView('search'); + setSel(0); + } + return; + } + if (key.backspace || key.delete) { + setSearchQuery(q => q.slice(0, -1)); + return; + } + if (input && !key.ctrl && !key.meta) { + setSearchQuery(q => q + input); + return; + } + return; + } + + // Navigation + if (key.upArrow) setSel(i => Math.max(0, i - 1)); + else if (key.downArrow) setSel(i => Math.min(items.length - 1, i + 1)); + else if (key.return) { + if (view === 'agents' && agents[sel]) { + installSkill(selectedSkill!.name, selectedSkill!.source, agents[sel].type); + } else if ((view === 'recommendations' || view === 'search') && items[sel]) { + const skill = items[sel] as typeof recommendations[0]; + if (skill.skill.source) { + installSkill(skill.skill.name, skill.skill.source); + } + } + } + // Actions + else if (input === '/') { + setSearchMode(true); + setSearchQuery(''); + } + else if (input === 'm' && (view === 'recommendations' || view === 'search') && items[sel]) { + const skill = items[sel] as typeof recommendations[0]; + if (skill.skill.source) { + showAgentSelection(skill.skill.name, skill.skill.source); + } + } + else if (input === 'u') { + updateIndex(); + } + else if (input === 'r' && view !== 'recommendations') { + if (view === 'agents') { + setView('recommendations'); + } else { + setView('recommendations'); + setSearchQuery(''); + } + setSel(0); + } + else if (input === 'R') { + refresh(); + } + }); + + // Agent selection view + if (view === 'agents') { + return ( + + SELECT AGENT + Install "{selectedSkill?.name}" to which agent? + + + {visible.map((agent, i) => { + const idx = start + i; + const isSel = idx === sel; + const a = agent as typeof agents[0]; + const status = a.detected ? '(ready)' : '(will create)'; + return ( + + {isSel ? symbols.pointer : ' '} {a.name.padEnd(20)} {status} + + ); + })} + + + + Enter=install r=back q=quit + + + ); + } + + // Score bar helper + const getScoreBar = (score: number): string => { + const filled = Math.round(score / 10); + const empty = 10 - filled; + return '█'.repeat(filled) + '░'.repeat(empty); + }; + + const getScoreColor = (score: number) => { + if (score >= 70) return 'green'; + if (score >= 50) return 'yellow'; + return 'gray'; + }; + + return ( + + + {view === 'search' ? `SEARCH: "${searchQuery}"` : 'RECOMMENDATIONS'} + + + {/* Status bar */} + {loading && Loading...} + {installing && Installing {installing}...} + {message && {message}} + {error && {error}} + + {/* Search input */} + {searchMode && ( + + Search: {searchQuery} + █ + + )} + + {/* Index status warning */} + {indexStatus === 'missing' && !loading && ( + + No skill index found. + Press 'u' to update index from known sources. + + )} + + {indexStatus === 'stale' && !loading && ( + Index may be outdated. Press 'u' to update. + )} + + {/* Profile info */} + {profile && !searchMode && ( + + + Project: {profile.name} + {profile.type ? ` (${profile.type})` : ''} + + {profile.stack.languages.length > 0 && ( + + Stack: {profile.stack.languages.map(l => l.name).join(', ')} + {profile.stack.frameworks.length > 0 && `, ${profile.stack.frameworks.map(f => f.name).join(', ')}`} + + )} + + )} + + {/* Item count */} + {!searchMode && ( + + {view === 'search' + ? `${searchResults.length} results` + : `${recommendations.length} of ${totalScanned} skills matched`} + + )} + + {/* List */} + + {start > 0 && ↑ {start} more} + {visible.map((item, i) => { + const idx = start + i; + const isSel = idx === sel; + const skill = (item as typeof recommendations[0]).skill; + const score = (item as typeof recommendations[0]).score; + + return ( + + + {isSel ? symbols.pointer : ' '} + {score.toString().padStart(3)}% + {' '} + {getScoreBar(score)} + {' '} + {skill.name} + + {isSel && skill.description && ( + {skill.description.slice(0, 60)}{skill.description.length > 60 ? '...' : ''} + )} + {isSel && skill.source && ( + Source: {skill.source} + )} + + ); + })} + {start + maxVisible < items.length && ↓ {items.length - start - maxVisible} more} + + + {/* Help bar */} + + + {view === 'search' + ? 'Enter=install m=choose agent /=search r=back u=update q=quit' + : 'Enter=install m=choose agent /=search u=update R=refresh q=quit'} + + + + ); +} diff --git a/packages/tui/src/screens/Settings.tsx b/packages/tui/src/screens/Settings.tsx new file mode 100644 index 00000000..79d0c86f --- /dev/null +++ b/packages/tui/src/screens/Settings.tsx @@ -0,0 +1,45 @@ +import { useState } from 'react'; +import { Box, Text, useInput } from 'ink'; +import { colors, symbols } from '../theme.js'; + +interface Props { + cols?: number; + rows?: number; +} + +const SETTINGS = [ + { id: 'agent', label: 'Default Agent', value: 'auto-detect' }, + { id: 'sync', label: 'Auto Sync', value: 'disabled' }, + { id: 'cache', label: 'Cache Dir', value: '~/.skillkit/cache' }, +]; + +export function Settings({}: Props) { + const [sel, setSel] = useState(0); + + useInput((_, key) => { + if (key.upArrow) setSel(i => Math.max(0, i - 1)); + else if (key.downArrow) setSel(i => Math.min(SETTINGS.length - 1, i + 1)); + }); + + return ( + + SETTINGS + Configure SkillKit + + + {SETTINGS.map((s, i) => { + const isSel = i === sel; + return ( + + {isSel ? symbols.pointer : ' '}{s.label.padEnd(16)} {s.value} + + ); + })} + + + + Enter=edit q=quit + + + ); +} diff --git a/packages/tui/src/screens/Sync.tsx b/packages/tui/src/screens/Sync.tsx new file mode 100644 index 00000000..66db7e5d --- /dev/null +++ b/packages/tui/src/screens/Sync.tsx @@ -0,0 +1,78 @@ +import { useState, useEffect } from 'react'; +import { Box, Text, useInput } from 'ink'; +import { colors, symbols } from '../theme.js'; +import { getAllAdapters } from '@skillkit/agents'; + +interface AgentStatus { + name: string; + type: string; + detected: boolean; +} + +interface Props { + cols?: number; + rows?: number; +} + +export function Sync({ rows = 24 }: Props) { + const [agents, setAgents] = useState([]); + const [loading, setLoading] = useState(true); + const [sel, setSel] = useState(0); + const [syncing, setSyncing] = useState(false); + + const maxVisible = Math.max(5, rows - 6); + const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), agents.length - maxVisible)); + const visible = agents.slice(start, start + maxVisible); + + useEffect(() => { + (async () => { + const adapters = getAllAdapters(); + const s: AgentStatus[] = []; + for (const a of adapters) { + s.push({ name: a.name, type: a.type, detected: await a.isDetected() }); + } + setAgents(s); + setLoading(false); + })(); + }, []); + + useInput((input, key) => { + if (loading || syncing) return; + if (key.upArrow) setSel(i => Math.max(0, i - 1)); + else if (key.downArrow) setSel(i => Math.min(agents.length - 1, i + 1)); + else if (input === 'a') { setSyncing(true); setTimeout(() => setSyncing(false), 500); } + else if (key.return && agents[sel]?.detected) { setSyncing(true); setTimeout(() => setSyncing(false), 300); } + }); + + const detected = agents.filter(a => a.detected).length; + + return ( + + SYNC SKILLS + {detected}/{agents.length} agents detected + + {loading && Detecting agents...} + {syncing && Syncing...} + + {!loading && !syncing && ( + + {start > 0 && ↑ {start} more} + {visible.map((agent, i) => { + const idx = start + i; + const isSel = idx === sel; + return ( + + {isSel ? symbols.pointer : ' '}{agent.detected ? symbols.checkboxOn : symbols.checkboxOff} {agent.name.padEnd(20)} {agent.detected ? 'Ready' : 'N/A'} + + ); + })} + {start + maxVisible < agents.length && ↓ {agents.length - start - maxVisible} more} + + )} + + + Enter=sync a=all q=quit + + + ); +} diff --git a/packages/tui/src/screens/Translate.tsx b/packages/tui/src/screens/Translate.tsx new file mode 100644 index 00000000..d895b611 --- /dev/null +++ b/packages/tui/src/screens/Translate.tsx @@ -0,0 +1,286 @@ +import { useState, useEffect } from 'react'; +import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { Box, Text, useInput } from 'ink'; +import { colors, symbols } from '../theme.js'; +import { + translateSkill, + getSupportedTranslationAgents, + type AgentType, +} from '@skillkit/core'; +import { getAllAdapters, getAdapter } from '@skillkit/agents'; +import { getInstallDir } from '../helpers.js'; + +type View = 'skills' | 'agents' | 'preview' | 'result'; + +interface InstalledSkill { + name: string; + path: string; + content: string; +} + +interface Props { + cols?: number; + rows?: number; +} + +export function Translate({ rows = 24 }: Props) { + const [view, setView] = useState('skills'); + const [skills, setSkills] = useState([]); + const [agents, setAgents] = useState<{ type: AgentType; name: string }[]>([]); + const [sel, setSel] = useState(0); + const [selectedSkill, setSelectedSkill] = useState(null); + const [selectedAgent, setSelectedAgent] = useState<{ type: AgentType; name: string } | null>(null); + const [preview, setPreview] = useState(''); + const [result, setResult] = useState<{ success: boolean; message: string; path?: string } | null>(null); + const [loading, setLoading] = useState(false); + + useEffect(() => { + const loadSkills = () => { + const installDir = getInstallDir(false); + const foundSkills: InstalledSkill[] = []; + + if (existsSync(installDir)) { + const dirs = readdirSync(installDir, { withFileTypes: true }) + .filter(d => d.isDirectory()) + .map(d => d.name); + + for (const dir of dirs) { + const skillPath = join(installDir, dir); + const skillMdPath = join(skillPath, 'SKILL.md'); + + if (existsSync(skillMdPath)) { + const content = readFileSync(skillMdPath, 'utf-8'); + foundSkills.push({ + name: dir, + path: skillPath, + content, + }); + } + } + } + + setSkills(foundSkills); + }; + + loadSkills(); + }, []); + + useEffect(() => { + const adapters = getAllAdapters(); + const supportedAgents = getSupportedTranslationAgents(); + const agentList = adapters + .filter(a => supportedAgents.includes(a.type as AgentType)) + .map(a => ({ + type: a.type as AgentType, + name: a.name, + })); + setAgents(agentList); + }, []); + + const currentItems = view === 'skills' ? skills : agents; + const maxVisible = Math.max(5, rows - 12); + const start = Math.max(0, Math.min(sel - Math.floor(maxVisible / 2), currentItems.length - maxVisible)); + const visible = currentItems.slice(start, start + maxVisible); + + const generatePreview = (skill: InstalledSkill, agent: { type: AgentType; name: string }) => { + try { + const result = translateSkill(skill.content, agent.type, { sourceFilename: 'SKILL.md' }); + return result.content; + } catch (err) { + return `Error: ${err instanceof Error ? err.message : 'Translation failed'}`; + } + }; + + const executeTranslation = () => { + if (!selectedSkill || !selectedAgent) return; + + setLoading(true); + try { + const translationResult = translateSkill(selectedSkill.content, selectedAgent.type, { + sourceFilename: 'SKILL.md', + }); + + if (!translationResult.success) { + setResult({ + success: false, + message: `Translation failed: ${translationResult.warnings.join(', ')}`, + }); + setLoading(false); + return; + } + + const adapter = getAdapter(selectedAgent.type); + const targetDir = adapter?.skillsDir + ? join(process.cwd(), adapter.skillsDir) + : join(process.cwd(), `.${selectedAgent.type}/skills/`); + + if (!existsSync(targetDir)) { + mkdirSync(targetDir, { recursive: true }); + } + + const filename = translationResult.filename || `${selectedSkill.name}.md`; + const targetPath = join(targetDir, filename); + + writeFileSync(targetPath, translationResult.content, 'utf-8'); + + setResult({ + success: true, + message: `Translated ${selectedSkill.name} to ${selectedAgent.name} format`, + path: targetPath, + }); + } catch (err) { + setResult({ + success: false, + message: `Error: ${err instanceof Error ? err.message : 'Unknown error'}`, + }); + } finally { + setLoading(false); + setView('result'); + } + }; + + useInput((_input, key) => { + if (loading) return; + + if (key.upArrow) setSel(i => Math.max(0, i - 1)); + else if (key.downArrow) setSel(i => Math.min(currentItems.length - 1, i + 1)); + else if (key.escape) { + if (view === 'result') { + setView('skills'); + setSelectedSkill(null); + setSelectedAgent(null); + setResult(null); + setSel(0); + } else if (view === 'preview') { + setView('agents'); + } else if (view === 'agents') { + setView('skills'); + setSelectedSkill(null); + } + } + else if (key.return) { + if (view === 'skills' && skills[sel]) { + setSelectedSkill(skills[sel]); + setView('agents'); + setSel(0); + } else if (view === 'agents' && agents[sel]) { + setSelectedAgent(agents[sel]); + const previewContent = generatePreview(selectedSkill!, agents[sel]); + setPreview(previewContent); + setView('preview'); + } else if (view === 'preview') { + executeTranslation(); + } else if (view === 'result') { + setView('skills'); + setSelectedSkill(null); + setSelectedAgent(null); + setResult(null); + setSel(0); + } + } + }); + + if (view === 'result' && result) { + return ( + + TRANSLATION {result.success ? 'COMPLETE' : 'FAILED'} + + + + {result.success ? '✓' : '✗'} {result.message} + + {result.path && ( + Saved to: {result.path} + )} + + + + Press Enter or Esc to continue + + + ); + } + + if (view === 'preview') { + const previewLines = preview.split('\n').slice(0, maxVisible); + return ( + + TRANSLATION PREVIEW + + {selectedSkill?.name} → {selectedAgent?.name} + + + + {previewLines.map((line, i) => ( + {line.slice(0, 70)} + ))} + {preview.split('\n').length > maxVisible && ( + ... ({preview.split('\n').length - maxVisible} more lines) + )} + + + + Enter=confirm translation Esc=back + + + ); + } + + return ( + + + {view === 'skills' ? 'TRANSLATE SKILL' : 'SELECT TARGET AGENT'} + + + {view === 'skills' && ( + Select a skill to translate to another agent format + )} + + {view === 'agents' && selectedSkill && ( + Translate "{selectedSkill.name}" to which agent format? + )} + + {skills.length === 0 && view === 'skills' && ( + + No skills installed. Install some skills first with 'skillkit install' + + )} + + + {start > 0 && ↑ {start} more} + {visible.map((item, i) => { + const idx = start + i; + const isSel = idx === sel; + + if (view === 'skills') { + const skill = item as InstalledSkill; + return ( + + {isSel ? symbols.pointer : ' '} {skill.name} + + ); + } else { + const agent = item as { type: AgentType; name: string }; + return ( + + {isSel ? symbols.pointer : ' '} {agent.name.padEnd(20)} ({agent.type}) + + ); + } + })} + {start + maxVisible < currentItems.length && ( + ↓ {currentItems.length - start - maxVisible} more + )} + + + + + {view === 'skills' + ? 'Enter=select skill q=quit' + : 'Enter=select agent Esc=back q=quit'} + + + + ); +} diff --git a/packages/tui/src/screens/index.ts b/packages/tui/src/screens/index.ts new file mode 100644 index 00000000..db2db42c --- /dev/null +++ b/packages/tui/src/screens/index.ts @@ -0,0 +1,8 @@ +export { Home } from './Home.js'; +export { Browse } from './Browse.js'; +export { Installed } from './Installed.js'; +export { Sync } from './Sync.js'; +export { Settings } from './Settings.js'; +export { Recommend } from './Recommend.js'; +export { Translate } from './Translate.js'; +export { Context } from './Context.js'; diff --git a/packages/tui/src/theme.ts b/packages/tui/src/theme.ts new file mode 100644 index 00000000..6347fbac --- /dev/null +++ b/packages/tui/src/theme.ts @@ -0,0 +1,31 @@ +import chalk from 'chalk'; + +export const colors = { + primary: 'white', + secondary: 'white', + secondaryDim: 'gray', + success: 'white', + danger: 'white', + warning: 'white', + background: 'bgBlack', + borderDim: 'gray', +}; + +export const symbols = { + pointer: chalk.white('❯'), + bullet: '●', + checkboxOn: chalk.white('✔'), + checkboxOff: chalk.dim('✖'), + check: chalk.white('✓'), + star: '★', + spinner: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'], +}; + +export const logo = ` +███████╗██╗ ██╗██╗██╗ ██╗ ██╗ ██╗██╗████████╗ +██╔════╝██║ ██╔╝██║██║ ██║ ██║ ██╔╝██║╚══██╔══╝ +███████╗█████╔╝ ██║██║ ██║ █████╔╝ ██║ ██║ +╚════██║██╔═██╗ ██║██║ ██║ ██╔═██╗ ██║ ██║ +███████║██║ ██╗██║███████╗███████╗██║ ██╗██║ ██║ +╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ +`; diff --git a/packages/tui/tsconfig.json b/packages/tui/tsconfig.json new file mode 100644 index 00000000..c31fc650 --- /dev/null +++ b/packages/tui/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src", + "jsx": "react-jsx", + "esModuleInterop": true, + "composite": false + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/tui/tsup.config.ts b/packages/tui/tsup.config.ts new file mode 100644 index 00000000..88583915 --- /dev/null +++ b/packages/tui/tsup.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: ['src/index.tsx'], + format: ['esm'], + dts: true, + splitting: false, + sourcemap: true, + clean: true, + external: ['react', 'ink', 'ink-text-input'], + esbuildOptions(options) { + options.jsx = 'automatic'; + }, +}); diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 00000000..4e708bd3 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,3 @@ +packages: + - 'packages/*' + - 'apps/*' diff --git a/src/tui/hooks/useMarketplace.ts b/src/tui/hooks/useMarketplace.ts index fe471742..dfa5e127 100644 --- a/src/tui/hooks/useMarketplace.ts +++ b/src/tui/hooks/useMarketplace.ts @@ -38,9 +38,6 @@ const POPULAR_REPOS: RepoInfo[] = [ { source: 'giuseppe-trisciuoglio/developer-kit', name: 'Shadcn / Radix' }, { source: 'openrouterteam/agent-skills', name: 'OpenRouter SDK' }, { source: 'intellectronica/agent-skills', name: 'Context7' }, - { source: 'boristane/agent-skills', name: 'Logging Patterns' }, - { source: 'f/awesome-chatgpt-prompts', name: 'ChatGPT Prompts' }, - { source: 'rohitg00/openskills', name: 'OpenSkills' }, ]; interface FetchedSkill { diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 00000000..6be471b1 --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2022"], + "jsx": "react-jsx", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "composite": true + }, + "exclude": ["node_modules", "dist"] +} diff --git a/turbo.json b/turbo.json new file mode 100644 index 00000000..7c8d61e8 --- /dev/null +++ b/turbo.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://turbo.build/schema.json", + "globalDependencies": ["**/.env.*local"], + "tasks": { + "build": { + "dependsOn": ["^build"], + "outputs": ["dist/**"] + }, + "dev": { + "cache": false, + "persistent": true + }, + "test": { + "dependsOn": ["build"], + "outputs": [] + }, + "typecheck": { + "dependsOn": ["^build"], + "outputs": [] + }, + "lint": { + "outputs": [] + } + } +}