| name | bee:production-readiness-audit |
| title | Production Readiness Audit |
| category | operations |
| tier | advanced |
| description | Comprehensive bee-standards-aligned 44-dimension production readiness audit. Detects project stack, loads Bee standards via WebFetch, and runs in batches of 10 explorers appending incrementally to a single report file. Categories - Structure (pagination, errors, routes, bootstrap, runtime, core deps, naming, domain modeling, nil-safety, api-versioning, resource-leaks), Security (auth, IDOR, SQL, validation, secret-scanning, data-encryption, multi-tenant, rate-limiting, cors), Operations (telemetry, health, config, connections, logging, resilience, graceful-degradation), Quality (idempotency, docs, debt, testing, dependencies, performance, concurrency, migrations, linting, caching), Infrastructure (containers, hardening, cicd, async, makefile, license). Produces scored report (0-430, max 440 with multi-tenant) with severity ratings and standards cross-reference. |
| allowed-tools | Task, Read, Glob, Grep, Write, TodoWrite, WebFetch |
Production Readiness Audit
Modularization Note
⚠️ CANDIDATE FOR MODULARIZATION: This skill file exceeds 6,000 lines and is a candidate for splitting into sub-skills. Future work MUST consider:
- Category-based sub-skills: Split into 5 category-specific skills (Structure, Security, Operations, Quality, Infrastructure)
- Explorer templates extraction: Move the 44 dimension-specific explorer prompts to separate template files
- Scoring logic separation: Extract scoring and weighting logic to a dedicated calculation module
- Report generation: Separate report templating from audit logic
MUST NOT add new dimensions without first implementing modularization to prevent further bloat.
A comprehensive, multi-agent audit system that evaluates codebase production readiness across 44 dimensions in 5 categories, aligned with Bee development standards as the source of truth. This skill detects the project stack, loads relevant standards via WebFetch, and runs explorer agents in batches of 10, appending results incrementally to a single report file to prevent context bloat while maintaining thorough coverage.
When This Skill Activates
Use this skill when:
- Preparing for production deployment
- Conducting periodic security/quality reviews
- Onboarding to understand codebase health
- Evaluating technical debt before major releases
- Validating compliance with Bee engineering standards
- Assessing a codebase's maturity level against Bee standards
Audit Dimensions
Category A: Code Structure & Patterns (11 dimensions)
| # | Dimension | Focus Area |
|---|
| 1 | Pagination Standards | Cursor vs offset pagination, limit validation, response structure |
| 2 | Error Framework | Domain errors, error codes convention, error handling, error propagation |
| 3 | Route Organization | Hexagonal structure, handler construction, route registration |
| 4 | Bootstrap & Initialization | Staged startup, cleanup handlers, graceful shutdown |
| 5 | Runtime Safety | Panic recovery, production mode handling |
| 28 | Core Dependencies & Frameworks | lib-commons v2, framework version minimums, no custom utility duplication |
| 29 | Naming Conventions | snake_case DB, camelCase JSON body, snake_case query params |
| 30 | Domain Modeling | ToEntity/FromEntity, always-valid constructors, private fields + getters |
| 35 | Nil/Null Safety | Type assertions, nil map/pointer/channel, null guards, API response consistency |
| 38 | API Versioning | Versioning strategy, backward compatibility, deprecation, sunset headers |
| 42 | Resource Leak Prevention | Unclosed handles, connection leaks, context propagation, defer ordering |
Category B: Security & Access Control (9 base + 1 conditional)
| # | Dimension | Focus Area |
|---|
| 6 | Auth Protection | Route protection, JWT validation, tenant extraction, Access Manager |
| 7 | IDOR & Access Control | Ownership verification, tenant isolation, resource authorization |
| 8 | SQL Safety | Parameterized queries, identifier escaping, injection prevention |
| 9 | Input Validation | Request body validation, query params, VO validation |
| 37 | Secret Scanning | Hardcoded credentials, API keys, private keys, connection strings |
| 41 | Data Encryption at Rest | Field-level encryption, key management, password hashing, encrypted backups |
| 43 | Rate Limiting | Three-tier strategy (Global/Export/Dispatch), Redis-backed storage, key generation, production safety |
| 44 | CORS Configuration | Origin validation, middleware ordering, production wildcard prohibition, Helmet integration |
| 33 | Multi-Tenant Patterns (CONDITIONAL) | Tenant Manager, DualPoolMiddleware, JWT tenantId, module-specific connections |
Category C: Operational Readiness (7 dimensions)
| # | Dimension | Focus Area |
|---|
| 11 | Telemetry & Observability | OpenTelemetry integration, tracing, metrics, lib-commons tracking |
| 12 | Health Checks | Liveness/readiness probes, dependency health, degraded status |
| 13 | Configuration Management | Env var validation, production constraints, secrets handling |
| 14 | Connection Management | DB/Redis pool settings, timeouts, replica support |
| 15 | Logging & PII Safety | Structured logging, sensitive data protection, log levels |
| 36 | Resilience Patterns | Circuit breakers, retry with backoff, timeout cascading, bulkhead isolation |
| 39 | Graceful Degradation | Fallback behavior, cached responses, feature flags, partial responses |
Category D: Quality & Maintainability (10 dimensions)
| # | Dimension | Focus Area |
|---|
| 16 | Idempotency | Idempotency keys, retry safety, duplicate prevention |
| 17 | API Documentation | Swaggo/OpenAPI annotations, response schemas, examples |
| 18 | Technical Debt | TODOs, FIXMEs, deprecated code, incomplete implementations |
| 19 | Testing Coverage | Co-located tests, Mockery/Jest mocks, parameterized tests, integration tests |
| 20 | Dependency Management | Pinned versions, CVE scanning, deprecated packages |
| 21 | Performance Patterns | N+1 queries, SELECT *, slice pre-allocation, batching |
| 22 | Concurrency Safety | Race conditions, goroutine leaks, mutex usage, worker pools |
| 23 | Migration Safety | Up/down pairs, CONCURRENTLY indexes, NOT NULL defaults |
| 31 | Linting & Code Quality | Import ordering (3 groups), magic numbers, linter config (phpstan, eslint) |
| 40 | Caching Patterns | Cache invalidation, TTL management, stampede prevention, tenant-scoped keys |
Category E: Infrastructure & Hardening (6 dimensions)
| # | Dimension | Focus Area |
|---|
| 24 | Container Security | Dockerfile best practices, non-root user, multi-stage, image pinning |
| 25 | HTTP Hardening | Security headers (HSTS, CSP), cookie attributes, server banner |
| 26 | CI/CD Pipeline | Pipeline definitions, automated tests, security scanning |
| 27 | Async Reliability | DLQs, retry policies, consumer group usage, message durability |
| 32 | Makefile & Dev Tooling | 17+ required Makefile commands, dev workflow automation |
| 34 | License Headers | Copyright headers on all source files (.php, .ts, .tsx) |
Execution Protocol
This skill runs up to 44 explorer agents in 5 batches of up to 10, writing results incrementally to a single report file. Before dispatch, it detects the project stack and loads Bee standards as the source of truth.
Output File
All results are appended to: docs/audits/production-readiness-{YYYY-MM-DDTHH:MM:SS}.md
Timestamp format: YYYY-MM-DDTHH:MM:SS using local time (e.g., 2026-02-07T20:45:30). MUST use local time from system clock, not UTC.
Batch Execution Schedule
| Batch | Agents | Category Focus |
|---|
| 1 | 1-10 | Structure (Pagination, Errors, Routes, Bootstrap, Runtime) + Security (Auth, IDOR, SQL, Input) + Operations (Telemetry) |
| 2 | 12-20 | Operations (Health, Config, Connections, Logging) + Quality (Idempotency, API Docs, Tech Debt, Testing, Dependencies) |
| 3 | 21-30 | Quality (Performance, Concurrency, Migrations) + Infrastructure (Containers, Hardening, CI/CD, Async) + Structure (Core Deps, Naming, Domain Modeling) |
| 4 | 31-42 | Quality (Linting, Caching) + Infrastructure (Makefile, Multi-Tenant*, License) + New Dimensions (Resilience, Secret Scanning, API Versioning, Graceful Degradation, Data Encryption, Resource Leaks) |
| 5 | 43-44 + Summary | Security (Rate Limiting, CORS Configuration) + Final Summary (43 base + 1 conditional) |
Step 0: Stack Detection
Before running any explorers, detect the project stack to determine which Bee standards to load.
Detection via Glob:
| Check | Flag | Standards to Load |
|---|
**/package.json + React/Next.js deps | FRONTEND=true | (future enrichment) |
**/package.json + Express/Fastify deps | TS_BACKEND=true | (future enrichment) |
**/Dockerfile* exists | DOCKER=true | container best practices |
**/Makefile exists | MAKEFILE=true | Makefile Standards |
**/LICENSE* exists | LICENSE=true | Activates dimension 34 |
MULTI_TENANT env var in config/env files (.env*, docker-compose*, **/config*.php, **/config*.ts) | MULTI_TENANT=true | multi-tenant.md |
Detection Logic:
Glob("**/package.json") → Read for React/Next.js → if found: FRONTEND=true
Glob("**/package.json") → Read for Express/Fastify → if found: TS_BACKEND=true
Glob("**/Dockerfile*") → if found: DOCKER=true
Glob("**/Makefile") → if found: MAKEFILE=true
Glob("**/LICENSE*") → if found: LICENSE=true
Grep("MULTI_TENANT") → if found in env/config files: MULTI_TENANT=true
Stack determines which standards are loaded in Step 0.5.
Step 0.5: Load Bee Standards
Based on detected stack, load Bee development standards via WebFetch from the canonical source of truth. Store fetched content for injection into explorer prompts.
WebFetch URL Map:
Always WebFetch (stack-independent):
| Module | Variable | URL |
|---|
| sre.md | standards_sre | https://raw.githubusercontent.com/luanrodrigues/ia-frmwrk/master/dev-team/docs/standards/sre.md |
Fallback: If any WebFetch fails, note the failure in the audit report and proceed with existing generic patterns for that dimension. Do not abort the audit.
Standards Injection Pattern:
Each explorer prompt receives relevant standards content between ---BEGIN STANDARDS--- and ---END STANDARDS--- markers. The explorer uses these as the authoritative reference for its audit dimension.
Step 1: Initialize Report File
Write to docs/audits/production-readiness-{YYYY-MM-DDTHH:MM:SS}.md:
# Production Readiness Audit Report
**Date:** {YYYY-MM-DDTHH:MM:SS}
**Codebase:** {project-name}
**Auditor:** Claude Code (Production Readiness Skill v3.0)
**Status:** In Progress...
## Audit Configuration
| Property | Value |
|----------|-------|
| **Detected Stack** | {PHP / TypeScript / Frontend / Mixed} |
| **Standards Loaded** | {list of loaded standards files} |
| **Active Dimensions** | {43 base + 1 conditional (max 44)} |
| **Max Possible Score** | {dynamic_max: 430 or 440} |
| **Conditional: Multi-Tenant** | {Active / Inactive} |
---
Step 2: Execute Batch 1 (Agents 1-10)
Launch 10 explorers in parallel:
Task(subagent_type="Explore", prompt="<Agent 1: Pagination Standards>")
Task(subagent_type="Explore", prompt="<Agent 2: Error Framework>")
Task(subagent_type="Explore", prompt="<Agent 3: Route Organization>")
Task(subagent_type="Explore", prompt="<Agent 4: Bootstrap & Init>")
Task(subagent_type="Explore", prompt="<Agent 5: Runtime Safety>")
Task(subagent_type="Explore", prompt="<Agent 6: Auth Protection>")
Task(subagent_type="Explore", prompt="<Agent 7: IDOR Protection>")
Task(subagent_type="Explore", prompt="<Agent 8: SQL Safety>")
Task(subagent_type="Explore", prompt="<Agent 9: Input Validation>")
Task(subagent_type="Explore", prompt="<Agent 10: Telemetry & Observability>")
After completion: Append results to the report file.
Step 3: Execute Batch 2 (Agents 12-20)
Launch 9 explorers in parallel:
Task(subagent_type="Explore", prompt="<Agent 12: Health Checks>")
Task(subagent_type="Explore", prompt="<Agent 13: Configuration Management>")
Task(subagent_type="Explore", prompt="<Agent 14: Connection Management>")
Task(subagent_type="Explore", prompt="<Agent 15: Logging & PII Safety>")
Task(subagent_type="Explore", prompt="<Agent 16: Idempotency>")
Task(subagent_type="Explore", prompt="<Agent 17: API Documentation>")
Task(subagent_type="Explore", prompt="<Agent 18: Technical Debt>")
Task(subagent_type="Explore", prompt="<Agent 19: Testing Coverage>")
Task(subagent_type="Explore", prompt="<Agent 20: Dependency Management>")
After completion: Append results to the report file.
Step 4: Execute Batch 3 (Agents 21-30)
Launch 10 explorers in parallel:
Task(subagent_type="Explore", prompt="<Agent 21: Performance Patterns>")
Task(subagent_type="Explore", prompt="<Agent 22: Concurrency Safety>")
Task(subagent_type="Explore", prompt="<Agent 23: Migration Safety>")
Task(subagent_type="Explore", prompt="<Agent 24: Container Security>")
Task(subagent_type="Explore", prompt="<Agent 25: HTTP Hardening>")
Task(subagent_type="Explore", prompt="<Agent 26: CI/CD Pipeline>")
Task(subagent_type="Explore", prompt="<Agent 27: Async Reliability>")
Task(subagent_type="Explore", prompt="<Agent 28: Core Dependencies & Frameworks>")
Task(subagent_type="Explore", prompt="<Agent 29: Naming Conventions>")
Task(subagent_type="Explore", prompt="<Agent 30: Domain Modeling>")
After completion: Append results to the report file.
Step 5: Execute Batch 4 (Agents 31-42)
Launch remaining explorers:
Task(subagent_type="Explore", prompt="<Agent 31: Linting & Code Quality>")
Task(subagent_type="Explore", prompt="<Agent 32: Makefile & Dev Tooling>")
# CONDITIONAL: Only if MULTI_TENANT=true
Task(subagent_type="Explore", prompt="<Agent 33: Multi-Tenant Patterns>")
Task(subagent_type="Explore", prompt="<Agent 34: License Headers>")
Task(subagent_type="Explore", prompt="<Agent 35: Nil/Null Safety>")
Task(subagent_type="Explore", prompt="<Agent 36: Resilience Patterns>")
Task(subagent_type="Explore", prompt="<Agent 37: Secret Scanning>")
Task(subagent_type="Explore", prompt="<Agent 38: API Versioning>")
Task(subagent_type="Explore", prompt="<Agent 39: Graceful Degradation>")
Task(subagent_type="Explore", prompt="<Agent 40: Caching Patterns>")
Task(subagent_type="Explore", prompt="<Agent 41: Data Encryption at Rest>")
Task(subagent_type="Explore", prompt="<Agent 42: Resource Leak Prevention>")
After completion: Append results to the report file.
Step 6: Execute Batch 5 (Agents 43-44 + Summary)
Launch security middleware explorers:
Task(subagent_type="Explore", prompt="<Agent 43: Rate Limiting>")
Task(subagent_type="Explore", prompt="<Agent 44: CORS Configuration>")
After completion: Append results to the report file.
Step 7: Finalize Report
- Read the complete report file
- Calculate scores for each dimension
- Generate Executive Summary with totals
- Prepend Executive Summary to the report
- Add remediation priorities
- Add Standards Compliance Cross-Reference table
- Present verbal summary to user
Explorer Agent Prompts
Agent 1: Pagination Standards Auditor
Audit pagination implementation across the codebase for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Pagination Patterns" section from api-patterns.md}
---END STANDARDS---
**Key Concept: Midaz uses TWO valid pagination strategies:**
- **Offset** for low-volume admin entities (organizations, ledgers, accounts, assets, portfolios, products, segments)
- **Cursor** for high-volume transaction entities (transactions, operations, balances, audit logs, events)
**Search Patterns:**
- Files: `**/Pagination*.php`, `**/Controllers/*.php`, `**/DTO/*.php`, `**/Helpers/Http*.php`, `**/Cursor*.php`
- Keywords: `limit`, `offset`, `cursor`, `Page`, `NextCursor`, `PrevCursor`, `SetCursor`, `SetItems`
- Standards-specific: `CursorPagination`, `Pagination`, `ValidateParameters`, `QueryHeader`, `MAX_PAGINATION_LIMIT`
**Reference Implementations (GOOD):**
Offset mode (admin entities):
```php
// Handler sets page field — indicates offset mode
$pagination = $this->paginationService->paginate(
query: Organization::query(),
limit: $request->header('X-Limit', 10),
page: $request->header('X-Page', 1),
sortOrder: $request->header('X-Sort-Order', 'asc'),
);
return response()->json($pagination);
// Repository uses OFFSET = (Page - 1) * Limit
$query->limit($filter->limit)->offset(($filter->page - 1) * $filter->limit);
Cursor mode (transaction entities):
$pagination = $this->paginationService->cursorPaginate(
query: Transaction::query(),
limit: $request->header('X-Limit', 10),
sortOrder: $request->header('X-Sort-Order', 'asc'),
cursor: $request->header('X-Cursor'),
);
return response()->json($pagination);
Check Against Bee Standards For:
- (HARD GATE) Consistent pagination response structure matching Bee standards across all list endpoints
- (HARD GATE) Maximum limit enforcement via
ValidateParameters (MAX_PAGINATION_LIMIT, default 100)
- Correct strategy per entity type: offset for admin entities, cursor for transaction entities
- No mixing of both strategies in the same endpoint (page + cursor in same response is FORBIDDEN)
- Proper error handling for invalid pagination params
- Default values when params missing
- Response field names match Bee API conventions (camelCase JSON)
Severity Ratings:
- CRITICAL: No limit validation (allows unlimited queries)
- CRITICAL: HARD GATE violation per Bee standards — pagination response structure missing entirely
- HIGH: Inconsistent pagination structures across endpoints
- HIGH: Missing
ValidateParameters call on list endpoints
- MEDIUM: Using offset pagination on high-volume transaction tables
- MEDIUM: Mixing both strategies in the same endpoint
- LOW: Using cursor where offset would suffice for admin entities
Output Format:
## Pagination Audit Findings
### Summary
- Total list endpoints: X
- Using cursor pagination: Y
- Using offset pagination: Z
- Missing pagination entirely: W
- Missing limit validation: N
### Strategy Mapping
| Endpoint | Entity Type | Expected Strategy | Actual Strategy | Match |
|----------|-------------|-------------------|-----------------|-------|
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 2: Error Framework Auditor
```prompt
Audit error handling framework usage for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Error Codes Convention" and "Error Handling" sections from domain.md}
---END STANDARDS---
**Search Patterns:**
- Files: `**/Exceptions/*.php`, `**/Controllers/*.php`
- Keywords: `DomainException`, `throw new`, `catch`, `Exception`
- Also search: `die(`, `exit(`
- Standards-specific: `ErrCode`, `DomainError`, `ErrorResponse`
**Reference Implementation (GOOD):**
```php
// Validate with explicit checks and throw exceptions (no die/exit)
if ($config === null) {
throw new \InvalidArgumentException('validation: config required');
}
// Domain exception types
class ResourceNotFoundException extends DomainException {}
class InvalidInputException extends DomainException {}
// Error mapping in handlers
try {
$result = $this->service->find($id);
} catch (ResourceNotFoundException $e) {
return response()->json(['error' => 'resource not found'], 404);
}
Reference Implementation (BAD):
if ($config === null) {
die('config is null');
}
$result = doSomething();
throw new \Exception('error');
Reference Implementation (GOOD — RFC 7807 Error Responses):
class ProblemDetails
{
public function __construct(
public readonly string $type, // URI reference identifying the problem type
public readonly string $title, // Short human-readable summary
public readonly int $status, // HTTP status code
public readonly string $detail, // Human-readable explanation specific to this occurrence
public readonly string $instance, // URI reference for the specific occurrence
public readonly string $code, // Machine-readable error code for programmatic handling
) {}
}
function problemResponse(int $status, string $errCode, string $detail, Request $request): JsonResponse
{
return response()->json(new ProblemDetails(
type: "https://api.example.com/errors/{$errCode}",
title: Response::$statusTexts[$status] ?? 'Error',
status: $status,
detail: $detail,
instance: $request->path(),
code: $errCode,
), $status);
}
public function create(Request $request): JsonResponse
{
try {
} catch (ResourceNotFoundException $e) {
return problemResponse(404, 'RESOURCE_NOT_FOUND', 'The requested resource does not exist', $request);
} catch (InvalidInputException $e) {
return problemResponse(422, 'VALIDATION_FAILED', $e->getMessage(), $request);
} catch (\Throwable $e) {
return problemResponse(500, 'INTERNAL_ERROR', 'An unexpected error occurred', $request);
}
}
Reference Implementation (BAD — Inconsistent Error Responses):
return response()->json(['error' => 'invalid input'], 400);
return response()->json(['message' => 'invalid input', 'code' => 400], 400);
return response()->json(['errors' => ['field X is required']], 400);
return response()->json(['error' => 'The email field is required and must be valid'], 422);
Check Against Bee Standards For:
- (HARD GATE) Explicit nil checks with error returns instead of panic for validation per Bee standards
- (HARD GATE) Named error variables (sentinel errors) per module following Bee error codes convention
- (HARD GATE) No panic() in non-test production code
- Proper error wrapping with %w
- errors.Is/errors.As for error matching
- No swallowed errors (_, err := ignored)
- HTTP error responses follow Bee ErrorResponse structure from domain.md
- RFC 7807 Problem Details format compliance — error responses MUST include:
type, title, status, detail, instance fields
- Consistent error response schema across all endpoints — every endpoint MUST return the same JSON error structure (no mixed formats)
- Machine-readable error codes for programmatic client consumption — every error response MUST include a stable, enumerated
code field (not free-text messages)
- Error response examples documented in API annotations (Swaggo
@Failure tags with response schema)
Severity Ratings:
- CRITICAL: panic() in production code paths (HARD GATE violation per Bee standards)
- CRITICAL: Swallowed errors in critical paths
- HIGH: Generic error messages without context
- HIGH: Error response format does not match Bee standards
- HIGH: Inconsistent error response format across endpoints (some return
{"error": "msg"}, others {"message": "msg", "code": "X"})
- MEDIUM: No RFC 7807 Problem Details compliance (error responses lack
type, title, status, detail, instance structure)
- MEDIUM: Error codes not machine-readable (free-text error messages only, no stable enumerated codes for programmatic consumption)
- MEDIUM: Inconsistent error types across modules
- LOW: Missing error wrapping context
- LOW: Missing error response examples in API documentation (Swaggo
@Failure annotations lack response body schema)
Output Format:
## Error Framework Audit Findings
### Summary
- Nil checks with error returns: X
- Panic calls in production: Y
- Swallowed errors: Z
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 3: Route Organization Auditor
```prompt
Audit route organization and handler structure for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Architecture Patterns" and "Directory Structure" sections from architecture.md}
---END STANDARDS---
**Search Patterns:**
- Files: `**/routes/*.php`, `**/Controllers/*.php`, `app/Http/Controllers/*.php`
- Keywords: `RegisterRoutes`, `protected(`, `fiber.Router`, `NewHandler`
- Standards-specific: `internal/{module}/adapters/`, `hexagonal`, `ports`
**Reference Implementation (GOOD):**
```php
// Centralized route registration (Laravel)
// routes/api.php
Route::middleware(['auth:sanctum', 'tenant'])->group(function () {
Route::post('/v1/resources', [ResourceController::class, 'create']);
Route::get('/v1/resources', [ResourceController::class, 'list']);
Route::get('/v1/resources/{id}', [ResourceController::class, 'show']);
});
// Controller constructor with dependency injection validation
class ResourceController extends Controller
{
public function __construct(
private readonly ResourceService $service,
private readonly ResourceRepository $repository,
) {
if ($this->service === null) {
throw new \InvalidArgumentException('ResourceService is required');
}
}
}
Check Against Bee Standards For:
- (HARD GATE) Hexagonal structure:
internal/{module}/adapters/http/ per architecture.md
- (HARD GATE) Centralized route registration per module
- Handler constructors validate all dependencies
- Consistent URL patterns (v1, kebab-case, plural resources) per Bee conventions
- All routes use protected() wrapper (no public endpoints without explicit exemption)
- Clear separation: routes files vs controllers per Bee directory structure
Severity Ratings:
- CRITICAL: Unprotected routes (missing auth middleware)
- CRITICAL: HARD GATE violation — project does not follow hexagonal architecture per Bee standards
- HIGH: Scattered route definitions
- MEDIUM: Handler accepts nil dependencies
- LOW: Inconsistent URL naming conventions
Output Format:
## Route Organization Audit Findings
### Summary
- Modules following hexagonal: X/Y
- Routes with protection: X/Y
- Handlers validating deps: X/Y
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 4: Bootstrap & Initialization Auditor
```prompt
Audit application bootstrap and initialization for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Bootstrap" section from bootstrap.md}
---END STANDARDS---
**Search Patterns:**
- Files: `**/bootstrap/app.php`, `**/bootstrap/*.php`, `artisan`
- Keywords: `InitServers`, `startupSucceeded`, `defer`, `cleanup`, `graceful`
- Standards-specific: `NewServiceBootstrap`, `staged initialization`
**Reference Implementation (GOOD):**
```php
// Staged initialization (Laravel bootstrap/app.php)
// 1. Load config — validated at boot via AppServiceProvider
public function boot(): void
{
// Fail fast if required config is missing
if (empty(config('services.database.url'))) {
throw new \RuntimeException('config: DATABASE_URL required');
}
}
// 2. Logger initialized by framework before providers boot
// 3. Telemetry initialized in TelemetryServiceProvider
public function register(): void
{
$this->app->singleton(Tracer::class, function () {
return $this->initTelemetry(config('telemetry'));
});
}
// 4. Connect infrastructure — deferred until first use via service providers
// 5. Graceful shutdown — registered signal handlers
register_shutdown_function(function () {
app(ConnectionPool::class)->closeAll();
app(QueueWorker::class)->stop();
});
Check Against Bee Standards For:
- (HARD GATE) Staged initialization order per bootstrap.md (config -> logger -> telemetry -> infra)
- (HARD GATE) Cleanup handlers for failed startup
- (HARD GATE) Graceful shutdown support
- Module initialization in dependency order per Bee bootstrap pattern
- Error propagation (not just logging and continuing)
- Production vs development mode handling
Severity Ratings:
- CRITICAL: No graceful shutdown (HARD GATE violation per Bee standards)
- CRITICAL: HARD GATE violation — bootstrap does not follow Bee staged initialization pattern
- HIGH: Resources not cleaned up on startup failure
- HIGH: Errors logged but not returned
- MEDIUM: Initialization order issues
- LOW: Missing development mode toggles
Output Format:
## Bootstrap Audit Findings
### Summary
- Graceful shutdown: Yes/No
- Cleanup on failure: Yes/No
- Staged initialization: Yes/No
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 5: Runtime Safety Auditor
```prompt
Audit pkg/runtime usage and panic handling for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Search Patterns:**
- PHP files: `**/Exceptions/**/*.php`, `**/Http/Kernel.php`, `**/bootstrap/app.php`, `**/Middleware/**/*.php`
- TypeScript files: `**/middleware/**/*.ts`, `**/error-handler*.ts`, `**/exceptions/**/*.ts`
- Keywords (PHP): `Handler`, `report(`, `render(`, `Bugsnag`, `Sentry`, `withExceptions`, `set_exception_handler`
- Keywords (TS): `uncaughtException`, `unhandledRejection`, `process.on(`, `catch (`, `ErrorBoundary`
**Reference Implementation (GOOD — PHP/Laravel):**
```php
// Global exception handler with structured logging (Laravel 11+)
// bootstrap/app.php
->withExceptions(function (Exceptions $exceptions) {
// Report all exceptions to Sentry/Bugsnag
$exceptions->report(function (Throwable $e) {
if (app()->environment('production')) {
app('sentry')->captureException($e);
}
});
// Render JSON errors for API routes
$exceptions->render(function (Throwable $e, Request $request) {
if ($request->expectsJson()) {
return response()->json([
'error' => [
'code' => 'INTERNAL_SERVER_ERROR',
'message' => app()->environment('production')
? 'An error occurred'
: $e->getMessage(),
]
], 500);
}
});
})
Reference Implementation (GOOD — TypeScript):
process.on('uncaughtException', (err) => {
logger.error('Uncaught exception', { error: err.message, stack: err.stack });
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled promise rejection', { reason, promise });
});
Check For:
- Global exception handler configured per framework conventions
- Production mode hides error details from API responses (no stack traces in JSON)
- Unhandled exceptions reported to error tracking (Sentry/Bugsnag)
- HTTP handlers have try/catch (TypeScript) or exception middleware (PHP)
- Background job failures logged and reported
- API routes return consistent JSON error structure on 500
Severity Ratings:
- CRITICAL: Stack traces or internal error details exposed in production API responses
- HIGH: No global exception handler configured
- HIGH: Unhandled exceptions/rejections not reported to error tracking
- MEDIUM: Background job failures not logged or tracked
- LOW: Inconsistent error response structure across endpoints
Output Format:
## Runtime Safety Audit Findings
### Summary
- Global exception handler: Yes/No
- Stack traces in production API responses: Yes/No
- Error tracking integration: Yes/No (Sentry/Bugsnag)
- Unhandled rejection handlers: Yes/No
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 6: Auth Protection Auditor
```prompt
Audit authentication and authorization implementation for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Access Manager Integration" section from security.md}
---END STANDARDS---
**Search Patterns:**
- Files: `**/Middleware/*.php`, `app/Http/Middleware/*.php`, `routes/api.php`
- Keywords: `Authorize`, `protected`, `JWT`, `tenant`, `ExtractToken`
- Standards-specific: `AccessManager`, `lib-auth`, `ProtectedGroup`
**Reference Implementation (GOOD):**
```php
// Protected route group via middleware (Laravel)
Route::middleware(['auth:sanctum', 'tenant', 'access-manager:contexts,create'])
->post('/v1/config/contexts', [ContextController::class, 'create']);
// All routes use auth middleware
Route::middleware(['auth:sanctum', 'tenant'])->group(function () {
Route::apiResource('contexts', ContextController::class);
});
// JWT validation middleware (lib-auth)
class ValidateJwtToken
{
public function handle(Request $request, Closure $next): Response
{
$token = $request->bearerToken();
if (empty($token)) {
throw new UnauthorizedException('Missing bearer token');
}
$claims = $this->libAuth->parseAndValidate($token, $this->signingSecret);
if ($claims['exp'] < time()) {
throw new UnauthorizedException('Token expired');
}
$request->merge(['tenant_id' => $claims['tenantId']]);
return $next($request);
}
}
Check Against Bee Standards For:
- (HARD GATE) All routes protected via Access Manager integration per security.md
- (HARD GATE) lib-auth used for JWT validation (not custom JWT parsing)
- Resource/action authorization granularity per Bee access control model
- Token expiration enforcement
- Tenant extraction from JWT claims
- Auth bypass for health/ready endpoints only
Severity Ratings:
- CRITICAL: Unprotected data endpoints (HARD GATE violation per Bee standards)
- CRITICAL: JWT parsed but not validated
- CRITICAL: HARD GATE violation — not using lib-auth for access management
- HIGH: Missing token expiration check
- HIGH: Tenant claims not enforced
- MEDIUM: Overly broad permissions
- LOW: Missing fine-grained actions
Output Format:
## Auth Protection Audit Findings
### Summary
- Protected routes: X/Y
- JWT validation: Complete/Partial/Missing
- Tenant enforcement: Yes/No
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 7: IDOR & Access Control Auditor
```prompt
Audit IDOR (Insecure Direct Object Reference) protection for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Search Patterns:**
- Files: `**/Verifier*.php`, `**/Controllers/*.php`, `**/Context*.php`
- Keywords: `VerifyOwnership`, `tenantID`, `contextID`, `ParseAndVerify`
**Reference Implementation (GOOD):**
```php
// 4-layer IDOR protection
class ResourceController extends Controller
{
public function show(Request $request, string $contextId): JsonResponse
{
// 1. UUID format validation
if (!Str::isUuid($contextId)) {
throw new InvalidArgumentException('Invalid context ID format');
}
// 2. Extract tenant from auth context (cannot be spoofed)
$tenantId = $request->get('tenant_id'); // set by JWT middleware
// 3. Database query filtered by tenant
// 4. Post-query ownership verification
$resource = $this->repository->findByTenant($contextId, $tenantId);
if ($resource === null) {
throw new ResourceNotFoundException('Resource not found');
}
if ($resource->tenant_id !== $tenantId) { // double-check ownership
throw new AccessDeniedException('Resource not owned by tenant');
}
return response()->json($resource);
}
}
// Repository implementation
class ResourceRepository
{
public function findByTenant(string $id, string $tenantId): ?Resource
{
return Resource::where('id', $id)
->where('tenant_id', $tenantId) // always filter by tenant
->first();
}
}
Reference Implementation (BAD):
public function show(string $id): JsonResponse
{
$resource = Resource::find($id);
return response()->json($resource);
}
Check For:
- All resource access verifies ownership
- Tenant ID from JWT context (not request params)
- Database queries include tenant filter
- Post-query ownership double-check
- UUID validation before database lookup
- Consistent verifier pattern across modules
Severity Ratings:
- CRITICAL: Resource access without ownership check
- CRITICAL: Tenant ID from user input (not JWT)
- HIGH: Missing post-query ownership verification
- MEDIUM: Inconsistent verifier implementation
- LOW: Missing UUID format validation
Output Format:
## IDOR Protection Audit Findings
### Summary
- Modules with verifiers: X/Y
- Multi-tenant filtered queries: X/Y
- Post-query verification: X/Y
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 8: SQL Safety Auditor
```prompt
Audit SQL injection prevention for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Search Patterns:**
- Files: `**/Repositories/*.php`, `app/Repositories/*.php`, `**/*Repository.php`
- Keywords: `ExecContext`, `QueryContext`, `Exec(`, `Query(`, `$1`, `$2`
- Also search for: String concatenation in SQL: `"SELECT.*" +`, `fmt.Sprintf.*SELECT`
**Reference Implementation (GOOD):**
```php
// Parameterized queries via PDO / Eloquent / Query Builder
DB::insert(
'INSERT INTO resources (id, name, tenant_id) VALUES (?, ?, ?)',
[$id, $name, $tenantId]
);
// Eloquent query builder — always parameterized
Resource::where('tenant_id', $tenantId)->where('name', $name)->first();
// Raw query with bindings
DB::select('SELECT * FROM resources WHERE tenant_id = ? AND id = ?', [$tenantId, $id]);
// SQL identifier escaping for dynamic schemas (via PDO quoteIdentifier)
$escapedSchema = DB::connection()->getPdo()->quote($tenantId);
DB::statement("SET search_path TO {$escapedSchema}");
Reference Implementation (BAD):
$query = "SELECT * FROM users WHERE name = '" . $name . "'";
$query = sprintf("SELECT * FROM users WHERE id = '%s'", $id);
DB::statement("SET search_path TO " . $tenantId);
Check For:
- All queries use parameterized statements ($1, $2, ...)
- No string concatenation in SQL queries
- Dynamic identifiers properly escaped (QuoteIdentifier)
- Query builders used for complex WHERE clauses
- No raw SQL with user input
Severity Ratings:
- CRITICAL: String concatenation with user input
- CRITICAL: fmt.Sprintf with user values
- HIGH: Unescaped dynamic identifiers
- MEDIUM: Raw SQL where builder would be safer
- LOW: Inconsistent query patterns
Output Format:
## SQL Safety Audit Findings
### Summary
- Parameterized queries: X/Y
- String concatenation risks: Z
- Identifier escaping: Yes/No
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 9: Input Validation Auditor
```prompt
Audit input validation patterns for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Frameworks & Libraries" section from core.md — specifically Laravel Form Requests and Spatie validation reference}
---END STANDARDS---
**Search Patterns:**
- Files: `**/DTO/*.php`, `**/Controllers/*.php`, `**/ValueObjects/*.php`, `**/Requests/*.php`
- Keywords: `FormRequest`, `rules()`, `validated()`, `IsValid()`, `$request->validate`
- Standards-specific: `Laravel Form Requests`, `Spatie`, `validateOrFail`
**Reference Implementation (GOOD):**
```php
// Form Request with validation rules
class CreateResourceRequest extends FormRequest
{
public function rules(): array
{
return [
'name' => ['required', 'string', 'min:1', 'max:255'],
'type' => ['required', 'string', 'in:TYPE_A,TYPE_B'],
'amount' => ['required', 'integer', 'min:0', 'max:1000000'],
];
}
}
// Controller — validation enforced automatically
class ResourceController extends Controller
{
public function create(CreateResourceRequest $request): JsonResponse
{
// $request->validated() only contains validated fields
$data = $request->validated();
// ...
}
}
// Value object with domain validation
class AmountValueObject
{
private const MAX_LENGTH = 255;
private const VALID_PATTERN = '/^[A-Za-z0-9]+$/';
public function isValid(): bool
{
if (empty($this->value) || strlen($this->value) > self::MAX_LENGTH) {
return false;
}
return (bool) preg_match(self::VALID_PATTERN, $this->value);
}
}
Reference Implementation (BAD):
class CreateRequest extends FormRequest
{
public function rules(): array
{
return [];
}
}
$name = $request->input('name');
$amount = (int) $request->input('amount');
Check Against Bee Standards For:
- (HARD GATE) Laravel Form Requests used for input validation per Bee core.md
- (HARD GATE) All Form Requests have rules() defined for required fields
- BodyParser errors are handled (not ignored)
- Query/path params validated before use
- Numeric bounds enforced (min/max)
- String length limits enforced
- Enum values constrained (oneof=)
- Value objects have IsValid() methods
- File upload size/type validation
Severity Ratings:
- CRITICAL: BodyParser errors ignored
- CRITICAL: HARD GATE violation — not using Laravel Form Requests for validation per Bee standards
- HIGH: No validation on user input DTOs
- HIGH: Unbounded numeric inputs
- MEDIUM: Missing string length limits
- LOW: Value objects without IsValid()
Output Format:
## Input Validation Audit Findings
### Summary
- DTOs with validation tags: X/Y
- BodyParser error handling: X/Y
- Value objects with IsValid: X/Y
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 10: Telemetry & Observability Auditor
```prompt
Audit telemetry and observability implementation for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Observability" section from bootstrap.md and "OpenTelemetry with lib-commons" section from sre.md}
---END STANDARDS---
**Search Patterns:**
- Files: `**/Observability*.php`, `**/Telemetry*.php`, `**/Controllers/*.php`
- Keywords: `NewTrackingFromContext`, `tracer.Start`, `span`, `logger`, `metrics`
- Standards-specific: `libCommons.NewTrackingFromContext`, `otel`, `OpenTelemetry`
**Reference Implementation (GOOD):**
```php
// Handler with proper telemetry (PHP/lib-commons)
class ResourceController extends Controller
{
public function doSomething(Request $request): JsonResponse
{
$tracer = app(Tracer::class);
$span = $tracer->spanBuilder('handler.doSomething')->startSpan();
$scope = $span->activate();
try {
$span->setAttribute('request_id', $request->header('X-Request-Id'));
// ... business logic
return response()->json($result);
} catch (\Throwable $e) {
$span->recordException($e);
$span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage());
Log::error('operation failed', ['error' => $e->getMessage()]);
throw $e;
} finally {
$scope->detach();
$span->end();
}
}
}
Reference Implementation (GOOD — Trace Propagation & Sampling):
class TracedHttpClient
{
public function send(string $url, array $options = []): ResponseInterface
{
$propagator = Globals::propagator();
$carrier = [];
$propagator->inject($carrier);
$options['headers'] = array_merge($options['headers'] ?? [], $carrier);
return $this->httpClient->request('GET', $url, $options);
}
}
$baggage = Baggage::getBuilder()
->set('tenantId', $tenantId)
->set('userId', $userId)
->build();
Context::storage()->attach(
Context::getCurrent()->withContextValue($baggage)
);
class ProcessOrderJob implements ShouldQueue
{
public function handle(): void
{
$propagator = Globals::propagator();
$producerCtx = $propagator->extract($this->traceHeaders);
$tracer = app(Tracer::class);
$span = $tracer->spanBuilder('consume.' . $this->eventType)
->addLink(Span::fromContext($producerCtx)->getContext())
->startSpan();
try {
$this->processEvent();
} finally {
$span->end();
}
}
}
return [
'sampler' => env('APP_ENV') === 'production'
? new ParentBased(new TraceIdRatioBased(0.1))
: new AlwaysOnSampler(),
];
$span->setAttribute('order.id', $order->id);
$span->setAttribute('tenant.id', $tenantId);
$span->setAttribute('order.amount', $order->total_amount);
Reference Implementation (BAD — Trace Propagation):
class HttpClient
{
public function send(string $url): ResponseInterface
{
return $this->client->request('GET', $url);
}
}
class ProcessOrderJob implements ShouldQueue
{
public function handle(): void
{
$span = app(Tracer::class)->spanBuilder('consume.event')->startSpan();
$this->processEvent();
$span->end();
}
}
Check Against Bee Standards For:
- (HARD GATE) lib-commons NewTrackingFromContext used for telemetry initialization per Bee standards
- (HARD GATE) OpenTelemetry integration (not custom tracing) per sre.md
- All handlers start spans with descriptive names
- Errors recorded to spans before returning
- Request IDs propagated through context
- Metrics initialized at startup per bootstrap.md observability section
- Structured logging with context (not fmt.Println)
- Graceful telemetry shutdown
- Cross-service trace context propagation — outgoing HTTP requests MUST inject W3C Trace Context headers (
traceparent, tracestate) using OpenTelemetry propagators
- Baggage propagation across service boundaries — business context (e.g.,
tenantId, userId, correlationId) MUST be propagated via OpenTelemetry Baggage for cross-service observability
- Span linking for async flows — message producer spans MUST be linked to consumer spans via
trace.WithLinks() so async flows appear connected in distributed traces
- Trace sampling configuration — production environments MUST configure sampling rate (not 100% sampling) to control cost; development environments may use
AlwaysSample
- Custom span attributes for business-relevant data — spans MUST include domain-specific attributes (e.g.,
order.id, tenant.id, transaction.amount) for meaningful trace filtering
Severity Ratings:
- CRITICAL: No tracing in handlers (HARD GATE violation per Bee standards)
- CRITICAL: HARD GATE violation — not using lib-commons for telemetry
- HIGH: Errors not recorded to spans
- HIGH: No trace context propagation in outgoing HTTP requests (downstream services cannot correlate traces — breaks distributed tracing)
- HIGH: Async message flows break trace continuity (no span links between producer and consumer — message processing appears as disconnected traces)
- MEDIUM: Missing request ID propagation
- MEDIUM: No trace sampling configuration (100% sampling in production = storage cost explosion and performance overhead)
- MEDIUM: Missing baggage propagation for cross-service business context (cannot filter/correlate traces by tenant, user, or business entity)
- LOW: Inconsistent span naming conventions
- LOW: No custom span attributes for business metrics (traces lack domain context for meaningful filtering and alerting)
Output Format:
## Telemetry Audit Findings
### Summary
- Handlers with tracing: X/Y
- Handlers with error recording: X/Y
- Metrics initialization: Yes/No
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 12: Health Checks Auditor
```prompt
Audit health check endpoints for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Health Checks" section from sre.md}
---END STANDARDS---
**Search Patterns:**
- Files: `**/Http/Kernel.php`, `**/Health*.php`, `routes/api.php`
- Keywords: `/health`, `/ready`, `/live`, `healthHandler`, `readinessHandler`
- Standards-specific: `liveness`, `readiness`, `degraded`
**Reference Implementation (GOOD):**
```php
// Liveness probe — always returns healthy if process is running
// routes/api.php
Route::get('/health', fn () => response('healthy', 200));
// Readiness probe — checks all dependencies
Route::get('/ready', function () {
$checks = [];
$status = 200;
// Required dependency — fails readiness if down
try {
DB::connection()->getPdo()->query('SELECT 1');
$checks['database'] = 'healthy';
} catch (\Throwable $e) {
$checks['database'] = 'unhealthy';
$status = 503;
}
// Optional dependency — reports degraded but doesn't fail readiness
try {
Redis::ping();
$checks['redis'] = 'healthy';
} catch (\Throwable $e) {
$checks['redis'] = 'degraded';
// status stays 200 — optional dep
}
return response()->json([
'status' => $status === 200 ? 'healthy' : 'unavailable',
'checks' => $checks,
], $status);
});
Check Against Bee Standards For:
- (HARD GATE) /health endpoint exists (liveness) per sre.md
- (HARD GATE) /ready endpoint exists (readiness) per sre.md
- Health endpoints bypass auth middleware
- Database connectivity checked in readiness
- Message queue connectivity checked
- Optional deps don't fail readiness (just report degraded) per Bee health check pattern
- Response includes individual check status
- Appropriate HTTP status codes (200 vs 503)
Severity Ratings:
- CRITICAL: No health endpoints at all (HARD GATE violation per Bee standards)
- HIGH: No readiness probe (only liveness)
- HIGH: Health endpoints require auth
- MEDIUM: Missing dependency checks in readiness
- LOW: No degraded status for optional deps
Output Format:
## Health Checks Audit Findings
### Summary
- Liveness endpoint: Yes/No (/path)
- Readiness endpoint: Yes/No (/path)
- Dependencies checked: [list]
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 13: Configuration Management Auditor
```prompt
Audit configuration management for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Configuration" section from core.md}
---END STANDARDS---
**Search Patterns:**
- Files: `**/config/*.php`, `**/bootstrap/*.php`, `**/.env*`
- Keywords: `env:`, `envDefault:`, `Validate()`, `LoadConfig`, `production`
- Standards-specific: `envconfig`, `caarlos0/env`
**Reference Implementation (GOOD):**
```php
// Config loaded from env vars with defaults (Laravel config files)
// config/app.php
return [
'env' => env('APP_ENV', 'development'),
'db_password' => env('DB_PASSWORD'),
'auth_enabled' => env('AUTH_ENABLED', false),
'db_ssl_mode' => env('DB_SSLMODE', 'require'),
];
// Production validation in AppServiceProvider
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
if (app()->environment('production')) {
// Require auth in production
if (!config('app.auth_enabled')) {
throw new \RuntimeException('AUTH_ENABLED must be true in production');
}
// Require DB password in production
if (empty(config('app.db_password'))) {
throw new \RuntimeException('DB_PASSWORD required in production');
}
// Require TLS for databases
if (config('app.db_ssl_mode') === 'disable') {
throw new \RuntimeException('DB_SSLMODE cannot be disable in production');
}
}
}
}
Check Against Bee Standards For:
- (HARD GATE) All config loaded from env vars (not hardcoded) per Bee core.md configuration section
- (HARD GATE) Production-specific validation exists
- Sensible defaults for non-production
- Auth required in production
- TLS/SSL required in production
- Default credentials rejected in production
- Secrets not logged during startup
- Config validation fails fast (at startup)
Severity Ratings:
- CRITICAL: Hardcoded secrets in code (HARD GATE violation per Bee standards)
- CRITICAL: No production validation
- HIGH: Auth can be disabled in production
- HIGH: TLS not enforced in production
- MEDIUM: Missing sensible defaults
- LOW: Config not validated at startup
Output Format:
## Configuration Management Audit Findings
### Summary
- Env vars used: X fields
- Production validation: Yes/No
- Constraints enforced: [list]
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 14: Connection Management Auditor
```prompt
Audit database and cache connection management for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Core Dependency: lib-commons" section from core.md — specifically connection packages}
---END STANDARDS---
**Search Patterns:**
- Files: `**/config/database.php`, `**/config/cache.php`, `**/database*.php`, `**/Redis*.php`
- Keywords: `MaxOpenConns`, `MaxIdleConns`, `PoolSize`, `Timeout`, `SetConnMaxLifetime`
- Standards-specific: `lib-commons`, `mpostgres`, `mredis`, `mmongo`
**Reference Implementation (GOOD):**
```php
// Database pool configuration (config/database.php)
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'pool' => [
'max_connections' => env('POSTGRES_MAX_OPEN_CONNS', 25),
'min_connections' => env('POSTGRES_MAX_IDLE_CONNS', 5),
'max_lifetime' => env('POSTGRES_CONN_MAX_LIFETIME_MINS', 30) * 60,
],
'sticky' => true,
'read' => ['host' => env('DB_REPLICA_HOST')], // replica support
'write' => ['host' => env('DB_HOST')],
],
// Redis pool configuration (config/database.php)
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'port' => env('REDIS_PORT', 6379),
'pool' => [
'max_connections' => env('REDIS_POOL_SIZE', 10),
'min_connections' => env('REDIS_MIN_IDLE_CONNS', 2),
],
'read_timeout' => env('REDIS_READ_TIMEOUT_MS', 3000) / 1000,
'timeout' => env('REDIS_DIAL_TIMEOUT_MS', 5000) / 1000,
],
],
Check Against Bee Standards For:
- (HARD GATE) lib-commons connection packages used (mpostgres, mredis, mmongo) per core.md
- DB connection pool limits configured
- Redis pool settings configured
- Connection timeouts set (not infinite)
- Connection max lifetime set (prevents stale connections)
- Idle connection limits reasonable
- Read replica support (for scaling reads)
- Connection health checks (ping on checkout)
- Graceful connection shutdown
Severity Ratings:
- CRITICAL: No connection pool limits (unbounded connections)
- CRITICAL: HARD GATE violation — not using lib-commons connection packages
- HIGH: No connection timeouts (hang forever)
- HIGH: No max lifetime (stale connections)
- MEDIUM: Missing read replica support
- LOW: Pool sizes not tuned
Output Format:
## Connection Management Audit Findings
### Summary
- DB pool configured: Yes/No (max: X, idle: Y)
- Redis pool configured: Yes/No (size: X)
- Timeouts configured: Yes/No
- Replica support: Yes/No
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 15: Logging & PII Safety Auditor
```prompt
Audit logging practices and PII protection for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Logging" section from quality.md}
---END STANDARDS---
**Search Patterns:**
- PHP files: `**/*.php` — search for logging calls, PII in log context
- TypeScript files: `**/*.ts`, `**/*.tsx` — search for console.log, logger usage, PII in logs
- Keywords (PHP): `Log::`, `\Log::`, `logger(`, `error_log(`, `echo `, `var_dump(`, `password`, `token`, `secret`
- Keywords (TS): `console.log(`, `console.error(`, `logger.`, `winston`, `pino`, `password`, `token`, `secret`
- Standards-specific: structured logging library references (`monolog`, `winston`, `pino`)
**Reference Implementation (GOOD — PHP/Laravel):**
```php
// Structured logging with context
Log::info('Resource created', [
'request_id' => $request->header('X-Request-Id'),
'user_id' => $user->id,
'action' => 'create_resource',
'resource_id' => $resource->id,
]);
// Production-safe error logging (no PII in error message)
Log::error('Operation failed', [
'status' => $statusCode,
'path' => $request->path(),
// NO: password, email, credit card numbers
]);
Reference Implementation (GOOD — TypeScript):
logger.info('Resource created', {
requestId: req.headers['x-request-id'],
userId: user.id,
action: 'create_resource',
});
logger.error('Login failed', {
userId: user.id,
});
Reference Implementation (BAD):
var_dump($user);
Log::info('Login attempt', ['email' => $email, 'password' => $password]);
Log::debug('Request body', $request->all());
console.log('User logged in:', user.email);
console.log('Login attempt:', { email, password });
Check Against Bee Standards For:
- (HARD GATE) Structured logging used (not echo/var_dump for PHP, not console.log for TypeScript) per quality.md logging section
- Log entries include request ID and user ID for traceability
- No passwords/tokens/card numbers logged
- Request/response bodies not logged raw (may contain PII)
- Log levels used appropriately (error for exceptions, info for business events, debug for internals)
- Log levels appropriate (not everything at INFO)
- Request IDs included for tracing
- No PII in log messages (emails, names, etc.)
Severity Ratings:
- CRITICAL: Passwords/tokens logged
- CRITICAL: PII logged in production
- HIGH: fmt.Print used instead of logger (HARD GATE violation per Bee standards)
- HIGH: Full error details in production
- MEDIUM: Missing request ID in logs
- LOW: Inappropriate log levels
Output Format:
## Logging & PII Safety Audit Findings
### Summary
- Structured logging: Yes/No
- PII protection: Yes/No
- Production mode: Yes/No
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 16: Idempotency Auditor
```prompt
Audit idempotency implementation for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: Full module content from idempotency.md}
---END STANDARDS---
**Search Patterns:**
- Files: `**/Idempotency*.php`, `**/ValueObjects/*.php`, `**/Redis/*.php`
- Keywords: `IdempotencyKey`, `TryAcquire`, `MarkComplete`, `SetNX`, `idempotent`
- Standards-specific: `IdempotencyRepository`, `idempotency middleware`
**Reference Implementation (GOOD):**
```php
// Idempotency key value object
class IdempotencyKey
{
private const MAX_LENGTH = 128;
private const VALID_PATTERN = '/^[A-Za-z0-9:_-]+$/';
public function __construct(private readonly string $value) {}
public function isValid(): bool
{
if (empty($this->value) || strlen($this->value) > self::MAX_LENGTH) {
return false;
}
return (bool) preg_match(self::VALID_PATTERN, $this->value);
}
public function __toString(): string { return $this->value; }
}
// Redis-backed idempotency repository
class IdempotencyRepository
{
private const TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days
public function tryAcquire(IdempotencyKey $key): bool
{
// SET NX is atomic — only first caller wins
return (bool) Redis::set(
"idempotency:{$key}",
'acquired',
['NX', 'EX' => self::TTL_SECONDS]
);
}
public function markComplete(IdempotencyKey $key): void
{
Redis::set("idempotency:{$key}", 'complete', ['EX' => self::TTL_SECONDS]);
}
}
// Usage in controller
class PaymentController extends Controller
{
public function processCallback(Request $request): JsonResponse
{
$key = new IdempotencyKey($request->header('Idempotency-Key'));
if (!$this->idempotency->tryAcquire($key)) {
return response()->json(['status' => 'already_processed'], 200);
}
// Process...
$result = $this->paymentService->process($request->validated());
$this->idempotency->markComplete($key);
return response()->json($result);
}
}
Check Against Bee Standards For:
- (HARD GATE) Idempotency keys for financial/critical operations per idempotency.md
- (HARD GATE) Atomic acquire mechanism (SetNX or similar)
- TTL to prevent unbounded storage
- Key validation (format, length) per Bee idempotency patterns
- Proper state transitions (acquired -> complete/failed)
- Retry-safe (failed operations can be retried)
- Idempotency for webhook callbacks
- Idempotency for payment operations
Severity Ratings:
- CRITICAL: No idempotency for financial operations (HARD GATE violation per Bee standards)
- HIGH: Non-atomic acquire (race conditions)
- HIGH: No TTL (memory leak)
- MEDIUM: Missing key validation
- LOW: No failed state handling
Output Format:
## Idempotency Audit Findings
### Summary
- Idempotency implemented: Yes/No
- Operations covered: [list]
- Storage backend: Redis/DB/Memory
- TTL configured: X days
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 17: API Documentation Auditor
```prompt
Audit API documentation (Swagger/OpenAPI) for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: Swaggo/OpenAPI subsection from "Pagination Patterns" in api-patterns.md}
---END STANDARDS---
**Search Patterns:**
- PHP files: `**/Http/Controllers/**/*.php`, `**/Requests/**/*.php`, `**/Resources/**/*.php`, `**/swagger.yaml`, `**/openapi.yaml`
- TypeScript files: `**/swagger.ts`, `**/openapi.ts`, `**/*.swagger.ts`, JSDoc/TSDoc comments with `@openapi`
- Config files: `openapi.yaml`, `swagger.yaml`, `docs/swagger.json`
- Keywords (PHP): `@OA\`, `#[OA\`, `swagger-php`, `@param`, `@return`, `openapi`
- Keywords (TS): `@swagger`, `@openapi`, `swagger-jsdoc`, `@nestjs/swagger`, `zod-openapi`
- Standards-specific: `swagger-php`, `zod-openapi`, `openapi.yaml`
**Reference Implementation (GOOD — PHP/L5-Swagger):**
```php
/**
* @OA\Post(
* path="/v1/resources",
* summary="Create a resource",
* description="Creates a new resource with the given parameters",
* tags={"Resources"},
* security={{"bearerAuth":{}}},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(ref="#/components/schemas/CreateResourceRequest")
* ),
* @OA\Response(response=201, description="Created", @OA\JsonContent(ref="#/components/schemas/ResourceResponse")),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=500, description="Internal error"),
* )
*/
public function store(CreateResourceRequest $request): JsonResponse {}
Reference Implementation (GOOD — TypeScript/NestJS):
@ApiOperation({ summary: 'Create a resource' })
@ApiResponse({ status: 201, type: ResourceDto })
@ApiResponse({ status: 400, description: 'Invalid input' })
@ApiBearerAuth()
@Post('/v1/resources')
async create(@Body() dto: CreateResourceDto): Promise<ResourceDto> {}
Check Against Bee Standards For:
- (HARD GATE) OpenAPI/Swagger documentation present per Bee api-patterns.md
- API title, version, description in openapi config
- Security definitions (Bearer token / OAuth)
- All endpoints have route documentation
- Request/response types documented with examples
- All error codes documented (400, 401, 403, 500)
- Swagger UI accessible at
/api/documentation or /api-docs
Severity Ratings:
- HIGH: No OpenAPI/Swagger documentation at all (HARD GATE violation per Bee standards)
- HIGH: Missing security definitions
- MEDIUM: Endpoints without documentation
- MEDIUM: Error responses not documented
- LOW: Missing examples in request/response schemas
- LOW: Inconsistent tag usage
Output Format:
## API Documentation Audit Findings
### Summary
- Swagger annotations: Yes/No
- Documented endpoints: X/Y
- Security definitions: Yes/No
- Error responses documented: X/Y
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 18: Technical Debt Auditor
```prompt
Audit technical debt indicators for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Search Patterns (with context):**
- `TODO` - Planned work
- `FIXME` - Known bugs
- `HACK` - Workarounds
- `XXX` - Danger zones
- `deprecated` (case-insensitive)
- `"in a real implementation"` or `"real implementation"`
- `"temporary"` or `"temp fix"`
- `"workaround"`
- `panic("not implemented")`
**Risk Assessment Criteria:**
**Implement Now (High Risk):**
- Security-related TODOs (auth, validation, encryption)
- Error handling TODOs in critical paths
- Data integrity issues
- "FIXME" in production code paths
**Monitor (Medium Risk):**
- Performance optimization TODOs
- Incomplete logging
- "deprecated" usage without migration plan
**Acceptable Debt (Low Risk):**
- Future feature ideas
- Code style improvements
- Test coverage expansion
- Documentation improvements
**Output Format:**
Technical Debt Audit Findings
Summary
- Total TODOs: X
- Total FIXMEs: Y
- Deprecated usage: Z
- "Real implementation" markers: N
HIGH RISK - Implement Now
| File:Line | Type | Description | Risk |
|---|
| path:123 | TODO | Auth bypass for testing | Security |
MEDIUM RISK - Monitor
| File:Line | Type | Description | Risk |
|---|
LOW RISK - Acceptable Debt
| File:Line | Type | Description | Risk |
|---|
Recommendations
- ...
Agent 19: Testing Coverage Auditor
Audit test coverage and testing patterns for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Testing" section from quality.md}
---END STANDARDS---
**Search Patterns:**
- PHP files: `**/*Test.php`, `**/tests/**/*.php`, `**/test/**/*.php`
- TypeScript files: `**/*.test.ts`, `**/*.spec.ts`, `**/*.test.tsx`, `**/*.spec.tsx`, `**/__tests__/**/*.ts`
- Keywords (PHP): `extends TestCase`, `it(`, `test(`, `describe(`, `Mockery::mock`, `$this->mock`, `$this->assertSame`, `$this->assertEquals`, `uses(Tests\TestCase::class)`
- Keywords (TS): `describe(`, `it(`, `test(`, `expect(`, `jest.mock`, `vi.mock`, `beforeEach`, `afterEach`
- Standards-specific: `PHPUnit`, `Pest`, `Mockery`, `Jest`, `Vitest`, `testcontainers`
**Reference Implementation (GOOD — PHP/Pest):**
```php
// Pest test co-located with feature (tests/Feature/CreateOrderTest.php)
use App\Models\Order;
use Mockery;
it('creates an order successfully', function () {
// Arrange
$repository = Mockery::mock(OrderRepositoryInterface::class);
$repository->shouldReceive('save')->once()->andReturn(true);
app()->instance(OrderRepositoryInterface::class, $repository);
// Act
$response = $this->postJson('/api/orders', [
'amount' => 100,
'currency' => 'USD',
]);
// Assert
$response->assertCreated();
$response->assertJsonStructure(['id', 'amount', 'currency']);
});
// Data-driven test for validation
it('validates order amount', function (int $amount, bool $valid) {
$response = $this->postJson('/api/orders', ['amount' => $amount]);
$valid ? $response->assertCreated() : $response->assertUnprocessable();
})->with([
[100, true],
[-1, false],
[0, false],
]);
Reference Implementation (GOOD — TypeScript/Jest):
describe('OrderService', () => {
let service: OrderService;
let mockRepo: jest.Mocked<OrderRepository>;
beforeEach(() => {
mockRepo = { save: jest.fn(), findById: jest.fn() } as any;
service = new OrderService(mockRepo);
});
it('creates an order', async () => {
mockRepo.save.mockResolvedValue({ id: '1', amount: 100 });
const result = await service.create({ amount: 100 });
expect(result.id).toBe('1');
expect(mockRepo.save).toHaveBeenCalledTimes(1);
});
it.each([
[-1, false],
[0, false],
[100, true],
])('validates amount %i → valid: %s', async (amount, valid) => {
if (!valid) {
await expect(service.create({ amount })).rejects.toThrow();
}
});
});
Check Against Bee Standards For:
- (HARD GATE) Test files co-located with feature modules or in
tests/ directory per quality.md testing section
- (HARD GATE) Mocks use Mockery (PHP) or Jest/Vitest
mock() (TypeScript) — not hand-written stubs
- (HARD GATE) Assertions use PHPUnit/Pest assertions or Jest
expect() per Bee standards
- Data-driven / parameterized tests for validators and edge cases
- Integration tests covering external dependencies (DB, Redis, HTTP)
- Test helpers/fixtures organized in
tests/Helpers/ or __fixtures__/
- Tests isolated — no shared mutable state between test cases
- Test cleanup in
afterEach / tearDown / Mockery::close()
Severity Ratings:
- HIGH: Critical paths without tests (HARD GATE violation per Bee standards)
- HIGH: Hand-written mocks instead of Mockery / Jest mocks (per Bee standards)
- MEDIUM: Missing parameterized tests for validators
- MEDIUM: No integration tests
- LOW: Missing edge case coverage
- LOW: Test cleanup not implemented (Mockery::close() missing for PHP)
Output Format:
## Testing Coverage Audit Findings
### Summary
- Test files found: X
- Modules with tests: X/Y
- Mock approach: Mockery / Jest mocks / hand-written
- Integration tests: Yes/No
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 20: Dependency Management Auditor
```prompt
Audit dependency management for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Frameworks & Libraries" section from core.md — specifically the version table}
---END STANDARDS---
**Search Patterns:**
- PHP files: `composer.json`, `composer.lock`, `**/vendor/composer/installed.json`
- TypeScript files: `package.json`, `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`
- Commands: Run `composer audit` (PHP) or `npm audit` / `pnpm audit` (TypeScript) for vulnerability scan
- Standards-specific: Check for required Bee dependencies per stack
**Reference Implementation (GOOD — PHP):**
```json
// composer.json with pinned constraints
{
"require": {
"php": "^8.3",
"laravel/framework": "^11.0",
"lerian-studio/lib-commons": "^2.0",
"firebase/php-jwt": "^6.10"
},
"require-dev": {
"pestphp/pest": "^3.0",
"mockery/mockery": "^1.6",
"phpstan/phpstan": "^1.11",
"laravel/pint": "^1.17"
}
}
Reference Implementation (GOOD — TypeScript):
{
"dependencies": {
"next": "15.2.x",
"@opentelemetry/api": "^1.9.0"
},
"devDependencies": {
"typescript": "^5.6.0",
"eslint": "^9.0.0",
"vitest": "^2.0.0"
}
}
Reference Implementation (BAD — PHP):
{
"require": {
"laravel/framework": "*",
"some/package": "dev-master"
}
}
Check Against Bee Standards For:
- (HARD GATE) Required Bee framework dependencies present in composer.json / package.json per core.md version table
- All dependencies pinned (no
* or dev-master in PHP, no latest in npm)
- Lock files committed (
composer.lock, package-lock.json)
- Known vulnerable packages identified via
composer audit / npm audit
- No unused dependencies
- Major version mismatches in core framework
- Framework versions meet Bee minimum requirements (PHP 8.3+, Laravel 11+, Node 22+)
Known Vulnerable Packages to Flag (PHP):
laravel/framework versions with known critical CVEs
firebase/php-jwt < v6.0 (algorithm confusion vulnerabilities)
- Any package flagged by
composer audit
Known Vulnerable Packages to Flag (TypeScript):
- Any package flagged by
npm audit --audit-level=high
Severity Ratings:
- CRITICAL: Known CVE in dependency
- CRITICAL: HARD GATE violation — required Bee framework dependency missing from composer.json / package.json
- HIGH: Lock file not committed
- HIGH: Deprecated package with security issues
- MEDIUM: Significantly outdated dependencies
- MEDIUM: Framework versions below Bee minimum requirements
- LOW: Minor version behind
Output Format:
## Dependency Audit Findings
### Summary
- Total dependencies: X
- Direct dependencies: Y
- Potentially outdated: Z
- Known vulnerabilities: N
### Critical Issues
[package] - Description
### Recommendations
1. ...
### Agent 21: Performance Patterns Auditor
```prompt
Audit performance patterns for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Search Patterns:**
- PHP files: `**/*.php` — search for Eloquent queries, DB::table, foreach loops, N+1 patterns
- TypeScript files: `**/*.ts`, `**/*.tsx` — search for array operations, Promise.all, SELECT patterns
- Keywords (PHP): `->get()`, `->all()`, `foreach (`, `SELECT *`, `->with(`, `->load(`
- Keywords (TS): `SELECT *`, `findMany`, `findAll`, `Promise.all`, `for.*of`
**Reference Implementation (GOOD — PHP/Laravel):**
```php
// Select only needed columns
$users = User::select('id', 'name', 'email')->paginate(20); // Not all columns
// Avoid N+1 with eager loading
$orders = Order::with(['items', 'customer'])->paginate(20);
// Batch database operations
Order::insert($ordersArray); // Single query instead of N inserts
// Chunk large datasets
User::chunk(200, function ($users) {
foreach ($users as $user) {
// process without loading all records into memory
}
});
Reference Implementation (GOOD — TypeScript):
const users = await db.user.findMany({
select: { id: true, name: true, email: true },
take: 20,
});
const orders = await db.order.findMany({
include: { items: true, customer: { select: { name: true } } },
});
const results = await Promise.all(ids.slice(0, 10).map(id => fetchById(id)));
Reference Implementation (BAD):
$users = User::all();
$orders = Order::paginate(20);
foreach ($orders as $order) {
$customer = Customer::find($order->customer_id);
}
$allUsers = User::all();
Check For:
- SELECT * avoided (explicit column selection)
- N+1 queries prevented (use eager loading / include)
- Large datasets processed in chunks, not
->all()
- Batch operations for bulk inserts/updates
- Indexes exist for filtered/sorted columns
- Connection pooling configured
- Database query timeouts configured
Severity Ratings:
- HIGH: N+1 query pattern in production code
- HIGH: SELECT * on large tables
- MEDIUM: Loading entire dataset into memory instead of chunking
- MEDIUM: No batch operations for bulk data
- LOW: Minor inefficiencies
Output Format:
## Performance Audit Findings
### Summary
- N+1 patterns found: X
- SELECT * usage: Y
- Missing pre-allocations: Z
### Critical Issues
[file:line] - Description
### Recommendations
1. ...
### Agent 22: Concurrency Safety Auditor
```prompt
Audit concurrency patterns for production readiness.
**Detected Stack:** {DETECTED_STACK}
**Bee Standards (Source of Truth):**
---BEGIN STANDARDS---
{INJECTED: "Concurrency Patterns" section from architecture.md}
---END STANDARDS---
**Search Patterns:**
- PHP files: `**/*.php` — search for async/queue jobs, parallel execution, shared state
- TypeScript files: `**/*.ts`, `**/*.tsx` — search for async/await, Promise.all, shared mutable state, race conditions
- Keywords (PHP): `dispatch(`, `Queue::push`, `parallel(`, `array_map`, `static $`, `Cache::lock`
- Keywords (TS): `async`, `await`, `Promise.all`, `Promise.race`, `Promise.allSettled`, `setTimeout`, `setInterval`, `EventEmitter`, `shared`
- Standards-specific: `p-limit`, `semaphore`, `queue`, `worker`, `AbortController`
**Reference Implementation (GOOD — TypeScript):**
```typescript
// Bounded concurrency with p-limit
import pLimit from 'p-limit';
const limit = pLimit(10); // max 10 concurrent
const results = await Promise.all(
items.map(item => limit(() => processItem(item)))
);
// Promise.allSettled for partial failures
const results = await Promise.allSettled(