Idiomark - Engineering Standards
Last Updated: 2026-02-11 Maintainer: Core Engineering Team Status: Active
Table of Contents
- Engineering Philosophy
- Code Quality Standards
- Testing Requirements
- Code Review Process
- Documentation Requirements
- Performance Standards
- Security Standards
- Release Process
Engineering Philosophy
Core Principles
Our engineering culture is built on these foundational beliefs:
- Default to Open - Every internal tool should be built with public use in mind
- Move Fast with Stable Infra - Quick iteration on top of reliable foundations
- Strong Opinions, Loosely Held - We have strong defaults but welcome better ideas
- Shipping is a Feature - Unpolished code in production helps no one
- Measured Progress - If you can't measure it, you can't improve it
The "Why" Behind Our Standards
These standards exist to minimize cognitive load for engineers working across the codebase. When you open any file in this monorepo, you should be able to:
- Understand the architectural patterns within 5 minutes
- Know where tests live and how to run them
- Find documentation for public APIs
- Understand the error handling strategy
Code Quality Standards
Language & Runtime Baselines
| Component | Version Rationale |
|---|---|
| Node.js | 18+ LTS - Async cache, fetch native, stable ESM |
| TypeScript | 5.7+ - Latest type narrowing, decorator support |
| pnpm | 9+ - Efficient monorepo, strict peer deps |
| Vitest | 2+ - Native ESM, Jest-compatible, faster runs |
TypeScript Standards
Strict Mode Configuration
All packages MUST use strict TypeScript configuration:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"exactOptionalPropertyTypes": true
}
}
Rationale: noUncheckedIndexedAccess prevents undefined access bugs that account for ~15% of runtime errors in TypeScript codebases.
Type Imports
USE type-only imports for types:
// ✅ GOOD
import type { IdiomarkFile, Personality } from '@idiomark/core';
import { IdiomarkExtractor } from '@idiomark/core';
// ❌ BAD
import { IdiomarkFile, Personality, IdiomarkExtractor } from '@idiomark/core';
Why: Enables better tree-shaking and prevents accidental runtime usage of type-only imports.
Interface vs Type
| Use Interface | Use Type |
|---|---|
| Public APIs that can be extended | Union types, mapped types |
| Class contracts | Function signatures, tuples |
| Extensible object shapes | Complex type transformations |
// ✅ GOOD: Interface for public API
export interface PlatformAdapter {
fetchContent(options: FetchOptions): Promise<NormalizedContent[]>;
normalize(raw: RawContent): NormalizedContent;
}
// ✅ GOOD: Type for unions
export type AuthType = 'bearer_token' | 'oauth2' | 'api_key' | 'basic';
// ✅ GOOD: Type for mapped types
export type FetchOptionsByPlatform<T extends string> = {
[K in T]: FetchOptions;
};
Naming Conventions
| Category | Convention | Example |
|---|---|---|
| Interfaces | PascalCase, no prefix | PlatformAdapter, IdiomarkFile |
| Types | PascalCase, no prefix | FetchOptions, AuthConfig |
| Classes | PascalCase | IdiomarkExtractor, RateLimiter |
| Functions/Methods | camelCase | fetchContent(), normalize() |
| Constants | UPPER_SNAKE_CASE | MAX_RETRY_ATTEMPTS, DEFAULT_TIMEOUT |
| Private Members | camelCase with # | #cache, #authManager |
| File Names | kebab-case | platform-adapter.ts, rate-limiter.ts |
Exception: Generic type parameters use single-letter uppercase T, K, V or descriptive TConfig, TOptions.
Code Organization
File Structure Per Package
packages/{package-name}/
├── src/
│ ├── index.ts # Public API barrel export
│ ├── types.ts # Public type definitions
│ ├── {feature}.ts # Feature implementations
│ ├── {feature}.test.ts # Co-located tests
│ ├── utils/ # Internal utilities
│ │ └── {util}.ts
│ └── errors.ts # Package-specific errors
├── package.json
├── tsconfig.json
└── README.md
Barrel Exports
Public APIs MUST be exported through a barrel file (src/index.ts):
// src/index.ts
export { PlatformAdapter } from './platform-adapter.js';
export { RateLimiter } from './rate-limiter.js';
export type { FetchOptions, NormalizedContent } from './types.js';
export * from './errors.js';
Why: Provides a single import point for consumers and enables explicit public API surface.
Error Handling
Error Hierarchy
All packages MUST define and throw typed errors:
// ✅ GOOD: Typed error with code
export class AdapterError extends Error {
constructor(
message: string,
public code: string,
public retryable: boolean = false,
public cause?: Error
) {
super(message);
this.name = 'AdapterError';
}
}
// Usage
throw new AdapterError(
'Rate limit exceeded',
'RATE_LIMIT_EXCEEDED',
true,
originalError
);
Error Handling Pattern
// ✅ GOOD: Explicit error handling
async function fetchWithRetry(url: string): Promise<Response> {
try {
return await fetch(url);
} catch (error) {
if (error instanceof NetworkError) {
// Handle network-specific errors
return handleNetworkError(error);
}
// Re-throw with context
throw new AdapterError(
`Failed to fetch ${url}`,
'FETCH_FAILED',
true,
error as Error
);
}
}
Async Patterns
Always Use async/await
// ✅ GOOD
async function fetchContent(): Promise<Content[]> {
const response = await fetch(url);
const data = await response.json();
return data.items;
}
// ❌ AVOID: Promises chains
function fetchContent(): Promise<Content[]> {
return fetch(url)
.then(r => r.json())
.then(data => data.items);
}
Promise.all for Parallel Operations
// ✅ GOOD: Parallel fetching
async function fetchAllPlatforms(): Promise<Content[]> {
const [github, twitter, reddit] = await Promise.all([
fetchGitHub(),
fetchTwitter(),
fetchReddit()
]);
return [...github, ...twitter, ...reddit];
}
Promise.allSettled for Best-Effort
// ✅ GOOD: Best-effort fetching
async function fetchWithFallback(): Promise<Content[]> {
const results = await Promise.allSettled([
fetchPrimary(),
fetchFallback()
]);
return results
.filter((r): r is PromiseFulfilledResult<Content[]> => r.status === 'fulfilled')
.map(r => r.value);
}
Comments & Documentation
When to Comment
| Comment Type | When to Use |
|---|---|
| JSDoc | All public APIs |
| Inline | Complex algorithms, non-obvious logic |
| TODO | Temporary workarounds with issues |
| FIXME | Known bugs with issues |
| NOTE | Architectural decisions requiring context |
JSDoc Format
/**
* Fetches content from a platform with rate limiting and retry.
*
* @example
* ```ts
* const adapter = new GitHubAdapter({ token: 'ghp_xxx' });
* const content = await adapter.fetchContent({
* username: 'torvalds',
* limit: 100
* });
* ```
*
* @throws {AdapterError} When authentication fails
* @throws {RateLimitError} When rate limit is exceeded (retryable)
*
* @param options - Fetch options including username/ID and limits
* @returns Normalized content items ready for personality extraction
*/
async fetchContent(options: FetchOptions): Promise<NormalizedContent[]>
Testing Requirements
Coverage Targets
| Package Type | Coverage Target | Critical Paths |
|---|---|---|
| Core | 90%+ | 100% on extraction, validation |
| Adapters | 80%+ | 100% on normalize(), fetch() mocking |
| CLI | 70%+ | 100% on command parsing |
| Web | 60%+ | 100% on API routes |
Note: Coverage is a floor, not a ceiling. High coverage with poor tests is worse than lower coverage with excellent tests.
Test Organization
File Structure
packages/{package}/
├── src/
│ ├── {feature}.ts
│ └── {feature}.test.ts # Unit tests (co-located)
└── test/
├── fixtures/ # Test data
│ ├── github-responses.json
│ └── sample-idiomark.idiomark
├── mocks/ # Mock servers
│ └── github-mock.ts
└── integration/ # Integration tests
└── adapter-flow.test.ts
Test Categories
Unit Tests
Purpose: Test individual functions/classes in isolation
import { describe, it, expect, vi } from 'vitest';
import { RateLimiter } from './rate-limiter.js';
describe('RateLimiter', () => {
it('should throttle requests when tokens are depleted', async () => {
const limiter = new RateLimiter({ tokens: 1, refillRate: 1 });
// First request succeeds immediately
await limiter.throttle();
// Second request waits
const start = Date.now();
await limiter.throttle();
const elapsed = Date.now() - start;
expect(elapsed).toBeGreaterThanOrEqual(1000);
});
});
Integration Tests
Purpose: Test component interactions
import { describe, it, expect, beforeAll } from 'vitest';
import { GitHubAdapter } from './github-adapter.js';
import { createMockServer } from '../test/mocks/github-mock.js';
describe('GitHubAdapter Integration', () => {
const mockServer = createMockServer();
beforeAll(async () => {
await mockServer.start();
});
afterAll(async () => {
await mockServer.stop();
});
it('should fetch and normalize user content', async () => {
const adapter = new GitHubAdapter({
token: 'test-token',
baseUrl: mockServer.url
});
const content = await adapter.fetchContent({ username: 'test-user' });
expect(content).toHaveLength(5);
expect(content[0]).toMatchObject({
platform: 'github',
type: 'commit'
});
});
});
Test Fixtures
Fixture Management
// test/fixtures/github.ts
export const githubUserResponse = {
login: 'octocat',
id: 583231,
// ... full response shape
};
export const githubCommitsResponse = [
{
sha: 'abc123',
commit: { message: 'Initial commit' },
author: { login: 'octocat' }
}
];
// Test usage
import { githubUserResponse } from '../../test/fixtures/github.js';
vi.mocked(global.fetch).mockResolvedValueOnce({
ok: true,
json: async () => githubUserResponse
} as Response);
Mocking Strategy
HTTP Mocking
import { vi } from 'vitest';
import { createMockFetch } from './test/mock-fetch.js';
const mockFetch = createMockFetch({
'https://api.github.com/users/octocat': {
status: 200,
body: { login: 'octocat', id: 583231 }
},
'https://api.github.com/users/octocat/repos': {
status: 200,
body: [{ name: 'Hello-World', full_name: 'octocat/Hello-World' }]
}
});
global.fetch = mockFetch;
Adapter Mocking
import { MockAdapter } from './test/mocks/mock-adapter.js';
const mockAdapter = new MockAdapter({
platform: 'test-platform',
normalize: (raw) => ({
platform: 'test-platform',
type: 'post',
content: raw.body,
timestamp: new Date(raw.created_at).toISOString(),
metadata: {}
})
});
Test Namespacing
Use descriptive test names that describe behavior:
// ✅ GOOD: Descriptive
it('should retry on 5xx errors up to max attempts', () => {});
// ❌ BAD: Vague
it('retries', () => {});
// ✅ GOOD: Context + behavior
describe('when rate limit is exceeded', () => {
it('should wait for reset before retrying', () => {});
it('should emit rate limit event', () => {});
});
Code Review Process
Review Workflow
[Open PR] → [Auto-checks] → [Reviewer Assigned] → [Review] → [Address] → [Approve] → [Merge]
Auto-Checks (Required Before Review)
All PRs MUST pass:
- CI Pipeline - All tests pass on all OS targets
- Type Check -
pnpm -r type-checkwith zero errors - Lint -
pnpm -r lintwith zero warnings (or exceptions documented) - Build -
pnpm -r buildproduces valid artifacts - Coverage - Coverage does not decrease (exceptions require justification)
Review Criteria
Must-Have (Blocking)
- Correctness: Code does what it claims to do
- Type Safety: No
anytypes without documented rationale - Error Handling: Proper error handling for all failure paths
- Tests: Tests cover new functionality
- Documentation: Public APIs have JSDoc comments
Nice-to-Have (Non-Blocking)
- Performance: No obvious performance regressions
- Consistency: Follows existing patterns in the codebase
- Readability: Code is easy to understand
- Maintainability: Easy to modify in the future
Review Response SLA
| Requestor | Reviewer SLA | Follow-up SLA |
|---|---|---|
| Core Team | 24 hours | 8 hours after address |
| Community | 48 hours | 24 hours after address |
| Urgent (Hotfix) | 2 hours | 1 hour after address |
Review Format
## Review Summary
**Overall**: ✅ Approve | 🔄 Changes Requested | ❌ Not Ready
### Must Fix
- [ ] Item 1 blocking approval
### Suggestions
- [ ] Optional improvement 1
### Nitpicks
- [ ] Minor style point (feel free to ignore)
### Questions
- Question about implementation approach
Documentation Requirements
Documentation Types
| Type | Location | Update Frequency | Owner |
|---|---|---|---|
| Public API Docs | packages/*/README.md | Every API change | Package owner |
| Architecture Docs | docs/engineering/ | Per decision | Core team |
| Runbooks | docs/operations/ | Per incident | Ops team |
| Contributing Guide | contributing.md | Quarterly | Core team |
| Changelog | CHANGELOG.md | Per release | Release manager |
Documentation Standards
README Structure
Every package MUST have a README with:
# @idiomark/package-name
[One sentence description]
## Installation
\`\`\`bash
pnpm add @idiomark/package-name
\`\`\`
## Quick Start
\`\`\`typescript
import { Feature } from '@idiomark/package-name';
const instance = new Feature();
await instance.doSomething();
\`\`\`
## API Reference
### `Feature.doSomething()`
Description...
**Parameters**:
- `options: FeatureOptions` - Configuration options
**Returns**: `Promise<Result>`
**Throws**:
- `FeatureError` - When...
## Examples
See [examples/](./examples/) for more usage examples.
## Contributing
See [contributing.md](../../contributing.md) for contribution guidelines.
API Documentation Standards
All public APIs MUST document:
- Purpose - What the API does
- Parameters - With types and descriptions
- Returns - With type and description
- Throws - Error types and conditions
- Example - Usage code snippet
- Performance - Time/space complexity when relevant
Architecture Decision Records
ADRs MUST follow the template:
# ADR-{number}: {Title}
**Status**: Accepted | Proposed | Deprecated | Superseded
**Date**: YYYY-MM-DD
**Authors**: @username1, @username2
## Context
What is the problem we're trying to solve? What are the constraints?
## Decision
What are we doing? Include technical details.
## Consequences
What are the pros/cons? What does this enable? What constraints does this introduce?
## Alternatives Considered
What other options did we consider and why did we not choose them?
Performance Standards
Performance Targets
| Component | Target | Measurement | Alert Threshold |
|---|---|---|---|
| CLI Extract | < 30s for 1000 items | End-to-end time | > 60s |
| Adapter Fetch | < 5s per 100 items | Request duration | > 10s |
| Normalization | < 100ms per item | CPU time | > 200ms |
| Analysis | < 60s per 10k chars | LLM + processing | > 120s |
| Web Response | < 200ms p95 | API response time | > 500ms |
| Cold Start | < 3s | Server init | > 5s |
Performance Profiling
Before Optimizing
- Measure first: Use built-in profiling to confirm bottleneck
- Check impact: Will optimization affect >5% of users?
- Consider complexity: Is the optimization worth the maintenance cost?
Profiling Tools
# Node.js built-in profiler
node --prof script.js
node --prof-process isolate-0xnnnnnnnnnnnn.log > processed.txt
# CPU profiling
clinic doctor -- node-on-'your-command'
# Heap profiling
clinic heapprofiler -- on-the-fly -- node-on-'your-command'
# Flame graphs
0x -p $(pgrep node) --output flamegraph.svg
Performance Best Practices
Streaming for Large Data
// ✅ GOOD: Stream large responses
async function fetchLargeFile(url: string): Promise<NodeJS.ReadableStream> {
const response = await fetch(url);
return response.body;
}
// ❌ BAD: Load entire file into memory
async function fetchLargeFile(url: string): Promise<Buffer> {
const response = await fetch(url);
return Buffer.from(await response.arrayBuffer());
}
Batching for Small Requests
// ✅ GOOD: Batch small requests
async function fetchManyUsers(ids: string[]): Promise<User[]> {
const batchSize = 100;
const results = [];
for (let i = 0; i < ids.length; i += batchSize) {
const batch = ids.slice(i, i + batchSize);
const response = await fetch(`/users?ids=${batch.join(',')}`);
results.push(...await response.json());
}
return results;
}
Caching Strategy
// ✅ GOOD: Multi-level cache
class CacheManager {
#l1Cache = new Map<string, any>();
#l2Cache?: Redis;
async get(key: string): Promise<any | null> {
// L1: In-memory cache (fastest)
if (this.#l1Cache.has(key)) {
return this.#l1Cache.get(key);
}
// L2: Redis (fast)
if (this.#l2Cache) {
const value = await this.#l2Cache.get(key);
if (value) {
this.#l1Cache.set(key, value);
return value;
}
}
return null;
}
}
Security Standards
Security Principles
- Zero Trust - Verify all inputs, even from internal services
- Defense in Depth - Multiple layers of security controls
- Secure by Default - Secure configurations out of the box
- Least Privilege - Minimal access required for functionality
Token Handling
Never Log Tokens
// ✅ GOOD: Redact tokens from logs
function sanitizeForLogging(config: Config): string {
return JSON.stringify(config, (key, value) => {
if (key.toLowerCase().includes('token') ||
key.toLowerCase().includes('secret') ||
key.toLowerCase().includes('password')) {
return '[REDACTED]';
}
return value;
});
}
Token Storage
// ✅ GOOD: Use environment variables for secrets
const token = process.env.GITHUB_TOKEN;
// ❌ BAD: Never hardcode tokens
const token = 'ghp_1234567890abcdef';
// ❌ BAD: Never commit tokens to git
// Even in comments or examples
Input Validation
Validate All External Input
import { z } from 'zod';
const FetchOptionsSchema = z.object({
username: z.string().min(1).max(39).regex(/^[a-zA-Z0-9-]+$/),
limit: z.number().int().min(1).max(1000).default(100),
startDate: z.string().datetime().optional(),
endDate: z.string().datetime().optional()
});
// Always validate
const options = FetchOptionsSchema.parse(input);
Dependency Management
Dependency Auditing
# Run before every release
pnpm audit
# Fix vulnerabilities
pnpm audit --fix
# Check for outdated dependencies
pnpm outdated
# Review licenses
pnpm licenses list
Dependency Acceptance Criteria
| Dependency Type | Criteria |
|---|---|
| Production | Active maintenance, compatible license, security policy |
| Development | Well-established, minimal dependencies |
| Peer | Required version range documented |
Security Checklist
Before shipping, verify:
- No hardcoded secrets in code
- All user input is validated
- Dependencies are audited and up-to-date
- Authentication is properly implemented
- Rate limiting is configured
- Error messages don't leak sensitive information
- CORS is properly configured for web apps
- Dependencies allow Snyk/Dependabot PRs
Release Process
Versioning
We follow Semantic Versioning 2.0.0:
- MAJOR - Breaking changes
- MINOR - New features, backwards compatible
- PATCH - Bug fixes, backwards compatible
Release Checklist
Pre-Release
- All tests passing
- Coverage targets met
- Documentation updated
- CHANGELOG.md updated
- Version bumped in all packages
- Security audit passed
Release
- Git tag created:
v{version} - GitHub release published
- Packages published to npm
- Registry updated
- Announcements posted
Post-Release
- Monitor for regressions (24 hours)
- Track error rates
- Gather user feedback
- Document any issues
Hotfix Process
Hotfixes bypass normal review SLAs but still require:
- Tests added/updated
- At least one approval
- CHANGELOG updated
Rollback Plan
Every release must have a documented rollback procedure:
- npm deprecate - Mark broken version
- Revert commit - If possible, revert the breaking change
- Hotfix - Patch forward if revert not possible
- Communicate - Notify users of workaround
Appendix: Quick Reference
Common Commands
# Development
pnpm dev # Start all packages in watch mode
pnpm -r dev # Start all packages in watch mode
pnpm --filter @idiomark/core dev # Start specific package
# Building
pnpm -r build # Build all packages
pnpm -r --filter ./packages/* build # Build specific packages
# Testing
pnpm test # Run all tests
pnpm -r test # Run tests in all packages
pnpm test --coverage # Run tests with coverage
# Type Checking
pnpm -r type-check # Type check all packages
# Linting
pnpm -r lint # Lint all packages
pnpm -r lint --fix # Auto-fix lint issues
# Release
pnpm release # Interactive release workflow
pnpm release patch # Bump patch version
Editor Configuration
VS Code Settings (.vscode/settings.json)
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit",
"source.organizeImports": "explicit"
},
"files.associations": {
"*.idiomark": "json"
}
}
Recommended Extensions
- TypeScript - Microsoft
- ESLint - Microsoft
- Prettier - Prettier
- Vitest - Vitest
- Error Lens - Alexander
- GitLens - GitKraken
For questions about these standards, please open a discussion or contact the core team.