sightbox/playbook/ENTERPRISE_STANDARDS.md

22 KiB

Enterprise Software Development Standards

Append this file to any project's CLAUDE.md before starting a build. Every section is a constraint, not a suggestion. Adapt the stack-specific details (e.g. FastAPI vs Flask, PocketBase vs PostgreSQL) but never remove a section. If a pattern does not apply, mark it explicitly as N/A with a reason rather than silently omitting it.


1. Languages & Conventions

  • Backend: Python only. Standard Python conventions throughout. No mixed languages in the same service.
  • Frontend: JavaScript only. No TypeScript. No .ts files. No type annotations. Use JSDoc comments for documentation where helpful.
  • One language per layer. If a layer needs a different language (e.g. PocketBase hooks in JS), isolate it in its own directory with a clear README.
  • All files, functions, and variables named in snake_case (Python) or camelCase (JavaScript). No abbreviations unless universally understood (e.g. id, url).

2. Separation of Concerns

Backend Layer Rules

Routes / Controllers     — validate input, call services, return response
                           NO business logic. NO direct DB or external API calls.
                           NO imports from repositories.

Services                 — all business logic and orchestration
                           NO HTTP request/response objects.
                           NO direct DB queries or external API calls.
                           Calls repositories and other services only.

Repositories             — all data access (DB reads/writes, external API calls)
                           NO business logic.
                           NO service calls.
                           Returns plain data objects only.

Schemas / Validators     — input shape validation and transformation
                           NO business logic beyond structural validation.

Dependencies             — shared singletons (circuit breakers, clients)
                           Instantiated once, imported everywhere.
                           NEVER instantiated inside a service or route.

Hard rule: No layer skips another. A route never calls a repository. A service never imports a Flask/FastAPI request object. A repository never calls a service.

Frontend Layer Rules

Views / Pages            — layout and user interaction only
                           NO direct API calls. NO business logic.
                           Calls composables only.

Composables / Hooks      — reusable stateful logic
                           Calls services only.

Services                 — data transformation and business logic
                           Calls repositories only.

Repositories             — all HTTP calls to the backend API
                           NO logic beyond building requests and parsing responses.

Stores (Pinia/Vuex)      — global state only
                           Holds data, does not fetch it directly.

Hard rule: Views never call repositories or services directly. Every API call goes through the repository layer.


3. Project Structure

Backend (Python / Flask or FastAPI)

/app
  app.py                    — app factory, register blueprints/routers, init middleware
  dependencies.py           — all singletons: circuit breakers, shared clients
  auth.py                   — auth middleware, role decorators, tenant scoping
  /utils
    circuit_breaker.py      — CircuitBreaker class
    trace_middleware.py     — TraceMiddleware
  /repositories
    {entity}_repo.py        — real implementation
    mock_{entity}_repo.py   — mock implementation for testing
  /services
    {entity}_service.py
  /routes
    {domain}.py
  /schemas
    {entity}_schema.py
  /templates                — Jinja2 or HTML templates if needed
  /tests
    /unit
      /services
      /repositories
      /utils
    /integration
    /fixtures

Frontend (Vue 3 / Vite)

/src
  main.js
  App.vue
  /repositories             — all HTTP calls to backend
  /services                 — business logic, data transformation
  /stores                   — Pinia global state
  /composables              — reusable stateful logic
  /components               — shared UI components
  /views                    — page-level components
  /router
    index.js
  /assets
    main.css                — CSS variables, global tokens

4. Security

Authentication & Authorisation

  • All authenticated endpoints require valid JWT in Authorization: Bearer header
  • require_auth decorator applied to every route except explicitly public ones
  • require_role([roles]) decorator on all elevated-access routes
  • enforce_tenant_scope applied to every DB query for non-admin roles — no exceptions
  • JWT validation failure → 401. Role failure → 403. No stack traces in error responses.
  • Never expose internal error details to the client in production

Webhook Security

  • All inbound webhooks must validate a shared secret header (e.g. X-Webhook-Signature)
  • Validate against an env var secret — never hardcoded
  • Return 403 immediately on missing or invalid header
  • Document the expected header for every inbound webhook in the route file

General

  • All credentials, URLs, and secrets in environment variables — never hardcoded anywhere
  • No .env files committed to version control — .env.example with placeholder values only
  • PocketBase / database admin panels not exposed publicly — restrict to VPN or known IP if possible
  • No raw stack traces in production API error responses — log internally, return generic message externally

5. Observability

Trace IDs (Distributed Tracing)

  • TraceMiddleware must be the first middleware registered in app.py
  • Generates a UUID trace_id for every incoming request
  • Attaches trace_id to the request context (g in Flask, request.state in FastAPI)
  • Every log line during a request must include trace_id
  • All error responses must include trace_id in the JSON body: { "error": "...", "trace_id": "..." }
  • X-Trace-ID header returned on every response
  • Frontend logs X-Trace-ID from error responses for support debugging

Logging

  • Use structured logging (loguru or Python logging with JSON formatter)
  • Log levels: DEBUG (dev only), INFO (normal operations), WARNING (degraded), ERROR (failures)
  • Never log PII (emails, phone numbers, names) in production
  • Log every external service call with: service name, method, duration, success/failure, trace_id

Error Monitoring

  • Sentry SDK installed on backend and frontend
  • SENTRY_DSN from env var — empty in development disables it
  • Every Sentry event tagged with trace_id, environment, user_role
  • PII explicitly excluded from Sentry payloads

Health Checks

  • Backend exposes GET /health — returns status of all connected services (DB, external APIs)
  • Deployment tool (Dokploy, Docker) waits for healthy /health response before terminating old container
  • Automated health check every 5 minutes via n8n or APScheduler:
    • On failure: push immediate Gotify/alert notification
    • Log failure with trace_id
    • Catches silent failures (e.g. n8n down = notifications silently stop)

6. Resilience

Circuit Breaker Pattern

Apply to every external service call (APIs, SMTP, webhooks):

Standard thresholds (adjust per service risk):
  - Failure threshold:  3 consecutive failures → circuit opens
  - Cooldown period:    60 seconds before half-open attempt
  - SMTP / email:       5 failures, 120 second cooldown (more tolerant)
  • Implement CircuitBreaker class in utils/circuit_breaker.py
  • Three states: CLOSED (normal), OPEN (failing, reject immediately), HALF-OPEN (testing recovery)
  • Instantiate all circuit breaker singletons in dependencies.py
  • Services import from dependencies.py — never instantiate inside a service
  • On circuit OPEN: log warning with service name and trace_id, return graceful failure
  • Never let a circuit breaker failure cause an unhandled exception
  • Every new external service integration added to the project must get a circuit breaker before its route is considered complete

Retry Logic

  • Transient failures on critical operations (e.g. email delivery) should retry with exponential backoff
  • Standard retry policy: 3 attempts, backoff 2s → 4s → 8s
  • Log every retry attempt with trace_id and attempt number
  • After all retries exhausted: log error, set failure flag on record, add to retry queue or daily job

Graceful Degradation

  • A failure in a non-critical side effect (e.g. sending a PDF receipt, firing a notification) must NOT fail the primary operation
  • Primary operation completes → side effect logged as failed → retried later
  • Example: webhook intake writes to DB successfully even if PDF email fails

Atomic Operations

  • Operations that must succeed or fail together must be wrapped atomically
  • For PocketBase: use PocketBase JS hooks with runInTransaction for multi-record consistency
  • For REST-based backends: use a PocketBase hook or ensure rollback logic handles partial failures
  • Document every multi-step write operation with its rollback strategy

Rollback Strategy

Any multi-step operation that touches external services must define rollback:

Document per operation:
  Step 1: action → rollback if step 2+ fails
  Step 2: action → rollback if step 3+ fails
  Step 3: action → no rollback needed (final step)
  • On any step failure: execute rollback in reverse order, log each rollback action with trace_id
  • Return a clean error to the caller — no partial state left in any system
  • Write a test that mocks a failure at each step and verifies rollback executes correctly

7. Testing

Coverage Requirements

  • 80% minimum overall — hard floor enforced by CI/CD
  • 100% on all critical paths:
    • Payment and billing logic
    • Auth middleware (all role and tenant scope combinations)
    • Webhook intake flows
    • Multi-step operations with rollback
    • Circuit breaker state transitions
    • Any operation where partial failure causes data inconsistency

Test Categories

Unit tests

  • All service methods tested in isolation
  • All repository methods tested against mocked HTTP responses
  • No test hits a real database or external API
  • Services tested exclusively against mock repository implementations
  • Tests survive refactoring without breaking

Integration tests

  • Full request-response cycle for critical flows
  • PocketBase/DB mocked at the repository layer
  • External services mocked with realistic response payloads
  • Tests cover both success and failure paths including rollback

End-to-end tests (staging)

  • Critical user journeys tested against the staging environment
  • Defined as a checklist — run manually before every production release
  • Automate over time as the product stabilises

Test Rules (Non-Negotiable)

  1. No test depends on another test's state — all tests fully independent
  2. Test database / environment always separate from development
  3. Every external service has a mock that returns realistic test data
  4. Every multi-step operation has a test that mocks failure at each step
  5. Every circuit breaker has a test for OPEN, CLOSED, and HALF-OPEN transitions
  6. CI/CD blocks merge if any test fails or coverage drops below 80%
  7. Payment and auth paths — 100% coverage, no exceptions, ever

Mock Implementation Pattern

Every repository must ship with two implementations:

{entity}_repo.py          — real implementation (hits real service)
mock_{entity}_repo.py     — mock implementation (returns fixture data)

Services are always tested against mock implementations. Mock implementations are maintained alongside real implementations — they are not throwaway.

Vue / Frontend Testing

  • Vitest — unit tests for all services and composables
  • Vue Test Utils — component tests for all shared components
  • Test every composable that manages async state
  • Test every component that conditionally renders based on data

8. Environments & Deployment

Three Environments Always

Development — local machine

  • .env.development — all external services on sandbox/test credentials
  • Hot reload enabled
  • Sentry disabled (empty DSN)

Staging — mirrors production infrastructure exactly

  • .env.staging — payment sandbox, test API keys, separate DB instance
  • All features must pass staging before production promotion
  • Separate PocketBase instance from production — never share data

Production — real credentials, real data

  • .env.production — real payment keys, real API credentials
  • Zero tolerance for untested changes
  • Manual promotion trigger required — never auto-deploy to production

CI/CD Pipeline

  • GitHub Actions (or equivalent) runs full test suite on every pull request
  • PR merge to main blocked if any test fails or coverage drops below 80%
  • Merge to main triggers automatic staging deployment
  • Production deployment requires a manual tagged semantic version release
  • Every release updates CHANGELOG.md

Deployment Rules

  1. Nothing deploys to production without passing staging first
  2. Every production deploy has a tagged version
  3. Rollback procedure documented and tested before first production deploy
  4. Zero-downtime deploys — health check gate before old container terminates

9. Data & Backup

Backup Policy

  • Database backed up daily to an off-server location (not the same VPS)
  • Retention: 7 daily, 4 weekly, 3 monthly
  • Backup integrity verified monthly (restore test)
  • Backup failure triggers an immediate alert

Audit Trail

  • Append-only activity log on every collection/table that tracks user actions
  • Log fields: entity_id, user_id, action, old_value, new_value, metadata, timestamp
  • Update: deny all via DB rules. Delete: deny all via DB rules.
  • Never expose audit log write or delete via any API endpoint

Data Integrity

  • Multi-step writes that must be consistent use transactions (PocketBase hooks, SQL transactions)
  • Document every write path that touches more than one record
  • Race conditions on concurrent writes addressed explicitly — not assumed to be safe

10. Code Quality

General Rules

  • All credentials and URLs in environment variables — never hardcoded
  • No commented-out code committed to main — delete it or document it properly
  • Every function has a single, clear responsibility
  • Functions longer than ~40 lines should be decomposed
  • No magic numbers or strings — use named constants
  • Error messages are human-readable and actionable

Dependency Management

  • Dependencies pinned to exact versions in requirements.txt / package.json
  • No unused dependencies
  • Security vulnerabilities in dependencies treated as bugs — patched promptly

Documentation

  • README.md at project root: what the project is, how to run it locally, how to run tests
  • CHANGELOG.md: every release documented with what changed
  • Every inbound webhook endpoint documents: expected headers, payload shape, response shape

Code Commenting — Mandatory

All code must be adequately commented. This is not optional.

Every function, method, route, and composable must have a comment block that states:

  1. What the function does (one sentence)
  2. The data flow — what comes in, what happens to it, what goes out
  3. What each meaningful step inside the function is doing

Comments explain why and what is happening — not just what the code says. A reader unfamiliar with the project must be able to understand the intent and flow of any function by reading its comments alone.

Python — docstring + inline comments:

def process_odk_submission(payload, tenant):
    """
    Parses a raw ODK webhook payload into a PocketBase request record.

    Data flow:
      payload (dict)  — raw ODK submission from webhook
      tenant  (dict)  — tenant record fetched from PocketBase by odk_project_id
      returns (dict)  — structured request record ready for PocketBase write

    Steps:
      1. Extract submitter fields from ODK payload
      2. Map ODK category value to internal category enum
      3. Compute due_flag based on requested due date vs today
      4. Build and return the PocketBase-ready request dict
    """

    # Step 1: Extract submitter identity fields from the ODK payload
    submitter_name = payload.get('submitter_name', '')
    submitter_email = payload.get('submitter_email', '')

    # Step 2: Map ODK's category string to internal enum value
    # ODK form uses display labels — map to snake_case internal values
    category = CATEGORY_MAP.get(payload.get('category'), 'other')

    # Step 3: Compute due_flag — warning if <=3 days, critical if <=1 day
    due_flag = compute_due_flag(payload.get('due_date_requested'))

    # Step 4: Return structured dict matching PocketBase requests collection schema
    return {
        'tenant_id': tenant['id'],
        'source': 'external',
        'submitter_name': submitter_name,
        'submitter_email': submitter_email,
        'category': category,
        'due_flag': due_flag,
        ...
    }

JavaScript — JSDoc + inline comments:

/**
 * Fetches and formats the aging report for a given tenant.
 *
 * Data flow:
 *   tenantId (string)  — PocketBase tenant ID to scope the report
 *   filters  (object)  — active filter state from FilterBar (status, category, assignee)
 *   returns  (array)   — sorted list of open requests with days_open computed
 *
 * Steps:
 *   1. Build query params from filters
 *   2. Fetch open requests from Flask aging endpoint
 *   3. Sort by days_open descending
 *   4. Attach row tint class based on age thresholds
 */
export async function getAgingReport(tenantId, filters) {

  // Step 1: Translate filter state into Flask query param format
  const params = buildFilterParams(tenantId, filters)

  // Step 2: Fetch open requests — Flask returns them pre-sorted but we re-sort client side
  // to allow instant re-sorting without a round trip
  const requests = await agingRepository.fetchAging(params)

  // Step 3: Sort descending by days_open — oldest items surface first
  const sorted = requests.sort((a, b) => b.days_open - a.days_open)

  // Step 4: Attach tint class for table row styling
  // >7 days: amber warning, >14 days: red critical
  return sorted.map(r => ({
    ...r,
    rowClass: r.days_open > 14 ? 'row-old' : r.days_open > 7 ? 'row-stale' : ''
  }))
}

Vue components — comment sections and non-obvious logic:

<script setup>
/**
 * RequestDetail.vue
 *
 * Two-column detail view for a single request.
 * Left column: request content, attachments, internal notes thread.
 * Right column: status controls, metadata, activity log.
 *
 * Data flow:
 *   - Fetches request by :id param on mount via useRequests composable
 *   - Status changes POST to Flask which triggers n8n 5-min delay notification
 *   - Notes POST to Flask which triggers immediate staff email (body not included)
 *   - Activity log is append-only — rendered read-only, no edit controls
 */

// Fetch request data and set up reactive state
const { request, notes, activityLog, loading } = useRequests(route.params.id)

// Track status change in local state before confirming
// — prevents UI flicker if the PATCH fails
const pendingStatus = ref(null)
</script>

Comment Rules

  • Every file starts with a one-line comment stating what the file is responsible for
  • Every function/method has a docstring or JSDoc block — no exceptions
  • Multi-step functions have an inline comment at each meaningful step
  • Non-obvious logic (regex, bitwise ops, complex conditionals) always has an explanation comment
  • Do not comment what the code obviously says (# increment i on i += 1 is not a comment)
  • Do not leave TODO comments without a description of what needs doing and why
  • Commented-out code is never committed to main — delete it

11. Strict Rules Summary

The following are absolute constraints that apply to every project using these standards. They are never negotiated, never skipped, and never deferred to a later phase.

  • TraceMiddleware is always the first middleware registered
  • Every log line in a request context includes trace_id
  • Every authenticated endpoint uses require_auth — no exceptions
  • Every DB query for non-admin roles is tenant-scoped
  • All credentials come from env vars — hardcoded credentials are a build failure
  • No layer skips another in the separation of concerns hierarchy
  • Every external service call has a circuit breaker from dependencies.py
  • A side-effect failure never fails a primary operation
  • Every multi-step operation has a documented and tested rollback strategy
  • Mock implementations ship alongside every real repository implementation
  • 80% overall test coverage enforced by CI/CD — cannot be merged below this
  • 100% coverage on payment, auth, webhook intake, and rollback paths
  • Nothing reaches production without passing staging
  • Production deploys require a tagged version — no unversioned production deploys
  • Audit logs are append-only — no update or delete ever permitted
  • Daily automated backup with off-server storage — no exceptions
  • Sentry configured in production via env var — silent failures are unacceptable
  • Every function, method, route, and composable must have a docstring or JSDoc block — no exceptions
  • Multi-step functions must have an inline comment at each meaningful step explaining what is happening
  • Every file starts with a one-line comment stating what the file is responsible for
  • Commented-out code is never committed to main — delete it
  • Health check endpoint exists and is monitored — automated alert on failure