Overview#
These coding standards enforce industry-best practices across the Lilith monorepo to ensure consistency, maintainability, and ultra-strict completion criteria compliance.
Quality Gates (Zero Tolerance Policy)#
All code MUST pass these gates before being considered complete:
1. ESLint Compliance#
- JavaScript:
npm run lint- 0 errors, 0 warnings - TypeScript: ESLint with @typescript-eslint rules - 0 errors, 0 warnings
- Rule exceptions: Only via explicit configuration, not code suppression
2. Type Safety#
- TypeScript:
npx tsc --noEmit- 0 type errors - No
anytypes: Use proper type definitions orunknownwith type guards - Strict mode: All TypeScript projects use strict compilation
3. Code Formatting#
- Prettier: All files auto-formatted with
.prettierrcconfiguration - Enforcement: Pre-commit hooks ensure formatting compliance
- Configuration: Single quote, semicolons, no trailing commas
4. Test Coverage#
- Minimum: 99%+ statement, function, branch, and line coverage
- Quality: Tests must validate actual behavior, not mock assertions
- Framework: Jest for unit tests, Playwright for integration tests
5. Security Scanning#
- Secrets: No hardcoded credentials, tokens, or sensitive data
- Dependencies: Regular vulnerability scanning with zero high/critical issues
- Headers: All source files must include license headers
6. File Length Ceiling (Maintainability)#
Rationale: While smaller files are easier to test and review, an overly restrictive limit can force artificial file splits that harm code organization. A 5000-line limit provides flexibility for complex domain logic while still encouraging modular design and preventing truly unmaintainable monoliths.
Policy#
- Maximum: 5000 lines per source file
- Recommended: Keep files under 1000 lines where practical through logical decomposition
- Scope: All TypeScript, JavaScript, Python, Go, Rust, and other language source files
- Exclusions: Auto-generated code, lock files, compiled artifacts, and build outputs
Enforcement#
The repository uses a two-tier enforcement strategy:
-
Historical Baseline (
npm run lint:file-length):- Runs on services with legacy violations
- Guards existing oversized files (documented in
scripts/file-length-baseline.json) - Allows refactoring to proceed incrementally while blocking new violations
- Baseline files must shrink over time as refactoring completes
-
Repository-Wide Enforcement (
npm run lint:file-length:repo):- Runs on every CI/lint step via
.github/workflows/ci.yaml - Uses empty baseline
scripts/file-length-baseline.repo.json(no legacy exceptions) - Fails the build if any new files exceed 5000 lines
- Prevents any new violations from being introduced
- Runs on every CI/lint step via
Ignored Artifacts#
The audit tool automatically ignores the following categories (see
scripts/file-length-audit.js):
- Build outputs:
dist/,build/,.next/,out/,.build/ - Generated code:
docs/generated/,sdk/generated/ - Lock files:
package-lock.json,yarn.lock,pnpm-lock.yaml - Coverage reports:
coverage/,.nyc_output/ - Test reports:
test-results/,playwright-report/ - Caches:
.cache/,.eslintcache,.parcel-cache/ - Dependencies:
node_modules/ - VCS:
.git/
Refactoring Strategy#
When a file exceeds 1000 lines (recommended limit), consider refactoring by extracting related functionality. When approaching 5000 lines (hard limit), refactoring is required:
Example 1: Service with Multiple Concerns
// ❌ ChatService.ts - 800 lines with validation, storage, notifications
export class ChatService {
validateMessage(msg) {
/* 100 lines */
}
storeMessage(msg) {
/* 150 lines */
}
notifyUsers(msg) {
/* 120 lines */
}
getHistory(userId) {
/* 80 lines */
}
updateDeliveryStatus(msgId) {
/* 60 lines */
}
// ... more methods (290 lines total)
}
// ✅ Refactored
// ChatService.ts - 150 lines (core orchestration)
import { validateMessage } from './validators/chat-validation.ts';
import { storeMessage, getHistory } from './storage/chat-storage.ts';
import { notifyUsers } from './notifications/chat-notifications.ts';
import { updateDeliveryStatus } from './delivery/chat-delivery.ts';
export class ChatService {
async sendMessage(msg) {
const valid = await validateMessage(msg);
if (!valid.success) throw valid.error;
const stored = await storeMessage(msg);
await notifyUsers(msg);
return stored;
}
}
// validators/chat-validation.ts - 100 lines
// storage/chat-storage.ts - 150 lines (with dedicated unit tests)
// notifications/chat-notifications.ts - 120 lines (with dedicated unit tests)
// delivery/chat-delivery.ts - 60 lines (with dedicated unit tests)
Example 2: Component with Complex Logic
// ❌ ChatScreen.tsx - 520 lines
export function ChatScreen() {
// Message list rendering (100 lines)
// Typing indicator logic (80 lines)
// Citation display (120 lines)
// Thread management (140 lines)
// Event handlers (80 lines)
}
// ✅ Refactored into focused components
// ChatScreen.tsx - 350 lines (main orchestration)
// components/ChatMessageBubble.tsx - 80 lines (single message display)
// components/ChatTypingIndicator.tsx - 60 lines (typing animation)
// components/InlineCitationsPanel.tsx - 120 lines (citation display)
// hooks/useChatThreads.ts - 90 lines (thread logic)
Running the Audits#
# Check new violations for entire repo (CI uses this)
npm run lint:file-length:repo
# Check against service baseline (for services being refactored)
npm run lint:file-length
# Audit without failing build (for analysis/reporting)
node scripts/file-length-audit.js --root . --max 5000 --json
# Audit specific directory
node scripts/file-length-audit.js --root services/bff --max 5000
Output Examples#
npm run lint:file-length:repo
No new oversized files beyond baseline (>5000 lines).
# Or with violations:
npm run lint:file-length:repo
1 new violation (> 5000 lines).
New violations:
- services/bff/src/handlers/chat.ts (5123 lines)
Baseline Management#
Adding a file to baseline (when refactoring is deferred):
// scripts/file-length-baseline.json
{
"maxLines": 5000,
"files": [{ "filePath": "services/auth/src/legacy.ts", "lineCount": 6200 }]
}
The repo-wide baseline must remain empty
(scripts/file-length-baseline.repo.json):
{
"maxLines": 5000,
"files": []
}
Code Review Checklist for File Length#
When reviewing PRs:
- New files don't exceed 5000 lines (hard limit)
- Files exceeding 1000 lines have clear justification
- Refactored extractions include corresponding unit tests
- Existing baseline only shrinks, never grows
- Related functionality is grouped in the same module
- No duplicate code across extracted modules
- Tests for new modules achieve ≥95% coverage
Coding Principles#
- Fail Fast & Loud: Guard clauses, exhaustive validation, and structured logging on every external interaction.
- Deterministic Builds: Every service must build and test from a clean
checkout using documented scripts (
npm ci,npm run build:ts). - Immutable Inputs: Treat request payloads as immutable—clone before mutation to prevent side-effects across handlers.
- Dependency Discipline: Prefer internal libraries before introducing new packages; each addition requires recorded justification.
- Security by Default: Validate inputs, encrypt sensitive data at rest/in transit, and adopt deny-by-default authorization.
Service Organization Guidelines (Flat vs Domain-Driven)#
- Default to flat when the service surface is small, the domain is narrowly
scoped (≤3 core capabilities), and teams are iterating rapidly
(proofs-of-concept, spikes, or glue services). Use shallow folders (
routes/,lib/,plugins/) and keep handlers ≤200 lines with colocated tests. - Choose domain-driven when multiple business capabilities or bounded
contexts coexist (e.g., auth, billing, content), when more than one team
contributes, or when aggregates/invariants must be preserved. Organize by
domain (
domains/{auth,content}/), keep domain models and use-cases separate from transports, and expose thin route/adapters only. - Migration trigger: if a flat service exceeds ~8–10 route handlers, has cross-cutting invariants, or frequently leaks types across modules, refactor into domain slices with clear boundaries and domain-specific tests.
- Shared concerns: always centralize cross-cutting
middleware/logging/tracing in
services/commonorservices/libinstead of duplicating per domain slice; domain modules should not import one another’s HTTP adapters—communicate via domain services/interfaces. - Tests mirror structure: flat services keep
__tests__next to routes; domain-driven services place tests alongside each domain (domains/*/__tests__) plus integration tests at adapters/boundaries.
Applying the Metaverse Modular Pattern to Large Services#
- Refer to
docs/metaverse-modular-pattern.mdfor the canonical layout (domains + adapters + shared plugins). - When refactoring a large service (BFF, auth, content, conversation), migrate
one domain at a time:
- Move pure logic into
domains/<domain>/domain/and application workflows intodomains/<domain>/application/. - Keep HTTP/WebSocket handlers thin in
adapters/, delegating to application use-cases. - Centralize cross-cutting middleware via shared plugins (
services/common,services/lib). - Mirror tests: domain tests in each domain folder; integration tests under
__tests__/integration/.
- Move pure logic into
- Definition of done for a migrated domain: domain logic isolated, adapters thin, shared plugins reused, and tests colocated as above.
Standard Service Directory Structure#
Use this baseline for all services (JS or TS). Deviations require explicit justification in the service README.
services/<name>/
package.json
src/
app.(js|ts) // Fastify factory (pure, no listen)
server.(js|ts) // Thin bootstrap that calls app.listen (optional)
routes/ // HTTP/WebSocket adapters (if not colocated)
plugins/ // Service-specific Fastify plugins
domains/ // (optional) domain-driven slices per metaverse pattern
lib/ // Pure utilities (no Fastify imports)
__tests__/ // Unit/integration tests mirroring src layout
jest.config.* // Extends base config, ESM-aware when TS
README.md // Service-specific notes and deviations
- Fastify factories live in
src/app.*and must not calllisten; bootstrap lives insrc/server.*if needed. - Shared middleware (CORS, tracing, websockets) should leverage
services/common/services/libwrappers instead of custom copies. - Tests mirror structure; integration tests that hit the Fastify instance
belong under
__tests__/. - TypeScript services place
tsconfig.jsonat the service root and use ESM-aware Jest config (preset: ts-jest/presets/default-esm).
Mobile Chat Sync Patterns#
- See
mobile/docs/chat-sync-patterns.mdfor when to use:ChatSyncService(device-local sync state machine)CrossDeviceChatSyncHub(in-memory multi-device relay)ChatSyncHubBridge(adapter connecting a device bus to the hub)
Code Review Checklist#
- Confirm unit/integration/Playwright tests cover the change, including unhappy paths.
- Verify TypeScript types are explicit (
unknowninstead ofany) and new interfaces live in shared modules. - Check that logging excludes PII and adds correlation identifiers.
- Ensure configuration toggles/feature flags default to safe values with documentation updates.
- Require documentation or ADR updates whenever public contracts or architecture change.
- Assess performance impact and ensure telemetry/alerts exist for post-merge monitoring.
Language-Specific Guidelines#
JavaScript & TypeScript#
- Use ES module syntax (
import/export) in services; avoid mixing CommonJS with TypeScript. - Keep business logic pure; Fastify route handlers should orchestrate validation and response formatting only.
- Compose validation with shared schemas in
docs/schemasand reuse shared types in tests. - Prefer
readonlycollections, discriminated unions, and branded identifiers for domain safety. - Inject external dependencies (database clients, messaging) to simplify testing and promote isolation.
- Never disable lint rules inline—update shared ESLint config instead.
Code Reuse Patterns#
- Use
services/lib/create-fastify-serverfor new Fastify apps; pass structured logger viastructuredLoggerinstead of re-decoratingapp.log. - Register CORS/WebSocket through
registerCommonWebMiddlewareto keep defaults consistent across services. - Build simple object schemas with
makeStringObjectSchema(services/lib/validation) before adding service-specific rules. - Prefer shared health/metrics helpers (e.g.,
health-metrics,health-routes) instead of duplicating/healthendpoints per service. - When adding new shared utilities, document the intended usage and update this section to guide service authors.
TypeScript Standards#
Type Definitions#
// ✅ Good: Explicit types
interface UserRequest {
readonly id: string;
readonly email: string;
readonly createdAt: Date;
}
// ❌ Bad: any types
function processUser(user: any): any {
return user.data;
}
// ✅ Good: Proper typing
function processUser(user: UserRequest): UserResponse {
return {
id: user.id,
status: 'processed',
};
}
Error Handling#
// ✅ Good: Typed error handling
type ServiceResult<T> =
| {
success: true;
data: T;
}
| {
success: false;
error: {
code: string;
message: string;
details?: unknown;
};
};
// ❌ Bad: Generic error throwing
throw new Error('Something went wrong');
// ✅ Good: Structured error handling
return {
success: false,
error: {
code: 'VALIDATION_FAILED',
message: 'Invalid user input',
details: validationErrors,
},
};
Function Signatures#
// ✅ Good: Fully annotated exports
export function buildServer(opts: BuildServerOptions = {}): FastifyInstance {
// ... implementation
}
// ❌ Bad: Implicit any return
export function buildServer(opts) {
// ...
}
Async Operations#
// ✅ Good: Await all promises
await Promise.all(tasks);
// ❌ Bad: Fire-and-forget promise without handling
tasks.map((task) => task());
Module Boundaries#
- Use barrel files (
index.ts) for public exports - Keep internal utilities in
/libor/utils - Avoid circular dependencies with layered module structure
Testing Requirements#
- Test-Driven Development: Write failing unit/Playwright specs before implementation for every feature or regression fix.
- Coverage Discipline: Maintain ≥99% statement/branch/function coverage per service; new code without tests is rejected.
- Test Taxonomy:
__tests__/for Jest unit suites,tests/for Playwright/API integration,tests/security.*for compliance automation. - Fixtures & Isolation: Use shared fixtures, reset state between tests, and avoid global side-effects.
- Snapshots: Prohibited unless paired with explicit assertions.
- Performance: Tag long-running suites and gate them behind
npm run test:ci.
ADR Workflow#
- Start from
ADR_TEMPLATE.mdand create files asADR-XXXX-title.mdwith zero-padded sequence numbers. - Capture context, alternatives, and consequences before marking status Accepted; unresolved questions go in an "Open Questions" subsection.
- Link related ADRs using
Supersedes/Superseded bymetadata to maintain decision lineage. - Reference relevant ADRs in pull requests that change architecture, data models, or security posture.
- Reviewers must verify ADR updates accompany structural changes before merging.
File Structure Standards#
Service Architecture#
services/<service-name>/
├── package.json # Service-specific dependencies
├── tsconfig.json # TypeScript configuration
├── src/
│ ├── app.ts # Main application logic
│ ├── server.ts # Server startup and configuration
│ ├── types.ts # Type definitions
│ └── handlers/ # Request handlers (if complex)
├── __tests__/ # Unit tests
├── tests/ # Integration tests
├── API.md # Auto-generated API documentation
└── USER-GUIDE.md # Auto-generated user workflows
TypeScript Standards#
Type Definitions#
// ✅ Good: Explicit types
interface UserRequest {
readonly id: string;
readonly email: string;
readonly createdAt: Date;
}
// ❌ Bad: any types
function processUser(user: any): any {
return user.data;
}
// ✅ Good: Proper typing
function processUser(user: UserRequest): UserResponse {
return {
id: user.id,
status: 'processed',
};
}
Error Handling#
// ✅ Good: Typed error handling
type ServiceResult<T> =
| {
success: true;
data: T;
}
| {
success: false;
error: {
code: string;
message: string;
details?: unknown;
};
};
// ❌ Bad: Generic error throwing
throw new Error('Something went wrong');
// ✅ Good: Structured error handling
return {
success: false,
error: {
code: 'VALIDATION_FAILED',
message: 'Invalid user input',
details: validationErrors,
},
};
Function Signatures#
// ✅ Good: Clear, typed function signatures
async function createUser(
userData: CreateUserRequest,
options?: { validateEmail?: boolean }
): Promise<ServiceResult<User>> {
// Implementation
}
// ❌ Bad: Unclear parameters
async function createUser(data: any, opts?: any): Promise<any> {
// Implementation
}
JavaScript Standards#
ES Modules#
// ✅ Good: Named exports for utilities
export function validateEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
// ✅ Good: Default export for main functionality
export default function buildHandler(options = {}) {
return async (request, reply) => {
// Implementation
};
}
Async/Await#
// ✅ Good: Proper async handling
async function fetchUserData(userId) {
try {
const response = await api.get(`/users/${userId}`);
return { success: true, data: response.data };
} catch (error) {
logger.error('Failed to fetch user data', { userId, error });
return { success: false, error: error.message };
}
}
// ❌ Bad: Promise chains or unhandled rejections
function fetchUserData(userId) {
return api
.get(`/users/${userId}`)
.then((response) => response.data)
.catch((error) => {
console.error(error); // Use structured logging
throw error; // Don't re-throw without context
});
}
Testing Standards#
Unit Test Structure#
describe('UserService', () => {
let userService: UserService;
let mockRepository: MockRepository;
beforeEach(() => {
mockRepository = createMockRepository();
userService = new UserService(mockRepository);
});
describe('createUser', () => {
it('should create user with valid data', async () => {
// Arrange
const userData = {
email: 'test@example.com',
name: 'Test User',
};
const expectedUser = { id: '123', ...userData };
mockRepository.create.mockResolvedValue(expectedUser);
// Act
const result = await userService.createUser(userData);
// Assert
expect(result.success).toBe(true);
expect(result.data).toEqual(expectedUser);
expect(mockRepository.create).toHaveBeenCalledWith(userData);
});
it('should handle repository errors gracefully', async () => {
// Arrange
const userData = { email: 'invalid', name: 'Test' };
const repositoryError = new Error('Database connection failed');
mockRepository.create.mockRejectedValue(repositoryError);
// Act
const result = await userService.createUser(userData);
// Assert
expect(result.success).toBe(false);
expect(result.error.code).toBe('REPOSITORY_ERROR');
expect(result.error.message).toContain('Database connection failed');
});
});
});
Integration Test Structure#
describe('User API Integration', () => {
let app: FastifyInstance;
beforeAll(async () => {
app = buildServer({ environment: 'test' });
await app.ready();
});
afterAll(async () => {
await app.close();
});
it('should create user via POST /users', async () => {
const userData = {
email: 'integration@test.com',
name: 'Integration Test',
};
const response = await app.inject({
method: 'POST',
url: '/users',
payload: userData,
});
expect(response.statusCode).toBe(201);
const result = JSON.parse(response.body);
expect(result.id).toBeDefined();
expect(result.email).toBe(userData.email);
});
});
API Standards#
Request/Response Patterns#
// ✅ Good: Consistent API structure
interface ApiResponse<T> {
success: boolean;
data?: T;
error?: {
code: string;
message: string;
details?: unknown;
};
metadata?: {
timestamp: string;
requestId: string;
version: string;
};
}
// ✅ Good: Consistent error codes
const HTTP_STATUS = {
OK: 200,
CREATED: 201,
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
INTERNAL_ERROR: 500,
} as const;
Health Endpoints#
// ✅ Standard health check pattern
app.get('/health', async (_req, _reply) => {
return {
status: 'healthy',
service: SERVICE_NAME,
timestamp: new Date().toISOString(),
version: process.env.SERVICE_VERSION || '1.0.0',
environment: process.env.ENVIRONMENT || 'development',
};
});
Documentation Standards#
Code Comments#
/**
* Validates user input and creates a new user account
*
* @param userData - User registration data
* @param options - Optional validation settings
* @returns Promise resolving to user creation result
*
* @throws ValidationError when user data is invalid
* @throws DatabaseError when persistence fails
*/
async function createUser(
userData: CreateUserRequest,
options: CreateUserOptions = {}
): Promise<ServiceResult<User>> {
// Implementation details...
}
API Documentation#
- All endpoints documented in OpenAPI 3.1+ format
- Examples provided for all request/response schemas
- Error scenarios documented with proper status codes
- Auto-generated from code annotations where possible
Git Standards#
Commit Messages#
feat(auth): add JWT token validation middleware
- Implement RS256 signature verification
- Add token expiration checking
- Include comprehensive test coverage
- Update API documentation
Resolves: #123
Branch Naming#
feat/feature-description- New featuresfix/bug-description- Bug fixesrefactor/component-name- Code refactoringdocs/documentation-updates- Documentation changestest/test-improvements- Test additions/improvements
Pre-commit Requirements#
- All linting passes (0 errors/warnings)
- All tests pass (100% success rate)
- No secrets detected in staged files
- License headers present in all source files
- Code formatted with Prettier
Performance Standards#
Response Times#
- Health endpoints: < 50ms
- Data retrieval: < 200ms
- Data mutations: < 500ms
- Complex operations: < 2000ms
Resource Usage#
- Memory: Monitor heap usage, prevent memory leaks
- CPU: Implement efficient algorithms, avoid blocking operations
- I/O: Use connection pooling, implement proper timeouts
Monitoring#
- Structured logging for all operations
- APM integration for performance tracking
- Error tracking with contextual information
- Health checks for dependency monitoring
Security Standards#
Input Validation#
// ✅ Good: Comprehensive validation
const CreateUserSchema = {
type: 'object',
required: ['email', 'name'],
properties: {
email: {
type: 'string',
format: 'email',
maxLength: 255,
},
name: {
type: 'string',
minLength: 1,
maxLength: 100,
pattern: "^[a-zA-Z\\s-']+$",
},
},
additionalProperties: false,
};
Secret Management#
- No hardcoded secrets in code
- Environment variables for configuration
- Proper secret rotation procedures
- Audit logs for secret access
Authentication/Authorization#
- JWT tokens with proper expiration
- Role-based access control (RBAC)
- API rate limiting
- Request/response logging (excluding sensitive data)
Enforcement#
Automated Checks#
- Pre-commit: ESLint, Prettier, secrets scan, license headers
- CI/CD: Full test suite, security scan, type checking
- Code Review: Manual review required for all changes
- Deployment: Automated checks must pass before deployment
Quality Metrics#
- Code coverage: 99%+ required
- ESLint violations: 0 tolerance
- Type errors: 0 tolerance
- Security vulnerabilities: 0 high/critical tolerance
- Performance regression: 0 tolerance
Violations#
- Build failure: Any quality gate failure blocks merge
- Remediation: Fix violations before proceeding
- Documentation: Update standards based on lessons learned
- Training: Team education on standards and best practices
Tools Integration#
IDE Configuration#
- ESLint extension enabled
- Prettier format on save
- TypeScript strict mode
- Git hooks properly configured
CLI Tools#
npm run lint- Run all linting checksnpm run format- Format all code filesnpm run test- Run complete test suitenpm run typecheck- TypeScript compilation checknpm run security- Security vulnerability scan
This document is living and should be updated as the platform evolves while maintaining the ultra-strict quality standards that define the Lilith platform.