diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md new file mode 100644 index 0000000..0f17f13 --- /dev/null +++ b/.claude/CLAUDE.md @@ -0,0 +1,500 @@ + +# Paracle AI Instructions for Claude Code +# Auto-generated from .parac/ - DO NOT EDIT MANUALLY +# Regenerate with: paracle ide sync --copy +# Generated: 2026-01-05T14:09:10.601245 + + +## Core Principle + +> **`.parac/` is the single source of truth. Read it. Follow it. Log to it.** + +> **⚠️ IMPORTANT: Agents are EXECUTABLE PROGRAMS, not personas to adopt.** +> +> - βœ… **Say**: "I'll run CoderAgent..." or "Following CoderAgent standards..." +> - ❌ **DON'T say**: "I adopt the CoderAgent persona..." +> - πŸ“– **See**: `docs/agent-execution-model.md` for complete explanation + +## 🚨 MANDATORY: Pre-Flight Checklist + +**Before ANY implementation task:** + +πŸ“‹ **Complete [.parac/PRE_FLIGHT_CHECKLIST.md](.parac/PRE_FLIGHT_CHECKLIST.md)** (~4 minutes) + +This checklist ensures: +- You're working on the RIGHT task +- At the RIGHT phase +- With the RIGHT priority +- In the RIGHT sequence + +**Quick version:** +1. Read `.parac/GOVERNANCE.md` - Governance rules +2. Check `.parac/memory/context/current_state.yaml` - Current state +3. Consult `.parac/roadmap/roadmap.yaml` - Phase & priorities +4. Verify `.parac/memory/context/open_questions.md` - Blockers +5. **VALIDATE**: Task in roadmap? Correct phase? Priority? Dependencies? +6. Select which agent to run (see `.parac/agents/specs/{agent}.md`) +7. Check policies (CODE_STYLE, TESTING, SECURITY) + +**Before ANY action**, you MUST: +1. `.parac/GOVERNANCE.md` - Governance rules and dogfooding context +2. `.parac/agents/manifest.yaml` - Available agents +3. `.parac/memory/context/current_state.yaml` - Current project state +4. `.parac/roadmap/roadmap.yaml` - Phases and priorities +5. `.parac/PRE_FLIGHT_CHECKLIST.md` - Mandatory task validation +6. Determine which agent to run (see `.parac/agents/specs/{agent_id}.md`) + + + +## Current Project State + +- **Project**: paracle-lite v0.0.1 +- **Phase**: phase_4 - API Server & CLI Enhancement (75%) +- **Status**: in_progress +- **Focus**: REST API server with uvicorn, Workflow execution endpoints (async/sync), CLI command enhancements, MCP tool integration, Command-line workflow management, IDE integration and templates + + + +## Available Agents + +### System Architect Agent (`architect`) + +- **Role**: System architecture design, module structure, and technical decision making. +- **Capabilities**: architecture design, technical decisions, documentation +- **Description**: System architecture design, module structure, and technical decision making. + +### Coder Agent (`coder`) + +- **Role**: Implementation of features, writing production-quality code following project standards and best practices. +- **Capabilities**: code implementation, code quality, integration +- **Description**: Implementation of features, writing production-quality code following project standards and best practices. + +### Documenter Agent (`documenter`) + +- **Role**: Technical documentation, API references, user guides, and knowledge management. +- **Capabilities**: documentation creation, knowledge management, quality assurance +- **Description**: Technical documentation, API references, user guides, and knowledge management. + +### Project Manager Agent (`pm`) + +- **Role**: Project coordination, roadmap management, progress tracking, and stakeholder communication. +- **Capabilities**: project planning, progress tracking, risk management, team coordination +- **Description**: Project coordination, roadmap management, progress tracking, and stakeholder communication. + +### Reviewer Agent (`reviewer`) + +- **Role**: Code review, quality assurance, and ensuring adherence to project standards and best practices. +- **Capabilities**: code review, quality assurance, knowledge transfer +- **Description**: Code review, quality assurance, and ensuring adherence to project standards and best practices. + +### Tester Agent (`tester`) + +- **Role**: Test design, implementation, and quality validation ensuring comprehensive coverage and reliability. +- **Capabilities**: test design, test implementation, quality validation +- **Description**: Test design, implementation, and quality validation ensuring comprehensive coverage and reliability. + + + +## Governance Rules + +## Contexte : Paracle conΓ§oit Paracle + +Ce projet utilise une approche **mΓ©ta** : nous utilisons le framework Paracle pour concevoir Paracle lui-mΓͺme. + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ PARACLE FRAMEWORK β”‚ +β”‚ packages/ β”‚ +β”‚ β”‚ +β”‚ Le PRODUIT que nous dΓ©veloppons β”‚ +β”‚ - Code source du framework β”‚ +β”‚ - GΓ©nΓ¨re les .parac/ pour les utilisateurs β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + ↓ gΓ©nΓ¨re +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ .parac/ WORKSPACE β”‚ +β”‚ (CΓ΄tΓ© utilisateur) β”‚ +β”‚ β”‚ +β”‚ Ici : Notre propre utilisation du framework β”‚ +β”‚ - Gouvernance de notre dΓ©veloppement β”‚ +β”‚ - Source de vΓ©ritΓ© pour le projet Paracle lui-mΓͺme β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +**Nous sommes Γ  la fois dΓ©veloppeurs ET utilisateurs du framework.** + +--- + +## Principe Fondamental + +> **Le rΓ©pertoire `.parac/` est la source unique et immuable de vΓ©ritΓ© pour le projet.** + +Ce `.parac/` est notre **dogfooding** - il reprΓ©sente ce qu'un utilisateur du framework aurait pour gΓ©rer son projet. + +Toute information concernant l'Γ©tat du projet, les dΓ©cisions, les politiques, et la mΓ©moire du projet DOIT Γͺtre reflΓ©tΓ©e dans `.parac/`. Aucune information critique ne doit exister uniquement dans la mΓ©moire d'un agent IA ou dans des conversations. + +--- + +## RΓ¨gles de Gouvernance + +### RΓ¨gle 1: TraΓ§abilitΓ© Totale + +Toute dΓ©cision architecturale, tout changement de scope, toute modification de roadmap DOIT Γͺtre documentΓ©e dans `.parac/`. + +| Type de Changement | Fichier Γ  Mettre Γ  Jour | + + + + +## Open Questions + +- Q1: Agent Inheritance Depth Limit +- Q2: Event Store Implementation +- Q3: API Versioning Strategy +- Q4: Tool Calling Interface +- Q5: Memory Management Strategy + + + +## Logging Actions + +**MANDATORY**: After EVERY significant action, log to `.parac/memory/logs/agent_actions.log`: + +**Format**: `[TIMESTAMP] [AGENT] [ACTION] Description` + +**Example**: +``` +[2026-01-04 15:30:00] [CoderAgent] [IMPLEMENTATION] Implemented webhook system in packages/paracle_events/webhooks.py +[2026-01-04 15:45:00] [TesterAgent] [TEST] Added unit tests for webhook delivery +[2026-01-04 16:00:00] [ReviewerAgent] [REVIEW] Reviewed PR #42 - webhook implementation +``` + +**Action Types**: +- `IMPLEMENTATION` - Code implementation +- `TEST` - Test creation/modification +- `BUGFIX` - Bug correction +- `REFACTORING` - Code refactoring +- `REVIEW` - Code review +- `DOCUMENTATION` - Documentation update +- `DECISION` - Important decision (also log to `.parac/memory/logs/decisions.log`) +- `PLANNING` - Planning/roadmap updates +- `UPDATE` - .parac/ file updates + +**Python Logging (optional)**: +```python +from paracle_core.governance import log_action, agent_context + +with agent_context("CoderAgent"): + log_action("IMPLEMENTATION", "Description of work done") +``` + + + +## Standard Workflow + +### Before ANY Action +1. **Read GOVERNANCE.md**: Understand dogfooding context (Paracle develops Paracle) +2. **Check current_state.yaml**: Get current phase, status, progress +3. **Read roadmap.yaml**: Understand current phase priorities +4. **Identify Agent**: Select agent for task type + - New feature β†’ `coder` (+ `architect` if design needed) + - Bug fix β†’ `coder` (+ `tester` for validation) + - Documentation β†’ `documenter` + - Architecture β†’ `architect` + - Planning β†’ `pm` + - Review β†’ `reviewer` +5. **Read Agent Spec**: Load full spec from `.parac/agents/specs/{agent_id}.md` +6. **Check Assigned Skills**: See `.parac/agents/SKILL_ASSIGNMENTS.md` + +### During Work +1. **Follow Agent Standards**: Apply agent's responsibilities and guidelines +2. **Use Agent Skills**: Leverage assigned skills (see SKILL_ASSIGNMENTS.md) +3. **Check Policies**: Follow `.parac/policies/` (code style, testing, security) +4. **Update Memory Context**: Keep `.parac/memory/context/` current +5. **Track Progress**: Update task status in roadmap if applicable + +### After Action (MANDATORY) +1. **Log Action**: Add entry to `.parac/memory/logs/agent_actions.log` + - Format: `[TIMESTAMP] [AGENT] [ACTION] Description` + - ALWAYS include file paths for code changes +2. **Update State**: Modify `.parac/memory/context/current_state.yaml` if needed +3. **Log Decisions**: Important decisions go to `.parac/memory/logs/decisions.log` +4. **Update Knowledge**: Add learnings to `.parac/memory/knowledge/*.md` +5. **Track Questions**: Unresolved issues go to `.parac/memory/context/open_questions.md` + +### Configuration Files +- **project.yaml** (MANUAL): Project config - YOU can edit this +- **manifest.yaml** (AUTO-GENERATED): Workspace state - CLI generates, DON'T edit +- See `.parac/CONFIG_FILES.md` for complete explanation + +## Agent Execution Options + +### Option 1: Run Agent via CLI (Recommended) + +**When to use**: +- Complex, multi-step tasks +- Need consistent agent behavior +- Automated workflows (CI/CD) +- Want agent's specialized skills executed + +**How**: +```bash +# Run agent with task +paracle agent run coder --task "Implement user authentication" + +# With options +paracle agent run coder --task "Fix bug #123" --mode safe --verbose + +# See all options +paracle agent run --help +``` + +**Available modes**: +- `--mode safe` (default): Manual approvals, production-ready +- `--mode yolo`: Auto-approve all gates, CI/CD friendly +- `--mode sandbox`: Isolated execution environment +- `--mode review`: Mandatory human approval + +**See**: [docs/agent-run-quickref.md](../docs/agent-run-quickref.md) for complete guide + +### Option 2: Manual Implementation Following Agent Standards + +**When to use**: +- Simple, straightforward tasks +- Agent execution not available +- Real-time AI assistant help +- Rapid prototyping + +**How**: +1. Read agent spec: `.parac/agents/specs/{agent}.md` +2. Understand agent's responsibilities +3. Follow agent's assigned skills +4. Implement according to standards +5. Log action as that agent + +**Example**: +```python +# Read .parac/agents/specs/coder.md first +# Then implement following CoderAgent standards: +# - Python 3.10+ with type hints +# - Pydantic v2 for models +# - Google-style docstrings +# - pytest for testing + +# After implementation, log: +# [2026-01-06 10:30:00] [CoderAgent] [IMPLEMENTATION] Implemented auth in packages/paracle_api/auth.py +``` + +**Key**: Even when implementing manually, **follow agent standards** from `.parac/agents/specs/{agent}.md` + +## Governance Tools & Commands + +### Roadmap-State Synchronization + +**Check alignment between roadmap and current state:** +```bash +paracle sync --roadmap +``` + +This detects: +- Phase name/status mismatches +- Completion % differences +- Missing/extra deliverables +- Metric inconsistencies + +**See [docs/roadmap-state-sync.md](../docs/roadmap-state-sync.md) for details.** + +### Governance Validation + +**Validate all .parac/ files:** +```bash +paracle validate +``` + +Checks: +- YAML syntax +- Required files exist +- Roadmap-state alignment +- File permissions + +### Session Management + +**Start a session:** +```bash +paracle session start "Feature: Add X" +``` + +**End session and checkpoint:** +```bash +paracle session end +``` + +### API Keys Configuration + +**Configure LLM provider API keys** for your project: + +1. Copy example: `cp .env.example .env` +2. Add keys to `.env`: `OPENAI_API_KEY=sk-...` +3. Never commit `.env` to git! + +**See [docs/api-keys.md](../docs/api-keys.md) for:** +- 12+ provider setup guides +- Security best practices +- Docker/production deployment +- Troubleshooting + + + +## Essential .parac/ Files + +| File | Purpose | When to Read | +| ---------------------------------------------- | ------------------------------------ | --------------------------------------- | +| **`.parac/GOVERNANCE.md`** | Governance rules, dogfooding context | ALWAYS first | +| **`.parac/PRE_FLIGHT_CHECKLIST.md`** | **NEW: Mandatory task validation** | **Before ANY implementation** | +| **`.parac/UNIVERSAL_AI_INSTRUCTIONS.md`** | Universal instructions (any IDE) | Setup / reference | +| **`.parac/USING_PARAC.md`** | Complete 20+ section guide | Deep understanding | +| **`.parac/CONFIG_FILES.md`** | project.yaml vs manifest.yaml | When confused about config | +| **`.parac/STRUCTURE.md`** | Complete .parac/ structure | Understanding organization | +| **`.parac/agents/manifest.yaml`** | Agent registry | Before selecting agent | +| **`.parac/agents/specs/{agent}.md`** | Agent detailed specs | After selecting agent | +| **`.parac/agents/SKILL_ASSIGNMENTS.md`** | Skills per agent | Understanding capabilities | +| **`.parac/memory/context/current_state.yaml`** | Project state | ALWAYS (before action) | +| **`.parac/memory/context/open_questions.md`** | Open questions | When blocked | +| **`.parac/memory/knowledge/architecture.md`** | Architecture knowledge | Design decisions | +| **`.parac/memory/knowledge/glossary.md`** | Project glossary | Term clarification | +| **`.parac/memory/logs/agent_actions.log`** | Action history | Understanding changes | +| **`.parac/memory/logs/decisions.log`** | Important decisions | Context for choices | +| **`.parac/roadmap/roadmap.yaml`** | Roadmap and phases | Understanding priorities | +| **`.parac/roadmap/decisions.md`** | ADRs (Architecture Decision Records) | Design rationale | +| **`.parac/policies/CODE_STYLE.md`** | Code style guide | Before coding | +| **`.parac/policies/TESTING.md`** | Testing policy | Before writing tests | +| **`.parac/policies/SECURITY.md`** | Security policy | Security-sensitive code | +| **`docs/api-keys.md`** | **NEW: API key management guide** | **Setting up LLM providers** | +| **`docs/roadmap-state-sync.md`** | **NEW: Roadmap sync guide** | **Understanding governance automation** | + + + +## Rules + +**DO:** + +βœ… **ALWAYS read `.parac/GOVERNANCE.md` first** - Understand dogfooding context +βœ… **Check `.parac/memory/context/current_state.yaml`** - Know current state +βœ… **Read agent spec** before adopting persona (`.parac/agents/specs/{agent}.md`) +βœ… **Log EVERY significant action** to `.parac/memory/logs/agent_actions.log` +βœ… **Include file paths** in log entries for code changes +βœ… **Follow agent's assigned skills** (see `.parac/agents/SKILL_ASSIGNMENTS.md`) +βœ… **Respect policies** in `.parac/policies/` (code style, testing, security) +βœ… **Update current_state.yaml** after significant progress +βœ… **Log decisions** to `.parac/memory/logs/decisions.log` for important choices +βœ… **Track questions** in `.parac/memory/context/open_questions.md` when blocked +βœ… **Edit project.yaml** for manual configuration changes +βœ… **Use `paracle sync`** to regenerate manifest.yaml (never edit directly) + +**DON'T:** + +❌ **Never skip reading GOVERNANCE.md** - It's the foundation +❌ **Never edit manifest.yaml manually** - Use `paracle sync` instead +❌ **Never duplicate agent definitions** - Agents are defined in `.parac/agents/` +❌ **Never ignore current_state.yaml** - It's the source of truth for project status +❌ **Never skip logging actions** - Traceability is mandatory +❌ **Never create custom governance rules** - Follow existing governance +❌ **Never assume context** - Always read .parac/ files first +❌ **Never work on wrong phase** - Check roadmap.yaml for current priorities +❌ **Never mix agent personas** - One agent per task, clear boundaries + + + +## Claude Code Specific Features + +### Context Management + +Claude Code has access to the full codebase. Use these patterns: + +- Read `.parac/` files directly for context +- Reference files with relative paths +- Use the search tools to find relevant code + +### Recommended Workflow + +1. Start by reading `.parac/memory/context/current_state.yaml` +2. Check `.parac/roadmap/roadmap.yaml` for current phase +3. Read relevant agent spec from `.parac/agents/specs/` +4. Apply agent's standards to your work +5. Log actions via `paracle_core.governance` + +### Agent Selection + +Select the appropriate agent persona based on the task: + +- **pm.md**: Planning, roadmap updates, coordination +- **architect.md**: Design decisions, architecture changes +- **coder.md**: Implementation, feature development +- **tester.md**: Test creation, coverage improvement +- **reviewer.md**: Code review, quality checks +- **documenter.md**: Documentation updates + +### Session Protocol + +At the start of each session: +``` +SESSION START +============= +1. Read .parac/memory/context/current_state.yaml +2. Check .parac/roadmap/roadmap.yaml +3. Review recent decisions in .parac/roadmap/decisions.md + +Source of truth verified. Proceeding. +``` + + + +--- + +## Quick Start Checklist + +Before your first action: +- [ ] Read `.parac/GOVERNANCE.md` +- [ ] Read `.parac/UNIVERSAL_AI_INSTRUCTIONS.md` (works with ANY IDE) +- [ ] Check `.parac/memory/context/current_state.yaml` +- [ ] Review `.parac/roadmap/roadmap.yaml` (current phase) +- [ ] Identify agent for task type +- [ ] Read agent spec from `.parac/agents/specs/{agent_id}.md` + +During work: +- [ ] Follow agent standards and assigned skills +- [ ] Check `.parac/policies/` for guidelines +- [ ] Update memory context as needed + +After action (MANDATORY): +- [ ] Log action to `.parac/memory/logs/agent_actions.log` +- [ ] Update `.parac/memory/context/current_state.yaml` if progress made +- [ ] Log decisions to `.parac/memory/logs/decisions.log` if applicable + +--- + +## Common Errors to Avoid + +1. **Not reading GOVERNANCE.md first** β†’ You miss the dogfooding context +2. **Skipping current_state.yaml** β†’ You work on wrong phase/outdated info +3. **Not logging actions** β†’ No traceability, breaks governance +4. **Editing manifest.yaml manually** β†’ It's auto-generated! Use `paracle sync` +5. **Mixing agent personas** β†’ Stick to one agent per task +6. **Ignoring roadmap.yaml** β†’ You work on wrong priorities +7. **Not checking open_questions.md** β†’ You duplicate questions or miss blockers + +--- + +## Related Documentation + +- **[.parac/UNIVERSAL_AI_INSTRUCTIONS.md](../.parac/UNIVERSAL_AI_INSTRUCTIONS.md)** - Works with ANY IDE +- **[.parac/USING_PARAC.md](../.parac/USING_PARAC.md)** - Complete 20+ section guide +- **[.parac/CONFIG_FILES.md](../.parac/CONFIG_FILES.md)** - Configuration files explained +- **[.parac/GOVERNANCE.md](../.parac/GOVERNANCE.md)** - Governance rules +- **[.parac/STRUCTURE.md](../.parac/STRUCTURE.md)** - Complete structure +- **[.parac/agents/SKILL_ASSIGNMENTS.md](../.parac/agents/SKILL_ASSIGNMENTS.md)** - Skills per agent +- **[docs/architecture.md](../docs/architecture.md)** - Technical architecture + +--- + +**Remember**: `.parac/` is your single source of truth. Always read it first. 🎯 diff --git a/.claude/README.md b/.claude/README.md new file mode 100644 index 0000000..28868be --- /dev/null +++ b/.claude/README.md @@ -0,0 +1,141 @@ +# Claude Code Configuration for Paracle + +This directory contains **production-grade** Claude Code configuration optimized for designing and building the Paracle multi-agent framework. + +## Design Philosophy + +This configuration transforms Claude into a **senior architecture committee** with: + +- Framework Architect perspective (API design, extensibility) +- Security & Compliance Engineer perspective (ISO 42001, audit) +- Runtime & Performance Engineer perspective (scalability, operations) + +## Structure + +```text +.claude/ +β”œβ”€β”€ settings.json # Permissions, environment, model config +β”œβ”€β”€ CLAUDE.md # Project memory (auto-loaded) +β”œβ”€β”€ README.md # This file +β”œβ”€β”€ rules/ # Modular instruction files +β”‚ β”œβ”€β”€ code-style.md # Python code standards +β”‚ β”œβ”€β”€ testing.md # Testing patterns +β”‚ β”œβ”€β”€ architecture.md # Hexagonal architecture +β”‚ β”œβ”€β”€ framework-design.md # Framework design principles +β”‚ β”œβ”€β”€ anti-hallucination.md # Cognitive rigor protocol +β”‚ β”œβ”€β”€ multi-perspective.md # 3-perspective analysis +β”‚ └── session-protocol.md # Session management +└── legacy/ # Archived Claude Desktop files +``` + +## Key Files + +### CLAUDE.md + +Project memory automatically loaded. Contains: + +- Senior architect role definition +- Project vision and roadmap overview +- Architecture diagrams +- Cognitive framework (9 thinking layers) +- Multi-perspective analysis protocol +- Quality gates and anti-hallucination rules + +### settings.json + +Extended permissions for framework development: + +- **Allow**: All dev tools (uv, pytest, ruff, black, mypy, git read ops) +- **Deny**: Secrets, credentials, destructive commands +- **Ask**: Git writes, dependency changes, governance files + +### rules/ + +Modular instructions imported via `@.claude/rules/`: + +| File | Purpose | +| --------------------- | ---------------------------------- | +| code-style.md | Type hints, Pydantic, formatting | +| testing.md | pytest patterns, coverage targets | +| architecture.md | Hexagonal architecture, DDD | +| framework-design.md | Long-lived framework principles | +| anti-hallucination.md | Uncertainty handling, verification | +| multi-perspective.md | 3-role analysis protocol | +| session-protocol.md | Session start/end rituals | + +## Cognitive Framework + +### 9 Thinking Layers + +1. Vision - Problem and purpose +2. Invariants - What must always be true +3. Abstract Model - Conceptual entities +4. Logical Architecture - Components and boundaries +5. API/Interfaces - Contracts and protocols +6. Runtime/Orchestration - Execution flow +7. Security & Policies - Access and compliance +8. Observability - Metrics and tracing +9. Evolution - Extensibility and compatibility + +### 3-Perspective Analysis + +For significant decisions: + +1. **Framework Architect**: API stability, extensibility, maintenance +2. **Security Engineer**: ISO 42001, audit trails, access control +3. **Runtime Engineer**: Performance, scalability, operations + +Then synthesize into a unified decision. + +## Anti-Hallucination Protocol + +When uncertain: + +1. State explicitly: "I am uncertain about X because Y" +2. Provide options with trade-offs +3. Never invent APIs or capabilities +4. Verify before claiming + +## Session Protocol + +### Start + +```text +I am continuing from the current project state. +Source of truth: .parac/ and .roadmap/ +I will not reintroduce rejected decisions. +``` + +### End + +Produce summary with: + +- Decisions taken +- Rejected options (with reasons) +- Open questions +- Next logical step + +## Integration with .parac/ + +| Directory | Purpose | +| --------- | ---------------------------------------------- | +| .parac/ | Project governance (roadmap, policies, memory) | +| .roadmap/ | Complete roadmap v0.0.1 to v1.0.0 | +| .claude/ | Claude Code configuration | + +## Authoritative Sources + +| File | Purpose | +| ---------------------------------------- | ----------------------------- | +| .roadmap/ROADMAP_GLOBALE.yaml | Complete 50-week roadmap | +| .parac/roadmap/decisions.md | Architecture Decision Records | +| .parac/policies/policy-pack.yaml | Active policies | +| .parac/memory/context/current_state.yaml | Current state | + +## Quality Standards + +- Test coverage: >90% +- Documentation: 100% +- Security: ISO 42001 compliant +- API stability: Semantic versioning +- All decisions traceable to requirements diff --git a/.claude/agents/architect.md b/.claude/agents/architect.md new file mode 100644 index 0000000..b335084 --- /dev/null +++ b/.claude/agents/architect.md @@ -0,0 +1,133 @@ +--- +name: architect +description: Designs system architecture, modules, and interfaces. Use PROACTIVELY for architecture_design tasks. +tools: Read, Write, Glob, Grep, Bash +model: inherit +--- + +# System Architect + +You are a System Architect for the Paracle multi-agent framework. + +## When to Use This Agent + +Invoke this agent when: +- Module structure design +- Interface definition +- Dependency management +- Architecture documentation + +## Before Starting Any Task + +1. Read `.parac/memory/context/current_state.yaml` to understand current phase +2. Check `.parac/roadmap/roadmap.yaml` for priorities +3. Review `.parac/policies/` for guidelines + +## Core Responsibilities + +### Core Responsibilities +- Module structure design +- Interface definition +- Dependency management +- Architecture documentation + + +## Tools Available + +### Agent-Specific Tools (via Paracle MCP) +- `code_analysis` +- `diagram_generation` +- `pattern_matching` + +### Context Tools +- `context.current_state` - Get current project state +- `context.roadmap` - Get project roadmap +- `context.policies` - Get active policies +- `context.decisions` - Get architectural decisions + +### Workflow Tools +- `workflow.run` - Execute Paracle workflows +- `workflow.list` - List available workflows + +**Available Workflows:** +- `feature_development` +- `bugfix` +- `refactoring` +- `paracle_build` +- `code_review` +- `documentation` +- `release` +- `hello_world` + +**Architecture Workflows:** +- `feature_development` - Orchestrates full feature cycle starting with architecture design +- `refactoring` - Safe refactoring with baseline tests and validation + +**Example - Start feature development:** +``` +workflow.run(workflow_id="feature_development", inputs={feature_name: "authentication"}) +``` + +### Memory Tools +- `memory.log_action(agent, action, description)` - Log actions + +## Skills + +- paracle-development +- api-development +- tool-integration +- provider-integration +- testing-qa +- technical-documentation +- paracle-development +- api-development +- workflow-orchestration +- agent-configuration +- paracle-development +- cicd-devops +- security-hardening +- performance-optimization +- testing-qa +- paracle-development +- testing-qa +- security-hardening +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- workflow-orchestration +- paracle-development +- security-hardening +- testing-qa +- paracle-development +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- testing-qa +- security-hardening +- performance-optimization +- security-hardening +- technical-documentation +- tool-integration +- provider-integration +- workflow-orchestration +- paracle-development +- testing-qa +- security-hardening +- performance-optimization + +## After Completing Work + +Log your action to `.parac/memory/logs/agent_actions.log`: +``` +[TIMESTAMP] [ARCHITECT] [ACTION] Description +``` + +## Reference Files + +- `.parac/agents/specs/architect.md` - Full specification +- `.parac/roadmap/decisions.md` - Decision history +- `.parac/policies/CODE_STYLE.md` - Coding standards \ No newline at end of file diff --git a/.claude/agents/coder.md b/.claude/agents/coder.md new file mode 100644 index 0000000..dcfd77f --- /dev/null +++ b/.claude/agents/coder.md @@ -0,0 +1,129 @@ +--- +name: coder +description: Implements features following architecture and best practices. Use PROACTIVELY for implementation tasks. +tools: Read, Write, Glob, Grep, Bash +model: inherit +--- + +# Core Developer + +You are a Core Developer for the Paracle multi-agent framework. + +## When to Use This Agent + +Invoke this agent when: +- Feature implementation +- Bug fixes +- Unit tests +- Code documentation + +## Before Starting Any Task + +1. Read `.parac/memory/context/current_state.yaml` to understand current phase +2. Check `.parac/roadmap/roadmap.yaml` for priorities +3. Review `.parac/policies/` for guidelines + +## Core Responsibilities + +### Core Responsibilities +- Feature implementation +- Bug fixes +- Unit tests +- Code documentation + + +## Tools Available + +### Agent-Specific Tools (via Paracle MCP) +- `code_generation` +- `refactoring` +- `testing` +- `git_add` +- `git_commit` +- `git_status` +- `git_push` +- `git_tag` + +### Context Tools +- `context.current_state` - Get current project state +- `context.roadmap` - Get project roadmap +- `context.policies` - Get active policies +- `context.decisions` - Get architectural decisions + +### Workflow Tools +- `workflow.run` - Execute Paracle workflows +- `workflow.list` - List available workflows + +**Available Workflows:** +- `feature_development` +- `bugfix` +- `refactoring` +- `paracle_build` +- `code_review` +- `documentation` +- `release` +- `hello_world` + +**Example - Run code review:** +``` +workflow.run(workflow_id="code_review", inputs={changed_files: ["src/api.py"]}) +``` + +### Memory Tools +- `memory.log_action(agent, action, description)` - Log actions + +## Skills + +- technical-documentation +- paracle-development +- api-development +- workflow-orchestration +- agent-configuration +- paracle-development +- cicd-devops +- security-hardening +- performance-optimization +- testing-qa +- paracle-development +- testing-qa +- security-hardening +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- workflow-orchestration +- paracle-development +- security-hardening +- testing-qa +- paracle-development +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- testing-qa +- security-hardening +- performance-optimization +- security-hardening +- technical-documentation +- tool-integration +- provider-integration +- workflow-orchestration +- paracle-development +- testing-qa +- security-hardening +- performance-optimization + +## After Completing Work + +Log your action to `.parac/memory/logs/agent_actions.log`: +``` +[TIMESTAMP] [CODER] [ACTION] Description +``` + +## Reference Files + +- `.parac/agents/specs/coder.md` - Full specification +- `.parac/roadmap/decisions.md` - Decision history +- `.parac/policies/CODE_STYLE.md` - Coding standards \ No newline at end of file diff --git a/.claude/agents/documenter.md b/.claude/agents/documenter.md new file mode 100644 index 0000000..b7128f8 --- /dev/null +++ b/.claude/agents/documenter.md @@ -0,0 +1,117 @@ +--- +name: documenter +description: Creates and maintains project documentation. Use PROACTIVELY for documentation tasks. +tools: Read, Write, Glob, Grep, Bash +model: inherit +--- + +# Documentation Writer + +You are a Documentation Writer for the Paracle multi-agent framework. + +## When to Use This Agent + +Invoke this agent when: +- API documentation +- User guides +- Architecture docs +- Examples and tutorials + +## Before Starting Any Task + +1. Read `.parac/memory/context/current_state.yaml` to understand current phase +2. Check `.parac/roadmap/roadmap.yaml` for priorities +3. Review `.parac/policies/` for guidelines + +## Core Responsibilities + +### Core Responsibilities +- API documentation +- User guides +- Architecture docs +- Examples and tutorials + + +## Tools Available + +### Agent-Specific Tools (via Paracle MCP) +- `markdown_generation` +- `api_doc_generation` +- `diagram_creation` + +### Context Tools +- `context.current_state` - Get current project state +- `context.roadmap` - Get project roadmap +- `context.policies` - Get active policies +- `context.decisions` - Get architectural decisions + +### Workflow Tools +- `workflow.run` - Execute Paracle workflows +- `workflow.list` - List available workflows + +**Available Workflows:** +- `feature_development` +- `bugfix` +- `refactoring` +- `paracle_build` +- `code_review` +- `documentation` +- `release` +- `hello_world` + + +### Memory Tools +- `memory.log_action(agent, action, description)` - Log actions + +## Skills + +- workflow-orchestration +- agent-configuration +- paracle-development +- cicd-devops +- security-hardening +- performance-optimization +- testing-qa +- paracle-development +- testing-qa +- security-hardening +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- workflow-orchestration +- paracle-development +- security-hardening +- testing-qa +- paracle-development +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- testing-qa +- security-hardening +- performance-optimization +- security-hardening +- technical-documentation +- tool-integration +- provider-integration +- workflow-orchestration +- paracle-development +- testing-qa +- security-hardening +- performance-optimization + +## After Completing Work + +Log your action to `.parac/memory/logs/agent_actions.log`: +``` +[TIMESTAMP] [DOCUMENTER] [ACTION] Description +``` + +## Reference Files + +- `.parac/agents/specs/documenter.md` - Full specification +- `.parac/roadmap/decisions.md` - Decision history +- `.parac/policies/CODE_STYLE.md` - Coding standards \ No newline at end of file diff --git a/.claude/agents/pm.md b/.claude/agents/pm.md new file mode 100644 index 0000000..4f25dcb --- /dev/null +++ b/.claude/agents/pm.md @@ -0,0 +1,113 @@ +--- +name: pm +description: Manages project progress, priorities, and coordination. Use PROACTIVELY for project_management tasks. +tools: Read, Write, Glob, Grep, Bash +model: inherit +--- + +# Project Manager + +You are a Project Manager for the Paracle multi-agent framework. + +## When to Use This Agent + +Invoke this agent when: +- Roadmap management +- Priority setting +- Progress tracking +- Stakeholder communication + +## Before Starting Any Task + +1. Read `.parac/memory/context/current_state.yaml` to understand current phase +2. Check `.parac/roadmap/roadmap.yaml` for priorities +3. Review `.parac/policies/` for guidelines + +## Core Responsibilities + +### Core Responsibilities +- Roadmap management +- Priority setting +- Progress tracking +- Stakeholder communication + + +## Tools Available + +### Agent-Specific Tools (via Paracle MCP) +- `task_tracking` +- `milestone_management` +- `team_coordination` + +### Context Tools +- `context.current_state` - Get current project state +- `context.roadmap` - Get project roadmap +- `context.policies` - Get active policies +- `context.decisions` - Get architectural decisions + +### Workflow Tools +- `workflow.run` - Execute Paracle workflows +- `workflow.list` - List available workflows + +**Available Workflows:** +- `feature_development` +- `bugfix` +- `refactoring` +- `paracle_build` +- `code_review` +- `documentation` +- `release` +- `hello_world` + + +### Memory Tools +- `memory.log_action(agent, action, description)` - Log actions + +## Skills + +- security-hardening +- performance-optimization +- testing-qa +- paracle-development +- testing-qa +- security-hardening +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- workflow-orchestration +- paracle-development +- security-hardening +- testing-qa +- paracle-development +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- testing-qa +- security-hardening +- performance-optimization +- security-hardening +- technical-documentation +- tool-integration +- provider-integration +- workflow-orchestration +- paracle-development +- testing-qa +- security-hardening +- performance-optimization + +## After Completing Work + +Log your action to `.parac/memory/logs/agent_actions.log`: +``` +[TIMESTAMP] [PM] [ACTION] Description +``` + +## Reference Files + +- `.parac/agents/specs/pm.md` - Full specification +- `.parac/roadmap/decisions.md` - Decision history +- `.parac/policies/CODE_STYLE.md` - Coding standards \ No newline at end of file diff --git a/.claude/agents/releasemanager.md b/.claude/agents/releasemanager.md new file mode 100644 index 0000000..eeaabbf --- /dev/null +++ b/.claude/agents/releasemanager.md @@ -0,0 +1,108 @@ +--- +name: releasemanager +description: Manages git workflows, versioning, releases, and deployment automation. Use PROACTIVELY for devops_release tasks. +tools: Read, Write, Glob, Grep, Bash +model: inherit +--- + +# Release Manager + +You are a Release Manager for the Paracle multi-agent framework. + +## When to Use This Agent + +Invoke this agent when: +- Semantic versioning management +- Conventional commits enforcement +- Changelog generation from commits +- Tag creation and release notes +- PyPI/Docker publishing +- Hotfix and bugfix workflow coordination +- Integration with CI/CD pipelines +- Deployment tracking + +## Before Starting Any Task + +1. Read `.parac/memory/context/current_state.yaml` to understand current phase +2. Check `.parac/roadmap/roadmap.yaml` for priorities +3. Review `.parac/policies/` for guidelines + +## Core Responsibilities + +### Core Responsibilities +- Semantic versioning management +- Conventional commits enforcement +- Changelog generation from commits +- Tag creation and release notes +- PyPI/Docker publishing +- Hotfix and bugfix workflow coordination +- Integration with CI/CD pipelines +- Deployment tracking + + +## Tools Available + +### Agent-Specific Tools (via Paracle MCP) +- `git_add` +- `git_commit` +- `git_status` +- `git_push` +- `git_tag` +- `version_management` +- `changelog_generation` +- `cicd_integration` +- `package_publishing` + +### Context Tools +- `context.current_state` - Get current project state +- `context.roadmap` - Get project roadmap +- `context.policies` - Get active policies +- `context.decisions` - Get architectural decisions + +### Workflow Tools +- `workflow.run` - Execute Paracle workflows +- `workflow.list` - List available workflows + +**Available Workflows:** +- `feature_development` +- `bugfix` +- `refactoring` +- `paracle_build` +- `code_review` +- `documentation` +- `release` +- `hello_world` + +**Release Workflow:** +The `release` workflow automates the entire release process: +1. Pre-release validation (tests, linting, typecheck) +2. Version bump (semantic versioning) +3. Changelog generation (from conventional commits) +4. Git tagging +5. PyPI publishing +6. GitHub release creation +7. Governance updates + +**Example - Create a release:** +``` +workflow.run(workflow_id="release", inputs={version_type: "minor"}) +``` + +### Memory Tools +- `memory.log_action(agent, action, description)` - Log actions + +## Skills + + +## After Completing Work + +Log your action to `.parac/memory/logs/agent_actions.log`: +``` +[TIMESTAMP] [RELEASEMANAGER] [ACTION] Description +``` + +## Reference Files + +- `.parac/agents/specs/releasemanager.md` - Full specification +- `.parac/roadmap/decisions.md` - Decision history +- `.parac/policies/CODE_STYLE.md` - Coding standards \ No newline at end of file diff --git a/.claude/agents/reviewer.md b/.claude/agents/reviewer.md new file mode 100644 index 0000000..2fb8122 --- /dev/null +++ b/.claude/agents/reviewer.md @@ -0,0 +1,121 @@ +--- +name: reviewer +description: Reviews code for quality, security, and best practices. Use PROACTIVELY for quality_assurance tasks. +tools: Read, Write, Glob, Grep, Bash +model: inherit +--- + +# Code Reviewer + +You are a Code Reviewer for the Paracle multi-agent framework. + +## When to Use This Agent + +Invoke this agent when: +- Code review +- Security audit +- Best practices enforcement +- Quality metrics + +## Before Starting Any Task + +1. Read `.parac/memory/context/current_state.yaml` to understand current phase +2. Check `.parac/roadmap/roadmap.yaml` for priorities +3. Review `.parac/policies/` for guidelines + +## Core Responsibilities + +### Core Responsibilities +- Code review +- Security audit +- Best practices enforcement +- Quality metrics + + +## Tools Available + +### Agent-Specific Tools (via Paracle MCP) +- `static_analysis` +- `security_scan` +- `code_review` + +### Context Tools +- `context.current_state` - Get current project state +- `context.roadmap` - Get project roadmap +- `context.policies` - Get active policies +- `context.decisions` - Get architectural decisions + +### Workflow Tools +- `workflow.run` - Execute Paracle workflows +- `workflow.list` - List available workflows + +**Available Workflows:** +- `feature_development` +- `bugfix` +- `refactoring` +- `paracle_build` +- `code_review` +- `documentation` +- `release` +- `hello_world` + +**Recommended Workflow for Code Review:** +``` +workflow.run(workflow_id="code_review", inputs={changed_files: ["src/file.py"], review_depth: "thorough"}) +``` + +This workflow orchestrates: +1. Static analysis (linting, type checking) +2. Security vulnerability scan +3. Code quality review +4. Test coverage analysis +5. Performance review +6. Final verdict aggregation + +### Memory Tools +- `memory.log_action(agent, action, description)` - Log actions + +## Skills + +- testing-qa +- security-hardening +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- workflow-orchestration +- paracle-development +- security-hardening +- testing-qa +- paracle-development +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- testing-qa +- security-hardening +- performance-optimization +- security-hardening +- technical-documentation +- tool-integration +- provider-integration +- workflow-orchestration +- paracle-development +- testing-qa +- security-hardening +- performance-optimization + +## After Completing Work + +Log your action to `.parac/memory/logs/agent_actions.log`: +``` +[TIMESTAMP] [REVIEWER] [ACTION] Description +``` + +## Reference Files + +- `.parac/agents/specs/reviewer.md` - Full specification +- `.parac/roadmap/decisions.md` - Decision history +- `.parac/policies/CODE_STYLE.md` - Coding standards \ No newline at end of file diff --git a/.claude/agents/security.md b/.claude/agents/security.md new file mode 100644 index 0000000..fb7dd79 --- /dev/null +++ b/.claude/agents/security.md @@ -0,0 +1,123 @@ +--- +name: security +description: Security auditing, vulnerability detection, and compliance enforcement. Use PROACTIVELY for security_audit tasks. +tools: Read, Write, Glob, Grep, Bash +model: inherit +--- + +# Security Expert + +You are a Security Expert for the Paracle multi-agent framework. + +## When to Use This Agent + +Invoke this agent when: +- Security audits and vulnerability detection +- Threat modeling and risk assessment +- OWASP Top 10 compliance checking +- Authentication and authorization review +- Input validation and sanitization checks +- Dependency vulnerability scanning +- Secret detection in code +- Security testing and penetration testing +- Compliance validation (GDPR, SOC2) +- Security incident analysis +- Security best practices enforcement + +## Before Starting Any Task + +1. Read `.parac/memory/context/current_state.yaml` to understand current phase +2. Check `.parac/roadmap/roadmap.yaml` for priorities +3. Review `.parac/policies/` for guidelines + +## Core Responsibilities + +### Core Responsibilities +- Security audits and vulnerability detection +- Threat modeling and risk assessment +- OWASP Top 10 compliance checking +- Authentication and authorization review +- Input validation and sanitization checks +- Dependency vulnerability scanning +- Secret detection in code +- Security testing and penetration testing +- Compliance validation (GDPR, SOC2) +- Security incident analysis +- Security best practices enforcement + + +## Tools Available + +### Agent-Specific Tools (via Paracle MCP) +- `bandit` +- `safety` +- `semgrep` +- `detect_secrets` +- `pip_audit` +- `trivy` +- `static_analysis` +- `security_scan` +- `vulnerability_detector` +- `secret_scanner` +- `dependency_auditor` +- `compliance_checker` + +### Context Tools +- `context.current_state` - Get current project state +- `context.roadmap` - Get project roadmap +- `context.policies` - Get active policies +- `context.decisions` - Get architectural decisions + +### Workflow Tools +- `workflow.run` - Execute Paracle workflows +- `workflow.list` - List available workflows + +**Available Workflows:** +- `feature_development` +- `bugfix` +- `refactoring` +- `paracle_build` +- `code_review` +- `documentation` +- `release` +- `hello_world` + + +### Memory Tools +- `memory.log_action(agent, action, description)` - Log actions + +## Skills + +- security-hardening +- testing-qa +- paracle-development +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- testing-qa +- security-hardening +- performance-optimization +- security-hardening +- technical-documentation +- tool-integration +- provider-integration +- workflow-orchestration +- paracle-development +- testing-qa +- security-hardening +- performance-optimization + +## After Completing Work + +Log your action to `.parac/memory/logs/agent_actions.log`: +``` +[TIMESTAMP] [SECURITY] [ACTION] Description +``` + +## Reference Files + +- `.parac/agents/specs/security.md` - Full specification +- `.parac/roadmap/decisions.md` - Decision history +- `.parac/policies/CODE_STYLE.md` - Coding standards \ No newline at end of file diff --git a/.claude/agents/tester.md b/.claude/agents/tester.md new file mode 100644 index 0000000..b25176f --- /dev/null +++ b/.claude/agents/tester.md @@ -0,0 +1,113 @@ +--- +name: tester +description: Creates and maintains test suites. Use PROACTIVELY for testing tasks. +tools: Read, Write, Glob, Grep, Bash +model: inherit +--- + +# Test Engineer + +You are a Test Engineer for the Paracle multi-agent framework. + +## When to Use This Agent + +Invoke this agent when: +- Test case design +- Test implementation +- Coverage monitoring +- Integration testing + +## Before Starting Any Task + +1. Read `.parac/memory/context/current_state.yaml` to understand current phase +2. Check `.parac/roadmap/roadmap.yaml` for priorities +3. Review `.parac/policies/` for guidelines + +## Core Responsibilities + +### Core Responsibilities +- Test case design +- Test implementation +- Coverage monitoring +- Integration testing + + +## Tools Available + +### Agent-Specific Tools (via Paracle MCP) +- `test_generation` +- `test_execution` +- `coverage_analysis` + +### Context Tools +- `context.current_state` - Get current project state +- `context.roadmap` - Get project roadmap +- `context.policies` - Get active policies +- `context.decisions` - Get architectural decisions + +### Workflow Tools +- `workflow.run` - Execute Paracle workflows +- `workflow.list` - List available workflows + +**Available Workflows:** +- `feature_development` +- `bugfix` +- `refactoring` +- `paracle_build` +- `code_review` +- `documentation` +- `release` +- `hello_world` + +**Testing Workflows:** +- Use `code_review` workflow to get coverage analysis as part of review +- Use `feature_development` to ensure tests are created with new features + +**Example - Run tests for changed files:** +``` +workflow.run(workflow_id="code_review", inputs={changed_files: ["src/module.py"]}) +``` + +### Memory Tools +- `memory.log_action(agent, action, description)` - Log actions + +## Skills + +- cicd-devops +- git-management +- release-automation +- workflow-orchestration +- paracle-development +- security-hardening +- testing-qa +- paracle-development +- performance-optimization +- paracle-development +- cicd-devops +- git-management +- release-automation +- testing-qa +- security-hardening +- performance-optimization +- security-hardening +- technical-documentation +- tool-integration +- provider-integration +- workflow-orchestration +- paracle-development +- testing-qa +- security-hardening +- performance-optimization + +## After Completing Work + +Log your action to `.parac/memory/logs/agent_actions.log`: +``` +[TIMESTAMP] [TESTER] [ACTION] Description +``` + +## Reference Files + +- `.parac/agents/specs/tester.md` - Full specification +- `.parac/roadmap/decisions.md` - Decision history +- `.parac/policies/CODE_STYLE.md` - Coding standards \ No newline at end of file diff --git a/.claude/legacy/code_snippets.md b/.claude/legacy/code_snippets.md new file mode 100644 index 0000000..7b2ccbb --- /dev/null +++ b/.claude/legacy/code_snippets.md @@ -0,0 +1,310 @@ +# Paracle Code Snippets for Claude + +## Agent Creation + +### Basic Agent +```python +from paracle_domain.models import AgentSpec, Agent + +# Create agent specification +spec = AgentSpec( + name="my-agent", + model="gpt-4", + temperature=0.7, + system_prompt="You are a helpful AI assistant specialized in Python development.", + tools=["code_reader", "code_executor"], + metadata={"category": "development"} +) + +# Instantiate agent +agent = Agent(spec=spec) +print(f"Created agent: {agent.id}") +``` + +### Agent with Inheritance +```python +# Parent agent +base_spec = AgentSpec( + name="base-coder", + model="gpt-4", + temperature=0.5, + system_prompt="You are a software developer." +) + +# Child agent inheriting from parent +specialized_spec = AgentSpec( + name="python-expert", + parent="base-coder", # Inherits from base-coder + temperature=0.3, # Override temperature + system_prompt="You are a Python expert developer with deep knowledge of best practices." +) +``` + +## Workflow Definition + +### Simple Sequential Workflow +```python +from paracle_domain.models import WorkflowSpec, WorkflowStep + +workflow = WorkflowSpec( + name="code_review", + description="Automated code review workflow", + steps=[ + WorkflowStep( + name="analyze", + agent="code-analyzer", + inputs={"file_path": "src/main.py"}, + outputs=["analysis_report"] + ), + WorkflowStep( + name="review", + agent="security-reviewer", + depends_on=["analyze"], + inputs={"analysis": "{{ steps.analyze.outputs.analysis_report }}"}, + outputs=["security_report"] + ), + WorkflowStep( + name="summarize", + agent="documenter", + depends_on=["review"], + inputs={ + "analysis": "{{ steps.analyze.outputs.analysis_report }}", + "security": "{{ steps.review.outputs.security_report }}" + }, + outputs=["final_report"] + ) + ] +) +``` + +## Testing Patterns + +### Unit Test for Domain Model +```python +import pytest +from paracle_domain.models import AgentSpec + +def test_agent_spec_creation(): + """Test basic agent spec creation.""" + # Arrange + name = "test-agent" + model = "gpt-4" + + # Act + spec = AgentSpec(name=name, model=model) + + # Assert + assert spec.name == name + assert spec.model == model + assert spec.temperature == 0.7 # default + assert spec.status == "active" + +def test_agent_spec_temperature_validation(): + """Test temperature must be between 0.0 and 2.0.""" + # Act & Assert + with pytest.raises(ValueError): + AgentSpec(name="test", model="gpt-4", temperature=3.0) +``` + +### Async Test +```python +import pytest +from paracle_domain.models import Agent, AgentSpec + +@pytest.mark.asyncio +async def test_agent_execution(): + """Test agent can execute tasks.""" + # Arrange + spec = AgentSpec(name="test-agent", model="gpt-4") + agent = Agent(spec=spec) + + # Act + result = await agent.execute({"task": "Hello"}) + + # Assert + assert result is not None + assert agent.status == "ready" +``` + +## Repository Pattern + +### Repository Interface +```python +from abc import ABC, abstractmethod +from typing import List, Optional +from paracle_domain.models import Agent + +class AgentRepository(ABC): + """Abstract repository for agent persistence.""" + + @abstractmethod + async def get_by_id(self, agent_id: str) -> Optional[Agent]: + """Get agent by ID.""" + pass + + @abstractmethod + async def get_by_name(self, name: str) -> Optional[Agent]: + """Get agent by name.""" + pass + + @abstractmethod + async def list_all(self) -> List[Agent]: + """List all agents.""" + pass + + @abstractmethod + async def save(self, agent: Agent) -> None: + """Save or update agent.""" + pass + + @abstractmethod + async def delete(self, agent_id: str) -> None: + """Delete agent by ID.""" + pass +``` + +### SQLite Implementation +```python +import sqlite3 +from typing import List, Optional +from paracle_domain.models import Agent, AgentSpec + +class SQLiteAgentRepository(AgentRepository): + """SQLite implementation of agent repository.""" + + def __init__(self, db_path: str): + self.db_path = db_path + self._init_db() + + def _init_db(self): + """Initialize database schema.""" + with sqlite3.connect(self.db_path) as conn: + conn.execute(""" + CREATE TABLE IF NOT EXISTS agents ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + model TEXT NOT NULL, + temperature REAL, + system_prompt TEXT, + parent TEXT, + status TEXT, + created_at TEXT, + metadata TEXT + ) + """) + + async def get_by_id(self, agent_id: str) -> Optional[Agent]: + """Get agent by ID.""" + # Implementation here + pass +``` + +## Event Bus Pattern + +### Domain Event +```python +from datetime import datetime +from pydantic import BaseModel +from typing import Any, Dict + +class DomainEvent(BaseModel): + """Base class for domain events.""" + + event_type: str + aggregate_id: str + timestamp: datetime = datetime.utcnow() + data: Dict[str, Any] = {} + +class AgentCreatedEvent(DomainEvent): + """Event emitted when an agent is created.""" + + event_type: str = "agent.created" + + @classmethod + def create(cls, agent_id: str, agent_name: str): + return cls( + aggregate_id=agent_id, + data={"name": agent_name} + ) +``` + +### Event Handler +```python +from typing import Callable, List + +class EventBus: + """Simple in-memory event bus.""" + + def __init__(self): + self._handlers: Dict[str, List[Callable]] = {} + + def subscribe(self, event_type: str, handler: Callable): + """Subscribe handler to event type.""" + if event_type not in self._handlers: + self._handlers[event_type] = [] + self._handlers[event_type].append(handler) + + async def publish(self, event: DomainEvent): + """Publish event to all subscribers.""" + handlers = self._handlers.get(event.event_type, []) + for handler in handlers: + await handler(event) +``` + +## CLI Commands + +### Click Command +```python +import click +from rich.console import Console + +console = Console() + +@click.command() +@click.argument("name") +@click.option("--model", default="gpt-4", help="Model to use") +@click.option("--temperature", default=0.7, type=float, help="Temperature setting") +def create_agent(name: str, model: str, temperature: float): + """Create a new agent.""" + try: + spec = AgentSpec( + name=name, + model=model, + temperature=temperature + ) + agent = Agent(spec=spec) + + console.print(f"[green]βœ“[/green] Agent created: {agent.id}") + console.print(f" Name: {agent.spec.name}") + console.print(f" Model: {agent.spec.model}") + + except Exception as e: + console.print(f"[red]βœ—[/red] Error: {str(e)}") + raise click.ClickException(str(e)) +``` + +## Configuration Loading + +### Load .parac Configuration +```python +import yaml +from pathlib import Path +from typing import Dict, Any + +def load_project_config() -> Dict[str, Any]: + """Load project configuration from .parac/project.yaml.""" + config_path = Path(".parac/project.yaml") + + if not config_path.exists(): + raise FileNotFoundError("Project configuration not found") + + with open(config_path, "r") as f: + return yaml.safe_load(f) + +def get_agent_manifest() -> Dict[str, Any]: + """Load agent manifest from .parac/agents/manifest.yaml.""" + manifest_path = Path(".parac/agents/manifest.yaml") + + with open(manifest_path, "r") as f: + return yaml.safe_load(f) +``` diff --git a/.claude/legacy/custom_instructions.md b/.claude/legacy/custom_instructions.md new file mode 100644 index 0000000..a5f8624 --- /dev/null +++ b/.claude/legacy/custom_instructions.md @@ -0,0 +1,141 @@ +# Custom Instructions for Paracle Project + +## Role and Approach + +You are an expert Python developer working on Paracle, a multi-agent AI framework. Your expertise includes: +- Python 3.10+ with type hints and async/await +- Pydantic for data validation +- Hexagonal architecture and DDD patterns +- Multi-agent systems and LLM orchestration +- Test-driven development + +## Code Generation Guidelines + +### Python Code +- Always use type hints for function parameters and returns +- Use Pydantic BaseModel for all domain models +- Follow PEP 8 with Black formatting (88 chars) +- Prefer composition over inheritance (except for agent specs) +- Write pure functions when possible +- Use descriptive variable names + +### Testing +- Write tests using pytest with arrange-act-assert pattern +- Target 80%+ code coverage +- Include unit tests for domain logic +- Add integration tests for external dependencies +- Use fixtures for common test setups + +### Documentation +- Add docstrings to all public functions and classes +- Use Google-style docstring format +- Include type information in docstrings +- Document complex algorithms and business logic +- Update README when adding features + +## Project-Specific Rules + +### Agent Specifications +- All agents must inherit from AgentSpec +- Use parent field for agent inheritance +- Validate temperature between 0.0 and 2.0 +- Include system_prompt for agent behavior +- Define tools array for agent capabilities + +### Workflows +- Define workflows using WorkflowSpec +- Each step must reference an agent +- Use depends_on for step ordering +- Include clear inputs and outputs +- Handle errors gracefully + +### Repository Pattern +- All data access through repositories +- Use abstract base classes for interfaces +- Implement SQLite for v0.0.1 +- Include unit of work pattern +- Support transactions + +### Event-Driven +- Emit domain events for state changes +- Use event bus for decoupling +- Include event metadata +- Support async event handlers +- Log all events + +## File Organization + +When creating new features: +1. Start with domain models in `packages/paracle_domain/` +2. Add repository interfaces in `packages/paracle_store/` +3. Implement use cases in application layer +4. Create API endpoints in `packages/paracle_api/` +5. Add CLI commands in `packages/paracle_cli/` +6. Write tests in `tests/unit/` and `tests/integration/` +7. Update documentation in `docs/` + +## Governance + +Before implementing features, check: +- `.parac/roadmap/roadmap.yaml` - Is it planned? +- `.parac/policies/policy-pack.yaml` - What policies apply? +- `.parac/roadmap/decisions.md` - Any relevant ADRs? +- `.parac/memory/context/current_state.yaml` - Current phase? + +## Code Review Checklist + +Before suggesting code: +- [ ] Type hints on all functions +- [ ] Pydantic validation for inputs +- [ ] Unit tests included +- [ ] Docstrings added +- [ ] Follows Black formatting +- [ ] No hardcoded secrets +- [ ] Error handling present +- [ ] Logging added +- [ ] Adheres to hexagonal architecture +- [ ] Updates relevant documentation + +## Communication Style + +- Be concise but complete +- Explain architectural decisions +- Reference relevant patterns +- Suggest alternatives when appropriate +- Point out potential issues +- Provide code examples +- Link to documentation + +## Common Tasks + +### Adding a new agent capability +1. Define in `AgentSpec` model +2. Update validation logic +3. Add to CLI command +4. Write unit tests +5. Update agent examples +6. Document in getting-started + +### Creating a new workflow +1. Define in `.parac/workflows/templates/` +2. Add to workflow catalog +3. Implement in `WorkflowSpec` model +4. Create example usage +5. Add CLI command +6. Write integration test + +### Adding a model provider +1. Create adapter in `packages/paracle_providers/` +2. Implement provider interface +3. Add configuration to `.parac/adapters/` +4. Write provider tests +5. Update documentation +6. Add example usage + +## References + +- Architecture: `docs/architecture.md` +- Getting Started: `docs/getting-started.md` +- Domain Models: `packages/paracle_domain/models.py` +- Roadmap: `.parac/roadmap/roadmap.yaml` +- ADRs: `.parac/roadmap/decisions.md` diff --git a/.claude/legacy/project_context.md b/.claude/legacy/project_context.md new file mode 100644 index 0000000..ca48a49 --- /dev/null +++ b/.claude/legacy/project_context.md @@ -0,0 +1,106 @@ +# Paracle Project - Claude Desktop Configuration + +## Project Context + +Paracle is a powerful multi-agent AI framework with unique features: + +- **Agent Inheritance**: Hierarchical agent specialization +- **Multi-Framework Support**: MSAF, LangChain, LlamaIndex +- **Multi-Provider**: OpenAI, Anthropic, Google, Local LLMs +- **API-First Design**: FastAPI with RESTful endpoints +- **MCP Protocol**: Model Context Protocol support +- **.parac Workspace**: Governance and configuration structure + +## Architecture + +- **Language**: Python 3.10+ +- **Package Manager**: uv (modern, fast) +- **Structure**: Modular monolith with 17 packages +- **Testing**: pytest with 80%+ coverage target +- **Patterns**: Hexagonal architecture, Repository, Event-driven + +## Key Directories + +### Source Code +- `packages/paracle_domain/` - Core business logic (AgentSpec, Agent, Workflow) +- `packages/paracle_cli/` - Command-line interface +- `packages/paracle_api/` - FastAPI REST API (future) +- `packages/paracle_store/` - Persistence layer (future) + +### Configuration +- `.parac/` - Workspace governance (roadmap, agents, policies, memory) +- `pyproject.toml` - Project dependencies and tools +- `Makefile` - Developer commands + +### Documentation +- `docs/` - Architecture, getting started, API reference +- `examples/` - Working code examples +- `README.md` - Project overview + +## Current Phase + +**Phase 0: Foundation** βœ… Complete (100%) +- Modular packages structure +- Domain models (AgentSpec, Agent, Workflow) +- CLI with hello command +- CI/CD pipelines +- Unit tests +- Documentation + +**Phase 1: Core Domain** (Next - 3 weeks) +- Agent inheritance resolution algorithm +- Repository pattern + SQLite persistence +- Event bus implementation +- 80%+ test coverage +- CRUD operations + +## Development Commands + +```bash +# Setup +uv sync # Install dependencies + +# Development +make test # Run tests +make coverage # Test coverage report +make lint # Lint code +make format # Format code +make typecheck # Type checking + +# CLI +paracle hello # Test CLI +paracle agent create # Create agent (placeholder) +paracle workflow run # Run workflow (placeholder) +``` + +## Code Standards + +- **Python**: Type hints, Pydantic models, 88 chars (Black) +- **Testing**: Pytest with arrange-act-assert pattern +- **Documentation**: Docstrings for all public APIs +- **Commits**: Conventional Commits format + +## Important Files + +When implementing features, always consider: +- `.parac/roadmap/roadmap.yaml` - Project roadmap and phases +- `.parac/policies/policy-pack.yaml` - Active policies +- `.parac/memory/context/current_state.yaml` - Current project state +- `packages/paracle_domain/models.py` - Core domain models + +## Meta-Approach + +We're using Paracle concepts to build Paracle itself: +- `.parac` workspace guides development +- Agent specifications in `.parac/agents/manifest.yaml` +- Workflows for common tasks in `.parac/workflows/` +- Policies enforce code quality and security + +## Next Steps + +Focus areas for Phase 1: +1. Implement agent inheritance resolution algorithm +2. Add SQLite persistence with Repository pattern +3. Create event bus for domain events +4. Achieve 80%+ test coverage +5. Implement full CRUD for agents and workflows diff --git a/.claude/legacy/prompts.md b/.claude/legacy/prompts.md new file mode 100644 index 0000000..1d1750b --- /dev/null +++ b/.claude/legacy/prompts.md @@ -0,0 +1,277 @@ +# Paracle Project Prompts + +This file contains helpful prompts for common development tasks on Paracle. + +## Quick Start Prompts + +### Understanding the Project +``` +I'm working on Paracle, a multi-agent AI framework. Can you help me understand: +- The current architecture (see docs/architecture.md) +- The roadmap and current phase (see .parac/roadmap/) +- Key domain models (see packages/paracle_domain/models.py) +``` + +### Starting Development +``` +I want to start working on Phase 1 features. Please review: +- Current state: .parac/memory/context/current_state.yaml +- Phase 1 requirements: .parac/roadmap/PHASE1_CORE_DOMAIN.md +- Architecture decisions: .parac/roadmap/decisions.md + +What should I focus on first? +``` + +## Feature Implementation Prompts + +### Agent Inheritance +``` +I need to implement the agent inheritance resolution algorithm for Paracle. + +Requirements: +- Resolve parent chain for any agent +- Merge properties from parents (system_prompt, tools, metadata) +- Override child properties take precedence +- Detect circular dependencies +- Validate all agents in chain exist + +Context: +- AgentSpec model in packages/paracle_domain/models.py +- Current implementation only has parent field +- Should support multi-level inheritance (grandparent β†’ parent β†’ child) + +Please provide: +1. Algorithm design +2. Implementation code +3. Unit tests +4. Example usage +``` + +### Repository Pattern +``` +Implement a Repository pattern for Agent persistence with: +- Abstract base class: AgentRepository +- SQLite implementation: SQLiteAgentRepository +- Methods: get_by_id, get_by_name, list_all, save, delete +- Async/await support +- Transaction support via Unit of Work + +Location: packages/paracle_store/ +Follow: Hexagonal architecture principles +Testing: Include unit tests with in-memory SQLite +``` + +### Event Bus +``` +Create an in-memory event bus for domain events: +- EventBus class with subscribe/publish +- DomainEvent base class +- Event types: agent.created, agent.updated, workflow.started, workflow.completed +- Support async event handlers +- Include event metadata and timestamps +- Add logging for all events + +Location: packages/paracle_events/ +Include: Unit tests and usage examples +``` + +## Testing Prompts + +### Unit Tests +``` +Write comprehensive unit tests for [feature/class]: +- Use pytest with fixtures +- Follow arrange-act-assert pattern +- Include happy path and edge cases +- Test validation and error handling +- Target 80%+ coverage + +Location: tests/unit/ +Context: [provide file path and class name] +``` + +### Integration Tests +``` +Create integration tests for [feature]: +- Test with real database (SQLite in-memory) +- Test full workflow end-to-end +- Include setup and teardown +- Use pytest-asyncio for async tests + +Location: tests/integration/ +``` + +## Refactoring Prompts + +### Code Review +``` +Review this code for: +- Type hints completeness +- Pydantic validation +- Error handling +- Code organization +- Performance issues +- Security concerns +- Adherence to hexagonal architecture + +[paste code] +``` + +### Improve Code Quality +``` +Refactor this code to: +- Add proper type hints +- Improve error handling +- Enhance readability +- Follow SOLID principles +- Add documentation +- Optimize performance + +Current code: +[paste code] +``` + +## Documentation Prompts + +### API Documentation +``` +Generate API documentation for: +- Class: [ClassName] +- Location: [file path] + +Include: +- Class description +- Method signatures with types +- Parameter descriptions +- Return value descriptions +- Usage examples +- Exceptions raised + +Format: Google-style docstrings +``` + +### Architecture Decision Record (ADR) +``` +Create an Architecture Decision Record for [decision]: + +Context: [background and problem] +Decision: [chosen solution] +Consequences: [positive and negative impacts] +Alternatives: [other options considered] + +Save to: .parac/roadmap/decisions.md +``` + +## Debugging Prompts + +### Analyze Error +``` +I'm getting this error: +[paste error message and traceback] + +Context: +- What I'm trying to do: [description] +- Relevant code: [paste code] +- Project structure: See .parac/ and packages/ + +Please help me: +1. Understand the root cause +2. Provide a solution +3. Suggest preventive measures +``` + +### Performance Issue +``` +This code is slow: +[paste code] + +Context: +- Input size: [description] +- Expected performance: [target] +- Measured performance: [actual] + +Please: +1. Identify bottlenecks +2. Suggest optimizations +3. Provide improved code +``` + +## CLI & Tools Prompts + +### Add CLI Command +``` +Add a new CLI command to paracle: + +Command: paracle agent [subcommand] +Subcommands: +- list: List all agents +- show : Show agent details +- delete : Delete an agent + +Requirements: +- Use Click framework +- Add rich console output +- Include error handling +- Add --help documentation +- Add to packages/paracle_cli/main.py +``` + +### Create Workflow Template +``` +Create a workflow template for [use case]: + +Requirements: +- YAML format in .parac/workflows/templates/ +- Include inputs, steps, outputs +- Add to catalog.yaml +- Create example usage +- Document in .parac/workflows/README.md +``` + +## Maintenance Prompts + +### Update Dependencies +``` +Review and update project dependencies: +- Check pyproject.toml +- Identify outdated packages +- Suggest updates with rationale +- Check for security vulnerabilities +- Ensure compatibility +``` + +### Code Cleanup +``` +Clean up [directory/file]: +- Remove unused imports +- Fix formatting issues +- Update docstrings +- Remove dead code +- Improve naming +- Add missing type hints +``` + +## Project Management Prompts + +### Progress Check +``` +Review current project status: +- Current phase progress (.parac/memory/context/current_state.yaml) +- Completed deliverables +- Remaining tasks +- Blockers or issues +- Next priorities + +Provide summary and recommendations. +``` + +### Planning Next Phase +``` +Plan Phase [N] implementation: +- Review phase requirements (.parac/roadmap/PHASE[N]_*.md) +- Break down into tasks +- Estimate effort +- Identify dependencies +- Suggest implementation order +- Create checklist +``` diff --git a/.claude/rules/anti-hallucination.md b/.claude/rules/anti-hallucination.md new file mode 100644 index 0000000..3bef2f3 --- /dev/null +++ b/.claude/rules/anti-hallucination.md @@ -0,0 +1,263 @@ +# Anti-Hallucination Protocol + +## Core Principle + +**When uncertain, say so. When guessing, label it. When inventing, stop.** + +This protocol ensures maximum accuracy and trustworthiness in all outputs. + +--- + +## Uncertainty Levels + +### Level 1: Confident (No Qualifier Needed) + +Use when: + +- Directly reading from provided code/documentation +- Applying well-established patterns (SOLID, hexagonal architecture) +- Using standard library features +- Following explicit project conventions from .parac/ + +```python +# Example: Reading from actual code +# The AgentSpec model uses Pydantic with these fields... +``` + +### Level 2: Reasonably Confident (Light Qualifier) + +Use when: + +- Inferring from context and patterns +- Applying common best practices +- Making logical deductions + +```text +"Based on the existing patterns in paracle_domain, +the repository interface should follow this structure..." +``` + +### Level 3: Uncertain (Explicit Statement Required) + +Use when: + +- Information is not in provided context +- Multiple valid approaches exist +- Implementation details are ambiguous + +```text +"I am uncertain about the exact error handling strategy for provider failures. +The codebase doesn't show an established pattern yet. + +Options: +1. Retry with exponential backoff +2. Fail fast with detailed error +3. Fallback to alternative provider + +Recommendation: Option 1, but this needs validation against project requirements." +``` + +### Level 4: Speculation (Must Be Labeled) + +Use when: + +- Guessing about future requirements +- Hypothesizing about user intent +- Exploring "what if" scenarios + +```text +"SPECULATION: If Paracle needs to support multi-tenant deployments, +we might need to add tenant_id to the Agent model. However, this is +not in the current roadmap and should not be implemented without +explicit requirements." +``` + +--- + +## Forbidden Behaviors + +### 1. Never Invent APIs + +```python +# FORBIDDEN: Making up library APIs +from langchain.agents import SuperAdvancedAgent # Does this exist? DON'T GUESS + +# CORRECT: State uncertainty +# I need to verify the exact LangChain API for agent creation. +# The import path may be different - please confirm or I'll check docs. +``` + +### 2. Never Assume Requirements + +```text +# FORBIDDEN +"The agent should also track token usage and costs..." +(Was this requested? Is it in the roadmap?) + +# CORRECT +"Token tracking is not in the current Phase 1 requirements. +Should this be added? If yes, I recommend creating an ADR first." +``` + +### 3. Never Fabricate File Contents + +```text +# FORBIDDEN +"The pyproject.toml contains these dependencies..." +(Did you actually read it?) + +# CORRECT +"Let me read pyproject.toml to confirm the dependencies..." +[Then actually read it] +``` + +### 4. Never Guess Configuration Values + +```python +# FORBIDDEN +REDIS_URL = "redis://localhost:6379/0" # Is this the project standard? + +# CORRECT +# Configuration should come from: +# 1. Environment variables +# 2. .parac/project.yaml +# 3. Explicit user input +# I need to check the project's configuration strategy. +``` + +--- + +## Verification Checklist + +Before providing any technical answer, verify: + +- [ ] **Source**: Can I point to where this information comes from? +- [ ] **Accuracy**: Have I read the actual code/docs, not assumed? +- [ ] **Currency**: Is this information current for this project? +- [ ] **Completeness**: Am I missing context that would change the answer? +- [ ] **Consistency**: Does this align with existing project patterns? + +--- + +## When to Ask for Clarification + +### Always Ask When + +1. **Multiple valid interpretations exist** + + ```text + "When you say 'agent inheritance', do you mean: + a) Configuration inheritance (merging settings) + b) Behavioral inheritance (extending capabilities) + c) Both?" + ``` + +2. **Missing critical context** + + ```text + "To implement the repository pattern, I need to know: + - Target database (SQLite for dev, PostgreSQL for prod?) + - Async or sync operations? + - Transaction boundary requirements?" + ``` + +3. **Contradictory information** + + ```text + "The roadmap mentions 'event bus with Redis' but the + architecture doc shows 'in-memory event bus for v0.0.1'. + Which is correct for the current phase?" + ``` + +4. **Significant architectural impact** + + ```text + "Adding MCP support would affect: + - Tool registration mechanism + - Security model + - API surface + + Should I proceed with this scope, or start with a minimal implementation?" + ``` + +--- + +## Response Templates + +### Template: Uncertain About Approach + +```text +I am uncertain about the best approach for [X] because: +- [Reason 1] +- [Reason 2] + +Options I've identified: +1. [Option A]: [Pros/Cons] +2. [Option B]: [Pros/Cons] + +My recommendation is [Option X] because [justification]. + +However, this decision should be validated because [risk/uncertainty]. +``` + +### Template: Missing Information + +```text +To provide an accurate answer, I need: +1. [Missing piece 1] - because [why it matters] +2. [Missing piece 2] - because [why it matters] + +With assumptions: +- Assuming [X], the answer would be [Y] +- Assuming [Z], the answer would be [W] + +Please clarify which assumptions are correct. +``` + +### Template: Partial Knowledge + +```text +What I know with confidence: +- [Fact 1] (source: [reference]) +- [Fact 2] (source: [reference]) + +What I'm inferring (lower confidence): +- [Inference 1] (based on: [reasoning]) + +What I don't know: +- [Unknown 1] - this would affect [impact] + +Recommendation: [action] with the caveat that [uncertainty]. +``` + +--- + +## Self-Review Protocol + +Before finalizing any significant output: + +```text +SELF-REVIEW CHECKLIST: +[ ] Did I verify all file paths exist? +[ ] Did I check actual API signatures, not assumed? +[ ] Did I read the referenced documentation? +[ ] Are my code examples syntactically correct? +[ ] Do my recommendations align with .parac/ governance? +[ ] Have I labeled all uncertainties? +[ ] Is anything I said not backed by evidence? +``` + +--- + +## Error Recovery + +When catching yourself in a potential hallucination: + +```text +"Wait - I need to correct myself. I stated [X] but upon reflection, +I'm not certain this is accurate because [reason]. + +Let me verify by [action] before proceeding." +``` + +This is preferable to confidently stating incorrect information. diff --git a/.claude/rules/architecture.md b/.claude/rules/architecture.md new file mode 100644 index 0000000..212ee1e --- /dev/null +++ b/.claude/rules/architecture.md @@ -0,0 +1,186 @@ +# Architecture Guidelines + +## Hexagonal Architecture (Ports & Adapters) + +### Layer Rules + +1. **Domain Layer** (innermost) + - Pure Python with Pydantic + - No external dependencies + - Contains business logic and entities + - 100% testable without mocks + +2. **Application Layer** + - Orchestrates use cases + - Calls domain layer + - Defines port interfaces (abstract classes) + +3. **Infrastructure Layer** (outermost) + - Implements adapters for ports + - Contains external integrations + - Database, HTTP, message queues + +### Dependency Direction +``` +Infrastructure β†’ Application β†’ Domain + ↓ ↓ ↓ + Adapters Ports Entities +``` + +Dependencies flow inward only. Domain never imports from infrastructure. + +## Repository Pattern + +### Interface Definition (Port) +```python +from abc import ABC, abstractmethod +from typing import Optional, List + +class AgentRepository(ABC): + """Abstract port for agent persistence.""" + + @abstractmethod + async def get_by_id(self, agent_id: str) -> Optional[Agent]: + """Retrieve agent by ID.""" + pass + + @abstractmethod + async def save(self, agent: Agent) -> None: + """Persist agent.""" + pass + + @abstractmethod + async def delete(self, agent_id: str) -> None: + """Remove agent.""" + pass +``` + +### Implementation (Adapter) +```python +class SQLiteAgentRepository(AgentRepository): + """SQLite adapter for agent persistence.""" + + def __init__(self, db_path: str): + self.db_path = db_path + self._init_schema() + + async def get_by_id(self, agent_id: str) -> Optional[Agent]: + # Implementation details + pass +``` + +## Event-Driven Architecture + +### Domain Events +```python +class DomainEvent(BaseModel): + """Base class for all domain events.""" + event_id: str = Field(default_factory=generate_ulid) + event_type: str + aggregate_id: str + timestamp: datetime = Field(default_factory=datetime.utcnow) + data: dict = Field(default_factory=dict) + +class AgentCreatedEvent(DomainEvent): + event_type: str = "agent.created" +``` + +### Event Bus +```python +class EventBus(ABC): + @abstractmethod + async def publish(self, event: DomainEvent) -> None: + pass + + @abstractmethod + def subscribe(self, event_type: str, handler: Callable) -> None: + pass +``` + +### Event Emission +- Emit events after state changes +- Keep events immutable +- Include all relevant context +- Handle failures gracefully + +```python +async def create_agent(self, spec: AgentSpec) -> Agent: + agent = Agent(spec=spec) + await self.repository.save(agent) + + await self.event_bus.publish( + AgentCreatedEvent( + aggregate_id=agent.id, + data={"name": spec.name, "model": spec.model} + ) + ) + return agent +``` + +## Factory Pattern + +### Agent Factory +```python +class AgentFactory: + """Factory for creating agents with inheritance resolution.""" + + def __init__(self, registry: AgentRegistry): + self.registry = registry + + def create(self, spec: AgentSpec) -> Agent: + """Create agent with resolved inheritance.""" + resolved_spec = self._resolve_inheritance(spec) + return Agent(spec=resolved_spec) + + def _resolve_inheritance(self, spec: AgentSpec) -> AgentSpec: + if not spec.parent: + return spec + + parent = self.registry.get(spec.parent) + merged = self._merge_specs(parent, spec) + return self._resolve_inheritance(merged) +``` + +## Package Dependencies + +### Allowed Dependencies +``` +paracle_core β†’ (none - pure utilities) +paracle_domain β†’ paracle_core +paracle_store β†’ paracle_core, paracle_domain +paracle_events β†’ paracle_core, paracle_domain +paracle_providers β†’ paracle_core, paracle_domain +paracle_orchestration β†’ paracle_core, paracle_domain, paracle_events +paracle_api β†’ paracle_core, paracle_domain, paracle_orchestration +paracle_cli β†’ paracle_core, paracle_domain, paracle_api +``` + +### Forbidden Dependencies +- Domain must NEVER import from infrastructure +- Packages should not have circular dependencies +- Prefer explicit over implicit imports + +## Configuration + +### Settings Management +```python +from pydantic_settings import BaseSettings + +class Settings(BaseSettings): + """Application settings from environment.""" + + database_url: str = "sqlite:///paracle.db" + redis_url: str = "redis://localhost:6379" + log_level: str = "INFO" + + model_config = ConfigDict( + env_prefix="PARACLE_", + env_file=".env" + ) +``` + +### Configuration Hierarchy +1. Environment variables (highest) +2. `.env` file +3. `.parac/project.yaml` +4. Default values (lowest) diff --git a/.claude/rules/code-style.md b/.claude/rules/code-style.md new file mode 100644 index 0000000..97dafb1 --- /dev/null +++ b/.claude/rules/code-style.md @@ -0,0 +1,153 @@ +# Code Style Guidelines + +## Python Code + +### Type Hints +- Always use type hints for function parameters and returns +- Use `Optional[T]` for nullable types +- Use `Union[A, B]` sparingly; prefer protocols +- Use `TypeVar` for generic functions + +```python +def process_agent(agent_id: str, config: Optional[Config] = None) -> Agent: + ... +``` + +### Pydantic Models +- Use Pydantic `BaseModel` for all domain models +- Use `Field()` with descriptions for documentation +- Add validators using `@field_validator` +- Keep models immutable with `model_config = ConfigDict(frozen=True)` + +```python +from pydantic import BaseModel, Field, field_validator + +class AgentSpec(BaseModel): + name: str = Field(..., description="Unique agent name") + temperature: float = Field(default=0.7, ge=0.0, le=2.0) + + @field_validator('name') + @classmethod + def validate_name(cls, v: str) -> str: + if not v.strip(): + raise ValueError("Name cannot be empty") + return v.lower().strip() +``` + +### Formatting +- Line length: 88 characters (Black default) +- Indentation: 4 spaces +- Use Black for formatting +- Use ruff for linting + +### Naming Conventions +- Variables/functions: `snake_case` +- Classes: `PascalCase` +- Constants: `UPPER_SNAKE_CASE` +- Private members: `_single_underscore` +- Avoid abbreviations; prefer descriptive names + +### Imports +- Group: stdlib, third-party, local +- Sort alphabetically within groups +- Use absolute imports +- Avoid `from module import *` + +```python +from datetime import datetime +from typing import List, Optional + +from pydantic import BaseModel +import click + +from paracle_core.config import Settings +from paracle_domain.models import Agent +``` + +## Documentation + +### Docstrings +- Use Google-style docstrings +- Document all public functions and classes +- Include type information +- Add examples for complex functions + +```python +def resolve_inheritance(agent: AgentSpec, registry: dict[str, AgentSpec]) -> AgentSpec: + """Resolve agent inheritance chain and merge properties. + + Args: + agent: The agent specification to resolve. + registry: Dictionary mapping agent names to their specs. + + Returns: + A new AgentSpec with all inherited properties merged. + + Raises: + CircularInheritanceError: If a circular dependency is detected. + AgentNotFoundError: If a parent agent doesn't exist. + + Example: + >>> base = AgentSpec(name="base", model="gpt-4") + >>> child = AgentSpec(name="child", parent="base") + >>> resolved = resolve_inheritance(child, {"base": base}) + >>> resolved.model + 'gpt-4' + """ +``` + +### Comments +- Write self-documenting code; minimize comments +- Use comments for "why", not "what" +- Keep comments up-to-date with code +- Use `# TODO:` for pending work + +## Error Handling + +### Exceptions +- Create custom exceptions inheriting from base +- Include context in error messages +- Use specific exception types + +```python +class ParacleError(Exception): + """Base exception for Paracle.""" + pass + +class AgentNotFoundError(ParacleError): + """Raised when an agent cannot be found.""" + def __init__(self, agent_name: str): + super().__init__(f"Agent not found: {agent_name}") + self.agent_name = agent_name +``` + +### Error Handling Pattern +```python +try: + agent = await repository.get_by_name(name) + if agent is None: + raise AgentNotFoundError(name) +except DatabaseError as e: + logger.error(f"Database error: {e}") + raise +``` + +## Async/Await + +- Use `async/await` for I/O operations +- Prefer `asyncio.gather()` for concurrent operations +- Use `async with` for context managers +- Handle cancellation gracefully + +```python +async def fetch_agents(names: list[str]) -> list[Agent]: + tasks = [repository.get_by_name(name) for name in names] + return await asyncio.gather(*tasks) +``` + +## Composition Over Inheritance + +- Prefer composition for code reuse +- Exception: Agent inheritance is a domain concept +- Use protocols for interface definitions +- Keep class hierarchies shallow diff --git a/.claude/rules/framework-design.md b/.claude/rules/framework-design.md new file mode 100644 index 0000000..92d5fcd --- /dev/null +++ b/.claude/rules/framework-design.md @@ -0,0 +1,442 @@ +# Framework Design Guidelines + +## Core Principles + +### 1. Design for Decades, Not Sprints + +A framework must outlive its initial implementation. Every decision should consider: + +- **10-year maintenance burden**: Will this be understandable in 10 years? +- **API stability**: Can we evolve without breaking consumers? +- **Conceptual integrity**: Does this fit the overall mental model? + +### 2. Invariants First + +Before writing any code, define what must ALWAYS be true: + +```python +# Example: Agent Invariants +AGENT_INVARIANTS = """ +1. An agent MUST have a unique name within its scope +2. An agent's parent chain MUST be acyclic (no circular inheritance) +3. An agent MUST have a valid model reference +4. Temperature MUST be in range [0.0, 2.0] +5. An agent MUST be auditable (all actions logged) +6. An agent MUST respect its permission boundaries +""" +``` + +### 3. Layered Abstraction + +```text +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ CONCEPTUAL LAYER β”‚ +β”‚ "What problems do we solve?" β”‚ +β”‚ Agents, Workflows, Tools, Policies β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ LOGICAL LAYER β”‚ +β”‚ "How do concepts interact?" β”‚ +β”‚ Inheritance, Orchestration, Events β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ TECHNICAL LAYER β”‚ +β”‚ "How do we implement?" β”‚ +β”‚ Python, Pydantic, SQLite, Redis β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ OPERATIONAL LAYER β”‚ +β”‚ "How do we run and observe?" β”‚ +β”‚ Deployment, Monitoring, Scaling β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +--- + +## API Design Principles + +### 1. Pit of Success + +Make the right thing easy and the wrong thing hard: + +```python +# GOOD: Safe by default +class AgentSpec(BaseModel): + temperature: float = Field(default=0.7, ge=0.0, le=2.0) + max_tokens: int = Field(default=4096, ge=1, le=128000) + +# BAD: Requires discipline +class AgentSpec: + def __init__(self, temperature=None): # None? What's the default? + self.temperature = temperature # No validation +``` + +### 2. Progressive Disclosure + +Simple things should be simple. Complex things should be possible. + +```python +# Simple: 1 line +agent = Agent(name="helper", model="gpt-4") + +# Intermediate: Common customization +agent = Agent( + name="coder", + model="gpt-4", + temperature=0.3, + system_prompt="You are a Python expert." +) + +# Advanced: Full control +agent = Agent( + name="enterprise-coder", + model="gpt-4", + temperature=0.3, + system_prompt="...", + parent="base-coder", + tools=["read_file", "write_file", "execute_code"], + policies=["iso-42001-compliant"], + metadata={"team": "platform", "cost_center": "engineering"} +) +``` + +### 3. Explicit Over Implicit + +Never hide important behavior: + +```python +# GOOD: Explicit inheritance resolution +resolved_spec = agent_factory.resolve_inheritance(spec) +agent = Agent(spec=resolved_spec) + +# BAD: Magic behind the scenes +agent = Agent(spec=spec) # Silently resolves inheritance? +``` + +### 4. Composability + +Design components that combine predictably: + +```python +# Components compose naturally +workflow = ( + Workflow("review-pipeline") + .add_step(Step("analyze", agent="analyzer")) + .add_step(Step("review", agent="reviewer", depends_on=["analyze"])) + .add_step(Step("approve", agent="approver", depends_on=["review"])) + .with_policy(RequireHumanApproval(threshold="high-risk")) + .with_timeout(minutes=30) +) +``` + +--- + +## Extension Points + +### 1. Protocols Over Inheritance + +Use Protocol (structural typing) for extension points: + +```python +from typing import Protocol, runtime_checkable + +@runtime_checkable +class LLMProvider(Protocol): + """Any LLM provider must implement this interface.""" + + async def complete( + self, + messages: list[Message], + model: str, + temperature: float + ) -> CompletionResult: + ... + + async def stream( + self, + messages: list[Message], + model: str, + temperature: float + ) -> AsyncIterator[StreamChunk]: + ... + +# Users can implement their own providers +class MyCustomProvider: + async def complete(self, messages, model, temperature): + # Custom implementation + ... +``` + +### 2. Hook Points + +Provide explicit extension hooks: + +```python +class WorkflowEngine: + """Workflow execution with extension hooks.""" + + # Lifecycle hooks + on_workflow_start: list[Callable[[Workflow], Awaitable[None]]] + on_step_start: list[Callable[[Step], Awaitable[None]]] + on_step_complete: list[Callable[[Step, Result], Awaitable[None]]] + on_workflow_complete: list[Callable[[Workflow, Result], Awaitable[None]]] + on_error: list[Callable[[Exception], Awaitable[None]]] + + # Decision hooks + should_continue: Callable[[Step, Result], Awaitable[bool]] + should_retry: Callable[[Step, Exception], Awaitable[bool]] +``` + +### 3. Plugin Architecture + +Design for third-party extensions: + +```python +# Plugin registration +@paracle.register_provider("my-llm") +class MyLLMProvider: + ... + +@paracle.register_tool("custom-search") +class CustomSearchTool: + ... + +@paracle.register_policy("my-company-rules") +class MyCompanyPolicy: + ... +``` + +--- + +## Versioning & Compatibility + +### 1. Semantic Versioning + +```text +MAJOR.MINOR.PATCH + +MAJOR: Breaking changes (removed/renamed APIs, changed behavior) +MINOR: New features (backward compatible) +PATCH: Bug fixes (backward compatible) +``` + +### 2. Deprecation Strategy + +```python +import warnings + +def old_method(self, arg): + """Deprecated: Use new_method() instead.""" + warnings.warn( + "old_method() is deprecated and will be removed in v2.0. " + "Use new_method() instead.", + DeprecationWarning, + stacklevel=2 + ) + return self.new_method(arg) +``` + +### 3. Feature Flags + +```python +class ParacleConfig: + """Feature flags for gradual rollout.""" + + # Experimental features (may change) + enable_experimental_rag: bool = False + enable_experimental_multi_agent_chat: bool = False + + # Beta features (stable API, may have bugs) + enable_beta_workflow_visualization: bool = False + + # Deprecated features (will be removed) + enable_legacy_agent_format: bool = True # Remove in v2.0 +``` + +--- + +## Error Handling Philosophy + +### 1. Fail Fast, Fail Loud + +```python +class AgentFactory: + def create(self, spec: AgentSpec) -> Agent: + # Validate immediately + self._validate_spec(spec) + self._validate_parent_exists(spec) + self._validate_no_circular_inheritance(spec) + self._validate_tools_available(spec) + + # Only then create + return self._build_agent(spec) +``` + +### 2. Rich Error Context + +```python +class ParacleError(Exception): + """Base exception with rich context.""" + + def __init__( + self, + message: str, + *, + code: str, + context: dict[str, Any] | None = None, + suggestion: str | None = None + ): + super().__init__(message) + self.code = code + self.context = context or {} + self.suggestion = suggestion + +class CircularInheritanceError(ParacleError): + def __init__(self, chain: list[str]): + super().__init__( + f"Circular inheritance detected: {' -> '.join(chain)}", + code="AGENT_CIRCULAR_INHERITANCE", + context={"inheritance_chain": chain}, + suggestion="Remove the circular dependency by updating parent references" + ) +``` + +### 3. Recoverable vs Fatal + +```python +# Recoverable: Retry or fallback possible +class ProviderTemporarilyUnavailable(ParacleError): + """Provider is temporarily unavailable. Retry is appropriate.""" + recoverable = True + +# Fatal: Cannot continue +class InvalidAgentSpecification(ParacleError): + """Agent specification is invalid. Cannot proceed.""" + recoverable = False +``` + +--- + +## Performance Considerations + +### 1. Lazy by Default + +```python +class Agent: + @cached_property + def resolved_spec(self) -> AgentSpec: + """Resolve inheritance only when needed.""" + return self._resolve_inheritance() + + @cached_property + def provider(self) -> LLMProvider: + """Initialize provider only when first used.""" + return self._create_provider() +``` + +### 2. Batch Operations + +```python +class AgentRepository: + # Single item + async def get(self, id: str) -> Agent | None: + ... + + # Batch operation (more efficient) + async def get_many(self, ids: list[str]) -> list[Agent]: + ... + + # Bulk operation + async def save_many(self, agents: list[Agent]) -> None: + ... +``` + +### 3. Streaming First + +```python +class LLMProvider(Protocol): + # Streaming is the primary interface + async def stream( + self, + messages: list[Message], + **kwargs + ) -> AsyncIterator[StreamChunk]: + ... + + # Non-streaming is built on streaming + async def complete( + self, + messages: list[Message], + **kwargs + ) -> CompletionResult: + chunks = [] + async for chunk in self.stream(messages, **kwargs): + chunks.append(chunk) + return CompletionResult.from_chunks(chunks) +``` + +--- + +## Documentation Standards + +### 1. Every Public API Documented + +```python +def resolve_inheritance( + spec: AgentSpec, + registry: AgentRegistry +) -> AgentSpec: + """Resolve agent inheritance chain and merge properties. + + Walks the parent chain from the given spec to the root, + merging properties at each level. Child properties override + parent properties. + + Args: + spec: The agent specification to resolve. + registry: Registry containing all agent definitions. + + Returns: + A new AgentSpec with all inherited properties merged. + The returned spec has no parent (fully resolved). + + Raises: + AgentNotFoundError: If a parent agent doesn't exist in registry. + CircularInheritanceError: If a circular dependency is detected. + + Example: + >>> base = AgentSpec(name="base", model="gpt-4", temperature=0.7) + >>> child = AgentSpec(name="child", parent="base", temperature=0.3) + >>> registry = AgentRegistry([base, child]) + >>> resolved = resolve_inheritance(child, registry) + >>> resolved.model + 'gpt-4' + >>> resolved.temperature + 0.3 + + Note: + The resolution is deterministic: given the same inputs, + it will always produce the same output. + """ +``` + +### 2. Architecture Decision Records + +Every significant decision gets an ADR: + +```markdown +# ADR-001: Use Pydantic for Domain Models + +## Status +Accepted + +## Context +We need a way to define and validate domain models. + +## Decision +Use Pydantic BaseModel for all domain entities. + +## Consequences +- (+) Built-in validation +- (+) Automatic JSON serialization +- (+) Type hints as documentation +- (-) Runtime overhead for validation +- (-) Learning curve for team +``` diff --git a/.claude/rules/multi-perspective.md b/.claude/rules/multi-perspective.md new file mode 100644 index 0000000..8f1d3b3 --- /dev/null +++ b/.claude/rules/multi-perspective.md @@ -0,0 +1,326 @@ +# Multi-Perspective Analysis Protocol + +## Purpose + +Complex framework decisions require analysis from multiple viewpoints. This protocol ensures comprehensive evaluation by simulating a **senior architecture review committee**. + +--- + +## The Three Perspectives + +### 1. Framework Architect + +**Focus**: Long-term maintainability, API design, extensibility + +**Questions to Answer**: + +- Does this fit the overall conceptual model? +- Will this API be stable for 5+ years? +- Can users extend this without modifying core code? +- Is the abstraction level appropriate? +- Does this follow established patterns (or justify deviation)? +- What's the learning curve for new developers? + +**Evaluation Criteria**: + +```text +[ ] Conceptual integrity preserved +[ ] API is intuitive and discoverable +[ ] Extension points are well-defined +[ ] Backward compatibility considered +[ ] Documentation implications clear +[ ] Naming is consistent and meaningful +``` + +### 2. Security & Compliance Engineer + +**Focus**: ISO 42001, audit trails, access control, data protection + +**Questions to Answer**: + +- Can all agent actions be audited? +- Is there proper access control? +- Are secrets properly managed? +- Does this create new attack vectors? +- Is data properly isolated (multi-tenant)? +- Does this comply with GDPR/privacy requirements? +- Can we explain AI decisions (explainability)? + +**Evaluation Criteria**: + +```text +[ ] Audit trail complete and tamper-evident +[ ] Permissions properly enforced +[ ] No secrets in code or logs +[ ] Input validation present +[ ] Data classification respected +[ ] Kill switch accessible +[ ] Human approval for high-risk actions +``` + +### 3. Runtime & Performance Engineer + +**Focus**: Latency, throughput, resource usage, operational concerns + +**Questions to Answer**: + +- What's the performance impact? +- How does this scale (10x, 100x, 1000x)? +- What are the failure modes? +- How do we monitor this? +- What's the resource footprint? +- Can this cause cascading failures? +- How do we debug issues in production? + +**Evaluation Criteria**: + +```text +[ ] Latency targets met (p50, p95, p99) +[ ] Memory usage bounded +[ ] Graceful degradation under load +[ ] Observability built-in (metrics, traces, logs) +[ ] Failure modes documented +[ ] Recovery procedures defined +[ ] Resource limits configurable +``` + +--- + +## Analysis Template + +For significant decisions, use this format: + +```markdown +## Decision: [Brief Description] + +### Context +[What problem are we solving? What constraints exist?] + +### Proposed Solution +[Brief description of the approach] + +--- + +### Framework Architect Perspective + +**Assessment**: [Positive/Neutral/Concerns] + +**Analysis**: +- [Key observation 1] +- [Key observation 2] + +**Recommendations**: +- [Suggestion 1] +- [Suggestion 2] + +--- + +### Security & Compliance Perspective + +**Assessment**: [Positive/Neutral/Concerns] + +**Analysis**: +- [Key observation 1] +- [Key observation 2] + +**ISO 42001 Implications**: +- [Requirement 1]: [How addressed] +- [Requirement 2]: [How addressed] + +**Recommendations**: +- [Suggestion 1] +- [Suggestion 2] + +--- + +### Runtime & Performance Perspective + +**Assessment**: [Positive/Neutral/Concerns] + +**Analysis**: +- [Key observation 1] +- [Key observation 2] + +**Performance Characteristics**: +- Expected latency: [estimate] +- Memory footprint: [estimate] +- Scaling behavior: [description] + +**Recommendations**: +- [Suggestion 1] +- [Suggestion 2] + +--- + +### Synthesized Decision + +**Final Recommendation**: [Accept/Modify/Reject] + +**Key Trade-offs**: +- [Trade-off 1] +- [Trade-off 2] + +**Action Items**: +1. [Action 1] +2. [Action 2] + +**Open Questions**: +- [Question 1] +- [Question 2] +``` + +--- + +## When to Apply Full Analysis + +### Always (Full 3-Perspective Review) + +- New domain entities (Agent, Workflow, Tool) +- API surface changes +- Security-sensitive features +- Performance-critical paths +- Cross-cutting concerns + +### Sometimes (2-Perspective Review) + +- Internal implementation details +- Utility functions +- Test infrastructure +- Documentation changes + +### Rarely (Single Perspective) + +- Bug fixes with clear scope +- Typo corrections +- Dependency updates (security perspective only) + +--- + +## Example: Agent Inheritance Decision + +```markdown +## Decision: Agent Inheritance Resolution Algorithm + +### Context +Agents can inherit from parent agents, creating a chain. +We need an algorithm to resolve the final configuration. + +### Proposed Solution +Walk the parent chain, merging properties at each level. +Child properties override parent properties. +Detect circular dependencies during resolution. + +--- + +### Framework Architect Perspective + +**Assessment**: Positive + +**Analysis**: +- Follows familiar OOP inheritance mental model +- Clear override semantics (child wins) +- Explicit resolution (no magic) + +**Recommendations**: +- Add `resolve_inheritance()` as explicit method, not implicit +- Cache resolved specs for performance +- Consider maximum inheritance depth limit + +--- + +### Security & Compliance Perspective + +**Assessment**: Concerns + +**Analysis**: +- Inherited permissions could create privilege escalation +- Audit trail must show effective (resolved) permissions +- Parent changes could silently affect children + +**ISO 42001 Implications**: +- Auditability: Must log both spec and resolved spec +- Traceability: Must show inheritance chain in audit + +**Recommendations**: +- Permissions should NOT inherit by default (security) +- Add `inherit_permissions: true` explicit flag +- Emit event when inheritance resolution changes effective config + +--- + +### Runtime & Performance Perspective + +**Assessment**: Neutral + +**Analysis**: +- Resolution is O(n) where n = chain length +- Typical chains are 2-3 levels (fast) +- Could be expensive with deep chains + many agents + +**Performance Characteristics**: +- Expected latency: <1ms for typical chains +- Memory: Minimal (only during resolution) +- Scaling: Linear with chain depth + +**Recommendations**: +- Cache resolved specs (invalidate on parent change) +- Set max depth limit (10?) to prevent abuse +- Add metrics for resolution time + +--- + +### Synthesized Decision + +**Final Recommendation**: Accept with modifications + +**Key Trade-offs**: +- Simplicity vs Security: Add explicit permission inheritance flag +- Performance vs Flexibility: Add caching with invalidation + +**Action Items**: +1. Implement basic resolution algorithm +2. Add `inherit_permissions` flag (default: false) +3. Add circular dependency detection +4. Add resolution caching +5. Emit AgentInheritanceResolved event + +**Open Questions**: +- Should tool inheritance be explicit too? +- How to handle parent deletion (orphan children)? +``` + +--- + +## Quick Perspective Checks + +For smaller decisions, use abbreviated format: + +```text +Quick Review: [Feature Name] + +Architect: [1-2 sentences on API/design impact] +Security: [1-2 sentences on security implications] +Runtime: [1-2 sentences on performance impact] + +Verdict: [Proceed/Needs discussion/Block] +``` + +--- + +## Disagreement Resolution + +When perspectives conflict: + +1. **Document the conflict explicitly** +2. **Identify the core trade-off** +3. **Consider project phase** (v0.0.1 priorities differ from v1.0) +4. **Default to safety** (security > performance > convenience) +5. **Escalate if needed** (create ADR for significant conflicts) + +```text +CONFLICT: Framework wants simple API, Security wants explicit permission checks + +Resolution: Security wins for v0.7.0+ (ISO 42001 phase). +For v0.0.1, use simpler API with TODO for security hardening. +Track in: .parac/memory/context/tech_debt.md +``` diff --git a/.claude/rules/parac-governance.md b/.claude/rules/parac-governance.md new file mode 100644 index 0000000..9500cb4 --- /dev/null +++ b/.claude/rules/parac-governance.md @@ -0,0 +1,233 @@ +# .parac Governance Rules for Claude Code + +## Principe Fondamental + +> **`.parac/` est la source unique et immuable de vΓ©ritΓ©.** + +Toute information concernant l'Γ©tat du projet DOIT Γͺtre reflΓ©tΓ©e dans `.parac/`. +Ne jamais contredire ce qui est documentΓ© dans `.parac/`. + +--- + +## RΓ¨gles Obligatoires + +### RΓ¨gle 1: Lecture au DΓ©but de Session + +**AVANT** de commencer tout travail, TOUJOURS lire: + +``` +1. .parac/memory/context/current_state.yaml β†’ Γ‰tat actuel +2. .parac/roadmap/roadmap.yaml β†’ Phase et prioritΓ©s +3. .parac/memory/context/open_questions.md β†’ Questions en attente +``` + +Format de confirmation: +``` +SESSION START +============= +Phase: [current_phase.id] - [current_phase.name] +Progress: [current_phase.progress] +Focus: [current_phase.focus_areas] + +Source of truth verified: .parac/ +``` + +### RΓ¨gle 2: Ne Jamais Contredire .parac/ + +Si une information diffΓ¨re entre: +- La conversation et `.parac/` β†’ `.parac/` a raison +- Ta mΓ©moire et `.parac/` β†’ `.parac/` a raison +- Une demande utilisateur et `.parac/` β†’ Signaler l'incohΓ©rence + +``` +INCOHΓ‰RENCE DΓ‰TECTΓ‰E +==================== +Source: [conversation/demande] +Dit: [X] + +.parac/ dit: [Y] + +.parac/ est la source de vΓ©ritΓ©. +Voulez-vous mettre Γ  jour .parac/ pour reflΓ©ter [X]? +``` + +### RΓ¨gle 3: Mise Γ  Jour en Fin de Session + +**APRÈS** chaque session significative, PROPOSER des mises Γ  jour: + +``` +SESSION END - Mises Γ  jour .parac/ proposΓ©es +============================================= + +1. current_state.yaml: + - progress: [ancien] β†’ [nouveau] + - completed: + [nouveaux items] + - in_progress: [changements] + +2. decisions.md (si applicable): + - ADR-XXX: [nouvelle dΓ©cision] + +3. open_questions.md (si applicable): + - Nouvelle question: [Q] + - Question rΓ©solue: [Q] + +Voulez-vous que j'applique ces mises Γ  jour? +``` + +### RΓ¨gle 4: Documenter ImmΓ©diatement les DΓ©cisions + +Toute dΓ©cision architecturale significative DOIT Γͺtre documentΓ©e: + +```markdown +### ADR-XXX: [Titre] + +**Date:** [YYYY-MM-DD] +**Status:** Accepted + +**Context:** +[Pourquoi cette dΓ©cision Γ©tait nΓ©cessaire] + +**Decision:** +[Ce qui a Γ©tΓ© dΓ©cidΓ©] + +**Rationale:** +[Pourquoi cette option a Γ©tΓ© choisie] + +**Consequences:** +- [Impact positif/nΓ©gatif] + +**Alternatives Rejected:** +- [Option rejetΓ©e]: [Raison] +``` + +### RΓ¨gle 5: Questions avec Owners et Deadlines + +Toute nouvelle question DOIT avoir: +- Un owner (qui dΓ©cide) +- Une deadline (quand dΓ©cider) +- Une prioritΓ© (High/Medium/Low) + +```markdown +### Q#: [Titre] + +**Status:** Open +**Priority:** [High/Medium/Low] +**Owner:** [Agent/Role] +**Deadline:** [Phase X End / Date] +**Context:** [Contexte] +``` + +--- + +## Checkpoints Automatiques + +### AprΓ¨s Chaque TΓ’che Majeure + +Quand un deliverable est complΓ©tΓ©: + +1. Proposer mise Γ  jour `current_state.yaml`: + ```yaml + deliverables: + - name: "[Deliverable]" + status: completed + completion: 100% + completed_date: "[Date]" + ``` + +2. Recalculer le progress de la phase + +### AprΓ¨s Chaque DΓ©cision + +1. Ajouter Γ  `decisions.md` +2. Si rΓ©sout une question β†’ mettre Γ  jour `open_questions.md` + +### AprΓ¨s Chaque Erreur/Blocage + +1. Documenter dans `current_state.yaml` sous `blockers:` +2. CrΓ©er une question si dΓ©cision nΓ©cessaire + +--- + +## Format de Commit .parac/ + +Quand des fichiers `.parac/` sont modifiΓ©s: + +``` +docs(parac): [description courte] + +- [Changement 1] +- [Changement 2] + +Refs: [Phase/ADR/Question] +``` + +Exemples: +``` +docs(parac): update phase 1 progress to 25% + +- Mark domain_models as in_progress +- Update metrics + +Refs: Phase 1 + +docs(parac): add ADR-009 for event store decision + +- Decision: Use SQLite for v0.0.1 +- Resolves Q2 + +Refs: ADR-009, Q2 +``` + +--- + +## Validation Avant Proposition + +Avant de proposer des changements `.parac/`: + +- [ ] Les fichiers YAML sont syntaxiquement corrects +- [ ] `current_state.yaml` et `roadmap.yaml` sont cohΓ©rents +- [ ] Les questions ont owners et deadlines +- [ ] Les dΓ©cisions sont complΓ¨tes (context, decision, rationale) +- [ ] Les mΓ©triques sont rΓ©alistes + +--- + +## Fichiers Critiques + +| Fichier | Quand Mettre Γ  Jour | +|---------|---------------------| +| `current_state.yaml` | Chaque session | +| `roadmap.yaml` | Changement de phase, milestone | +| `decisions.md` | Chaque dΓ©cision architecturale | +| `open_questions.md` | Nouvelle question ou rΓ©solution | + +--- + +## Anti-Patterns + +### ❌ Ne PAS Faire + +1. **Ignorer `.parac/`** et travailler de mΓ©moire +2. **Modifier sans proposer** - toujours demander confirmation +3. **Omettre les dΓ©cisions** - tout doit Γͺtre tracΓ© +4. **Laisser les questions sans owner** +5. **Ne pas mettre Γ  jour le progress** + +### βœ… Faire + +1. **Lire `.parac/` systΓ©matiquement** au dΓ©but +2. **Proposer les mises Γ  jour** en fin de session +3. **Documenter immΓ©diatement** les dΓ©cisions +4. **Maintenir la cohΓ©rence** entre fichiers +5. **Signaler les incohΓ©rences** dΓ©tectΓ©es + +--- + +## IntΓ©gration avec Session Protocol + +Ce fichier complΓ¨te `.claude/rules/session-protocol.md`: + +- **session-protocol.md** : Comment gΓ©rer les sessions +- **parac-governance.md** : Comment maintenir `.parac/` Γ  jour + +Les deux DOIVENT Γͺtre suivis ensemble. diff --git a/.claude/rules/session-protocol.md b/.claude/rules/session-protocol.md new file mode 100644 index 0000000..de5e569 --- /dev/null +++ b/.claude/rules/session-protocol.md @@ -0,0 +1,240 @@ +# Session Protocol + +## Session Start Ritual + +At the beginning of each work session, establish context: + +```text +SESSION START +============= +Project: Paracle Multi-Agent Framework +Phase: [Current phase from .parac/memory/context/current_state.yaml] +Focus: [Current task or feature] + +Source of Truth: +- .parac/ - Project governance +- .roadmap/ - Complete roadmap +- docs/ - Architecture documentation + +Continuing from previous state. +I will not reintroduce rejected decisions (see .parac/roadmap/decisions.md). +``` + +--- + +## Context Loading Order + +1. **Read current state** + + ```text + .parac/memory/context/current_state.yaml + ``` + +2. **Check recent decisions** + + ```text + .parac/roadmap/decisions.md (last 5 entries) + ``` + +3. **Review open questions** + + ```text + .parac/memory/context/open_questions.md + ``` + +4. **Check tech debt** + + ```text + .parac/memory/context/tech_debt.md + ``` + +--- + +## During Session + +### Progress Tracking + +After completing significant work: + +```text +CHECKPOINT +========== +Completed: +- [Task 1] +- [Task 2] + +Decisions Made: +- [Decision 1]: [Rationale] + +Open Questions: +- [Question 1] + +Next Steps: +- [Step 1] +- [Step 2] +``` + +### When Stuck + +```text +BLOCKED +======= +Task: [What I'm trying to do] +Blocker: [What's preventing progress] +Attempted: +- [Approach 1]: [Why it failed] +- [Approach 2]: [Why it failed] + +Need: +- [Information/decision/clarification needed] +``` + +--- + +## Session End Ritual + +Before ending a session, produce a summary: + +```markdown +## Session Summary: [Date/Identifier] + +### Accomplished +- [Major accomplishment 1] +- [Major accomplishment 2] + +### Decisions Made +| Decision | Rationale | Impact | +|----------|-----------|--------| +| [D1] | [Why] | [What it affects] | +| [D2] | [Why] | [What it affects] | + +### Rejected Approaches +| Approach | Reason for Rejection | +|----------|---------------------| +| [A1] | [Why rejected] | +| [A2] | [Why rejected] | + +### Open Questions +1. [Question 1] - Priority: [High/Medium/Low] +2. [Question 2] - Priority: [High/Medium/Low] + +### Technical Debt Incurred +- [Debt 1]: [Why, and when to address] + +### Next Session Focus +1. [Priority 1] +2. [Priority 2] +3. [Priority 3] + +### Files Modified +- `path/to/file1.py` - [Brief description] +- `path/to/file2.py` - [Brief description] +``` + +--- + +## Context Handoff + +When transitioning between sessions or contexts: + +```text +HANDOFF DOCUMENT +================ + +## Current State +[Brief description of where things stand] + +## Critical Context +- [Key fact 1 that must not be forgotten] +- [Key fact 2 that must not be forgotten] + +## In-Progress Work +- [Task]: [Status, what's done, what remains] + +## Gotchas +- [Non-obvious thing 1 that could cause confusion] +- [Non-obvious thing 2] + +## Do Not +- [Thing to avoid 1] +- [Thing to avoid 2] + +## Resume From +[Exact point to continue from] +``` + +--- + +## Emergency Recovery + +If context is lost or confused: + +```text +RECOVERY PROTOCOL +================= + +1. Read: .parac/memory/context/current_state.yaml +2. Read: .parac/roadmap/roadmap.yaml (current phase) +3. Read: .roadmap/ROADMAP_GLOBALE.yaml (big picture) +4. Check: git log --oneline -20 (recent changes) +5. Check: git status (current state) + +DO NOT proceed until context is re-established. +ASK for clarification if state is ambiguous. +``` + +--- + +## Cognitive Load Management + +### When Task is Large + +Break into subtasks with explicit boundaries: + +```text +TASK DECOMPOSITION +================== + +Main Task: [Description] + +Subtasks: +1. [ ] [Subtask 1] - Scope: [boundaries] +2. [ ] [Subtask 2] - Scope: [boundaries] +3. [ ] [Subtask 3] - Scope: [boundaries] + +Current Focus: Subtask [N] +Out of Scope for Now: [Everything else] +``` + +### When Confused + +```text +CONFUSION CHECKPOINT +==================== + +What I think I'm doing: [Description] +What I'm uncertain about: [Uncertainty] +What I need to clarify: [Question] + +PAUSE until clarity is achieved. +``` + +--- + +## Quality Gates Per Session + +Before ending any session: + +```text +SESSION QUALITY CHECK +===================== + +[ ] All code changes have tests +[ ] No new linting errors introduced +[ ] Documentation updated if needed +[ ] Decisions documented in decisions.md +[ ] Open questions captured +[ ] Tech debt logged if incurred +[ ] Session summary produced +[ ] Next steps identified +``` diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md new file mode 100644 index 0000000..4a71c7e --- /dev/null +++ b/.claude/rules/testing.md @@ -0,0 +1,193 @@ +# Testing Guidelines + +## Test Structure + +### Arrange-Act-Assert Pattern +```python +def test_agent_creation(): + # Arrange + name = "test-agent" + model = "gpt-4" + + # Act + spec = AgentSpec(name=name, model=model) + + # Assert + assert spec.name == name + assert spec.model == model + assert spec.temperature == 0.7 # default +``` + +### File Organization +``` +tests/ +β”œβ”€β”€ unit/ # Fast, isolated tests +β”‚ β”œβ”€β”€ domain/ +β”‚ β”‚ β”œβ”€β”€ test_agent.py +β”‚ β”‚ └── test_workflow.py +β”‚ β”œβ”€β”€ core/ +β”‚ └── cli/ +β”œβ”€β”€ integration/ # Tests with real dependencies +β”‚ β”œβ”€β”€ test_repository.py +β”‚ └── test_api.py +└── e2e/ # Full system tests + └── test_workflows.py +``` + +### Naming Conventions +- Test files: `test_.py` +- Test functions: `test___` +- Test classes: `Test` + +```python +def test_agent_spec_validates_temperature_when_above_max(): + ... + +def test_agent_inherits_tools_from_parent(): + ... + +class TestAgentRepository: + def test_save_creates_new_agent(self): + ... +``` + +## Fixtures + +### Common Fixtures +```python +import pytest +from paracle_domain.models import AgentSpec, Agent + +@pytest.fixture +def base_agent_spec() -> AgentSpec: + """Create a basic agent specification.""" + return AgentSpec( + name="base-agent", + model="gpt-4", + temperature=0.7, + system_prompt="You are a helpful assistant." + ) + +@pytest.fixture +def agent(base_agent_spec) -> Agent: + """Create an agent instance.""" + return Agent(spec=base_agent_spec) + +@pytest.fixture +async def repository(tmp_path) -> AgentRepository: + """Create an in-memory repository for testing.""" + db_path = tmp_path / "test.db" + repo = SQLiteAgentRepository(str(db_path)) + yield repo + # Cleanup handled by tmp_path fixture +``` + +### Fixture Scope +```python +@pytest.fixture(scope="module") +def expensive_resource(): + """Shared across all tests in module.""" + resource = create_expensive_resource() + yield resource + resource.cleanup() +``` + +## Async Testing + +```python +import pytest + +@pytest.mark.asyncio +async def test_agent_execution(): + # Arrange + spec = AgentSpec(name="test", model="gpt-4") + agent = Agent(spec=spec) + + # Act + result = await agent.execute({"task": "hello"}) + + # Assert + assert result is not None +``` + +## Mocking + +### Use Fixtures Over Mocks When Possible +```python +# Prefer: In-memory implementation +@pytest.fixture +def repository() -> AgentRepository: + return InMemoryAgentRepository() + +# Avoid: Heavy mocking +@pytest.fixture +def repository(mocker): + mock_repo = mocker.Mock(spec=AgentRepository) + mock_repo.get_by_id.return_value = Agent(...) + return mock_repo +``` + +### When Mocking Is Needed +```python +from unittest.mock import AsyncMock, patch + +async def test_provider_called_correctly(mocker): + mock_provider = AsyncMock() + mock_provider.complete.return_value = "response" + + agent = Agent(spec=spec, provider=mock_provider) + await agent.execute({"prompt": "hello"}) + + mock_provider.complete.assert_called_once() +``` + +## Edge Cases + +Always test: +- Empty inputs +- Boundary values (0, max, min) +- None/null handling +- Invalid inputs (validation errors) +- Error conditions + +```python +class TestAgentSpecValidation: + def test_empty_name_raises_error(self): + with pytest.raises(ValueError, match="cannot be empty"): + AgentSpec(name="", model="gpt-4") + + def test_temperature_at_max_boundary(self): + spec = AgentSpec(name="test", model="gpt-4", temperature=2.0) + assert spec.temperature == 2.0 + + def test_temperature_above_max_raises_error(self): + with pytest.raises(ValueError): + AgentSpec(name="test", model="gpt-4", temperature=2.1) +``` + +## Coverage + +- Target: 80%+ code coverage +- Focus on domain logic first +- Don't test implementation details +- Run: `make coverage` + +```bash +pytest --cov=packages --cov-report=html +``` + +## Markers + +```python +@pytest.mark.slow +def test_large_workflow_execution(): + ... + +@pytest.mark.integration +async def test_database_persistence(): + ... + +# Run specific markers +# pytest -m "not slow" +# pytest -m integration +``` diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..d231d40 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,100 @@ +{ + "permissions": { + "allow": [ + "Bash(uv:*)", + "Bash(python:*)", + "Bash(pytest:*)", + "Bash(make:*)", + "Bash(ruff:*)", + "Bash(black:*)", + "Bash(mypy:*)", + "Bash(alembic:*)", + "Bash(git status:*)", + "Bash(git diff:*)", + "Bash(git log:*)", + "Bash(git branch:*)", + "Bash(git show:*)", + "Bash(git stash:*)", + "Bash(paracle:*)", + "Bash(tree:*)", + "Bash(ls:*)", + "Bash(cat:*)", + "Bash(head:*)", + "Bash(tail:*)", + "Bash(wc:*)", + "Bash(find:*)", + "Bash(grep:*)", + "Read(./packages/**)", + "Read(./tests/**)", + "Read(./docs/**)", + "Read(./examples/**)", + "Read(./.parac/**)", + "Read(./.roadmap/**)", + "Read(./.claude/**)", + "Read(./.github/**)", + "Read(./.vscode/**)", + "Read(./pyproject.toml)", + "Read(./Makefile)", + "Read(./README.md)", + "Read(./CONTRIBUTING.md)", + "Read(./.editorconfig)", + "Read(./.gitignore)", + "Edit(./packages/**)", + "Edit(./tests/**)", + "Edit(./docs/**)", + "Edit(./examples/**)", + "Edit(./.parac/**)", + "Edit(./.roadmap/**)", + "Write(./packages/**)", + "Write(./tests/**)", + "Write(./docs/**)", + "Write(./examples/**)" + ], + "deny": [ + "Read(./.env)", + "Read(./.env.*)", + "Read(./secrets/**)", + "Read(**/*credentials*)", + "Read(**/*secret*)", + "Read(**/*password*)", + "Read(**/*token*)", + "Read(**/*.pem)", + "Read(**/*.key)", + "Bash(rm -rf:*)", + "Bash(curl:*)", + "Bash(wget:*)", + "Bash(ssh:*)", + "Bash(scp:*)" + ], + "ask": [ + "Bash(git push:*)", + "Bash(git commit:*)", + "Bash(git checkout:*)", + "Bash(git merge:*)", + "Bash(git rebase:*)", + "Bash(git reset:*)", + "Bash(pip install:*)", + "Bash(uv add:*)", + "Bash(uv remove:*)", + "Bash(docker:*)", + "Bash(npm:*)", + "Edit(./pyproject.toml)", + "Edit(./Makefile)", + "Edit(./.github/**)", + "Write(./.parac/**)", + "Write(./.roadmap/**)" + ], + "additionalDirectories": [] + }, + "env": { + "PYTHONPATH": "./packages", + "PYTHONDONTWRITEBYTECODE": "1", + "PARACLE_ENV": "development", + "PARACLE_LOG_LEVEL": "DEBUG" + }, + "model": "claude-opus-4-5-20251101", + "attribution": { + "commit": "feat: [description]\n\n[detailed changes]\n\nπŸ€– Generated with Claude Code (Opus 4.5)\nCo-Authored-By: Claude ", + "pr": "## Summary\n\n[Brief description]\n\n## Changes\n\n- [Change 1]\n- [Change 2]\n\n## Testing\n\n- [ ] Unit tests added/updated\n- [ ] Integration tests pass\n- [ ] Manual testing completed\n\n---\nπŸ€– Generated with [Claude Code](https://claude.ai/code) (Opus 4.5)" + } +} diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..0e4782e --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,28 @@ +{ + "permissions": { + "allow": [ + "Bash(uv run pytest:*)", + "Bash(mkdir:*)", + "Bash(set:*)", + "Bash(done)", + "Bash(timeout 2 uv run:*)", + "Bash(timeout 10 uv run python:*)", + "Bash(timeout 15 uv run python:*)", + "Bash(taskkill:*)", + "Bash(tasklist:*)", + "Bash(rm:*)", + "Bash(dir \"c:\\\\Projets\\\\paracle\\\\paracle-lite\\\\docs\\\\index.md\")", + "Bash(python3:*)", + "Bash(sqlite3:*)", + "Bash(timeout 30 uv run python:*)", + "Bash(timeout 30 uv run:*)", + "Bash(timeout 60 uv run:*)", + "Bash(for cmd in a2a adr approvals audit benchmark board cache compliance conflicts cost git governance groups meta pool release remote retry reviews roadmap runs)", + "Bash(do)", + "Bash(if ! grep -q \"### $cmd\" \"c:/Projets/paracle/paracle-lite/content/docs/technical/cli-reference.md\")", + "Bash(then)", + "Bash(echo:*)", + "Bash(fi)" + ] + } +} diff --git a/.claude/skills/agent-configuration/SKILL.md b/.claude/skills/agent-configuration/SKILL.md new file mode 100644 index 0000000..934a730 --- /dev/null +++ b/.claude/skills/agent-configuration/SKILL.md @@ -0,0 +1,100 @@ +--- +name: agent-configuration +description: Configure agent specs, inheritance, skills, and tools in .parac/ workspace. Use when setting up or customizing agents. +license: Apache-2.0 +compatibility: YAML, Paracle Framework +metadata: + author: paracle-core-team + version: "1.0.0" + category: automation + level: intermediate + display_name: "Agent Configuration" + tags: + - agents + - configuration + - yaml + - inheritance + capabilities: + - agent_configuration + - inheritance_setup + - skill_assignment + - tool_configuration +allowed-tools: Read Write +--- + +# Agent Configuration Skill + +## When to use this skill + +Use when: +- Creating new agent specifications +- Setting up agent inheritance +- Configuring agent skills and tools +- Customizing agent behavior +- Troubleshooting agent configuration + +## Agent Spec Structure + +```yaml +# .parac/agents/specs/my-agent.yaml +name: my-agent +model: gpt-4 +temperature: 0.7 +max_tokens: 2000 + +system_prompt: | + You are an expert software developer. + You write clean, maintainable code. + +skills: + - code-generation + - debugging + - testing + +tools: + - file-read + - file-write + - shell-execute + +metadata: + author: team + version: "1.0.0" +``` + +## Inheritance Pattern + +```yaml +# Base agent +# .parac/agents/specs/base-coder.yaml +name: base-coder +model: gpt-4 +temperature: 0.7 +system_prompt: "You are a software developer." +skills: + - code-generation + +# Specialized agent (inherits from base) +# .parac/agents/specs/python-coder.yaml +name: python-coder +inherits: base-coder # Inherits all properties from base-coder +temperature: 0.5 # Override: lower temperature for Python +skills: + - code-generation # Inherited + - python-specific # Added +system_prompt: | + You are a Python expert. + Follow PEP 8 standards. +``` + +## Configuration Best Practices + +1. **Use inheritance for common configurations** +2. **Keep system prompts focused** +3. **Test configurations before deployment** +4. **Version control all agent specs** +5. **Document custom configurations** + +## Resources + +- Agent Specs: `.parac/agents/specs/` +- Template: `templates/.parac-template/agents/specs/` \ No newline at end of file diff --git a/.claude/skills/agent-configuration/assets/agent-template.yaml b/.claude/skills/agent-configuration/assets/agent-template.yaml new file mode 100644 index 0000000..402802d --- /dev/null +++ b/.claude/skills/agent-configuration/assets/agent-template.yaml @@ -0,0 +1,38 @@ +--- +# Example Agent Specification Template +# Copy this file and customize for your agent + +name: my-agent +model: gpt-4 +temperature: 0.7 +max_tokens: 2000 + +system_prompt: | + You are a helpful assistant specialized in [DOMAIN]. + + Your responsibilities: + - [RESPONSIBILITY 1] + - [RESPONSIBILITY 2] + - [RESPONSIBILITY 3] + + Guidelines: + - [GUIDELINE 1] + - [GUIDELINE 2] + +skills: + - code-generation + - debugging + # Add more skills as needed + +tools: + - file-read + - file-write + # Add more tools as needed + +metadata: + author: your-name + version: "1.0.0" + description: Brief description of what this agent does + tags: + - tag1 + - tag2 diff --git a/.claude/skills/agent-configuration/assets/specialized-agent-template.yaml b/.claude/skills/agent-configuration/assets/specialized-agent-template.yaml new file mode 100644 index 0000000..7c40101 --- /dev/null +++ b/.claude/skills/agent-configuration/assets/specialized-agent-template.yaml @@ -0,0 +1,34 @@ +--- +# Specialized Agent with Inheritance +# This agent inherits from a base agent and adds specialization + +name: specialized-agent +inherits: base-agent # Inherits all properties from base-agent + +# Override specific properties +temperature: 0.5 # Lower temperature for more focused responses + +# Extend system prompt +system_prompt: | + {{parent.system_prompt}} + + Additional specialization: + - [SPECIALIZATION 1] + - [SPECIALIZATION 2] + +# Add more skills +skills: + - { { parent.skills } } # Include parent skills + - specialized-skill-1 + - specialized-skill-2 + +# Add more tools +tools: + - { { parent.tools } } # Include parent tools + - specialized-tool + +metadata: + author: your-name + version: "1.0.0" + parent: base-agent + description: Specialized version of base-agent for [PURPOSE] diff --git a/.claude/skills/api-development/SKILL.md b/.claude/skills/api-development/SKILL.md new file mode 100644 index 0000000..2b7f05c --- /dev/null +++ b/.claude/skills/api-development/SKILL.md @@ -0,0 +1,514 @@ +--- +name: api-development +description: Design and implement REST APIs using FastAPI. Use when creating endpoints, request/response schemas, middleware, error handling, or API documentation. +license: Apache-2.0 +compatibility: FastAPI, Pydantic v2, Python 3.10+ +metadata: + author: paracle-core-team + version: "1.0.0" + category: creation + level: advanced + display_name: "API Development with FastAPI" + tags: + - api + - fastapi + - rest + - http + - openapi + capabilities: + - endpoint_creation + - schema_design + - middleware_implementation + - error_handling + - api_documentation +allowed-tools: Read Write Bash(python:*) Bash(pytest:*) +--- + +# API Development Skill + +## When to use this skill + +Use this skill when: + +- Creating new REST API endpoints +- Designing request/response schemas with Pydantic +- Implementing middleware or dependencies +- Adding error handling and validation +- Documenting APIs with OpenAPI/Swagger +- Testing API endpoints +- Adding authentication/authorization + +## Paracle API Architecture + +### Structure + +``` +packages/paracle_api/ +β”œβ”€β”€ __init__.py +β”œβ”€β”€ main.py # FastAPI application +β”œβ”€β”€ routers/ # Endpoint routers +β”‚ β”œβ”€β”€ agents.py +β”‚ β”œβ”€β”€ workflows.py +β”‚ └── tools.py +β”œβ”€β”€ schemas/ # Pydantic models +β”‚ β”œβ”€β”€ agent.py +β”‚ β”œβ”€β”€ workflow.py +β”‚ └── common.py +β”œβ”€β”€ dependencies.py # Shared dependencies +β”œβ”€β”€ middleware.py # Custom middleware +└── errors.py # Error handlers +``` + +## API Development Patterns + +### Pattern 1: Creating a New Endpoint + +```python +# packages/paracle_api/routers/agents.py +from fastapi import APIRouter, Depends, HTTPException, status +from pydantic import BaseModel, Field + +router = APIRouter(prefix="/api/v1/agents", tags=["agents"]) + +# Request schema +class CreateAgentRequest(BaseModel): + """Request to create a new agent.""" + name: str = Field(..., min_length=1, max_length=100, description="Agent name") + model: str = Field(default="gpt-4", description="LLM model to use") + temperature: float = Field(default=0.7, ge=0.0, le=2.0) + system_prompt: str | None = Field(default=None, description="Custom system prompt") + +# Response schema +class AgentResponse(BaseModel): + """Agent response.""" + id: str = Field(..., description="Unique agent ID") + name: str + model: str + temperature: float + created_at: str + + class Config: + from_attributes = True # For SQLAlchemy models + +# Endpoint +@router.post( + "/", + response_model=AgentResponse, + status_code=status.HTTP_201_CREATED, + summary="Create a new agent", + description="Create a new agent with the specified configuration", +) +async def create_agent( + request: CreateAgentRequest, + repo: AgentRepository = Depends(get_agent_repository), +) -> AgentResponse: + """ + Create a new agent. + + Args: + request: Agent creation request + repo: Agent repository (injected) + + Returns: + Created agent + + Raises: + HTTPException: If agent creation fails + """ + try: + agent = await repo.create( + name=request.name, + model=request.model, + temperature=request.temperature, + system_prompt=request.system_prompt, + ) + return AgentResponse.from_orm(agent) + except ValidationError as e: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail=str(e), + ) + except Exception as e: + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail="Failed to create agent", + ) +``` + +### Pattern 2: Dependency Injection + +```python +# packages/paracle_api/dependencies.py +from typing import Annotated +from fastapi import Depends, Header, HTTPException +from paracle_store import AgentRepository, get_session + +async def get_agent_repository() -> AgentRepository: + """Get agent repository instance.""" + session = get_session() + return AgentRepository(session) + +async def verify_api_key( + x_api_key: Annotated[str, Header()] = None, +) -> str: + """Verify API key from header.""" + if not x_api_key or x_api_key != settings.API_KEY: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid API key", + ) + return x_api_key + +# Usage in endpoint +@router.get("/agents/{agent_id}") +async def get_agent( + agent_id: str, + repo: AgentRepository = Depends(get_agent_repository), + api_key: str = Depends(verify_api_key), +): + ... +``` + +### Pattern 3: Error Handling + +```python +# packages/paracle_api/errors.py +from fastapi import Request, status +from fastapi.responses import JSONResponse +from paracle_domain import AgentNotFoundError, ValidationError + +async def agent_not_found_handler( + request: Request, + exc: AgentNotFoundError, +) -> JSONResponse: + """Handle agent not found errors.""" + return JSONResponse( + status_code=status.HTTP_404_NOT_FOUND, + content={ + "error": "agent_not_found", + "message": str(exc), + "agent_id": exc.agent_id, + }, + ) + +# Register in main.py +app.add_exception_handler(AgentNotFoundError, agent_not_found_handler) +``` + +### Pattern 4: Middleware + +```python +# packages/paracle_api/middleware.py +from fastapi import Request +from time import time +import logging + +logger = logging.getLogger(__name__) + +async def logging_middleware(request: Request, call_next): + """Log all requests with timing.""" + start_time = time() + + # Log request + logger.info( + f"Request: {request.method} {request.url.path}", + extra={ + "method": request.method, + "path": request.url.path, + "client": request.client.host if request.client else None, + }, + ) + + # Process request + response = await call_next(request) + + # Log response + duration = time() - start_time + logger.info( + f"Response: {response.status_code} ({duration:.3f}s)", + extra={ + "status_code": response.status_code, + "duration_ms": int(duration * 1000), + }, + ) + + response.headers["X-Process-Time"] = str(duration) + return response + +# Register in main.py +app.middleware("http")(logging_middleware) +``` + +### Pattern 5: API Testing + +```python +# tests/integration/test_api_agents.py +import pytest +from fastapi.testclient import TestClient +from paracle_api.main import app + +client = TestClient(app) + +def test_create_agent(): + """Test creating an agent via API.""" + response = client.post( + "/api/v1/agents/", + json={ + "name": "test-agent", + "model": "gpt-4", + "temperature": 0.7, + }, + ) + + assert response.status_code == 201 + data = response.json() + assert data["name"] == "test-agent" + assert "id" in data + assert "created_at" in data + +def test_create_agent_validation_error(): + """Test validation error handling.""" + response = client.post( + "/api/v1/agents/", + json={ + "name": "", # Invalid: empty name + "temperature": 3.0, # Invalid: too high + }, + ) + + assert response.status_code == 422 + assert "detail" in response.json() + +@pytest.mark.asyncio +async def test_get_agent_not_found(): + """Test 404 handling.""" + response = client.get("/api/v1/agents/nonexistent") + + assert response.status_code == 404 + data = response.json() + assert data["error"] == "agent_not_found" +``` + +## API Design Standards + +### 1. URL Structure + +``` +# Resources (plural nouns) +GET /api/v1/agents # List all agents +POST /api/v1/agents # Create agent +GET /api/v1/agents/{id} # Get specific agent +PUT /api/v1/agents/{id} # Update agent +DELETE /api/v1/agents/{id} # Delete agent + +# Sub-resources +GET /api/v1/agents/{id}/skills # List agent's skills +POST /api/v1/agents/{id}/run # Execute agent action + +# Query parameters for filtering/pagination +GET /api/v1/agents?model=gpt-4&limit=10&offset=0 +``` + +### 2. Status Codes + +```python +# Success +200 OK # GET, PUT, PATCH success +201 Created # POST success +204 No Content # DELETE success + +# Client Errors +400 Bad Request # Invalid request format +401 Unauthorized # Missing/invalid authentication +403 Forbidden # Valid auth but no permission +404 Not Found # Resource doesn't exist +422 Unprocessable Entity # Validation error + +# Server Errors +500 Internal Server Error # Unexpected server error +503 Service Unavailable # Temporary service issue +``` + +### 3. Response Format + +```json +// Success response +{ + "id": "agent-123", + "name": "my-agent", + "model": "gpt-4", + "created_at": "2026-01-04T10:30:00Z" +} + +// Error response +{ + "error": "validation_error", + "message": "Temperature must be between 0.0 and 2.0", + "field": "temperature", + "value": 3.0 +} + +// List response with pagination +{ + "items": [...], + "total": 42, + "limit": 10, + "offset": 0, + "next": "/api/v1/agents?limit=10&offset=10" +} +``` + +### 4. OpenAPI Documentation + +```python +# main.py +app = FastAPI( + title="Paracle API", + description="Multi-agent orchestration framework API", + version="0.1.0", + docs_url="/docs", + redoc_url="/redoc", + openapi_tags=[ + { + "name": "agents", + "description": "Agent management endpoints", + }, + { + "name": "workflows", + "description": "Workflow orchestration endpoints", + }, + ], +) +``` + +## Testing APIs + +### Unit Tests + +```python +# Test schemas +def test_create_agent_request_validation(): + """Test request schema validation.""" + # Valid + request = CreateAgentRequest(name="test", model="gpt-4") + assert request.name == "test" + + # Invalid temperature + with pytest.raises(ValidationError): + CreateAgentRequest(name="test", temperature=5.0) +``` + +### Integration Tests + +```python +# Test with test database +@pytest.fixture +def test_db(): + """Provide test database.""" + engine = create_engine("sqlite:///:memory:") + Base.metadata.create_all(engine) + yield engine + Base.metadata.drop_all(engine) + +def test_full_agent_lifecycle(test_db): + """Test create -> read -> update -> delete.""" + # Create + response = client.post("/api/v1/agents/", json={"name": "test"}) + agent_id = response.json()["id"] + + # Read + response = client.get(f"/api/v1/agents/{agent_id}") + assert response.status_code == 200 + + # Update + response = client.put( + f"/api/v1/agents/{agent_id}", + json={"temperature": 0.8}, + ) + assert response.json()["temperature"] == 0.8 + + # Delete + response = client.delete(f"/api/v1/agents/{agent_id}") + assert response.status_code == 204 +``` + +## Performance Considerations + +### 1. Async All The Way + +```python +# Good: Fully async +@router.get("/agents/{id}") +async def get_agent( + id: str, + repo: AgentRepository = Depends(get_async_repository), +): + agent = await repo.get_by_id(id) + return agent + +# Bad: Blocking call in async function +async def get_agent(id: str): + agent = repo.get_by_id_sync(id) # Blocks event loop! + return agent +``` + +### 2. Database Connection Pooling + +```python +# Use async SQLAlchemy with connection pooling +from sqlalchemy.ext.asyncio import create_async_engine + +engine = create_async_engine( + "sqlite+aiosqlite:///paracle.db", + pool_size=5, + max_overflow=10, +) +``` + +### 3. Response Caching + +```python +from fastapi_cache import FastAPICache +from fastapi_cache.decorator import cache + +@router.get("/agents") +@cache(expire=60) # Cache for 60 seconds +async def list_agents(): + return await repo.list_all() +``` + +## Security Best Practices + +1. **Input Validation**: Always validate with Pydantic +2. **SQL Injection**: Use parameterized queries (SQLAlchemy) +3. **Authentication**: Implement API key or JWT +4. **Rate Limiting**: Use middleware to prevent abuse +5. **CORS**: Configure allowed origins +6. **HTTPS**: Always use in production + +## Common Pitfalls + +❌ **Don't:** + +- Return raw database models (use Pydantic schemas) + +- Block the event loop with sync code +- Return 500 for validation errors (use 422) + +- Expose internal error details in production +- Skip input validation + +βœ… **Do:** + +- Use proper HTTP status codes +- Implement comprehensive error handling +- Add request/response logging +- Write integration tests +- Document with OpenAPI tags + +## Resources + +- [FastAPI Documentation](https://fastapi.tiangolo.com/) +- [Pydantic V2 Documentation](https://docs.pydantic.dev/) +- [REST API Best Practices](https://restfulapi.net/) +- Paracle API: `packages/paracle_api/` \ No newline at end of file diff --git a/.claude/skills/api-development/references/REFERENCE.md b/.claude/skills/api-development/references/REFERENCE.md new file mode 100644 index 0000000..a3099ec --- /dev/null +++ b/.claude/skills/api-development/references/REFERENCE.md @@ -0,0 +1,297 @@ +# API Development Reference Guide + +This document provides extended patterns and best practices for API development with FastAPI. + +## Table of Contents + +- [Advanced Request Handling](#advanced-request-handling) +- [Response Models](#response-models) +- [Pagination Patterns](#pagination-patterns) +- [Filtering and Sorting](#filtering-and-sorting) +- [Background Tasks](#background-tasks) +- [WebSocket Support](#websocket-support) + +## Advanced Request Handling + +### File Uploads + +```python +from fastapi import UploadFile, File + +@app.post("/upload") +async def upload_file(file: UploadFile = File(...)): + contents = await file.read() + # Process file + return {"filename": file.filename, "size": len(contents)} +``` + +### Form Data + +```python +from fastapi import Form + +@app.post("/login") +async def login(username: str = Form(...), password: str = Form(...)): + # Authenticate user + return {"access_token": token} +``` + +### Request Body with Multiple Models + +```python +from pydantic import BaseModel +from typing import Union + +class ImageData(BaseModel): + url: str + alt: str + +class TextData(BaseModel): + content: str + format: str + +@app.post("/content") +async def create_content(data: Union[ImageData, TextData]): + # Handle either type + return data +``` + +## Response Models + +### Excluding Unset Fields + +```python +@app.get("/agents/{id}", response_model=AgentResponse, response_model_exclude_unset=True) +async def get_agent(id: str): + # Only return fields that are set + return agent +``` + +### Multiple Response Models + +```python +from fastapi.responses import JSONResponse + +@app.get("/data") +async def get_data(format: str = "json"): + data = fetch_data() + + if format == "csv": + return Response(content=to_csv(data), media_type="text/csv") + + return JSONResponse(content=data) +``` + +## Pagination Patterns + +### Offset-Based Pagination + +```python +from fastapi import Query + +class PaginatedResponse(BaseModel): + items: List[Any] + total: int + offset: int + limit: int + +@app.get("/items", response_model=PaginatedResponse) +async def list_items( + offset: int = Query(0, ge=0), + limit: int = Query(10, ge=1, le=100), +): + items = fetch_items(offset, limit) + total = count_items() + + return PaginatedResponse( + items=items, + total=total, + offset=offset, + limit=limit, + ) +``` + +### Cursor-Based Pagination + +```python +@app.get("/items") +async def list_items(cursor: Optional[str] = None, limit: int = 10): + items, next_cursor = fetch_items_after(cursor, limit) + + return { + "items": items, + "next_cursor": next_cursor, + "has_more": next_cursor is not None, + } +``` + +## Filtering and Sorting + +### Query Parameters + +```python +from enum import Enum + +class SortOrder(str, Enum): + ASC = "asc" + DESC = "desc" + +@app.get("/agents") +async def list_agents( + status: Optional[str] = None, + model: Optional[str] = None, + sort_by: str = "created_at", + order: SortOrder = SortOrder.DESC, +): + filters = {} + if status: + filters["status"] = status + if model: + filters["model"] = model + + agents = fetch_agents(filters, sort_by, order) + return agents +``` + +### Complex Filtering + +```python +from fastapi import Query + +@app.get("/search") +async def search( + q: str = Query(..., min_length=1), + tags: List[str] = Query([]), + min_score: float = Query(0.0, ge=0.0, le=1.0), +): + results = search_items( + query=q, + tags=tags, + min_score=min_score, + ) + return results +``` + +## Background Tasks + +### Simple Background Task + +```python +from fastapi import BackgroundTasks + +def send_notification(email: str, message: str): + # Send email (time-consuming) + send_email(email, message) + +@app.post("/process") +async def process_data( + data: DataInput, + background_tasks: BackgroundTasks, +): + # Process immediately + result = process(data) + + # Send notification in background + background_tasks.add_task( + send_notification, + data.email, + "Processing complete", + ) + + return result +``` + +### Task Queue Integration + +```python +from celery import Celery + +celery = Celery("tasks", broker="redis://localhost:6379") + +@celery.task +def process_heavy_task(data_id: str): + # Long-running task + pass + +@app.post("/heavy-task") +async def create_task(data: DataInput): + # Queue task + task = process_heavy_task.delay(data.id) + + return {"task_id": task.id, "status": "queued"} +``` + +## WebSocket Support + +### Basic WebSocket + +```python +from fastapi import WebSocket + +@app.websocket("/ws") +async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + + try: + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Echo: {data}") + except: + pass +``` + +### WebSocket with Authentication + +```python +@app.websocket("/ws/{token}") +async def websocket_endpoint(websocket: WebSocket, token: str): + user = await authenticate_token(token) + if not user: + await websocket.close(code=status.WS_1008_POLICY_VIOLATION) + return + + await websocket.accept() + # Handle messages +``` + +## API Versioning + +### URL Path Versioning + +```python +from fastapi import APIRouter + +v1_router = APIRouter(prefix="/v1") +v2_router = APIRouter(prefix="/v2") + +@v1_router.get("/agents") +async def list_agents_v1(): + # Version 1 implementation + pass + +@v2_router.get("/agents") +async def list_agents_v2(): + # Version 2 implementation + pass + +app.include_router(v1_router) +app.include_router(v2_router) +``` + +### Header-Based Versioning + +```python +from fastapi import Header + +@app.get("/agents") +async def list_agents(api_version: str = Header("1.0")): + if api_version == "2.0": + return list_agents_v2() + return list_agents_v1() +``` + +## See Also + +- [FastAPI Documentation](https://fastapi.tiangolo.com/) +- [Pydantic Documentation](https://docs.pydantic.dev/) +- `SKILL.md` for quick reference patterns diff --git a/.claude/skills/api-development/scripts/example_app.py b/.claude/skills/api-development/scripts/example_app.py new file mode 100644 index 0000000..166e4cd --- /dev/null +++ b/.claude/skills/api-development/scripts/example_app.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Example FastAPI application demonstrating best practices. + +This example shows: +- Pydantic models for validation +- Dependency injection +- Error handling +- API documentation +- Middleware +""" + + +from fastapi import Depends, FastAPI, HTTPException, status +from pydantic import BaseModel, Field + +app = FastAPI( + title="Paracle API Example", + description="Example API following best practices", + version="1.0.0", +) + +# Models + + +class AgentCreate(BaseModel): + """Request model for creating an agent.""" + name: str = Field(..., min_length=1, max_length=100) + model: str = Field(default="gpt-4") + temperature: float = Field(default=0.7, ge=0.0, le=2.0) + + +class AgentResponse(BaseModel): + """Response model for agent.""" + id: str + name: str + model: str + temperature: float + +# Dependency injection example + + +async def get_current_user(): + """Dependency for authentication.""" + # In production, validate JWT token here + return {"id": "user123", "name": "Test User"} + +# Endpoints + + +@app.post( + "/agents", + response_model=AgentResponse, + status_code=status.HTTP_201_CREATED, +) +async def create_agent( + agent: AgentCreate, + user=Depends(get_current_user), +): + """Create a new agent. + + Args: + agent: Agent creation data + user: Current authenticated user + + Returns: + Created agent with ID + + Raises: + HTTPException: If agent name already exists + """ + # Check if agent exists + if agent.name == "existing-agent": + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Agent with this name already exists", + ) + + # Create agent (simplified) + return AgentResponse( + id="agent-123", + name=agent.name, + model=agent.model, + temperature=agent.temperature, + ) + + +@app.get("/agents/{agent_id}", response_model=AgentResponse) +async def get_agent( + agent_id: str, + user=Depends(get_current_user), +): + """Get agent by ID.""" + if agent_id != "agent-123": + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Agent not found", + ) + + return AgentResponse( + id=agent_id, + name="example-agent", + model="gpt-4", + temperature=0.7, + ) + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/.claude/skills/cicd-devops/SKILL.md b/.claude/skills/cicd-devops/SKILL.md new file mode 100644 index 0000000..20aca21 --- /dev/null +++ b/.claude/skills/cicd-devops/SKILL.md @@ -0,0 +1,447 @@ +--- +name: cicd-devops +description: Manage GitHub Actions workflows, containerization, deployment pipelines, and release automation. Use when working with CI/CD, Docker, or deployment. +license: Apache-2.0 +compatibility: GitHub Actions, Docker, Docker Compose +metadata: + author: paracle-core-team + version: "1.0.0" + category: automation + level: advanced + display_name: "CI/CD & DevOps" + tags: + - cicd + - github-actions + - docker + - deployment + - automation + capabilities: + - ci_pipeline + - docker_containerization + - deployment_automation + - release_management +allowed-tools: Read Write Bash(docker:*) Bash(git:*) +--- + +# CI/CD & DevOps Skill + +## When to use this skill + +Use this skill when: +- Creating or updating GitHub Actions workflows +- Building Docker containers +- Setting up deployment pipelines +- Automating releases +- Managing infrastructure as code +- Configuring environments + +## Paracle CI/CD Structure + +``` +.github/ +β”œβ”€β”€ workflows/ +β”‚ β”œβ”€β”€ ci.yml # Main CI pipeline +β”‚ β”œβ”€β”€ release.yml # Release automation +β”‚ └── deploy.yml # Deployment +β”œβ”€β”€ actions/ # Custom actions +β”‚ └── setup-python/ +└── dependabot.yml # Dependency updates + +docker/ +β”œβ”€β”€ Dockerfile.api # API container +β”œβ”€β”€ Dockerfile.worker # Worker container +β”œβ”€β”€ docker-compose.yaml # Local development +└── docker-compose.prod.yaml # Production +``` + +## GitHub Actions Patterns + +### Pattern 1: CI Pipeline + +```yaml +# .github/workflows/ci.yml +name: CI + +on: + push: + branches: [main, develop] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.10", "3.11", "3.12"] + + steps: + - uses: actions/checkout@v4 + + - name: Install uv + uses: astral-sh/setup-uv@v1 + + - name: Set up Python ${{ matrix.python-version }} + run: uv python install ${{ matrix.python-version }} + + - name: Install dependencies + run: uv sync + + - name: Run linters + run: | + uv run ruff check . + uv run black --check . + uv run mypy packages/ + + - name: Run tests + run: uv run pytest --cov=packages --cov-report=xml + + - name: Upload coverage + uses: codecov/codecov-action@v3 + with: + file: ./coverage.xml + + build: + needs: test + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Build package + run: | + uv build + + - name: Upload artifacts + uses: actions/upload-artifact@v3 + with: + name: dist + path: dist/ +``` + +### Pattern 2: Release Automation + +```yaml +# .github/workflows/release.yml +name: Release + +on: + push: + tags: + - 'v*' + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: write + + steps: + - uses: actions/checkout@v4 + + - name: Build package + run: uv build + + - name: Create Release + uses: softprops/action-gh-release@v1 + with: + files: dist/* + generate_release_notes: true + + - name: Publish to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + password: ${{ secrets.PYPI_API_TOKEN }} +``` + +### Pattern 3: Docker Build & Push + +```yaml +# .github/workflows/docker.yml +name: Docker + +on: + push: + branches: [main] + tags: ['v*'] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ghcr.io/${{ github.repository }} + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + + - name: Build and push + uses: docker/build-push-action@v5 + with: + context: . + file: docker/Dockerfile.api + push: true + tags: ${{ steps.meta.outputs.tags }} + cache-from: type=gha + cache-to: type=gha,mode=max +``` + +## Docker Patterns + +### Pattern 1: Multi-Stage Dockerfile + +```dockerfile +# docker/Dockerfile.api +FROM python:3.11-slim as builder + +# Install uv +COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv + +# Set working directory +WORKDIR /app + +# Copy dependency files +COPY pyproject.toml uv.lock ./ + +# Install dependencies +RUN uv sync --frozen --no-dev + +# Production stage +FROM python:3.11-slim + +WORKDIR /app + +# Copy virtual environment from builder +COPY --from=builder /app/.venv /app/.venv + +# Copy application code +COPY packages/ ./packages/ + +# Set environment +ENV PATH="/app/.venv/bin:$PATH" +ENV PYTHONPATH="/app" + +# Expose port +EXPOSE 8000 + +# Run application +CMD ["uvicorn", "paracle_api.main:app", "--host", "0.0.0.0", "--port", "8000"] +``` + +### Pattern 2: Docker Compose + +```yaml +# docker/docker-compose.yaml +version: '3.8' + +services: + api: + build: + context: .. + dockerfile: docker/Dockerfile.api + ports: + - "8000:8000" + environment: + - DATABASE_URL=sqlite:///data/paracle.db + - LOG_LEVEL=info + volumes: + - api-data:/app/data + depends_on: + - redis + networks: + - paracle + + worker: + build: + context: .. + dockerfile: docker/Dockerfile.worker + environment: + - REDIS_URL=redis://redis:6379 + depends_on: + - redis + networks: + - paracle + + redis: + image: redis:7-alpine + ports: + - "6379:6379" + volumes: + - redis-data:/data + networks: + - paracle + +volumes: + api-data: + redis-data: + +networks: + paracle: + driver: bridge +``` + +## Deployment Patterns + +### Pattern 1: Environment Configuration + +```yaml +# .parac/deployment/environments/production.yaml +environment: production + +api: + replicas: 3 + resources: + limits: + cpu: "1000m" + memory: "1Gi" + requests: + cpu: "500m" + memory: "512Mi" + +database: + url: ${DATABASE_URL} + pool_size: 10 + +monitoring: + enabled: true + metrics_port: 9090 +``` + +### Pattern 2: Health Checks + +```python +# packages/paracle_api/health.py +from fastapi import APIRouter, status +from pydantic import BaseModel + +router = APIRouter(tags=["health"]) + +class HealthResponse(BaseModel): + status: str + version: str + database: str + +@router.get("/health", response_model=HealthResponse) +async def health_check(): + """Health check endpoint for monitoring.""" + return HealthResponse( + status="healthy", + version="0.1.0", + database="connected", + ) + +@router.get("/ready") +async def readiness_check(): + """Readiness check for load balancers.""" + # Check dependencies (database, redis, etc.) + return {"ready": True} +``` + +## Monitoring & Logging + +### Pattern 1: Structured Logging + +```python +# packages/paracle_core/logging/structured.py +import logging +import json +from datetime import datetime + +class JSONFormatter(logging.Formatter): + """Format logs as JSON for aggregation.""" + + def format(self, record): + log_data = { + "timestamp": datetime.utcnow().isoformat(), + "level": record.levelname, + "logger": record.name, + "message": record.getMessage(), + "module": record.module, + "function": record.funcName, + } + + if record.exc_info: + log_data["exception"] = self.formatException(record.exc_info) + + return json.dumps(log_data) + +# Usage +handler = logging.StreamHandler() +handler.setFormatter(JSONFormatter()) +logger = logging.getLogger("paracle") +logger.addHandler(handler) +``` + +## Best Practices + +### 1. Secrets Management + +```yaml +# ❌ Bad: Hardcoded secrets +env: + API_KEY: "sk-abc123" + +# βœ… Good: GitHub Secrets +env: + API_KEY: ${{ secrets.API_KEY }} +``` + +### 2. Caching + +```yaml +# Cache dependencies +- name: Cache uv packages + uses: actions/cache@v3 + with: + path: ~/.cache/uv + key: ${{ runner.os }}-uv-${{ hashFiles('**/uv.lock') }} +``` + +### 3. Matrix Testing + +```yaml +strategy: + matrix: + python-version: ["3.10", "3.11", "3.12"] + os: [ubuntu-latest, macos-latest, windows-latest] +``` + +## Common Pitfalls + +❌ **Don't:** +- Commit secrets to repository +- Run CI on every file change +- Use `latest` tags in production +- Skip health checks +- Ignore resource limits + +βœ… **Do:** +- Use secrets management +- Optimize CI with caching +- Pin versions +- Implement health endpoints +- Set resource limits + +## Resources + +- [GitHub Actions Docs](https://docs.github.com/actions) +- [Docker Best Practices](https://docs.docker.com/develop/dev-best-practices/) +- [12-Factor App](https://12factor.net/) +- Paracle CI/CD: `.github/workflows/` \ No newline at end of file diff --git a/.claude/skills/cicd-devops/assets/ci-template.yml b/.claude/skills/cicd-devops/assets/ci-template.yml new file mode 100644 index 0000000..7020883 --- /dev/null +++ b/.claude/skills/cicd-devops/assets/ci-template.yml @@ -0,0 +1,61 @@ +name: CI Pipeline + +on: + push: + branches: [main, develop] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.10", "3.11", "3.12"] + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -e ".[dev]" + + - name: Run tests + run: | + pytest --cov=packages --cov-report=xml --cov-report=term + + - name: Upload coverage + uses: codecov/codecov-action@v3 + with: + file: ./coverage.xml + fail_ci_if_error: true + + lint: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.10" + + - name: Install dependencies + run: | + pip install ruff black mypy + + - name: Run ruff + run: ruff check packages/ + + - name: Run black + run: black --check packages/ + + - name: Run mypy + run: mypy packages/ diff --git a/.claude/skills/cicd-devops/assets/deploy-template.yml b/.claude/skills/cicd-devops/assets/deploy-template.yml new file mode 100644 index 0000000..1f0f95e --- /dev/null +++ b/.claude/skills/cicd-devops/assets/deploy-template.yml @@ -0,0 +1,62 @@ +name: Deploy to Production + +on: + release: + types: [published] + workflow_dispatch: + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + build-and-push: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - uses: actions/checkout@v4 + + - name: Log in to Container Registry + uses: docker/login-action@v3 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + type=sha + + - name: Build and push Docker image + uses: docker/build-push-action@v5 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + + deploy: + needs: build-and-push + runs-on: ubuntu-latest + environment: production + + steps: + - name: Deploy to production + run: | + # Add your deployment commands here + echo "Deploying version ${{ github.ref_name }}" + # kubectl set image deployment/app app=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.ref_name }} + + - name: Verify deployment + run: | + # Health check + curl -f https://api.example.com/health || exit 1 diff --git a/.claude/skills/cicd-devops/scripts/check_health.sh b/.claude/skills/cicd-devops/scripts/check_health.sh new file mode 100644 index 0000000..22a862b --- /dev/null +++ b/.claude/skills/cicd-devops/scripts/check_health.sh @@ -0,0 +1,23 @@ +#!/bin/bash +# Health check script for deployment verification + +set -e + +API_URL="${API_URL:-http://localhost:8000}" +MAX_RETRIES="${MAX_RETRIES:-30}" +RETRY_INTERVAL="${RETRY_INTERVAL:-2}" + +echo "πŸ” Checking API health at $API_URL" + +for i in $(seq 1 $MAX_RETRIES); do + if curl -sf "$API_URL/health" > /dev/null; then + echo "βœ… API is healthy!" + exit 0 + fi + + echo "⏳ Attempt $i/$MAX_RETRIES failed, retrying in ${RETRY_INTERVAL}s..." + sleep $RETRY_INTERVAL +done + +echo "❌ API health check failed after $MAX_RETRIES attempts" +exit 1 diff --git a/.claude/skills/framework-architecture/SKILL.md b/.claude/skills/framework-architecture/SKILL.md new file mode 100644 index 0000000..69f5b92 --- /dev/null +++ b/.claude/skills/framework-architecture/SKILL.md @@ -0,0 +1,505 @@ +--- +name: framework-architecture +description: Design and evolve the architecture of the Paracle multi-agent framework. Use when discussing system design, architecture decisions, component structure, or technical debt. +license: Apache-2.0 +compatibility: Requires understanding of Python, FastAPI, SQLAlchemy, event-driven architecture +metadata: + author: paracle-core-team + version: "1.0.0" + category: creation + level: expert + display_name: "Framework Architecture Design" + tags: + - architecture + - design + - framework + - system-design + - patterns + capabilities: + - architecture_design + - pattern_selection + - component_design + - integration_planning + - scalability_analysis +allowed-tools: Read Write Bash(git:*) Bash(python:*) +--- + +# Framework Architecture Design Skill + +## When to use this skill + +Use this skill when: +- Designing new framework components or subsystems +- Evaluating architecture decisions and trade-offs +- Refactoring existing framework code +- Planning integration between modules +- Addressing scalability or performance concerns +- Resolving technical debt +- Creating ADRs (Architecture Decision Records) + +## Paracle Framework Context + +### Core Principles + +1. **User-Driven Philosophy** + - Users control agent behavior via .parac/ configuration + - Declarative over imperative configuration + - Progressive disclosure of complexity + +2. **Modular Architecture** + - Clear separation of concerns + - Domain-driven design + - Pluggable components + +3. **Multi-Agent Coordination** + - Agent inheritance system + - Skill-based capabilities + - Workflow orchestration + +### Architecture Layers + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ User Configuration β”‚ +β”‚ (.parac/) β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Application Layer β”‚ +β”‚ (CLI, API, Orchestrator) β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Domain Layer β”‚ +β”‚ (Agents, Workflows, Tools, Skills) β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Infrastructure Layer β”‚ +β”‚ (Events, Storage, Providers) β”‚ +β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ +β”‚ Adapters Layer β”‚ +β”‚ (OpenAI, Anthropic, Azure, MCP) β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +## Design Patterns for Paracle + +### Pattern 1: Plugin Architecture + +For adding new capabilities (LLM providers, tools, orchestrators): + +```python +# Base interface +class Provider(Protocol): + """Base protocol for LLM providers.""" + + def generate(self, prompt: str, **kwargs) -> str: + """Generate completion from prompt.""" + ... + + def stream(self, prompt: str, **kwargs) -> Iterator[str]: + """Stream completion tokens.""" + ... + +# Implementation +class OpenAIProvider: + """OpenAI implementation.""" + + def __init__(self, api_key: str, model: str): + self.client = OpenAI(api_key=api_key) + self.model = model + + def generate(self, prompt: str, **kwargs) -> str: + response = self.client.chat.completions.create( + model=self.model, + messages=[{"role": "user", "content": prompt}], + **kwargs + ) + return response.choices[0].message.content + +# Registry +class ProviderRegistry: + _providers: Dict[str, Type[Provider]] = {} + + @classmethod + def register(cls, name: str, provider_class: Type[Provider]): + cls._providers[name] = provider_class + + @classmethod + def get(cls, name: str) -> Type[Provider]: + return cls._providers[name] + +# Usage +ProviderRegistry.register("openai", OpenAIProvider) +``` + +### Pattern 2: Event-Driven Communication + +For decoupling components: + +```python +from dataclasses import dataclass +from typing import Callable, List +from enum import Enum + +class EventType(str, Enum): + AGENT_STARTED = "agent.started" + AGENT_COMPLETED = "agent.completed" + TOOL_EXECUTED = "tool.executed" + ERROR_OCCURRED = "error.occurred" + +@dataclass +class Event: + """Base event class.""" + type: EventType + agent_id: str + timestamp: datetime + payload: dict + +class EventBus: + """Simple in-memory event bus.""" + + def __init__(self): + self._handlers: Dict[EventType, List[Callable]] = {} + + def subscribe(self, event_type: EventType, handler: Callable): + """Subscribe to an event type.""" + if event_type not in self._handlers: + self._handlers[event_type] = [] + self._handlers[event_type].append(handler) + + def publish(self, event: Event): + """Publish an event to all subscribers.""" + if event.type in self._handlers: + for handler in self._handlers[event.type]: + handler(event) + +# Usage +event_bus = EventBus() + +def log_agent_completion(event: Event): + print(f"Agent {event.agent_id} completed") + +event_bus.subscribe(EventType.AGENT_COMPLETED, log_agent_completion) +``` + +### Pattern 3: Configuration-Driven Behavior + +Load behavior from YAML configs: + +```python +from pathlib import Path +import yaml +from pydantic import BaseModel + +class AgentConfig(BaseModel): + """Agent configuration from .parac/agents/specs/""" + name: str + provider: str + model: str + temperature: float + system_prompt: str + skills: List[str] + tools: List[str] + +class ConfigLoader: + """Load and validate configurations.""" + + @staticmethod + def load_agent(path: Path) -> AgentConfig: + """Load agent configuration from YAML.""" + with open(path) as f: + data = yaml.safe_load(f) + + # Validate with Pydantic + config = AgentConfig(**data) + return config + + @staticmethod + def load_all_agents(base_path: Path) -> Dict[str, AgentConfig]: + """Load all agent configurations.""" + agents = {} + specs_dir = base_path / "agents" / "specs" + + for yaml_file in specs_dir.glob("*.yaml"): + config = ConfigLoader.load_agent(yaml_file) + agents[config.name] = config + + return agents +``` + +## Architecture Decision Process + +### Step 1: Understand Requirements + +Questions to ask: +- What problem are we solving? +- Who are the users (framework developers vs end users)? +- What are the constraints (performance, compatibility)? +- What are the failure modes? + +### Step 2: Explore Options + +Consider multiple approaches: +- List 3-5 potential solutions +- Document pros/cons for each +- Consider existing patterns in codebase + +### Step 3: Evaluate Trade-offs + +| Criteria | Option A | Option B | Option C | +| --------------- | --------- | --------- | --------- | +| Complexity | Low | Medium | High | +| Performance | Good | Excellent | Fair | +| Maintainability | Excellent | Good | Fair | +| Extensibility | Fair | Good | Excellent | + +### Step 4: Document Decision (ADR) + +```markdown +# ADR-XXX: [Short Title] + +## Status +Proposed | Accepted | Deprecated | Superseded + +## Context +What is the issue that we're seeing that is motivating this decision? + +## Decision +What is the change that we're proposing and/or doing? + +## Consequences +What becomes easier or more difficult because of this change? + +### Positive +- Pro 1 +- Pro 2 + +### Negative +- Con 1 +- Con 2 + +### Neutral +- Note 1 + +## Alternatives Considered +- Alternative 1: [Brief description and why rejected] +- Alternative 2: [Brief description and why rejected] +``` + +## Key Design Principles + +### 1. Separation of Concerns + +```python +# ❌ Bad: Mixed responsibilities +class Agent: + def execute(self, task: str): + # Load config + config = yaml.load(...) + + # Call LLM + response = openai.create(...) + + # Store result + db.insert(...) + + # Send event + event_bus.publish(...) + +# βœ“ Good: Clear responsibilities +class Agent: + def __init__(self, config: AgentConfig, provider: Provider, storage: Storage): + self.config = config + self.provider = provider + self.storage = storage + + def execute(self, task: str): + response = self.provider.generate(task) + self.storage.save(response) + return response +``` + +### 2. Dependency Injection + +```python +# βœ“ Good: Dependencies injected +class AgentOrchestrator: + def __init__( + self, + event_bus: EventBus, + provider_registry: ProviderRegistry, + storage: Storage + ): + self.event_bus = event_bus + self.provider_registry = provider_registry + self.storage = storage + + def run_agent(self, agent_config: AgentConfig): + provider = self.provider_registry.get(agent_config.provider) + agent = Agent(agent_config, provider, self.storage) + return agent.execute() +``` + +### 3. Interface Segregation + +```python +# Define minimal interfaces +class Executable(Protocol): + """Can be executed.""" + def execute(self) -> Any: ... + +class Configurable(Protocol): + """Can be configured.""" + def configure(self, config: dict) -> None: ... + +class Observable(Protocol): + """Can emit events.""" + def on_event(self, handler: Callable) -> None: ... + +# Implement only what's needed +class SimpleAgent: + """Agent that is executable but not observable.""" + def execute(self) -> str: + return "result" + +class ObservableAgent: + """Agent that is both executable and observable.""" + def execute(self) -> str: + self._notify_listeners("started") + result = "result" + self._notify_listeners("completed") + return result + + def on_event(self, handler: Callable) -> None: + self._listeners.append(handler) +``` + +## Framework Evolution Strategy + +### Phase 0: Core Domain (βœ… Complete) +- Basic project structure +- Configuration system (.parac/) +- Core domain models + +### Phase 1: Core Domain Enhancement (Current) +- Agent inheritance +- Skill system (YAML + Agent Skills format) +- Tool registry +- Workflow engine + +### Phase 2: Multi-Provider Support +- Provider abstraction +- OpenAI, Anthropic, Azure integration +- Streaming support +- Token management + +### Phase 3: Advanced Features +- MCP (Model Context Protocol) integration +- Event-driven architecture +- Advanced orchestration +- Observability (tracing, metrics) + +## Common Architecture Challenges + +### Challenge 1: Circular Dependencies + +**Problem**: Module A depends on B, B depends on C, C depends on A + +**Solution**: +- Use dependency injection +- Create abstraction layer +- Apply dependency inversion principle + +```python +# Instead of direct dependency +from paracle_agents import Agent # Creates circular dep + +# Use protocol/interface +from typing import Protocol + +class IAgent(Protocol): + def execute(self) -> str: ... + +# Inject at runtime +def create_workflow(agent: IAgent): + return Workflow(agent) +``` + +### Challenge 2: Configuration Complexity + +**Problem**: Too many configuration options, unclear defaults + +**Solution**: +- Layer configurations (defaults β†’ user β†’ runtime) +- Validate early with Pydantic +- Document all options + +```python +class AgentConfig(BaseModel): + # Required fields + name: str + provider: str + + # Optional with sensible defaults + model: str = "gpt-4" + temperature: float = Field(default=0.7, ge=0.0, le=2.0) + max_tokens: int = Field(default=2000, gt=0) + + # Computed fields + @property + def full_name(self) -> str: + return f"{self.provider}:{self.name}" +``` + +### Challenge 3: Testing Complexity + +**Problem**: Hard to test components that depend on external services + +**Solution**: +- Use dependency injection +- Create test doubles (mocks, fakes) +- Isolate side effects + +```python +# Production +class OpenAIProvider: + def generate(self, prompt: str) -> str: + return self.client.chat.completions.create(...) + +# Test +class FakeProvider: + """Fake provider for testing.""" + def generate(self, prompt: str) -> str: + return f"Mock response for: {prompt}" + +# Test usage +def test_agent_execution(): + fake_provider = FakeProvider() + agent = Agent(config, provider=fake_provider) + result = agent.execute("test prompt") + assert "Mock response" in result +``` + +## Best Practices Checklist + +When designing new components: + +- [ ] Clear single responsibility +- [ ] Dependencies injected, not created +- [ ] Interfaces over concrete types +- [ ] Fails fast with clear errors +- [ ] Unit testable in isolation +- [ ] Documented with examples +- [ ] Follows existing patterns +- [ ] Backward compatible (if extending) +- [ ] Performance considered +- [ ] Security reviewed + +## Related Skills + +- **code-generation**: For implementing designs +- **code-review**: For validating implementations +- **documentation-writing**: For ADRs and design docs + +## References + +- [Clean Architecture by Robert C. Martin](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html) +- [Domain-Driven Design](https://martinfowler.com/bliki/DomainDrivenDesign.html) +- [ADR (Architecture Decision Records)](https://adr.github.io/) +- [Python Design Patterns](https://refactoring.guru/design-patterns/python) \ No newline at end of file diff --git a/.claude/skills/git-management/SKILL.md b/.claude/skills/git-management/SKILL.md new file mode 100644 index 0000000..936ff0d --- /dev/null +++ b/.claude/skills/git-management/SKILL.md @@ -0,0 +1,669 @@ +--- +name: git-management +description: Expert-level git workflow management, conventional commits, branching strategies, and merge operations. Use for git operations, branch management, and commit standardization. +license: Apache-2.0 +compatibility: Git 2.x+, GitHub, GitLab +metadata: + author: paracle-core-team + version: "1.0.0" + category: version-control + level: advanced + display_name: "Git Management" + tags: + - git + - version-control + - conventional-commits + - branching-strategy + - merge-management + capabilities: + - conventional_commits + - branch_management + - merge_strategies + - conflict_resolution + - git_hooks +allowed-tools: Read Write Bash(git:*) +--- + +# Git Management Skill + +## When to use this skill + +Use this skill when: + +- Managing git branches and merges +- Enforcing conventional commit standards +- Coordinating feature/bugfix/hotfix workflows +- Resolving merge conflicts +- Setting up git hooks for automation +- Managing git tags and references +- Creating and reviewing pull requests + +## Git Workflow for Paracle + +### Branch Strategy + +Paracle uses a **modified Gitflow** with two main branches: + +``` +main ← Production releases (v0.1.0, v0.2.0) + ↓ +develop ← Integration branch (default) + ↓ +β”œβ”€β”€ feature/* ← New features +β”œβ”€β”€ bugfix/* ← Bug fixes +β”œβ”€β”€ hotfix/* ← Urgent production fixes +└── release/* ← Release preparation +``` + +**Branch Lifecycle**: + +```bash +# Feature branch +develop β†’ feature/add-webhook-support β†’ develop + +# Bugfix branch +develop β†’ bugfix/fix-agent-inheritance β†’ develop + +# Release branch +develop β†’ release/v0.2.0 β†’ main + develop + +# Hotfix branch +main β†’ hotfix/v0.1.1-critical-fix β†’ main + develop +``` + +### Conventional Commits + +**Format**: `(): ` + +**Types**: + +- `feat`: New feature +- `fix`: Bug fix +- `docs`: Documentation only +- `style`: Formatting, missing semicolons +- `refactor`: Code restructuring +- `perf`: Performance improvement +- `test`: Adding/updating tests +- `chore`: Tooling, dependencies +- `ci`: CI/CD changes + +- `build`: Build system changes + +**Scopes** (Paracle-specific): + +- `core`: paracle_core package +- `domain`: paracle_domain package +- `api`: paracle_api package +- `cli`: paracle_cli package +- `orchestration`: paracle_orchestration +- `providers`: paracle_providers +- `adapters`: paracle_adapters +- `tools`: paracle_tools +- `sandbox`: paracle_sandbox +- `review`: paracle_review +- `rollback`: paracle_rollback +- `store`: paracle_store + +- `events`: paracle_events +- `isolation`: paracle_isolation + +**Examples**: + +```bash +# Good commits +feat(api): add workflow execution endpoints +fix(orchestration): resolve agent inheritance bug +docs(readme): update installation instructions +refactor(domain): simplify agent factory logic +perf(store): optimize repository queries with indexes +test(cli): add integration tests for workflow commands +chore(deps): bump pydantic to v2.10.0 +ci(github): add automated release workflow + +# Bad commits (avoid) +update stuff +fixed bug + +WIP +asdfasdf +``` + +**Breaking Changes**: + +```bash +feat(api)!: change workflow response structure + +BREAKING CHANGE: WorkflowResponse now returns `result` instead of `output` +Migrate by updating response handling to use `.result` attribute. +``` + +### Git Operations + +#### Creating a Feature Branch + +```bash +# Always branch from develop +git checkout develop +git pull origin develop + +# Create feature branch +git checkout -b feature/webhook-integration + +# Work on feature... +git add packages/paracle_events/webhooks.py +git commit -m "feat(events): implement webhook delivery system" + +# Keep feature updated with develop +git fetch origin +git rebase origin/develop + +# Push and create PR +git push origin feature/webhook-integration +``` + +#### Creating a Release Branch + +```bash +# Branch from develop +git checkout develop +git pull origin develop +git checkout -b release/v0.2.0 + +# Bump version +python scripts/bump_version.py minor # 0.1.0 β†’ 0.2.0 + +# Generate changelog +python scripts/generate_changelog.py + +# Commit release prep +git add pyproject.toml CHANGELOG.md +git commit -m "chore(release): prepare v0.2.0 release" + +# Push release branch +git push origin release/v0.2.0 +``` + +#### Creating a Hotfix Branch + +```bash +# Branch from main (production) +git checkout main +git pull origin main +git checkout -b hotfix/v0.1.1-security-fix + +# Fix the issue +git add packages/paracle_api/auth.py +git commit -m "fix(api)!: patch authentication bypass vulnerability + +BREAKING CHANGE: API key validation now requires bearer token format" + +# Bump patch version +python scripts/bump_version.py patch # 0.1.0 β†’ 0.1.1 + +# Merge to main +git checkout main +git merge --no-ff hotfix/v0.1.1-security-fix +git tag -a v0.1.1 -m "Release v0.1.1 - Security Fix" +git push origin main --tags + +# Backport to develop +git checkout develop +git merge --no-ff hotfix/v0.1.1-security-fix + +git push origin develop +``` + +#### Merge Strategies + +**Feature β†’ Develop** (Squash merge): + +```bash +# Squash commits for cleaner history +git checkout develop +git merge --squash feature/webhook-integration +git commit -m "feat(events): add webhook integration system + +- Implement webhook delivery +- Add retry logic with exponential backoff + +- Support custom headers and authentication +- Add webhook logging and monitoring + +Closes #123" +``` + +**Release β†’ Main** (No-fast-forward): + +```bash + +# Preserve release history +git checkout main +git merge --no-ff release/v0.2.0 +git tag -a v0.2.0 -m "Release v0.2.0" +git push origin main --tags +``` + +**Develop β†’ Release** (Fast-forward): + +```bash +# Keep linear history for releases +git checkout release/v0.2.0 +git merge --ff develop +``` + +### Git Hooks + +#### Pre-Commit Hook + +```bash +#!/bin/bash +# .git/hooks/pre-commit + +# Run linting +make lint || { + echo "❌ Linting failed. Fix issues and try again." + exit 1 +} + +# Run type checking +make typecheck || { + echo "❌ Type checking failed. Fix issues and try again." + exit 1 +} + +# Run tests +make test || { + echo "❌ Tests failed. Fix issues and try again." + exit 1 +} + +echo "βœ… Pre-commit checks passed!" +``` + +#### Commit-Msg Hook + +```bash +#!/bin/bash +# .git/hooks/commit-msg + +# Validate conventional commit format +commit_msg=$(cat "$1") + +# Pattern: type(scope): description +pattern="^(feat|fix|docs|style|refactor|perf|test|chore|ci|build)(\(.+\))?: .{1,100}$" + +if ! echo "$commit_msg" | grep -qE "$pattern"; then + echo "❌ Invalid commit message format!" + echo "" + echo "Expected: (): " + echo "" + echo "Types: feat, fix, docs, style, refactor, perf, test, chore, ci, build" + echo "Example: feat(api): add webhook endpoints" + exit 1 +fi + +echo "βœ… Commit message format valid!" +``` + +#### Pre-Push Hook + +```bash +#!/bin/bash +# .git/hooks/pre-push + +# Get current branch +branch=$(git rev-parse --abbrev-ref HEAD) + +# Protected branches +protected_branches="main|master" + +if echo "$branch" | grep -qE "$protected_branches"; then + echo "❌ Direct push to $branch is not allowed!" + echo "Create a pull request instead." + exit 1 +fi + + +echo "βœ… Push allowed!" +``` + +### Conflict Resolution + +#### Common Conflicts in Paracle + +**1. pyproject.toml (version conflicts)**: + +```toml +<<<<<<< HEAD + +version = "0.1.0" +======= +version = "0.2.0" +>>>>>>> feature/new-feature + +# Resolution: Keep higher version or semantic version +version = "0.2.0" +``` + +**2. CHANGELOG.md (merge conflicts)**: + +```markdown +<<<<<<< HEAD +## [0.1.0] - 2026-01-05 +### Added +- Feature A +======= +## [0.2.0] - 2026-01-06 +### Added +- Feature B +>>>>>>> feature/new-feature + + +# Resolution: Merge both entries chronologically +## [0.2.0] - 2026-01-06 +### Added +- Feature B + +## [0.1.0] - 2026-01-05 +### Added +- Feature A +``` + +**3. Manifest files (.parac/agents/manifest.yaml)**: + +```yaml +<<<<<<< HEAD +agents: + - id: coder + - id: tester +======= +agents: + - id: coder + - id: reviewer +>>>>>>> feature/add-reviewer + +# Resolution: Merge both additions +agents: + - id: coder + - id: reviewer + - id: tester +``` + +#### Conflict Resolution Workflow + +```bash +# Start merge/rebase and encounter conflicts +git rebase develop +# CONFLICT (content): Merge conflict in pyproject.toml + +# Check conflicted files +git status + +# Edit files to resolve conflicts +# Remove markers: <<<<<<<, =======, >>>>>>> + +# Mark as resolved +git add pyproject.toml + +# Continue rebase +git rebase --continue + +# Or abort if needed +git rebase --abort +``` + +### Git Best Practices for Paracle + +#### Commit Guidelines + +**DO**: +βœ… Write clear, descriptive commi**message** +βœ… Use conventional commit format +βœ… Keep commits atomic (one logical change) +βœ… Reference issue numbers (`Closes #123`) +βœ… Include breaking change notes when applicable +βœ… Test before committing + +**DON'T**: +❌ Commit broken code +❌ Use vague messages ("fix bug", "update") +❌ Mix unrelated changes in one commit +❌ Commit secrets or API keys +❌ Commit generated files (.pyc, **pycache**) +❌ Force push to shared branches + +#### Branch Guidelines + +**DO**: +βœ… Use descriptive branch names +βœ… Keep branches short-lived (< 1 week) +βœ… Rebase regularly to stay updated +βœ… Delete merged branches +βœ… Protect main and develop branches + +**DON'T**: +❌ Create long-lived feature branches +❌ Push directly to main/develop +❌ Leave stale branches +❌ Use generic names ("fix", "test") + +#### PR Guidelines + +**DO**: +βœ… Provide clear PR descriptions +βœ… Link related issues +βœ… Add screenshots for UI changes +βœ… Request specific reviewers +βœ… Address review comments +βœ… Ensure CI passes + +**DON'T**: +❌ Create massive PRs (>500 lines) +❌ Ignore review feedback +❌ Merge with failing tests +❌ Skip PR template sections + +### Git Maintenance + +#### Clean Up Local Branches + +```bash +# List merged branches +git branch --merged develop + +# Delete merged branches +git branch -d feature/old-feature + +# Prune remote references +git remote prune origin + +# Clean up stale branches +git fetch --prune +``` + +#### Rewrite History (Use with Caution) + +```bash +# Interactive rebase (last 3 commits) +git rebase -i HEAD~3 + +# Squash commits +# Change 'pick' to 'squash' for commits to combine + +# Amend last commit +git commit --amend -m "new message" + +# ⚠️ NEVER rewrite history on shared branches! +``` + +#### Recover from Mistakes + +```bash +# Undo last commit (keep changes) +git reset --soft HEAD~1 + +# Undo last commit (discard changes) +git reset --hard HEAD~1 + +# Recover deleted commits +git reflog +git checkout + +# Restore deleted files +git restore +``` + +## Examples + +### Example 1: Feature Development Workflow + +```bash +# Start feature +git checkout develop +git pull origin develop +git checkout -b feature/add-mcp-protocol + +# Implement feature +git add packages/paracle_providers/mcp.py +git commit -m "feat(providers): add MCP protocol support" + +git add tests/unit/providers/test_mcp.py +git commit -m "test(providers): add MCP provider tests" + +git add docs/mcp-integration.md +git commit -m "docs: add MCP integration guide" + +# Update with develop +git fetch origin +git rebase origin/develop + +# Push and create PR +git push origin feature/add-mcp-protocol + +# After PR approval and merge, clean up +git checkout develop +git pull origin develop +git branch -d feature/add-mcp-protocol +``` + +### Example 2: Release Workflow + +```bash +# Create release branch +git checkout develop +git pull origin develop +git checkout -b release/v0.3.0 + +# Prepare release +python scripts/bump_version.py minor +python scripts/generate_changelog.py + +# Commit changes +git add pyproject.toml CHANGELOG.md +git commit -m "chore(release): bump version to v0.3.0" + +# Push release branch +git push origin release/v0.3.0 + +# Create release PR to main +# After approval: + +# Merge to main +git checkout main +git pull origin main +git merge --no-ff release/v0.3.0 +git tag -a v0.3.0 -m "Release v0.3.0" +git push origin main --tags + +# Backport to develop +git checkout develop +git merge --no-ff release/v0.3.0 +git push origin develop + +# Delete release branch +git branch -d release/v0.3.0 +git push origin --delete release/v0.3.0 +``` + +### Example 3: Hotfix Workflow + +```bash +# Create hotfix from main +git checkout main +git pull origin main +git checkout -b hotfix/v0.2.1-memory-leak + +# Fix issue +git add packages/paracle_orchestration/engine.py +git commit -m "fix(orchestration): resolve memory leak in agent cleanup" + +# Bump version +python scripts/bump_version.py patch +git add pyproject.toml +git commit -m "chore: bump version to v0.2.1" + +# Merge to main +git checkout main +git merge --no-ff hotfix/v0.2.1-memory-leak +git tag -a v0.2.1 -m "Release v0.2.1 - Hotfix" +git push origin main --tags + +# Backport to develop +git checkout develop +git merge --no-ff hotfix/v0.2.1-memory-leak +git push origin develop + +# Clean up +git branch -d hotfix/v0.2.1-memory-leak +``` + +## Common Patterns + +### Pattern 1: Keeping Feature Branch Updated + +```bash +# Rebase strategy (recommended) +git checkout feature/my-feature +git fetch origin +git rebase origin/develop + +# Or merge strategy (if conflicts expected) +git merge origin/develop +``` + +### Pattern 2: Interactive Commit Cleanup + +```bash +# Before pushing, clean up commit history +git rebase -i HEAD~5 + +# Options: +# pick = use commit +# reword = edit message +# squash = combine with previous +# fixup = squash without message +# drop = remove commit +``` + +### Pattern 3: Cherry-Pick Specific Commits + +```bash +# Pick commit from another branch +git cherry-pick + +# Cherry-pick range +git cherry-pick commit1^..commit2 +``` + +## Related Skills + +- [CI/CD & DevOps](../cicd-devops/SKILL.md) - Automated workflows +- [Release Automation](../release-automation/SKILL.md) - Version management +- [Paracle Development](../paracle-development/SKILL.md) - Framework development + +## References + +- [Paracle Git Workflow Policy](../../../policies/GIT_WORKFLOW.md) +- [Conventional Commits](https://www.conventionalcommits.org/) +- [Gitflow Workflow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow) +- [Semantic Versioning](https://semver.org/) \ No newline at end of file diff --git a/.claude/skills/migration-upgrading/SKILL.md b/.claude/skills/migration-upgrading/SKILL.md new file mode 100644 index 0000000..e7671e5 --- /dev/null +++ b/.claude/skills/migration-upgrading/SKILL.md @@ -0,0 +1,341 @@ +--- +name: migration-upgrading +description: Handle version migrations, database schema changes, and breaking changes. Use when upgrading framework versions or migrating data. +license: Apache-2.0 +compatibility: Python 3.10+, Alembic, SQLAlchemy +metadata: + author: paracle-core-team + version: "1.0.0" + category: automation + level: advanced + display_name: "Migration & Upgrading" + tags: + - migration + - upgrade + - versioning + - database + capabilities: + - version_migration + - schema_migration + - data_migration + - breaking_changes +allowed-tools: Read Write Bash(python:*) +--- + +# Migration & Upgrading Skill + +## When to use this skill + +Use when: +- Upgrading Paracle framework versions +- Migrating database schema +- Handling breaking changes +- Converting old configurations +- Migrating agent specifications + +## Version Migration Strategy + +```markdown +# Migration Path + +v0.1.x β†’ v0.2.x β†’ v0.3.x β†’ v1.0.x + ↓ ↓ ↓ ↓ + βœ“ βœ“ βœ— βœ— (must go through intermediate versions) +``` + +## Database Migrations (Alembic) + +```python +# Create migration +# alembic revision --autogenerate -m "add_workflow_table" + +"""add workflow table + +Revision ID: abc123 +Revises: def456 +Create Date: 2024-01-15 10:00:00 +""" +from alembic import op +import sqlalchemy as sa + +def upgrade(): + # Create table + op.create_table( + 'workflows', + sa.Column('id', sa.String(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + + # Add column to existing table + op.add_column('agents', sa.Column('workflow_id', sa.String(), nullable=True)) + + # Add index + op.create_index('ix_agents_workflow_id', 'agents', ['workflow_id']) + + # Add foreign key + op.create_foreign_key( + 'fk_agents_workflow_id', + 'agents', 'workflows', + ['workflow_id'], ['id'], + ) + +def downgrade(): + # Drop foreign key + op.drop_constraint('fk_agents_workflow_id', 'agents', type_='foreignkey') + + # Drop index + op.drop_index('ix_agents_workflow_id', 'agents') + + # Drop column + op.drop_column('agents', 'workflow_id') + + # Drop table + op.drop_table('workflows') +``` + +## Data Migration + +```python +# packages/paracle_cli/commands/migrate.py +import click +from sqlalchemy import select + +@click.command() +@click.option('--from-version', required=True) +@click.option('--to-version', required=True) +async def migrate_data(from_version: str, to_version: str): + """Migrate data between versions.""" + + if from_version == "0.1.0" and to_version == "0.2.0": + await migrate_0_1_to_0_2() + elif from_version == "0.2.0" and to_version == "0.3.0": + await migrate_0_2_to_0_3() + else: + click.echo(f"No migration path from {from_version} to {to_version}") + return + + click.echo(f"βœ… Migration complete: {from_version} β†’ {to_version}") + +async def migrate_0_1_to_0_2(): + """Migrate from v0.1.0 to v0.2.0.""" + + # Convert old agent format + agents = await session.execute(select(Agent)) + for agent in agents: + # Old format: tools as comma-separated string + # New format: tools as JSON array + if isinstance(agent.tools, str): + agent.tools = agent.tools.split(',') + session.add(agent) + + await session.commit() +``` + +## Configuration Migration + +```python +# Migrate .parac/ files +from pathlib import Path +import yaml + +def migrate_parac_config(parac_dir: Path, from_version: str, to_version: str): + """Migrate .parac configuration.""" + + # Migrate agent specs + specs_dir = parac_dir / "agents" / "specs" + for spec_file in specs_dir.glob("*.yaml"): + spec = yaml.safe_load(spec_file.read_text()) + + # v0.1 β†’ v0.2: Rename 'prompt' to 'system_prompt' + if 'prompt' in spec: + spec['system_prompt'] = spec.pop('prompt') + + # v0.2 β†’ v0.3: Add required 'metadata' field + if 'metadata' not in spec: + spec['metadata'] = { + 'version': '1.0.0', + 'author': 'user', + } + + spec_file.write_text(yaml.dump(spec)) + + # Update version + version_file = parac_dir / "VERSION" + version_file.write_text(to_version) +``` + +## Breaking Changes Handling + +```python +# Deprecation warnings +import warnings + +def old_function(): + warnings.warn( + "old_function() is deprecated, use new_function() instead", + DeprecationWarning, + stacklevel=2, + ) + return new_function() + +# Compatibility layer +class AgentV1: + """Old agent interface (deprecated).""" + + def __init__(self, *args, **kwargs): + warnings.warn( + "AgentV1 is deprecated, use Agent instead", + DeprecationWarning, + ) + self._agent = Agent(*args, **kwargs) + + def __getattr__(self, name): + # Delegate to new implementation + return getattr(self._agent, name) +``` + +## Version Compatibility Check + +```python +from packaging import version + +CURRENT_VERSION = "0.3.0" +MIN_SUPPORTED_VERSION = "0.2.0" + +def check_compatibility(parac_dir: Path) -> bool: + """Check if .parac is compatible.""" + version_file = parac_dir / "VERSION" + + if not version_file.exists(): + # Pre-versioning + return False + + parac_version = version_file.read_text().strip() + + if version.parse(parac_version) < version.parse(MIN_SUPPORTED_VERSION): + raise ValueError( + f"Unsupported .parac version: {parac_version}\\n" + f"Minimum supported: {MIN_SUPPORTED_VERSION}\\n" + f"Please migrate your .parac using: paracle migrate" + ) + + return True +``` + +## CLI Migration Command + +```bash +# Check current version +paracle version + +# Check migration path +paracle migrate --check + +# Perform migration +paracle migrate --from 0.2.0 --to 0.3.0 + +# Dry run (preview changes) +paracle migrate --from 0.2.0 --to 0.3.0 --dry-run + +# Backup before migration +paracle migrate --from 0.2.0 --to 0.3.0 --backup +``` + +## Migration Testing + +```python +def test_migration_0_1_to_0_2(): + """Test data migration.""" + # Setup old format + agent = Agent( + name="test", + tools="file-read,file-write", # Old format + ) + session.add(agent) + session.commit() + + # Run migration + migrate_0_1_to_0_2() + + # Verify new format + session.refresh(agent) + assert isinstance(agent.tools, list) + assert agent.tools == ["file-read", "file-write"] + +def test_config_migration(): + """Test config file migration.""" + # Create old spec + old_spec = { + 'name': 'test-agent', + 'prompt': 'You are helpful', # Old field + } + + # Migrate + new_spec = migrate_spec_v1_to_v2(old_spec) + + # Verify + assert 'system_prompt' in new_spec + assert 'prompt' not in new_spec + assert new_spec['system_prompt'] == 'You are helpful' +``` + +## CHANGELOG.md + +```markdown +# Changelog + +## [0.3.0] - 2024-01-15 + +### Added +- Workflow orchestration engine +- DAG execution support + +### Changed +- **BREAKING**: Agent specs now require `metadata` field +- **BREAKING**: Tools field changed from string to array +- Improved error messages + +### Deprecated +- `AgentV1` class (use `Agent` instead) +- `old_function()` (use `new_function()` instead) + +### Removed +- Support for Python 3.9 +- Legacy `prompt` field (use `system_prompt`) + +### Migration Guide +```bash +paracle migrate --from 0.2.0 --to 0.3.0 +``` +``` + +## Best Practices + +1. **Version everything** - Track .parac, database, code +2. **Test migrations** - On copy of production data +3. **Backup before migrating** - Always have rollback plan +4. **Deprecate before removing** - Give users time to adapt +5. **Document breaking changes** - Clear migration guides +6. **Provide CLI tools** - Automate migration process + +## Migration Checklist + +- [ ] Database schema updated (Alembic) +- [ ] Data migrated to new format +- [ ] Config files converted +- [ ] Tests updated for new version +- [ ] Documentation updated +- [ ] CHANGELOG.md updated +- [ ] Migration guide written +- [ ] CLI migration command tested +- [ ] Backward compatibility layer added (if possible) +- [ ] Users notified of breaking changes + +## Resources + +- Alembic: https://alembic.sqlalchemy.org/ +- Semantic Versioning: https://semver.org/ +- Migration Scripts: `packages/paracle_cli/commands/migrate.py` +- CHANGELOG: `CHANGELOG.md` \ No newline at end of file diff --git a/.claude/skills/migration-upgrading/assets/migration-template.py b/.claude/skills/migration-upgrading/assets/migration-template.py new file mode 100644 index 0000000..23edc50 --- /dev/null +++ b/.claude/skills/migration-upgrading/assets/migration-template.py @@ -0,0 +1,62 @@ +# Migration Script Template +# Copy and modify this template for your migration + +"""Migration from v[OLD] to v[NEW] + +Revision ID: [UNIQUE_ID] +Revises: [PREVIOUS_REVISION] +Create Date: [DATE] + +Description: +- [Change 1] +- [Change 2] +""" + +import sqlalchemy as sa +from alembic import op + +# Revision identifiers +revision = '[UNIQUE_ID]' +down_revision = '[PREVIOUS_REVISION]' +branch_labels = None +depends_on = None + + +def upgrade(): + """Upgrade to v[NEW].""" + + # Example: Add new table + op.create_table( + 'new_table', + sa.Column('id', sa.String(), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + ) + + # Example: Add column to existing table + op.add_column('existing_table', sa.Column( + 'new_column', sa.String(), nullable=True)) + + # Example: Create index + op.create_index('ix_new_table_name', 'new_table', ['name']) + + # Example: Data migration + connection = op.get_bind() + connection.execute( + sa.text( + "UPDATE existing_table SET new_column = 'default' WHERE new_column IS NULL") + ) + + # Example: Make column non-nullable after data migration + op.alter_column('existing_table', 'new_column', nullable=False) + + +def downgrade(): + """Downgrade to v[OLD].""" + + # Reverse all changes in opposite order + op.alter_column('existing_table', 'new_column', nullable=True) + op.drop_index('ix_new_table_name', 'new_table') + op.drop_column('existing_table', 'new_column') + op.drop_table('new_table') diff --git a/.claude/skills/migration-upgrading/scripts/migrate_agent_specs.py b/.claude/skills/migration-upgrading/scripts/migrate_agent_specs.py new file mode 100644 index 0000000..870749a --- /dev/null +++ b/.claude/skills/migration-upgrading/scripts/migrate_agent_specs.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Migrate agent specs between versions. + +Usage: + python migrate_agent_specs.py --from 0.1.0 --to 0.2.0 .parac/agents/specs/ +""" + +import argparse +from pathlib import Path +from typing import Any + +import yaml + + +def migrate_0_1_to_0_2(spec: dict[str, Any]) -> dict[str, Any]: + """Migrate from v0.1.0 to v0.2.0.""" + + # Rename 'prompt' to 'system_prompt' + if 'prompt' in spec: + spec['system_prompt'] = spec.pop('prompt') + + # Convert tools from string to list + if 'tools' in spec and isinstance(spec['tools'], str): + spec['tools'] = [t.strip() for t in spec['tools'].split(',')] + + return spec + + +def migrate_0_2_to_0_3(spec: dict[str, Any]) -> dict[str, Any]: + """Migrate from v0.2.0 to v0.3.0.""" + + # Add required metadata field + if 'metadata' not in spec: + spec['metadata'] = { + 'version': '1.0.0', + 'author': 'user', + } + + return spec + + +MIGRATIONS = { + ('0.1.0', '0.2.0'): migrate_0_1_to_0_2, + ('0.2.0', '0.3.0'): migrate_0_2_to_0_3, +} + + +def migrate_spec_file(file_path: Path, from_version: str, to_version: str): + """Migrate a single spec file.""" + + migration_key = (from_version, to_version) + if migration_key not in MIGRATIONS: + print( + f"⚠️ No migration available from {from_version} to {to_version}") + return False + + print(f"πŸ“ Migrating {file_path.name}") + + # Load spec + with open(file_path) as f: + spec = yaml.safe_load(f) + + # Apply migration + migrator = MIGRATIONS[migration_key] + spec = migrator(spec) + + # Save migrated spec + with open(file_path, 'w') as f: + yaml.dump(spec, f, default_flow_style=False, sort_keys=False) + + print(f" βœ“ Migrated to v{to_version}") + return True + + +def main(): + parser = argparse.ArgumentParser( + description="Migrate agent specifications") + parser.add_argument("--from", dest="from_version", + required=True, help="Source version") + parser.add_argument("--to", dest="to_version", + required=True, help="Target version") + parser.add_argument("path", help="Path to specs directory") + + args = parser.parse_args() + + specs_dir = Path(args.path) + if not specs_dir.is_dir(): + print(f"❌ Directory not found: {specs_dir}") + return 1 + + print( + f"\nπŸ”„ Migrating specs from v{args.from_version} to v{args.to_version}\n") + + # Migrate all YAML files + migrated = 0 + for spec_file in specs_dir.glob("*.yaml"): + if migrate_spec_file(spec_file, args.from_version, args.to_version): + migrated += 1 + + print(f"\nβœ… Migrated {migrated} spec file(s)") + return 0 + + +if __name__ == "__main__": + exit(main()) diff --git a/.claude/skills/paracle-development/SKILL.md b/.claude/skills/paracle-development/SKILL.md new file mode 100644 index 0000000..af06c67 --- /dev/null +++ b/.claude/skills/paracle-development/SKILL.md @@ -0,0 +1,644 @@ +--- +name: paracle-development +description: Develop, test, and maintain the Paracle framework codebase. Use when implementing features, fixing bugs, writing tests, or refactoring framework code. +license: Apache-2.0 +compatibility: Python 3.10+, pytest, black, mypy, uv package manager +metadata: + author: paracle-core-team + version: "1.0.0" + category: creation + level: advanced + display_name: "Paracle Framework Development" + tags: + - development + - framework + - python + - testing + - paracle + capabilities: + - framework_development + - test_writing + - code_refactoring + - bug_fixing + - feature_implementation +allowed-tools: Read Write Bash(python:*) Bash(pytest:*) Bash(git:*) +--- + +# Paracle Framework Development Skill + +## When to use this skill + +Use this skill when: +- Implementing new features in Paracle framework +- Writing or updating tests +- Fixing bugs in framework code +- Refactoring existing code +- Adding new providers or adapters +- Updating documentation +- Managing dependencies + +## Paracle Project Structure + +``` +paracle-lite/ +β”œβ”€β”€ .parac/ # Framework development config +β”‚ β”œβ”€β”€ project.yaml +β”‚ β”œβ”€β”€ agents/specs/ +β”‚ └── workflows/ +β”œβ”€β”€ packages/ # Framework packages +β”‚ β”œβ”€β”€ paracle_core/ # Core utilities +β”‚ β”œβ”€β”€ paracle_domain/ # Domain models +β”‚ β”œβ”€β”€ paracle_api/ # FastAPI application +β”‚ β”œβ”€β”€ paracle_cli/ # CLI interface +β”‚ β”œβ”€β”€ paracle_store/ # Persistence layer +β”‚ β”œβ”€β”€ paracle_events/ # Event system +β”‚ β”œβ”€β”€ paracle_orchestration/# Orchestrator +β”‚ β”œβ”€β”€ paracle_providers/ # LLM providers +β”‚ β”œβ”€β”€ paracle_adapters/ # External adapters +β”‚ └── paracle_tools/ # Built-in tools +β”œβ”€β”€ tests/ # Test suite +β”‚ β”œβ”€β”€ unit/ +β”‚ β”œβ”€β”€ integration/ +β”‚ └── conftest.py +β”œβ”€β”€ docs/ # Documentation +β”œβ”€β”€ examples/ # Usage examples +β”œβ”€β”€ templates/ # User templates +β”‚ └── .parac-template/ +β”œβ”€β”€ pyproject.toml # Project config +β”œβ”€β”€ Makefile # Common tasks +└── README.md + +``` + +## Development Workflow + +### Step 1: Set up environment + +```bash +# Install dependencies +uv sync + +# Activate virtual environment (if needed) +source .venv/bin/activate # Linux/Mac +.venv\Scripts\activate # Windows + +# Verify installation +python -c "import paracle_core; print('OK')" +``` + +### Step 2: Create a branch + +```bash +# For features +git checkout -b feature/agent-skills-system + +# For bugs +git checkout -b fix/config-validation-error + +# For documentation +git checkout -b docs/update-readme +``` + +### Step 3: Implement changes + +Follow TDD (Test-Driven Development): + +```python +# 1. Write test first (tests/unit/test_skills.py) +import pytest +from paracle_domain.models import SkillSpec, SkillCategory, SkillLevel + +def test_skill_creation(): + """Test creating a skill specification.""" + skill = SkillSpec( + name="test-skill", + display_name="Test Skill", + category=SkillCategory.COMMUNICATION, + description="A test skill", + level=SkillLevel.BASIC + ) + + assert skill.name == "test-skill" + assert skill.category == SkillCategory.COMMUNICATION + assert skill.enabled is True + +def test_skill_validation(): + """Test skill name validation.""" + with pytest.raises(ValueError): + SkillSpec( + name="Invalid Name", # Should fail: uppercase and space + display_name="Invalid", + category=SkillCategory.COMMUNICATION, + description="Invalid" + ) + +# 2. Run test (should fail) +pytest tests/unit/test_skills.py -v + +# 3. Implement feature (packages/paracle_domain/models.py) +from pydantic import BaseModel, Field, field_validator + +class SkillSpec(BaseModel): + name: str + display_name: str + category: SkillCategory + description: str + level: SkillLevel = SkillLevel.BASIC + + @field_validator('name') + @classmethod + def validate_name(cls, v: str) -> str: + """Validate skill name format.""" + if not v.islower(): + raise ValueError("Skill name must be lowercase") + if ' ' in v: + raise ValueError("Skill name cannot contain spaces") + if not all(c.isalnum() or c == '-' for c in v): + raise ValueError("Skill name must be alphanumeric with hyphens") + return v + +# 4. Run test (should pass) +pytest tests/unit/test_skills.py -v +``` + +### Step 4: Format and lint + +```bash +# Format code with black +make format + +# Sort imports +make format # includes isort + +# Type check +make typecheck + +# Lint +make lint + +# Run all checks +make check +``` + +### Step 5: Run tests + +```bash +# Run all tests +make test + +# Run specific test file +pytest tests/unit/test_skills.py -v + +# Run with coverage +make coverage + +# Run only unit tests +pytest tests/unit/ -v + +# Run only integration tests +pytest tests/integration/ -v +``` + +### Step 6: Commit changes + +```bash +# Add files +git add packages/paracle_domain/models.py +git add tests/unit/test_skills.py + +# Commit with conventional commit message +git commit -m "feat(domain): add skill specification model + +- Add SkillSpec model with validation +- Support YAML and Agent Skills formats +- Add tests for skill creation and validation + +Refs: #42" +``` + +## Conventional Commits + +Use structured commit messages: + +``` +(): + + + +