Idiomark Backend Code Audit Report
Date: 2026-02-12
Auditor: Automated Code Audit
Scope: Backend implementation in packages/core/ and packages/cli/
Executive Summary
| Category | Status | Notes |
|---|---|---|
| Core Package | Well-structured, comprehensive | 18 source files, ~5,500 LOC |
| Documentation | Partial | ARCHITECTURE.md is good, but API reference is missing |
| TypeScript Coverage | Excellent | Comprehensive type definitions |
| Undocumented Features | Significant | ~40% of code lacks explicit docs |
| CLI Coverage | Complete | All commands implemented |
Key Finding: The backend code is high-quality and well-architected, but there are significant gaps between what's implemented and what's documented.
1. Core Package: Source File Inventory
Implemented Source Files
| File | LOC | Purpose | Documented? |
|---|---|---|---|
| index.ts | ~105 | Public API exports | Partially |
| types.ts | ~235 | Core TypeScript interfaces | Yes |
| schema.ts | ? | Zod validation schema | No |
| validator.ts | ? | Idiomark file validation | No |
| analyzer.ts | ~705 | Personality analysis LLM wrapper | No |
| generator.ts | ~495 | Response generation with personality | No |
| reader.ts | ~275 | High-level Idiomark file consumer | No |
| loader.ts | ~167 | File I/O operations | No |
| extractor.ts | ~570 | Platform data extraction orchestration | No |
| personality-prompt.ts | ? | System/response prompt builders | Partially |
| prompts.ts | ~269 | LLM analysis prompts | No |
| inference.ts | ~262 | HTTP inference server | Partially |
| adapters/base.ts | ~1033 | Base adapter class with rate limiting, caching, retry | No |
| adapters/index.ts | ? | Adapter registry | No |
| adapters/testing/index.ts | ? | Test utilities | No |
| adapters/rest.ts | ? | REST API template | No |
| adapters/registry.ts | ? | Dynamic adapter loading | No |
| types-v2.ts | ? | V2 experimental types | Partially |
| all-types.ts | ? | Type aggregation | No |
2. Undocumented APIs and Features
2.1 PersonalityAnalyzer (packages/core/src/analyzer.ts)
Undocumented Features:
| API/Feature | Type | Description |
|---|---|---|
AnalysisOptions | Interface | Configuration for LLM provider, model, chunking, caching |
AnalysisResult | Interface | Contains personality, confidence, metadata |
LLMResponse | Interface | Raw LLM response with token usage |
PersonalityAnalyzer.analyze() | Method | Main analysis entry point |
PersonalityAnalyzer.refine() | Method | Refine existing analysis with new context |
PersonalityAnalyzer.validate() | Method | Validate analysis quality |
PersonalityAnalyzer.clearCache() | Method | Clear analysis cache |
analyzeText() | Function | Convenience function for direct text analysis |
| Chunking strategy | Feature | Automatic text chunking for large inputs |
| Mock LLM mode | Feature | provider: 'mock' for testing |
Configuration Options:
interface AnalysisOptions {
provider?: 'anthropic' | 'openai' | 'mock'
apiKey?: string
model?: string
maxTokens?: number
chunkSize?: number // Undocumented!
cache?: boolean // Undocumented!
endpoint?: string // For OpenAI-compatible APIs
}
Environment Variables (Undocumented):
Idiomark_MAX_TOKENS- Override default max tokensIdiomark_CHUNK_SIZE- Override default chunk size
2.2 IdiomarkGenerator (packages/core/src/generator.ts)
Undocumented Features:
| API/Feature | Type | Description |
|---|---|---|
GenerationOptions | Interface | Full configuration for generation |
GenerationResult | Interface | Contains content, model, tokens, timestamp |
StreamChunk | Interface | Streaming response chunks |
StreamCallback | Type | Callback type for streaming |
IdiomarkGenerator.generate() | Method | Single response generation |
IdiomarkGenerator.generateStream() | Method | Streaming response generation |
IdiomarkGenerator.addHistory() | Method | Add message to conversation history |
IdiomarkGenerator.clearHistory() | Method | Clear conversation history |
IdiomarkGenerator.updatePersonality() | Method | Update personality after creation |
generateResponse() | Function | Convenience function |
createGenerator() | Function | Convenience function |
Streaming Support:
- Full SSE (Server-Sent Events) streaming implementation
- Chunk types:
content,metadata,error,done - Both Anthropic and OpenAI supported
2.3 IdiomarkReader (packages/core/src/reader.ts)
Undocumented Features:
| API/Feature | Type | Description |
|---|---|---|
ReaderOptions | Interface | Extends GenerationOptions |
IdiomarkReader.fromFile() | Static method | Load from file path |
IdiomarkReader.fromIdiomarkFile() | Static method | Load from IdiomarkFile object |
IdiomarkReader.fromPersonality() | Static method | Load from Personality object |
IdiomarkReader.chat() | Method | Interactive chat session |
IdiomarkReader.getSystemPrompt() | Method | Get current system prompt |
IdiomarkReader.getMetadata() | Method | Get Idiomark file metadata |
IdiomarkReader.getPersonalitySummary() | Method | Get personality summary |
IdiomarkReader.updatePersonality() | Method | Update personality |
IdiomarkReader.updateOptions() | Method | Update generation options |
loadReader() | Function | Convenience function |
createReader() | Function | Convenience function |
Chat Options (Undocumented):
{
exitCommand?: string // Default: 'exit'
greeting?: string // Optional greeting message
}
2.4 IdiomarkExtractor (packages/core/src/extractor.ts)
Undocumented Features:
| API/Feature | Type | Description |
|---|---|---|
IdiomarkExtractor.extractFromContent() | Method | Extract from pre-normalized content |
IdiomarkExtractor.extractFromText() | Method | Extract from text strings |
IdiomarkExtractor.extract() | Method | Main extraction with adapters |
extractFromTextString() | Function | Convenience for single text |
extractFromTextStrings() | Function | Convenience for multiple texts |
extractFromPlatforms() | Function | Platform extraction with auth |
getSupportedPlatforms() | Function | List all platforms |
isPlatformSupported() | Function | Check if platform supported |
getAdapterPackage() | Function | Get adapter package name |
Mock Fallback (Undocumented):
- Returns mock personality when no content available
- Automatic fallback when all adapters fail
- 90-day default timeframe
2.5 Loader API (packages/core/src/loader.ts)
Undocumented Features:
| API/Feature | Type | Description |
|---|---|---|
LoadOptions | Interface | validate, throwOnNotFound options |
LoadResult | Interface | file, path, validated fields |
loadIdiomarkFile() | Function | Load with validation |
loadIdiomarkById() | Function | Load by ID from directory |
listIdiomarkFiles() | Function | List all Idiomark files in directory |
loadAllIdiomarkFiles() | Function | Load all from directory |
writeIdiomarkFile() | Function | Write with formatting options |
deleteIdiomarkFile() | Function | Delete with boolean result |
File Extension Patterns (Undocumented):
- Searches for:
{id}.idiomark.json,{id}.idiomark,{id}.json - Used by
loadIdiomarkById()
2.6 Inference Server (packages/core/src/inference.ts)
Undocumented Features:
| API/Feature | Type | Description |
|---|---|---|
InferenceServerOptions | Interface | port, model, personality, generation |
IdiomarkInferenceServer.start() | Method | Start HTTP server |
IdiomarkInferenceServer.stop() | Method | Stop server |
Endpoints: /health | GET | Health check |
Endpoints: /personality | GET | Get loaded personality JSON |
Endpoints: /system-prompt | GET | Get system prompt text |
Endpoints: /generate | POST | Generate response (returns JSON) |
Endpoints: /stream | POST | Generate response (SSE streaming) |
Server Request/Response (Undocumented):
// POST /generate or /stream
{
message: string // Required
history?: Array<{ // Optional conversation history
role: 'user' | 'assistant' | 'system'
content: string
}>
}
// Response
{
response: string
metadata: {
model: string
provider: string
tokens: { input: number; output: number }
timestamp: string
personality: {
id: string
tone: string
toneConfidence: number
}
}
}
2.7 Base Adapter (packages/core/src/adapters/base.ts)
Undocumented Features:
This is a major gap - ~1,000 lines of sophisticated functionality with no dedicated documentation.
| Component | Description | Key Features |
|---|---|---|
RateLimiter | Token bucket rate limiting | Per-endpoint limits, header-based updates, wait prediction |
CacheManager | L1/L2 cache | LRU eviction, TTL expiration, persistent option |
RetryHandler | Exponential backoff | Jitter, retryable error detection, max retry limit |
AuthManager | Authentication handling | Bearer, OAuth2, API key, Basic auth |
ErrorHandler | Error classification | AdapterError, RateLimitError, AuthError |
MetricsCollector | Performance tracking | Latency (avg/median), counters |
BaseAdapter | Abstract base class | Combines all components |
Configuration Interfaces (All Undocumented):
interface RateLimiterConfig {
maxRequests: number
windowDuration: number
perEndpoint?: boolean
}
interface CacheConfig {
enabled: boolean
ttl: number // milliseconds
maxSize?: number
persistent?: boolean
persistentPath?: string
}
interface RetryConfig {
maxRetries: number
baseDelay: number
maxDelay: number
}
interface AuthConfig {
type: 'none' | 'bearer_token' | 'oauth2' | 'api_key' | 'basic'
credentials?: Record<string, string>
tokenProvider?: () => Promise<string>
}
Events Emitted (Undocumented):
rateLimitWait- When waiting for rate limitcacheHit- When cache hit occursretry- When a retry is attemptedfetchComplete- When fetch completesreset- When adapter is resetdispose- When adapter is disposed
Health Check Response (Undocumented):
interface AdapterHealth {
healthy: boolean
latency?: number
rateLimit?: {
tokensRemaining: number
maxTokens: number
resetAt: Date
waitTime: number
}
cache?: {
hits: number
misses: number
size: number
hitRate: number
}
retry?: {
totalRetries: number
successfulRetries: number
failedRetries: number
}
error?: string
}
Metrics Response (Undocumented):
interface AdapterMetrics {
requests: number
cacheHits: number
cacheMisses: number
retries: number
errors: number
avgLatency: number
}
2.8 CLI Commands (packages/cli/src/)
Undocumented Commands:
| Command | Options | Description |
|---|---|---|
adapter create | name | Create new adapter scaffold |
adapter list | - | List all adapters |
apply | Multiple | Apply Idiomark to external systems |
projection-adapter | - | Manage projection adapters |
Apply Command Options (Undocumented):
-m, --mcp-server <name> Start MCP server
--mcp-transport <stdio|http> MCP transport method
--mcp-port <number> Port for HTTP transport
-u, --ucp-merchant <id> Generate UCP profile
--ucp-business-name <name> UCP business name
-p, --http-port <number> Start HTTP server
--provider <anthropic|openai|auto> LLM provider
--llm-model <model> AI model to use
3. Documentation Gaps
3.1 Missing Documentation Files
| Needed | Priority | Content |
|---|---|---|
packages/core/API_REFERENCE.md | HIGH | Complete API reference for all exported functions/classes |
packages/core/ANALYZER.md | HIGH | PersonalityAnalyzer usage guide |
packages/core/GENERATOR.md | HIGH | IdiomarkGenerator usage guide |
packages/core/READER.md | HIGH | IdiomarkReader usage guide |
packages/core/LOADER.md | MEDIUM | File I/O operations guide |
packages/core/INFERENCE_SERVER.md | HIGH | Inference server API docs |
packages/core/ADAPTER_BASE.md | HIGH | BaseAdapter implementation guide |
packages/cli/COMMANDS.md | MEDIUM | CLI command reference |
packages/core/ENVIRONMENT.md | MEDIUM | Environment variables reference |
packages/core/ERROR_CODES.md | LOW | Error codes and handling |
packages/core/STREAMING.md | MEDIUM | SSE streaming implementation guide |
3.2 Undocumented Environment Variables
| Variable | Package | Default | Description |
|---|---|---|---|
Idiomark_MAX_TOKENS | core | 131072 | Max tokens per request |
Idiomark_CHUNK_SIZE | core | 200000 | Chunk size for large text analysis |
ANTHROPIC_API_KEY | core | - | Anthropic API key |
OPENAI_API_KEY | core | - | OpenAI API key |
3.3 Undocumented Type Exports
From packages/core/src/index.ts, the following are exported but not documented:
Functions:
extractFromTextString()extractFromTextStrings()extractFromPlatforms()getSupportedPlatforms()isPlatformSupported()getAdapterPackage()createTextSamples()(via analyzer)analyzeText()(via analyzer)createGenerator()generateResponse()loadReader()createReader()
Classes:
IdiomarkExtractorPersonalityAnalyzerIdiomarkGeneratorIdiomarkReaderIdiomarkInferenceServerIdiomarkValidatorBaseAdapterRateLimiterCacheManagerRetryHandlerAuthManagerErrorHandlerMetricsCollector
Types:
AnalysisOptions,AnalysisResult,LLMResponseGenerationOptions,GenerationResult,StreamChunk,StreamCallbackLoadOptions,LoadResultReaderOptions- All adapter config and health types
PlatformAdapter,NormalizedContent,RawContent,FetchOptions
4. Inference Server API (Undocumented)
4.1 Endpoints
| Method | Endpoint | Request | Response |
|---|---|---|---|
| GET | /health | - | Health status |
| GET | /personality | - | Full Idiomark file |
| GET | /system-prompt | - | System prompt text |
| POST | /generate | {message, history?} | {response, metadata} |
| POST | /stream | {message, history?} | SSE stream |
4.2 CORS Headers
Server sends:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type
5. Error Handling (Undocumented)
5.1 Error Classes
| Class | Code | Status | Retryable |
|---|---|---|---|
AdapterError | UNKNOWN | - | |
RateLimitError | RATE_LIMIT_EXCEEDED | 429 | Yes |
AuthError | AUTH_FAILED | 401 | No |
5.2 Retryable Error Patterns
/ECONNRESET
/ETIMEDOUT
/ENOTFOUND
/ECONNREFUSED
/429/
/50[0-4]/
6. Recommendations
6.1 Documentation Priorities
Immediate (P0):
- Create
API_REFERENCE.md- Complete exported API documentation - Create
ADAPTER_BASE.md- BaseAdapter is complex and fully undocumented - Create
INFERENCE_SERVER.md- Server API is fully functional but undocumented - Create
ANALYZER.md- LLM integration patterns
High (P1):
5. Create GENERATOR.md - Response generation patterns
6. Create READER.md - Main consumer API
7. Document environment variables in README
8. Add JSDoc comments to all public APIs
Medium (P2):
9. Create LOADER.md - File operations
10. Create STREAMING.md - SSE implementation guide
11. Document CLI apply and adapter subcommands
12. Create error handling guide
6.2 Code Quality Improvements
-
Add JSDoc to all public exports
/**
* Extract personality from text content
* @param text - Text content to analyze
* @param options - Analysis configuration
* @returns Promise<AnalysisResult>
*/
export async function analyzeText(...) -
Document example files
- Add examples/ directory to packages/core
- Cover common use cases
-
Type improvements
- Consider stricter typing for optional fields
- Add branded types for error handling
6.3 Documentation Structure
packages/core/
├── API_REFERENCE.md # Complete API (NEW)
├── ANALYZER.md # PersonalityAnalyzer guide (NEW)
├── GENERATOR.md # IdiomarkGenerator guide (NEW)
├── READER.md # IdiomarkReader guide (NEW)
├── LOADER.md # File operations (NEW)
├── INFERENCE_SERVER.md # Server API (NEW)
├── ADAPTER_BASE.md # Adapter implementation (NEW)
├── ENVIRONMENT.md # Environment variables (NEW)
├── STREAMING.md # SSE guide (NEW)
└── examples/
├── basic-usage.ts # Simple examples (NEW)
├── platform-extraction.ts # Adapter usage (NEW)
├── streaming-response.ts # SSE example (NEW)
└── custom-adapter.ts # Adapter dev (NEW)
7. Summary Metrics
| Metric | Value |
|---|---|
| Total Source Files | 18+ |
| Total Lines of Code | ~5,500 |
| Documented Public APIs | ~20% |
| Undocumented Public APIs | ~80% |
| Missing Documentation Files | 12 |
| Undocumented Environment Variables | 4 |
| Undocumented REST Endpoints | 5 |
| Undocumented Classes | 12+ |
8. Positive Findings
- Architecture Documentation - ARCHITECTURE.md is excellent and comprehensive
- Type Safety - Excellent TypeScript coverage throughout
- Code Organization - Clear separation of concerns, good file naming
- Export Structure - Clean, well-organized public API surface
- Error Handling - Sophisticated error handling in BaseAdapter
- Event System - Well-designed event emission throughout
- CLI UX - Good help text and command structure
Conclusion
The Idiomark backend is well-architected and production-ready, but suffers from significant documentation gaps. The code quality is high, but developers must read source code to understand most functionality.
Key Takeaway: Implement 12 priority documentation files to bring docs in line with code quality.
Report generated by automated code audit For questions, see ARCHITECTURE.md