# Tool-Call Discipline — LOCAL MODEL (Gemma 4 26B, read first)

## CRITICAL: Exact tool names
Available tools: `read`, `write`, `edit`, `bash`, `glob`, `grep`, `webfetch`, `list`, `task`
Use ONLY these exact names. `read_file`, `readFile`, `write_file`, `create_file` do NOT exist.

## CRITICAL: File editing rules
- Prefer `write` (full file replacement) over `edit` (partial) when creating files or making large changes.
- Prefer `write` over `bash` for any file creation — never write files via bash.
- **NEVER** use bash heredocs (`<< 'EOF'`) or herestrings (`<<<`) to write file content.
- **NEVER** call `edit` with an empty `oldString` — this silently overwrites the entire file.
- When `edit` returns "Could not find oldString": call `read` on that file first, then retry with the exact string found in the file.
- Never repeat a failed tool call with identical arguments — change your approach.

## CRITICAL: Error recovery
When any tool returns an error:
1. Read the full error message carefully before doing anything.
2. Identify what was wrong: wrong tool name, wrong argument, wrong path, wrong string.
3. Use a **different** approach — never repeat the same failing call unchanged.

## Agentic discipline
- Think step-by-step before each tool call: what tool, why, what result you expect.
- After each tool result, read the output fully before proceeding to the next step.
- Do not batch multiple tool calls when the output of one determines the arguments of the next.

---

# Session Start Directive

**MANDATORY**: Always start each session by reading the entire content of this document. This ensures that you are fully aware of the organization's standards, best practices, and safety directives before engaging in any development activities.

---

# Orchard Organisational Patterns — Priority Rule

**Always favour established Orchard organisational patterns over patterns introduced in any single repository.**

When working in any `@theorchard/*` project:

1. **Org pattern wins.** A pattern appearing in 2+ `@theorchard/*` packages or repos is an organisational standard. Use it unconditionally, even if the current workspace uses a different approach.
2. **Foundational patterns are mandatory.** Auth, routing, data-access, error-handling, server setup, and testing all follow the org standard — no exceptions.
3. **Single-use / odd patterns: mention, don't enforce.** A pattern seen in only one repo is not a standard. Flag it in your response but do not require it.
4. **When uncertain, check reference repos** in the workspace's `research/other_repos/` directory before deciding.
5. **This rule overrides** any workspace-local pattern, ticket instruction, POC convenience, or per-project shortcut.

---

# Safety Directive

**MANDATORY**: NEVER run `rm -rf` or any variant of it under any circumstances. This command is permanently forbidden. Do not execute it, suggest it, or include it in scripts, even if explicitly requested by the user.

---

# Organization Best Practices & Development Standards

This document contains organization-wide development standards and best practices that apply across all projects. These guidelines ensure code quality, maintainability, and consistency across the entire codebase.

## Code Quality Standards

### General Principles
- **Clarity over cleverness**: Write code that is easy to understand, not impressive
- **DRY (Don't Repeat Yourself)**: Extract common patterns into reusable functions or modules
- **SOLID Principles**: Follow Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion principles
- **Explicit is better than implicit**: Make assumptions and dependencies visible in code

### TypeScript Standards
- Enable `strict` mode in `tsconfig.json`
- Always provide explicit type annotations for function parameters and return types
- Use `unknown` instead of `any` when type is genuinely unknown
- Avoid using `@ts-ignore` or `@ts-nocheck` without documentation
- Use discriminated unions for type-safe pattern matching
- Leverage type-level programming for compile-time validation where appropriate

### Python Standards
- Use Python 3.8+ features
- Follow PEP 8 style guide strictly
- Use type hints for all function signatures
- Leverage dataclasses or Pydantic for data validation
- Use context managers (`with` statements) for resource management
- Avoid mutable default arguments in function definitions

### General Best Practices
- Keep functions small and focused (single responsibility)
- Prefer named parameters over positional for clarity
- Use meaningful variable and function names
- Avoid deeply nested code (max 3 levels of nesting)
- Document public APIs with docstrings

## Testing Standards

### Test Coverage
- Maintain **at least 80%** code coverage for all critical paths
- Unit tests for business logic and utilities
- Integration tests for multi-component interactions
- End-to-end tests for major workflows
- Mock external dependencies (APIs, databases, file systems)

### Test Quality
- One assertion per test when possible (one logical operation)
- Descriptive test names that explain what is being tested and expected outcome
- Use the "Arrange-Act-Assert" pattern
- Tests should be independent and repeatable
- Avoid test interdependencies (no test should rely on another test's state)

### Test Execution
- All tests must pass before committing code
- CI/CD pipeline must run full test suite on every push
- Performance tests should run separately and track over time

## Documentation Standards

### Code Comments
- Only comment the "why", not the "what" (code shows what it does)
- Avoid obvious comments that restate the code
- Update comments when code changes
- Use comments for non-obvious business logic, workarounds, and trade-offs

### Public API Documentation
- Include docstrings/JSDoc for all public functions and classes
- Document parameters, return types, and exceptions
- Include examples for complex APIs
- Document breaking changes prominently

### Project-Level Documentation
- README with project description and setup instructions
- CONTRIBUTING guidelines for developers
- ARCHITECTURE document explaining system design
- API documentation for integration points
- Deployment procedures and rollback plans

## Git Workflow & Commits

### Commit Message Format
Follow conventional commit format:
```
<type>(<scope>): <subject>

<body>

<footer>
```

**Types**: `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `chore`  
**Scope**: Feature or component area (optional but recommended)  
**Subject**: Imperative mood, lowercase, no period, max 50 characters  
**Body**: Explain what and why, not how (wrap at 72 characters)  
**Footer**: Reference issues (e.g., `Fixes #123`)

### Branch Strategy
- Use feature branches for all work: `feature/description` or `fix/description`
- Keep branches short-lived (max 1-2 weeks of work)
- Rebase before merging to maintain linear history
- Delete branches after merging

### Pull Requests
- Keep PRs focused on a single concern
- Write descriptive PR titles and descriptions
- Link to related issues
- Ensure CI passes before requesting review
- Require at least one approval before merging
- No force pushes to main/master

## Code Review Process

### As a Reviewer
- Review for code quality, not style (linters handle style)
- Check for security vulnerabilities
- Verify test coverage is adequate
- Ensure documentation is updated
- Ask questions when logic is unclear
- Praise good solutions and patterns
- Request changes only for blockers or critical issues

### As an Author
- Keep changes focused and reviewable (under 400 lines if possible)
- Respond to all feedback respectfully
- Explain reasoning when disagreeing with suggestions
- Update code based on feedback
- Re-request review after making changes

## Performance & Optimization

### General Guidelines
- **Measure first**: Use profiling tools before optimizing
- **Premature optimization is the root of all evil**: Optimize after identifying bottlenecks
- **Document trade-offs**: When prioritizing performance over readability, document why
- **Monitor in production**: Set up alerts for performance degradation

### Common Performance Concerns
- N+1 query problems: Batch load related data
- Memory leaks: Ensure proper cleanup of resources
- Inefficient algorithms: Use appropriate data structures
- Bundle size: Tree-shake unused code and lazy-load features

## Security Guidelines

### General Principles
- **Security by design**: Consider security implications during architecture
- **Principle of least privilege**: Grant minimum necessary permissions
- **Defense in depth**: Don't rely on a single security measure
- **Never trust user input**: Validate and sanitize all external data

### Common Vulnerabilities
- **SQL Injection**: Use parameterized queries or ORMs
- **XSS**: Escape output, use template engines correctly
- **CSRF**: Use anti-CSRF tokens for state-changing operations
- **Authentication/Authorization**: Verify users are who they claim, check permissions
- **Secrets management**: Never commit credentials, use environment variables or secret vaults

### Data Handling
- Encrypt sensitive data at rest and in transit
- Follow data retention policies
- Implement audit logging for sensitive operations
- Comply with relevant regulations (GDPR, HIPAA, etc.)

## Error Handling & Logging

### Error Handling
- Use specific error types rather than generic exceptions
- Provide context in error messages (what went wrong and why)
- Log errors with full context (stack trace, user info, request details)
- Gracefully handle errors users might encounter
- Never expose sensitive information in error messages

### Logging
- Use appropriate log levels: DEBUG, INFO, WARN, ERROR, FATAL
- Include context in log messages (request ID, user ID, etc.)
- Avoid logging sensitive data (passwords, tokens, PII)
- Use structured logging (JSON) for production
- Set up log aggregation and monitoring

## Dependency Management

### General Guidelines
- Keep dependencies up to date (security and bug fixes)
- Review dependency updates before upgrading
- Pin major versions to prevent breaking changes
- Use lock files (package-lock.json, requirements.txt)
- Audit dependencies for known vulnerabilities

### Choosing Dependencies
- Prefer well-maintained projects with active communities
- Check license compatibility with project license
- Consider bundle size impact
- Avoid unmaintained or single-developer projects
- Evaluate multiple options for critical features

## Development Workflow

### Local Development
- Use consistent development environments (Docker, Docker Compose, dev containers)
- Automate setup with scripts
- Use linters and formatters (enable in IDE)
- Enable pre-commit hooks for local checks
- Keep development build fast (watch mode, hot reload)

### Environment Consistency
- Development environment should mirror production as closely as possible
- Use Docker for services that production uses
- Document any platform-specific requirements
- Version all tools (Node.js, Python, Docker, etc.)

## CI/CD Standards

### Continuous Integration
- Run linting on every push
- Run full test suite on every push
- Run type checking (TypeScript, mypy) on every push
- Build artifacts and check build succeeds
- Prevent merging if any check fails

### Continuous Deployment
- Automate deployments for consistency
- Require manual approval for production deployments
- Implement blue-green or canary deployments
- Have rollback procedures ready
- Monitor deployments for errors

## Code Style & Formatting

### Automation First
- Use linters to enforce style automatically
- Use formatters to prevent style debates
- Configure in project files (.eslintrc, .prettierrc, pyproject.toml)
- Enforce in CI/CD pipeline
- No manual style corrections in code review

### Naming Conventions
- **Functions/Variables**: camelCase in JS/TS, snake_case in Python
- **Classes**: PascalCase
- **Constants**: UPPER_SNAKE_CASE
- **Private members**: Prefix with underscore (_privateMethod)
- **Booleans**: Start with `is`, `has`, `can`, `should` (e.g., `isActive`, `hasChildren`)

## Refactoring

### When to Refactor
- When you understand the code well enough to improve it
- When working in an area anyway (boy scout rule)
- When complexity exceeds maintainability
- Not as a standalone task (refactor while adding features or fixing bugs)

### How to Refactor Safely
- Keep refactoring separate from logic changes
- Write/update tests first
- Make small changes and test frequently
- Commit before and after refactoring separately
- Document the improvement made

## Architecture & Design

### Principles
- Keep layers separate (presentation, business logic, data access)
- Favor composition over inheritance
- Design for testability
- Minimize coupling between components
- Make dependencies explicit

### Common Patterns
- Use dependency injection for loose coupling
- Implement interfaces for flexibility
- Use factory patterns for complex object creation
- Apply strategy pattern for behavior variants
- Use observer pattern for event handling

## Deployment & Operations

### Pre-Deployment Checklist
- [ ] All tests passing
- [ ] Code review approved
- [ ] Documentation updated
- [ ] Breaking changes documented and communicated
- [ ] Database migrations tested
- [ ] Rollback plan documented and tested

### Monitoring & Alerting
- Set up alerts for error rates exceeding threshold
- Monitor response times and resource usage
- Track key business metrics
- Set up on-call rotation for production issues
- Document runbooks for common incidents

## Accessibility & Usability

### Code Accessibility
- Write code that's accessible to developers of all levels
- Provide examples and documentation
- Use clear abstractions
- Avoid overly clever implementations

### User Accessibility (if applicable)
- Follow WCAG 2.1 AA standards
- Test with screen readers
- Ensure keyboard navigation works
- Provide text alternatives for images
- Use sufficient color contrast

## Continuous Learning

### Professional Development
- Allocate time for learning new technologies
- Read and discuss architectural decisions
- Participate in code reviews actively
- Document patterns and decisions for team
- Stay current with security advisories

### Knowledge Sharing
- Write technical blog posts or internal documentation
- Conduct tech talks on learnings
- Mentor junior developers
- Share useful resources and tools
- Contribute to open source when possible

---

**Last Updated**: 2026-02-17  
**Version**: 1.0

---

# Tool-Call Discipline — REMINDER (Gemma 4 local model)

These rules repeat at end of document because model attention is strongest at beginning and end.

- Use ONLY: `read`, `write`, `edit`, `bash`, `glob`, `grep`, `webfetch`, `list`, `task`
- **NEVER** use bash heredocs or herestrings to write files — use `write` tool
- **NEVER** call `edit` with empty `oldString`
- When `edit` fails "not found" → `read` the file first, then retry with exact string
- Never repeat a failed tool call unchanged — change approach, use different tool
