OpenPolicy Monorepo Development Rules
Comprehensive development and code quality guidelines for the OpenPolicy Merge Platform V2 monorepo. Enforces legacy code reuse, API-first architecture, strict testing thresholds, and systematic merge conflict resolution.
Core Principles
**FUNDAMENTAL RULE: Never reinvent the wheel.** Before implementing any new functionality, always check the `/legacy` directory first. If similar code exists, copy and adapt it rather than writing from scratch.
Instructions
1. Legacy Code Reuse (HIGHEST PRIORITY)
**ALWAYS check `/legacy` directory before implementing new functionality**If similar code exists in `/legacy`, copy it over and adapt/refactor to meet current requirementsDo NOT write new implementations from scratch if legacy code can be reused/modifiedThis applies to: parsers, APIs, utilities, data loaders, transformers, validators, etc.When copying from legacy: preserve original comments noting source, then document adaptations madeNever delete files in `/legacy`; propose replacements under `/services` or `/apps` and mark deprecated code in `/docs/REFERENCE/omitted.md`2. Code Style & Language Standards
**TypeScript:**
Use strict mode for all TypeScript projectsAvoid `any`; model domain types explicitlyUse ES6+ features, arrow functions, and async/awaitPrefer immutability and functional decomposition**Python:**
Require Python >=3.11Enforce Ruff + Black formattingKeep functions pure where possibleStrict type annotations required**General:**
All new APIs and data loaders must have tests first (TDD-leaning)Strict type annotations or JSDoc as per languageAvoid duplicate code via abstractionHandle edge cases and input validation rigorously3. Architecture & API Design
**API-first:** Update `openapi.yaml` before implementing endpointsDo not break existing contracts; introduce new fields behind feature flagsAvoid breaking changes to existing APIsIngestion must be idempotent; all loaders should support upsert semanticsTreat `instructions.md` as the single source of truth for task scope4. Testing & Quality Thresholds
Statement coverage must be **85%+** for `services/api-gateway` and `services/etl`Branch coverage must be **95%+** for critical modules (parsers, normalizers)Generate integration and unit test cases for all major changesRun all test suites post-merge; note and mark failed filesAlways include unit tests alongside code changes5. Security & Safety
Never commit secrets or credentials; always use `.env` and GitHub Actions secretsSanitize all inputs (prevent injection/XSS)Use environment variables for API keys or secretsDo not log sensitive dataHandle API errors with retries, timeouts, and clear logsRespect and document rate limits6. Codebase Organization & Repo Merging
**Structure:**
Maintain traceability of migrated code in comments and commit messagesStandardize all folder/file naming; flatten redundant directoriesMove shared logic/utilities to `common/` at root levelEliminate duplicate code by suggesting unification or abstractionMark deprecated/legacy code with clear isolation and explicit deprecation notes**Merge Process:**
1. Move code
2. Unify structure
3. Resolve conflicts
4. Integrate tooling
5. Update docs
7. AI-Assisted Refactoring & Conflict Handling
Auto-detect and list conflicts: duplicate files/classes/functions/module namesUse path/glob rules to trigger language-appropriate refactorsFor every duplicated/conflicting fragment, propose the best candidate and document resolution processAlways merge documentation (README, LICENSE, CONTRIBUTING) and update links/source attributionPreserve git history where possible; otherwise, note source repo/path in headersWhen uncertain, auto-generate a design note in `docs/ADR/` with pros/cons/decision8. Version Control
Follow Conventional Commits: `feat:`, `fix:`, `chore:`, `refactor:`, `test:`, `docs:`, `ci:`Write concise, meaningful messagesExplain rationale for major changes in PRs or commit bodies9. Testing & CI
Upgrade, merge, and unify test runners (Jest, Pytest, etc.), linters, and formatters for a single workflowNo merged code should break lint or test on CIRun all test suites after merge; summarize conflicts and next stepsPropose test or linter migration where disparate tools exist10. Documentation & Traceability
Every moved module/file should reference original source in comments or commit logsMaintain a migration report in `docs/`: list moved/transformed files, structural changes, and outstanding itemsInsert links to original repo URLs/commits for auditabilityWhen changes may impact other teams or systems, document the impact and tag relevant ownersClearly document deprecation, API, or config/environment changes11. Advanced Workflow Practices
Before code merging, produce or update architectural map/diagram of both source and target reposUse feature branches/worktrees for each merge phase for safety and clarityKeep AI context up to date by opening relevant files and closing unrelated tabsRegularly review and self-improve these rules based on results12. UI/UX & Accessibility (When Applicable)
Ensure responsive design and semantic HTMLApply ARIA roles and keyboard navigationProvide fallback UI for loading, error, empty statesPrioritize accessibility: color contrast, focus indicators, readable fonts13. AI Cursor Behavior
Provide clear plan or reasoning before code changesAsk clarifying questions on ambiguous promptsSuggest alternative patterns with rationaleAvoid fabrications; seek factual or confirmed knowledgePropose improvements and refactorings beyond immediate requests when justifiedAvoid off-topic code generation or side conversations14. Continuous Improvement
Seek feedback for uncertain or major changesAfter merge, schedule a post-mortem in docs on challenges and automation wins/gapsKeep `.cursorrules` file updated as the monorepo evolvesConstraints
Never delete files in `/legacy` directoryNever commit secrets or credentialsAPI changes must update `openapi.yaml` firstAll code must pass lint and tests in CICoverage thresholds are non-negotiable (85% statement, 95% branch for critical modules)