# AI Instructions — DevOps & Security Posture Principles Token-efficient guidance for AI agents writing code with DevOps and security maturity. Use as system context or project rules. --- ## How to Use This File Drop this into any repo as `DEVOPS.md` — it sits alongside `CLAUDE.md` and `AGENTS.md`. Reference it in your cursor rules, claude rules, or agent prompts. It gives AI agents the principles they need to write production-grade code — not just working code. ## Repository Setup for AI Agents Repos using [@creo-team/wisdom](https://github.com/creo-team/wisdom) generate these per-tool files with `wisdom sync` — author standards once, sync everywhere, and let CI guard drift. The manual tree below is the no-tooling fallback. Every repo should have these files for effective AI collaboration: ``` project/ ├── CLAUDE.md # Comprehensive project context for Claude Code ├── AGENTS.md # Quick-reference for all AI agents ├── DEVOPS.md # This file — DevOps & security principles ├── .cursor/ │ └── rules/ │ ├── project.mdc # Project overview (alwaysApply: true) │ ├── code-style.mdc # Naming, formatting (alwaysApply: true) │ ├── typescript.mdc # TS conventions (globs: *.ts,*.tsx) │ ├── react-nextjs.mdc # React/Next patterns (globs: *.tsx) │ ├── components.mdc # Component standards (globs: *.tsx) │ ├── security.mdc # Security patterns │ ├── testing.mdc # Test conventions (globs: *.test.ts) │ └── api-routes.mdc # API patterns (globs: app/api/**) └── README.md # Human-readable setup ``` ### What Each File Does | File | Audience | Purpose | |------|----------|---------| | `CLAUDE.md` | Claude Code | Comprehensive: architecture, conventions, file map, verification | | `AGENTS.md` | All AI agents | Quick reference: core rules, naming, verification commands | | `DEVOPS.md` | All AI agents | Principle-level guidance: DevOps maturity, security posture | | `.cursor/rules/*.mdc` | Cursor IDE | Auto-applied rules by file glob — most granular guidance | | `README.md` | Humans | Setup, installation, development workflow | ### Real Examples These files from the [Vecta](https://github.com/creo-team) project demonstrate the pattern: **CLAUDE.md** includes: - Project overview and tech stack - Code style rules (zero magic values, enums, naming, imports) - Architecture with file tree - Security section (auth, validation, secrets, headers) - Key file map with every important file and its purpose - Verification commands **AGENTS.md** includes: - One-paragraph project description - Required reading table - Core rules (the 5-6 most important conventions) - Naming table - Verification commands **.cursor/rules/** includes: - `project.mdc` (alwaysApply) — project overview, architecture - `code-style.mdc` (alwaysApply) — naming, imports, file organization - `components.mdc` (globs: *.tsx) — props, accessibility, styling - `typescript.mdc` (globs: *.ts) — enums, type safety, null vs undefined - `security.mdc` — auth patterns, input validation, secrets - `testing.mdc` (globs: *.test.ts) — Vitest patterns, naming - Domain-specific rules for billing, notifications, database, etc. --- ## DevOps Principles for AI-Generated Code ### 1. Ship Small, Ship Often Write code that supports frequent, low-risk deployments: - **Small, focused changes** — one concern per commit, one purpose per function - **Feature flags over long-lived branches** — deploy dark, enable when ready - **Backward compatibility** — additive changes first, deprecate, then remove - **Trunk-based development** — short-lived branches, merge to main frequently ### 2. Automate Everything Repeatable Never leave a manual step that a machine could do: - **CI/CD pipelines** — every push triggers build, lint, test, deploy - **Infrastructure as Code** — Terraform, CDK, Pulumi — never click-ops - **Dependency updates** — Dependabot, Renovate — automated PRs - **Code formatting** — Prettier, ESLint — no style debates in review ### 3. Fail Fast, Recover Faster Design systems that surface problems immediately: - **Shift-left testing** — unit tests catch bugs before CI, not after deploy - **Type safety** — TypeScript strict mode, no `any`, enums over magic strings - **Input validation at boundaries** — validate early, fail with clear errors - **Graceful degradation** — catch errors, show useful messages, don't crash ### 4. Observe Everything You can't fix what you can't see: - **Structured logging** — JSON logs with context (requestId, userId, action) - **Health checks** — `/health` endpoint, readiness probes - **Error tracking** — Sentry, Datadog — automatic alerting on anomalies - **DORA metrics** — deployment frequency, lead time, failed deployment recovery time, change failure rate ### 5. Secure by Default Security is not a feature — it's a property of every line of code: - **Auth checks first** — every protected route starts with authorization - **Validate all input** — never trust client data, re-validate server-side - **Secrets in env vars** — never hardcoded, never committed, never logged - **Least privilege** — IAM roles scoped to exactly what's needed - **Dependencies audited** — `npm audit`, keep packages current --- ## Security Posture Maturity ### Level 1: Foundations Every repo, every project, no exceptions: - [ ] Secrets in environment variables, never in code - [ ] `.env` files gitignored - [ ] Input validation at API boundaries - [ ] Auth checks before business logic - [ ] Dependencies up to date, `npm audit` clean - [ ] HTTPS everywhere ### Level 2: Hardened Production-ready security: - [ ] Security headers (CSP, HSTS, X-Frame-Options, X-Content-Type-Options) - [ ] Rate limiting on public endpoints - [ ] CSRF protection on state-changing operations - [ ] Cookies: `httpOnly`, `secure`, `sameSite: 'lax'` - [ ] Error messages don't leak implementation details - [ ] SQL/NoSQL injection prevention (parameterized queries) ### Level 3: Proactive Mature security culture: - [ ] Automated security scanning in CI (SAST, dependency scanning) - [ ] Infrastructure as Code with security guardrails - [ ] Penetration testing schedule - [ ] Incident response runbooks - [ ] Secret rotation automation - [ ] Audit logging for sensitive operations --- ## Code Quality Principles ### Never Nest Early returns, flat code. If you're indenting more than once inside a function, refactor. Extract helpers, guard clause, return early. ```typescript // BAD function process(user: User) { if (user) { if (user.isActive) { if (user.hasPermission) { return doWork(user) } } } return null } // GOOD function process(user: User) { if (!user) return null if (!user.isActive) return null if (!user.hasPermission) return null return doWork(user) } ``` ### No Narration Comments Code speaks for itself. Only comment non-obvious intent, trade-offs, or constraints. Never `// Get the user`, `// Return the result`, or section banners. ```typescript // BAD // Get the user from the database const user = await getUser(id) // Check if user exists if (!user) return null // GOOD const user = await getUser(id) if (!user) return null ``` ### Zero Magic Values Every string, number, and boolean should trace to a named constant or enum: ```typescript // BAD if (status === 'approved') { ... } const timeout = 5000 // GOOD if (status === BookingStatus.Approved) { ... } const timeout = REQUEST_TIMEOUT_MS ``` ### Simple Over Clever Readable beats terse. Flat logic over nested ternaries. If someone needs to pause to parse your code, simplify it. ### Deduplicate Ruthlessly Shared data goes in shared modules, not copied between files. If two components need the same data, extract it. If two projects need the same pattern, standardize it. ### Verb-Driven Function Names Name functions for what they do, not the HTTP method behind them: ```typescript // BAD fetchUser() deleteBooking() postInvoice() // GOOD getUser() removeBooking() createInvoice() listAlbums() putConfig() updateStatus() ``` Verbs like `get`, `remove`, `create`, `list`, `put`, `update` describe the action. Verbs like `fetch`, `delete`, `post` describe the transport. ### Types in Dedicated Files Interfaces, enums, and types live in `types.ts` — never scattered across implementation files. When a domain grows, the types file is the first thing a new developer reads to understand the data model. ### Defensive Guards Don't trust that data is what you expect. Verify assumptions with `if` checks and logging: ```typescript // BAD — assumes booking exists const booking = await getBooking(id) return booking.status // GOOD — verify and log const booking = await getBooking(id) if (!booking) { logger.warn('Booking not found', { bookingId: id }) return null } return booking.status ``` This is especially critical in distributed systems where data flows through multiple services. The person debugging the failure at 3am will thank you for the log line. ### Generators When Appropriate Use generator functions for iteration, lazy evaluation, and streaming patterns where they simplify the code: ```typescript function* paginateResults(query: Query) { let cursor: string | undefined do { const page = getPage(query, cursor) yield* page.items cursor = page.nextCursor } while (cursor) } ``` ### Exhaustive Patterns Use TypeScript to enforce completeness: ```typescript const STATUS_LABELS: Record = { [Status.Active]: 'Active', [Status.Inactive]: 'Inactive', } ``` ### Centralized Resources Single source of truth for cross-cutting concerns: | Resource | File | Why | |----------|------|-----| | User-facing text | `strings.ts` | i18n-ready, consistent voice | | Page/API paths | `routes.ts` | No broken links, refactor-safe | | Config values | `constants.ts` | No magic numbers scattered | | Input validation | `validation.ts` | Consistent rules, no inline regex | | Env vars | `env.ts` | Validated at startup, typed | ### Footer Version Pattern (Next.js / TypeScript) Every Creo TypeScript web project displays the `package.json` version in the footer, linked to the GitHub release: 1. `next.config.ts` reads version: `const version = require('./package.json').version` 2. Exposes as env var: `env: { NEXT_PUBLIC_APP_VERSION: version }` 3. Footer reads `process.env.NEXT_PUBLIC_APP_VERSION` and renders `{version}` 4. Version links to `https://github.com/{org}/{repo}/releases/tag/{version}` This gives instant visibility into what's deployed and links directly to the release notes. --- ## Commit & PR Conventions ### Conventional Commits ``` feat(auth): add magic link authentication fix(billing): handle partial refund edge case refactor(api): extract validation middleware test(booking): add state transition coverage chore: upgrade dependencies docs: add API documentation ``` ### PR Description Template ```markdown ## Summary - [1-3 bullet points describing what changed and why] ## Test Plan - [ ] Unit tests pass - [ ] Manual testing completed - [ ] Edge cases covered ``` --- ## Quick Reference ### Verification Commands ```bash npm run build # Production build succeeds npm run lint # No lint errors npm test # All tests pass npm audit # No known vulnerabilities ``` ### File Naming | Element | Convention | Example | |---------|-----------|---------| | Files | kebab-case | `booking-service.ts` | | Components | PascalCase | `BookingModal` | | Tests | `*.test.ts` | `booking-service.test.ts` | | Types | `types.ts` | `app/lib/billing/types.ts` | | Config | `config.ts` | `app/lib/billing/config.ts` |