Skip to main content

Idiomark Backend Code Audit Report

Date: 2026-02-12 Auditor: Automated Code Audit Scope: Backend implementation in packages/core/ and packages/cli/


Executive Summary​

CategoryStatusNotes
Core PackageWell-structured, comprehensive18 source files, ~5,500 LOC
DocumentationPartialARCHITECTURE.md is good, but API reference is missing
TypeScript CoverageExcellentComprehensive type definitions
Undocumented FeaturesSignificant~40% of code lacks explicit docs
CLI CoverageCompleteAll 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​

FileLOCPurposeDocumented?
index.ts~105Public API exportsPartially
types.ts~235Core TypeScript interfacesYes
schema.ts?Zod validation schemaNo
validator.ts?Idiomark file validationNo
analyzer.ts~705Personality analysis LLM wrapperNo
generator.ts~495Response generation with personalityNo
reader.ts~275High-level Idiomark file consumerNo
loader.ts~167File I/O operationsNo
extractor.ts~570Platform data extraction orchestrationNo
personality-prompt.ts?System/response prompt buildersPartially
prompts.ts~269LLM analysis promptsNo
inference.ts~262HTTP inference serverPartially
adapters/base.ts~1033Base adapter class with rate limiting, caching, retryNo
adapters/index.ts?Adapter registryNo
adapters/testing/index.ts?Test utilitiesNo
adapters/rest.ts?REST API templateNo
adapters/registry.ts?Dynamic adapter loadingNo
types-v2.ts?V2 experimental typesPartially
all-types.ts?Type aggregationNo

2. Undocumented APIs and Features​

2.1 PersonalityAnalyzer (packages/core/src/analyzer.ts)​

Undocumented Features:

API/FeatureTypeDescription
AnalysisOptionsInterfaceConfiguration for LLM provider, model, chunking, caching
AnalysisResultInterfaceContains personality, confidence, metadata
LLMResponseInterfaceRaw LLM response with token usage
PersonalityAnalyzer.analyze()MethodMain analysis entry point
PersonalityAnalyzer.refine()MethodRefine existing analysis with new context
PersonalityAnalyzer.validate()MethodValidate analysis quality
PersonalityAnalyzer.clearCache()MethodClear analysis cache
analyzeText()FunctionConvenience function for direct text analysis
Chunking strategyFeatureAutomatic text chunking for large inputs
Mock LLM modeFeatureprovider: '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 tokens
  • Idiomark_CHUNK_SIZE - Override default chunk size

2.2 IdiomarkGenerator (packages/core/src/generator.ts)​

Undocumented Features:

API/FeatureTypeDescription
GenerationOptionsInterfaceFull configuration for generation
GenerationResultInterfaceContains content, model, tokens, timestamp
StreamChunkInterfaceStreaming response chunks
StreamCallbackTypeCallback type for streaming
IdiomarkGenerator.generate()MethodSingle response generation
IdiomarkGenerator.generateStream()MethodStreaming response generation
IdiomarkGenerator.addHistory()MethodAdd message to conversation history
IdiomarkGenerator.clearHistory()MethodClear conversation history
IdiomarkGenerator.updatePersonality()MethodUpdate personality after creation
generateResponse()FunctionConvenience function
createGenerator()FunctionConvenience 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/FeatureTypeDescription
ReaderOptionsInterfaceExtends GenerationOptions
IdiomarkReader.fromFile()Static methodLoad from file path
IdiomarkReader.fromIdiomarkFile()Static methodLoad from IdiomarkFile object
IdiomarkReader.fromPersonality()Static methodLoad from Personality object
IdiomarkReader.chat()MethodInteractive chat session
IdiomarkReader.getSystemPrompt()MethodGet current system prompt
IdiomarkReader.getMetadata()MethodGet Idiomark file metadata
IdiomarkReader.getPersonalitySummary()MethodGet personality summary
IdiomarkReader.updatePersonality()MethodUpdate personality
IdiomarkReader.updateOptions()MethodUpdate generation options
loadReader()FunctionConvenience function
createReader()FunctionConvenience function

Chat Options (Undocumented):

{
exitCommand?: string // Default: 'exit'
greeting?: string // Optional greeting message
}

2.4 IdiomarkExtractor (packages/core/src/extractor.ts)​

Undocumented Features:

API/FeatureTypeDescription
IdiomarkExtractor.extractFromContent()MethodExtract from pre-normalized content
IdiomarkExtractor.extractFromText()MethodExtract from text strings
IdiomarkExtractor.extract()MethodMain extraction with adapters
extractFromTextString()FunctionConvenience for single text
extractFromTextStrings()FunctionConvenience for multiple texts
extractFromPlatforms()FunctionPlatform extraction with auth
getSupportedPlatforms()FunctionList all platforms
isPlatformSupported()FunctionCheck if platform supported
getAdapterPackage()FunctionGet 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/FeatureTypeDescription
LoadOptionsInterfacevalidate, throwOnNotFound options
LoadResultInterfacefile, path, validated fields
loadIdiomarkFile()FunctionLoad with validation
loadIdiomarkById()FunctionLoad by ID from directory
listIdiomarkFiles()FunctionList all Idiomark files in directory
loadAllIdiomarkFiles()FunctionLoad all from directory
writeIdiomarkFile()FunctionWrite with formatting options
deleteIdiomarkFile()FunctionDelete 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/FeatureTypeDescription
InferenceServerOptionsInterfaceport, model, personality, generation
IdiomarkInferenceServer.start()MethodStart HTTP server
IdiomarkInferenceServer.stop()MethodStop server
Endpoints: /healthGETHealth check
Endpoints: /personalityGETGet loaded personality JSON
Endpoints: /system-promptGETGet system prompt text
Endpoints: /generatePOSTGenerate response (returns JSON)
Endpoints: /streamPOSTGenerate 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.

ComponentDescriptionKey Features
RateLimiterToken bucket rate limitingPer-endpoint limits, header-based updates, wait prediction
CacheManagerL1/L2 cacheLRU eviction, TTL expiration, persistent option
RetryHandlerExponential backoffJitter, retryable error detection, max retry limit
AuthManagerAuthentication handlingBearer, OAuth2, API key, Basic auth
ErrorHandlerError classificationAdapterError, RateLimitError, AuthError
MetricsCollectorPerformance trackingLatency (avg/median), counters
BaseAdapterAbstract base classCombines 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 limit
  • cacheHit - When cache hit occurs
  • retry - When a retry is attempted
  • fetchComplete - When fetch completes
  • reset - When adapter is reset
  • dispose - 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:

CommandOptionsDescription
adapter createnameCreate new adapter scaffold
adapter list-List all adapters
applyMultipleApply 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​

NeededPriorityContent
packages/core/API_REFERENCE.mdHIGHComplete API reference for all exported functions/classes
packages/core/ANALYZER.mdHIGHPersonalityAnalyzer usage guide
packages/core/GENERATOR.mdHIGHIdiomarkGenerator usage guide
packages/core/READER.mdHIGHIdiomarkReader usage guide
packages/core/LOADER.mdMEDIUMFile I/O operations guide
packages/core/INFERENCE_SERVER.mdHIGHInference server API docs
packages/core/ADAPTER_BASE.mdHIGHBaseAdapter implementation guide
packages/cli/COMMANDS.mdMEDIUMCLI command reference
packages/core/ENVIRONMENT.mdMEDIUMEnvironment variables reference
packages/core/ERROR_CODES.mdLOWError codes and handling
packages/core/STREAMING.mdMEDIUMSSE streaming implementation guide

3.2 Undocumented Environment Variables​

VariablePackageDefaultDescription
Idiomark_MAX_TOKENScore131072Max tokens per request
Idiomark_CHUNK_SIZEcore200000Chunk size for large text analysis
ANTHROPIC_API_KEYcore-Anthropic API key
OPENAI_API_KEYcore-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:

  • IdiomarkExtractor
  • PersonalityAnalyzer
  • IdiomarkGenerator
  • IdiomarkReader
  • IdiomarkInferenceServer
  • IdiomarkValidator
  • BaseAdapter
  • RateLimiter
  • CacheManager
  • RetryHandler
  • AuthManager
  • ErrorHandler
  • MetricsCollector

Types:

  • AnalysisOptions, AnalysisResult, LLMResponse
  • GenerationOptions, GenerationResult, StreamChunk, StreamCallback
  • LoadOptions, LoadResult
  • ReaderOptions
  • All adapter config and health types
  • PlatformAdapter, NormalizedContent, RawContent, FetchOptions

4. Inference Server API (Undocumented)​

4.1 Endpoints​

MethodEndpointRequestResponse
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​

ClassCodeStatusRetryable
AdapterErrorUNKNOWN-
RateLimitErrorRATE_LIMIT_EXCEEDED429Yes
AuthErrorAUTH_FAILED401No

5.2 Retryable Error Patterns​

/ECONNRESET
/ETIMEDOUT
/ENOTFOUND
/ECONNREFUSED
/429/
/50[0-4]/

6. Recommendations​

6.1 Documentation Priorities​

Immediate (P0):

  1. Create API_REFERENCE.md - Complete exported API documentation
  2. Create ADAPTER_BASE.md - BaseAdapter is complex and fully undocumented
  3. Create INFERENCE_SERVER.md - Server API is fully functional but undocumented
  4. 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​

  1. 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(...)
  2. Document example files

    • Add examples/ directory to packages/core
    • Cover common use cases
  3. 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​

MetricValue
Total Source Files18+
Total Lines of Code~5,500
Documented Public APIs~20%
Undocumented Public APIs~80%
Missing Documentation Files12
Undocumented Environment Variables4
Undocumented REST Endpoints5
Undocumented Classes12+

8. Positive Findings​

  1. Architecture Documentation - ARCHITECTURE.md is excellent and comprehensive
  2. Type Safety - Excellent TypeScript coverage throughout
  3. Code Organization - Clear separation of concerns, good file naming
  4. Export Structure - Clean, well-organized public API surface
  5. Error Handling - Sophisticated error handling in BaseAdapter
  6. Event System - Well-designed event emission throughout
  7. 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