Skip to content

Commit 2bd179d

Browse files
committed
Adds initial AI Agent constitution
Establishes foundational governance for the AI Agent project by adding an initial constitution. The constitution defines core principles, security standards, development workflow, and governance rules. This ensures code quality, security, and maintainability across the project.
1 parent b6d31b3 commit 2bd179d

File tree

2 files changed

+190
-169
lines changed

2 files changed

+190
-169
lines changed

.github/copilot-instructions.md

Lines changed: 0 additions & 134 deletions
Original file line numberDiff line numberDiff line change
@@ -7,137 +7,3 @@ You are an AI coding assistant for the ai-agent Python project. Generate high-qu
77
- Python version: 3.9+
88
- Test location: All tests MUST be placed in the `tests` folder
99
- Architecture: Modular design with domain-specific packages in `src/<domain>`
10-
11-
## Code Quality Requirements
12-
- Follow semantic versioning (`vX.Y.Z`)
13-
- Code must pass `pylint`, `flake8`, `mypy`, and `black` checks
14-
- Use 4-space indentation, max 88 characters per line
15-
- Functions must be under 50 lines and follow single responsibility principle
16-
- Prefer pure functions with dependency injection
17-
- Import order: stdlib, third-party, local imports
18-
- Auto-format with `black` and `isort`
19-
20-
## Documentation Standards (CRITICAL)
21-
1. **NO DOCSTRINGS OR COMMENTS** unless absolutely necessary
22-
2. Code must be self-documenting through descriptive names
23-
3. Use comprehensive type hints instead of parameter descriptions
24-
4. If comments are unavoidable:
25-
- Explain WHY, never WHAT
26-
- Use minimal prefixes (# NOTE: or # TODO: TICKET-123)
27-
- Maximum 2 lines
28-
5. **NEVER generate** verbose multi-line docstrings with parameter descriptions, return values, examples, or usage notes
29-
30-
## Security & Testing
31-
- No hard-coded secrets (use environment variables)
32-
- Validate all input using dataclasses, Pydantic, or attrs
33-
- Unit-test logic with pytest, integration-test I/O boundaries
34-
- Always use virtual environments for isolation
35-
36-
## Virtual Environment Setup
37-
```bash
38-
python3 -m venv .venv
39-
source .venv/bin/activate # On Windows: venv\Scripts\activate
40-
pip install -r requirements.txt
41-
```
42-
43-
## Folder Responsibilities
44-
- `.github` - Houses GitHub prompts (.github/prompts/), workflows(.github/workflows/), and Copilot instructions. Used by GitHub Actions and Copilot Chat.
45-
- `tests` - Contains all tests for the application
46-
- Root files
47-
- .env – environment variables (managed via GitHub and Context7 MCP Servers)
48-
- README.md, LICENSE – project overview and licensing
49-
50-
# Steps
51-
1. Analyze the coding task and determine the appropriate `src/<domain>` location
52-
2. Design the solution using modular, pure functions with proper type hints
53-
3. Generate code with descriptive variable/function names that eliminate need for comments
54-
4. Include comprehensive type annotations for all parameters and return values
55-
5. Structure imports in the correct order (stdlib, third-party, local)
56-
6. If tests are needed, place them in the `tests` folder with appropriate naming
57-
58-
# Output Format
59-
Generate complete, production-ready Python code that:
60-
- Follows all coding standards without deviation
61-
- Includes proper type hints for all functions
62-
- Uses descriptive names that make the code self-documenting
63-
- Contains minimal to no comments/docstrings
64-
- Is properly formatted for `black` and linting tools
65-
- Includes import statements in the correct order
66-
67-
# Examples
68-
69-
## Example 1: Service Implementation
70-
71-
**Input**: "Create a user authentication service"
72-
**Output**:
73-
```python
74-
from typing import Optional
75-
from dataclasses import dataclass
76-
import bcrypt
77-
from jose import jwt
78-
79-
@dataclass
80-
class AuthenticationResult:
81-
is_valid: bool
82-
user_id: Optional[str] = None
83-
error_message: Optional[str] = None
84-
85-
def hash_password(plain_password: str) -> str:
86-
return bcrypt.hashpw(plain_password.encode(), bcrypt.gensalt()).decode()
87-
88-
def verify_password(plain_password: str, hashed_password: str) -> bool:
89-
return bcrypt.checkpw(plain_password.encode(), hashed_password.encode())
90-
91-
def authenticate_user(username: str, password: str, stored_hash: str) -> AuthenticationResult:
92-
if not verify_password(password, stored_hash):
93-
return AuthenticationResult(False, error_message="Invalid credentials")
94-
return AuthenticationResult(True, user_id=username)
95-
```
96-
97-
## Example 2: Test Implementation
98-
99-
**Input**: "Write a test for the authentication service"
100-
**Output** (in `tests/test_auth_service.py`):
101-
```python
102-
import pytest
103-
from src.auth.service import hash_password, verify_password, authenticate_user, AuthenticationResult
104-
105-
def test_hash_password_creates_valid_hash():
106-
password = "test_password_123"
107-
hashed = hash_password(password)
108-
assert hashed != password
109-
assert len(hashed) > 20
110-
111-
def test_verify_password_with_correct_password():
112-
password = "test_password_123"
113-
hashed = hash_password(password)
114-
assert verify_password(password, hashed) is True
115-
116-
def test_authenticate_user_with_valid_credentials():
117-
password = "test_password_123"
118-
hashed = hash_password(password)
119-
result = authenticate_user("testuser", password, hashed)
120-
assert result.is_valid is True
121-
assert result.user_id == "testuser"
122-
assert result.error_message is None
123-
```
124-
125-
# CI/CD Requirements
126-
- Always activate virtual environment in CI pipelines:
127-
```yaml
128-
- name: Set up Python
129-
run: |
130-
python3 -m venv .venv
131-
source .venv/bin/activate
132-
```
133-
- Run `pytest --cov=src` and check coverage in CI
134-
- Run security checks: `bandit`, Safety, CodeQL, Dependabot
135-
- Fail build on critical CVEs
136-
137-
# Notes
138-
- All generated code will be rejected if it contains unnecessary docstrings or comments
139-
- Type hints are mandatory and replace the need for parameter documentation
140-
- Function and variable names must be descriptive enough to eliminate ambiguity
141-
- Virtual environment setup is required before running any code
142-
- Security validation using dataclasses/Pydantic is non-negotiable for input handling
143-
- Each unnecessary comment is technical debt - the code itself should communicate intent

.specify/memory/constitution.md

Lines changed: 190 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,205 @@
1-
# [PROJECT_NAME] Constitution
2-
<!-- Example: Spec Constitution, TaskFlow Constitution, etc. -->
1+
<!--
2+
SYNC IMPACT REPORT
3+
==================
4+
Version Change: Template → 1.0.0
5+
6+
Modified Principles:
7+
- PRINCIPLE_1_NAME → I. Modular Architecture & Separation of Concerns
8+
- PRINCIPLE_2_NAME → II. Code Readability & Self-Documentation
9+
- PRINCIPLE_3_NAME → III. Test-First Development (NON-NEGOTIABLE)
10+
- PRINCIPLE_4_NAME → IV. Type Safety & Static Analysis
11+
- PRINCIPLE_5_NAME → V. Python Best Practices
12+
13+
Added Sections:
14+
- Core Principles (5 principles defined)
15+
- Security & Quality Standards
16+
- Development Workflow & Review Process
17+
- Governance
18+
19+
Templates Requiring Updates:
20+
✅ plan-template.md - Reviewed, constitution check section aligns
21+
✅ spec-template.md - Reviewed, requirements and acceptance criteria align
22+
✅ tasks-template.md - Reviewed, test-first and phase structure aligns
23+
✅ coding-guidelines.instructions.md - Source of truth for principles
24+
25+
Follow-up TODOs: None - all principles fully defined
26+
27+
Rationale for Version 1.0.0:
28+
- Initial ratification of constitution from template
29+
- Establishes foundational governance for AI Agent project
30+
- All principles and sections are now concrete and actionable
31+
-->
32+
33+
# AI Agent Constitution
334

435
## Core Principles
536

6-
### [PRINCIPLE_1_NAME]
7-
<!-- Example: I. Library-First -->
8-
[PRINCIPLE_1_DESCRIPTION]
9-
<!-- Example: Every feature starts as a standalone library; Libraries must be self-contained, independently testable, documented; Clear purpose required - no organizational-only libraries -->
37+
### I. Modular Architecture & Separation of Concerns
38+
39+
Every component in the AI Agent project MUST adhere to strict modularity and separation of concerns:
40+
41+
- **One domain = one package**: Each logical domain (e.g., `llm`, `rag`, `tools`, `api`) MUST reside in its own package under `src/<domain>`
42+
- **Single Responsibility Principle**: Each module, class, and function MUST have exactly one reason to change
43+
- **Clear boundaries**: Domain packages MUST expose well-defined interfaces and MUST NOT leak implementation details
44+
- **Dependency direction**: Dependencies MUST flow inward toward core business logic; outer layers (API, UI) depend on inner layers (services, models), never vice versa
45+
- **Isolated side effects**: Pure business logic MUST be separated from side effects (I/O, database, external APIs) which belong in service layers
46+
47+
**Rationale**: Modular architecture enables independent development, testing, and evolution of components. It reduces coupling, improves maintainability, and allows teams to work in parallel without conflicts.
48+
49+
### II. Code Readability & Self-Documentation
50+
51+
Code MUST be written to be immediately understandable by humans without requiring extensive comments:
52+
53+
- **Descriptive naming**: Variable, function, and class names MUST clearly express intent and purpose
54+
- Classes: PascalCase (e.g., `SessionManager`, `DebugCapture`)
55+
- Functions/variables: snake_case (e.g., `capture_event`, `session_id`)
56+
- Constants: ALL_CAPS (e.g., `MAX_EVENTS_PER_SESSION`)
57+
- **Type hints required**: All function parameters and return values MUST include type hints for clarity and tool support
58+
- **Self-explanatory structure**: Code structure and flow MUST convey logic; avoid "clever" code that requires explanation
59+
- **Minimal comments**: Comments explain WHY decisions were made, not WHAT code does; if code needs WHAT comments, refactor for clarity
60+
- **Comment discipline**: Comments MUST be under 2 lines; use `# NOTE:` or `# TODO: <ticket-id>` prefixes; delete expired comments
61+
62+
**Rationale**: Self-documenting code reduces cognitive load, speeds up onboarding, and prevents documentation drift. Type hints enable better IDE support and catch errors early.
63+
64+
### III. Test-First Development (NON-NEGOTIABLE)
65+
66+
Testing MUST drive implementation through strict Test-Driven Development:
67+
68+
- **Red-Green-Refactor cycle**: Tests MUST be written first, verified to fail, then implementation makes them pass, followed by refactoring
69+
- **Test location**: All tests MUST be placed in the `tests/` folder at repository root, never co-located with source
70+
- **Test coverage**: Unit tests required for all business logic; integration tests required for I/O boundaries (API endpoints, database, external services)
71+
- **Coverage gate**: CI MUST enforce minimum 80% code coverage; uncovered code MUST be explicitly justified
72+
- **Test categories**:
73+
- **Unit tests**: Pure functions, business logic, algorithms (`tests/unit/`)
74+
- **Integration tests**: API endpoints, database operations, MCP sessions (`tests/integration/`)
75+
- **Contract tests**: External API interfaces and protocol compliance (`tests/contract/`)
76+
- **Test execution**: Use `pytest --cov=src` for all test runs; tests MUST pass before any code merge
77+
78+
**Rationale**: Test-first development catches bugs before they exist, documents intended behavior, enables confident refactoring, and ensures every line of code has proven value.
79+
80+
### IV. Type Safety & Static Analysis
81+
82+
All Python code MUST pass strict static analysis without warnings:
83+
84+
- **Type checking**: `mypy` MUST run in strict mode with no type errors; use `# type: ignore[specific-error]` only with justification comment
85+
- **Linting**: `pylint` and `flake8` MUST pass without warnings; configure exceptions in `pyproject.toml` only when justified
86+
- **Code formatting**: `black` and `isort` MUST auto-format all code; 88 characters max line length; 4-space indentation
87+
- **Pre-commit hooks**: All quality tools (black, isort, mypy, pylint, flake8) MUST run before commits
88+
- **CI enforcement**: Pull requests MUST fail if any static analysis tool reports warnings or errors
89+
- **Validation framework**: Use Pydantic models for all external input validation (API requests, environment variables, configuration files)
90+
91+
**Rationale**: Static analysis prevents entire classes of bugs before runtime, improves code quality, and provides better IDE support. Type safety documentation becomes executable and verified.
92+
93+
### V. Python Best Practices
94+
95+
All code MUST follow Python idioms and modern best practices:
96+
97+
- **Python version**: Target Python 3.9+ for all features and dependencies
98+
- **Virtual environments**: Always use isolated virtual environments; never install packages globally
99+
- **Dependency management**: Pin exact versions in `requirements.txt`; regularly update and audit dependencies
100+
- **Async/await**: Use `asyncio` for I/O-bound operations (API calls, database queries, file I/O)
101+
- **Error handling**: Prefer specific exceptions over generic; always provide context in error messages; use structured logging
102+
- **Resource management**: Use context managers (`with` statements) for file handles, database connections, and locks
103+
- **Data classes**: Use `dataclasses`, `Pydantic`, or `attrs` for data containers; avoid dictionaries for structured data
104+
- **Configuration**: Load from environment variables (via `.env`); never hard-code secrets or configuration
105+
- **Logging**: Use structured logging with proper levels (DEBUG, INFO, WARNING, ERROR); include context (session_id, user_id, etc.)
106+
107+
**Rationale**: Consistent Python idioms make code predictable and maintainable. Modern features (async, type hints, data classes) improve performance and developer experience.
108+
109+
## Security & Quality Standards
10110

11-
### [PRINCIPLE_2_NAME]
12-
<!-- Example: II. CLI Interface -->
13-
[PRINCIPLE_2_DESCRIPTION]
14-
<!-- Example: Every library exposes functionality via CLI; Text in/out protocol: stdin/args → stdout, errors → stderr; Support JSON + human-readable formats -->
111+
### Security Requirements
15112

16-
### [PRINCIPLE_3_NAME]
17-
<!-- Example: III. Test-First (NON-NEGOTIABLE) -->
18-
[PRINCIPLE_3_DESCRIPTION]
19-
<!-- Example: TDD mandatory: Tests written → User approved → Tests fail → Then implement; Red-Green-Refactor cycle strictly enforced -->
113+
All code MUST adhere to security best practices:
20114

21-
### [PRINCIPLE_4_NAME]
22-
<!-- Example: IV. Integration Testing -->
23-
[PRINCIPLE_4_DESCRIPTION]
24-
<!-- Example: Focus areas requiring integration tests: New library contract tests, Contract changes, Inter-service communication, Shared schemas -->
115+
- **No hard-coded secrets**: API keys, passwords, tokens MUST be loaded from environment variables or secrets manager
116+
- **Input validation**: All external input (API requests, file uploads, user input) MUST be validated using Pydantic models or similar
117+
- **Secure communications**: HTTPS required for all external communications; verify TLS certificates
118+
- **Authentication**: API endpoints MUST enforce authentication via API keys; protected routes MUST verify JWTs
119+
- **Security scanning**: CI MUST run security tools (`bandit`, `Safety`, Dependabot) and fail on critical CVEs
120+
- **Audit logging**: Security events (authentication, authorization failures, data access) MUST be logged with sufficient detail
25121

26-
### [PRINCIPLE_5_NAME]
27-
<!-- Example: V. Observability, VI. Versioning & Breaking Changes, VII. Simplicity -->
28-
[PRINCIPLE_5_DESCRIPTION]
29-
<!-- Example: Text I/O ensures debuggability; Structured logging required; Or: MAJOR.MINOR.BUILD format; Or: Start simple, YAGNI principles -->
122+
### Quality Gates
30123

31-
## [SECTION_2_NAME]
32-
<!-- Example: Additional Constraints, Security Requirements, Performance Standards, etc. -->
124+
Before any merge to main branch:
33125

34-
[SECTION_2_CONTENT]
35-
<!-- Example: Technology stack requirements, compliance standards, deployment policies, etc. -->
126+
- **All tests pass**: Unit, integration, and contract tests MUST succeed
127+
- **Coverage threshold**: Minimum 80% code coverage achieved
128+
- **Static analysis clean**: mypy, pylint, flake8 report zero warnings
129+
- **Security scan clean**: No critical or high-severity vulnerabilities
130+
- **Code formatting**: All code formatted with black and isort
131+
- **Documentation updated**: README, docstrings, and architecture docs reflect changes
36132

37-
## [SECTION_3_NAME]
38-
<!-- Example: Development Workflow, Review Process, Quality Gates, etc. -->
133+
## Development Workflow & Review Process
39134

40-
[SECTION_3_CONTENT]
41-
<!-- Example: Code review requirements, testing gates, deployment approval process, etc. -->
135+
### Code Review Requirements
136+
137+
All pull requests MUST undergo code review before merge:
138+
139+
- **Constitution compliance**: Reviewer MUST verify adherence to all principles in this constitution
140+
- **Test verification**: Reviewer MUST verify tests were written first and originally failed
141+
- **Architecture alignment**: Changes MUST align with modular architecture and separation of concerns
142+
- **Naming review**: Variable, function, and class names MUST be clear and descriptive
143+
- **Documentation**: Changes requiring documentation updates MUST include those updates in the same PR
144+
145+
### Complexity Justification
146+
147+
Any violation of constitution principles MUST be explicitly justified:
148+
149+
- **Document in plan**: Complexity justification MUST appear in `specs/[feature]/plan.md`
150+
- **Alternative considered**: Justification MUST explain why simpler alternatives were rejected
151+
- **Review approval**: Complexity violations require explicit approval from senior developers
152+
- **Technical debt tracking**: Violations MUST be tracked as technical debt with a remediation plan
153+
154+
### Branch Strategy
155+
156+
- **Main branch protection**: Direct commits to `main` forbidden; all changes via pull requests
157+
- **Feature branches**: Use format `###-feature-name` aligned with specification documents
158+
- **Commit discipline**: Commit after each logical unit of work (typically one task from `tasks.md`)
42159

43160
## Governance
44-
<!-- Example: Constitution supersedes all other practices; Amendments require documentation, approval, migration plan -->
45161

46-
[GOVERNANCE_RULES]
47-
<!-- Example: All PRs/reviews must verify compliance; Complexity must be justified; Use [GUIDANCE_FILE] for runtime development guidance -->
162+
### Constitutional Authority
163+
164+
This constitution supersedes all other development practices and guidelines:
165+
166+
- **Precedence**: In case of conflict between this constitution and other documents, constitution takes precedence
167+
- **Mandatory compliance**: All code changes, regardless of urgency, MUST comply with constitutional principles
168+
- **No exceptions without documentation**: Any exception MUST be documented and justified in the feature's `plan.md`
169+
170+
### Amendment Process
171+
172+
Amendments to this constitution require:
173+
174+
1. **Proposal document**: Written proposal explaining the change, rationale, and impact
175+
2. **Impact analysis**: Assessment of changes required in codebase and existing specifications
176+
3. **Team review**: Discussion and consensus among development team
177+
4. **Migration plan**: For breaking changes, a clear migration path for existing code
178+
5. **Version update**: Semantic versioning applied to constitution version
179+
6. **Template propagation**: Update all affected templates (plan, spec, tasks) to align with amendments
180+
181+
### Versioning Policy
182+
183+
Constitution versions follow semantic versioning (MAJOR.MINOR.PATCH):
184+
185+
- **MAJOR**: Backward-incompatible changes (principle removals, redefinitions that invalidate existing code)
186+
- **MINOR**: New principles or sections added, material expansions to existing principles
187+
- **PATCH**: Clarifications, wording improvements, typo fixes, non-semantic refinements
188+
189+
### Compliance Review
190+
191+
- **Every pull request**: Reviewer MUST verify constitutional compliance
192+
- **Quarterly audits**: Conduct quarterly reviews of codebase for constitutional drift
193+
- **Metrics tracking**: Track metrics on test coverage, static analysis violations, security issues
194+
- **Continuous improvement**: Use metrics to identify areas for process improvement
195+
196+
### Runtime Guidance
197+
198+
For day-to-day development guidance and practical implementation details, developers SHOULD reference:
199+
200+
- **Coding guidelines**: `.github/instructions/coding-guidelines.instructions.md`
201+
- **Architecture documentation**: `docs/architecture.md`
202+
- **Architecture Decision Records**: `docs/ADRs/` for historical context on technical decisions
203+
- **Template files**: `.specify/templates/*.md` for specification and planning workflows
48204

49-
**Version**: [CONSTITUTION_VERSION] | **Ratified**: [RATIFICATION_DATE] | **Last Amended**: [LAST_AMENDED_DATE]
50-
<!-- Example: Version: 2.1.1 | Ratified: 2025-06-13 | Last Amended: 2025-07-16 -->
205+
**Version**: 1.0.0 | **Ratified**: 2025-10-29 | **Last Amended**: 2025-10-29

0 commit comments

Comments
 (0)