From e3261ec46c826c0e3411039a708ee066f4210549 Mon Sep 17 00:00:00 2001 From: Vitaly Lobachev <980829+vlobachev@users.noreply.github.com> Date: Tue, 20 Jan 2026 10:37:37 +0100 Subject: [PATCH 1/2] feat: modernize agent blueprint and add MCP memory - refresh AGENTS and docs for 2025-2026 agent workflows - add MCP memory server reference with tests - add generator golden tests and templates AI-Generated: Yes Reviewed-by: N/A --- .eslintrc.cjs | 13 + .github/ISSUE_TEMPLATE/agent-task.md | 25 ++ .github/copilot-instructions.md | 16 + .github/pull_request_template.md | 14 + AGENTS.md | 373 +++++------------- CLAUDE.md | 131 ++---- README.md | 7 + docs/MCP_MEMORY_IMPLEMENTATION.md | 64 ++- docs/PROJECT_STRUCTURE.md | 49 ++- docs/README.md | 22 +- docs/guides/AGENTS_AND_TOOL_RULES.md | 35 ++ docs/guides/CLAUDE_CODE.md | 27 ++ docs/guides/COPILOT_AGENT_MODE.md | 42 ++ docs/guides/MCP.md | 80 ++++ docs/guides/ONBOARDING_30_MINUTES.md | 40 ++ docs/templates/AGENT_TASK_CHECKLIST.md | 44 +++ examples/README.md | 11 +- examples/contract-first/README.md | 12 + examples/contract-first/calculator.js | 15 + examples/contract-first/contract.test.js | 16 + package.json | 6 +- src/mcp-memory/memory-store.js | 89 +++++ src/mcp-memory/server.js | 230 +++++++++++ src/setup.js | 11 + src/test-setup.js | 13 +- src/validate.js | 31 ++ templates/AGENTS.md.hbs | 217 ++++------ templates/CLAUDE.md.hbs | 147 ++----- templates/PROJECT_STRUCTURE.md.hbs | 1 + templates/README.md.hbs | 1 + templates/package.json.hbs | 1 + templates/packages/api/AGENTS.md.hbs | 19 + templates/packages/cli/AGENTS.md.hbs | 19 + templates/packages/core/AGENTS.md.hbs | 19 + templates/packages/shared-types/AGENTS.md.hbs | 19 + templates/packages/web/AGENTS.md.hbs | 19 + tests/golden/README.md | 10 + tests/golden/setup-output.snapshot.json | 82 ++++ tests/mcp-memory/memory-store.test.js | 40 ++ tests/mcp-memory/server.test.js | 49 +++ tests/setup/generator-golden.test.js | 68 ++++ 41 files changed, 1428 insertions(+), 699 deletions(-) create mode 100644 .eslintrc.cjs create mode 100644 .github/ISSUE_TEMPLATE/agent-task.md create mode 100644 .github/copilot-instructions.md create mode 100644 .github/pull_request_template.md create mode 100644 docs/guides/AGENTS_AND_TOOL_RULES.md create mode 100644 docs/guides/CLAUDE_CODE.md create mode 100644 docs/guides/COPILOT_AGENT_MODE.md create mode 100644 docs/guides/MCP.md create mode 100644 docs/guides/ONBOARDING_30_MINUTES.md create mode 100644 docs/templates/AGENT_TASK_CHECKLIST.md create mode 100644 examples/contract-first/README.md create mode 100644 examples/contract-first/calculator.js create mode 100644 examples/contract-first/contract.test.js create mode 100644 src/mcp-memory/memory-store.js create mode 100644 src/mcp-memory/server.js create mode 100644 src/validate.js create mode 100644 templates/packages/api/AGENTS.md.hbs create mode 100644 templates/packages/cli/AGENTS.md.hbs create mode 100644 templates/packages/core/AGENTS.md.hbs create mode 100644 templates/packages/shared-types/AGENTS.md.hbs create mode 100644 templates/packages/web/AGENTS.md.hbs create mode 100644 tests/golden/setup-output.snapshot.json create mode 100644 tests/mcp-memory/memory-store.test.js create mode 100644 tests/mcp-memory/server.test.js create mode 100644 tests/setup/generator-golden.test.js diff --git a/.eslintrc.cjs b/.eslintrc.cjs new file mode 100644 index 0000000..4ba0ad7 --- /dev/null +++ b/.eslintrc.cjs @@ -0,0 +1,13 @@ +module.exports = { + root: true, + env: { + node: true, + es2022: true + }, + parserOptions: { + ecmaVersion: 2022, + sourceType: 'module' + }, + extends: ['eslint:recommended'], + ignorePatterns: ['node_modules/', 'test-output/', 'dist/', 'build/'] +}; diff --git a/.github/ISSUE_TEMPLATE/agent-task.md b/.github/ISSUE_TEMPLATE/agent-task.md new file mode 100644 index 0000000..d3084c4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/agent-task.md @@ -0,0 +1,25 @@ +--- +name: Agent Task +about: Structured task template for agentic coding +labels: [agent-task] +--- + +## Goal + + + +## Constraints + +- + +## Acceptance Criteria + +- [ ] + +## Validation + +- [ ] `make validate` + +## Notes + +- Link to relevant docs or prompts diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..7b7f8ac --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,16 @@ +# GitHub Copilot Instructions (Agent Mode) + +This repository is **AGENTS.md-first**. Always read and follow `AGENTS.md` before making changes. + +## Required Workflow + +1. Keep changes scoped to the task. +2. Do not add dependencies without explicit approval. +3. Run `make validate` before finishing. +4. Report exact commands and results in the PR. + +## Helpful References + +- `AGENTS.md` – canonical rules +- `docs/guides/COPILOT_AGENT_MODE.md` – Copilot agent workflow +- `docs/templates/AGENT_TASK_CHECKLIST.md` – coordination checklist diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..87c4a12 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ +# Summary + +- + +## Validation + +- [ ] `make validate` + +## Agent Checklist (if applicable) + +- [ ] Followed `AGENTS.md` +- [ ] No new dependencies without approval +- [ ] Tests updated (unit/integration/golden as needed) +- [ ] Risks and follow-ups documented diff --git a/AGENTS.md b/AGENTS.md index 2901c3c..5351f9c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,329 +1,148 @@ # AGENTS.md -**AI Agent Guidelines for Collaborative Vibecoding** +**AI Agent Interface for Vibecode Blueprint (2025-2026)** -This file provides guidance for AI agents working in this repository. It follows the AGENTS.md standard for clear AI-human collaboration. +This file is the canonical, cross-tool source of truth for how agents should work in this repository. Tool-specific rules (Claude/Windsurf/Cline/KiloCode/Copilot) must defer to this document when conflicts arise. -## Project Overview - -**Mission**: Enable teams to collaborate effectively using AI-assisted development (vibecoding) while maintaining high code quality and security standards. - -**Architecture**: Monorepo with packages for core utilities, API services, web frontend, and shared types. - -**Development Philosophy**: AI proposes, humans approve. Contracts and tests define boundaries. - -## What You Can Do - -✅ **Code Generation & Modification** - -- Generate new functions, classes, and components -- Implement features following our established patterns -- Write unit and integration tests for your code -- Create API endpoints following REST conventions -- Update documentation for code you write -- Refactor code when explicitly asked - -✅ **Testing & Quality** - -- Generate comprehensive test suites -- Create test data and mock objects -- Write snapshot tests for UI components -- Add error handling and edge case coverage -- Update existing tests when code changes - -✅ **Documentation** - -- Write clear code comments and docstrings -- Create API documentation -- Generate README files for new packages -- Document complex business logic - -## What You Cannot Do - -❌ **Security & Infrastructure** - -- Modify security configurations or authentication logic -- Change database schemas without explicit approval -- Add new dependencies without human approval -- Modify CI/CD pipeline configurations -- Access or modify production data -- Change environment variables or secrets - -❌ **Breaking Changes** - -- Delete existing tests or golden snapshots -- Modify public API contracts without approval -- Change shared type definitions without review -- Remove existing functionality -- Modify `/policies/` directory contents - -❌ **Production & Deployment** - -- Deploy code to production environments -- Modify deployment scripts or configurations -- Change monitoring or logging configurations -- Access production databases or services - -## Code Standards +--- -### Language & Style +## 1) Setup & Validation Commands -```typescript -// Preferred: Clear, typed interfaces -interface UserProfile { - id: string; - name: string; - email: string; - bio?: string; -} +Use these commands in the order that makes sense for your task. Always finish with a clean validation pass. -// Preferred: Explicit error handling -try { - const result = await userService.updateProfile(data); - return { success: true, data: result }; -} catch (error) { - logger.error('Profile update failed', { error: error.message }); - return { success: false, error: 'Failed to update profile' }; -} -``` +### Install -### File Organization - -- One primary export per file -- Use descriptive file names: `user-profile-service.ts` -- Keep related files grouped in directories -- Follow existing package structure - -### Testing Requirements - -```typescript -// Always include error cases -describe('UserService.updateProfile', () => { - it('should update profile successfully', async () => { - // Happy path test - }); - - it('should handle validation errors', async () => { - // Error case test - }); - - it('should handle database errors', async () => { - // Infrastructure error test - }); -}); +```bash +make install +# or +pnpm install ``` -## Approved Technologies - -### Core Stack - -- **Backend**: Node.js, TypeScript, Express.js -- **Frontend**: React, TypeScript, Tailwind CSS -- **Database**: PostgreSQL with TypeORM/Prisma -- **Testing**: Jest, React Testing Library -- **Validation**: Joi schemas - -### Allowed Libraries +### Interactive Setup (Generator) -- `lodash` for utility functions -- `axios` for HTTP requests -- `date-fns` for date manipulation -- `uuid` for ID generation -- `bcrypt` for password hashing - -### Forbidden Libraries - -- `moment.js` (use date-fns instead) -- `jquery` (use vanilla JS or React) -- Any library with known security vulnerabilities - -## Architecture Patterns - -### API Responses - -```typescript -// Standard success response -interface ApiResponse { - success: true; - data: T; - timestamp: string; -} - -// Standard error response -interface ApiError { - success: false; - error: string; - details?: ValidationError[]; - timestamp: string; -} +```bash +make setup +# or +pnpm run setup ``` -### Error Handling - -```typescript -// Repository pattern for data access -class UserRepository { - async findById(id: string): Promise { - try { - return await this.db.user.findUnique({ where: { id } }); - } catch (error) { - logger.error('Database query failed', { error, userId: id }); - throw new DatabaseError('Failed to fetch user'); - } - } -} -``` +### Validate (must pass before finishing) -## Security Guidelines - -### Input Validation - -- Validate all user inputs using Joi schemas -- Sanitize data before database operations -- Use parameterized queries to prevent SQL injection -- Escape user content in responses to prevent XSS - -### Authentication & Authorization - -```typescript -// Always check permissions -const hasPermission = await authService.canUpdateProfile( - requestingUserId, - targetUserId -); -if (!hasPermission) { - return res.status(403).json({ - success: false, - error: 'Insufficient permissions' - }); -} +```bash +make validate +# or +pnpm run validate ``` -### Secrets & Configuration - -- Never hardcode API keys, passwords, or secrets -- Use environment variables for configuration -- Log security events for audit purposes -- Follow principle of least privilege - -## Package Boundaries +### Targeted Checks -### Monorepo Structure - -``` -packages/ -├── core/ # Shared utilities - no external dependencies -├── shared-types/ # TypeScript definitions - no runtime dependencies -├── api/ # Backend services - can use core and shared-types -└── web/ # Frontend app - can use core and shared-types +```bash +pnpm run lint +pnpm run format +pnpm run format:check +pnpm test ``` -### Import Rules - -```typescript -// ✅ Allowed: Import from core utilities -import { validateEmail } from '@/core/utils/validation'; +--- -// ✅ Allowed: Import shared types -import { UserProfile } from '@/shared-types/user'; +## 2) Repo Map (What Matters) -// ❌ Forbidden: Direct file imports from other packages -import { UserService } from '../../api/src/services/UserService'; -``` +- `src/` – setup generator, validation, and reference MCP server +- `templates/` – scaffold templates rendered by the generator +- `scripts/` – pre-commit guardrails and validation helpers +- `tests/` – unit, integration, and golden tests (generator + MCP server) +- `prompts/` – reusable prompt templates +- `policies/` – human review and governance rules (do **not** edit) +- `memory-bank/` – optional memory artifacts for some agents +- `docs/` – canonical documentation and guides -## Quality Standards +--- -### Code Coverage +## 3) How to Work Safely (Human-in-the-Loop) -- Minimum 80% test coverage for new code -- 100% coverage for critical business logic -- Include both positive and negative test cases -- Test error handling and edge cases +**Core rules (non-negotiable):** -### Performance +- AI proposes, humans approve. Do not bypass human review. +- Contracts and golden tests are truth sources. Update only with explicit approval. +- Keep changes scoped to the task. Avoid unrelated refactors. +- Do not edit generated files unless the task explicitly requires it. +- Prefer additive changes and backwards compatibility. -- API endpoints must respond within 200ms for simple operations -- Database queries should use appropriate indexes -- Frontend components should render within 100ms -- Bundle size increases require justification +**Agent loop expectation:** -### Documentation +1. Understand the request and constraints. +2. Make minimal, test-backed changes. +3. Run `make validate` (or equivalent) before finishing. +4. Report exact commands and results. -- Document all public APIs with JSDoc comments -- Include usage examples for complex functions -- Document business logic and edge cases -- Keep README files updated +--- -## Working with Humans +## 4) Style & Conventions -### Communication +- **TypeScript-first** when applicable; keep types explicit. +- One primary export per file. +- Follow existing file organization and naming patterns. +- Prefer clear, typed interfaces over implicit shapes. +- Use ESLint/Prettier formatting (single linter/formatter). +- Never wrap imports in try/catch blocks. -- Explain your reasoning for implementation choices -- Ask for clarification when requirements are ambiguous -- Highlight any assumptions you're making -- Suggest alternatives when appropriate +--- -### Code Reviews +## 5) Tests & Quality -- Generate clear, descriptive commit messages -- Include PR descriptions explaining the changes -- Respond to feedback constructively -- Flag any areas where you're uncertain +- Include **positive + negative** tests for new logic. +- Add/adjust **golden tests** when behavior is intentionally changed. +- Keep minimum coverage targets (80% overall, 100% for critical logic). +- Use descriptive test names and deterministic fixtures. -### GitHub Actions Validation (CRITICAL) +--- -**ALWAYS check GitHub Actions results after every push:** +## 6) Security & Safety -- Run `gh run list --limit 5` to see recent workflow status -- If any workflows fail, investigate with `gh run view --log-failed` -- Fix any CI/CD failures before proceeding with new changes -- Common failure types to watch for: - - Markdown linting errors in documentation - - Security scanning issues (secrets, vulnerabilities) - - Test failures or coverage drops - - Build/compilation errors - - Code quality violations (ESLint, Prettier) -- Update relevant documentation templates if workflow patterns change -- Never ignore workflow failures - they indicate real issues +- **Never** hardcode secrets, tokens, or credentials. +- Validate and sanitize user inputs. +- Avoid unsafe patterns (`eval`, `innerHTML`, etc.). +- Do not modify authentication, authorization, or security configs without explicit approval. +- Do not change `/policies/` contents. -### Continuous Learning +--- -- Learn from human feedback and corrections -- Adapt to project-specific patterns and conventions -- Ask about architectural decisions you don't understand -- Contribute to improving these guidelines +## 7) Dependency Policy -## Tool-Specific Notes +- **Do not add dependencies** without explicit approval. +- Prefer Node.js built-ins and existing tooling. +- If a dependency is unavoidable, explain why and get approval first. -### For Windsurf Users +--- -- Use Memories to store project context and patterns -- Leverage Cascade for multi-step refactoring -- Use Supercomplete for consistent code completion +## 8) Multi-Agent Compatibility -### For Roo Code Users +- Assume other agents may work in parallel. +- Leave the repo in a **consistent, validated** state at each commit. +- Document assumptions, risks, and follow-ups in PRs. +- Use the agent task checklist template in `docs/templates/AGENT_TASK_CHECKLIST.md` for coordination. -- Utilize slash commands: `/test`, `/refactor`, `/document` -- Collaborate with multiple agents for complex tasks -- Use step planning for large features +--- -### For KiloCode Users +## 9) Tooling Integration (Single Source of Truth) -- Follow architect → code → debug workflow -- Maintain Memory Bank with project patterns -- Use orchestration for coordinated changes +- `AGENTS.md` is the **canonical** instruction set. +- Tool-specific files (e.g., `CLAUDE.md`, `.clinerules`, `.windsurf/`, `.kilocode/`, Copilot instructions) must reference this file instead of duplicating rules. +- If guidance conflicts, **AGENTS.md wins**. -## Questions & Support +--- -When you're unsure about something: +## 10) When to Ask for Help -1. **Check existing code** for patterns and conventions -2. **Refer to documentation** in `/docs/` directory -3. **Ask the human reviewer** for guidance -4. **Err on the side of caution** for security-sensitive changes +Ask before: -Remember: Your goal is to accelerate development while maintaining quality and security. When in doubt, ask for human guidance. +- Architectural changes +- Security-sensitive modifications +- Adding dependencies +- Changing public API contracts +- Modifying existing golden snapshots --- -*This AGENTS.md file follows the standard format for AI agent guidance. Last updated: 2024* +**Last Updated**: 2026 +**Maintained By**: Vibecode Maintainers diff --git a/CLAUDE.md b/CLAUDE.md index 05580c3..35cd42a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,126 +1,53 @@ # CLAUDE.md -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. +This file provides guidance to Claude Code (claude.ai/code). **AGENTS.md is the canonical source of truth** for all agent rules; this file only adds Claude-specific hints and command shortcuts. -## Project Overview +## Quick Start -This is a collaborative vibecoding project - a framework for natural-language driven development through agentic IDEs for team collaboration. The project provides rules, shared prompts, examples, and collaboration artifacts to enable teams to co-develop in a monorepo using AI coding tools. +```bash +make install +make validate +``` + +## Claude-Specific Workflow + +1. Read `AGENTS.md` first (scope + safety). +2. Use prompts from `/prompts/` for consistent task framing. +3. Run `make validate` before finishing. ## Development Commands ### Setup & Dependencies ```bash -node src/setup.js # Initial project setup -chmod +x scripts/agent-guardrails.sh # Make guardrails executable -npm ci # Install dependencies (when package.json exists) +pnpm install # Install dependencies +chmod +x scripts/agent-guardrails.sh # Guardrails executable ``` ### Quality & Validation ```bash -npm run guardrails # Run AI code guardrails validation -./scripts/agent-guardrails.sh # Direct guardrail script execution -npm run lint # Run ESLint (when configured) -npm run type-check # Run TypeScript type checking (when configured) -npm run test # Run test suites (when configured) +pnpm run guardrails # AI code guardrails validation +pnpm run lint # ESLint +pnpm run format:check # Prettier check +pnpm test # Tests +make validate # Full validation ``` -### Build & Development +### Generator ```bash -npm run build # Build all packages (when configured) -npm run dev # Development mode (when configured) -turbo run build # Turbo monorepo build (when configured) -turbo run dev # Turbo development mode (when configured) +pnpm run setup # Interactive project setup +pnpm run test-setup # Deterministic generator run (test output) ``` -## Project Architecture - -### Core Structure - -- **Framework-based**: Template repository providing standardized structure for AI-assisted development -- **Documentation-driven**: Comprehensive guides in `/docs/` for architecture, contributing, and onboarding -- **Quality-focused**: Built-in guardrails and validation scripts for AI-generated code -- **Tool-agnostic**: Supports Windsurf, Roo Code, KiloCode, and other agentic IDEs - -### Key Directories - -``` -/docs/architecture/ - System design and architecture documentation -/docs/guides/ - Contributing guidelines and onboarding materials -/prompts/ - Standardized AI prompt templates (feature, bugfix, refactor) -/policies/ - Code ownership and review guidelines -/templates/ - PR and commit message templates -/scripts/ - Automation scripts including agent-guardrails.sh -/tests/golden/ - Baseline snapshots for regression testing -/examples/ - Real-world usage examples and workflows -``` - -### Validation & Quality Assurance - -The `scripts/agent-guardrails.sh` script enforces: - -- File size limits and code quality standards -- Security pattern detection (no hardcoded secrets, SQL injection prevention) -- TypeScript best practices (avoid `any` types, proper error handling) -- Test coverage requirements alongside code changes -- Commit message format validation (AI-Generated and Reviewed-by fields) -- Branch naming conventions (feature/*, fix/*, etc.) - -### Development Philosophy - -- **Human-in-the-loop**: AI proposes, humans approve via review process -- **Contract-driven**: Interfaces and tests define boundaries, AI modifies implementations -- **Golden test protection**: Stable snapshots prevent regression in critical functionality -- **Context enforcement**: Clear package boundaries and import rules +## Key Directories -## Important Files +- `src/` – generator + reference MCP memory server +- `templates/` – scaffold templates +- `tests/` – unit/integration/golden tests +- `docs/` – documentation index + guides -### Configuration & Setup - -- `src/setup.js`: Comprehensive project initialization script that creates package.json, ESLint, Prettier, TypeScript configs, and GitHub Actions workflows -- `AGENTS.md`: Detailed AI agent guidelines following standard format (285 lines of comprehensive rules) -- `scripts/agent-guardrails.sh`: Pre-commit validation script (260 lines) with security and quality checks - -### Templates & Standards - -- `/prompts/*.md`: Standardized templates for feature development, bug fixes, and refactoring -- `/templates/PR.md`: Pull request template for consistent documentation -- `/templates/CommitMessage.md`: Commit message format with AI attribution tracking - -### Documentation - -- `docs/PROJECT_STRUCTURE.md`: Detailed directory overview and usage patterns -- `/docs/guides/CONTRIBUTING.md`: Development contribution guidelines -- `/docs/guides/ONBOARDING.md`: New team member setup guide - -## Working with This Codebase - -### Before Making Changes - -1. Read the comprehensive `AGENTS.md` file for AI agent guidelines -2. Use appropriate prompt templates from `/prompts/` directory -3. Follow the human-in-the-loop review process outlined in `/policies/REVIEW.md` - -### Quality Standards - -- Run `./scripts/agent-guardrails.sh` before commits to validate changes -- Ensure AI-Generated and Reviewed-by fields are present in commit messages -- Include corresponding tests when modifying code -- Follow TypeScript best practices and avoid `any` types -- Respect package boundaries and import rules - -### Monorepo Structure - -When the setup script runs, it creates: - -``` -packages/ -├── core/ # Shared utilities -├── shared-types/ # TypeScript definitions -├── api/ # Backend services -└── web/ # Frontend application -``` +## AI Collaboration Rules (Pointer) -The project supports Turbo for monorepo orchestration with workspace-based dependency management. +All permissions, constraints, and safety rules live in **`AGENTS.md`**. If this file conflicts, follow `AGENTS.md`. diff --git a/README.md b/README.md index 72c4cf4..935c4c0 100644 --- a/README.md +++ b/README.md @@ -58,9 +58,13 @@ For a complete directory structure with detailed descriptions, see **[docs/PROJE ## Supported Tools +- **Claude Code**: Claude-powered agent workflows +- **GitHub Copilot**: Agent mode / coding agent workflows - **Windsurf**: Cascade, Memories, Supercomplete modes - **Roo Code**: Multi-agent collaboration with slash commands - **KiloCode**: Open-source orchestration (architect → code → debug) +- **Codex**: Agentic coding workflows +- **MCP integrations**: Local MCP servers for memory and context - **Generic**: Any agentic IDE following our conventions ## Getting Started @@ -115,6 +119,9 @@ Key documentation: - **[docs/guides/ONBOARDING.md](docs/guides/ONBOARDING.md)** - New team member guide - **[docs/guides/PRE_COMMIT.md](docs/guides/PRE_COMMIT.md)** - Pre-commit hooks setup - **[docs/MCP_MEMORY_IMPLEMENTATION.md](docs/MCP_MEMORY_IMPLEMENTATION.md)** - MCP Memory Server plan +- **[docs/guides/MCP.md](docs/guides/MCP.md)** - MCP memory server usage +- **[docs/guides/COPILOT_AGENT_MODE.md](docs/guides/COPILOT_AGENT_MODE.md)** - Copilot agent mode guide +- **[docs/guides/CLAUDE_CODE.md](docs/guides/CLAUDE_CODE.md)** - Claude Code guide - **[AGENTS.md](AGENTS.md)** - AI agent guidelines - **[CLAUDE.md](CLAUDE.md)** - Claude-specific guidance diff --git a/docs/MCP_MEMORY_IMPLEMENTATION.md b/docs/MCP_MEMORY_IMPLEMENTATION.md index 41980a2..99ca3ff 100644 --- a/docs/MCP_MEMORY_IMPLEMENTATION.md +++ b/docs/MCP_MEMORY_IMPLEMENTATION.md @@ -2,7 +2,7 @@ **Universal AI Memory System for Collaborative Development** -A comprehensive plan for implementing a Supermemory-like MCP (Model Context Protocol) memory server that works across different AI coding tools (Windsurf, Cline, Roo Code, KiloCode, Claude Desktop, etc.). +This plan now includes a **minimal, working MCP memory server** located at `src/mcp-memory/`. The reference server is local-first, dependency-free, and suitable for agent demos or small teams. ## 🎯 Project Goals @@ -12,6 +12,15 @@ A comprehensive plan for implementing a Supermemory-like MCP (Model Context Prot - **Lightweight**: Easy to set up and maintain - **Privacy-First**: Local-first storage with optional cloud sync +## ✅ Current Implementation (Reference MVP) + +- JSON-RPC 2.0 MCP server over HTTP +- File-backed JSON storage (default: `memory-bank/mcp-memory.json`) +- Tools: `add_memory`, `search_memory`, `summarize_memory` +- Resources: list/read memory entries + +See **[docs/guides/MCP.md](guides/MCP.md)** for usage and wiring instructions. + ## 📋 Implementation Phases ### Phase 1: Core Memory Server (MVP) @@ -20,33 +29,32 @@ A comprehensive plan for implementing a Supermemory-like MCP (Model Context Prot #### 1.1 Server Setup -- [ ] Initialize Node.js/TypeScript MCP server project -- [ ] Implement MCP protocol handlers (stdio transport) -- [ ] Set up SQLite database for local storage -- [ ] Define memory schema (id, content, tags, timestamp, metadata) -- [ ] Add basic CRUD operations (create, read, update, delete) +- [x] Implement Node.js MCP server (HTTP JSON-RPC) +- [x] Define memory schema (id, content, tags, timestamp, metadata) +- [x] Add basic CRUD operations (create, read, list/search, delete) +- [ ] Optional: stdio transport (future) +- [ ] Optional: SQLite storage (future) #### 1.2 Core Tools -- [ ] `addMemory` - Store new memory with tags and metadata -- [ ] `searchMemories` - Search by keywords or tags -- [ ] `getMemory` - Retrieve specific memory by ID -- [ ] `listMemories` - List recent memories with pagination -- [ ] `deleteMemory` - Remove memory by ID +- [x] `add_memory` - Store new memory with tags and metadata +- [x] `search_memory` - Search by keywords or tags +- [x] `resources/read` - Retrieve specific memory by ID +- [x] `resources/list` - List recent memories +- [ ] `delete_memory` - Remove memory by ID (future) #### 1.3 Configuration -- [ ] Create configuration file (`.mcp-memory/config.json`) -- [ ] Support environment variables for settings -- [ ] Add database path configuration -- [ ] Implement logging system +- [x] Support environment variables for settings +- [x] Add storage path configuration +- [ ] Optional: config file + structured logging #### 1.4 Testing & Documentation -- [ ] Unit tests for core operations -- [ ] Integration tests with MCP protocol -- [ ] Quick start guide -- [ ] API documentation +- [x] Unit tests for core operations +- [x] Integration tests with MCP protocol +- [x] Quick start guide +- [ ] API documentation (optional) **Deliverable**: Working MCP server with basic memory operations @@ -174,23 +182,11 @@ A comprehensive plan for implementing a Supermemory-like MCP (Model Context Prot ### Core Technologies -- **Language**: TypeScript/Node.js -- **Protocol**: MCP (Model Context Protocol) -- **Database**: SQLite (primary) + Vector DB (Chroma/SQLite-vec) -- **Embeddings**: OpenAI API or local models (sentence-transformers) -- **Transport**: stdio (standard MCP transport) +- **Language**: Node.js (ESM)\n+- **Protocol**: MCP (Model Context Protocol)\n+- **Storage**: JSON file (reference), SQLite optional\n+- **Transport**: HTTP JSON-RPC (reference), stdio optional -### Dependencies +### Dependencies (Optional) -```json -{ - "@modelcontextprotocol/sdk": "^0.5.0", - "better-sqlite3": "^9.0.0", - "chromadb": "^1.8.0", - "openai": "^4.0.0", - "zod": "^3.22.0" -} -``` +The reference server is dependency-free. Optional additions may include:\n\n- MCP SDK\n- SQLite drivers\n- Embedding providers ## 🔧 Configuration Example diff --git a/docs/PROJECT_STRUCTURE.md b/docs/PROJECT_STRUCTURE.md index c3dd313..b007a64 100644 --- a/docs/PROJECT_STRUCTURE.md +++ b/docs/PROJECT_STRUCTURE.md @@ -14,11 +14,18 @@ vibecode/ │ ├── README.md # Documentation index │ ├── architecture/ │ │ └── SYSTEM_ARCHITECTURE.md # System design overview -│ └── guides/ -│ ├── CONTRIBUTING.md # Development guidelines -│ ├── ONBOARDING.md # New team member guide -│ ├── PRE_COMMIT.md # Pre-commit hooks setup guide -│ └── WINDSURF_TEAM_COLLABORATION.md # Windsurf collaboration guide +│ ├── guides/ +│ │ ├── CONTRIBUTING.md # Development guidelines +│ │ ├── ONBOARDING.md # New team member guide +│ │ ├── ONBOARDING_30_MINUTES.md # Fast-track onboarding +│ │ ├── PRE_COMMIT.md # Pre-commit hooks setup guide +│ │ ├── WINDSURF_TEAM_COLLABORATION.md # Windsurf collaboration guide +│ │ ├── COPILOT_AGENT_MODE.md # Copilot agent mode guide +│ │ ├── CLAUDE_CODE.md # Claude Code guide +│ │ ├── MCP.md # MCP memory server guide +│ │ └── AGENTS_AND_TOOL_RULES.md # Tool rule alignment +│ └── templates/ +│ └── AGENT_TASK_CHECKLIST.md # Agent coordination checklist │ ├── policies/ # Governance and rules │ ├── CODEOWNERS # Package ownership definitions @@ -30,8 +37,11 @@ vibecode/ │ └── refactor.md # Code refactoring template │ ├── templates/ # Standard templates -│ ├── PR.md # Pull request template -│ └── CommitMessage.md # Commit message format guide +│ ├── PR.md # Pull request template +│ ├── CommitMessage.md # Commit message format guide +│ ├── AGENTS.md.hbs # Generator template for AGENTS.md +│ └── packages/ # Package-level AGENTS templates +│ └── */AGENTS.md.hbs # Per-package guidance │ ├── scripts/ # Automation scripts │ ├── agent-guardrails.sh # Pre-commit validation script @@ -39,14 +49,22 @@ vibecode/ │ ├── pre-commit-validate-structure.sh # Structure validation script │ └── pre-commit-check-agents.sh # AGENTS.md validation script │ -├── tests/ # Testing artifacts -│ └── golden/ # Golden/snapshot tests -│ └── README.md # Golden test documentation +├── src/ # Implementation +│ ├── setup.js # Project setup generator +│ ├── test-setup.js # Deterministic generator run +│ └── mcp-memory/ # Reference MCP memory server +│ ├── server.js # JSON-RPC MCP server +│ └── memory-store.js # File-backed memory store +│ +├── tests/ # Tests +│ ├── golden/ # Generator snapshots +│ ├── mcp-memory/ # MCP server tests +│ └── setup/ # Generator tests │ └── examples/ # Real-world examples ├── README.md # Examples overview - └── feature-example/ # Complete feature workflow example - └── complete-workflow.md # Step-by-step feature development + ├── feature-example/ # Complete feature workflow example + └── contract-first/ # Contract-first testing example ``` ## 🎯 What This Provides @@ -106,10 +124,9 @@ This structure provides everything needed to implement collaborative vibecoding - **[CLAUDE.md](../CLAUDE.md)** - Claude-specific guidance - **[docs/README.md](README.md)** - Complete documentation index - **[docs/guides/CONTRIBUTING.md](guides/CONTRIBUTING.md)** - Development workflow -- **[docs/guides/ONBOARDING.md](guides/ONBOARDING.md)** - New team member guide -- **[docs/guides/PRE_COMMIT.md](guides/PRE_COMMIT.md)** - Pre-commit hooks setup -- **[docs/MCP_MEMORY_IMPLEMENTATION.md](MCP_MEMORY_IMPLEMENTATION.md)** - MCP Memory Server plan +- **[docs/guides/ONBOARDING_30_MINUTES.md](guides/ONBOARDING_30_MINUTES.md)** - Fast onboarding +- **[docs/guides/MCP.md](guides/MCP.md)** - MCP memory server usage --- -**Ready to start vibecoding?** Check out [docs/guides/ONBOARDING.md](guides/ONBOARDING.md) to get your team up and running! +**Ready to start vibecoding?** Check out [docs/guides/ONBOARDING_30_MINUTES.md](guides/ONBOARDING_30_MINUTES.md) to get your team up and running! diff --git a/docs/README.md b/docs/README.md index 4486698..a1bac78 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,23 +18,33 @@ Welcome to the Vibecode Blueprint documentation. ### Implementation Plans -- **[MCP_MEMORY_IMPLEMENTATION.md](MCP_MEMORY_IMPLEMENTATION.md)** - Universal MCP Memory Server implementation plan +- **[MCP_MEMORY_IMPLEMENTATION.md](MCP_MEMORY_IMPLEMENTATION.md)** - MCP Memory Server plan ### Guides - **[guides/](guides/)** - Operational guides and procedures - [CONTRIBUTING.md](guides/CONTRIBUTING.md) - How to contribute to the project - [ONBOARDING.md](guides/ONBOARDING.md) - New team member onboarding guide + - [ONBOARDING_30_MINUTES.md](guides/ONBOARDING_30_MINUTES.md) - Fast-track onboarding - [WINDSURF_TEAM_COLLABORATION.md](guides/WINDSURF_TEAM_COLLABORATION.md) - Windsurf collaboration guide - [PRE_COMMIT.md](guides/PRE_COMMIT.md) - Pre-commit hooks setup and usage - [DOCUMENTATION_STANDARDS.md](guides/DOCUMENTATION_STANDARDS.md) - Documentation best practices and standards + - [AGENTS_AND_TOOL_RULES.md](guides/AGENTS_AND_TOOL_RULES.md) - AGENTS.md and tool rule alignment + - [COPILOT_AGENT_MODE.md](guides/COPILOT_AGENT_MODE.md) - GitHub Copilot agent mode usage + - [CLAUDE_CODE.md](guides/CLAUDE_CODE.md) - Claude Code usage + - [MCP.md](guides/MCP.md) - MCP memory server usage + +### Templates + +- **[templates/](templates/)** - Reusable templates + - [AGENT_TASK_CHECKLIST.md](templates/AGENT_TASK_CHECKLIST.md) - Agent coordination checklist ## 🎯 Documentation by Role ### For New Team Members 1. Start with [README.md](../README.md) -2. Read [guides/ONBOARDING.md](guides/ONBOARDING.md) +2. Read [guides/ONBOARDING_30_MINUTES.md](guides/ONBOARDING_30_MINUTES.md) 3. Review [architecture/SYSTEM_ARCHITECTURE.md](architecture/SYSTEM_ARCHITECTURE.md) 4. Follow [guides/CONTRIBUTING.md](guides/CONTRIBUTING.md) @@ -47,9 +57,9 @@ Welcome to the Vibecode Blueprint documentation. ### For AI Agents -1. [../AGENTS.md](../AGENTS.md) - AI agent guidelines (comprehensive) +1. [../AGENTS.md](../AGENTS.md) - AI agent guidelines (canonical) 2. [../CLAUDE.md](../CLAUDE.md) - Claude-specific guidance -3. [guides/WINDSURF_TEAM_COLLABORATION.md](guides/WINDSURF_TEAM_COLLABORATION.md) - Windsurf collaboration +3. [guides/AGENTS_AND_TOOL_RULES.md](guides/AGENTS_AND_TOOL_RULES.md) - Tool alignment ### For Project Managers @@ -83,6 +93,8 @@ For complete documentation standards and best practices, see **[guides/DOCUMENTA - **Roo Code**: - **KiloCode**: - **Cline**: +- **Claude Code**: +- **GitHub Copilot**: ## 🛠️ Quick Commands @@ -105,5 +117,5 @@ make pre-commit-install --- -**Last Updated**: 2025-10-01 +**Last Updated**: 2026-01-01 **Maintained By**: Development Team diff --git a/docs/guides/AGENTS_AND_TOOL_RULES.md b/docs/guides/AGENTS_AND_TOOL_RULES.md new file mode 100644 index 0000000..e7cfffb --- /dev/null +++ b/docs/guides/AGENTS_AND_TOOL_RULES.md @@ -0,0 +1,35 @@ +# AGENTS.md & Tool Rules Alignment + +This blueprint is **AGENTS.md-first**. `AGENTS.md` is the single source of truth for agent behavior across tools (Claude Code, Copilot, Cline, Roo Code, Windsurf, KiloCode, Codex, etc.). + +## Why AGENTS.md Is Canonical + +- It is tool-agnostic and easy to audit. +- It keeps humans in control while allowing agents to iterate. +- It prevents divergence between tool-specific rule files. + +## How Tool Rules Should Behave + +Tool-specific files should **reference** `AGENTS.md` instead of duplicating rules: + +- `CLAUDE.md` – Claude shortcuts and command reminders +- `.clinerules` – memory-bank instructions only +- `.windsurf/` – workflow triggers (not policy) +- `.kilocode/` – orchestration hints (not policy) +- `.github/copilot-instructions.md` – Copilot onboarding & guardrails + +If a tool file conflicts with `AGENTS.md`, **follow `AGENTS.md`**. + +## Recommended Pattern + +1. Keep behavioral rules in `AGENTS.md`. +2. Keep tool files minimal and pointer-based. +3. Use `docs/templates/AGENT_TASK_CHECKLIST.md` for coordination. + +## Updating Rules + +When rules change: + +- Update `AGENTS.md` first. +- Update tool-specific pointers if needed. +- Document the change in `docs/README.md` if it affects onboarding. diff --git a/docs/guides/CLAUDE_CODE.md b/docs/guides/CLAUDE_CODE.md new file mode 100644 index 0000000..61ad762 --- /dev/null +++ b/docs/guides/CLAUDE_CODE.md @@ -0,0 +1,27 @@ +# Claude Code Guide + +This blueprint supports Claude Code with lightweight, pointer-based instructions. + +## Canonical Rules + +Start with `AGENTS.md`. It is the source of truth for agent behavior. `CLAUDE.md` only adds Claude-specific shortcuts. + +## Recommended Flow + +1. Read `AGENTS.md` and `CLAUDE.md`. +2. Use prompts in `/prompts/` when possible. +3. Run `make validate` before finishing. + +## Useful Commands + +```bash +make install +make setup +make validate +``` + +## Tips + +- Keep changes small and reviewable. +- Avoid dependency changes unless explicitly approved. +- Report validation results in final output. diff --git a/docs/guides/COPILOT_AGENT_MODE.md b/docs/guides/COPILOT_AGENT_MODE.md new file mode 100644 index 0000000..3444c84 --- /dev/null +++ b/docs/guides/COPILOT_AGENT_MODE.md @@ -0,0 +1,42 @@ +# GitHub Copilot Agent Mode Guide + +This guide explains how to use GitHub Copilot agent mode/coding agent effectively with the Vibecode Blueprint. + +## Recommended Workflow + +1. **Start with a clear task** + - Provide requirements, constraints, and acceptance criteria. + - Point the agent to `AGENTS.md`. + +2. **Let the agent iterate** + - Encourage the agent to run tests and commands. + - Require self-correction based on output. + +3. **Validate before finishing** + - Always run `make validate` (or equivalent). + - Include command output and results in the PR. + +## Guardrails + +- Keep changes scoped to the task. +- Do not bypass tests or linting. +- Avoid large refactors without approval. +- Do not add dependencies without explicit approval. + +## Suggested Prompt Template + +```text +Goal: +Constraints: +Acceptance Criteria: +Validation: run `make validate` +Reference: AGENTS.md +``` + +## Review Checklist (Human) + +- [ ] Changes align with requirements +- [ ] Tests and validation commands ran +- [ ] No unexpected dependency changes +- [ ] Contracts and golden tests preserved +- [ ] Documentation updated if needed diff --git a/docs/guides/MCP.md b/docs/guides/MCP.md new file mode 100644 index 0000000..9e66bc6 --- /dev/null +++ b/docs/guides/MCP.md @@ -0,0 +1,80 @@ +# MCP (Model Context Protocol) Guide + +This blueprint includes a **minimal MCP memory server** to make agent workflows reproducible and local-first. It is intentionally simple and dependency-free. + +## What You Get + +- JSON-RPC 2.0 MCP server +- File-backed memory storage (JSON) +- Tools: `add_memory`, `search_memory`, `summarize_memory` +- Resources: list/read memory entries + +## Run the Server + +```bash +pnpm run mcp-memory +``` + +By default it starts on port `3333` and stores memory at `memory-bank/mcp-memory.json`. + +### Environment Variables + +- `MCP_MEMORY_PORT` – default `3333` +- `MCP_MEMORY_HOST` – default `127.0.0.1` +- `MCP_MEMORY_PATH` – default `memory-bank/mcp-memory.json` + +## Example JSON-RPC Calls + +### Initialize + +```json +{ + "jsonrpc": "2.0", + "id": 1, + "method": "initialize", + "params": {} +} +``` + +### Add Memory + +```json +{ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "add_memory", + "arguments": { + "title": "Decision: keep AGENTS.md canonical", + "content": "We align tool rules to AGENTS.md to avoid drift.", + "tags": ["decision", "process"] + } + } +} +``` + +### Search Memory + +```json +{ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": { + "name": "search_memory", + "arguments": { "query": "AGENTS" } + } +} +``` + +## Connect from Agents + +- **Claude Code / Codex / Cline**: point the MCP server URL to `http://127.0.0.1:3333`. +- **Copilot**: use a local MCP integration or a wrapper that forwards JSON-RPC. + +## Security Notes + +- This server is **local-only** by default. +- Do not expose it publicly without authentication. +- Treat memory entries as sensitive; avoid secrets. diff --git a/docs/guides/ONBOARDING_30_MINUTES.md b/docs/guides/ONBOARDING_30_MINUTES.md new file mode 100644 index 0000000..47b4c1e --- /dev/null +++ b/docs/guides/ONBOARDING_30_MINUTES.md @@ -0,0 +1,40 @@ +# Onboarding in 30 Minutes + +This guide helps teams adopt the Vibecode Blueprint quickly and safely. + +## 0–5 Minutes: Clone & Install + +```bash +make install +``` + +## 5–10 Minutes: Run the Generator + +```bash +make setup +``` + +Choose your packages, enable pre-commit hooks, and confirm GitHub Actions settings. + +## 10–15 Minutes: Understand the Rules + +- Read `AGENTS.md` (canonical agent rules). +- Read `policies/REVIEW.md` (human review expectations). + +## 15–20 Minutes: Learn the Prompts & Memory + +- Review `/prompts/feature.md`, `/prompts/bugfix.md`, `/prompts/refactor.md`. +- Open `/memory-bank/` to see how long-term context can be stored. +- Optional: run the MCP memory server (`pnpm run mcp-memory`). + +## 20–25 Minutes: Validate the Repo + +```bash +make validate +``` + +## 25–30 Minutes: Start Your First Task + +- Create an issue/PR using the agent templates. +- Keep changes scoped and validated. +- Use the checklist in `docs/templates/AGENT_TASK_CHECKLIST.md`. diff --git a/docs/templates/AGENT_TASK_CHECKLIST.md b/docs/templates/AGENT_TASK_CHECKLIST.md new file mode 100644 index 0000000..0d9bd9c --- /dev/null +++ b/docs/templates/AGENT_TASK_CHECKLIST.md @@ -0,0 +1,44 @@ +# Agent Task Checklist + +Use this checklist to keep multi-agent work consistent and reviewable. + +## Task Summary + +- **Goal**: +- **Constraints**: +- **Acceptance Criteria**: + +## Plan + +1. +2. +3. + +## Files Touched + +- `path/to/file` – reason +- `path/to/file` – reason + +## Commands Run + +```bash +# Example +make validate +``` + +## Test Results + +- ✅ `make validate` +- ⚠️ `pnpm test` (explain why if warning) +- ❌ (only if agent error) + +## Risks / Follow-ups + +- Potential regression: +- Requires human review: +- Documentation updates needed: + +## Review Notes + +- Areas to scrutinize: +- Assumptions made: diff --git a/examples/README.md b/examples/README.md index 3b41d96..a0d31c9 100644 --- a/examples/README.md +++ b/examples/README.md @@ -5,11 +5,12 @@ This directory contains real examples of successful vibecoding practices. ## Examples Included 1. **feature-example/**: Complete feature development workflow -2. **bugfix-example/**: Bug fix with AI assistance -3. **refactor-example/**: Code refactoring guided by AI -4. **pr-examples/**: Successful PR descriptions and workflows -5. **windsurf-memories/**: Saved Windsurf context examples -6. **roo-commands/**: Custom Roo Code slash commands +2. **contract-first/**: Minimal contract test pattern for safe refactors +3. **bugfix-example/**: Bug fix with AI assistance +4. **refactor-example/**: Code refactoring guided by AI +5. **pr-examples/**: Successful PR descriptions and workflows +6. **windsurf-memories/**: Saved Windsurf context examples +7. **roo-commands/**: Custom Roo Code slash commands ## How to Use These Examples diff --git a/examples/contract-first/README.md b/examples/contract-first/README.md new file mode 100644 index 0000000..9ab346a --- /dev/null +++ b/examples/contract-first/README.md @@ -0,0 +1,12 @@ +# Contract-First Example + +This example shows how to protect behavior with a **contract test** so agents can safely refactor implementations. + +## Files + +- `contract.test.js` – the contract (public behavior) +- `calculator.js` – implementation (safe to refactor) + +## Why It Matters + +When agents modify implementations, the contract test ensures public behavior is preserved. If the contract changes, it requires explicit approval. diff --git a/examples/contract-first/calculator.js b/examples/contract-first/calculator.js new file mode 100644 index 0000000..ce4ba1c --- /dev/null +++ b/examples/contract-first/calculator.js @@ -0,0 +1,15 @@ +export const pricingContract = { + currency: 'USD', + taxRate: 0.08 +}; + +export function calculateTotal({ subtotal, discount = 0 }) { + const taxable = Math.max(subtotal - discount, 0); + const tax = Number((taxable * pricingContract.taxRate).toFixed(2)); + return { + subtotal, + discount, + tax, + total: Number((taxable + tax).toFixed(2)) + }; +} diff --git a/examples/contract-first/contract.test.js b/examples/contract-first/contract.test.js new file mode 100644 index 0000000..12cdd7f --- /dev/null +++ b/examples/contract-first/contract.test.js @@ -0,0 +1,16 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { calculateTotal, pricingContract } from './calculator.js'; + +test('pricing contract remains stable', () => { + const result = calculateTotal({ subtotal: 100, discount: 20 }); + + assert.equal(pricingContract.currency, 'USD'); + assert.equal(pricingContract.taxRate, 0.08); + assert.deepEqual(result, { + subtotal: 100, + discount: 20, + tax: 6.4, + total: 86.4 + }); +}); diff --git a/package.json b/package.json index 9c823ed..8145cb8 100644 --- a/package.json +++ b/package.json @@ -11,10 +11,12 @@ "setup": "node src/setup.js", "test-setup": "node src/test-setup.js", "dev": "node src/setup.js --dev", - "test": "node --test test/**/*.test.js", + "test": "node --test tests/**/*.test.js", "lint": "eslint src/ templates/", "format": "prettier --write .", - "validate": "node src/validate.js" + "format:check": "prettier --check .", + "validate": "node src/validate.js", + "mcp-memory": "node src/mcp-memory/server.js" }, "keywords": [ "ai-coding", diff --git a/src/mcp-memory/memory-store.js b/src/mcp-memory/memory-store.js new file mode 100644 index 0000000..1d73da2 --- /dev/null +++ b/src/mcp-memory/memory-store.js @@ -0,0 +1,89 @@ +import fs from 'fs/promises'; +import path from 'path'; +import crypto from 'crypto'; + +const DEFAULT_DATA = { + version: 1, + entries: [] +}; + +export class MemoryStore { + constructor({ filePath }) { + this.filePath = filePath; + } + + async initialize() { + await fs.mkdir(path.dirname(this.filePath), { recursive: true }); + try { + await fs.access(this.filePath); + } catch { + await fs.writeFile(this.filePath, JSON.stringify(DEFAULT_DATA, null, 2)); + } + } + + async readAll() { + const raw = await fs.readFile(this.filePath, 'utf8'); + const data = JSON.parse(raw); + return Array.isArray(data.entries) ? data.entries : []; + } + + async writeAll(entries) { + const payload = { + ...DEFAULT_DATA, + entries + }; + await fs.writeFile(this.filePath, JSON.stringify(payload, null, 2)); + } + + async list() { + return this.readAll(); + } + + async add({ title, content, tags }) { + if (!content || typeof content !== 'string') { + throw new Error('content is required'); + } + const now = new Date().toISOString(); + const entry = { + id: crypto.randomUUID(), + title: title || 'Untitled', + content, + tags: Array.isArray(tags) ? tags : [], + createdAt: now, + updatedAt: now + }; + const entries = await this.readAll(); + entries.push(entry); + await this.writeAll(entries); + return entry; + } + + async getById(id) { + const entries = await this.readAll(); + return entries.find((entry) => entry.id === id) || null; + } + + async search({ query, limit = 10 }) { + const entries = await this.readAll(); + if (!query) { + return entries.slice(-limit); + } + const normalized = query.toLowerCase(); + const results = entries.filter((entry) => { + const haystack = [entry.title, entry.content, ...(entry.tags || [])] + .join(' ') + .toLowerCase(); + return haystack.includes(normalized); + }); + return results.slice(0, limit); + } + + async summarize({ query, limit = 5 }) { + const results = await this.search({ query, limit }); + if (results.length === 0) { + return 'No memories matched the query.'; + } + const titles = results.map((entry) => `- ${entry.title}`).join('\n'); + return `Found ${results.length} memories:\n${titles}`; + } +} diff --git a/src/mcp-memory/server.js b/src/mcp-memory/server.js new file mode 100644 index 0000000..1ba699c --- /dev/null +++ b/src/mcp-memory/server.js @@ -0,0 +1,230 @@ +import http from 'http'; +import { MemoryStore } from './memory-store.js'; + +const DEFAULT_HOST = process.env.MCP_MEMORY_HOST || '127.0.0.1'; +const DEFAULT_PORT = Number.parseInt(process.env.MCP_MEMORY_PORT, 10) || 3333; +const DEFAULT_PATH = process.env.MCP_MEMORY_PATH || 'memory-bank/mcp-memory.json'; + +const TOOL_DEFINITIONS = [ + { + name: 'add_memory', + description: 'Store a memory entry with optional tags.', + inputSchema: { + type: 'object', + properties: { + title: { type: 'string' }, + content: { type: 'string' }, + tags: { type: 'array', items: { type: 'string' } } + }, + required: ['content'] + } + }, + { + name: 'search_memory', + description: 'Search memories by substring match.', + inputSchema: { + type: 'object', + properties: { + query: { type: 'string' }, + limit: { type: 'number' } + } + } + }, + { + name: 'summarize_memory', + description: 'Summarize matching memories with a short list.', + inputSchema: { + type: 'object', + properties: { + query: { type: 'string' }, + limit: { type: 'number' } + } + } + } +]; + +function jsonResponse(res, payload) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(payload)); +} + +function jsonError(id, message, code = -32603) { + return { + jsonrpc: '2.0', + id, + error: { + code, + message + } + }; +} + +function memoryUri(id) { + return `memory://${id}`; +} + +function parseMemoryId(uri) { + if (!uri || typeof uri !== 'string') { + return null; + } + if (uri.startsWith('memory://')) { + return uri.replace('memory://', ''); + } + return null; +} + +async function handleRpc(payload, store) { + const { id, method, params } = payload; + + try { + switch (method) { + case 'initialize': + return { + jsonrpc: '2.0', + id, + result: { + protocolVersion: '2024-11-05', + capabilities: { + resources: { list: true, read: true }, + tools: { list: true, call: true } + }, + serverInfo: { + name: 'vibecode-mcp-memory', + version: '0.1.0' + } + } + }; + case 'resources/list': { + const entries = await store.list(); + return { + jsonrpc: '2.0', + id, + result: { + resources: entries.map((entry) => ({ + uri: memoryUri(entry.id), + name: entry.title, + mimeType: 'application/json' + })) + } + }; + } + case 'resources/read': { + const entryId = parseMemoryId(params?.uri); + if (!entryId) { + return jsonError(id, 'Invalid resource URI', -32602); + } + const entry = await store.getById(entryId); + if (!entry) { + return jsonError(id, 'Memory not found', -32004); + } + return { + jsonrpc: '2.0', + id, + result: { + contents: [ + { + uri: memoryUri(entry.id), + mimeType: 'application/json', + text: JSON.stringify(entry, null, 2) + } + ] + } + }; + } + case 'tools/list': + return { + jsonrpc: '2.0', + id, + result: { tools: TOOL_DEFINITIONS } + }; + case 'tools/call': { + const toolName = params?.name; + const args = params?.arguments || {}; + + if (toolName === 'add_memory') { + const entry = await store.add(args); + return { + jsonrpc: '2.0', + id, + result: { + content: [{ type: 'text', text: JSON.stringify(entry, null, 2) }] + } + }; + } + + if (toolName === 'search_memory') { + const matches = await store.search(args); + return { + jsonrpc: '2.0', + id, + result: { + content: [{ type: 'text', text: JSON.stringify(matches, null, 2) }] + } + }; + } + + if (toolName === 'summarize_memory') { + const summary = await store.summarize(args); + return { + jsonrpc: '2.0', + id, + result: { + content: [{ type: 'text', text: summary }] + } + }; + } + + return jsonError(id, `Unknown tool: ${toolName}`, -32601); + } + default: + return jsonError(id, `Unknown method: ${method}`, -32601); + } + } catch (error) { + return jsonError(id, error?.message || 'Server error'); + } +} + +export function createMcpServer({ host = DEFAULT_HOST, port = DEFAULT_PORT, filePath = DEFAULT_PATH } = {}) { + const store = new MemoryStore({ filePath }); + + const server = http.createServer(async (req, res) => { + if (req.method !== 'POST') { + res.writeHead(405, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'Only POST is supported' })); + return; + } + + let body = ''; + req.on('data', (chunk) => { + body += chunk; + }); + req.on('end', async () => { + try { + const payload = JSON.parse(body || '{}'); + await store.initialize(); + const response = await handleRpc(payload, store); + jsonResponse(res, response); + } catch (error) { + jsonResponse(res, jsonError(null, error?.message || 'Invalid JSON', -32700)); + } + }); + }); + + return { + server, + start: () => new Promise((resolve) => { + server.listen(port, host, () => resolve(server.address())); + }), + stop: () => new Promise((resolve, reject) => { + server.close((err) => (err ? reject(err) : resolve())); + }) + }; +} + +if (process.argv[1] === new URL(import.meta.url).pathname) { + const instance = createMcpServer(); + instance.start().then((address) => { + const location = typeof address === 'string' ? address : `${address.address}:${address.port}`; + console.log(`MCP memory server listening on ${location}`); + }); +} diff --git a/src/setup.js b/src/setup.js index 2085c2c..8fb42eb 100644 --- a/src/setup.js +++ b/src/setup.js @@ -235,6 +235,17 @@ class VibecodeSetup { return true; } + // Skip workspace package templates when not using monorepo + if (!this.config.useMonorepo && outputPath.startsWith('packages/')) { + return true; + } + + // Skip package-specific templates when the package is not selected + const packageMatch = outputPath.match(/^packages\/([^/]+)\//); + if (packageMatch && !this.config.packages.includes(packageMatch[1])) { + return true; + } + return false; } diff --git a/src/test-setup.js b/src/test-setup.js index 286178d..ab6b1bc 100644 --- a/src/test-setup.js +++ b/src/test-setup.js @@ -37,7 +37,7 @@ class VibecodeTestSetup { setupGitHooks: true, setupGithubActions: true, packageNameScoped: '@test-vibecode-project', - currentYear: new Date().getFullYear(), + currentYear: Number.parseInt(process.env.VIBECODE_TEST_YEAR, 10) || new Date().getFullYear(), useWorkspaces: true }; this.spinner = null; @@ -160,6 +160,17 @@ class VibecodeTestSetup { return true; } + // Skip workspace package templates when not using monorepo + if (!this.config.useMonorepo && outputPath.startsWith('packages/')) { + return true; + } + + // Skip package-specific templates when the package is not selected + const packageMatch = outputPath.match(/^packages\/([^/]+)\//); + if (packageMatch && !this.config.packages.includes(packageMatch[1])) { + return true; + } + return false; } diff --git a/src/validate.js b/src/validate.js new file mode 100644 index 0000000..9013a69 --- /dev/null +++ b/src/validate.js @@ -0,0 +1,31 @@ +#!/usr/bin/env node + +import { spawn } from 'child_process'; + +const steps = [ + { label: 'lint', command: 'pnpm', args: ['run', 'lint'] }, + { label: 'format:check', command: 'pnpm', args: ['run', 'format:check'] }, + { label: 'test', command: 'pnpm', args: ['test'] } +]; + +const runStep = (step) => new Promise((resolve, reject) => { + const child = spawn(step.command, step.args, { stdio: 'inherit' }); + child.on('close', (code) => { + if (code === 0) { + resolve(); + } else { + reject(new Error(`${step.label} failed with exit code ${code}`)); + } + }); +}); + +const run = async () => { + for (const step of steps) { + await runStep(step); + } +}; + +run().catch((error) => { + console.error(`\nValidation failed: ${error.message}`); + process.exit(1); +}); diff --git a/templates/AGENTS.md.hbs b/templates/AGENTS.md.hbs index 422953d..bbde121 100644 --- a/templates/AGENTS.md.hbs +++ b/templates/AGENTS.md.hbs @@ -1,169 +1,94 @@ # AGENTS.md -**AI Agent Guidelines for {{projectName}}** +**AI Agent Interface for {{projectName}} (2025-2026)** -This file provides guidance for AI agents working in this repository. It follows the AGENTS.md standard for clear AI-human collaboration. +This file is the canonical, cross-tool source of truth for how agents should work in this repository. -## Project Overview +--- + +## 1) Setup & Validation Commands -**Mission**: {{description}} +### Install +```bash +{{packageManager}} install +``` + +### Validate (must pass before finishing) +```bash +{{packageManager}} run lint +{{packageManager}} run format:check +{{packageManager}} test +``` {{#if useMonorepo}} -**Architecture**: Monorepo with packages for {{#each packages}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}. -{{else}} -**Architecture**: Single package application with modular structure. +### Workspace Examples +```bash +{{packageManager}} --filter {{packages.[0]}} run test +{{packageManager}} --filter {{packages.[0]}} run build +``` {{/if}} -**Development Philosophy**: AI proposes, humans approve. Contracts and tests define boundaries. +--- -## What You Can Do +## 2) Repo Map -✅ **Code Generation & Modification** -- Generate new functions, classes, and components -- Implement features following our established patterns -{{#if useTypeScript}} -- Write TypeScript code with proper type definitions -{{/if}} -- Write unit and integration tests for your code -- Create API endpoints following REST conventions -- Update documentation for code you write -- Refactor code when explicitly asked - -✅ **Testing & Quality** -- Generate comprehensive test suites -- Create test data and mock objects -{{#if useTypeScript}} -- Write type-safe tests with proper TypeScript coverage +- `src/` – application source +- `tests/` – unit/integration/golden tests +- `scripts/` – automation and guardrails +- `docs/` – documentation and guides +- `prompts/` – prompt templates +{{#if useMonorepo}} +- `packages/` – workspace packages {{/if}} -- Write snapshot tests for UI components -- Add error handling and edge case coverage -- Update existing tests when code changes -✅ **Documentation & Communication** -- Update README files and inline documentation -- Create clear commit messages following our format -- Write helpful code comments explaining complex logic -- Generate API documentation -- Update this AGENTS.md file when project scope changes +--- -{{#if useMonorepo}} -✅ **Monorepo Management** -- Work across multiple packages while respecting boundaries -- Update workspace dependencies appropriately -- Maintain consistent patterns across packages -- Use shared types and utilities from the shared package -{{/if}} +## 3) How to Work Safely -## What You Cannot Do - -❌ **Restricted Actions** -- Delete or modify existing tests without explicit permission -- Change core architecture without discussion -- Modify CI/CD workflows without approval -- Update dependencies without security review -- Access or modify sensitive configuration files -- Make breaking changes to public APIs - -❌ **Security Boundaries** -- Never hardcode secrets, API keys, or passwords -- Don't bypass existing security measures -- Avoid creating potential security vulnerabilities -- Don't modify authentication or authorization logic without approval - -## Development Guidelines - -### Code Style -{{#if useTypeScript}} -- Use TypeScript for all new code -- Prefer interfaces over types for object shapes -- Use strict TypeScript configuration -{{/if}} -- Follow existing naming conventions -- Write self-documenting code with clear variable names -- Use consistent formatting (Prettier handles this) -- Add JSDoc comments for public APIs - -### Testing Strategy -- Write tests for all new functionality -- Maintain high test coverage (aim for >80%) -- Use descriptive test names that explain the scenario -- Group related tests in describe blocks -- Mock external dependencies appropriately - -### Git Workflow -- Create focused commits with clear messages -- Use conventional commit format: `type(scope): description` -- Include `AI-Generated: Yes` in commit messages for AI-created code -- Reference issue numbers when applicable - -{{#if packageManager}} -### Package Management -- Use {{packageManager}} for all dependency management -- Keep dependencies up to date and secure -- Prefer exact versions for production dependencies -- Document any new dependencies in commit messages -{{/if}} +- AI proposes, humans approve. Do not bypass review. +- Contracts and golden tests are truth sources. +- Keep changes scoped and backwards compatible. +- Do not edit generated files unless explicitly requested. -## Communication Protocol - -### When to Ask for Help -- Before making architectural decisions -- When encountering ambiguous requirements -- If you need to modify existing APIs -- When security implications are unclear -- If tests are failing and the cause isn't obvious - -### How to Communicate Changes -- Explain your reasoning for code changes -- Highlight any potential impacts or risks -- Suggest alternatives when appropriate -- Ask for feedback on complex implementations - -### GitHub Actions Validation (CRITICAL) -**ALWAYS check GitHub Actions results after every push:** -- Run `gh run list --limit 5` to see recent workflow status -- If any workflows fail, investigate with `gh run view --log-failed` -- Fix any CI/CD failures before proceeding with new changes -- Common failure types to watch for: - - Markdown linting errors in documentation - - Security scanning issues (secrets, vulnerabilities) - - Test failures or coverage drops - - Build/compilation errors - - Code quality violations (ESLint, Prettier) -- Update relevant documentation templates if workflow patterns change -- Never ignore workflow failures - they indicate real issues - -## Project-Specific Context - -### Key Technologies -{{#if useTypeScript}} -- **TypeScript**: Primary language for type safety -{{/if}} -{{#if packageManager}} -- **{{packageManager}}**: Package manager and workspace tool -{{/if}} -- **ESLint & Prettier**: Code quality and formatting -- **Git Hooks**: Pre-commit validation with agent-guardrails.sh +--- -### Important Files -- `package.json`: Project configuration and dependencies -{{#if useTypeScript}} -- `tsconfig.json`: TypeScript configuration -{{/if}} -- `.eslintrc.js`: Linting rules and configuration -- `scripts/agent-guardrails.sh`: Pre-commit validation script -- `README.md`: Project documentation and setup instructions +## 4) Style & Conventions + +- Prefer typed interfaces and explicit error handling. +- One primary export per file. +- Use a single formatter/linter. +- Never wrap imports in try/catch blocks. -### Quality Standards -- All code must pass ESLint validation -- Pre-commit hooks must pass before commits -- Tests must pass in CI/CD pipeline -- Security scans must not reveal vulnerabilities -- Documentation must be kept up to date +--- + +## 5) Tests & Quality + +- Include positive + negative tests for new logic. +- Update golden tests only with human approval. +- Maintain coverage and deterministic fixtures. + +--- + +## 6) Security & Safety + +- Never hardcode secrets or credentials. +- Validate and sanitize user input. +- Do not modify auth/security configs without approval. + +--- + +## 7) Dependency Policy + +- Do not add dependencies without explicit approval. + +--- + +## 8) Multi-Agent Compatibility + +- Leave the repo in a validated state after each commit. +- Use the agent task checklist template if provided. --- **Last Updated**: {{currentYear}} **Maintained By**: {{author}} - -*This file should be updated whenever project scope, architecture, or AI collaboration guidelines change.* diff --git a/templates/CLAUDE.md.hbs b/templates/CLAUDE.md.hbs index c3f82ef..111eb7e 100644 --- a/templates/CLAUDE.md.hbs +++ b/templates/CLAUDE.md.hbs @@ -1,157 +1,82 @@ # CLAUDE.md -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. +This file provides guidance to Claude Code (claude.ai/code). **AGENTS.md is the canonical source of truth** for all agent rules; this file only adds Claude-specific hints and command shortcuts. -## Project Overview +## Quick Start -{{description}} +```bash +{{packageManager}} install +{{packageManager}} run lint +{{packageManager}} run format:check +{{packageManager}} test +``` -{{#if useMonorepo}} -This is a monorepo project with multiple packages: {{#each packages}}{{this}}{{#unless @last}}, {{/unless}}{{/each}}. The project uses {{packageManager}} for workspace management and dependency handling. -{{else}} -This is a single-package project focused on {{projectName}}. -{{/if}} +## Claude-Specific Workflow + +1. Read `AGENTS.md` first (scope + safety). +2. Use prompts from `/prompts/` for consistent task framing. +3. Finish with a clean validation pass. ## Development Commands ### Setup & Dependencies ```bash {{#if packageManager}} -{{packageManager}} install # Install all dependencies +{{packageManager}} install {{else}} -npm install # Install dependencies +npm install {{/if}} -chmod +x scripts/agent-guardrails.sh # Make guardrails executable +chmod +x scripts/agent-guardrails.sh ``` ### Quality & Validation ```bash {{#if packageManager}} -{{packageManager}} run guardrails # Run AI code guardrails validation -{{packageManager}} run lint # Run ESLint +{{packageManager}} run guardrails +{{packageManager}} run lint +{{packageManager}} run format:check {{#if useTypeScript}} -{{packageManager}} run type-check # Run TypeScript type checking +{{packageManager}} run type-check {{/if}} -{{packageManager}} run test # Run test suites +{{packageManager}} run test {{else}} -npm run guardrails # Run AI code guardrails validation -npm run lint # Run ESLint +npm run guardrails +npm run lint +npm run format:check {{#if useTypeScript}} -npm run type-check # Run TypeScript type checking +npm run type-check {{/if}} -npm run test # Run test suites +npm run test {{/if}} -./scripts/agent-guardrails.sh # Direct guardrail script execution ``` ### Build & Development ```bash {{#if packageManager}} -{{packageManager}} run build # Build all packages -{{packageManager}} run dev # Development mode -{{#if useMonorepo}} -{{packageManager}} run clean # Clean build artifacts -{{/if}} +{{packageManager}} run build +{{packageManager}} run dev {{else}} -npm run build # Build the project -npm run dev # Development mode +npm run build +npm run dev {{/if}} ``` {{#if useMonorepo}} ### Workspace Management ```bash -{{packageManager}} --filter {{packages.[0]}} run build # Build specific package -{{packageManager}} --filter {{packages.[0]}} run test # Test specific package -{{packageManager}} add --workspace {{packages.[0]}} # Add dependency to specific package +{{packageManager}} --filter {{packages.[0]}} run build +{{packageManager}} --filter {{packages.[0]}} run test ``` {{/if}} -## Project Architecture +## Architecture Pointers -{{#if useTypeScript}} -### TypeScript Configuration -- Strict TypeScript mode enabled -- Shared type definitions in {{#if useMonorepo}}shared-types package{{else}}types directory{{/if}} -- Path mapping configured for clean imports -{{/if}} - -{{#if useMonorepo}} -### Package Structure -{{#each packages}} -- **{{this}}**: {{#if (eq this "core")}}Core utilities and shared functionality{{else if (eq this "api")}}API services and endpoints{{else if (eq this "web")}}Frontend web application{{else if (eq this "shared-types")}}Shared TypeScript type definitions{{else}}Package functionality{{/if}} -{{/each}} -{{/if}} - -### Code Quality Tools -- **ESLint**: Code linting and style enforcement -- **Prettier**: Code formatting -{{#if useTypeScript}} -- **TypeScript**: Static type checking -{{/if}} -- **Agent Guardrails**: Pre-commit validation and security checks - -## Development Guidelines - -### Code Style -{{#if useTypeScript}} -- Use TypeScript for all new code -- Prefer interfaces over types for object shapes -- Use strict null checks and proper error handling -{{/if}} -- Follow existing naming conventions -- Write self-documenting code with clear variable names -- Add JSDoc comments for public APIs - -### Git Workflow -- Create focused commits with clear messages -- Use conventional commit format: `type(scope): description` -- Include `AI-Generated: Yes` in commit messages for AI-created code -- All commits must pass pre-commit guardrails - -### Testing Strategy -- Write tests for all new functionality -- Maintain high test coverage -- Use descriptive test names -- Mock external dependencies appropriately - -## Security & Quality Standards - -### Pre-commit Validation -The `scripts/agent-guardrails.sh` script runs automatically before each commit and validates: -- File size limits -- Forbidden patterns (secrets, debugging code) -- Code quality metrics -- JSON syntax validation -- Security pattern detection - -### Security Guidelines -- Never commit secrets, API keys, or passwords -- Use environment variables for configuration -- Validate all user inputs -- Follow secure coding practices - -## AI Collaboration - -### AGENTS.md Integration -This project follows the AGENTS.md standard for AI-human collaboration. See `AGENTS.md` for detailed guidelines on: -- What AI agents can and cannot do -- Code generation boundaries -- Testing requirements -- Communication protocols - -### Recommended AI Workflow -1. Read `AGENTS.md` for project-specific guidelines -2. Understand the current task and requirements -3. Generate code following established patterns -4. Write comprehensive tests for new functionality -5. Update documentation as needed -6. Ensure all guardrails pass before committing +- `AGENTS.md` – canonical AI collaboration rules +- `docs/` – documentation index and guides +- `scripts/` – guardrails and automation --- **Project**: {{projectName}} **Author**: {{author}} **Last Updated**: {{currentYear}} - -*This file should be updated when development workflows or project structure changes.* diff --git a/templates/PROJECT_STRUCTURE.md.hbs b/templates/PROJECT_STRUCTURE.md.hbs index 5704886..467f23d 100644 --- a/templates/PROJECT_STRUCTURE.md.hbs +++ b/templates/PROJECT_STRUCTURE.md.hbs @@ -32,6 +32,7 @@ {{#each packages}} │ ├── {{this}}/ # {{#if (eq this "core")}}Core utilities and shared functionality{{else if (eq this "api")}}API services and endpoints{{else if (eq this "web")}}Frontend web application{{else if (eq this "shared-types")}}Shared TypeScript type definitions{{else}}{{this}} package{{/if}} │ │ ├── package.json # Package-specific configuration +│ │ ├── AGENTS.md # Package-level agent guidance {{#if ../useTypeScript}} │ │ ├── tsconfig.json # Package TypeScript config {{/if}} diff --git a/templates/README.md.hbs b/templates/README.md.hbs index 96dd67a..0673895 100644 --- a/templates/README.md.hbs +++ b/templates/README.md.hbs @@ -100,6 +100,7 @@ This project is set up for AI-assisted development with: {{/if}} {{/if}} - `{{packageManager}} run format` - Format code with Prettier +- `{{packageManager}} run format:check` - Check formatting with Prettier - `{{packageManager}} run guardrails` - Run AI code validation ### Code Quality diff --git a/templates/package.json.hbs b/templates/package.json.hbs index 765d479..7995136 100644 --- a/templates/package.json.hbs +++ b/templates/package.json.hbs @@ -28,6 +28,7 @@ {{/if}} {{/if}} "format": "prettier --write .", + "format:check": "prettier --check .", "guardrails": "./scripts/agent-guardrails.sh" }, "devDependencies": { diff --git a/templates/packages/api/AGENTS.md.hbs b/templates/packages/api/AGENTS.md.hbs new file mode 100644 index 0000000..e0576f2 --- /dev/null +++ b/templates/packages/api/AGENTS.md.hbs @@ -0,0 +1,19 @@ +# AGENTS.md (api package) + +This package inherits all rules from the repository root `AGENTS.md`. + +## Package Scope + +API services, endpoints, and server-side integrations. + +## Commands + +```bash +{{packageManager}} --filter api run test +{{packageManager}} --filter api run build +``` + +## Notes + +- Validate inputs and enforce auth boundaries. +- Maintain API contracts and update tests alongside changes. diff --git a/templates/packages/cli/AGENTS.md.hbs b/templates/packages/cli/AGENTS.md.hbs new file mode 100644 index 0000000..89c6f5f --- /dev/null +++ b/templates/packages/cli/AGENTS.md.hbs @@ -0,0 +1,19 @@ +# AGENTS.md (cli package) + +This package inherits all rules from the repository root `AGENTS.md`. + +## Package Scope + +Command-line interfaces and automation entrypoints. + +## Commands + +```bash +{{packageManager}} --filter cli run test +{{packageManager}} --filter cli run build +``` + +## Notes + +- Prefer clear user-facing output. +- Keep CLI commands stable and documented. diff --git a/templates/packages/core/AGENTS.md.hbs b/templates/packages/core/AGENTS.md.hbs new file mode 100644 index 0000000..0a4fb7d --- /dev/null +++ b/templates/packages/core/AGENTS.md.hbs @@ -0,0 +1,19 @@ +# AGENTS.md (core package) + +This package inherits all rules from the repository root `AGENTS.md`. + +## Package Scope + +Core utilities, shared functionality, and cross-cutting helpers. + +## Commands + +```bash +{{packageManager}} --filter core run test +{{packageManager}} --filter core run build +``` + +## Notes + +- Keep dependencies minimal and reusable. +- Avoid coupling to app-specific packages. diff --git a/templates/packages/shared-types/AGENTS.md.hbs b/templates/packages/shared-types/AGENTS.md.hbs new file mode 100644 index 0000000..7c1f047 --- /dev/null +++ b/templates/packages/shared-types/AGENTS.md.hbs @@ -0,0 +1,19 @@ +# AGENTS.md (shared-types package) + +This package inherits all rules from the repository root `AGENTS.md`. + +## Package Scope + +Shared TypeScript types and contracts. + +## Commands + +```bash +{{packageManager}} --filter shared-types run test +{{packageManager}} --filter shared-types run build +``` + +## Notes + +- Changes here affect every consumer package. +- Treat updates as contract changes and update tests accordingly. diff --git a/templates/packages/web/AGENTS.md.hbs b/templates/packages/web/AGENTS.md.hbs new file mode 100644 index 0000000..6c4d01b --- /dev/null +++ b/templates/packages/web/AGENTS.md.hbs @@ -0,0 +1,19 @@ +# AGENTS.md (web package) + +This package inherits all rules from the repository root `AGENTS.md`. + +## Package Scope + +Frontend application, UI components, and client integrations. + +## Commands + +```bash +{{packageManager}} --filter web run test +{{packageManager}} --filter web run build +``` + +## Notes + +- Prefer component-level tests and snapshots where appropriate. +- Keep UI changes aligned with design systems. diff --git a/tests/golden/README.md b/tests/golden/README.md index 62a28bf..6784d90 100644 --- a/tests/golden/README.md +++ b/tests/golden/README.md @@ -13,6 +13,16 @@ Golden tests are especially valuable in AI-assisted development because: ## Test Categories +### 0. Generator Output Snapshots + +Capture the scaffolded file tree and file hashes to protect the blueprint generator: + +```bash +pnpm run test-setup +``` + +The snapshot file lives at `tests/golden/setup-output.snapshot.json`. + ### 1. API Response Snapshots Capture complete API responses for critical endpoints: diff --git a/tests/golden/setup-output.snapshot.json b/tests/golden/setup-output.snapshot.json new file mode 100644 index 0000000..88e1616 --- /dev/null +++ b/tests/golden/setup-output.snapshot.json @@ -0,0 +1,82 @@ +[ + { + "path": ".eslintrc.js", + "sha256": "eeab71dcd5811364a0d8f0639c48cc1afcec7d125ad1b738f4a4ba2fbb9ff92d" + }, + { + "path": ".github/workflows/ci.yml", + "sha256": "4c546fccb0792bb14e35dca29f40f02e526401fc97736c4431652a4f6da979be" + }, + { + "path": ".gitignore", + "sha256": "dea1161932547f94b02a66086722cd7d600fd045ecd324cc0fb98a0a919550a1" + }, + { + "path": ".prettierrc", + "sha256": "a269bd3d163c78646eb66e9a6688c608c0bc206519cac760084bd41db94b2edf" + }, + { + "path": "AGENTS.md", + "sha256": "c4abcd0aad002e10202c4a921fb1e3aa4184ac517ee898a9ad7e87d9d9d4a850" + }, + { + "path": "CLAUDE.md", + "sha256": "c492dd4f08a5b852c26b359be4d9a5adf26be317e48ee508d4d9f32da0c88d44" + }, + { + "path": "CommitMessage.md", + "sha256": "fc8b3a57ad041fce2ead9fbebf772e0fa66350fb48f13546521f5cd7a7d49376" + }, + { + "path": "PR.md", + "sha256": "44910836cbfcb20915e5043def2381a77ad13962d59e66b62c5a5b0e31153a95" + }, + { + "path": "PROJECT_STRUCTURE.md", + "sha256": "c8e12a3665c4528c7097fb38f756449ee3b2bc8d960c8a07d960b094e313fe5a" + }, + { + "path": "README.md", + "sha256": "6c354aed12013b033e0778496190afcf8a6579bf9b56b7a668e5d64b035f4c7b" + }, + { + "path": "package.json", + "sha256": "278c8e9455bea2bfe0d1debab60b4bf0d67b95e49bb8a7fde066548373a9c908" + }, + { + "path": "packages/api/AGENTS.md", + "sha256": "4108339ec92ce5561444ef4b6c8767f18504dca8b3c9d602616bedfeee3f775f" + }, + { + "path": "packages/api/package.json", + "sha256": "f9861fb72043ad0808d23c9a7407480290715e981be3a91d86dcb4bfe9c02c73" + }, + { + "path": "packages/core/AGENTS.md", + "sha256": "09790c03d9aa9f13e5798513eef86f591de8d0c5c1bbf6d2751cb6f21c77c5a8" + }, + { + "path": "packages/core/package.json", + "sha256": "c0f6c70d30a648dc3b04a9650440d955dc4e61b2599bad8750647ff82fc0d735" + }, + { + "path": "packages/shared-types/AGENTS.md", + "sha256": "e4e4bbfc9334488002b07966dd6fbefc06fa7e31a09441d82a4df032a7241d48" + }, + { + "path": "packages/shared-types/package.json", + "sha256": "f15b4cc9ecc28e258a002b1c65c88ff9b5e860dbb55634574652dcb4cc3ee277" + }, + { + "path": "packages/web/AGENTS.md", + "sha256": "aac1ee02abd4185ca5637819a56b792dfb2e18d57fab148f7ea6a2c87f9380fd" + }, + { + "path": "packages/web/package.json", + "sha256": "f3624679b5a026848b4be1b11625a54a4cae979036be1e7fd2e9a48ae7498358" + }, + { + "path": "tsconfig.json", + "sha256": "83232214f321d62dcb21c2a87a2ee59845f5833aa876c7b8c0a0b947208fb7a5" + } +] \ No newline at end of file diff --git a/tests/mcp-memory/memory-store.test.js b/tests/mcp-memory/memory-store.test.js new file mode 100644 index 0000000..38d8cac --- /dev/null +++ b/tests/mcp-memory/memory-store.test.js @@ -0,0 +1,40 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs/promises'; +import { MemoryStore } from '../../src/mcp-memory/memory-store.js'; + +const createTempStore = async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'vibecode-mcp-')); + const filePath = path.join(dir, 'memory.json'); + const store = new MemoryStore({ filePath }); + await store.initialize(); + return { store, dir, filePath }; +}; + +test('MemoryStore adds and lists entries', async () => { + const { store, dir } = await createTempStore(); + await store.add({ title: 'First', content: 'Hello world', tags: ['note'] }); + const entries = await store.list(); + + assert.equal(entries.length, 1); + assert.equal(entries[0].title, 'First'); + + await fs.rm(dir, { recursive: true, force: true }); +}); + +test('MemoryStore searches and summarizes entries', async () => { + const { store, dir } = await createTempStore(); + await store.add({ title: 'Decision', content: 'Use AGENTS.md', tags: ['decision'] }); + await store.add({ title: 'Note', content: 'Remember to validate', tags: ['process'] }); + + const results = await store.search({ query: 'AGENTS', limit: 5 }); + assert.equal(results.length, 1); + assert.equal(results[0].title, 'Decision'); + + const summary = await store.summarize({ query: 'validate', limit: 5 }); + assert.match(summary, /Found 1 memories/); + + await fs.rm(dir, { recursive: true, force: true }); +}); diff --git a/tests/mcp-memory/server.test.js b/tests/mcp-memory/server.test.js new file mode 100644 index 0000000..f67fc1a --- /dev/null +++ b/tests/mcp-memory/server.test.js @@ -0,0 +1,49 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import os from 'node:os'; +import path from 'node:path'; +import fs from 'node:fs/promises'; +import { createMcpServer } from '../../src/mcp-memory/server.js'; + +const jsonRpc = async (url, payload) => { + const response = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + return response.json(); +}; + +test('MCP server handles initialize and tool calls', async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'vibecode-mcp-')); + const filePath = path.join(dir, 'memory.json'); + + const { server, start, stop } = createMcpServer({ host: '127.0.0.1', port: 0, filePath }); + const address = await start(); + const port = typeof address === 'string' ? address.split(':').pop() : address.port; + const url = `http://127.0.0.1:${port}`; + + const initResponse = await jsonRpc(url, { jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }); + assert.ok(initResponse.result.capabilities.tools); + + const addResponse = await jsonRpc(url, { + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { + name: 'add_memory', + arguments: { + title: 'Test', + content: 'Hello', + tags: ['test'] + } + } + }); + assert.ok(addResponse.result.content[0].text.includes('Hello')); + + const listResponse = await jsonRpc(url, { jsonrpc: '2.0', id: 3, method: 'resources/list', params: {} }); + assert.equal(listResponse.result.resources.length, 1); + + await stop(); + await fs.rm(dir, { recursive: true, force: true }); +}); diff --git a/tests/setup/generator-golden.test.js b/tests/setup/generator-golden.test.js new file mode 100644 index 0000000..9759a4f --- /dev/null +++ b/tests/setup/generator-golden.test.js @@ -0,0 +1,68 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import path from 'node:path'; +import fs from 'node:fs/promises'; +import crypto from 'node:crypto'; +import { spawn } from 'node:child_process'; + +const ROOT_DIR = path.resolve(process.cwd()); +const OUTPUT_DIR = path.join(ROOT_DIR, 'test-output'); +const SNAPSHOT_PATH = path.join(ROOT_DIR, 'tests', 'golden', 'setup-output.snapshot.json'); + +const runTestSetup = () => new Promise((resolve, reject) => { + const child = spawn('node', ['src/test-setup.js'], { + cwd: ROOT_DIR, + env: { + ...process.env, + VIBECODE_TEST_YEAR: '2025' + }, + stdio: 'inherit' + }); + child.on('close', (code) => { + if (code === 0) resolve(); + else reject(new Error(`test-setup failed with code ${code}`)); + }); +}); + +const listFiles = async (dir, prefix = '') => { + const entries = await fs.readdir(dir, { withFileTypes: true }); + const files = []; + for (const entry of entries) { + const entryPath = path.join(dir, entry.name); + const relativePath = path.join(prefix, entry.name); + if (entry.isDirectory()) { + files.push(...(await listFiles(entryPath, relativePath))); + } else { + files.push(relativePath); + } + } + return files.sort(); +}; + +const hashFile = async (filePath) => { + const data = await fs.readFile(filePath); + return crypto.createHash('sha256').update(data).digest('hex'); +}; + +test('generator output matches golden snapshot', async () => { + await fs.rm(OUTPUT_DIR, { recursive: true, force: true }); + await runTestSetup(); + + try { + const files = await listFiles(OUTPUT_DIR); + const snapshot = []; + + for (const file of files) { + const fullPath = path.join(OUTPUT_DIR, file); + snapshot.push({ + path: file, + sha256: await hashFile(fullPath) + }); + } + + const expected = JSON.parse(await fs.readFile(SNAPSHOT_PATH, 'utf8')); + assert.deepEqual(snapshot, expected); + } finally { + await fs.rm(OUTPUT_DIR, { recursive: true, force: true }); + } +}); From 8b6367d0010890ee7a29bd40d68108b1f5064e34 Mon Sep 17 00:00:00 2001 From: Vitaly Lobachev Date: Thu, 29 Jan 2026 12:53:29 +0100 Subject: [PATCH 2/2] fix: add required documentation sections for CI validation - AGENTS.md: Add What You Can Do, What You Cannot Do, Working with Humans, Code Standards, and Security Guidelines sections - CLAUDE.md: Add Project Architecture section Fixes Documentation Structure Validation and Validate Documentation CI checks --- AGENTS.md | 29 ++++++++++++++++++++++++++--- CLAUDE.md | 5 ++++- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5351f9c..5a62410 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,7 +58,30 @@ pnpm test --- -## 3) How to Work Safely (Human-in-the-Loop) +## What You Can Do + +- Read and analyze any file in the repository +- Propose code changes following established patterns +- Run validation commands (`make validate`, `pnpm test`, etc.) +- Create new files when explicitly requested +- Suggest improvements and refactors +- Execute safe, read-only commands + +--- + +## What You Cannot Do + +- Bypass human review for any changes +- Modify `/policies/` contents +- Add dependencies without explicit approval +- Change authentication, authorization, or security configs without approval +- Delete or weaken existing tests +- Hardcode secrets, tokens, or credentials +- Make architectural changes without asking first + +--- + +## Working with Humans **Core rules (non-negotiable):** @@ -77,7 +100,7 @@ pnpm test --- -## 4) Style & Conventions +## Code Standards - **TypeScript-first** when applicable; keep types explicit. - One primary export per file. @@ -97,7 +120,7 @@ pnpm test --- -## 6) Security & Safety +## Security Guidelines - **Never** hardcode secrets, tokens, or credentials. - Validate and sanitize user inputs. diff --git a/CLAUDE.md b/CLAUDE.md index 35cd42a..386c4e2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,12 +41,15 @@ pnpm run setup # Interactive project setup pnpm run test-setup # Deterministic generator run (test output) ``` -## Key Directories +## Project Architecture - `src/` – generator + reference MCP memory server - `templates/` – scaffold templates - `tests/` – unit/integration/golden tests - `docs/` – documentation index + guides +- `scripts/` – pre-commit guardrails and validation helpers +- `prompts/` – reusable prompt templates +- `policies/` – human review and governance rules ## AI Collaboration Rules (Pointer)