## SDLC Compliance Process (MANDATORY)

This project follows the Metasession SDLC framework. These rules are MANDATORY and OVERRIDE default behaviour.

### 🛑 SYSTEM OVERRIDE: AUTOMATED SDLC ENFORCEMENT

If you are an AI agent reading this file, you are strictly prohibited from manually executing this workflow step-by-step unless explicitly authorized by the operator. Route immediately to your platform's valid orchestration path:

- **CLAUDE CODE:** Halt manual tracking immediately. Invoke the orchestrator skill via: `Skill(name: "sdlc-implementer", …)` 
- **OTHER AGENTS (Cursor, Windsurf, Gemini, etc.):** Halt manual execution and output this exact message to the user: 
  "I am pausing to request authorization for the SDLC workflow on this issue. Please confirm if I should proceed."
  
  CRITICAL WORKFLOW REQUIRED AFTER AUTHORIZATION: Once the operator grants permission to proceed, you MUST immediately execute 'touch .sdlc-implementer-invoked' to generate the required commit sentinel file in the root directory BEFORE making any file modifications or code changes. Failure to create this file will result in your local git commits being automatically blocked by our pre-commit hooks.

### SDLC Workflow Files

Detailed workflow instructions are in this project's `SDLC/` directory. Read the relevant workflow file before executing each stage:

- Stage 0: `SDLC/0-project-setup.md` — One-time project initialisation
- Stage 1: `SDLC/1-plan-requirement.md` — Starting a new feature or tracked change
- Stage 2: `SDLC/2-implement-and-test.md` — Writing and testing code
- Stage 3: `SDLC/3-compile-evidence.md` — After implementation, before PR
- Stage 4: `SDLC/4-submit-for-review.md` — Creating the PR to main
- Stage 5: `SDLC/5-deploy-main.md` — After PR approval, deploying

When a workflow step requires detailed commands or templates, read the full workflow file rather than relying on the summary below.

### Entry point: the `sdlc-implementer` skill

The default way to implement a tracked change is the **`sdlc-implementer`** skill (`.claude/skills/sdlc-implementer/SKILL.md`): give it one GitHub issue and it runs Stage 1 (classify risk, assign the next `REQ-XXX`, write the implementation plan, update `RTM.md`) through Stage 4 (PR + UAT review), delegating all end-to-end / visual test work to `e2e-test-engineer`. **Do NOT hand-roll implementation outside this flow** — every change starts from a requirement, which starts from an issue. The only exceptions are trivial housekeeping (docs, formatting, dependency bumps, CI tweaks).

**This is enforced, not just advised.** `feat` / `fix` / `refactor` / `perf` commits that cite no requirement (`[REQ-XXX]` in the subject or a `Ref: REQ-XXX` trailer) are **rejected** locally by the commit-msg hook (commitlint) and at PR CI by `validate-commits.sh` (which `--no-verify` cannot skip). So implementation work cannot reach `develop` without a requirement — which is also what keeps release labels correct (the version-deriver only falls back to a bare date for genuine housekeeping, never for real feature work). Housekeeping commit types remain exempt.

### MANDATORY: `sdlc-implementer` prompt before implementation (devaudit-installer#199)

When the user requests implementation of an issue (e.g. "implement issue #N", "fix issue #N", "do issue #N", "implement #N"), you MUST prompt before writing any code:

> Implementing #N using sdlc-implementer, can I proceed?

Wait for the user's yes/no response. Do NOT begin implementation until they answer.

- **YES** → route to your platform's orchestration path:
  - **Claude Code:** invoke the `sdlc-implementer` skill immediately via `Skill(name: "sdlc-implementer", …)`. The skill drives Phase 0 (triage) through Phase 4 (PR + UAT review).
  - **Other agents (Cursor, Windsurf, Gemini, etc.):** proceed with the SDLC workflow manually, following the stage docs in `SDLC/`. **You MUST first create the commit sentinel:** `touch .sdlc-implementer-invoked` — without this file, the `commit-msg` and `pre-push` hooks will reject `feat`/`fix`/`refactor`/`perf` commits.
- **NO** → proceed with manual implementation outside the SDLC workflow. The user has explicitly opted out; respect their choice and do not ask again for the same issue.

This prompt is **mandatory and structural** — it is not advisory. The `sdlc-implementer` is the default entry point; manual implementation is the explicit opt-out. Skipping the prompt and jumping straight into code is the same class of inertia-trap bug as #132 (e2e delegation bypass).

The only exception: if the user's request is clearly housekeeping ("bump a dep", "fix a typo", "update docs") and does not involve `feat`/`fix`/`refactor`/`perf` commit types, skip the prompt and proceed directly.

### Anti-pattern: manually walking through SDLC stages instead of invoking the skill (devaudit-installer#199)

The most common failure mode for this rule is **not skipping the prompt entirely** — it is **prompting (or being told to use the skill) and then manually reading the SDLC workflow files and walking through the steps yourself** instead of invoking the `sdlc-implementer` skill. The skill exists to orchestrate this. Manually reading `SDLC/1-plan-requirement.md`, `SDLC/2-implement-and-test.md`, etc. and executing their steps by hand is the exact failure mode this rule exists to prevent.

**Self-check — if you find yourself doing any of these, STOP:**
- Reading `SDLC/1-plan-requirement.md` directly instead of invoking the skill
- Manually classifying risk, writing an implementation plan, or updating the RTM by hand instead of letting the skill drive it
- Walking through Stage 1 → Stage 2 → Stage 3 sequentially by reading each workflow file
- Saying "let me read the SDLC workflow files" or "let me follow the SDLC process" without invoking the skill

**When you catch yourself:** Stop immediately and route to your platform's orchestration path:
- **Claude Code:** Invoke the skill with `Skill(name: "sdlc-implementer", …)`. The skill will re-read state and resume correctly.
- **Other agents (Cursor, Windsurf, Gemini, etc.):** Ensure you have operator authorization and have created the commit sentinel (`touch .sdlc-implementer-invoked`). Then follow the stage docs step by step, pausing at each gate for operator confirmation.

**Structural enforcement (not just advisory):**
- Every SDLC stage doc (`SDLC/1-plan-requirement.md` through `SDLC/5-deploy-main.md`) and `SDLC/implementing-an-sdlc-issue.md` now opens with a **SYSTEM OVERRIDE banner** naming this anti-pattern and providing agent-agnostic routing instructions. If you read one of those files manually, the first thing you see is the warning. Heed it.
- The `commit-msg` hook checks for the `.sdlc-implementer-invoked` sentinel on `feat`/`fix`/`refactor`/`perf` commits. If the skill was not invoked (or the sentinel was not manually created by a non-Claude agent with operator authorization), **the commit is refused** — not just the push, the commit itself.
- The `pre-push` hook provides a second sentinel check (defence in depth).
- CI's `validate-commits.sh` checks RTM provenance — the unskippable safety net.

This anti-pattern is the same class of bug as #132 (e2e delegation bypass): the agent has a purpose-built tool and defaults to hand-rolling the procedure it automates. Use the tool — or, for non-Claude agents, follow the authorized manual path with the sentinel in place.

### Driver clarity — always state who is driving (devaudit-installer#199)

The operator must be able to tell at a glance whether they need to act or whether the agent is handling it. **Every substantive response during SDLC work MUST open with a driver tag** on the first line, before any other content:

- **`[Agent driving]`** — the agent is auto-continuing; no human action needed right now. The operator can look away.
- **`[Operator driving]`** — the agent has halted; the human must do something (review, approve, merge, answer a question). State the specific action needed.
- **`[Blocked]`** — something failed and the agent cannot proceed. State the blocker and the operator action needed to unblock.

Rules:
- The tag is the **first thing** in the response — no preamble, no acknowledgement, no "Great question" before it.
- If the driver changes mid-response (e.g. the agent was driving, hits a gate failure, and halts), the tag at the top of the response reflects the **final** state. If the agent stops mid-work, the tag is `[Operator driving]` or `[Blocked]`.
- The tag is mandatory for any response that does work, reports status, or hands off. Skip it only for pure chitchat or one-word confirmations.
- The tag works alongside the LAST/NEXT sticky convention — the tag says *who* is driving right now; the sticky says *what* just happened and *what* is next.

**Why this exists:** Without an explicit driver tag, the operator cannot distinguish "the agent is working and I can wait" from "the agent stopped and I need to act" without reading the entire response. That ambiguity is the root cause of both false-waits (operator thinks the agent is working when it has halted) and false-stops (operator thinks they need to act when the agent is auto-continuing).

### Before ANY Code Change

1. If the user has NOT been prompted for `sdlc-implementer` and the change is not trivial housekeeping, stop and run the mandatory prompt above before continuing.
2. Ask: "Which GitHub Issue is this for?" before writing code. Fetch it with `gh issue view NNN`.
3. If no issue exists: ask if one should be created. When creating via `gh issue create`, ALWAYS append the SDLC checklist to the body (see below).
4. If new requirement needed: read `SDLC/1-plan-requirement.md` and follow it BEFORE implementing.
5. If trivial (typo/formatting): proceed without requirement but use conventional commit format.
6. Verify `develop` branch: `git branch --show-current` — never implement on `main`.

### For ALL Code Changes (including bug fixes)

Even if a change doesn't need a REQ entry:
1. Review existing tests that cover the changed code
2. Update or add tests BEFORE committing
3. Run the applicable local checks from the approved scope/test plan — do not push without verifying the change-relevant commands pass
4. If the change affects financial calculations, user-facing data, or access control — it needs a REQ entry regardless of size

What needs a REQ entry: New features → always. Bug fixes affecting financial data, user-facing behaviour, access control → always. Internal logic → only if MEDIUM/HIGH risk. Typos, formatting, dependency bumps → never.

### Creating GitHub Issues

When creating an issue via `gh issue create`, ALWAYS append this to the body:

## SDLC Checklist
- [ ] Requirement: RTM entry created (or confirmed trivial)
- [ ] Planning: test-scope.md and test-plan.md created (or confirmed trivial)
- [ ] Tests: existing tests reviewed, tests updated/added
- [ ] Gates: applicable local checks pass; CI/UAT full gates pass where required
- [ ] Evidence: compiled and uploaded (if tracked requirement)

### Requirement Planning (do this BEFORE coding)

Read `SDLC/1-plan-requirement.md` for full details. Summary:

1. Confirm GitHub Issue `#NNN` exists (create if needed via `gh issue create`).
2. Get next REQ ID: `grep -oP 'REQ-\d+' compliance/RTM.md | sort -t- -k2 -n | tail -1`
3. Classify risk (use issue labels as input): LOW (internal, no auth) / MEDIUM (PII, user-facing, APIs) / HIGH (security, payments, RBAC). AI involvement raises risk by one level.
4. Add to `compliance/RTM.md` Part B: `| REQ-XXX | #NNN | [RISK] | compliance/evidence/REQ-XXX/ | DRAFT | -- | -- |`
5. **MEDIUM/HIGH risk:** Create `compliance/evidence/REQ-XXX/implementation-plan.md` from `SDLC/Implementation_Plan_TEMPLATE.md` (synced from the framework in v0.1.37+). The template's shape is load-bearing — it carries the `## Framework attribution` section that closes **ISO 29119 §3.4** (test plan), **ISO 27001 A.8.25** (secure SDLC), **GDPR Art. 25** (data protection by design), and **EU AI Act Art. 11** (technical documentation). Don't delete sections — mark with `N/A — <reason>` if a clause genuinely doesn't apply. **WAIT CHECKPOINT:** Present the plan to the developer. Do NOT proceed until approved.
6. Create `compliance/evidence/REQ-XXX/test-scope.md` with acceptance criteria (derived from the implementation plan for MEDIUM/HIGH).
7. **WAIT CHECKPOINT:** Present the test scope to the developer. Do NOT proceed until confirmed.
8. Create `compliance/evidence/REQ-XXX/test-plan.md` — map acceptance criteria to specific tests, list tests to add/update/remove. Distinguish unit tests (TDD, before implementation) from E2E tests (after implementation).
9. **WAIT CHECKPOINT:** Present the test plan to the developer. Do NOT proceed until confirmed.
10. Create `compliance/evidence/REQ-XXX/ai-use-note.md` if AI is involved.
11. Commit plan: `compliance: [REQ-XXX] define requirement, test scope, and test plan`

### During Implementation

Read `SDLC/2-implement-and-test.md` for full details. Summary:

- **Before coding:** Verify ALL exist: `ls compliance/evidence/REQ-XXX/test-scope.md` AND `ls compliance/evidence/REQ-XXX/test-plan.md`. If either is missing, STOP and run planning workflow first. For MEDIUM/HIGH also verify `implementation-plan.md` exists.
- **Phase 1 — Unit tests (TDD):** Write unit tests before implementation. Tests should initially fail. **CHECKPOINT:** Unit test coverage matches test plan.
- **Phase 2 — Implementation:** Write the code. Unit tests should now pass. **CHECKPOINT:** All unit tests green.
- **Phase 3 — E2E tests:** Write E2E tests against the working implementation when the test plan calls for E2E coverage. Before starting a full local E2E suite, confirm local prerequisites (services, database, secrets, seeded auth/test data, browsers). If prerequisites are missing, run the targeted local checks from the test plan and let CI/UAT provide the authoritative full E2E gate.
- **Phase 4 — All gates:** Run the applicable local gate suite for the change (TypeScript/SAST/dep audit/unit or targeted tests/build as specified). **CHECKPOINT:** Local scoped checks are green, then push to develop for authoritative CI gates.
- Every commit: conventional format with `Ref: REQ-XXX` and `Co-Authored-By` for AI.
- Add `@requirement REQ-XXX` JSDoc headers to modified files.
- Log AI prompts in `compliance/evidence/REQ-XXX/ai-prompts.md` for MEDIUM/HIGH risk.

### Before Pushing

Run the local checks required by the approved test plan/scope. For a typical code change this includes:
```
npx tsc --noEmit                    # 0 errors
semgrep scan --config auto src/     # 0 high/critical
npm audit --audit-level=high        # 0 vulnerabilities
npm test                            # unit/integration tests pass
```

**Full local E2E boundary:** Do NOT start `npx playwright test` locally unless you have confirmed the local environment has every required service, database, secret, seeded fixture, authenticated test setup, and browser dependency. For LOW-risk docs/tooling/script-only changes, run the targeted commands in the approved test plan and rely on CI/UAT for the full E2E gate unless the operator explicitly requests a local full-suite run.

**Verify test plan tests are written:** For tracked requirements, check that every test file referenced in `compliance/evidence/REQ-XXX/test-plan.md` exists and passes. If `test-plan.md` lists tests that haven't been written yet, STOP — write and run the tests before pushing.

### After Pushing: WAIT — Confirm CI Green

```
gh run list --branch develop --limit 1
```

Do NOT proceed to evidence compilation or PR creation until CI is green. If CI fails, fix locally and re-push. CI/UAT is the authoritative full E2E verification environment when local prerequisites are unavailable.

### Evidence Storage Rule

Markdown stays in git. Binary/JSON evidence goes to DevAudit portal.

Upload to DevAudit (NEVER commit to git):
- E2E results (JSON), screenshots (PNG/JPG), SAST results (JSON), dependency audit (JSON), unit test output (TXT), test reports (HTML)

Keep in git (small markdown, needs PR review):
- compliance/RTM.md, test-scope.md, security-summary.md, ai-use-note.md (YAML frontmatter — devaudit-installer#197), ai-agent-handoff.md (if AI agent changed mid-implementation), ai-prompts.md, release tickets

### AI Contributor Tracking (devaudit-installer#197)

- `ai-use-note.md` uses YAML frontmatter with an `ai_contributors` list supporting multiple entries (tool, version, session_id, date_range, commits).
- The `prepare-commit-msg` git hook warns when the `Co-Authored-By` trailer changes between commits on the same branch, prompting creation of an `ai-agent-handoff.md` entry.
- The release ticket template includes an AI Contributors table with handoff and verification fields.
- Legacy `ai-use-note.md` files without YAML frontmatter are still accepted (portal falls back to text parsing).

### After Implementation

Read `SDLC/3-compile-evidence.md` for full details, including release ticket template. Summary:

1. Confirm CI is green before compiling evidence: `gh run list --branch develop --limit 1`
2. Generate `compliance/evidence/REQ-XXX/test-execution-summary.md` — gate results, test changes, coverage against test plan
3. Upload binary/JSON evidence to DevAudit portal
4. Create `compliance/evidence/REQ-XXX/security-summary.md` (in git)
5. Update RTM status to `TESTED - PENDING SIGN-OFF`
6. Create `compliance/pending-releases/RELEASE-TICKET-REQ-XXX.md` (use template from workflow file). If the change requires post-deploy actions (data migrations, backfill scripts), document them in the release ticket's Post-Deploy Actions section with exact commands
7. Commit compliance markdown locally (do NOT push yet — batch with UAT results)
8. **WAIT CHECKPOINT:** Confirm CI + UAT deployment complete before UAT verification.
9. **Verify on UAT** (if configured) — health check, smoke test, feature verification. Record in `security-summary.md`. Commit locally. Do NOT create a PR until UAT is green.
10. **Push all compliance commits** in a single push: `git push origin develop`
11. **Verify release in DevAudit** — CI auto-creates releases and links evidence. Check that a release exists with the current version (date-based: `v{YYYY}.{MM}.{DD}` or `v{YYYY}.{MM}.{DD}.{N}` for multiple releases on the same day) and evidence is linked.

### Pre-Flight Checklist (Before Creating PR)

**Do NOT create the PR until ready to merge.** Every push to `develop` while a PR is open triggers duplicate CI runs. The PR is the merge request, not the development workspace.

Before creating a PR, verify ALL of the following:
- [ ] All development and iteration is complete
- [ ] CI green on develop (not stale): `gh run list --branch develop --limit 1`
- [ ] Working tree clean: `git status`
- [ ] UAT verification passed (if configured)
- [ ] DevAudit UAT approval granted
- [ ] For tracked requirements: test-scope.md complete, implementation-plan.md exists (MEDIUM/HIGH), RTM is `TESTED - PENDING SIGN-OFF`, release ticket created, evidence uploaded

If any item fails, resolve it before proceeding.

### Status Reporting (MANDATORY before handing off)

Before describing a PR as "awaiting review", "waiting on reviewers", "ready to merge", "Stage 4/5 requires human action", or any other happy-path language, you MUST:

1. Run `gh pr checks <PR>` and capture the full output, and `gh pr view <PR> --json mergeable,mergeStateStatus` for GitHub's own mergeability signal.
2. If ANY required check is `fail` or `pending`, do NOT use happy-path language. Instead report:
   - Each failing check by name, with its error (from `gh run view <RUN> --log-failed` if needed)
   - Each pending check by name
   - The concrete fix you are about to apply, or a specific question for the developer
3. If `mergeStateStatus` is anything other than `CLEAN` or `BLOCKED` (blocked only by required-reviewer approval), treat it as an open issue and investigate before claiming "ready".
4. If `gh` itself fails (auth, rate limit, network): report "status unknown — gh call failed", never assume green.
5. Only when every required check is `pass` AND the PR is mergeable may you say "awaiting review" or "awaiting approval".

A summary like "awaiting UAT + 2 reviewers" reads to the developer as "nothing to do but approve." If a required check is red, that summary is a lie by omission — the PR cannot merge regardless of what the reviewer does.

This rule applies any time you summarise PR state in chat, not only at the final handoff.

### Review Policy (Risk-Tiered)

- **LOW risk:** CI provides independent verification. Self-merge is permitted after all CI checks pass.
- **MEDIUM/HIGH risk:** A second human reviewer MUST approve before merge. Self-merge is NOT permitted.

### Rules (NEVER break these)

- NEVER code without a GitHub Issue and requirement entry for tracked changes
- NEVER push without all four gates passing
- NEVER self-merge a MEDIUM or HIGH risk PR — a second human reviewer MUST approve
- NEVER use `--no-verify` to skip hooks
- NEVER commit secrets (.env, credentials, API keys)
- NEVER commit binary/JSON evidence to git — upload to DevAudit instead
- NEVER create a PR to main without UAT verification passing first (if UAT configured)
- NEVER push directly to main — always develop → PR → main
- NEVER skip Co-Authored-By when AI generates code
- NEVER proceed past a WAIT CHECKPOINT without developer confirmation
- NEVER describe a PR as "awaiting review" or "ready to merge" without first running `gh pr checks <PR>` and confirming every required check is `pass`
- ALWAYS commit compliance markdown to git (RTM, test-scope, implementation-plan, security-summary, release tickets)
- ALWAYS use merge commits (not squash) for develop → main
