<!-- AUTO-GENERATED FROM ai-tools/shared-prompts/. DO NOT EDIT DIRECTLY. -->
<!-- To change: edit _header-cursor.md or standards.md, then run scripts/build-ai-configs.sh -->

<!-- Tool: Cursor. Output path: .cursorrules -->
# .cursorrules — Project rules for Cursor

You are an expert AI pair-programmer working in this repo. You MUST follow the rules below.

## Project context
- See `CLAUDE.md` (root) for project overview, tech stack, and SDLC structure.
- This repo organizes work into 4 SDLC phases under `01-Planning/`, `02-Design/`, `03-Development/`, `04-Testing-Deploy/`.

## Agent / autonomous mode
- Follow `automation/AGENT-LOOP.md`. Read `automation/state.json` to know progress.
- Stop for clarification / gate / high-risk action — never bypass.

## Always
1. Read existing code in the same folder before writing new code; match style.
2. Follow `03-Development/standards/coding-standards.md`.
3. Follow `03-Development/standards/error-handling.md`.
4. For any auth, crypto, payment, or PII path: read `03-Development/standards/security-checklist.md` first.
5. Tests: write or update tests for any change. AAA pattern.
6. Keep diffs small (≤ 200 lines per change). Split large work.
7. Use TypeScript strict / Python typed / Go errcheck — no shortcuts.
8. Structured logging only (`logger.info({ ... })`).

## Never
- Never invent APIs, packages, or types. If unsure, say so.
- Never commit secrets / API keys / PII.
- Never use `any`, bare `except`, empty `catch`.
- Never bypass authorization checks "to make tests pass".
- Never reformat unrelated files.
- Never write code without running it / linting it mentally first.

## Patterns to prefer
- Pure functions, push side-effects to edges.
- Result types over exceptions for expected failure.
- Discriminated unions over class hierarchies.
- Composition over inheritance.
- Feature flags around risky paths.

## Output format
- Concise reasoning, then code.
- Mention which files you change and why.
- End with a "How to verify" section.

## When user asks for a feature
1. Restate the requirement.
2. Identify edge cases.
3. Propose a plan (≤ 5 steps).
4. Wait for approval, then implement step-by-step.

## Disclosure
- If your output is non-trivial code, remind the user to add Cursor to the PR's AI-tool disclosure section (`03-Development/templates/PR-Template.md`).

<!-- standards.md — shared body included into every AI tool config. -->
<!-- Source of truth. Edit this file (and per-tool _header-*.md) only. -->

## ⛔ CONTRACT — violating these breaks the state machine

1. NEVER edit `automation/state.json`, `automation/tasks/*.yaml`, or any
   file under `automation/` directly. Only `sdlc <cmd>` mutates these.
2. NEVER work on more than one Phase 3 task at a time. The active task is
   `state.json → phase3.active_story_id`. If your task ID does not match,
   STOP and run `sdlc auto-step` — it will tell you what to do.
3. NEVER skip a phase. If Phase 3 has an active task, you do NOT touch
   Phase 4/5 files no matter how stuck you feel. Write a clarification
   under `automation/clarifications/` instead.
4. The ONLY way to advance is `sdlc auto-step` between every change. Do
   not infer "next" from folder order or file names.

## When you are stuck

DO: write `automation/clarifications/<NNN>-<slug>.md` with `STATUS: open`,
explain what you don't know, then STOP. The user will resolve and re-prompt.

DO NOT: pick a different task, switch to another phase, edit state.json to
"unblock" yourself, or fabricate a deliverable to look productive.

---

## ⚡ Subagent priority — read this first

This repo has 11 specialist subagents in `.claude/agents/`. Files include:

- **Phase 1**: `pm-agent.md`
- **Phase 2 architecture**: `architect-agent.md`
- **Phase 2 UI/UX**: `ux-designer.md`
- **Phase 3 task stages**: `test-author.md` (write-tests), `developer-agent.md` (write-code), `code-reviewer.md` (review)
- **Phase 4 E2E**: `qa-engineer.md`
- **Phase 5 deploy & monitor**: `sre-agent.md`
- **Cross-cutting**: `security-reviewer.md`, `doc-keeper.md`, `clarification-triager.md`, `orchestrator.md`

**When the user says "use the X subagent ..." or runs `/agents X`, you MUST honour the named subagent and not delegate to plugin skills (e.g. brainstorming).** The subagent files in `.claude/agents/` are this repo's authoritative role specs. If you have a plugin skill whose description overlaps with what the user asked, defer to the named subagent.

## ⚡ Default behaviour when the user shares a project idea

If the user's first substantive message in this repo describes a **project idea / requirement / what they want to build** ("I want to build", "let's start a project", "yêu cầu là...", "tôi muốn build", a pasted brief, etc.) — and `automation/state.json` shows `prd-drafted` is **NOT done** — then **automatically**:

1. Adopt the **`pm-agent`** role (read `agents/phase-1-pm.md`).
2. Read `01-Planning/templates/01-PRD.md` for structure.
3. Read `automation/rules.json` → find item `prd-drafted` → know what evidence is required.
4. Save the user's raw idea to `01-Planning/IDEA.md`.
5. Write the actual filled-in PRD to **`01-Planning/01-PRD.md`** (NOT into `templates/`), replacing all `{{PLACEHOLDERS}}`. Quantify NFRs (p95 / p99 / RTO / RPO / uptime%). Leave at most 5 placeholders for genuinely unknown values, marked `{{TBD: <reason>}}`.
6. **Append the verify marker** at the bottom: `<!-- sdlc:verified-by: <user-name> <iso-date> -->`. The user may overwrite later via `sdlc verify prd-drafted --name=<who>`.
7. Briefly tell the user what you wrote and what's next: `sdlc scan --print`, `sdlc next`.
8. **Stop**. Do not auto-progress to user stories / requirements unless the user asks. Phase 1 has more items (`user-stories`, `nfr-targets`, `stakeholder-map`, `risks-identified`); the user picks pace.

**STOP triggers** (write `automation/clarifications/<NNN>-...md` with `STATUS: open` and halt):
- 🔍 Ambiguity: idea too vague to fill required PRD sections
- ⚔️ Conflict: user gave conflicting constraints
- 🛑 High-risk path: idea touches auth/crypto/payment/secrets/migrations and needs explicit direction

---

## SDLC framework — 5-phase model

This repo follows a 5-phase SDLC. Every change should advance one of the Definition-of-Done items tracked in `automation/state.json`. Run `sdlc scan --print` to see current state.

### Phases (high-level)

1. **Planning** (`01-Planning/`) — PRD, user stories (G/W/T), quantified NFRs, stakeholder map + RACI, risks. Per-artifact verify required.
2. **Design** (`02-Design/`) — two sub-tracks:
   - 🏛️ **Architecture**: C4, API spec (OpenAPI), DB schema, ADRs, STRIDE threat model
   - 🎨 **UI/UX**: UI spec, wireframes, design system, accessibility (WCAG)
3. **Development** (`03-Development/`) — two sub-tracks:
   - 🛠️ **Setup**: coding standards, git workflow, PR template, security checklist, AI tool configs, AI disclosure, TDD coverage (mostly green post-`sdlc init`)
   - ✅ **Tasks**: per-feature Kanban with sequential TDD strict (5 stages: pending → write-tests → write-code → review → committed; each label names the activity in flight, not the artifact already produced)
4. **E2E & Integration Testing** (`04-Testing-Deploy/`) — test plan, E2E suite, integration, smoke, regression, load tests
5. **Deploy & Monitor** (`04-Testing-Deploy/`) — CI/CD, deploy runbook, SLOs, incident response, observability dashboard

### Per-artifact verify (Phase 1, 2, 4)

Each artifact has a two-state model: `drafted` + `verified`. Both must be true for the item to be `done`.

To verify, append the marker at the bottom of the file (or run `sdlc verify <item-id>`):

```markdown
<!-- sdlc:verified-by: <name> <iso-date> -->
```

Three visual states on the dashboard: ⚪ pending → 🟡 drafted, awaiting verify → ✅ verified.

### Phase 3 task lifecycle (sequential TDD strict)

Tasks live in `automation/tasks/<id>.yaml`. Each task progresses through 5 stages. Stage detection is automatic (filesystem state + the `committed_at` field on the task yaml). **Stage labels name the activity in flight, not the artifact already produced** — e.g. `write-tests` means test-author is writing tests right now, not "tests have been written":

| Stage | When (filesystem state) | Activity in flight |
|-------|-------------------------|--------------------|
| `pending` | task is queued behind the Phase 3 serial lock (inactive group) | none — waits for active group to finish |
| `write-tests` | active task, no deliverables yet (or code-without-tests → backfill) | `test-author` writes tests |
| `write-code` | tests exist, no code yet | `developer-agent` writes code |
| `review` | both files exist, `committed_at` not yet set | `code-reviewer` (or `security-reviewer` if sensitive area: auth/crypto/payment/secrets/migrations) reviews locally |
| `committed` | `committed_at` set on yaml — developer-agent staged+committed | terminal at task tier; story-tier handles PR/merge/deploy |

Each subagent runs in a **fresh context** — no memory leakage between stages. Strict TDD: tests come first, then code, then review.

**Serial lock (0.15.0+):** Only the task whose `story_id` (or `task.id`) matches `state.json → phase3.active_story_id` advances. All other tasks stay `pending` regardless of filesystem state. The engine auto-promotes the next group when the active group reaches `committed`. View with `sdlc story list` (look for `in-progress`); override with `sdlc story activate <slug>`; rollback with `sdlc story deactivate <slug>`.

When acting on a Phase 3 task, follow your stage's mandate strictly:
- `test-author` writes tests only — does not write production code
- `developer-agent` writes code that makes tests pass — does not modify tests
- `code-reviewer` does not modify code — leaves findings under `automation/reviews/<task-id>-<ts>.md`

Bootstrap tasks from user stories: `sdlc tasks bootstrap`. Manual task: `sdlc tasks new <id>`.

#### Grouping multiple tasks under one PR (`story_id`)

Real product work often splits one user requirement into 3-4 tasks. Asking the user to open 3-4 separate PRs for one requirement is friction without value. Add `story_id: <slug>` to each task yaml that belongs to the same requirement — all siblings then share one branch (`feature/<slug>` by default, or the first explicit `pr_branch` declared on any sibling). Each task terminates at `committed` independently; in v1.1.0 the story tier opens the single PR for the shared branch once every grouped task is `committed`, and merging it advances the story to `deployed`.

```yaml
# automation/tasks/cart-validate.yaml
id: cart-validate
story_id: checkout-flow
code_glob: "src/checkout/cart/**/*.ts"
test_glob: "src/checkout/cart/**/*.test.ts"
```

Code review still runs per task at the `review` stage with that task's globs — the grouping changes only the PR boundary, not the per-task TDD discipline.

### Standards live in `03-Development/standards/`

- `coding-standards.md`
- `git-workflow.md`
- `error-handling.md`
- `security-checklist.md`

Read them before writing code.

### Project metadata: `project.yaml`

When present, the engine reads:

- `schema_version: 2` (v2 phase model)
- `tier` (1=critical / 2=standard / 3=experiment) — drives DoD strictness
- `phase_target` (1..5) — focus phase
- `stack` — node / python / go (auto-detected)
- `owners` — sponsor, eng_lead, security, sre, qa (per-tier requirements)
- `legacy_code_globs` — paths excluded from TDD coverage (for retrofit projects)
- `e2e_glob`, `integration_glob` — Phase 4 detection overrides
- `observability` — `dashboard_url`, `on_call_runbook` (tier 1)

The engine fails `owners-defined` rule when required owners for the project's tier are missing.

### Autonomous loop rules

When operating without a human in the loop, follow `automation/AGENT-LOOP.md`. Stop and write a clarification file under `automation/clarifications/` when:

- Information is ambiguous or missing
- Two sources conflict
- A gate (sign-off) is required
- The task touches a high-risk path: auth, crypto, payment, secrets, database migrations, webhooks

Resolve a clarification: edit the file, change `STATUS: open` → `STATUS: resolved`. Approve a gate: write `automation/signoffs/<gate-id>.yaml` with `approved: true`.

### AI disclosure

Every PR must include the AI tool disclosure section from `03-Development/templates/PR-Template.md`. Do not omit it.

### Adopting on an existing running project

For a project that already has code, designs, or runbooks, run `sdlc adopt`. The wizard scans for existing assets (`docs/PRD.md`, `docs/ARCHITECTURE.md`, runbooks, SLO docs, CI workflows, source + test files), creates symlinks into the canonical SDLC paths, and auto-verifies them with the marker `imported-from-existing`. Idempotent and non-destructive.

For Phase 3 development on retrofits, set `legacy_code_globs: ["src/**"]` in `project.yaml` so existing code is grandfathered (no TDD enforcement); only new tasks under `automation/tasks/` go through the full TDD cycle.

### Autopilot mode (preferred)

When the user wants the framework to run on autopilot through pending items, loop on `sdlc auto-step`:

1. Run `sdlc auto-step` → returns JSON describing the next action.
2. If `action: "invoke"` → adopt the named agent role (from `agents/<role>.md`), **prepend the JSON `brief_context` field** (a role-tailored slice of `automation/.context-bundle.md`, ≤ ~600 tokens) to your prompt as pre-loaded orientation, follow the `instruction` field, write the deliverable, then **re-run `sdlc auto-step`**. Read the snippet first; only fall back to upstream artifacts when its detail is insufficient.
3. If `action: "stop"` → report `stop_reason` + `user_action` to the user, exit the loop. Stop reasons: `verify_needed`, `gate`, `clarification`, `high_risk`, `review_pending`, `tasks_empty` (Phase 3 reached without bootstrapped tasks — user must draft `01-Planning/02-User-Stories.md` then run `sdlc tasks bootstrap`).
4. If `action: "done"` → all phases complete. Celebrate.

Defensive cap: max 20 iterations per session. Re-run `sdlc auto-step` between every deliverable — don't trust your own state. Never skip a `stop`.

### MAD-mode autopilot (`sdlc auto-mad-step`)

⚠️  **Opt-in YOLO autopilot for prototypes / hackathons.** AI auto-signs Phase 1/2/4/5 signoffs and auto-verifies drafted artifacts. Do NOT use for production work where a human must review signoffs.

Difference from `auto-step`:

| Stop reason       | `auto-step` | `auto-mad-step` |
| ----------------- | ----------- | --------------- |
| `verify_needed`   | stop        | auto-verify (marker `ai-mad-mode`) |
| `gate`            | stop        | auto-sign (yaml `approved_by: ai-mad-mode`) |
| `clarification`   | stop        | stop (kept — agent cannot infer intent) |
| `high_risk`       | stop        | stop (kept — auth/crypto/payment policy) |
| `review_pending`  | stop        | stop (PR is external dep) |

Loop on `sdlc auto-mad-step` the same way as `auto-step`. The JSON output gains `auto_actions_taken: [{kind, item_id|gate_id, at}, ...]` listing every auto-signoff / auto-verification applied this iteration. Surface those to the user before invoking the next agent so the audit trail is visible.

Auto-signed yaml files clearly identify themselves (`approved_by: ai-mad-mode`, timestamp, version, `unsign_command`). To revert all in one shot:

```
grep -l "approved_by: ai-mad-mode" automation/signoffs/*.yaml | xargs rm
```

Stop reasons exclusive to mad mode: `auto_mad_cap` (defensive — 20 inner auto-actions without producing real work).

### Project memory bundle and pin file

Every `sdlc scan` regenerates `automation/.context-bundle.md` (mirrored at `dashboard/.context-bundle.md`) — a compact summary (≤ 12 KB) of project + goals + tech decisions + active item + recent runs + open clarifications + pending gates. When you adopt a specialist role from `agents/<role>.md`, read this bundle (or the role-tailored slice via `brief_context`) instead of re-reading PRD + stories + architecture for orientation.

User-curated facts that the engine cannot infer go in `automation/CONTEXT-PINS.md`:

```markdown
# Context Pins
## Tech decisions
- Auth: VNPay (NOT Stripe — switched 2026-04-15)
## Gotchas
- Postgres users.email — always wrap in LOWER(); legacy rows mixed-case.
```

Plain markdown — no DB, no service. The engine merges its contents verbatim under `## User pins` in the bundle. Missing/vacant files are skipped.

### CLI — recommended commands

```bash
# Autopilot
sdlc auto-step                        # JSON: action=invoke|stop|done + agent + instruction

# Daily flow (single-step)
sdlc resume                           # "where am I?" — phase, last activity, next action
sdlc next                             # paste-ready prompt for the next pending DoD item
sdlc scan --print                     # progress summary
sdlc verify <item-id>                 # mark a Phase 1/2/4 artifact verified

# Tasks (Phase 3)
sdlc tasks bootstrap                  # auto-create tasks from user stories
sdlc tasks list                       # tasks with current stage
sdlc tasks new <id>                   # manual task creation

# Adjustments
sdlc replan                           # mark items dirty after a major change

# Engine + dashboard
sdlc scan --watch                     # background scanner with notifications
sdlc dashboard                        # serve UI on localhost
```

### Logging your run (optional)

When you start working on an SDLC item, append a `start` entry to the activity log; when you finish, append `done` or `fail`:

```bash
# at the start
SDLC_TOOL=<your-tool> sdlc agent-log start <agent-name> <item-id>
# work...
# at the end
sdlc agent-log done <agent-name> <item-id> --summary="<one-line>"
# or on failure
sdlc agent-log fail <agent-name> <item-id> --summary="<error>"
```

The log is local-only, gitignored, capped at 50 entries. Failing to call the wrapper breaks nothing.

### Surfacing STOP triggers to GitHub

When you raise a clarification or gate-signoff placeholder, optionally file it on GitHub:

```bash
sdlc gh-issue --clarification automation/clarifications/<NNN>-...md
sdlc gh-issue --gate <gate-id>
```

Both wrappers are idempotent (skip on existing `issue_url:`) and exit 0 when `gh` is unavailable. For Phase 3 task review, open a Draft PR: `sdlc gh-pr`.
