From 46ec840235ae3d187e5726abbee519b24f84c15a Mon Sep 17 00:00:00 2001 From: Jonah Schulte Date: Mon, 26 Jan 2026 23:36:26 -0500 Subject: [PATCH] feat: add patterns library with @ reference support Phase 3: Patterns Library - Create src/bmm/patterns/ with reusable pattern files: - hospital-grade.md - Quality standards for safety-critical code - tdd.md - Test-driven development guidance - security-checklist.md - OWASP-based security review - verification.md - File and code verification patterns - agent-completion.md - Standard output format for agents - Update all agent templates with sections: - builder.md: @patterns/hospital-grade, tdd, agent-completion - inspector.md: @patterns/verification, hospital-grade, agent-completion - reviewer.md: @patterns/security-checklist, hospital-grade, agent-completion - fixer.md: @patterns/hospital-grade, agent-completion This follows GSD's @ reference pattern for loading context. --- src/bmm/patterns/agent-completion.md | 187 ++++++++++++++++++ src/bmm/patterns/hospital-grade.md | 111 +++++++++++ src/bmm/patterns/security-checklist.md | 122 ++++++++++++ src/bmm/patterns/tdd.md | 93 +++++++++ src/bmm/patterns/verification.md | 143 ++++++++++++++ .../super-dev-pipeline/agents/builder.md | 6 + .../super-dev-pipeline/agents/fixer.md | 5 + .../super-dev-pipeline/agents/inspector.md | 6 + .../super-dev-pipeline/agents/reviewer.md | 6 + src/modules/bmm/patterns/agent-completion.md | 187 ++++++++++++++++++ src/modules/bmm/patterns/hospital-grade.md | 111 +++++++++++ .../bmm/patterns/security-checklist.md | 122 ++++++++++++ src/modules/bmm/patterns/tdd.md | 93 +++++++++ src/modules/bmm/patterns/verification.md | 143 ++++++++++++++ .../super-dev-pipeline/agents/builder.md | 6 + .../super-dev-pipeline/agents/fixer.md | 5 + .../super-dev-pipeline/agents/inspector.md | 6 + .../super-dev-pipeline/agents/reviewer.md | 6 + 18 files changed, 1358 insertions(+) create mode 100644 src/bmm/patterns/agent-completion.md create mode 100644 src/bmm/patterns/hospital-grade.md create mode 100644 src/bmm/patterns/security-checklist.md create mode 100644 src/bmm/patterns/tdd.md create mode 100644 src/bmm/patterns/verification.md create mode 100644 src/modules/bmm/patterns/agent-completion.md create mode 100644 src/modules/bmm/patterns/hospital-grade.md create mode 100644 src/modules/bmm/patterns/security-checklist.md create mode 100644 src/modules/bmm/patterns/tdd.md create mode 100644 src/modules/bmm/patterns/verification.md diff --git a/src/bmm/patterns/agent-completion.md b/src/bmm/patterns/agent-completion.md new file mode 100644 index 00000000..d256c155 --- /dev/null +++ b/src/bmm/patterns/agent-completion.md @@ -0,0 +1,187 @@ +# Agent Completion Format + + +All agents must return structured output that the orchestrator can parse. This enables automated verification and reliable workflow progression. + +**Principle:** Return parseable data, not prose. The orchestrator needs to extract file lists, status, and evidence. + + + +## Standard Completion Format + +Every agent returns this structure when done: + +```markdown +## AGENT COMPLETE + +**Agent:** [builder|inspector|reviewer|fixer] +**Story:** {{story_key}} +**Status:** [SUCCESS|PASS|FAIL|ISSUES_FOUND|PARTIAL] + +### [Agent-Specific Section] +[See below for each agent type] + +### Files Created +- path/to/new/file.ts +- path/to/another.ts + +### Files Modified +- path/to/existing/file.ts + +### Ready For +[Next phase or action required] +``` + + + +## Builder Agent Output + +```markdown +## AGENT COMPLETE + +**Agent:** builder +**Story:** {{story_key}} +**Status:** SUCCESS | FAILED + +### Files Created +- src/lib/feature/service.ts +- src/lib/feature/__tests__/service.test.ts + +### Files Modified +- src/app/api/feature/route.ts + +### Tests Added +- 3 test files +- 12 test cases total + +### Implementation Summary +Brief description of what was built. + +### Known Gaps +- Edge case X not handled +- NONE if all complete + +### Ready For +Inspector validation +``` + + + +## Inspector Agent Output + +```markdown +## AGENT COMPLETE + +**Agent:** inspector +**Story:** {{story_key}} +**Status:** PASS | FAIL + +### Evidence +- **Type Check:** PASS (0 errors) +- **Lint:** PASS (0 warnings) +- **Build:** PASS +- **Tests:** 45 passing, 0 failing, 92% coverage + +### Files Verified +- src/lib/feature/service.ts ✓ +- src/app/api/feature/route.ts ✓ + +### Failures (if FAIL status) +1. Type error in service.ts:45 +2. Test failing: "should handle empty input" + +### Ready For +Reviewer (if PASS) | Builder fix (if FAIL) +``` + + + +## Reviewer Agent Output + +```markdown +## AGENT COMPLETE + +**Agent:** reviewer +**Story:** {{story_key}} +**Status:** ISSUES_FOUND | CLEAN + +### Issue Summary +- **CRITICAL:** 1 (security, data loss) +- **HIGH:** 2 (production bugs) +- **MEDIUM:** 3 (tech debt) +- **LOW:** 1 (nice-to-have) + +### Must Fix (CRITICAL + HIGH) +1. [CRITICAL] service.ts:45 - SQL injection vulnerability +2. [HIGH] route.ts:23 - Missing authorization check +3. [HIGH] service.ts:78 - Unhandled null case + +### Should Fix (MEDIUM) +1. service.ts:92 - No error logging + +### Files Reviewed +- src/lib/feature/service.ts ✓ +- src/app/api/feature/route.ts ✓ + +### Ready For +Fixer agent to address CRITICAL and HIGH issues +``` + + + +## Fixer Agent Output + +```markdown +## AGENT COMPLETE + +**Agent:** fixer +**Story:** {{story_key}} +**Status:** SUCCESS | PARTIAL | FAILED + +### Issues Fixed +- **CRITICAL:** 1/1 fixed +- **HIGH:** 2/2 fixed +- **Total:** 3 issues resolved + +### Fixes Applied +1. [CRITICAL] service.ts:45 - Parameterized query +2. [HIGH] route.ts:23 - Added auth check +3. [HIGH] service.ts:78 - Added null guard + +### Quality Checks +- **Type Check:** PASS +- **Lint:** PASS +- **Tests:** 47 passing (2 new) + +### Git Commit +- **Hash:** abc123def +- **Message:** fix({{story_key}}): address security and null handling + +### Deferred Issues +- MEDIUM: 3 (defer to follow-up) +- LOW: 1 (skip as gold-plating) + +### Ready For +Orchestrator reconciliation +``` + + + +## Parsing Hints for Orchestrator + +Extract key data using grep: + +```bash +# Get status +grep "^\*\*Status:\*\*" agent_output.txt | cut -d: -f2 | xargs + +# Get files created +sed -n '/### Files Created/,/###/p' agent_output.txt | grep "^-" | cut -d' ' -f2 + +# Get issue count +grep "CRITICAL:" agent_output.txt | grep -oE "[0-9]+" + +# Check if ready for next phase +grep "### Ready For" -A 1 agent_output.txt | tail -1 +``` + diff --git a/src/bmm/patterns/hospital-grade.md b/src/bmm/patterns/hospital-grade.md new file mode 100644 index 00000000..2f1ff435 --- /dev/null +++ b/src/bmm/patterns/hospital-grade.md @@ -0,0 +1,111 @@ +# Hospital-Grade Code Standards + + +This code may be deployed in healthcare, financial, or safety-critical contexts where failures have serious consequences. Every line of code must meet hospital-grade reliability standards. + +**Principle:** Quality >> Speed. Take 5 hours to do it right, not 1 hour to do it poorly. + + + +## Think Like a Hospital Engineer + +Before writing any code, ask: +- What happens if this fails at 3 AM? +- What happens if input is malformed? +- What happens if a dependency is unavailable? +- What happens if this runs with 10x expected load? +- Would I trust this code with patient data? + +If you can't answer confidently, add safeguards. + + + +## Non-Negotiable Practices + +**Error Handling:** +- Every external call wrapped in try/catch +- Meaningful error messages (not just "Error occurred") +- Graceful degradation when possible +- Errors logged with context (user, action, timestamp) + +**Input Validation:** +- Never trust user input +- Validate at system boundaries +- Use schema validation (zod, joi, etc.) +- Sanitize before database operations + +**Type Safety:** +- No `any` types (TypeScript) +- Explicit return types on functions +- Null checks before property access +- Union types for known variants + +**Authentication/Authorization:** +- Every endpoint checks auth +- Every data access checks ownership +- No security through obscurity +- Principle of least privilege + + + +## Forbidden Patterns + +**Never do these:** +```typescript +// BAD: Swallowed errors +try { doThing() } catch (e) { } + +// BAD: any type +function process(data: any) { } + +// BAD: No null check +const name = user.profile.name + +// BAD: String concatenation in queries +const query = `SELECT * FROM users WHERE id = '${id}'` + +// BAD: Hardcoded secrets +const apiKey = "sk_live_abc123" + +// BAD: TODO comments left in production +// TODO: implement validation + +// BAD: Console.log debugging +console.log("got here") +``` + + + +## Quality Gates (All Must Pass) + +Before code is considered complete: + +```bash +# Type check - zero errors +npm run type-check + +# Lint - zero errors, zero warnings +npm run lint + +# Tests - all passing +npm test + +# Build - succeeds +npm run build +``` + +If any gate fails, code is not done. + + + +## Verification Checklist + +- [ ] All error paths handled +- [ ] Input validated at boundaries +- [ ] No `any` types +- [ ] No hardcoded secrets +- [ ] No TODO/FIXME in production code +- [ ] Tests cover happy path AND error paths +- [ ] Auth checks on all protected routes +- [ ] Logging for debugging without exposing PII + diff --git a/src/bmm/patterns/security-checklist.md b/src/bmm/patterns/security-checklist.md new file mode 100644 index 00000000..b7e41310 --- /dev/null +++ b/src/bmm/patterns/security-checklist.md @@ -0,0 +1,122 @@ +# Security Review Checklist + + +Security vulnerabilities are CRITICAL issues. A single vulnerability can expose user data, enable account takeover, or cause financial loss. + +**Principle:** Assume all input is malicious. Validate everything. + + + +## OWASP Top 10 Checks + +### 1. Injection +```bash +# Check for SQL injection +grep -E "SELECT.*\+|INSERT.*\+|UPDATE.*\+|DELETE.*\+" . -r +grep -E '\$\{.*\}.*query|\`.*\$\{' . -r + +# Check for command injection +grep -E "exec\(|spawn\(|system\(" . -r +``` + +**Fix:** Use parameterized queries, never string concatenation. + +### 2. Broken Authentication +```bash +# Check for hardcoded credentials +grep -E "password.*=.*['\"]|api.?key.*=.*['\"]|secret.*=.*['\"]" . -r -i + +# Check for weak session handling +grep -E "localStorage.*token|sessionStorage.*password" . -r +``` + +**Fix:** Use secure session management, never store secrets in code. + +### 3. Sensitive Data Exposure +```bash +# Check for PII logging +grep -E "console\.(log|info|debug).*password|log.*email|log.*ssn" . -r -i + +# Check for unencrypted transmission +grep -E "http://(?!localhost)" . -r +``` + +**Fix:** Never log sensitive data, always use HTTPS. + +### 4. XML External Entities (XXE) +```bash +# Check for unsafe XML parsing +grep -E "parseXML|DOMParser|xml2js" . -r +``` + +**Fix:** Disable external entity processing. + +### 5. Broken Access Control +```bash +# Check for missing auth checks +grep -E "export.*function.*(GET|POST|PUT|DELETE)" . -r | head -20 +# Then verify each has auth check +``` + +**Fix:** Every endpoint must verify user has permission. + +### 6. Security Misconfiguration +```bash +# Check for debug mode in prod +grep -E "debug.*true|NODE_ENV.*development" . -r + +# Check for default credentials +grep -E "admin.*admin|password.*password|123456" . -r +``` + +**Fix:** Secure configuration, no defaults. + +### 7. Cross-Site Scripting (XSS) +```bash +# Check for innerHTML usage +grep -E "innerHTML|dangerouslySetInnerHTML" . -r + +# Check for unescaped output +grep -E "\$\{.*\}.*<|<.*\$\{" . -r +``` + +**Fix:** Always escape user input, use safe rendering. + +### 8. Insecure Deserialization +```bash +# Check for unsafe JSON parsing +grep -E "JSON\.parse\(.*req\." . -r +grep -E "eval\(|Function\(" . -r +``` + +**Fix:** Validate structure before parsing. + +### 9. Using Components with Known Vulnerabilities +```bash +# Check for outdated dependencies +npm audit +``` + +**Fix:** Keep dependencies updated, monitor CVEs. + +### 10. Insufficient Logging +```bash +# Check for security event logging +grep -E "log.*(login|auth|permission|access)" . -r +``` + +**Fix:** Log security events with context. + + + +## Severity Ratings + +| Severity | Impact | Examples | +|----------|--------|----------| +| CRITICAL | Data breach, account takeover | SQL injection, auth bypass | +| HIGH | Service disruption, data corruption | Logic flaws, N+1 queries | +| MEDIUM | Technical debt, maintainability | Missing validation, tight coupling | +| LOW | Code style, nice-to-have | Naming, documentation | + +**CRITICAL and HIGH must be fixed before merge.** + diff --git a/src/bmm/patterns/tdd.md b/src/bmm/patterns/tdd.md new file mode 100644 index 00000000..7cb113a2 --- /dev/null +++ b/src/bmm/patterns/tdd.md @@ -0,0 +1,93 @@ +# Test-Driven Development Pattern + + +TDD is about design quality, not coverage metrics. Writing tests first forces you to think about behavior before implementation. + +**Principle:** If you can describe behavior as `expect(fn(input)).toBe(output)` before writing `fn`, TDD improves the result. + + + +## When TDD Improves Quality + +**Use TDD for:** +- Business logic with defined inputs/outputs +- API endpoints with request/response contracts +- Data transformations, parsing, formatting +- Validation rules and constraints +- Algorithms with testable behavior + +**Skip TDD for:** +- UI layout and styling +- Configuration changes +- Glue code connecting existing components +- One-off scripts +- Simple CRUD with no business logic + + + +## Red-Green-Refactor Cycle + +**RED - Write failing test:** +1. Create test describing expected behavior +2. Run test - it MUST fail +3. If test passes: feature exists or test is wrong + +**GREEN - Implement to pass:** +1. Write minimal code to make test pass +2. No cleverness, no optimization - just make it work +3. Run test - it MUST pass + +**REFACTOR (if needed):** +1. Clean up implementation +2. Run tests - MUST still pass +3. Only commit if changes made + + + +## Good Tests vs Bad Tests + +**Test behavior, not implementation:** +```typescript +// GOOD: Tests observable behavior +expect(formatDate(new Date('2024-01-15'))).toBe('Jan 15, 2024') + +// BAD: Tests implementation details +expect(formatDate).toHaveBeenCalledWith(expect.any(Date)) +``` + +**One concept per test:** +```typescript +// GOOD: Separate tests +it('accepts valid email', () => { ... }) +it('rejects empty email', () => { ... }) +it('rejects malformed email', () => { ... }) + +// BAD: Multiple assertions +it('validates email', () => { + expect(validate('test@example.com')).toBe(true) + expect(validate('')).toBe(false) + expect(validate('invalid')).toBe(false) +}) +``` + +**Descriptive names:** +```typescript +// GOOD +it('returns null for invalid user ID') +it('should reject empty email') + +// BAD +it('test1') +it('handles error') +it('works') +``` + + + +## Coverage Targets + +- **90%+ line coverage** for new code +- **100% branch coverage** for critical paths (auth, payments) +- **Every error path** has at least one test +- **Edge cases** explicitly tested + diff --git a/src/bmm/patterns/verification.md b/src/bmm/patterns/verification.md new file mode 100644 index 00000000..2d359205 --- /dev/null +++ b/src/bmm/patterns/verification.md @@ -0,0 +1,143 @@ +# Verification Patterns + + +Existence ≠ Implementation. A file existing does not mean the feature works. + +**Verification levels:** +1. **Exists** - File is present +2. **Substantive** - Content is real, not placeholder +3. **Wired** - Connected to rest of system +4. **Functional** - Actually works when invoked + + + +## Detecting Stubs and Placeholders + +```bash +# Comment-based stubs +grep -E "(TODO|FIXME|XXX|PLACEHOLDER)" "$file" +grep -E "implement|add later|coming soon" "$file" -i + +# Empty implementations +grep -E "return null|return undefined|return \{\}|return \[\]" "$file" +grep -E "console\.(log|warn).*only" "$file" + +# Placeholder text +grep -E "placeholder|lorem ipsum|sample data" "$file" -i +``` + +**Red flags in code:** +```typescript +// STUBS - Not real implementations: +return
Placeholder
+onClick={() => {}} +export async function POST() { return Response.json({ ok: true }) } +``` +
+ + +## File Verification Commands + +**React Components:** +```bash +# Exists and exports component +[ -f "$file" ] && grep -E "export.*function|export const.*=" "$file" + +# Has real JSX (not null/empty) +grep -E "return.*<" "$file" | grep -v "return.*null" + +# Uses props/state (not static) +grep -E "props\.|useState|useEffect" "$file" +``` + +**API Routes:** +```bash +# Exports HTTP handlers +grep -E "export.*(GET|POST|PUT|DELETE)" "$file" + +# Has database interaction +grep -E "prisma\.|db\.|query|find|create" "$file" + +# Has error handling +grep -E "try|catch|throw" "$file" +``` + +**Tests:** +```bash +# Test file exists +[ -f "$test_file" ] + +# Has test cases +grep -E "it\(|test\(|describe\(" "$test_file" + +# Not all skipped +grep -c "\.skip" "$test_file" +``` + + + +## Quality Check Commands + +```bash +# Type check - zero errors +npm run type-check +echo "Exit code: $?" + +# Lint - zero errors/warnings +npm run lint 2>&1 | tail -5 + +# Tests - all passing +npm test 2>&1 | grep -E "pass|fail|error" -i | tail -10 + +# Build - succeeds +npm run build 2>&1 | tail -5 +``` + +**All must return exit code 0.** + + + +## Wiring Verification + +**Component → API:** +```bash +# Check component calls the API +grep -E "fetch\(['\"].*$api_path|axios.*$api_path" "$component" +``` + +**API → Database:** +```bash +# Check API queries database +grep -E "await.*prisma|await.*db\." "$route" +``` + +**Form → Handler:** +```bash +# Check form has real submit handler +grep -A 5 "onSubmit" "$component" | grep -E "fetch|axios|mutate" +``` + + + +## Verdict Format + +```markdown +## VALIDATION RESULT + +**Status:** PASS | FAIL + +### Evidence +- Type check: PASS (0 errors) +- Lint: PASS (0 warnings) +- Build: PASS +- Tests: 45/45 passing + +### Files Verified +- path/to/file.ts ✓ +- path/to/other.ts ✓ + +### Failures (if FAIL) +1. [CRITICAL] Missing file: src/api/route.ts +2. [HIGH] Type error in lib/auth.ts:45 +``` + diff --git a/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/builder.md b/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/builder.md index 6c100cbc..bcbc8cf5 100644 --- a/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/builder.md +++ b/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/builder.md @@ -4,6 +4,12 @@ **Steps:** 1-4 (init, pre-gap, write-tests, implement) **Trust Level:** LOW (assume will cut corners) + +@patterns/hospital-grade.md +@patterns/tdd.md +@patterns/agent-completion.md + + --- ## Your Mission diff --git a/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/fixer.md b/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/fixer.md index 32343483..968572fd 100644 --- a/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/fixer.md +++ b/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/fixer.md @@ -4,6 +4,11 @@ **Steps:** 8-9 (review-analysis, fix-issues) **Trust Level:** MEDIUM (incentive to minimize work) + +@patterns/hospital-grade.md +@patterns/agent-completion.md + + --- ## Your Mission diff --git a/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/inspector.md b/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/inspector.md index 93d92625..968afb93 100644 --- a/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/inspector.md +++ b/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/inspector.md @@ -4,6 +4,12 @@ **Steps:** 5-6 (post-validation, quality-checks) **Trust Level:** MEDIUM (no conflict of interest) + +@patterns/verification.md +@patterns/hospital-grade.md +@patterns/agent-completion.md + + --- ## Your Mission diff --git a/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/reviewer.md b/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/reviewer.md index 72038cc6..2a711e05 100644 --- a/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/reviewer.md +++ b/src/bmm/workflows/4-implementation/super-dev-pipeline/agents/reviewer.md @@ -4,6 +4,12 @@ **Steps:** 7 (code-review) **Trust Level:** HIGH (wants to find issues) + +@patterns/security-checklist.md +@patterns/hospital-grade.md +@patterns/agent-completion.md + + --- ## Your Mission diff --git a/src/modules/bmm/patterns/agent-completion.md b/src/modules/bmm/patterns/agent-completion.md new file mode 100644 index 00000000..d256c155 --- /dev/null +++ b/src/modules/bmm/patterns/agent-completion.md @@ -0,0 +1,187 @@ +# Agent Completion Format + + +All agents must return structured output that the orchestrator can parse. This enables automated verification and reliable workflow progression. + +**Principle:** Return parseable data, not prose. The orchestrator needs to extract file lists, status, and evidence. + + + +## Standard Completion Format + +Every agent returns this structure when done: + +```markdown +## AGENT COMPLETE + +**Agent:** [builder|inspector|reviewer|fixer] +**Story:** {{story_key}} +**Status:** [SUCCESS|PASS|FAIL|ISSUES_FOUND|PARTIAL] + +### [Agent-Specific Section] +[See below for each agent type] + +### Files Created +- path/to/new/file.ts +- path/to/another.ts + +### Files Modified +- path/to/existing/file.ts + +### Ready For +[Next phase or action required] +``` + + + +## Builder Agent Output + +```markdown +## AGENT COMPLETE + +**Agent:** builder +**Story:** {{story_key}} +**Status:** SUCCESS | FAILED + +### Files Created +- src/lib/feature/service.ts +- src/lib/feature/__tests__/service.test.ts + +### Files Modified +- src/app/api/feature/route.ts + +### Tests Added +- 3 test files +- 12 test cases total + +### Implementation Summary +Brief description of what was built. + +### Known Gaps +- Edge case X not handled +- NONE if all complete + +### Ready For +Inspector validation +``` + + + +## Inspector Agent Output + +```markdown +## AGENT COMPLETE + +**Agent:** inspector +**Story:** {{story_key}} +**Status:** PASS | FAIL + +### Evidence +- **Type Check:** PASS (0 errors) +- **Lint:** PASS (0 warnings) +- **Build:** PASS +- **Tests:** 45 passing, 0 failing, 92% coverage + +### Files Verified +- src/lib/feature/service.ts ✓ +- src/app/api/feature/route.ts ✓ + +### Failures (if FAIL status) +1. Type error in service.ts:45 +2. Test failing: "should handle empty input" + +### Ready For +Reviewer (if PASS) | Builder fix (if FAIL) +``` + + + +## Reviewer Agent Output + +```markdown +## AGENT COMPLETE + +**Agent:** reviewer +**Story:** {{story_key}} +**Status:** ISSUES_FOUND | CLEAN + +### Issue Summary +- **CRITICAL:** 1 (security, data loss) +- **HIGH:** 2 (production bugs) +- **MEDIUM:** 3 (tech debt) +- **LOW:** 1 (nice-to-have) + +### Must Fix (CRITICAL + HIGH) +1. [CRITICAL] service.ts:45 - SQL injection vulnerability +2. [HIGH] route.ts:23 - Missing authorization check +3. [HIGH] service.ts:78 - Unhandled null case + +### Should Fix (MEDIUM) +1. service.ts:92 - No error logging + +### Files Reviewed +- src/lib/feature/service.ts ✓ +- src/app/api/feature/route.ts ✓ + +### Ready For +Fixer agent to address CRITICAL and HIGH issues +``` + + + +## Fixer Agent Output + +```markdown +## AGENT COMPLETE + +**Agent:** fixer +**Story:** {{story_key}} +**Status:** SUCCESS | PARTIAL | FAILED + +### Issues Fixed +- **CRITICAL:** 1/1 fixed +- **HIGH:** 2/2 fixed +- **Total:** 3 issues resolved + +### Fixes Applied +1. [CRITICAL] service.ts:45 - Parameterized query +2. [HIGH] route.ts:23 - Added auth check +3. [HIGH] service.ts:78 - Added null guard + +### Quality Checks +- **Type Check:** PASS +- **Lint:** PASS +- **Tests:** 47 passing (2 new) + +### Git Commit +- **Hash:** abc123def +- **Message:** fix({{story_key}}): address security and null handling + +### Deferred Issues +- MEDIUM: 3 (defer to follow-up) +- LOW: 1 (skip as gold-plating) + +### Ready For +Orchestrator reconciliation +``` + + + +## Parsing Hints for Orchestrator + +Extract key data using grep: + +```bash +# Get status +grep "^\*\*Status:\*\*" agent_output.txt | cut -d: -f2 | xargs + +# Get files created +sed -n '/### Files Created/,/###/p' agent_output.txt | grep "^-" | cut -d' ' -f2 + +# Get issue count +grep "CRITICAL:" agent_output.txt | grep -oE "[0-9]+" + +# Check if ready for next phase +grep "### Ready For" -A 1 agent_output.txt | tail -1 +``` + diff --git a/src/modules/bmm/patterns/hospital-grade.md b/src/modules/bmm/patterns/hospital-grade.md new file mode 100644 index 00000000..2f1ff435 --- /dev/null +++ b/src/modules/bmm/patterns/hospital-grade.md @@ -0,0 +1,111 @@ +# Hospital-Grade Code Standards + + +This code may be deployed in healthcare, financial, or safety-critical contexts where failures have serious consequences. Every line of code must meet hospital-grade reliability standards. + +**Principle:** Quality >> Speed. Take 5 hours to do it right, not 1 hour to do it poorly. + + + +## Think Like a Hospital Engineer + +Before writing any code, ask: +- What happens if this fails at 3 AM? +- What happens if input is malformed? +- What happens if a dependency is unavailable? +- What happens if this runs with 10x expected load? +- Would I trust this code with patient data? + +If you can't answer confidently, add safeguards. + + + +## Non-Negotiable Practices + +**Error Handling:** +- Every external call wrapped in try/catch +- Meaningful error messages (not just "Error occurred") +- Graceful degradation when possible +- Errors logged with context (user, action, timestamp) + +**Input Validation:** +- Never trust user input +- Validate at system boundaries +- Use schema validation (zod, joi, etc.) +- Sanitize before database operations + +**Type Safety:** +- No `any` types (TypeScript) +- Explicit return types on functions +- Null checks before property access +- Union types for known variants + +**Authentication/Authorization:** +- Every endpoint checks auth +- Every data access checks ownership +- No security through obscurity +- Principle of least privilege + + + +## Forbidden Patterns + +**Never do these:** +```typescript +// BAD: Swallowed errors +try { doThing() } catch (e) { } + +// BAD: any type +function process(data: any) { } + +// BAD: No null check +const name = user.profile.name + +// BAD: String concatenation in queries +const query = `SELECT * FROM users WHERE id = '${id}'` + +// BAD: Hardcoded secrets +const apiKey = "sk_live_abc123" + +// BAD: TODO comments left in production +// TODO: implement validation + +// BAD: Console.log debugging +console.log("got here") +``` + + + +## Quality Gates (All Must Pass) + +Before code is considered complete: + +```bash +# Type check - zero errors +npm run type-check + +# Lint - zero errors, zero warnings +npm run lint + +# Tests - all passing +npm test + +# Build - succeeds +npm run build +``` + +If any gate fails, code is not done. + + + +## Verification Checklist + +- [ ] All error paths handled +- [ ] Input validated at boundaries +- [ ] No `any` types +- [ ] No hardcoded secrets +- [ ] No TODO/FIXME in production code +- [ ] Tests cover happy path AND error paths +- [ ] Auth checks on all protected routes +- [ ] Logging for debugging without exposing PII + diff --git a/src/modules/bmm/patterns/security-checklist.md b/src/modules/bmm/patterns/security-checklist.md new file mode 100644 index 00000000..b7e41310 --- /dev/null +++ b/src/modules/bmm/patterns/security-checklist.md @@ -0,0 +1,122 @@ +# Security Review Checklist + + +Security vulnerabilities are CRITICAL issues. A single vulnerability can expose user data, enable account takeover, or cause financial loss. + +**Principle:** Assume all input is malicious. Validate everything. + + + +## OWASP Top 10 Checks + +### 1. Injection +```bash +# Check for SQL injection +grep -E "SELECT.*\+|INSERT.*\+|UPDATE.*\+|DELETE.*\+" . -r +grep -E '\$\{.*\}.*query|\`.*\$\{' . -r + +# Check for command injection +grep -E "exec\(|spawn\(|system\(" . -r +``` + +**Fix:** Use parameterized queries, never string concatenation. + +### 2. Broken Authentication +```bash +# Check for hardcoded credentials +grep -E "password.*=.*['\"]|api.?key.*=.*['\"]|secret.*=.*['\"]" . -r -i + +# Check for weak session handling +grep -E "localStorage.*token|sessionStorage.*password" . -r +``` + +**Fix:** Use secure session management, never store secrets in code. + +### 3. Sensitive Data Exposure +```bash +# Check for PII logging +grep -E "console\.(log|info|debug).*password|log.*email|log.*ssn" . -r -i + +# Check for unencrypted transmission +grep -E "http://(?!localhost)" . -r +``` + +**Fix:** Never log sensitive data, always use HTTPS. + +### 4. XML External Entities (XXE) +```bash +# Check for unsafe XML parsing +grep -E "parseXML|DOMParser|xml2js" . -r +``` + +**Fix:** Disable external entity processing. + +### 5. Broken Access Control +```bash +# Check for missing auth checks +grep -E "export.*function.*(GET|POST|PUT|DELETE)" . -r | head -20 +# Then verify each has auth check +``` + +**Fix:** Every endpoint must verify user has permission. + +### 6. Security Misconfiguration +```bash +# Check for debug mode in prod +grep -E "debug.*true|NODE_ENV.*development" . -r + +# Check for default credentials +grep -E "admin.*admin|password.*password|123456" . -r +``` + +**Fix:** Secure configuration, no defaults. + +### 7. Cross-Site Scripting (XSS) +```bash +# Check for innerHTML usage +grep -E "innerHTML|dangerouslySetInnerHTML" . -r + +# Check for unescaped output +grep -E "\$\{.*\}.*<|<.*\$\{" . -r +``` + +**Fix:** Always escape user input, use safe rendering. + +### 8. Insecure Deserialization +```bash +# Check for unsafe JSON parsing +grep -E "JSON\.parse\(.*req\." . -r +grep -E "eval\(|Function\(" . -r +``` + +**Fix:** Validate structure before parsing. + +### 9. Using Components with Known Vulnerabilities +```bash +# Check for outdated dependencies +npm audit +``` + +**Fix:** Keep dependencies updated, monitor CVEs. + +### 10. Insufficient Logging +```bash +# Check for security event logging +grep -E "log.*(login|auth|permission|access)" . -r +``` + +**Fix:** Log security events with context. + + + +## Severity Ratings + +| Severity | Impact | Examples | +|----------|--------|----------| +| CRITICAL | Data breach, account takeover | SQL injection, auth bypass | +| HIGH | Service disruption, data corruption | Logic flaws, N+1 queries | +| MEDIUM | Technical debt, maintainability | Missing validation, tight coupling | +| LOW | Code style, nice-to-have | Naming, documentation | + +**CRITICAL and HIGH must be fixed before merge.** + diff --git a/src/modules/bmm/patterns/tdd.md b/src/modules/bmm/patterns/tdd.md new file mode 100644 index 00000000..7cb113a2 --- /dev/null +++ b/src/modules/bmm/patterns/tdd.md @@ -0,0 +1,93 @@ +# Test-Driven Development Pattern + + +TDD is about design quality, not coverage metrics. Writing tests first forces you to think about behavior before implementation. + +**Principle:** If you can describe behavior as `expect(fn(input)).toBe(output)` before writing `fn`, TDD improves the result. + + + +## When TDD Improves Quality + +**Use TDD for:** +- Business logic with defined inputs/outputs +- API endpoints with request/response contracts +- Data transformations, parsing, formatting +- Validation rules and constraints +- Algorithms with testable behavior + +**Skip TDD for:** +- UI layout and styling +- Configuration changes +- Glue code connecting existing components +- One-off scripts +- Simple CRUD with no business logic + + + +## Red-Green-Refactor Cycle + +**RED - Write failing test:** +1. Create test describing expected behavior +2. Run test - it MUST fail +3. If test passes: feature exists or test is wrong + +**GREEN - Implement to pass:** +1. Write minimal code to make test pass +2. No cleverness, no optimization - just make it work +3. Run test - it MUST pass + +**REFACTOR (if needed):** +1. Clean up implementation +2. Run tests - MUST still pass +3. Only commit if changes made + + + +## Good Tests vs Bad Tests + +**Test behavior, not implementation:** +```typescript +// GOOD: Tests observable behavior +expect(formatDate(new Date('2024-01-15'))).toBe('Jan 15, 2024') + +// BAD: Tests implementation details +expect(formatDate).toHaveBeenCalledWith(expect.any(Date)) +``` + +**One concept per test:** +```typescript +// GOOD: Separate tests +it('accepts valid email', () => { ... }) +it('rejects empty email', () => { ... }) +it('rejects malformed email', () => { ... }) + +// BAD: Multiple assertions +it('validates email', () => { + expect(validate('test@example.com')).toBe(true) + expect(validate('')).toBe(false) + expect(validate('invalid')).toBe(false) +}) +``` + +**Descriptive names:** +```typescript +// GOOD +it('returns null for invalid user ID') +it('should reject empty email') + +// BAD +it('test1') +it('handles error') +it('works') +``` + + + +## Coverage Targets + +- **90%+ line coverage** for new code +- **100% branch coverage** for critical paths (auth, payments) +- **Every error path** has at least one test +- **Edge cases** explicitly tested + diff --git a/src/modules/bmm/patterns/verification.md b/src/modules/bmm/patterns/verification.md new file mode 100644 index 00000000..2d359205 --- /dev/null +++ b/src/modules/bmm/patterns/verification.md @@ -0,0 +1,143 @@ +# Verification Patterns + + +Existence ≠ Implementation. A file existing does not mean the feature works. + +**Verification levels:** +1. **Exists** - File is present +2. **Substantive** - Content is real, not placeholder +3. **Wired** - Connected to rest of system +4. **Functional** - Actually works when invoked + + + +## Detecting Stubs and Placeholders + +```bash +# Comment-based stubs +grep -E "(TODO|FIXME|XXX|PLACEHOLDER)" "$file" +grep -E "implement|add later|coming soon" "$file" -i + +# Empty implementations +grep -E "return null|return undefined|return \{\}|return \[\]" "$file" +grep -E "console\.(log|warn).*only" "$file" + +# Placeholder text +grep -E "placeholder|lorem ipsum|sample data" "$file" -i +``` + +**Red flags in code:** +```typescript +// STUBS - Not real implementations: +return
Placeholder
+onClick={() => {}} +export async function POST() { return Response.json({ ok: true }) } +``` +
+ + +## File Verification Commands + +**React Components:** +```bash +# Exists and exports component +[ -f "$file" ] && grep -E "export.*function|export const.*=" "$file" + +# Has real JSX (not null/empty) +grep -E "return.*<" "$file" | grep -v "return.*null" + +# Uses props/state (not static) +grep -E "props\.|useState|useEffect" "$file" +``` + +**API Routes:** +```bash +# Exports HTTP handlers +grep -E "export.*(GET|POST|PUT|DELETE)" "$file" + +# Has database interaction +grep -E "prisma\.|db\.|query|find|create" "$file" + +# Has error handling +grep -E "try|catch|throw" "$file" +``` + +**Tests:** +```bash +# Test file exists +[ -f "$test_file" ] + +# Has test cases +grep -E "it\(|test\(|describe\(" "$test_file" + +# Not all skipped +grep -c "\.skip" "$test_file" +``` + + + +## Quality Check Commands + +```bash +# Type check - zero errors +npm run type-check +echo "Exit code: $?" + +# Lint - zero errors/warnings +npm run lint 2>&1 | tail -5 + +# Tests - all passing +npm test 2>&1 | grep -E "pass|fail|error" -i | tail -10 + +# Build - succeeds +npm run build 2>&1 | tail -5 +``` + +**All must return exit code 0.** + + + +## Wiring Verification + +**Component → API:** +```bash +# Check component calls the API +grep -E "fetch\(['\"].*$api_path|axios.*$api_path" "$component" +``` + +**API → Database:** +```bash +# Check API queries database +grep -E "await.*prisma|await.*db\." "$route" +``` + +**Form → Handler:** +```bash +# Check form has real submit handler +grep -A 5 "onSubmit" "$component" | grep -E "fetch|axios|mutate" +``` + + + +## Verdict Format + +```markdown +## VALIDATION RESULT + +**Status:** PASS | FAIL + +### Evidence +- Type check: PASS (0 errors) +- Lint: PASS (0 warnings) +- Build: PASS +- Tests: 45/45 passing + +### Files Verified +- path/to/file.ts ✓ +- path/to/other.ts ✓ + +### Failures (if FAIL) +1. [CRITICAL] Missing file: src/api/route.ts +2. [HIGH] Type error in lib/auth.ts:45 +``` + diff --git a/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/builder.md b/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/builder.md index 6c100cbc..bcbc8cf5 100644 --- a/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/builder.md +++ b/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/builder.md @@ -4,6 +4,12 @@ **Steps:** 1-4 (init, pre-gap, write-tests, implement) **Trust Level:** LOW (assume will cut corners) + +@patterns/hospital-grade.md +@patterns/tdd.md +@patterns/agent-completion.md + + --- ## Your Mission diff --git a/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/fixer.md b/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/fixer.md index 32343483..968572fd 100644 --- a/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/fixer.md +++ b/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/fixer.md @@ -4,6 +4,11 @@ **Steps:** 8-9 (review-analysis, fix-issues) **Trust Level:** MEDIUM (incentive to minimize work) + +@patterns/hospital-grade.md +@patterns/agent-completion.md + + --- ## Your Mission diff --git a/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/inspector.md b/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/inspector.md index 93d92625..968afb93 100644 --- a/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/inspector.md +++ b/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/inspector.md @@ -4,6 +4,12 @@ **Steps:** 5-6 (post-validation, quality-checks) **Trust Level:** MEDIUM (no conflict of interest) + +@patterns/verification.md +@patterns/hospital-grade.md +@patterns/agent-completion.md + + --- ## Your Mission diff --git a/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/reviewer.md b/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/reviewer.md index 72038cc6..2a711e05 100644 --- a/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/reviewer.md +++ b/src/modules/bmm/workflows/4-implementation/super-dev-pipeline/agents/reviewer.md @@ -4,6 +4,12 @@ **Steps:** 7 (code-review) **Trust Level:** HIGH (wants to find issues) + +@patterns/security-checklist.md +@patterns/hospital-grade.md +@patterns/agent-completion.md + + --- ## Your Mission