From b4f75938018a85f3714ec5548a5d6d843d9a461d Mon Sep 17 00:00:00 2001 From: wehub-resource-sync Date: Mon, 13 Jul 2026 12:46:57 +0800 Subject: [PATCH] chore: import upstream snapshot with attribution --- .claude/commands/execute-prp.md | 40 + .claude/commands/generate-prp.md | 69 + .gitattributes | 2 + .gitignore | 5 + CLAUDE.md | 59 + INITIAL.md | 15 + INITIAL_EXAMPLE.md | 26 + LICENSE | 21 + PRPs/EXAMPLE_multi_agent_prp.md | 395 + PRPs/templates/prp_base.md | 212 + README.md | 296 + README.wehub.md | 7 + .../.claude/agents/documentation-manager.md | 72 + .../.claude/agents/validation-gates.md | 133 + .../.claude/commands/execute-parallel.md | 27 + .../.claude/commands/execute-prp.md | 40 + .../.claude/commands/fix-github-issue.md | 14 + .../.claude/commands/generate-prp.md | 69 + .../.claude/commands/prep-parallel.md | 14 + .../.claude/commands/primer.md | 16 + .../.claude/hooks/README.md | 109 + .../.claude/hooks/example-hook-config.json | 50 + .../.claude/hooks/log-tool-usage.sh | 14 + .../.devcontainer/Dockerfile | 78 + .../.devcontainer/devcontainer.json | 52 + .../.devcontainer/init-firewall.sh | 118 + claude-code-full-guide/CLAUDE.md | 759 ++ claude-code-full-guide/INITIAL.md | 15 + .../PRPs/EXAMPLE_multi_agent_prp.md | 395 + .../PRPs/templates/prp_base.md | 212 + claude-code-full-guide/README.md | 573 ++ .../install_claude_code_windows.md | 33 + examples/.gitkeep | 0 .../agents/pydantic-ai-dependency-manager.md | 560 ++ .../.claude/agents/pydantic-ai-planner.md | 187 + .../agents/pydantic-ai-prompt-engineer.md | 295 + .../agents/pydantic-ai-tool-integrator.md | 346 + .../.claude/agents/pydantic-ai-validator.md | 312 + .../agent-factory-with-subagents/.gitignore | 11 + .../agent-factory-with-subagents/CLAUDE.md | 717 ++ .../PRPs/INITIAL.md | 47 + .../PRPs/templates/prp_pydantic_ai_base.md | 411 + .../agent-factory-with-subagents/README.md | 226 + .../SAMPLE_PROMPT.md | 1 + .../agents/rag_agent/.env.example | 20 + .../agents/rag_agent/README.md | 141 + .../agents/rag_agent/__init__.py | 17 + .../agents/rag_agent/agent.py | 21 + .../agents/rag_agent/cli.py | 293 + .../agents/rag_agent/dependencies.py | 71 + .../documents/doc10_apple_ai_struggles.md | 156 + .../doc11_investment_funding_trends.md | 306 + .../documents/doc12_executive_moves.md | 208 + .../documents/doc13_regulatory_landscape.md | 255 + .../documents/doc14_patent_innovation.md | 379 + .../documents/doc15_competitive_analysis.md | 253 + .../documents/doc16_startup_ecosystem.md | 219 + .../rag_agent/documents/doc17_cloud_wars.md | 284 + .../documents/doc18_future_predictions.md | 339 + .../documents/doc19_acquisition_targets.md | 297 + .../documents/doc1_openai_funding.md | 43 + .../doc20_international_competition.md | 427 + .../documents/doc21_enterprise_adoption.md | 290 + .../documents/doc2_anthropic_amazon.md | 50 + .../documents/doc3_meta_scale_acquisition.md | 73 + .../documents/doc4_databricks_funding.md | 83 + .../doc5_microsoft_openai_tensions.md | 83 + .../documents/doc6_google_ai_strategy.md | 131 + .../documents/doc7_sam_altman_profile.md | 134 + .../documents/doc8_nvidia_dominance.md | 169 + .../documents/doc9_ai_market_analysis.md | 218 + .../agents/rag_agent/ingestion/__init__.py | 3 + .../agents/rag_agent/ingestion/chunker.py | 518 ++ .../agents/rag_agent/ingestion/embedder.py | 418 + .../agents/rag_agent/ingestion/ingest.py | 434 + .../agents/rag_agent/planning/INITIAL.md | 147 + .../agents/rag_agent/planning/dependencies.md | 351 + .../agents/rag_agent/planning/prompts.md | 164 + .../agents/rag_agent/planning/tools.md | 196 + .../agents/rag_agent/prompts.py | 66 + .../agents/rag_agent/providers.py | 81 + .../agents/rag_agent/requirements.txt | Bin 0 -> 54894 bytes .../agents/rag_agent/settings.py | 98 + .../agents/rag_agent/sql/schema.sql | 170 + .../rag_agent/tests/VALIDATION_REPORT.md | 492 ++ .../agents/rag_agent/tests/conftest.py | 274 + .../agents/rag_agent/tests/test_agent.py | 335 + .../agents/rag_agent/tests/test_cli.py | 665 ++ .../rag_agent/tests/test_dependencies.py | 570 ++ .../rag_agent/tests/test_integration.py | 734 ++ .../rag_agent/tests/test_requirements.py | 963 +++ .../agents/rag_agent/tests/test_tools.py | 510 ++ .../agents/rag_agent/tools.py | 149 + .../agents/rag_agent/utils/db_utils.py | 217 + .../agents/rag_agent/utils/models.py | 196 + .../agents/rag_agent/utils/providers.py | 103 + .../examples/basic_chat_agent/agent.py | 191 + .../main_agent_reference/.env.example | 9 + .../examples/main_agent_reference/cli.py | 214 + .../examples/main_agent_reference/models.py | 103 + .../main_agent_reference/providers.py | 61 + .../main_agent_reference/research_agent.py | 263 + .../examples/main_agent_reference/settings.py | 58 + .../examples/main_agent_reference/tools.py | 120 + .../documents/doc10_apple_ai_struggles.md | 156 + .../doc11_investment_funding_trends.md | 306 + .../documents/doc12_executive_moves.md | 208 + .../documents/doc13_regulatory_landscape.md | 255 + .../documents/doc14_patent_innovation.md | 379 + .../documents/doc15_competitive_analysis.md | 253 + .../documents/doc16_startup_ecosystem.md | 219 + .../documents/doc17_cloud_wars.md | 284 + .../documents/doc18_future_predictions.md | 339 + .../documents/doc19_acquisition_targets.md | 297 + .../documents/doc1_openai_funding.md | 43 + .../doc20_international_competition.md | 427 + .../documents/doc21_enterprise_adoption.md | 290 + .../documents/doc2_anthropic_amazon.md | 50 + .../documents/doc3_meta_scale_acquisition.md | 73 + .../documents/doc4_databricks_funding.md | 83 + .../doc5_microsoft_openai_tensions.md | 83 + .../documents/doc6_google_ai_strategy.md | 131 + .../documents/doc7_sam_altman_profile.md | 134 + .../documents/doc8_nvidia_dominance.md | 169 + .../documents/doc9_ai_market_analysis.md | 218 + .../rag_pipeline/ingestion/__init__.py | 3 + .../rag_pipeline/ingestion/chunker.py | 518 ++ .../rag_pipeline/ingestion/embedder.py | 418 + .../examples/rag_pipeline/ingestion/ingest.py | 434 + .../examples/rag_pipeline/sql/schema.sql | 170 + .../examples/rag_pipeline/utils/db_utils.py | 217 + .../examples/rag_pipeline/utils/models.py | 196 + .../examples/rag_pipeline/utils/providers.py | 103 + .../examples/structured_output_agent/agent.py | 303 + .../examples/testing_examples/pytest.ini | 18 + .../testing_examples/test_agent_patterns.py | 399 + .../examples/tool_enabled_agent/agent.py | 374 + .../.claude/commands/commit.md | 86 + .../.claude/commands/execute.md | 189 + .../.claude/commands/handoff.md | 133 + .../.claude/commands/plan-feature.md | 170 + .../.claude/commands/prime-backend.md | 96 + .../.claude/commands/prime-frontend.md | 84 + .../.claude/commands/prime-isolation.md | 105 + .../.claude/commands/prime-workflows.md | 96 + .../.claude/commands/prime.md | 75 + .../adapter-implementation-guide.md | 248 + .../docs-example/architecture-deep-dive.md | 324 + .../isolation-and-worktree-guide.md | 231 + .../docs-example/workflow-yaml-reference.md | 309 + .../.claude/rules-example/adapters.md | 42 + .../.claude/rules-example/cli.md | 77 + .../.claude/rules-example/database.md | 90 + .../.claude/rules-example/isolation.md | 77 + .../.claude/rules-example/orchestrator.md | 116 + .../.claude/rules-example/server-api.md | 109 + .../.claude/rules-example/testing.md | 105 + .../.claude/rules-example/web-frontend.md | 90 + .../.claude/rules-example/workflows.md | 109 + use-cases/ai-coding-wisc-framework/README.md | 116 + .../WISCFrameworkForAICoding.png | Bin 0 -> 786366 bytes .../ai-coding-workflows-foundation/README.md | 87 + .../agents/codebase-analyst.md | 114 + .../agents/validator.md | 176 + .../commands/create-plan.md | 202 + .../commands/execute-plan.md | 139 + .../commands/primer.md | 17 + .../AgentTeamsVsSubagents.png | Bin 0 -> 152842 bytes use-cases/build-with-agent-team/README.md | 156 + use-cases/build-with-agent-team/SKILL.md | 357 + .../example-plan/session-manager-plan.md | 522 ++ .../.claude/commands/prp-mcp-create.md | 100 + .../.claude/commands/prp-mcp-execute.md | 44 + use-cases/mcp-server/.dev.vars.example | 22 + use-cases/mcp-server/.gitignore | 174 + use-cases/mcp-server/.prettierrc | 14 + use-cases/mcp-server/CLAUDE.md | 835 ++ use-cases/mcp-server/PRPs/INITIAL.md | 32 + use-cases/mcp-server/PRPs/README.md | 44 + .../PRPs/ai_docs/claude_api_usage.md | 28 + .../mcp-server/PRPs/ai_docs/mcp_patterns.md | 491 ++ .../mcp-server/PRPs/templates/prp_mcp_base.md | 538 ++ use-cases/mcp-server/README.md | 248 + use-cases/mcp-server/copy_template.py | 362 + .../examples/database-tools-sentry.ts | 235 + .../mcp-server/examples/database-tools.ts | 155 + use-cases/mcp-server/package-lock.json | 5859 +++++++++++++ use-cases/mcp-server/package.json | 38 + .../mcp-server/src/auth/github-handler.ts | 119 + use-cases/mcp-server/src/auth/oauth-utils.ts | 662 ++ .../mcp-server/src/database/connection.ts | 37 + use-cases/mcp-server/src/database/security.ts | 72 + use-cases/mcp-server/src/database/utils.ts | 27 + use-cases/mcp-server/src/index.ts | 49 + use-cases/mcp-server/src/index_sentry.ts | 68 + .../mcp-server/src/tools/register-tools.ts | 14 + use-cases/mcp-server/src/types.ts | 126 + .../tests/fixtures/auth.fixtures.ts | 45 + .../tests/fixtures/database.fixtures.ts | 64 + .../mcp-server/tests/fixtures/mcp.fixtures.ts | 38 + .../mcp-server/tests/mocks/crypto.mock.ts | 54 + .../mcp-server/tests/mocks/database.mock.ts | 57 + .../mcp-server/tests/mocks/github.mock.ts | 59 + .../mcp-server/tests/mocks/oauth.mock.ts | 47 + use-cases/mcp-server/tests/setup.ts | 20 + .../tests/unit/database/security.test.ts | 135 + .../tests/unit/database/utils.test.ts | 78 + .../tests/unit/tools/database-tools.test.ts | 257 + .../tests/unit/utils/response-helpers.test.ts | 155 + use-cases/mcp-server/tsconfig.json | 46 + use-cases/mcp-server/vitest.config.js | 9 + .../mcp-server/worker-configuration.d.ts | 7365 +++++++++++++++++ use-cases/mcp-server/wrangler.jsonc | 78 + .../commands/execute-pydantic-ai-prp.md | 55 + .../commands/generate-pydantic-ai-prp.md | 94 + use-cases/pydantic-ai/CLAUDE.md | 208 + use-cases/pydantic-ai/PRPs/INITIAL.md | 47 + .../PRPs/templates/prp_pydantic_ai_base.md | 411 + use-cases/pydantic-ai/README.md | 189 + use-cases/pydantic-ai/copy_template.py | 291 + .../examples/basic_chat_agent/agent.py | 191 + .../main_agent_reference/.env.example | 9 + .../examples/main_agent_reference/cli.py | 214 + .../examples/main_agent_reference/models.py | 103 + .../main_agent_reference/providers.py | 61 + .../main_agent_reference/research_agent.py | 263 + .../examples/main_agent_reference/settings.py | 58 + .../examples/main_agent_reference/tools.py | 120 + .../examples/structured_output_agent/agent.py | 303 + .../examples/testing_examples/pytest.ini | 18 + .../testing_examples/test_agent_patterns.py | 399 + .../examples/tool_enabled_agent/agent.py | 374 + .../.claude/commands/execute-template-prp.md | 165 + .../.claude/commands/generate-template-prp.md | 105 + use-cases/template-generator/CLAUDE.md | 76 + use-cases/template-generator/PRPs/INITIAL.md | 228 + .../PRPs/INITIAL_PYDANTIC_AI.md | 101 + .../PRPs/template-pydantic-ai.md | 604 ++ .../PRPs/templates/prp_template_base.md | 525 ++ use-cases/template-generator/README.md | 184 + validation/README.md | 102 + validation/example-validate.md | 61 + validation/ultimate_validate_command.md | 116 + 243 files changed, 57858 insertions(+) create mode 100644 .claude/commands/execute-prp.md create mode 100644 .claude/commands/generate-prp.md create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100644 INITIAL.md create mode 100644 INITIAL_EXAMPLE.md create mode 100644 LICENSE create mode 100644 PRPs/EXAMPLE_multi_agent_prp.md create mode 100644 PRPs/templates/prp_base.md create mode 100644 README.md create mode 100644 README.wehub.md create mode 100644 claude-code-full-guide/.claude/agents/documentation-manager.md create mode 100644 claude-code-full-guide/.claude/agents/validation-gates.md create mode 100644 claude-code-full-guide/.claude/commands/execute-parallel.md create mode 100644 claude-code-full-guide/.claude/commands/execute-prp.md create mode 100644 claude-code-full-guide/.claude/commands/fix-github-issue.md create mode 100644 claude-code-full-guide/.claude/commands/generate-prp.md create mode 100644 claude-code-full-guide/.claude/commands/prep-parallel.md create mode 100644 claude-code-full-guide/.claude/commands/primer.md create mode 100644 claude-code-full-guide/.claude/hooks/README.md create mode 100644 claude-code-full-guide/.claude/hooks/example-hook-config.json create mode 100644 claude-code-full-guide/.claude/hooks/log-tool-usage.sh create mode 100644 claude-code-full-guide/.devcontainer/Dockerfile create mode 100644 claude-code-full-guide/.devcontainer/devcontainer.json create mode 100644 claude-code-full-guide/.devcontainer/init-firewall.sh create mode 100644 claude-code-full-guide/CLAUDE.md create mode 100644 claude-code-full-guide/INITIAL.md create mode 100644 claude-code-full-guide/PRPs/EXAMPLE_multi_agent_prp.md create mode 100644 claude-code-full-guide/PRPs/templates/prp_base.md create mode 100644 claude-code-full-guide/README.md create mode 100644 claude-code-full-guide/install_claude_code_windows.md create mode 100644 examples/.gitkeep create mode 100644 use-cases/agent-factory-with-subagents/.claude/agents/pydantic-ai-dependency-manager.md create mode 100644 use-cases/agent-factory-with-subagents/.claude/agents/pydantic-ai-planner.md create mode 100644 use-cases/agent-factory-with-subagents/.claude/agents/pydantic-ai-prompt-engineer.md create mode 100644 use-cases/agent-factory-with-subagents/.claude/agents/pydantic-ai-tool-integrator.md create mode 100644 use-cases/agent-factory-with-subagents/.claude/agents/pydantic-ai-validator.md create mode 100644 use-cases/agent-factory-with-subagents/.gitignore create mode 100644 use-cases/agent-factory-with-subagents/CLAUDE.md create mode 100644 use-cases/agent-factory-with-subagents/PRPs/INITIAL.md create mode 100644 use-cases/agent-factory-with-subagents/PRPs/templates/prp_pydantic_ai_base.md create mode 100644 use-cases/agent-factory-with-subagents/README.md create mode 100644 use-cases/agent-factory-with-subagents/SAMPLE_PROMPT.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/.env.example create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/README.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/__init__.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/agent.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/cli.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/dependencies.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc10_apple_ai_struggles.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc11_investment_funding_trends.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc12_executive_moves.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc13_regulatory_landscape.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc14_patent_innovation.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc15_competitive_analysis.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc16_startup_ecosystem.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc17_cloud_wars.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc18_future_predictions.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc19_acquisition_targets.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc1_openai_funding.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc20_international_competition.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc21_enterprise_adoption.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc2_anthropic_amazon.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc3_meta_scale_acquisition.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc4_databricks_funding.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc5_microsoft_openai_tensions.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc6_google_ai_strategy.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc7_sam_altman_profile.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc8_nvidia_dominance.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/documents/doc9_ai_market_analysis.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/ingestion/__init__.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/ingestion/chunker.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/ingestion/embedder.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/ingestion/ingest.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/planning/INITIAL.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/planning/dependencies.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/planning/prompts.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/planning/tools.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/prompts.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/providers.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/requirements.txt create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/settings.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/sql/schema.sql create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/tests/VALIDATION_REPORT.md create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/tests/conftest.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/tests/test_agent.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/tests/test_cli.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/tests/test_dependencies.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/tests/test_integration.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/tests/test_requirements.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/tests/test_tools.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/tools.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/utils/db_utils.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/utils/models.py create mode 100644 use-cases/agent-factory-with-subagents/agents/rag_agent/utils/providers.py create mode 100644 use-cases/agent-factory-with-subagents/examples/basic_chat_agent/agent.py create mode 100644 use-cases/agent-factory-with-subagents/examples/main_agent_reference/.env.example create mode 100644 use-cases/agent-factory-with-subagents/examples/main_agent_reference/cli.py create mode 100644 use-cases/agent-factory-with-subagents/examples/main_agent_reference/models.py create mode 100644 use-cases/agent-factory-with-subagents/examples/main_agent_reference/providers.py create mode 100644 use-cases/agent-factory-with-subagents/examples/main_agent_reference/research_agent.py create mode 100644 use-cases/agent-factory-with-subagents/examples/main_agent_reference/settings.py create mode 100644 use-cases/agent-factory-with-subagents/examples/main_agent_reference/tools.py create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc10_apple_ai_struggles.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc11_investment_funding_trends.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc12_executive_moves.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc13_regulatory_landscape.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc14_patent_innovation.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc15_competitive_analysis.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc16_startup_ecosystem.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc17_cloud_wars.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc18_future_predictions.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc19_acquisition_targets.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc1_openai_funding.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc20_international_competition.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc21_enterprise_adoption.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc2_anthropic_amazon.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc3_meta_scale_acquisition.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc4_databricks_funding.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc5_microsoft_openai_tensions.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc6_google_ai_strategy.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc7_sam_altman_profile.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc8_nvidia_dominance.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/documents/doc9_ai_market_analysis.md create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/ingestion/__init__.py create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/ingestion/chunker.py create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/ingestion/embedder.py create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/ingestion/ingest.py create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/sql/schema.sql create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/utils/db_utils.py create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/utils/models.py create mode 100644 use-cases/agent-factory-with-subagents/examples/rag_pipeline/utils/providers.py create mode 100644 use-cases/agent-factory-with-subagents/examples/structured_output_agent/agent.py create mode 100644 use-cases/agent-factory-with-subagents/examples/testing_examples/pytest.ini create mode 100644 use-cases/agent-factory-with-subagents/examples/testing_examples/test_agent_patterns.py create mode 100644 use-cases/agent-factory-with-subagents/examples/tool_enabled_agent/agent.py create mode 100644 use-cases/ai-coding-wisc-framework/.claude/commands/commit.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/commands/execute.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/commands/handoff.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/commands/plan-feature.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/commands/prime-backend.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/commands/prime-frontend.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/commands/prime-isolation.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/commands/prime-workflows.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/commands/prime.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/docs-example/adapter-implementation-guide.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/docs-example/architecture-deep-dive.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/docs-example/isolation-and-worktree-guide.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/docs-example/workflow-yaml-reference.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/rules-example/adapters.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/rules-example/cli.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/rules-example/database.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/rules-example/isolation.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/rules-example/orchestrator.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/rules-example/server-api.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/rules-example/testing.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/rules-example/web-frontend.md create mode 100644 use-cases/ai-coding-wisc-framework/.claude/rules-example/workflows.md create mode 100644 use-cases/ai-coding-wisc-framework/README.md create mode 100644 use-cases/ai-coding-wisc-framework/WISCFrameworkForAICoding.png create mode 100644 use-cases/ai-coding-workflows-foundation/README.md create mode 100644 use-cases/ai-coding-workflows-foundation/agents/codebase-analyst.md create mode 100644 use-cases/ai-coding-workflows-foundation/agents/validator.md create mode 100644 use-cases/ai-coding-workflows-foundation/commands/create-plan.md create mode 100644 use-cases/ai-coding-workflows-foundation/commands/execute-plan.md create mode 100644 use-cases/ai-coding-workflows-foundation/commands/primer.md create mode 100644 use-cases/build-with-agent-team/AgentTeamsVsSubagents.png create mode 100644 use-cases/build-with-agent-team/README.md create mode 100644 use-cases/build-with-agent-team/SKILL.md create mode 100644 use-cases/build-with-agent-team/example-plan/session-manager-plan.md create mode 100644 use-cases/mcp-server/.claude/commands/prp-mcp-create.md create mode 100644 use-cases/mcp-server/.claude/commands/prp-mcp-execute.md create mode 100644 use-cases/mcp-server/.dev.vars.example create mode 100644 use-cases/mcp-server/.gitignore create mode 100644 use-cases/mcp-server/.prettierrc create mode 100644 use-cases/mcp-server/CLAUDE.md create mode 100644 use-cases/mcp-server/PRPs/INITIAL.md create mode 100644 use-cases/mcp-server/PRPs/README.md create mode 100644 use-cases/mcp-server/PRPs/ai_docs/claude_api_usage.md create mode 100644 use-cases/mcp-server/PRPs/ai_docs/mcp_patterns.md create mode 100644 use-cases/mcp-server/PRPs/templates/prp_mcp_base.md create mode 100644 use-cases/mcp-server/README.md create mode 100644 use-cases/mcp-server/copy_template.py create mode 100644 use-cases/mcp-server/examples/database-tools-sentry.ts create mode 100644 use-cases/mcp-server/examples/database-tools.ts create mode 100644 use-cases/mcp-server/package-lock.json create mode 100644 use-cases/mcp-server/package.json create mode 100644 use-cases/mcp-server/src/auth/github-handler.ts create mode 100644 use-cases/mcp-server/src/auth/oauth-utils.ts create mode 100644 use-cases/mcp-server/src/database/connection.ts create mode 100644 use-cases/mcp-server/src/database/security.ts create mode 100644 use-cases/mcp-server/src/database/utils.ts create mode 100644 use-cases/mcp-server/src/index.ts create mode 100644 use-cases/mcp-server/src/index_sentry.ts create mode 100644 use-cases/mcp-server/src/tools/register-tools.ts create mode 100644 use-cases/mcp-server/src/types.ts create mode 100644 use-cases/mcp-server/tests/fixtures/auth.fixtures.ts create mode 100644 use-cases/mcp-server/tests/fixtures/database.fixtures.ts create mode 100644 use-cases/mcp-server/tests/fixtures/mcp.fixtures.ts create mode 100644 use-cases/mcp-server/tests/mocks/crypto.mock.ts create mode 100644 use-cases/mcp-server/tests/mocks/database.mock.ts create mode 100644 use-cases/mcp-server/tests/mocks/github.mock.ts create mode 100644 use-cases/mcp-server/tests/mocks/oauth.mock.ts create mode 100644 use-cases/mcp-server/tests/setup.ts create mode 100644 use-cases/mcp-server/tests/unit/database/security.test.ts create mode 100644 use-cases/mcp-server/tests/unit/database/utils.test.ts create mode 100644 use-cases/mcp-server/tests/unit/tools/database-tools.test.ts create mode 100644 use-cases/mcp-server/tests/unit/utils/response-helpers.test.ts create mode 100644 use-cases/mcp-server/tsconfig.json create mode 100644 use-cases/mcp-server/vitest.config.js create mode 100644 use-cases/mcp-server/worker-configuration.d.ts create mode 100644 use-cases/mcp-server/wrangler.jsonc create mode 100644 use-cases/pydantic-ai/.claude/commands/execute-pydantic-ai-prp.md create mode 100644 use-cases/pydantic-ai/.claude/commands/generate-pydantic-ai-prp.md create mode 100644 use-cases/pydantic-ai/CLAUDE.md create mode 100644 use-cases/pydantic-ai/PRPs/INITIAL.md create mode 100644 use-cases/pydantic-ai/PRPs/templates/prp_pydantic_ai_base.md create mode 100644 use-cases/pydantic-ai/README.md create mode 100644 use-cases/pydantic-ai/copy_template.py create mode 100644 use-cases/pydantic-ai/examples/basic_chat_agent/agent.py create mode 100644 use-cases/pydantic-ai/examples/main_agent_reference/.env.example create mode 100644 use-cases/pydantic-ai/examples/main_agent_reference/cli.py create mode 100644 use-cases/pydantic-ai/examples/main_agent_reference/models.py create mode 100644 use-cases/pydantic-ai/examples/main_agent_reference/providers.py create mode 100644 use-cases/pydantic-ai/examples/main_agent_reference/research_agent.py create mode 100644 use-cases/pydantic-ai/examples/main_agent_reference/settings.py create mode 100644 use-cases/pydantic-ai/examples/main_agent_reference/tools.py create mode 100644 use-cases/pydantic-ai/examples/structured_output_agent/agent.py create mode 100644 use-cases/pydantic-ai/examples/testing_examples/pytest.ini create mode 100644 use-cases/pydantic-ai/examples/testing_examples/test_agent_patterns.py create mode 100644 use-cases/pydantic-ai/examples/tool_enabled_agent/agent.py create mode 100644 use-cases/template-generator/.claude/commands/execute-template-prp.md create mode 100644 use-cases/template-generator/.claude/commands/generate-template-prp.md create mode 100644 use-cases/template-generator/CLAUDE.md create mode 100644 use-cases/template-generator/PRPs/INITIAL.md create mode 100644 use-cases/template-generator/PRPs/INITIAL_PYDANTIC_AI.md create mode 100644 use-cases/template-generator/PRPs/template-pydantic-ai.md create mode 100644 use-cases/template-generator/PRPs/templates/prp_template_base.md create mode 100644 use-cases/template-generator/README.md create mode 100644 validation/README.md create mode 100644 validation/example-validate.md create mode 100644 validation/ultimate_validate_command.md diff --git a/.claude/commands/execute-prp.md b/.claude/commands/execute-prp.md new file mode 100644 index 0000000..81fb8ea --- /dev/null +++ b/.claude/commands/execute-prp.md @@ -0,0 +1,40 @@ +# Execute BASE PRP + +Implement a feature using using the PRP file. + +## PRP File: $ARGUMENTS + +## Execution Process + +1. **Load PRP** + - Read the specified PRP file + - Understand all context and requirements + - Follow all instructions in the PRP and extend the research if needed + - Ensure you have all needed context to implement the PRP fully + - Do more web searches and codebase exploration as needed + +2. **ULTRATHINK** + - Think hard before you execute the plan. Create a comprehensive plan addressing all requirements. + - Break down complex tasks into smaller, manageable steps using your todos tools. + - Use the TodoWrite tool to create and track your implementation plan. + - Identify implementation patterns from existing code to follow. + +3. **Execute the plan** + - Execute the PRP + - Implement all the code + +4. **Validate** + - Run each validation command + - Fix any failures + - Re-run until all pass + +5. **Complete** + - Ensure all checklist items done + - Run final validation suite + - Report completion status + - Read the PRP again to ensure you have implemented everything + +6. **Reference the PRP** + - You can always reference the PRP again if needed + +Note: If validation fails, use error patterns in PRP to fix and retry. \ No newline at end of file diff --git a/.claude/commands/generate-prp.md b/.claude/commands/generate-prp.md new file mode 100644 index 0000000..e1b4ac8 --- /dev/null +++ b/.claude/commands/generate-prp.md @@ -0,0 +1,69 @@ +# Create PRP + +## Feature file: $ARGUMENTS + +Generate a complete PRP for general feature implementation with thorough research. Ensure context is passed to the AI agent to enable self-validation and iterative refinement. Read the feature file first to understand what needs to be created, how the examples provided help, and any other considerations. + +The AI agent only gets the context you are appending to the PRP and training data. Assuma the AI agent has access to the codebase and the same knowledge cutoff as you, so its important that your research findings are included or referenced in the PRP. The Agent has Websearch capabilities, so pass urls to documentation and examples. + +## Research Process + +1. **Codebase Analysis** + - Search for similar features/patterns in the codebase + - Identify files to reference in PRP + - Note existing conventions to follow + - Check test patterns for validation approach + +2. **External Research** + - Search for similar features/patterns online + - Library documentation (include specific URLs) + - Implementation examples (GitHub/StackOverflow/blogs) + - Best practices and common pitfalls + +3. **User Clarification** (if needed) + - Specific patterns to mirror and where to find them? + - Integration requirements and where to find them? + +## PRP Generation + +Using PRPs/templates/prp_base.md as template: + +### Critical Context to Include and pass to the AI agent as part of the PRP +- **Documentation**: URLs with specific sections +- **Code Examples**: Real snippets from codebase +- **Gotchas**: Library quirks, version issues +- **Patterns**: Existing approaches to follow + +### Implementation Blueprint +- Start with pseudocode showing approach +- Reference real files for patterns +- Include error handling strategy +- list tasks to be completed to fullfill the PRP in the order they should be completed + +### Validation Gates (Must be Executable) eg for python +```bash +# Syntax/Style +ruff check --fix && mypy . + +# Unit Tests +uv run pytest tests/ -v + +``` + +*** CRITICAL AFTER YOU ARE DONE RESEARCHING AND EXPLORING THE CODEBASE BEFORE YOU START WRITING THE PRP *** + +*** ULTRATHINK ABOUT THE PRP AND PLAN YOUR APPROACH THEN START WRITING THE PRP *** + +## Output +Save as: `PRPs/{feature-name}.md` + +## Quality Checklist +- [ ] All necessary context included +- [ ] Validation gates are executable by AI +- [ ] References existing patterns +- [ ] Clear implementation path +- [ ] Error handling documented + +Score the PRP on a scale of 1-10 (confidence level to succeed in one-pass implementation using claude codes) + +Remember: The goal is one-pass implementation success through comprehensive context. \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3a70f21 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +venv +venv_linux +__pycache__ +.ruff_cache +.pytest_cache \ No newline at end of file diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..f0423f5 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,59 @@ +### 🔄 Project Awareness & Context +- **Always read `PLANNING.md`** at the start of a new conversation to understand the project's architecture, goals, style, and constraints. +- **Check `TASK.md`** before starting a new task. If the task isn’t listed, add it with a brief description and today's date. +- **Use consistent naming conventions, file structure, and architecture patterns** as described in `PLANNING.md`. +- **Use venv_linux** (the virtual environment) whenever executing Python commands, including for unit tests. + +### 🧱 Code Structure & Modularity +- **Never create a file longer than 500 lines of code.** If a file approaches this limit, refactor by splitting it into modules or helper files. +- **Organize code into clearly separated modules**, grouped by feature or responsibility. + For agents this looks like: + - `agent.py` - Main agent definition and execution logic + - `tools.py` - Tool functions used by the agent + - `prompts.py` - System prompts +- **Use clear, consistent imports** (prefer relative imports within packages). +- **Use clear, consistent imports** (prefer relative imports within packages). +- **Use python_dotenv and load_env()** for environment variables. + +### 🧪 Testing & Reliability +- **Always create Pytest unit tests for new features** (functions, classes, routes, etc). +- **After updating any logic**, check whether existing unit tests need to be updated. If so, do it. +- **Tests should live in a `/tests` folder** mirroring the main app structure. + - Include at least: + - 1 test for expected use + - 1 edge case + - 1 failure case + +### ✅ Task Completion +- **Mark completed tasks in `TASK.md`** immediately after finishing them. +- Add new sub-tasks or TODOs discovered during development to `TASK.md` under a “Discovered During Work” section. + +### 📎 Style & Conventions +- **Use Python** as the primary language. +- **Follow PEP8**, use type hints, and format with `black`. +- **Use `pydantic` for data validation**. +- Use `FastAPI` for APIs and `SQLAlchemy` or `SQLModel` for ORM if applicable. +- Write **docstrings for every function** using the Google style: + ```python + def example(): + """ + Brief summary. + + Args: + param1 (type): Description. + + Returns: + type: Description. + """ + ``` + +### 📚 Documentation & Explainability +- **Update `README.md`** when new features are added, dependencies change, or setup steps are modified. +- **Comment non-obvious code** and ensure everything is understandable to a mid-level developer. +- When writing complex logic, **add an inline `# Reason:` comment** explaining the why, not just the what. + +### 🧠 AI Behavior Rules +- **Never assume missing context. Ask questions if uncertain.** +- **Never hallucinate libraries or functions** – only use known, verified Python packages. +- **Always confirm file paths and module names** exist before referencing them in code or tests. +- **Never delete or overwrite existing code** unless explicitly instructed to or if part of a task from `TASK.md`. \ No newline at end of file diff --git a/INITIAL.md b/INITIAL.md new file mode 100644 index 0000000..80e88f5 --- /dev/null +++ b/INITIAL.md @@ -0,0 +1,15 @@ +## FEATURE: + +[Insert your feature here] + +## EXAMPLES: + +[Provide and explain examples that you have in the `examples/` folder] + +## DOCUMENTATION: + +[List out any documentation (web pages, sources for an MCP server like Crawl4AI RAG, etc.) that will need to be referenced during development] + +## OTHER CONSIDERATIONS: + +[Any other considerations or specific requirements - great place to include gotchas that you see AI coding assistants miss with your projects a lot] diff --git a/INITIAL_EXAMPLE.md b/INITIAL_EXAMPLE.md new file mode 100644 index 0000000..c7fca83 --- /dev/null +++ b/INITIAL_EXAMPLE.md @@ -0,0 +1,26 @@ +## FEATURE: + +- Pydantic AI agent that has another Pydantic AI agent as a tool. +- Research Agent for the primary agent and then an email draft Agent for the subagent. +- CLI to interact with the agent. +- Gmail for the email draft agent, Brave API for the research agent. + +## EXAMPLES: + +In the `examples/` folder, there is a README for you to read to understand what the example is all about and also how to structure your own README when you create documentation for the above feature. + +- `examples/cli.py` - use this as a template to create the CLI +- `examples/agent/` - read through all of the files here to understand best practices for creating Pydantic AI agents that support different providers and LLMs, handling agent dependencies, and adding tools to the agent. + +Don't copy any of these examples directly, it is for a different project entirely. But use this as inspiration and for best practices. + +## DOCUMENTATION: + +Pydantic AI documentation: https://ai.pydantic.dev/ + +## OTHER CONSIDERATIONS: + +- Include a .env.example, README with instructions for setup including how to configure Gmail and Brave. +- Include the project structure in the README. +- Virtual environment has already been set up with the necessary dependencies. +- Use python_dotenv and load_env() for environment variables diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..44b90e6 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Cole Medin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/PRPs/EXAMPLE_multi_agent_prp.md b/PRPs/EXAMPLE_multi_agent_prp.md new file mode 100644 index 0000000..46a5966 --- /dev/null +++ b/PRPs/EXAMPLE_multi_agent_prp.md @@ -0,0 +1,395 @@ +name: "Multi-Agent System: Research Agent with Email Draft Sub-Agent" +description: | + +## Purpose +Build a Pydantic AI multi-agent system where a primary Research Agent uses Brave Search API and has an Email Draft Agent (using Gmail API) as a tool. This demonstrates agent-as-tool pattern with external API integrations. + +## Core Principles +1. **Context is King**: Include ALL necessary documentation, examples, and caveats +2. **Validation Loops**: Provide executable tests/lints the AI can run and fix +3. **Information Dense**: Use keywords and patterns from the codebase +4. **Progressive Success**: Start simple, validate, then enhance + +--- + +## Goal +Create a production-ready multi-agent system where users can research topics via CLI, and the Research Agent can delegate email drafting tasks to an Email Draft Agent. The system should support multiple LLM providers and handle API authentication securely. + +## Why +- **Business value**: Automates research and email drafting workflows +- **Integration**: Demonstrates advanced Pydantic AI multi-agent patterns +- **Problems solved**: Reduces manual work for research-based email communications + +## What +A CLI-based application where: +- Users input research queries +- Research Agent searches using Brave API +- Research Agent can invoke Email Draft Agent to create Gmail drafts +- Results stream back to the user in real-time + +### Success Criteria +- [ ] Research Agent successfully searches via Brave API +- [ ] Email Agent creates Gmail drafts with proper authentication +- [ ] Research Agent can invoke Email Agent as a tool +- [ ] CLI provides streaming responses with tool visibility +- [ ] All tests pass and code meets quality standards + +## All Needed Context + +### Documentation & References +```yaml +# MUST READ - Include these in your context window +- url: https://ai.pydantic.dev/agents/ + why: Core agent creation patterns + +- url: https://ai.pydantic.dev/multi-agent-applications/ + why: Multi-agent system patterns, especially agent-as-tool + +- url: https://developers.google.com/gmail/api/guides/sending + why: Gmail API authentication and draft creation + +- url: https://api-dashboard.search.brave.com/app/documentation + why: Brave Search API REST endpoints + +- file: examples/agent/agent.py + why: Pattern for agent creation, tool registration, dependencies + +- file: examples/agent/providers.py + why: Multi-provider LLM configuration pattern + +- file: examples/cli.py + why: CLI structure with streaming responses and tool visibility + +- url: https://github.com/googleworkspace/python-samples/blob/main/gmail/snippet/send%20mail/create_draft.py + why: Official Gmail draft creation example +``` + +### Current Codebase tree +```bash +. +├── examples/ +│ ├── agent/ +│ │ ├── agent.py +│ │ ├── providers.py +│ │ └── ... +│ └── cli.py +├── PRPs/ +│ └── templates/ +│ └── prp_base.md +├── INITIAL.md +├── CLAUDE.md +└── requirements.txt +``` + +### Desired Codebase tree with files to be added +```bash +. +├── agents/ +│ ├── __init__.py # Package init +│ ├── research_agent.py # Primary agent with Brave Search +│ ├── email_agent.py # Sub-agent with Gmail capabilities +│ ├── providers.py # LLM provider configuration +│ └── models.py # Pydantic models for data validation +├── tools/ +│ ├── __init__.py # Package init +│ ├── brave_search.py # Brave Search API integration +│ └── gmail_tool.py # Gmail API integration +├── config/ +│ ├── __init__.py # Package init +│ └── settings.py # Environment and config management +├── tests/ +│ ├── __init__.py # Package init +│ ├── test_research_agent.py # Research agent tests +│ ├── test_email_agent.py # Email agent tests +│ ├── test_brave_search.py # Brave search tool tests +│ ├── test_gmail_tool.py # Gmail tool tests +│ └── test_cli.py # CLI tests +├── cli.py # CLI interface +├── .env.example # Environment variables template +├── requirements.txt # Updated dependencies +├── README.md # Comprehensive documentation +└── credentials/.gitkeep # Directory for Gmail credentials +``` + +### Known Gotchas & Library Quirks +```python +# CRITICAL: Pydantic AI requires async throughout - no sync functions in async context +# CRITICAL: Gmail API requires OAuth2 flow on first run - credentials.json needed +# CRITICAL: Brave API has rate limits - 2000 req/month on free tier +# CRITICAL: Agent-as-tool pattern requires passing ctx.usage for token tracking +# CRITICAL: Gmail drafts need base64 encoding with proper MIME formatting +# CRITICAL: Always use absolute imports for cleaner code +# CRITICAL: Store sensitive credentials in .env, never commit them +``` + +## Implementation Blueprint + +### Data models and structure + +```python +# models.py - Core data structures +from pydantic import BaseModel, Field +from typing import List, Optional +from datetime import datetime + +class ResearchQuery(BaseModel): + query: str = Field(..., description="Research topic to investigate") + max_results: int = Field(10, ge=1, le=50) + include_summary: bool = Field(True) + +class BraveSearchResult(BaseModel): + title: str + url: str + description: str + score: float = Field(0.0, ge=0.0, le=1.0) + +class EmailDraft(BaseModel): + to: List[str] = Field(..., min_items=1) + subject: str = Field(..., min_length=1) + body: str = Field(..., min_length=1) + cc: Optional[List[str]] = None + bcc: Optional[List[str]] = None + +class ResearchEmailRequest(BaseModel): + research_query: str + email_context: str = Field(..., description="Context for email generation") + recipient_email: str +``` + +### List of tasks to be completed + +```yaml +Task 1: Setup Configuration and Environment +CREATE config/settings.py: + - PATTERN: Use pydantic-settings like examples use os.getenv + - Load environment variables with defaults + - Validate required API keys present + +CREATE .env.example: + - Include all required environment variables with descriptions + - Follow pattern from examples/README.md + +Task 2: Implement Brave Search Tool +CREATE tools/brave_search.py: + - PATTERN: Async functions like examples/agent/tools.py + - Simple REST client using httpx (already in requirements) + - Handle rate limits and errors gracefully + - Return structured BraveSearchResult models + +Task 3: Implement Gmail Tool +CREATE tools/gmail_tool.py: + - PATTERN: Follow OAuth2 flow from Gmail quickstart + - Store token.json in credentials/ directory + - Create draft with proper MIME encoding + - Handle authentication refresh automatically + +Task 4: Create Email Draft Agent +CREATE agents/email_agent.py: + - PATTERN: Follow examples/agent/agent.py structure + - Use Agent with deps_type pattern + - Register gmail_tool as @agent.tool + - Return EmailDraft model + +Task 5: Create Research Agent +CREATE agents/research_agent.py: + - PATTERN: Multi-agent pattern from Pydantic AI docs + - Register brave_search as tool + - Register email_agent.run() as tool + - Use RunContext for dependency injection + +Task 6: Implement CLI Interface +CREATE cli.py: + - PATTERN: Follow examples/cli.py streaming pattern + - Color-coded output with tool visibility + - Handle async properly with asyncio.run() + - Session management for conversation context + +Task 7: Add Comprehensive Tests +CREATE tests/: + - PATTERN: Mirror examples test structure + - Mock external API calls + - Test happy path, edge cases, errors + - Ensure 80%+ coverage + +Task 8: Create Documentation +CREATE README.md: + - PATTERN: Follow examples/README.md structure + - Include setup, installation, usage + - API key configuration steps + - Architecture diagram +``` + +### Per task pseudocode + +```python +# Task 2: Brave Search Tool +async def search_brave(query: str, api_key: str, count: int = 10) -> List[BraveSearchResult]: + # PATTERN: Use httpx like examples use aiohttp + async with httpx.AsyncClient() as client: + headers = {"X-Subscription-Token": api_key} + params = {"q": query, "count": count} + + # GOTCHA: Brave API returns 401 if API key invalid + response = await client.get( + "https://api.search.brave.com/res/v1/web/search", + headers=headers, + params=params, + timeout=30.0 # CRITICAL: Set timeout to avoid hanging + ) + + # PATTERN: Structured error handling + if response.status_code != 200: + raise BraveAPIError(f"API returned {response.status_code}") + + # Parse and validate with Pydantic + data = response.json() + return [BraveSearchResult(**result) for result in data.get("web", {}).get("results", [])] + +# Task 5: Research Agent with Email Agent as Tool +@research_agent.tool +async def create_email_draft( + ctx: RunContext[AgentDependencies], + recipient: str, + subject: str, + context: str +) -> str: + """Create email draft based on research context.""" + # CRITICAL: Pass usage for token tracking + result = await email_agent.run( + f"Create an email to {recipient} about: {context}", + deps=EmailAgentDeps(subject=subject), + usage=ctx.usage # PATTERN from multi-agent docs + ) + + return f"Draft created with ID: {result.data}" +``` + +### Integration Points +```yaml +ENVIRONMENT: + - add to: .env + - vars: | + # LLM Configuration + LLM_PROVIDER=openai + LLM_API_KEY=sk-... + LLM_MODEL=gpt-4 + + # Brave Search + BRAVE_API_KEY=BSA... + + # Gmail (path to credentials.json) + GMAIL_CREDENTIALS_PATH=./credentials/credentials.json + +CONFIG: + - Gmail OAuth: First run opens browser for authorization + - Token storage: ./credentials/token.json (auto-created) + +DEPENDENCIES: + - Update requirements.txt with: + - google-api-python-client + - google-auth-httplib2 + - google-auth-oauthlib +``` + +## Validation Loop + +### Level 1: Syntax & Style +```bash +# Run these FIRST - fix any errors before proceeding +ruff check . --fix # Auto-fix style issues +mypy . # Type checking + +# Expected: No errors. If errors, READ and fix. +``` + +### Level 2: Unit Tests +```python +# test_research_agent.py +async def test_research_with_brave(): + """Test research agent searches correctly""" + agent = create_research_agent() + result = await agent.run("AI safety research") + assert result.data + assert len(result.data) > 0 + +async def test_research_creates_email(): + """Test research agent can invoke email agent""" + agent = create_research_agent() + result = await agent.run( + "Research AI safety and draft email to john@example.com" + ) + assert "draft_id" in result.data + +# test_email_agent.py +def test_gmail_authentication(monkeypatch): + """Test Gmail OAuth flow handling""" + monkeypatch.setenv("GMAIL_CREDENTIALS_PATH", "test_creds.json") + tool = GmailTool() + assert tool.service is not None + +async def test_create_draft(): + """Test draft creation with proper encoding""" + agent = create_email_agent() + result = await agent.run( + "Create email to test@example.com about AI research" + ) + assert result.data.get("draft_id") +``` + +```bash +# Run tests iteratively until passing: +pytest tests/ -v --cov=agents --cov=tools --cov-report=term-missing + +# If failing: Debug specific test, fix code, re-run +``` + +### Level 3: Integration Test +```bash +# Test CLI interaction +python cli.py + +# Expected interaction: +# You: Research latest AI safety developments +# 🤖 Assistant: [Streams research results] +# 🛠 Tools Used: +# 1. brave_search (query='AI safety developments', limit=10) +# +# You: Create an email draft about this to john@example.com +# 🤖 Assistant: [Creates draft] +# 🛠 Tools Used: +# 1. create_email_draft (recipient='john@example.com', ...) + +# Check Gmail drafts folder for created draft +``` + +## Final Validation Checklist +- [ ] All tests pass: `pytest tests/ -v` +- [ ] No linting errors: `ruff check .` +- [ ] No type errors: `mypy .` +- [ ] Gmail OAuth flow works (browser opens, token saved) +- [ ] Brave Search returns results +- [ ] Research Agent invokes Email Agent successfully +- [ ] CLI streams responses with tool visibility +- [ ] Error cases handled gracefully +- [ ] README includes clear setup instructions +- [ ] .env.example has all required variables + +--- + +## Anti-Patterns to Avoid +- ❌ Don't hardcode API keys - use environment variables +- ❌ Don't use sync functions in async agent context +- ❌ Don't skip OAuth flow setup for Gmail +- ❌ Don't ignore rate limits for APIs +- ❌ Don't forget to pass ctx.usage in multi-agent calls +- ❌ Don't commit credentials.json or token.json files + +## Confidence Score: 9/10 + +High confidence due to: +- Clear examples to follow from the codebase +- Well-documented external APIs +- Established patterns for multi-agent systems +- Comprehensive validation gates + +Minor uncertainty on Gmail OAuth first-time setup UX, but documentation provides clear guidance. \ No newline at end of file diff --git a/PRPs/templates/prp_base.md b/PRPs/templates/prp_base.md new file mode 100644 index 0000000..265d508 --- /dev/null +++ b/PRPs/templates/prp_base.md @@ -0,0 +1,212 @@ +name: "Base PRP Template v2 - Context-Rich with Validation Loops" +description: | + +## Purpose +Template optimized for AI agents to implement features with sufficient context and self-validation capabilities to achieve working code through iterative refinement. + +## Core Principles +1. **Context is King**: Include ALL necessary documentation, examples, and caveats +2. **Validation Loops**: Provide executable tests/lints the AI can run and fix +3. **Information Dense**: Use keywords and patterns from the codebase +4. **Progressive Success**: Start simple, validate, then enhance +5. **Global rules**: Be sure to follow all rules in CLAUDE.md + +--- + +## Goal +[What needs to be built - be specific about the end state and desires] + +## Why +- [Business value and user impact] +- [Integration with existing features] +- [Problems this solves and for whom] + +## What +[User-visible behavior and technical requirements] + +### Success Criteria +- [ ] [Specific measurable outcomes] + +## All Needed Context + +### Documentation & References (list all context needed to implement the feature) +```yaml +# MUST READ - Include these in your context window +- url: [Official API docs URL] + why: [Specific sections/methods you'll need] + +- file: [path/to/example.py] + why: [Pattern to follow, gotchas to avoid] + +- doc: [Library documentation URL] + section: [Specific section about common pitfalls] + critical: [Key insight that prevents common errors] + +- docfile: [PRPs/ai_docs/file.md] + why: [docs that the user has pasted in to the project] + +``` + +### Current Codebase tree (run `tree` in the root of the project) to get an overview of the codebase +```bash + +``` + +### Desired Codebase tree with files to be added and responsibility of file +```bash + +``` + +### Known Gotchas of our codebase & Library Quirks +```python +# CRITICAL: [Library name] requires [specific setup] +# Example: FastAPI requires async functions for endpoints +# Example: This ORM doesn't support batch inserts over 1000 records +# Example: We use pydantic v2 and +``` + +## Implementation Blueprint + +### Data models and structure + +Create the core data models, we ensure type safety and consistency. +```python +Examples: + - orm models + - pydantic models + - pydantic schemas + - pydantic validators + +``` + +### list of tasks to be completed to fullfill the PRP in the order they should be completed + +```yaml +Task 1: +MODIFY src/existing_module.py: + - FIND pattern: "class OldImplementation" + - INJECT after line containing "def __init__" + - PRESERVE existing method signatures + +CREATE src/new_feature.py: + - MIRROR pattern from: src/similar_feature.py + - MODIFY class name and core logic + - KEEP error handling pattern identical + +...(...) + +Task N: +... + +``` + + +### Per task pseudocode as needed added to each task +```python + +# Task 1 +# Pseudocode with CRITICAL details dont write entire code +async def new_feature(param: str) -> Result: + # PATTERN: Always validate input first (see src/validators.py) + validated = validate_input(param) # raises ValidationError + + # GOTCHA: This library requires connection pooling + async with get_connection() as conn: # see src/db/pool.py + # PATTERN: Use existing retry decorator + @retry(attempts=3, backoff=exponential) + async def _inner(): + # CRITICAL: API returns 429 if >10 req/sec + await rate_limiter.acquire() + return await external_api.call(validated) + + result = await _inner() + + # PATTERN: Standardized response format + return format_response(result) # see src/utils/responses.py +``` + +### Integration Points +```yaml +DATABASE: + - migration: "Add column 'feature_enabled' to users table" + - index: "CREATE INDEX idx_feature_lookup ON users(feature_id)" + +CONFIG: + - add to: config/settings.py + - pattern: "FEATURE_TIMEOUT = int(os.getenv('FEATURE_TIMEOUT', '30'))" + +ROUTES: + - add to: src/api/routes.py + - pattern: "router.include_router(feature_router, prefix='/feature')" +``` + +## Validation Loop + +### Level 1: Syntax & Style +```bash +# Run these FIRST - fix any errors before proceeding +ruff check src/new_feature.py --fix # Auto-fix what's possible +mypy src/new_feature.py # Type checking + +# Expected: No errors. If errors, READ the error and fix. +``` + +### Level 2: Unit Tests each new feature/file/function use existing test patterns +```python +# CREATE test_new_feature.py with these test cases: +def test_happy_path(): + """Basic functionality works""" + result = new_feature("valid_input") + assert result.status == "success" + +def test_validation_error(): + """Invalid input raises ValidationError""" + with pytest.raises(ValidationError): + new_feature("") + +def test_external_api_timeout(): + """Handles timeouts gracefully""" + with mock.patch('external_api.call', side_effect=TimeoutError): + result = new_feature("valid") + assert result.status == "error" + assert "timeout" in result.message +``` + +```bash +# Run and iterate until passing: +uv run pytest test_new_feature.py -v +# If failing: Read error, understand root cause, fix code, re-run (never mock to pass) +``` + +### Level 3: Integration Test +```bash +# Start the service +uv run python -m src.main --dev + +# Test the endpoint +curl -X POST http://localhost:8000/feature \ + -H "Content-Type: application/json" \ + -d '{"param": "test_value"}' + +# Expected: {"status": "success", "data": {...}} +# If error: Check logs at logs/app.log for stack trace +``` + +## Final validation Checklist +- [ ] All tests pass: `uv run pytest tests/ -v` +- [ ] No linting errors: `uv run ruff check src/` +- [ ] No type errors: `uv run mypy src/` +- [ ] Manual test successful: [specific curl/command] +- [ ] Error cases handled gracefully +- [ ] Logs are informative but not verbose +- [ ] Documentation updated if needed + +--- + +## Anti-Patterns to Avoid +- ❌ Don't create new patterns when existing ones work +- ❌ Don't skip validation because "it should work" +- ❌ Don't ignore failing tests - fix them +- ❌ Don't use sync functions in async context +- ❌ Don't hardcode values that should be config +- ❌ Don't catch all exceptions - be specific \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..d1843da --- /dev/null +++ b/README.md @@ -0,0 +1,296 @@ +# Context Engineering Template + +A comprehensive template for getting started with Context Engineering - the discipline of engineering context for AI coding assistants so they have the information necessary to get the job done end to end. + +> **Context Engineering is 10x better than prompt engineering and 100x better than vibe coding.** + +## 🚀 Quick Start + +```bash +# 1. Clone this template +git clone https://github.com/coleam00/Context-Engineering-Intro.git +cd Context-Engineering-Intro + +# 2. Set up your project rules (optional - template provided) +# Edit CLAUDE.md to add your project-specific guidelines + +# 3. Add examples (highly recommended) +# Place relevant code examples in the examples/ folder + +# 4. Create your initial feature request +# Edit INITIAL.md with your feature requirements + +# 5. Generate a comprehensive PRP (Product Requirements Prompt) +# In Claude Code, run: +/generate-prp INITIAL.md + +# 6. Execute the PRP to implement your feature +# In Claude Code, run: +/execute-prp PRPs/your-feature-name.md +``` + +## 📚 Table of Contents + +- [What is Context Engineering?](#what-is-context-engineering) +- [Template Structure](#template-structure) +- [Step-by-Step Guide](#step-by-step-guide) +- [Writing Effective INITIAL.md Files](#writing-effective-initialmd-files) +- [The PRP Workflow](#the-prp-workflow) +- [Using Examples Effectively](#using-examples-effectively) +- [Best Practices](#best-practices) + +## What is Context Engineering? + +Context Engineering represents a paradigm shift from traditional prompt engineering: + +### Prompt Engineering vs Context Engineering + +**Prompt Engineering:** +- Focuses on clever wording and specific phrasing +- Limited to how you phrase a task +- Like giving someone a sticky note + +**Context Engineering:** +- A complete system for providing comprehensive context +- Includes documentation, examples, rules, patterns, and validation +- Like writing a full screenplay with all the details + +### Why Context Engineering Matters + +1. **Reduces AI Failures**: Most agent failures aren't model failures - they're context failures +2. **Ensures Consistency**: AI follows your project patterns and conventions +3. **Enables Complex Features**: AI can handle multi-step implementations with proper context +4. **Self-Correcting**: Validation loops allow AI to fix its own mistakes + +## Template Structure + +``` +context-engineering-intro/ +├── .claude/ +│ ├── commands/ +│ │ ├── generate-prp.md # Generates comprehensive PRPs +│ │ └── execute-prp.md # Executes PRPs to implement features +│ └── settings.local.json # Claude Code permissions +├── PRPs/ +│ ├── templates/ +│ │ └── prp_base.md # Base template for PRPs +│ └── EXAMPLE_multi_agent_prp.md # Example of a complete PRP +├── examples/ # Your code examples (critical!) +├── CLAUDE.md # Global rules for AI assistant +├── INITIAL.md # Template for feature requests +├── INITIAL_EXAMPLE.md # Example feature request +└── README.md # This file +``` + +This template doesn't focus on RAG and tools with context engineering because I have a LOT more in store for that soon. ;) + +## Step-by-Step Guide + +### 1. Set Up Global Rules (CLAUDE.md) + +The `CLAUDE.md` file contains project-wide rules that the AI assistant will follow in every conversation. The template includes: + +- **Project awareness**: Reading planning docs, checking tasks +- **Code structure**: File size limits, module organization +- **Testing requirements**: Unit test patterns, coverage expectations +- **Style conventions**: Language preferences, formatting rules +- **Documentation standards**: Docstring formats, commenting practices + +**You can use the provided template as-is or customize it for your project.** + +### 2. Create Your Initial Feature Request + +Edit `INITIAL.md` to describe what you want to build: + +```markdown +## FEATURE: +[Describe what you want to build - be specific about functionality and requirements] + +## EXAMPLES: +[List any example files in the examples/ folder and explain how they should be used] + +## DOCUMENTATION: +[Include links to relevant documentation, APIs, or MCP server resources] + +## OTHER CONSIDERATIONS: +[Mention any gotchas, specific requirements, or things AI assistants commonly miss] +``` + +**See `INITIAL_EXAMPLE.md` for a complete example.** + +### 3. Generate the PRP + +PRPs (Product Requirements Prompts) are comprehensive implementation blueprints that include: + +- Complete context and documentation +- Implementation steps with validation +- Error handling patterns +- Test requirements + +They are similar to PRDs (Product Requirements Documents) but are crafted more specifically to instruct an AI coding assistant. + +Run in Claude Code: +```bash +/generate-prp INITIAL.md +``` + +**Note:** The slash commands are custom commands defined in `.claude/commands/`. You can view their implementation: +- `.claude/commands/generate-prp.md` - See how it researches and creates PRPs +- `.claude/commands/execute-prp.md` - See how it implements features from PRPs + +The `$ARGUMENTS` variable in these commands receives whatever you pass after the command name (e.g., `INITIAL.md` or `PRPs/your-feature.md`). + +This command will: +1. Read your feature request +2. Research the codebase for patterns +3. Search for relevant documentation +4. Create a comprehensive PRP in `PRPs/your-feature-name.md` + +### 4. Execute the PRP + +Once generated, execute the PRP to implement your feature: + +```bash +/execute-prp PRPs/your-feature-name.md +``` + +The AI coding assistant will: +1. Read all context from the PRP +2. Create a detailed implementation plan +3. Execute each step with validation +4. Run tests and fix any issues +5. Ensure all success criteria are met + +## Writing Effective INITIAL.md Files + +### Key Sections Explained + +**FEATURE**: Be specific and comprehensive +- ❌ "Build a web scraper" +- ✅ "Build an async web scraper using BeautifulSoup that extracts product data from e-commerce sites, handles rate limiting, and stores results in PostgreSQL" + +**EXAMPLES**: Leverage the examples/ folder +- Place relevant code patterns in `examples/` +- Reference specific files and patterns to follow +- Explain what aspects should be mimicked + +**DOCUMENTATION**: Include all relevant resources +- API documentation URLs +- Library guides +- MCP server documentation +- Database schemas + +**OTHER CONSIDERATIONS**: Capture important details +- Authentication requirements +- Rate limits or quotas +- Common pitfalls +- Performance requirements + +## The PRP Workflow + +### How /generate-prp Works + +The command follows this process: + +1. **Research Phase** + - Analyzes your codebase for patterns + - Searches for similar implementations + - Identifies conventions to follow + +2. **Documentation Gathering** + - Fetches relevant API docs + - Includes library documentation + - Adds gotchas and quirks + +3. **Blueprint Creation** + - Creates step-by-step implementation plan + - Includes validation gates + - Adds test requirements + +4. **Quality Check** + - Scores confidence level (1-10) + - Ensures all context is included + +### How /execute-prp Works + +1. **Load Context**: Reads the entire PRP +2. **Plan**: Creates detailed task list using TodoWrite +3. **Execute**: Implements each component +4. **Validate**: Runs tests and linting +5. **Iterate**: Fixes any issues found +6. **Complete**: Ensures all requirements met + +See `PRPs/EXAMPLE_multi_agent_prp.md` for a complete example of what gets generated. + +## Using Examples Effectively + +The `examples/` folder is **critical** for success. AI coding assistants perform much better when they can see patterns to follow. + +### What to Include in Examples + +1. **Code Structure Patterns** + - How you organize modules + - Import conventions + - Class/function patterns + +2. **Testing Patterns** + - Test file structure + - Mocking approaches + - Assertion styles + +3. **Integration Patterns** + - API client implementations + - Database connections + - Authentication flows + +4. **CLI Patterns** + - Argument parsing + - Output formatting + - Error handling + +### Example Structure + +``` +examples/ +├── README.md # Explains what each example demonstrates +├── cli.py # CLI implementation pattern +├── agent/ # Agent architecture patterns +│ ├── agent.py # Agent creation pattern +│ ├── tools.py # Tool implementation pattern +│ └── providers.py # Multi-provider pattern +└── tests/ # Testing patterns + ├── test_agent.py # Unit test patterns + └── conftest.py # Pytest configuration +``` + +## Best Practices + +### 1. Be Explicit in INITIAL.md +- Don't assume the AI knows your preferences +- Include specific requirements and constraints +- Reference examples liberally + +### 2. Provide Comprehensive Examples +- More examples = better implementations +- Show both what to do AND what not to do +- Include error handling patterns + +### 3. Use Validation Gates +- PRPs include test commands that must pass +- AI will iterate until all validations succeed +- This ensures working code on first try + +### 4. Leverage Documentation +- Include official API docs +- Add MCP server resources +- Reference specific documentation sections + +### 5. Customize CLAUDE.md +- Add your conventions +- Include project-specific rules +- Define coding standards + +## Resources + +- [Claude Code Documentation](https://docs.anthropic.com/en/docs/claude-code) +- [Context Engineering Best Practices](https://www.philschmid.de/context-engineering) \ No newline at end of file diff --git a/README.wehub.md b/README.wehub.md new file mode 100644 index 0000000..dd4ccbc --- /dev/null +++ b/README.wehub.md @@ -0,0 +1,7 @@ +# WeHub 来源说明 + +- 原始项目:`coleam00/context-engineering-intro` +- 原始仓库:https://github.com/coleam00/context-engineering-intro +- 导入方式:上游默认分支的最新快照 +- 原作者、版权和许可证信息以原始仓库及本仓库 LICENSE 为准 +- 本文件仅用于记录来源,不代表 WeHub 是原项目作者 diff --git a/claude-code-full-guide/.claude/agents/documentation-manager.md b/claude-code-full-guide/.claude/agents/documentation-manager.md new file mode 100644 index 0000000..a0728c0 --- /dev/null +++ b/claude-code-full-guide/.claude/agents/documentation-manager.md @@ -0,0 +1,72 @@ +--- +name: documentation-manager +description: "Expert documentation specialist. Proactively updates documentation when code changes are made, ensures README accuracy, and maintains comprehensive technical documentation. Be sure to give this subagent information on the files that were changed so it knows where to look to document changes. Always call this agent after there are code changes." +tools: Read, Write, Edit, MultiEdit, Grep, Glob, ls +--- + +You are a documentation management specialist focused on maintaining high-quality, accurate, and comprehensive documentation for software projects. Your primary responsibility is ensuring that all documentation stays synchronized with code changes and remains helpful for developers. + +## Core Responsibilities + +### 1. Documentation Synchronization +- When code changes are made, proactively check if related documentation needs updates +- Ensure README.md accurately reflects current project state, dependencies, and setup instructions +- Update API documentation when endpoints or interfaces change +- Maintain consistency between code comments and external documentation + +### 2. Documentation Structure +- Organize documentation following best practices: + - README.md for project overview and quick start + - docs/ folder for detailed documentation + - API.md for endpoint documentation + - ARCHITECTURE.md for system design + - CONTRIBUTING.md for contribution guidelines +- Ensure clear navigation between documentation files + +### 3. Documentation Quality Standards +- Write clear, concise explanations that a mid-level developer can understand +- Include code examples for complex concepts +- Add diagrams or ASCII art where visual representation helps +- Ensure all commands and code snippets are tested and accurate +- Use consistent formatting and markdown conventions + +### 4. Proactive Documentation Tasks +When you notice: +- New features added → Update feature documentation +- Dependencies changed → Update installation/setup docs +- API changes → Update API documentation and examples +- Configuration changes → Update configuration guides +- Breaking changes → Add migration guides + +### 5. Documentation Validation +- Check that all links in documentation are valid +- Verify that code examples compile/run correctly +- Ensure setup instructions work on fresh installations +- Validate that documented commands produce expected results + +## Working Process + +1. **Analyze Changes**: When code modifications occur, analyze what was changed +2. **Identify Impact**: Determine which documentation might be affected +3. **Update Systematically**: Update all affected documentation files +4. **Validate Changes**: Ensure documentation remains accurate and helpful +5. **Cross-Reference**: Make sure all related docs are consistent + +## Key Principles + +- Documentation is as important as code +- Out-of-date documentation is worse than no documentation +- Examples are worth a thousand words +- Always consider the reader's perspective +- Test everything you document + +## Output Standards + +When updating documentation: +- Use clear headings and subheadings +- Include table of contents for long documents +- Add timestamps or version numbers when relevant +- Provide both simple and advanced examples +- Link to related documentation sections + +Remember: Good documentation reduces support burden, accelerates onboarding, and makes projects more maintainable. Always strive for clarity, accuracy, and completeness. \ No newline at end of file diff --git a/claude-code-full-guide/.claude/agents/validation-gates.md b/claude-code-full-guide/.claude/agents/validation-gates.md new file mode 100644 index 0000000..bbb8a07 --- /dev/null +++ b/claude-code-full-guide/.claude/agents/validation-gates.md @@ -0,0 +1,133 @@ +--- +name: validation-gates +description: "Testing and validation specialist. Proactively runs tests, validates code changes, ensures quality gates are met, and iterates on fixes until all tests pass. Call this agent after you implement features and need to validate that they were implemented correctly. Be very specific with the features that were implemented and a general idea of what needs to be tested." +tools: Bash, Read, Edit, MultiEdit, Grep, Glob, TodoWrite +--- + +You are a validation and testing specialist responsible for ensuring code quality through comprehensive testing, validation, and iterative improvement. Your role is to act as a quality gatekeeper, ensuring that all code changes meet the project's standards before being considered complete. + +## Core Responsibilities + +### 1. Automated Testing Execution +- Run all relevant tests after code changes +- Execute linting and formatting checks +- Run type checking where applicable +- Perform build validation +- Check for security vulnerabilities + +### 2. Test Coverage Management +- Ensure new code has appropriate test coverage +- Write missing tests for uncovered code paths +- Validate that tests actually test meaningful scenarios +- Maintain or improve overall test coverage metrics + +### 3. Iterative Fix Process +When tests fail: +1. Analyze the failure carefully +2. Identify the root cause +3. Implement a fix +4. Re-run tests to verify the fix +5. Continue iterating until all tests pass +6. Document any non-obvious fixes + +### 4. Validation Gates Checklist +Before marking any task as complete, ensure: +- [ ] All unit tests pass +- [ ] Integration tests pass (if applicable) +- [ ] Linting produces no errors +- [ ] Type checking passes (for typed languages) +- [ ] Code formatting is correct +- [ ] Build succeeds without warnings +- [ ] No security vulnerabilities detected +- [ ] Performance benchmarks met (if applicable) + +### 5. Test Writing Standards +When creating new tests: +- Write descriptive test names that explain what is being tested +- Include at least: + - Happy path test cases + - Edge case scenarios + - Error/failure cases + - Boundary condition tests +- Use appropriate testing patterns (AAA: Arrange, Act, Assert) +- Mock external dependencies appropriately +- Keep tests fast and deterministic + +## Validation Process Workflow + +1. **Initial Assessment** + - Identify what type of validation is needed + - Determine which tests should be run + - Check for existing test suites + +2. **Execute Validation** + ```bash + # Example validation sequence (adapt based on project) + npm run lint + npm run typecheck + npm run test + npm run build + ``` + +3. **Handle Failures** + - Read error messages carefully + - Use grep/search to find related code + - Fix issues one at a time + - Re-run failed tests after each fix + +4. **Iterate Until Success** + - Continue fixing and testing + - Don't give up after first attempt + - Try different approaches if needed + - Ask for help if truly blocked + +5. **Final Verification** + - Run complete test suite one final time + - Verify no regressions were introduced + - Ensure all validation gates pass + +## Common Validation Commands by Language + +### JavaScript/TypeScript +```bash +npm run lint # or: npx eslint . +npm run typecheck # or: npx tsc --noEmit +npm run test # or: npx jest +npm run test:coverage # Check coverage +npm run build # Verify build +``` + +### Python +```bash +ruff check . # Linting +mypy . # Type checking +pytest # Run tests +pytest --cov # With coverage +python -m build # Build check +``` + +### Go +```bash +go fmt ./... # Format +go vet ./... # Linting +go test ./... # Run tests +go build . # Build validation +``` + +## Quality Metrics to Track + +- Test success rate (must be 100%) +- Code coverage (aim for >80%) +- Linting warnings/errors (should be 0) +- Build time (shouldn't increase significantly) +- Test execution time (keep under reasonable limits) + +## Important Principles + +1. **Never Skip Validation**: Even for "simple" changes +2. **Fix, Don't Disable**: Fix failing tests rather than disabling them +3. **Test Behavior, Not Implementation**: Focus on what code does, not how +4. **Fast Feedback**: Run quick tests first, comprehensive tests after +5. **Document Failures**: When tests reveal bugs, document the fix + +Remember: Your role is to ensure that code not only works but is maintainable, reliable, and meets all quality standards. Be thorough, be persistent, and don't compromise on quality. \ No newline at end of file diff --git a/claude-code-full-guide/.claude/commands/execute-parallel.md b/claude-code-full-guide/.claude/commands/execute-parallel.md new file mode 100644 index 0000000..4d522b6 --- /dev/null +++ b/claude-code-full-guide/.claude/commands/execute-parallel.md @@ -0,0 +1,27 @@ +# Parallel Task Version Execution + +## Variables +FEATURE_NAME: $ARGUMENTS +PLAN_TO_EXECUTE: $ARGUMENTS +NUMBER_OF_PARALLEL_WORKTREES: $ARGUMENTS + +## Instructions + +We're going to create NUMBER_OF_PARALLEL_WORKTREES new subagents that use the Task tool to create N versions of the same feature in parallel. + +Be sure to read PLAN_TO_EXECUTE. + +This enables use to concurrently build the same feature in parallel so we can test and validate each subagent's changes in isolation then pick the best changes. + +The first agent will run in trees/-1/ +The second agent will run in trees/-2/ +... +The last agent will run in trees/-/ + +The code in trees/-/ will be identical to the code in the current branch. It will be setup and ready for you to build the feature end to end. + +Each agent will independently implement the engineering plan detailed in PLAN_TO_EXECUTE in their respective workspace. + +When the subagent completes it's work, have the subagent to report their final changes made in a comprehensive `RESULTS.md` file at the root of their respective workspace. + +Make sure agents don't run any tests or other code - focus on the code changes only. \ No newline at end of file diff --git a/claude-code-full-guide/.claude/commands/execute-prp.md b/claude-code-full-guide/.claude/commands/execute-prp.md new file mode 100644 index 0000000..81fb8ea --- /dev/null +++ b/claude-code-full-guide/.claude/commands/execute-prp.md @@ -0,0 +1,40 @@ +# Execute BASE PRP + +Implement a feature using using the PRP file. + +## PRP File: $ARGUMENTS + +## Execution Process + +1. **Load PRP** + - Read the specified PRP file + - Understand all context and requirements + - Follow all instructions in the PRP and extend the research if needed + - Ensure you have all needed context to implement the PRP fully + - Do more web searches and codebase exploration as needed + +2. **ULTRATHINK** + - Think hard before you execute the plan. Create a comprehensive plan addressing all requirements. + - Break down complex tasks into smaller, manageable steps using your todos tools. + - Use the TodoWrite tool to create and track your implementation plan. + - Identify implementation patterns from existing code to follow. + +3. **Execute the plan** + - Execute the PRP + - Implement all the code + +4. **Validate** + - Run each validation command + - Fix any failures + - Re-run until all pass + +5. **Complete** + - Ensure all checklist items done + - Run final validation suite + - Report completion status + - Read the PRP again to ensure you have implemented everything + +6. **Reference the PRP** + - You can always reference the PRP again if needed + +Note: If validation fails, use error patterns in PRP to fix and retry. \ No newline at end of file diff --git a/claude-code-full-guide/.claude/commands/fix-github-issue.md b/claude-code-full-guide/.claude/commands/fix-github-issue.md new file mode 100644 index 0000000..3db87dc --- /dev/null +++ b/claude-code-full-guide/.claude/commands/fix-github-issue.md @@ -0,0 +1,14 @@ +Please analyze and fix the GitHub issue: $ARGUMENTS. + +Follow these steps: + +1. Use `gh issue view` to get the issue details +2. Understand the problem described in the issue +3. Search the codebase for relevant files +4. Implement the necessary changes to fix the issue +5. Write and run tests to verify the fix +6. Ensure code passes linting and type checking +7. Create a descriptive commit message +8. Push and create a PR + +Remember to use the GitHub CLI (`gh`) for all GitHub-related tasks. \ No newline at end of file diff --git a/claude-code-full-guide/.claude/commands/generate-prp.md b/claude-code-full-guide/.claude/commands/generate-prp.md new file mode 100644 index 0000000..e1b4ac8 --- /dev/null +++ b/claude-code-full-guide/.claude/commands/generate-prp.md @@ -0,0 +1,69 @@ +# Create PRP + +## Feature file: $ARGUMENTS + +Generate a complete PRP for general feature implementation with thorough research. Ensure context is passed to the AI agent to enable self-validation and iterative refinement. Read the feature file first to understand what needs to be created, how the examples provided help, and any other considerations. + +The AI agent only gets the context you are appending to the PRP and training data. Assuma the AI agent has access to the codebase and the same knowledge cutoff as you, so its important that your research findings are included or referenced in the PRP. The Agent has Websearch capabilities, so pass urls to documentation and examples. + +## Research Process + +1. **Codebase Analysis** + - Search for similar features/patterns in the codebase + - Identify files to reference in PRP + - Note existing conventions to follow + - Check test patterns for validation approach + +2. **External Research** + - Search for similar features/patterns online + - Library documentation (include specific URLs) + - Implementation examples (GitHub/StackOverflow/blogs) + - Best practices and common pitfalls + +3. **User Clarification** (if needed) + - Specific patterns to mirror and where to find them? + - Integration requirements and where to find them? + +## PRP Generation + +Using PRPs/templates/prp_base.md as template: + +### Critical Context to Include and pass to the AI agent as part of the PRP +- **Documentation**: URLs with specific sections +- **Code Examples**: Real snippets from codebase +- **Gotchas**: Library quirks, version issues +- **Patterns**: Existing approaches to follow + +### Implementation Blueprint +- Start with pseudocode showing approach +- Reference real files for patterns +- Include error handling strategy +- list tasks to be completed to fullfill the PRP in the order they should be completed + +### Validation Gates (Must be Executable) eg for python +```bash +# Syntax/Style +ruff check --fix && mypy . + +# Unit Tests +uv run pytest tests/ -v + +``` + +*** CRITICAL AFTER YOU ARE DONE RESEARCHING AND EXPLORING THE CODEBASE BEFORE YOU START WRITING THE PRP *** + +*** ULTRATHINK ABOUT THE PRP AND PLAN YOUR APPROACH THEN START WRITING THE PRP *** + +## Output +Save as: `PRPs/{feature-name}.md` + +## Quality Checklist +- [ ] All necessary context included +- [ ] Validation gates are executable by AI +- [ ] References existing patterns +- [ ] Clear implementation path +- [ ] Error handling documented + +Score the PRP on a scale of 1-10 (confidence level to succeed in one-pass implementation using claude codes) + +Remember: The goal is one-pass implementation success through comprehensive context. \ No newline at end of file diff --git a/claude-code-full-guide/.claude/commands/prep-parallel.md b/claude-code-full-guide/.claude/commands/prep-parallel.md new file mode 100644 index 0000000..25004ed --- /dev/null +++ b/claude-code-full-guide/.claude/commands/prep-parallel.md @@ -0,0 +1,14 @@ +# Initialize parallel git worktree directories for parallel Claude Code agents + +## Variables +FEATURE_NAME: $ARGUMENTS +NUMBER_OF_PARALLEL_WORKTREES: $ARGUMENTS + +## Execute these commands +> Execute the loop in parallel with the Batch and Task tool + +- create a new dir `trees/` +- for i in NUMBER_OF_PARALLEL_WORKTREES + - RUN `git worktree add -b FEATURE_NAME-i ./trees/FEATURE_NAME-i` + - RUN `cd trees/FEATURE_NAME-i`, `git ls-files` to validate +- RUN `git worktree list` to verify all trees were created properly \ No newline at end of file diff --git a/claude-code-full-guide/.claude/commands/primer.md b/claude-code-full-guide/.claude/commands/primer.md new file mode 100644 index 0000000..9ad0366 --- /dev/null +++ b/claude-code-full-guide/.claude/commands/primer.md @@ -0,0 +1,16 @@ +# Prime Context for Claude Code + +Use the command `tree` to get an understanding of the project structure. + +Start with reading the CLAUDE.md file if it exists to get an understanding of the project. + +Read the README.md file to get an understanding of the project. + +Read key files in the src/ or root directory + +Explain back to me: +- Project structure +- Project purpose and goals +- Key files and their purposes +- Any important dependencies +- Any important configuration files \ No newline at end of file diff --git a/claude-code-full-guide/.claude/hooks/README.md b/claude-code-full-guide/.claude/hooks/README.md new file mode 100644 index 0000000..0eafda8 --- /dev/null +++ b/claude-code-full-guide/.claude/hooks/README.md @@ -0,0 +1,109 @@ +# Claude Code Hooks Examples + +This directory contains example hooks for Claude Code that demonstrate how to add deterministic behavior to your AI coding workflow. + +## What are Hooks? + +Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. They provide control over Claude's behavior, ensuring certain actions always happen rather than relying on the AI to choose to run them. + +## Files in this Directory + +1. **format-after-edit.sh** - A PostToolUse hook that automatically formats code after file edits +2. **example-hook-config.json** - Example configuration showing how to set up various hooks + +## How to Use These Hooks + +### Option 1: Copy to Your Settings File + +Copy the hooks configuration from `example-hook-config.json` to your Claude Code settings: + +**Project-specific** (`.claude/settings.json`): +```bash +# Create settings file if it doesn't exist +touch .claude/settings.json + +# Add hooks configuration from example-hook-config.json +``` + +**User-wide** (`~/.claude/settings.json`): +```bash +# Apply hooks to all Claude Code sessions +cp example-hook-config.json ~/.claude/settings.json +``` + +### Option 2: Use Individual Hooks + +1. Copy the hook script to your project: +```bash +cp format-after-edit.sh /your/project/.claude/hooks/ +chmod +x /your/project/.claude/hooks/format-after-edit.sh +``` + +2. Add to your settings.json: +```json +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { + "type": "command", + "command": ".claude/hooks/format-after-edit.sh" + } + ] + } + ] + } +} +``` + +## Available Hook Events + +- **PreToolUse**: Before tool execution (can block tools) +- **PostToolUse**: After successful tool completion +- **UserPromptSubmit**: When user submits a prompt +- **SubagentStop**: When a subagent completes +- **Stop**: When main agent finishes responding +- **Notification**: During system notifications +- **PreCompact**: Before context compaction +- **SessionStart**: At session initialization + +## Creating Your Own Hooks + +1. Write a shell script that: + - Reads JSON input from stdin + - Processes the input + - Returns JSON output (empty `{}` for success) + - Can return `{"action": "block", "message": "reason"}` to block operations + +2. Make it executable: +```bash +chmod +x your-hook.sh +``` + +3. Add to settings.json with appropriate matcher and event + +## Security Considerations + +- Hooks execute arbitrary shell commands +- Always validate and sanitize inputs +- Use full paths to avoid PATH manipulation +- Be careful with file operations +- Test hooks thoroughly before deployment + +## Debugging Hooks + +Run Claude Code with debug flag to see hook execution: +```bash +claude --debug +``` + +This will show: +- Which hooks are triggered +- Input/output for each hook +- Any errors or issues + +## Integration with Subagents + +The example configuration includes a hook that integrates with the validation-gates subagent, demonstrating how hooks and subagents can work together for a more robust development workflow. \ No newline at end of file diff --git a/claude-code-full-guide/.claude/hooks/example-hook-config.json b/claude-code-full-guide/.claude/hooks/example-hook-config.json new file mode 100644 index 0000000..1a90cdc --- /dev/null +++ b/claude-code-full-guide/.claude/hooks/example-hook-config.json @@ -0,0 +1,50 @@ +{ + "hooks": { + "PostToolUse": [ + { + "matcher": "Edit|Write|MultiEdit", + "hooks": [ + { + "type": "command", + "command": ".claude/hooks/log-tool-usage.sh", + "description": "Automatically logs file edits" + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "bash -c 'input=$(cat); cmd=$(echo \"$input\" | jq -r \".tool_input.command // empty\"); if [[ \"$cmd\" =~ (rm|delete).*(\\*|\\.env|credentials|secret) ]]; then echo \"{\\\"action\\\": \\\"block\\\", \\\"message\\\": \\\"Dangerous command blocked: $cmd\\\"}\"; else echo \"{}\"; fi'", + "description": "Block dangerous bash commands" + } + ] + } + ], + "SubagentStop": [ + { + "hooks": [ + { + "type": "command", + "command": "bash -c 'input=$(cat); agent=$(echo \"$input\" | jq -r \".subagent_name // empty\"); if [[ \"$agent\" == \"validation-gates\" ]]; then echo \"Validation gates completed. Running final checks...\" >&2; fi; echo \"{}\"'", + "description": "Log when validation-gates subagent completes" + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "bash -c 'input=$(cat); prompt=$(echo \"$input\" | jq -r \".prompt // empty\"); if [[ \"$prompt\" =~ (test|validate|check) ]] && [[ ! \"$prompt\" =~ (skip|no|without).*(test|validation) ]]; then echo \"Reminder: Use the validation-gates subagent to ensure comprehensive testing.\" >&2; fi; echo \"{}\"'", + "description": "Remind about validation when testing is mentioned" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/claude-code-full-guide/.claude/hooks/log-tool-usage.sh b/claude-code-full-guide/.claude/hooks/log-tool-usage.sh new file mode 100644 index 0000000..86f6cbc --- /dev/null +++ b/claude-code-full-guide/.claude/hooks/log-tool-usage.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# PostToolUse hook: Log all tool usage for tracking and debugging +# This hook runs after any tool execution to maintain an audit log + +timestamp=$(date '+%Y-%m-%d %H:%M:%S') + +# Create logs directory if it doesn't exist +mkdir -p .claude/logs + +# Log the tool usage +echo "[$timestamp] Claude made an edit " >> .claude/logs/tool-usage.log + +# Always return success to avoid blocking tools +echo "{}" \ No newline at end of file diff --git a/claude-code-full-guide/.devcontainer/Dockerfile b/claude-code-full-guide/.devcontainer/Dockerfile new file mode 100644 index 0000000..af83a55 --- /dev/null +++ b/claude-code-full-guide/.devcontainer/Dockerfile @@ -0,0 +1,78 @@ +FROM node:20 + +ARG TZ +ENV TZ="$TZ" + +# Install basic development tools and iptables/ipset +RUN apt update && apt install -y less \ + git \ + procps \ + sudo \ + fzf \ + zsh \ + man-db \ + unzip \ + gnupg2 \ + gh \ + iptables \ + ipset \ + iproute2 \ + dnsutils \ + aggregate \ + jq + +# Ensure default node user has access to /usr/local/share +RUN mkdir -p /usr/local/share/npm-global && \ + chown -R node:node /usr/local/share + +ARG USERNAME=node + +# Persist bash history. +RUN SNIPPET="export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhistory/.bash_history" \ + && mkdir /commandhistory \ + && touch /commandhistory/.bash_history \ + && chown -R $USERNAME /commandhistory + +# Set `DEVCONTAINER` environment variable to help with orientation +ENV DEVCONTAINER=true + +# Create workspace and config directories and set permissions +RUN mkdir -p /workspace /home/node/.claude && \ + chown -R node:node /workspace /home/node/.claude + +WORKDIR /workspace + +RUN ARCH=$(dpkg --print-architecture) && \ + wget "https://github.com/dandavison/delta/releases/download/0.18.2/git-delta_0.18.2_${ARCH}.deb" && \ + sudo dpkg -i "git-delta_0.18.2_${ARCH}.deb" && \ + rm "git-delta_0.18.2_${ARCH}.deb" + +# Set up non-root user +USER node + +# Install global packages +ENV NPM_CONFIG_PREFIX=/usr/local/share/npm-global +ENV PATH=$PATH:/usr/local/share/npm-global/bin + +# Set the default shell to zsh rather than sh +ENV SHELL=/bin/zsh + +# Default powerline10k theme +RUN sh -c "$(wget -O- https://github.com/deluan/zsh-in-docker/releases/download/v1.2.0/zsh-in-docker.sh)" -- \ + -p git \ + -p fzf \ + -a "source /usr/share/doc/fzf/examples/key-bindings.zsh" \ + -a "source /usr/share/doc/fzf/examples/completion.zsh" \ + -a "export PROMPT_COMMAND='history -a' && export HISTFILE=/commandhistory/.bash_history" \ + -x + +# Install Claude +RUN npm install -g @anthropic-ai/claude-code + +# Copy and set up firewall script +COPY init-firewall.sh /usr/local/bin/ +USER root +RUN chmod +x /usr/local/bin/init-firewall.sh && \ + echo "node ALL=(root) NOPASSWD: /usr/local/bin/init-firewall.sh" > /etc/sudoers.d/node-firewall && \ + chmod 0440 /etc/sudoers.d/node-firewall +USER node \ No newline at end of file diff --git a/claude-code-full-guide/.devcontainer/devcontainer.json b/claude-code-full-guide/.devcontainer/devcontainer.json new file mode 100644 index 0000000..89cff24 --- /dev/null +++ b/claude-code-full-guide/.devcontainer/devcontainer.json @@ -0,0 +1,52 @@ +{ + "name": "Claude Code Sandbox", + "build": { + "dockerfile": "Dockerfile", + "args": { + "TZ": "${localEnv:TZ:America/Los_Angeles}" + } + }, + "runArgs": [ + "--cap-add=NET_ADMIN", + "--cap-add=NET_RAW" + ], + "customizations": { + "vscode": { + "extensions": [ + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "eamodio.gitlens" + ], + "settings": { + "editor.formatOnSave": true, + "editor.defaultFormatter": "esbenp.prettier-vscode", + "editor.codeActionsOnSave": { + "source.fixAll.eslint": "explicit" + }, + "terminal.integrated.defaultProfile.linux": "zsh", + "terminal.integrated.profiles.linux": { + "bash": { + "path": "bash", + "icon": "terminal-bash" + }, + "zsh": { + "path": "zsh" + } + } + } + } + }, + "remoteUser": "node", + "mounts": [ + "source=claude-code-bashhistory,target=/commandhistory,type=volume", + "source=claude-code-config,target=/home/node/.claude,type=volume" + ], + "remoteEnv": { + "NODE_OPTIONS": "--max-old-space-size=4096", + "CLAUDE_CONFIG_DIR": "/home/node/.claude", + "POWERLEVEL9K_DISABLE_GITSTATUS": "true" + }, + "workspaceMount": "source=${localWorkspaceFolder},target=/workspace,type=bind,consistency=delegated", + "workspaceFolder": "/workspace", + "postCreateCommand": "sudo /usr/local/bin/init-firewall.sh" + } \ No newline at end of file diff --git a/claude-code-full-guide/.devcontainer/init-firewall.sh b/claude-code-full-guide/.devcontainer/init-firewall.sh new file mode 100644 index 0000000..ea63ff8 --- /dev/null +++ b/claude-code-full-guide/.devcontainer/init-firewall.sh @@ -0,0 +1,118 @@ +#!/bin/bash +set -euo pipefail # Exit on error, undefined vars, and pipeline failures +IFS=$'\n\t' # Stricter word splitting + +# Flush existing rules and delete existing ipsets +iptables -F +iptables -X +iptables -t nat -F +iptables -t nat -X +iptables -t mangle -F +iptables -t mangle -X +ipset destroy allowed-domains 2>/dev/null || true + +# First allow DNS and localhost before any restrictions +# Allow outbound DNS +iptables -A OUTPUT -p udp --dport 53 -j ACCEPT +# Allow inbound DNS responses +iptables -A INPUT -p udp --sport 53 -j ACCEPT +# Allow outbound SSH +iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT +# Allow inbound SSH responses +iptables -A INPUT -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT +# Allow localhost +iptables -A INPUT -i lo -j ACCEPT +iptables -A OUTPUT -o lo -j ACCEPT + +# Create ipset with CIDR support +ipset create allowed-domains hash:net + +# Fetch GitHub meta information and aggregate + add their IP ranges +echo "Fetching GitHub IP ranges..." +gh_ranges=$(curl -s https://api.github.com/meta) +if [ -z "$gh_ranges" ]; then + echo "ERROR: Failed to fetch GitHub IP ranges" + exit 1 +fi + +if ! echo "$gh_ranges" | jq -e '.web and .api and .git' >/dev/null; then + echo "ERROR: GitHub API response missing required fields" + exit 1 +fi + +echo "Processing GitHub IPs..." +while read -r cidr; do + if [[ ! "$cidr" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}$ ]]; then + echo "ERROR: Invalid CIDR range from GitHub meta: $cidr" + exit 1 + fi + echo "Adding GitHub range $cidr" + ipset add allowed-domains "$cidr" +done < <(echo "$gh_ranges" | jq -r '(.web + .api + .git)[]' | aggregate -q) + +# Resolve and add other allowed domains +for domain in \ + "registry.npmjs.org" \ + "api.anthropic.com" \ + "sentry.io" \ + "statsig.anthropic.com" \ + "statsig.com"; do + echo "Resolving $domain..." + ips=$(dig +short A "$domain") + if [ -z "$ips" ]; then + echo "ERROR: Failed to resolve $domain" + exit 1 + fi + + while read -r ip; do + if [[ ! "$ip" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then + echo "ERROR: Invalid IP from DNS for $domain: $ip" + exit 1 + fi + echo "Adding $ip for $domain" + ipset add allowed-domains "$ip" + done < <(echo "$ips") +done + +# Get host IP from default route +HOST_IP=$(ip route | grep default | cut -d" " -f3) +if [ -z "$HOST_IP" ]; then + echo "ERROR: Failed to detect host IP" + exit 1 +fi + +HOST_NETWORK=$(echo "$HOST_IP" | sed "s/\.[0-9]*$/.0\/24/") +echo "Host network detected as: $HOST_NETWORK" + +# Set up remaining iptables rules +iptables -A INPUT -s "$HOST_NETWORK" -j ACCEPT +iptables -A OUTPUT -d "$HOST_NETWORK" -j ACCEPT + +# Set default policies to DROP first +iptables -P INPUT DROP +iptables -P FORWARD DROP +iptables -P OUTPUT DROP + +# First allow established connections for already approved traffic +iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT +iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT + +# Then allow only specific outbound traffic to allowed domains +iptables -A OUTPUT -m set --match-set allowed-domains dst -j ACCEPT + +echo "Firewall configuration complete" +echo "Verifying firewall rules..." +if curl --connect-timeout 5 https://example.com >/dev/null 2>&1; then + echo "ERROR: Firewall verification failed - was able to reach https://example.com" + exit 1 +else + echo "Firewall verification passed - unable to reach https://example.com as expected" +fi + +# Verify GitHub API access +if ! curl --connect-timeout 5 https://api.github.com/zen >/dev/null 2>&1; then + echo "ERROR: Firewall verification failed - unable to reach https://api.github.com" + exit 1 +else + echo "Firewall verification passed - able to reach https://api.github.com as expected" +fi \ No newline at end of file diff --git a/claude-code-full-guide/CLAUDE.md b/claude-code-full-guide/CLAUDE.md new file mode 100644 index 0000000..2a2bffe --- /dev/null +++ b/claude-code-full-guide/CLAUDE.md @@ -0,0 +1,759 @@ +# CLAUDE.md + +This file provides comprehensive guidance to Claude Code when working with Python code in this repository. + +## Core Development Philosophy + +### KISS (Keep It Simple, Stupid) + +Simplicity should be a key goal in design. Choose straightforward solutions over complex ones whenever possible. Simple solutions are easier to understand, maintain, and debug. + +### YAGNI (You Aren't Gonna Need It) + +Avoid building functionality on speculation. Implement features only when they are needed, not when you anticipate they might be useful in the future. + +### Design Principles + +- **Dependency Inversion**: High-level modules should not depend on low-level modules. Both should depend on abstractions. +- **Open/Closed Principle**: Software entities should be open for extension but closed for modification. +- **Single Responsibility**: Each function, class, and module should have one clear purpose. +- **Fail Fast**: Check for potential errors early and raise exceptions immediately when issues occur. + +## 🧱 Code Structure & Modularity + +### File and Function Limits + +- **Never create a file longer than 500 lines of code**. If approaching this limit, refactor by splitting into modules. +- **Functions should be under 50 lines** with a single, clear responsibility. +- **Classes should be under 100 lines** and represent a single concept or entity. +- **Organize code into clearly separated modules**, grouped by feature or responsibility. +- **Line lenght should be max 100 characters** ruff rule in pyproject.toml +- **Use venv_linux** (the virtual environment) whenever executing Python commands, including for unit tests. + +### Project Architecture + +Follow strict vertical slice architecture with tests living next to the code they test: + +``` +src/project/ + __init__.py + main.py + tests/ + test_main.py + conftest.py + + # Core modules + database/ + __init__.py + connection.py + models.py + tests/ + test_connection.py + test_models.py + + auth/ + __init__.py + authentication.py + authorization.py + tests/ + test_authentication.py + test_authorization.py + + # Feature slices + features/ + user_management/ + __init__.py + handlers.py + validators.py + tests/ + test_handlers.py + test_validators.py + + payment_processing/ + __init__.py + processor.py + gateway.py + tests/ + test_processor.py + test_gateway.py +``` + +## 🛠️ Development Environment + +### UV Package Management + +This project uses UV for blazing-fast Python package and environment management. + +```bash +# Install UV (if not already installed) +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Create virtual environment +uv venv + +# Sync dependencies +uv sync + +# Add a package ***NEVER UPDATE A DEPENDENCY DIRECTLY IN PYPROJECT.toml*** +# ALWAYS USE UV ADD +uv add requests + +# Add development dependency +uv add --dev pytest ruff mypy + +# Remove a package +uv remove requests + +# Run commands in the environment +uv run python script.py +uv run pytest +uv run ruff check . + +# Install specific Python version +uv python install 3.12 +``` + +### Development Commands + +```bash +# Run all tests +uv run pytest + +# Run specific tests with verbose output +uv run pytest tests/test_module.py -v + +# Run tests with coverage +uv run pytest --cov=src --cov-report=html + +# Format code +uv run ruff format . + +# Check linting +uv run ruff check . + +# Fix linting issues automatically +uv run ruff check --fix . + +# Type checking +uv run mypy src/ + +# Run pre-commit hooks +uv run pre-commit run --all-files +``` + +## 📋 Style & Conventions + +### Python Style Guide + +- **Follow PEP8** with these specific choices: + - Line length: 100 characters (set by Ruff in pyproject.toml) + - Use double quotes for strings + - Use trailing commas in multi-line structures +- **Always use type hints** for function signatures and class attributes +- **Format with `ruff format`** (faster alternative to Black) +- **Use `pydantic` v2** for data validation and settings management + +### Docstring Standards + +Use Google-style docstrings for all public functions, classes, and modules: + +```python +def calculate_discount( + price: Decimal, + discount_percent: float, + min_amount: Decimal = Decimal("0.01") +) -> Decimal: + """ + Calculate the discounted price for a product. + + Args: + price: Original price of the product + discount_percent: Discount percentage (0-100) + min_amount: Minimum allowed final price + + Returns: + Final price after applying discount + + Raises: + ValueError: If discount_percent is not between 0 and 100 + ValueError: If final price would be below min_amount + + Example: + >>> calculate_discount(Decimal("100"), 20) + Decimal('80.00') + """ +``` + +### Naming Conventions + +- **Variables and functions**: `snake_case` +- **Classes**: `PascalCase` +- **Constants**: `UPPER_SNAKE_CASE` +- **Private attributes/methods**: `_leading_underscore` +- **Type aliases**: `PascalCase` +- **Enum values**: `UPPER_SNAKE_CASE` + +## 🧪 Testing Strategy + +### Test-Driven Development (TDD) + +1. **Write the test first** - Define expected behavior before implementation +2. **Watch it fail** - Ensure the test actually tests something +3. **Write minimal code** - Just enough to make the test pass +4. **Refactor** - Improve code while keeping tests green +5. **Repeat** - One test at a time + +### Testing Best Practices + +```python +# Always use pytest fixtures for setup +import pytest +from datetime import datetime + +@pytest.fixture +def sample_user(): + """Provide a sample user for testing.""" + return User( + id=123, + name="Test User", + email="test@example.com", + created_at=datetime.now() + ) + +# Use descriptive test names +def test_user_can_update_email_when_valid(sample_user): + """Test that users can update their email with valid input.""" + new_email = "newemail@example.com" + sample_user.update_email(new_email) + assert sample_user.email == new_email + +# Test edge cases and error conditions +def test_user_update_email_fails_with_invalid_format(sample_user): + """Test that invalid email formats are rejected.""" + with pytest.raises(ValidationError) as exc_info: + sample_user.update_email("not-an-email") + assert "Invalid email format" in str(exc_info.value) +``` + +### Test Organization + +- Unit tests: Test individual functions/methods in isolation +- Integration tests: Test component interactions +- End-to-end tests: Test complete user workflows +- Keep test files next to the code they test +- Use `conftest.py` for shared fixtures +- Aim for 80%+ code coverage, but focus on critical paths + +## 🚨 Error Handling + +### Exception Best Practices + +```python +# Create custom exceptions for your domain +class PaymentError(Exception): + """Base exception for payment-related errors.""" + pass + +class InsufficientFundsError(PaymentError): + """Raised when account has insufficient funds.""" + def __init__(self, required: Decimal, available: Decimal): + self.required = required + self.available = available + super().__init__( + f"Insufficient funds: required {required}, available {available}" + ) + +# Use specific exception handling +try: + process_payment(amount) +except InsufficientFundsError as e: + logger.warning(f"Payment failed: {e}") + return PaymentResult(success=False, reason="insufficient_funds") +except PaymentError as e: + logger.error(f"Payment error: {e}") + return PaymentResult(success=False, reason="payment_error") + +# Use context managers for resource management +from contextlib import contextmanager + +@contextmanager +def database_transaction(): + """Provide a transactional scope for database operations.""" + conn = get_connection() + trans = conn.begin_transaction() + try: + yield conn + trans.commit() + except Exception: + trans.rollback() + raise + finally: + conn.close() +``` + +### Logging Strategy + +```python +import logging +from functools import wraps + +# Configure structured logging +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' +) + +logger = logging.getLogger(__name__) + +# Log function entry/exit for debugging +def log_execution(func): + @wraps(func) + def wrapper(*args, **kwargs): + logger.debug(f"Entering {func.__name__}") + try: + result = func(*args, **kwargs) + logger.debug(f"Exiting {func.__name__} successfully") + return result + except Exception as e: + logger.exception(f"Error in {func.__name__}: {e}") + raise + return wrapper +``` + +## 🔧 Configuration Management + +### Environment Variables and Settings + +```python +from pydantic_settings import BaseSettings +from functools import lru_cache + +class Settings(BaseSettings): + """Application settings with validation.""" + app_name: str = "MyApp" + debug: bool = False + database_url: str + redis_url: str = "redis://localhost:6379" + api_key: str + max_connections: int = 100 + + class Config: + env_file = ".env" + env_file_encoding = "utf-8" + case_sensitive = False + +@lru_cache() +def get_settings() -> Settings: + """Get cached settings instance.""" + return Settings() + +# Usage +settings = get_settings() +``` + +## 🏗️ Data Models and Validation + +### Example Pydantic Models strict with pydantic v2 + +```python +from pydantic import BaseModel, Field, validator, EmailStr +from datetime import datetime +from typing import Optional, List +from decimal import Decimal + +class ProductBase(BaseModel): + """Base product model with common fields.""" + name: str = Field(..., min_length=1, max_length=255) + description: Optional[str] = None + price: Decimal = Field(..., gt=0, decimal_places=2) + category: str + tags: List[str] = [] + + @validator('price') + def validate_price(cls, v): + if v > Decimal('1000000'): + raise ValueError('Price cannot exceed 1,000,000') + return v + + class Config: + json_encoders = { + Decimal: str, + datetime: lambda v: v.isoformat() + } + +class ProductCreate(ProductBase): + """Model for creating new products.""" + pass + +class ProductUpdate(BaseModel): + """Model for updating products - all fields optional.""" + name: Optional[str] = Field(None, min_length=1, max_length=255) + description: Optional[str] = None + price: Optional[Decimal] = Field(None, gt=0, decimal_places=2) + category: Optional[str] = None + tags: Optional[List[str]] = None + +class Product(ProductBase): + """Complete product model with database fields.""" + id: int + created_at: datetime + updated_at: datetime + is_active: bool = True + + class Config: + from_attributes = True # Enable ORM mode +``` + +## 🔄 Git Workflow + +### Branch Strategy + +- `main` - Production-ready code +- `develop` - Integration branch for features +- `feature/*` - New features +- `fix/*` - Bug fixes +- `docs/*` - Documentation updates +- `refactor/*` - Code refactoring +- `test/*` - Test additions or fixes + +### Commit Message Format + +Never include claude code, or written by claude code in commit messages + +``` +(): + + + +