| name | prpm-development |
| description | Use when developing PRPM (Prompt Package Manager) - comprehensive knowledge base covering architecture, format conversion, package types, collections, quality standards, testing, and deployment |
PRPM Development Knowledge Base
Complete knowledge base for developing PRPM - the universal package manager for AI prompts, agents, and rules.
Mission
Build the npm/cargo/pip equivalent for AI development artifacts. Enable developers to discover, install, share, and manage prompts across Cursor, Claude Code, Continue, Windsurf, and future AI editors.
Core Architecture
Universal Format Philosophy
- Canonical Format: All packages stored in normalized JSON structure
- Smart Conversion: Server-side format conversion with quality scoring
- Zero Lock-In: Users convert between any format without data loss
- Format-Specific Optimization: IDE-specific variants (e.g., Claude with MCP)
Package Manager Best Practices
- Semantic Versioning: Strict semver for all packages
- Dependency Resolution: Smart conflict resolution like npm/cargo
- Lock Files: Reproducible installs (prpm-lock.json)
- Registry-First: All operations through central registry API
- Caching: Redis caching for converted packages (1-hour TTL)
Developer Experience
- One Command Install:
prpm install @collection/nextjs-progets everything - Auto-Detection: Detect IDE from directory structure (.cursor/, .claude/)
- Format Override:
--as claudeto force specific format - Telemetry Opt-Out: Privacy-first with easy opt-out
- Beautiful CLI: Clear progress indicators and colored output
Package Types
🎓 Skill
Purpose: Knowledge and guidelines for AI assistants
Location: .claude/skills/, .cursor/rules/
Examples: @prpm/pulumi-troubleshooting, @typescript/best-practices
🤖 Agent
Purpose: Autonomous AI agents for multi-step tasks
Location: .claude/agents/, .cursor/agents/
Examples: @prpm/code-reviewer, @cursor/debugging-agent
📋 Rule
Purpose: Specific instructions or constraints for AI behavior
Location: .cursor/rules/, .cursorrules
Examples: @cursor/react-conventions, @cursor/test-first
🔌 Plugin
Purpose: Extensions that add functionality
Location: .cursor/plugins/, .claude/plugins/
💬 Prompt
Purpose: Reusable prompt templates
Location: .prompts/, project-specific directories
⚡ Workflow
Purpose: Multi-step automation workflows
Location: .workflows/, .github/workflows/
🔧 Tool
Purpose: Executable utilities and scripts
Location: scripts/, tools/, .bin/
📄 Template
Purpose: Reusable file and project templates
Location: templates/, project-specific directories
🔗 MCP Server
Purpose: Model Context Protocol servers
Location: .mcp/servers/
Format Conversion System
Supported Formats
Cursor (.mdc)
- MDC frontmatter with
ruleType,alwaysApply,description - Markdown body
- Simple, focused on coding rules
- No structured tools/persona definitions
Claude (agent format)
- YAML frontmatter:
name,description - Optional:
tools(comma-separated),model(sonnet/opus/haiku/inherit) - Markdown body
- Supports persona, examples, instructions
Continue (JSON)
- JSON configuration
- Simple prompts, context rules
- Limited metadata support
Windsurf
- Similar to Cursor
- Markdown-based
- Basic structure
Conversion Quality Scoring (0-100)
Start at 100 points, deduct for lossy conversions:
- Missing tools: -10 points
- Missing persona: -5 points
- Missing examples: -5 points
- Unsupported sections: -10 points each
- Format-specific features lost: -5 points
Lossless vs Lossy Conversions
- Canonical ↔ Claude: Nearly lossless (95-100%)
- Canonical ↔ Cursor: Lossy on tools/persona (70-85%)
- Canonical ↔ Continue: Most lossy (60-75%)
Collections System
Collections are curated bundles of packages that solve specific use cases.
Collection Structure
{
"id": "@collection/nextjs-pro",
"name": "Next.js Professional Setup",
"description": "Complete Next.js development setup",
"category": "frontend",
"packages": [
{
"packageId": "react-best-practices",
"required": true,
"reason": "Core React patterns"
},
{
"packageId": "typescript-strict",
"required": true,
"reason": "Type safety"
},
{
"packageId": "tailwind-helper",
"required": false,
"reason": "Styling utilities"
}
]
}
Collection Installation Behavior
Collections can be installed using multiple identifier formats. The system intelligently resolves collections based on the format provided.
Installation Formats (Priority Order)
1. Recommended Format: collections/{slug}
prpm install collections/nextjs-pro
prpm install collections/nextjs-pro@2.0.0
- Behavior: Searches across ALL scopes for
name_slug = "nextjs-pro" - Resolution: Prioritizes by official → verified → downloads → created_at
- Use Case: User-friendly format for discovering popular collections
- Example: Finds
khaliqgant/nextjs-proeven when searchingcollections/nextjs-pro
2. Explicit Scope: {scope}/{slug} or @{scope}/{slug}
prpm install khaliqgant/nextjs-pro
prpm install @khaliqgant/nextjs-pro
prpm install khaliqgant/nextjs-pro@2.0.0
- Behavior: Searches for specific
scopeandname_slugcombination - Resolution: Exact match only within that scope
- Use Case: Installing a specific author's version when multiple exist
- Example: Gets specifically the collection published by
khaliqgant
3. Name-Only Format: {slug} (Legacy/Fallback)
prpm install nextjs-pro
prpm install nextjs-pro@1.0.0
- Behavior: Defaults to
scope = "collection", then falls back to cross-scope search - Resolution: First tries scope="collection", then searches all scopes
- Use Case: Quick installs when collection origin doesn't matter
- Recommendation: Prefer
collections/{slug}for clarity
Registry Resolution Logic
Implementation Location: app/packages/registry/src/routes/collections.ts:485-519
// When scope is 'collection' (default from CLI for collections/* prefix):
if (scope === 'collection') {
// Search across ALL scopes, prioritize by:
// 1. Official collections (official = true)
// 2. Verified authors (verified = true)
// 3. Most downloads
// 4. Most recent
SELECT * FROM collections
WHERE name_slug = $1
ORDER BY official DESC, verified DESC, downloads DESC, created_at DESC
LIMIT 1
} else {
// Explicit scope: exact match only
SELECT * FROM collections
WHERE scope = $1 AND name_slug = $2
ORDER BY created_at DESC
LIMIT 1
}
CLI Resolution Logic
Implementation Location: app/packages/cli/src/commands/collections.ts:487-504
// Parse collection spec:
// - collections/nextjs-pro → scope='collection', name_slug='nextjs-pro'
// - khaliqgant/nextjs-pro → scope='khaliqgant', name_slug='nextjs-pro'
// - @khaliqgant/nextjs-pro → scope='khaliqgant', name_slug='nextjs-pro'
// - nextjs-pro → scope='collection', name_slug='nextjs-pro'
const matchWithScope = collectionSpec.match(/^@?([^/]+)\/([^/@]+)(?:@(.+))?$/);
if (matchWithScope) {
[, scope, name_slug, version] = matchWithScope;
} else {
// No scope: default to 'collection'
[, name_slug, version] = collectionSpec.match(/^([^/@]+)(?:@(.+))?$/);
scope = 'collection';
}
Version Resolution
Collections support semantic versioning:
# Latest version (default)
prpm install collections/nextjs-pro
# Specific version
prpm install collections/nextjs-pro@2.0.4
# With scope and version
prpm install khaliqgant/nextjs-pro@2.0.4
Registry Behavior:
- Without version: Returns latest (most recent
created_at) - With version: Exact match required
Discovery Prioritization
When searching across all scopes (collections/* format), the system prioritizes:
Official Collections (official = true)
- Curated by PRPM maintainers
- Highest trust level
Verified Authors (verified = true)
- Known community contributors
- GitHub verified
Download Count (downloads DESC)
- Most popular collections
- Community validation
Recency (created_at DESC)
- Latest versions
- Actively maintained
Error Handling
Collection Not Found:
prpm install collections/nonexistent
# ❌ Failed to install collection: Collection not found
Scope-Specific Not Found:
prpm install wrongscope/nextjs-pro
# ❌ Failed to install collection: Collection not found
# Suggestion: Try 'collections/nextjs-pro' to search all scopes
Collection Best Practices
- Required vs Optional: Clearly mark essential vs nice-to-have packages
- Reason Documentation: Every package explains why it's included
- IDE-Specific Variants: Different packages per editor when needed
- Installation Order: Consider dependencies
- Scope Naming:
- Use your username/org as scope for personal collections
- Reserve "collection" scope for official PRPM collections
- User-Friendly IDs: Use descriptive slugs (e.g., "nextjs-pro" not "np-setup")
- Version Incrementing: Bump versions on meaningful changes (follow semver)
Quality & Ranking System
Multi-Factor Scoring (0-100)
Popularity (0-30 points):
- Total downloads (weighted by recency)
- Stars/favorites
- Trending velocity
Quality (0-30 points):
- User ratings (1-5 stars)
- Review sentiment
- Documentation completeness
Trust (0-20 points):
- Verified author badge
- Original creator vs fork
- Publisher reputation
- Security scan results
Recency (0-10 points):
- Last updated date (<30 days = 10 points)
- Release frequency
- Active maintenance
Completeness (0-10 points):
- Has README
- Has examples
- Has tags
- Complete metadata
Technical Stack
CLI (TypeScript + Node.js)
- Commander.js: CLI framework
- Fastify Client: HTTP client for registry
- Tar: Package tarball creation/extraction
- Chalk: Terminal colors
- Ora: Spinners for async operations
Registry (TypeScript + Fastify + PostgreSQL)
- Fastify: High-performance web framework
- PostgreSQL: Primary database with GIN indexes
- Redis: Caching layer for converted packages
- GitHub OAuth: Authentication provider
- Docker: Containerized deployment
Testing
- Vitest: Unit and integration tests
- 100% Coverage Goal: Especially for format converters
- Round-Trip Tests: Ensure conversion quality
- Fixtures: Real-world package examples
Testing Standards
Test Pyramid
- 70% Unit Tests: Format converters, parsers, utilities
- 20% Integration Tests: API routes, database operations, CLI commands
- 10% E2E Tests: Full workflows (install, publish, search)
Coverage Goals
- Format Converters: 100% coverage (critical path)
- CLI Commands: 90% coverage
- API Routes: 85% coverage
- Utilities: 90% coverage
Key Testing Patterns
// Format converter test
describe('toCursor', () => {
it('preserves data in roundtrip', () => {
const result = toCursor(canonical);
const back = fromCursor(result.content);
expect(back).toEqual(canonical);
});
});
// CLI command test
describe('install', () => {
it('downloads and installs package', async () => {
await handleInstall('test-pkg', { as: 'cursor' });
expect(fs.existsSync('.cursor/rules/test-pkg.md')).toBe(true);
});
});
Development Workflow
When Adding Features
- Check Existing Patterns: Look at similar commands/routes
- Update Types First: TypeScript interfaces drive implementation
- Write Tests: Create test fixtures and cases
- Document: Update README and relevant docs
- Environment Variables: If adding new env vars, update
.env.exampleimmediately - Telemetry: Add tracking for new commands (with privacy)
When Fixing Bugs
- Write Failing Test: Reproduce the bug in a test
- Fix Minimally: Smallest change that fixes the issue
- Check Round-Trip: Ensure conversions still work
- Update Fixtures: Add bug case to test fixtures
Dependency Management Best Practices
AVOID Runtime Dependencies (Dynamic Imports)
❌ Bad: Using dynamic imports for runtime dependencies
// BAD - tar-stream is imported dynamically at runtime
const tarStream = await import('tar-stream');
Problems with Dynamic Imports:
- Module Resolution Failures: In production (Elastic Beanstalk, Docker), dynamic imports can fail to resolve even if the package is installed as a transitive dependency
- Build Complexity: TypeScript compilation doesn't validate dynamic imports
- Deployment Issues: Package may not be in the module resolution path in production
- Harder to Debug: Failures happen at runtime, not at build time
✅ Good: Declare all dependencies explicitly
// GOOD - Import normally at the top
import * as tarStream from 'tar-stream';
Dependency Guidelines:
- Explicit Dependencies: Always declare dependencies in package.json, never rely on transitive dependencies
- Static Imports: Use static imports whenever possible for compile-time validation
- Production Dependencies: If you import it, it should be in
dependencies, notdevDependencies - Build-Time Validation: Let TypeScript catch missing dependencies at build time, not runtime
Environment Variable Management
ALWAYS Update .env.example When Adding New Environment Variables
Environment variables are configuration points. When adding new ones, follow this checklist:
- Add to
.env.exampleimmediately - Don't wait until later - Group logically - Place in appropriate section (DATABASE, AUTH, etc.)
- Add clear comments - Explain what it does and where to get values
- Include examples - Show format (e.g.,
sk-ant-api03-...for API keys) - Mark optional vs required - Comment out optional variables with
# - Update production notes - Add to deployment checklist if needed
Example:
# ==============================================================================
# NEW FEATURE SECTION
# ==============================================================================
# Description of what this variable does
# Get from: https://where-to-get-it.com
NEW_FEATURE_API_KEY=your-key-here
# Optional feature flag (default: false)
# ENABLE_NEW_FEATURE=true
Why this matters:
- New developers need to know what env vars to set
.env.exampleis the source of truth for configuration- Missing env vars cause runtime errors that are hard to debug
- Production deployments fail without proper env var documentation
Finding missing env vars:
# Search for all process.env usage
grep -rh "process.env\." packages/ --include="*.ts" --include="*.tsx" | \
grep -o "process\.env\.[A-Z_][A-Z0-9_]*" | sort -u
# Compare with .env.example to find gaps
When Designing APIs
- REST Best Practices: Proper HTTP methods and status codes
- Versioning: All routes under
/api/v1/ - Pagination: Limit/offset for list endpoints
- Filtering: Support query params for filtering
- OpenAPI: Document with Swagger/OpenAPI specs
Security Standards
- No Secrets in DB: Never store GitHub tokens, use session IDs
- SQL Injection: Parameterized queries only
- Rate Limiting: Prevent abuse of registry API
- Content Security: Validate package contents before publishing
Performance Considerations
- Batch Operations: Use Promise.all for independent operations
- Database Indexes: GIN for full-text, B-tree for lookups
- Caching Strategy: Cache converted packages, not raw data
- Lazy Loading: Don't load full package data until needed
- Connection Pooling: Reuse PostgreSQL connections
Deployment
AWS Infrastructure
Registry Backend (Elastic Beanstalk)
- Environment: Node.js 20 on 64bit Amazon Linux 2023
- Instance: t3.micro (cost-optimized)
- Database: RDS PostgreSQL
- Cache: ElastiCache Redis
- DNS: Route 53
- SSL: ACM certificates
Webapp (S3 Static Export) ⚠️ CRITICAL
The webapp MUST be deployable as a static site via S3/CloudFront.
Requirements:
- Next.js with
output: 'export'configuration - NO server-side rendering (SSR) - all pages must be static or client-side rendered
- NO API routes - all API calls go to the registry backend
- Dynamic routes require
generateStaticParams()- return empty array[]for client-side only routes - All data fetching must be client-side (useEffect, fetch, etc.)
Common Issues:
Dynamic routes in client components ⚠️ CANNOT USE BOTH
- Error:
Page "page" cannot use both "use client" and export function "generateStaticParams()" - Solution: Use query strings instead of path parameters
- ❌ Wrong:
/playground/shared/[token]/page.tsxwith'use client' - ✅ Correct:
/playground/shared/page.tsxwith?token=xxxquery param - Implementation: Use
useSearchParams()instead ofuseParams() - IMPORTANT: Must wrap
useSearchParams()in<Suspense>boundary - Example:
// ❌ Dynamic route (doesn't work with 'use client') // /app/shared/[token]/page.tsx const params = useParams(); const token = params.token; // ✅ Query string with Suspense (works with 'use client') // /app/shared/page.tsx import { Suspense } from 'react'; function Content() { const searchParams = useSearchParams(); const token = searchParams.get('token'); // ... component logic } export default function Page() { return ( <Suspense fallback={<div>Loading...</div>}> <Content /> </Suspense> ); }
- Error:
Server components in static export
- All pages with dynamic content must use
'use client'directive - Shared session pages, playground interfaces, etc. are client-rendered
- All pages with dynamic content must use
Environment variables
- Build-time: Embedded in static bundle (public/exposed)
- Runtime: Fetched via API from registry backend
Why S3 Static Export?
- Cost: $0.023/GB vs $30+/month for server hosting
- Scale: CloudFront CDN handles traffic spikes
- Reliability: No server maintenance or downtime
- Performance: Pre-rendered static pages are instant
GitHub Actions Workflows
- Test & Deploy: Runs on push to main
- NPM Publish: Manual trigger for releases
- Homebrew Publish: Updates tap formula
- Webapp Deploy: Builds static export and deploys to S3
Publishing PRPM to NPM
Publishable Packages:
prpm- CLI (public)@prpm/registry-client- HTTP client (public)- Registry and Infra are private (deployed, not published)
Process:
- Go to Actions → NPM Publish
- Select version bump (patch/minor/major)
- Choose packages (all or specific)
- Run workflow
Homebrew Formula:
- Formula repository:
khaliqgant/homebrew-prpm - Auto-updates on NPM publish
- Requires
HOMEBREW_TAP_TOKENsecret
Version Bumping:
# CLI and client together
npm version patch --workspace=prpm --workspace=@prpm/registry-client
# Individual package
npm version minor --workspace=prpm
Common Patterns
CLI Command Structure
export async function handleCommand(args: Args, options: Options) {
const startTime = Date.now();
try {
const config = await loadUserConfig();
const client = getRegistryClient(config);
const result = await client.fetchData();
console.log('✅ Success');
await telemetry.track({ command: 'name', success: true });
} catch (error) {
console.error('❌ Failed:', error.message);
await telemetry.track({ command: 'name', success: false });
process.exit(1);
}
}
Registry Route Structure
server.get('/:id', {
schema: { /* OpenAPI schema */ },
}, async (request, reply) => {
const { id } = request.params;
if (!id) return reply.code(400).send({ error: 'Missing ID' });
const result = await server.pg.query('SELECT...');
return result.rows[0];
});
Format Converter Structure
export function toFormat(pkg: CanonicalPackage): ConversionResult {
const warnings: string[] = [];
let qualityScore = 100;
const content = convertSections(pkg.content.sections, warnings);
const lossyConversion = warnings.some(w => w.includes('not supported'));
if (lossyConversion) qualityScore -= 10;
return { content, format: 'target', warnings, qualityScore, lossyConversion };
}
Naming Conventions
- Files: kebab-case (
registry-client.ts,to-cursor.ts) - Types: PascalCase (
CanonicalPackage,ConversionResult) - Functions: camelCase (
getPackage,convertToFormat) - Constants: UPPER_SNAKE_CASE (
DEFAULT_REGISTRY_URL) - Database: snake_case (
package_id,created_at) - API Requests/Responses: snake_case (
package_id,session_id,created_at)- Important: All API request and response fields use snake_case to match PostgreSQL database conventions
- Internal service methods may use camelCase, but must convert to snake_case at API boundaries
- TypeScript interfaces for API types should use snake_case fields
- Examples:
PlaygroundRunRequest.package_id,CreditBalance.reset_at
Documentation Standards
- Inline Comments: Explain WHY, not WHAT
- JSDoc: Required for public APIs
- README: Keep examples up-to-date
- Markdown Docs: Use code blocks with language tags
- Changelog: Follow Keep a Changelog format
- Continuous Accuracy: Documentation must be continuously updated and tended to for accuracy
- When adding features, update relevant docs immediately
- When fixing bugs, check if docs need corrections
- When refactoring, verify examples still work
- Review docs quarterly for outdated information
- Keep CLI docs, README, and Mintlify docs in sync
Reference Documentation
See supporting files in this skill directory for detailed information:
format-conversion.md- Complete format conversion specspackage-types.md- All package types with examplescollections.md- Collections system and examplesquality-ranking.md- Quality and ranking algorithmstesting-guide.md- Testing patterns and standardsdeployment.md- Deployment procedures
Remember: PRPM is infrastructure. It must be rock-solid, fast, and trustworthy like npm or cargo.