Imported from WojcikMM/spec-development-protocol (
AGENTS.md). Install upstream withnpx skills add WojcikMM/spec-development-protocol. Copyright stays with the author.
AGENTS.md
Files matching **/*
Global Coding Standards
These apply to all code produced regardless of language, framework, or project type. Adjust specifics to the stack defined in TECH.md.
For SDLC orchestration, gate ordering, agent routing, AGENTS.md context strategy, plan scope budgets, and hardening policy, see @/.github/instructions/sdlc-process.instructions.md — that file is the single source of truth for process. Do not duplicate process rules here; this file governs code quality only.
Code Quality
- Clean Code first: small, focused functions with a single clear responsibility.
- Naming is communication: use intent-revealing names for variables, functions, classes, and files. Avoid abbreviations unless they are universally understood in the domain.
- YAGNI: do not add functionality until it is needed. Avoid speculative abstractions.
- DRY with judgment: eliminate duplication, but do not abstract prematurely. Three occurrences before extracting a shared concept is a reasonable heuristic.
- Avoid deep nesting: prefer early returns, guard clauses, and flat logic over nested conditionals.
- Functions and methods: prefer pure functions where possible. Side effects should be explicit and isolated at system boundaries.
Architecture & Design
- Separation of concerns: keep infrastructure, application logic, and domain rules in separate layers.
- Dependency direction: dependencies should point inward toward domain/core logic, never outward.
- Ports and adapters (Hexagonal): use interfaces/contracts at external boundaries (HTTP, DB, messaging, file system). This keeps the core testable and portable.
- Right-size the design: a simple CRUD endpoint does not need a domain model. A financial transaction processor does. Match complexity to the problem.
- Prefer composition over inheritance.
Error Handling
- Fail fast: validate at system entry points (API boundaries, CLI inputs, event consumers). Do not let invalid data propagate deep into business logic.
- Errors are data: represent failures explicitly (result types, structured errors) rather than using exceptions for control flow where avoidable.
- Surface actionable messages: error messages should help the operator or developer understand what failed and why. Never expose stack traces or internal details to end users.
- Distinguish error categories: transient (retry-able) vs. permanent (fail fast) vs. programmer errors (crash loudly in dev, alert in prod).
Testing
- Test pyramid: unit tests are the foundation, integration tests verify boundaries, end-to-end tests cover critical user paths only.
- Test behavior, not implementation: tests should validate what the code does, not how it does it internally. Avoid testing private methods directly.
- One assertion focus per test: each test should answer one question. Use descriptive test names that describe the scenario and expected outcome.
- Arrange-Act-Assert (AAA): structure tests consistently with clear setup, execution, and verification sections.
- Tests must pass before merging. No skipped or commented-out tests without a documented reason.
- Coverage is a proxy, not a goal: aim for meaningful coverage of business-critical and error paths, not 100% line coverage of trivial code.
Security (Always On)
Apply these regardless of whether a formal security review has been done:
- Input validation at boundaries: validate and sanitize all external input — HTTP requests, file uploads, event payloads, CLI arguments.
- Output encoding: encode output appropriate to context (HTML, SQL, shell) to prevent injection attacks.
- Least privilege: components, services, and users should have only the permissions they need to do their job.
- No secrets in code or version control: use environment variables, secret managers (e.g. Azure Key Vault, AWS Secrets Manager, HashiCorp Vault), or CI/CD secret stores.
- Secure defaults: default to deny-all access, require HTTPS/TLS, set secure cookie flags, apply CORS policies explicitly.
- Dependency hygiene: flag and address known vulnerable dependencies. Do not add new dependencies without justification.
- OWASP Top 10 awareness: treat injection, broken auth, IDOR, security misconfiguration, and sensitive data exposure as active threats in every feature.
Observability
- Structured logging: emit logs as structured data (JSON preferred) with consistent fields: timestamp, level, correlation/trace ID, service name, message, relevant context.
- Log levels with intent: DEBUG for development detail, INFO for significant state transitions, WARN for recoverable anomalies, ERROR for failures requiring attention.
- Never log sensitive data: no passwords, tokens, PII, or financial details in logs.
- Health and readiness: expose health check endpoints on all services. Distinguish liveness (is the process alive) from readiness (is it ready to serve traffic).
- Metrics at boundaries: measure and expose latency, error rates, and throughput at external-facing boundaries and critical internal operations.
Version Control & Commits
- Atomic commits: each commit represents one logical change. A commit should be explainable in a single sentence.
- Commit messages: use the imperative mood in the subject line (
Add,Fix,Remove, notAdded,Fixed). Reference issue/story IDs where applicable. - Branch per story/task: never commit feature work directly to the main/trunk branch.
- No commented-out code in commits: delete unused code. Version control preserves history.
Documentation
- Code should read as documentation: prioritize self-documenting code over comments. Comments explain why, not what.
- Update docs with code: if a change affects an API contract, architectural decision, or user-facing behavior, update the corresponding documentation in the same commit/PR.
- Architecture Decision Records (ADRs): for significant technical decisions, record the context, options considered, and rationale in a short ADR file.
Greenfield vs. Legacy
- Greenfield: establish the full structure from
TECH.mdup front. Set linting, testing, and CI standards before writing feature code. - Legacy: prefer the strangler fig pattern — incrementally improve at touch points rather than rewriting working code. Respect existing conventions until a deliberate decision to change them is made and documented.
SDLC Process Instructions
You are operating under the Spec Development Protocol (SDP) — a spec-first, gate-driven engineering framework for both greenfield and legacy projects. This file is the single source of truth for process, gate ordering, agent routing, and orchestration. Coding standards live separately in coding-standards.instructions.md.
All work must follow these gates sequentially unless an explicit exception below applies.
Mandatory Startup Context
- Read
@/.github/TECH.mdfirst — it defines the stack, cloud environment, and project-specific standards. All agents and decisions must be consistent with it. If it does not exist, invokesdp.discoverbefore Gate 1 to draft it from repository evidence. - Follow the 6-gate SDLC below — never skip or reorder gates without explicit user approval.
- Route specialized work through the agents in
@/.github/agents/using the routing table below. - Check
@/spec/ACTIVE.md— if it exists, it names the currently active feature and its progress (slug, title, current gate, current story, status). Use it as the default working context for all gate operations when no explicit feature is specified in the user's input, and as the resume point after an interrupted session. - Resolve the
AGENTS.mdcontext chain before broad repo exploration: read root-levelAGENTS.mdplus the nearestAGENTS.mdfiles in the target module path and follow their scope constraints.
AGENTS.md Context Strategy (Required)
- Use
AGENTS.mdfiles as scoped context maps to avoid loading unrelated repository areas. - Resolution order:
- Repository root
AGENTS.md(global rules and boundaries) - Nearest domain-level
AGENTS.md(for example solution/app folder) - Nearest module-level
AGENTS.mdin the exact implementation path
- Repository root
- If instructions conflict, the most specific (closest)
AGENTS.mdwins for that module. - Before searching for files, identify the target module and read only its relevant
AGENTS.mdchain. - Suggested placement in client repositories:
- One
AGENTS.mdin each meaningful.NETlibrary/service folder (typically next to each.csprojor library root). - One
AGENTS.mdin each frontend app/package root (for exampleapps/web,src/frontend,packages/ui).
- One
Agent Routing
| Task | Agent | Entry-point prompt |
|---|---|---|
| Legacy stack discovery | sdp.discover |
/discover-tech |
| Discovery / PRD creation | sdp.prd |
/create-prd |
| Backlog refinement (epics, stories, AC) | sdp.analyst |
/refine-backlog |
| Architecture / technical design | sdp.architect |
/design-system |
| Task planning (no code) | sdp.planner |
/plan-task |
| Implementation | sdp.developer |
/implement |
| Code and design review | sdp.reviewer |
/run-review |
| Security assessment | sdp.security |
/audit-security |
| Acceptance criteria validation | sdp.qa |
/qa-validate |
Prefer prompt commands over manually selecting an agent. Each gate has exactly one entry-point prompt; use it instead of invoking the agent directly, so the correct mode and inputs are always applied.
SDLC Discipline
- Never write code before an approved implementation plan exists.
- Implement exactly one story or task at a time — no bundling.
- Keep every artifact traceable: PRD → backlog → design → plan → code → validation.
- Block on incomplete or ambiguous artifacts.
- Flag and block progression if gate exit criteria are not met.
Feature Folder Convention
All artifacts for a feature are stored in spec/<feature-slug>/.
spec/
ACTIVE.md # Active feature slug, title, and progress state
<feature-slug>/
PRD.md # Gate 1: Product Requirements
BACKLOG.md # Gate 2: Epics and stories
EPIC-<N>-<slug>.md # Gate 2: Epic details
DESIGN.md # Gate 3: Technical design
PLAN.md # Gate 4: Implementation plan
HISTORY.md # Log of completed tasks and hardening outcomes
Every gate artifact (PRD.md, BACKLOG.md, EPIC-*.md, DESIGN.md, PLAN.md) MUST follow its template in .github/templates/ and MUST start with a status header:
status: draft | approved | rejected
approved_by: <name or "pending">
approved_at: <ISO date or "pending">
Agents MUST treat an artifact as usable input for the next gate only when status: approved. Do not infer approval from conversational tone alone — check the field. An agent that produces an artifact sets status: draft and stops; only the user (or an explicit user instruction such as "approved") flips it to approved.
ACTIVE.md format:
slug: <feature-slug>
title: <Human Readable Feature Title>
current_gate: <1-6>
current_story: <story id or "n/a">
status: <in-progress | blocked | done>
Agents read and update spec/ACTIVE.md at the start and end of every gate so work can resume correctly after an interrupted session.
The 6 Gates
-
Discovery (PRD): Define the "what" and "why".
- Owner:
sdp.prd - Output:
spec/<feature-slug>/PRD.md
- Owner:
-
Refinement (Backlog): Break PRD into epics and right-sized stories (INVEST: Independent, Negotiable, Valuable, Estimable, Small, Testable — target ~1 day/1 PR of effort per story; split anything larger).
- Owner:
sdp.analyst - Output:
spec/<feature-slug>/BACKLOG.md,EPIC-*.md - Each epic declares a
security_reviewpolicy (see Security Review Policy below).
- Owner:
-
Architecture (Design): Create the technical design, including a rough complexity/effort rating per story so oversized stories are caught before planning.
- Owner:
sdp.architect - Output:
spec/<feature-slug>/DESIGN.md
- Owner:
-
Planning (Task Plan): Create an implementation plan for exactly one story. Does not write code.
- Owner:
sdp.planner - Output:
spec/<feature-slug>/PLAN.md, including a mandatory Scope Budget (see below).
- Owner:
-
Implementation (Code): Execute the approved plan exactly.
- Owner:
sdp.developer - Output: Code, tests, and docs. Appends to
HISTORY.md. - Terminal step: once implementation is complete, the only valid next action is handing off to
sdp.reviewer.sdp.developernever re-invokes itself and never regeneratesPLAN.mdon its own initiative.
- Owner:
-
Hardening (Validate): Review, secure, and test.
- Sequence:
sdp.reviewer→sdp.security(unless waived/deferred, see policy below) →sdp.qa - Output: Review, audit, and QA reports appended to
HISTORY.md.
- Sequence:
Plan Scope Budget (Gate 4, mandatory)
To keep implementation time and token usage predictable, every PLAN.md MUST declare a Scope Budget before it can be approved:
| Field | Limit |
|---|---|
| Files touched | 8 max |
| Estimated changed lines | 300 max (guideline, not a hard line-counter) |
| Complexity tier | S / M / L — L requires an explicit justification note |
| Exploration budget | Stated up front (e.g., "read only files listed in DESIGN.md section X") |
Rule: If a plan would exceed these limits, sdp.planner MUST stop and recommend splitting the story, returning it to Gate 2 (sdp.analyst) for re-slicing instead of producing an oversized plan. Do not silently plan past the budget.
Gate 4 → Gate 5 Handoff (Loop Prevention)
sdp.planner (plan-task) and sdp.developer (implement) are separate agents with no self-referencing handoff. This prevents the plan → implement → implement → implement loop seen when a single agent's mode is ambiguous:
sdp.planneronly ever producesPLAN.mdwithstatus: draftand stops. It never calls itself and never callssdp.developerautomatically.- Moving from Gate 4 to Gate 5 requires an explicit user action: approving the plan (
status: approved) and running/implement. sdp.developeronly ever hands off forward tosdp.reviewerafter implementation. It never re-enters implementation or planning on its own.- If an approved plan needs to change mid-implementation,
sdp.developerMUST stop, explain why, and request the user route back to/plan-taskfor an amended, re-approved plan — it must not silently keep "implementing" in a loop.
Hardening Gate Rules (Gate 6)
Unified Severity Taxonomy
sdp.reviewer, sdp.security, and sdp.qa all use the same four-level severity scale so findings can be aggregated and gated consistently:
| Severity | Meaning | Gate outcome |
|---|---|---|
| Critical | Breaks correctness, security, or data integrity | Always blocks; must return to Gate 5 |
| High | Significant risk or defect, must fix before ship | Blocks; must return to Gate 5 |
| Medium | Should fix, does not block this story | Logged in HISTORY.md as tracked debt |
| Low | Cosmetic/suggestion | Logged only, no action required |
Security Review Policy (per-epic, configurable)
Security audits are not always required per-story. BACKLOG.md/EPIC-*.md declares one of:
per-story(default) —sdp.securityruns on every story before QA.epic-level—sdp.securityis deferred until all stories in the epic are implemented, then runs once against the full epic diff.sdp.reviewerhands off directly tosdp.qafor individual stories and notes the deferral inHISTORY.md; the epic cannot be marked done until the deferred audit completes.waived— Security audit is intentionally skipped, with a documented reason recorded in the epic'ssecurity_reviewfield (e.g., "internal tooling, no external input, no auth/data boundary changed").sdp.reviewerhands off directly tosdp.qaand logs the waiver and reason inHISTORY.md. Agents must not complain or block when a waiver is explicitly declared — but must complain and stop ifsecurity_reviewis unset/ambiguous on a story that touches auth, secrets, external input, or data boundaries.
Loop Breaker / Escalation
Hardening feedback loops (reviewer/security/qa → developer → hardening again) are capped:
- After 2 failed hardening cycles on the same story (i.e., the same story fails review, security, or QA twice), the responsible agent MUST stop auto-retrying and escalate to the user for a decision (e.g., descope, split the story, accept documented risk) instead of routing back to Gate 5 a third time.
- Escalations are logged in
HISTORY.mdwith the cycle count and reason.
Feedback Loops
Failures route back to the appropriate gate, not to the start.
| Finding Source | Returns To | Action |
|---|---|---|
sdp.reviewer (Critical/High) |
Gate 5 | Developer fixes findings. |
sdp.security (Critical/High) |
Gate 5 or 3 | Developer or Architect fixes issues. |
sdp.qa (fail) |
Gate 5 | Developer fixes defects. |
| Blocked Story | Gate 2 | Analyst updates backlog. |
| PRD Gaps | Gate 1 | PRD agent updates PRD. |
| 2x failed hardening cycle on same story | User (escalation) | User decides: descope, split, or accept risk. |
Rule: Never silently fix and continue. Feedback loops must be explicit. See Loop Breaker above for the retry cap.
Cross-Gate Rules
- Reference
@/.github/TECH.mdfor stack and standards. - Resolve
AGENTS.mdbefore broad file searches. - Maintain traceability: PRD -> Backlog -> Design -> Plan -> Code -> Validation.
- Block on incomplete, ambiguous, or unapproved (
status: draft/rejected) artifacts. - Implement one story at a time through Gates 4-6.
- Prefer the prompt commands (
/create-prd,/refine-backlog,/design-system,/plan-task,/implement,/run-review,/audit-security,/qa-validate,/discover-tech) over manually invoking an agent.
This file was generated by APM CLI. Do not edit manually.
To regenerate: apm compile
