Skip to main content

Architecture Decision Records (ADRs)

Repository: Idiomark Maintainer: Core Architecture Team Last Updated: 2026-02-11


What are ADRs?​

Architecture Decision Records (ADRs) document significant architectural decisions in a project. Each ADR captures:

  1. Context - The problem being solved
  2. Decision - What we decided to do
  3. Consequences - Results of the decision (positive and negative)
  4. Alternatives - What else we considered

Why ADR Matter: Future maintainers (including your future self) need to understand why things were built a certain way. ADRs prevent "archaeology" - digging through git history to understand intent.


Table of Contents​

ADRTitleStatusDate
001Monorepo with pnpm WorkspacesAccepted2025-01-15
002TypeScript Strict Mode for All PackagesAccepted2025-01-15
003Base Adapter Class with Built-in InfrastructureAccepted2025-01-20
004Token Bucket Rate LimitingAccepted2025-01-20
005Multi-Level Caching StrategyAccepted2025-01-22
006Zod for Runtime ValidationAccepted2025-01-25
007Chunks for Large Text AnalysisAccepted2025-02-01
008In-Memory Cache with TTLAccepted2025-02-01
009Adapter Registry PatternAccepted2025-02-05
010Idiomark File Format with Digital SignaturesAccepted2025-02-10
011Reproducible Builds✅ Accepted2026-02-17
012Forward Secrecy (Double Ratchet)✅ Accepted2026-02-17

ADR-001: Monorepo with pnpm Workspaces​

Status: Accepted Date: 2025-01-15 Authors: @idiomark-core-team Deciders: Core Team

Context​

The Idiomark project consists of multiple related packages:

  • Core extraction logic
  • Platform adapters (potentially 50+)
  • CLI tooling
  • Web interface
  • SDKs for multiple languages

Problem: How should we organize these packages?

Decision​

Use a pnpm monorepo with the following structure:

idiomark/
├── packages/
│ ├── core/ # Core extraction library
│ ├── cli/ # Command-line interface
│ ├── sdk/ # JavaScript/TypeScript SDK
│ ├── adapters/ # Individual adapter packages
│ │ ├── github/
│ │ ├── twitter/
│ │ └── ...
│ ├── inference/ # Inference integration
│ └── web/ # Next.js web app
├── pnpm-workspace.yaml
└── package.json

Key Configuration:

# pnpm-workspace.yaml
packages:
- 'packages/*'
- 'packages/adapters/*'

Consequences​

Positive​

  • Single source of truth: All code in one repository
  • Shared tooling: One ESLint config, one TypeScript config
  • Atomic commits: Change core + adapters in one PR
  • Easier onboarding: Clone one repo to get everything
  • Local development: Test adapters against local core
  • Efficient CI: Turbo can optimize builds

Negative​

  • Longer initial clone: Full repo needed even for adapter-only work
  • Coupled releases: Breaking changes require coordinated version bumps
  • CI complexity: Need to run tests for affected packages only

Alternatives Considered​

Multi-Repo (Each Package Separate)​

Pros:

  • Independent versioning
  • Faster clones for single package work
  • Clearer ownership boundaries

Cons:

  • Duplication of tooling (15+ package.json files, configs)
  • Cross-package changes require multiple PRs
  • Difficult local development (need to npm link)
  • Higher CI/CD overhead

Why not rejected: Actually used for separate projects (e.g., if we split out a completely independent tooling library), but too heavy for tightly-coupled packages.

Single Package​

Pros:

  • Simplest structure
  • One dependency to install

Cons:

  • Cannot install adapters individually
  • No tree-shaking benefit
  • All-or-nothing dependency

Rejected: Users should be able to install only the adapters they need.

Lerna / Nx​

Pros:

  • Mature monorepo tools
  • Rich feature set

Cons:

  • Additional dependency
  • Steeper learning curve
  • pnpm workspaces provide same functionality

Rejected: pnpm workspaces are native, simpler, and all we need.

  • ADR-012: Turbo for build orchestration
  • ADR-013: Changesets for versioning (not yet written)

References​


ADR-002: TypeScript Strict Mode for All Packages​

Status: Accepted Date: 2025-01-15 Authors: @idiomark-core-team

Context​

TypeScript offers multiple strictness levels. More strict means catching more bugs at compile time but potentially more verbose code.

Decision​

All packages MUST use strict TypeScript mode with additional strict options:

{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true
}
}

Consequences​

Positive​

  • Catches null/undefined bugs: noUncheckedIndexedAccess prevents array access on undefined
  • Better IDE support: More types mean better autocomplete
  • Self-documenting: Types serve as inline documentation
  • Refactoring confidence: Change with confidence knowing compiler will catch issues
  • Better error messages: More specific types lead to more helpful errors

Negative​

  • Initial learning curve: New contributors may find strict mode challenging
  • More verbose types: Sometimes need explicit type annotations
  • Longer compile times: Additional type checking adds overhead
  • More type tests: May need tests for type-level behavior

Alternatives Considered​

Loose TypeScript (Non-Strict)​

Pros:

  • Faster to write initially
  • Less fighting with compiler

Cons:

  • Runtime null/undefined errors common
  • Less reliable refactoring
  • False sense of security (you have types but they're weak)

Rejected: The safety gains are worth the initial friction.

JSDoc with No TS Build Step​

Pros:

  • No build step needed
  • Works with plain JS

Cons:

  • Limited type checking
  • Poor tooling support
  • No type-level programming

Rejected: We want full type safety, not just type hints.


ADR-003: Base Adapter Class with Built-in Infrastructure​

Status: Accepted Date: 2025-01-20 Authors: @idiomark-core-team

Context​

We expect to support 50+ platform adapters. Common concerns across all adapters:

  • Rate limiting
  • Caching
  • Retry logic
  • Authentication
  • Error handling
  • Metrics collection

Problem: How to avoid duplicating this logic 50+ times?

Decision​

Create a BaseAdapter abstract class that provides all common infrastructure:

export abstract class BaseAdapter {
protected rateLimiter: RateLimiter;
protected cacheManager: CacheManager;
protected retryHandler: RetryHandler;
protected authManager: AuthManager;
protected errorHandler: ErrorHandler;
protected metricsCollector: MetricsCollector;

// High-level extract method with all infrastructure built-in
async extract(options: FetchOptions): Promise<NormalizedContent[]> {
await this.validateAuth(options);
await this.rateLimiter.throttle();

const cached = await this.cacheManager.get(options);
if (cached) return cached;

const raw = await this.retryHandler.execute(() =>
this.fetchContent(options)
);

const normalized = this.normalize(raw);
await this.cacheManager.set(options, normalized);

return normalized;
}

// Abstract methods - platform-specific
protected abstract fetchContent(options: FetchOptions): Promise<RawContent[]>;
protected abstract normalize(raw: RawContent): NormalizedContent;
}

Adapter authors only implement 2 methods:

  • fetchContent() - Platform-specific data fetching
  • normalize() - Transform platform data to NormalizedContent

Consequences​

Positive​

  • Massive code reduction: ~5000 lines of infrastructure implemented once
  • Consistency: All adapters behave identically
  • Lower contribution barrier: New adapters take hours, not days
  • Easy upgrades: Update base class, all adapters inherit improvements
  • Testability: Infrastructure tested once, not 50 times

Negative​

  • Base class complexity: Base class is large (~2700 lines)
  • Learning curve: Need to understand base class architecture
  • Rigidity: Hard to customize behavior not supported by base class
  • God object risk: Base class could become too monolithic

Mitigation: Extensive documentation and examples for adapter authors.

Alternatives Considered​

Composition (Adapter Has RateLimiter, Not Extends Base)​

Pros:

  • More flexible (can swap components)
  • Smaller classes
  • Easier to test in isolation

Cons:

  • More boilerplate in each adapter
  • Inconsistent implementations (some may forget to use retry)
  • Harder to upgrade (changes require touching all adapters)

Rejected: Composition is more flexible but leads to inconsistent implementations. We value consistency over flexibility for adapters.

Mixins​

Pros:

  • Composable features
  • Can mix and match capabilities

Cons:

  • TypeScript mixin support is awkward
  • Harder to understand control flow
  • Name collision issues

Rejected: Mixins add complexity without clear benefits over base class approach.

Framework Code Generation​

Pros:

  • Can see all code in adapter repo
  • No inheritance hierarchy

Cons:

  • Generated code hard to customize
  • Upgrades require regeneration
  • Duplication in git history

Rejected: Prefer actual code reuse over generation.

References​


ADR-004: Token Bucket Rate Limiting​

Status: Accepted Date: 2025-01-20 Authors: @idiomark-core-team

Context​

Different platforms have different rate limits:

  • GitHub: 5000 requests/hour (authenticated)
  • Twitter: varies by tier (15/15min free, 300/3hr Pro)
  • Reddit: 600 requests/min

Problem: How to respect rate limits while maximizing throughput?

Decision​

Implement Token Bucket algorithm for rate limiting:

class RateLimiter {
#tokens: number;
#maxTokens: number;
#refillRate: number; // tokens per second
#lastRefill: number;

constructor(maxTokens: number, refillRate: number) {
this.#tokens = maxTokens;
this.#maxTokens = maxTokens;
this.#refillRate = refillRate;
this.#lastRefill = Date.now();
}

async throttle(): Promise<void> {
this.#refill();

if (this.#tokens >= 1) {
this.#tokens--;
return;
}

// Calculate wait time
const waitTime = (1 - this.#tokens) / this.#refillRate * 1000;
await sleep(waitTime);
this.#tokens = 0;
}

#refill(): void {
const now = Date.now();
const elapsed = (now - this.#lastRefill) / 1000;
const refillAmount = elapsed * this.#refillRate;

this.#tokens = Math.min(this.#maxTokens, this.#tokens + refillAmount);
this.#lastRefill = now;
}
}

Key Features:

  1. Per-endpoint limits: Different limits for different endpoints
  2. Dynamic adjustment: Read rate limit headers to adjust limits
  3. Wait prediction: Tell caller exactly how long to wait
  4. Burst allowance: Allow short bursts up to max tokens

Consequences​

Positive​

  • Fair allocation: All requests get fair access
  • Burst handling: Can handle short bursts without blocking
  • Predictable: Wait times are known in advance
  • Standard algorithm: Well-documented, battle-tested
  • No thundering herd: Spreads requests evenly

Negative​

  • Requires rate limit knowledge: Need to know platform's limits
  • Wastes capacity: Unused tokens are lost (not bankable indefinitely)
  • Clock dependency: Relies on system clock

Mitigation:

  • Auto-discover limits from headers
  • Conservative defaults for unknown platforms

Alternatives Considered​

Fixed Window (Reset at Hour Boundary)​

Pros:

  • Simple to implement
  • Easy to understand

Cons:

  • Spiky behavior: bursts at start of window, drought at end
  • Unfair: last request before reset wastes full window

Rejected: Token bucket provides smoother experience.

Sliding Window Log​

Pros:

  • More accurate rate limiting
  • No bursts

Cons:

  • Higher memory: must store all request timestamps
  • Higher CPU: need to prune old timestamps

Rejected: Token bucket is simpler and good enough for our use case.

Leaky Bucket​

Pros:

  • Smooths out request rate

Cons:

  • Less intuitive: queue-based rather than token-based
  • Less flexible: harder to configure burst allowance

Rejected: Token bucket is more intuitive for API rate limiting.


ADR-005: Multi-Level Caching Strategy​

Status: Accepted Date: 2025-01-22 Authors: @idiomark-core-team

Context​

Adapter fetch operations are expensive:

  • API calls have rate limits
  • Network round-trips are slow
  • Some platforms charge per request

Problem: How to minimize redundant API calls?

Decision​

Implement two-level caching (L1 + L2):

class CacheManager {
// L1: In-memory LRU cache (fastest)
#l1Cache: LRUCache<string, CachedData>;
// L2: Persistent cache (slower but survives restarts)
#l2Cache: RedisCache | FileCache;

async get(key: string): Promise<NormalizedContent[] | null> {
// Check L1 first
const l1Value = this.#l1Cache.get(key);
if (l1Value && !this.isExpired(l1Value)) {
return l1Value.data;
}

// Fall back to L2
if (this.#l2Cache) {
const l2Value = await this.#l2Cache.get(key);
if (l2Value && !this.isExpired(l2Value)) {
// Promote to L1
this.#l1Cache.set(key, l2Value);
return l2Value.data;
}
}

return null;
}

async set(key: string, value: NormalizedContent[], ttl: number): Promise<void> {
const cached = { data: value, expiresAt: Date.now() + ttl };
this.#l1Cache.set(key, cached);
if (this.#l2Cache) {
await this.#l2Cache.set(key, cached);
}
}
}

Cache Key Strategy: Deterministic hash of fetch options

function getCacheKey(options: FetchOptions): string {
return crypto
.createHash('sha256')
.update(JSON.stringify(options))
.digest('hex');
}

Default TTL: 1 hour (configurable per adapter)

Consequences​

Positive​

  • Dramatic speedup: Cache hits are instantaneous vs API call
  • Reduced rate limit pressure: Fewer actual API calls
  • Cost savings: Fewer API calls for paid platforms
  • Better UX: Faster responses for repeated queries
  • Graceful degradation: L1 works even if L2 unavailable

Negative​

  • Stale data risk: Cached data may be outdated
  • Memory usage: L1 cache uses memory
  • Complexity: Need to manage cache invalidation
  • Cold start: First request is still slow

Mitigation:

  • Configurable TTL
  • Manual cache invalidation API
  • Cache warming for common queries

Alternatives Considered​

Single-Level In-Memory Cache​

Pros:

  • Simpler implementation
  • Faster (no L2 lookup)

Cons:

  • Lost on restart
  • Doesn't share across processes

Rejected: L2 provides persistence and cross-process sharing worth the complexity.

Single-Level Persistent Cache​

Pros:

  • Simpler implementation
  • Data survives restarts

Cons:

  • Slower than in-memory
  • Higher latency

Rejected: L1 provides significant speedup for hot data.

No Caching​

Pros:

  • Always fresh data
  • Simpler

Cons:

  • Much slower
  • Wastes rate limits
  • Poor UX for repeated queries

Rejected: Caching benefits are too significant to ignore.

  • ADR-008: In-memory cache with TTL
  • ADR-003: Base adapter with caching built-in

ADR-006: Zod for Runtime Validation​

Status: Accepted Date: 2025-01-25 Authors: @idiomark-core-team

Context​

Idiomark files are external data that must be validated:

  • Files may be malformed
  • External APIs may return unexpected data
  • LLM responses may not match expected schema

Problem: How to validate data at runtime?

Decision​

Use Zod for all runtime validation:

import { z } from 'zod';

const VoiceSchema = z.object({
tone: z.object({
primary: z.string(),
secondary: z.string().optional(),
confidence: z.number().min(0).max(1)
}),
formality: z.number().min(0).max(1),
humor: z.number().min(0).max(1),
sarcasm: z.number().min(0).max(1),
enthusiasm: z.number().min(0).max(1),
directness: z.number().min(0).max(1)
});

const PersonalitySchema = z.object({
voice: VoiceSchema,
patterns: PatternsSchema,
domains: DomainsSchema,
values: ValuesSchema,
knowledge: KnowledgeSchema
});

// Type inference
export type Voice = z.infer<typeof VoiceSchema>;

// Validation
function validateIdiomarkFile(data: unknown): IdiomarkFile {
return IdiomarkFileSchema.parse(data);
}

Usage Throughout:

// Validate external API responses
const githubUser = GitHubUserSchema.parse(response.json());

// Validate LLM outputs
const analysis = PersonalityAnalysisSchema.parse(llmResponse);

// Validate Idiomark files
const idiomarkFile = IdiomarkFileSchema.parse(rawFile);

Consequences​

Positive​

  • Type safety: Runtime validation + TypeScript types from same source
  • Detailed errors: Zod provides clear error messages
  • Composable: Schemas can be combined
  • Inference: Derive TypeScript types from schemas
  • Zero dependencies: Zod is lightweight

Negative​

  • Schema duplication: Need to maintain both Zod schema and potentially TypeScript interfaces
  • Runtime overhead: Validation adds CPU time
  • Learning curve: Need to learn Zod API

Mitigation:

  • Use type inference to derive types from schemas
  • Cache validation results where performance matters

Alternatives Considered​

Manual Validation​

Pros:

  • No dependency
  • Full control

Cons:

  • Boilerplate-heavy
  • Error-prone
  • Inconsistent error messages

Rejected: Zod's benefits outweigh the dependency.

io-ts​

Pros:

  • Functional programming style
  • More mature

Cons:

  • More complex API
  • Worse error messages
  • Less popular

Rejected: Zod has better ergonomics and error messages.

class-validator​

Pros:

  • Decorator-based
  • Works with classes

Cons:

  • Requires class-transformer
  • Heavy on decorators
  • Not type-first

Rejected: Zod's schema-first approach is cleaner.

No Runtime Validation​

Pros:

  • Fastest
  • Simplest

Cons:

  • Runtime crashes on malformed data
  • Silent data corruption possible

Rejected: External data MUST be validated.


ADR-007: Chunking for Large Text Analysis​

Status: Accepted Date: 2025-02-01 Authors: @idiomark-core-team

Context​

LLMs have context window limits:

  • Claude 3: ~200k tokens (~750k characters)
  • GPT-4: ~128k tokens (~500k characters)
  • Large user histories may exceed limits

Problem: How to analyze content larger than LLM context window?

Decision​

Implement intelligent chunking at sentence boundaries:

const CHUNK_SIZE = 15000; // characters
const CHUNK_OVERLAP = 500; // characters

function chunkText(text: string): string[] {
const chunks: string[] = [];
let remaining = text;

while (remaining.length > CHUNK_SIZE) {
// Find break point at sentence boundary
let breakPoint = CHUNK_SIZE;

// Look for sentence ending within last 500 chars
const searchArea = remaining.substring(CHUNK_SIZE - 500, CHUNK_SIZE + 500);
const sentenceEnd = searchArea.match(/[.!?]+\s/g);

if (sentenceEnd) {
const lastEnd = sentenceEnd[sentenceEnd.length - 1].index!;
breakPoint = CHUNK_SIZE - 500 + lastEnd + 1;
}

chunks.push(remaining.substring(0, breakPoint).trim());
remaining = remaining.substring(breakPoint - CHUNK_OVERLAP);
}

if (remaining.length > 0) {
chunks.push(remaining.trim());
}

return chunks;
}

Analysis Strategy:

  1. Chunk text at sentence boundaries
  2. Analyze each chunk independently
  3. Merge results with confidence weighting
  4. Handle overlapping regions by averaging

Consequences​

Positive​

  • Handles arbitrary size: Can analyze any size text
  • Preserves context: Overlap prevents boundary artifacts
  • Parallelizable: Chunks can be analyzed in parallel
  • Quality: Sentence boundaries maintain meaning

Negative​

  • Complex merging: Need to combine results intelligently
  • Overlap duplication: Some content analyzed twice
  • Cost: More chunks = more API calls
  • Boundary effects: Chunks may lose cross-sentence context

Mitigation:

  • Configurable chunk size
  • Smart result merging with confidence weighting
  • Summary analysis after chunk analysis

Alternatives Considered​

Truncation​

Pros:

  • Simple
  • No merging needed

Cons:

  • Loses data
  • Incomplete analysis

Rejected: Better to analyze all data than to truncate.

Streaming Analysis​

Pros:

  • No chunking needed
  • Real-time results

Cons:

  • Not supported by most LLMs
  • Complex state management

Rejected: LLMs don't support streaming input yet.

Sampling​

Pros:

  • Faster than full analysis
  • Fewer API calls

Cons:

  • May miss important patterns
  • Incomplete picture

Rejected: For personality analysis, completeness matters more than speed.


ADR-008: In-Memory Cache with TTL​

Status: Accepted Date: 2025-02-01 Authors: @idiomark-core-team

Context​

LLM analysis is expensive:

  • API costs per request
  • Rate limits on LLM providers
  • Same content may be analyzed multiple times

Problem: How to cache LLM analysis results?

Decision​

Implement in-memory LRU cache with TTL for the PersonalityAnalyzer:

class PersonalityAnalyzer {
#cache = new Map<string, { result: PersonalityAnalysis; expiresAt: number }>();
#CACHE_TTL = 3600000; // 1 hour

async analyze(text: string, options?: AnalysisOptions): Promise<PersonalityAnalysis> {
const cacheKey = this.getCacheKey(text, options);

// Check cache
const cached = this.#cache.get(cacheKey);
if (cached && cached.expiresAt > Date.now()) {
return cached.result;
}

// Not in cache or expired, analyze
const result = await this.performAnalysis(text, options);

// Store in cache
this.#cache.set(cacheKey, {
result,
expiresAt: Date.now() + this.#CACHE_TTL
});

// Prune old entries
this.pruneCache();

return result;
}

private pruneCache(): void {
const now = Date.now();
for (const [key, value] of this.#cache.entries()) {
if (value.expiresAt < now) {
this.#cache.delete(key);
}
}
}
}

Cache Key Strategy: Hash of text + options

private getCacheKey(text: string, options?: AnalysisOptions): string {
return crypto.createHash('sha256')
.update(text)
.update(JSON.stringify(options ?? {}))
.digest('hex');
}

Consequences​

Positive​

  • Dramatic cost savings: Repeat queries are free
  • Faster responses: Cache hits are instant
  • Reduced rate limit pressure: Fewer LLM API calls
  • Simple implementation: No external dependencies

Negative​

  • Memory usage: Cache grows with usage
  • Stale results: Same text may produce different results over time
  • Process-bound: Doesn't share across processes
  • Lost on restart: Cache doesn't persist

Mitigation:

  • TTL ensures eventual freshness
  • Manual invalidation API
  • Configurable cache size limits

Alternatives Considered​

Redis Cache​

Pros:

  • Persists across restarts
  • Shares across processes
  • LRU eviction built-in

Cons:

  • External dependency
  • Network latency
  • Infrastructure cost

Rejected: Overkill for single-process CLI. Can add later if needed.

No Caching​

Pros:

  • Always fresh results
  • Simpler

Cons:

  • Expensive (LLM costs)
  • Slow
  • Wastes rate limits

Rejected: Cost and performance benefits are significant.

File-Based Cache​

Pros:

  • Persists across restarts
  • No external dependencies

Cons:

  • Slower than in-memory
  • I/O overhead
  • Concurrent access issues

Rejected: In-memory is sufficient for current use case.


ADR-009: Adapter Registry Pattern​

Status: Accepted Date: 2025-02-05 Authors: @idiomark-core-team

Context​

With 50+ planned adapters, we need:

  • Discovery mechanism
  • Health monitoring
  • Metrics aggregation
  • Dynamic loading

Problem: How to manage the adapter ecosystem?

Decision​

Implement a central AdapterRegistry class:

class AdapterRegistry {
#adapters = new Map<string, AdapterInfo>();
#instances = new Map<string, PlatformAdapter>();

register(info: AdapterInfo): void {
this.#adapters.set(info.name, info);
this.emit('registered', info);
}

async get(name: string, auth?: any): Promise<PlatformAdapter> {
// Check if already instantiated
if (this.#instances.has(name)) {
return this.#instances.get(name)!;
}

// Get adapter info
const info = this.#adapters.get(name);
if (!info) {
throw new AdapterNotFoundError(name);
}

// Dynamic import
const module = await import(info.package);
const AdapterClass = module.default || module[info.className];

// Create instance with auth
const instance = new AdapterClass({ auth });
this.#instances.set(name, instance);

return instance;
}

search(query: string): AdapterInfo[] {
const results: AdapterInfo[] = [];

for (const adapter of this.#adapters.values()) {
if (adapter.name.includes(query) ||
adapter.category.includes(query) ||
adapter.tags.includes(query)) {
results.push(adapter);
}
}

return results;
}

async healthCheck(name: string): Promise<AdapterHealth> {
const adapter = await this.get(name);
return adapter.healthCheck();
}
}

Registry JSON:

{
"adapters": [
{
"name": "github",
"version": "1.0.0",
"package": "@idiomark/adapter-github",
"className": "GitHubAdapter",
"category": "development",
"platform": "github.com",
"website": "https://github.com",
"docs": "https://docs.github.com",
"auth": ["bearer_token"],
"rateLimit": {
"authenticated": 5000,
"unauthenticated": 60,
"window": "hour"
},
"status": "stable",
"tags": ["git", "code", "development"]
}
]
}

Consequences​

Positive​

  • Central discovery: One place to find all adapters
  • Health monitoring: Can check adapter health
  • Dynamic loading: Load adapters on-demand
  • Metrics aggregation: Collect metrics across all adapters
  • Easy testing: Can mock registry in tests

Negative​

  • Central point of failure: Registry issues affect all adapters
  • Additional complexity: Need to maintain registry
  • Synchronization: Registry JSON must stay in sync with code

Mitigation:

  • Registry generation from code
  • CLI commands for registry management
  • Validation on load

Alternatives Considered​

Direct Import​

import { GitHubAdapter } from '@idiomark/adapter-github';
const adapter = new GitHubAdapter({ token });

Pros:

  • Simple
  • Direct dependency

Cons:

  • No discovery
  • No health monitoring
  • Hard to mock in tests

Rejected: Registry provides essential infrastructure.

Plugin System​

Pros:

  • Dynamic discovery
  • Self-registering

Cons:

  • More complex
  • Security concerns (arbitrary code)

Rejected: Overkill for adapter use case.


ADR-010: Idiomark File Format with Digital Signatures​

Status: Accepted Date: 2025-02-10 Authors: @idiomark-core-team

Context​

Idiomark files represent personality profiles. Users may:

  • Share Idiomark files publicly
  • Verify authenticity of profiles
  • Detect tampering

Problem: How to ensure Idiomark file integrity and authenticity?

Decision​

Add optional digital signature field to Idiomark file format:

interface IdiomarkFile {
idiomark: string; // "1.0.0"
id: string; // "idiomark_abc123..."
created: string; // ISO timestamp
updated: string; // ISO timestamp
metadata: IdiomarkMetadata;
personality: Personality;
signature?: string; // NEW: Digital signature
}

Signing Process:

import { createSign, createVerify } from 'crypto';

function signIdiomarkFile(idiomarkFile: IdiomarkFile, privateKey: string): string {
// Create canonical representation
const canonical = JSON.stringify({
idiomark: idiomarkFile.idiomark,
id: idiomarkFile.id,
created: idiomarkFile.created,
updated: idiomarkFile.updated,
metadata: idiomarkFile.metadata,
personality: idiomarkFile.personality
}, null, 0);

const sign = createSign('SHA256');
sign.update(canonical);
sign.end();

return sign.sign(privateKey, 'base64');
}

function verifyIdiomarkFile(idiomarkFile: IdiomarkFile, publicKey: string): boolean {
if (!idiomarkFile.signature) {
return false; // No signature
}

// Create same canonical representation
const canonical = JSON.stringify({
idiomark: idiomarkFile.idiomark,
id: idiomarkFile.id,
created: idiomarkFile.created,
updated: idiomarkFile.updated,
metadata: idiomarkFile.metadata,
personality: idiomarkFile.personality
}, null, 0);

const verify = createVerify('SHA256');
verify.update(canonical);
verify.end();

return verify.verify(publicKey, idiomarkFile.signature, 'base64');
}

Signature Field Optional: Idiomark files work without signatures, but signed files provide authenticity guarantees.

Consequences​

Positive​

  • Authenticity: Users can verify profile creator
  • Integrity: Detect any tampering with profile
  • Trust: Enables trusted profile sharing
  • Optional: Doesn't break existing workflow
  • Standard: Uses established crypto standards

Negative​

  • Key management: Users need to manage keys
  • Complexity: Additional crypto infrastructure
  • Learning curve: Need to understand signing
  • Recovery: Lost keys mean can't sign new files

Mitigation:

  • Optional feature (not required)
  • Tooling support (CLI signing commands)
  • Documentation on key management

Alternatives Considered​

Hash Only​

hash: string; // SHA256 of content

Pros:

  • Detects tampering
  • Simpler
  • No key management

Cons:

  • Doesn't verify authenticity
  • Anyone can recompute hash

Rejected: Signature provides authenticity guarantees.

No Integrity Mechanism​

Pros:

  • Simpler

Cons:

  • No integrity guarantee
  • Easy to tamper with profiles

Rejected: Integrity is important for trusted profiles.

Blockchain Verification​

Pros:

  • Immutable
  • Decentralized

Cons:

  • Overkill
  • Costly
  • Complex

Rejected: Traditional crypto is sufficient.


ADR-011: Reproducible Builds​

Status: ✅ Accepted Date: 2026-02-17 Authors: @idiomark-core-team

Context​

Idiomark is open source, but users cannot verify that published npm packages match the source code. This creates a trust gap for supply chain security.

Decision​

Implement reproducible builds with deterministic configuration and cryptographic verification:

  1. Deterministic tsup and TypeScript configuration
  2. Build manifest with SHA-256 hashes of all artifacts
  3. SLSA attestations via GitHub Actions
  4. CLI verification command (idiomark verify @idiomark/core)

Implementation​

  • tsup.config.base.ts - Deterministic build configuration
  • scripts/verify-build.mjs - Build verification and manifest generation
  • See ADR-011 full spec

Consequences​

Positive​

  • Supply chain security: Users can verify package integrity
  • Trust by default: Published packages match source code exactly
  • Audit trail: Every release has cryptographic proof

Negative​

  • No minification: Larger bundle sizes
  • Build complexity: Additional scripts required
  • Strict ordering: Builds must happen in consistent environment

Full Specification​

See docs/proposals/ADR-011-reproducible-builds.md


ADR-012: Forward Secrecy (Double Ratchet)​

Status: ✅ Accepted Date: 2026-02-17 Authors: @idiomark-core-team

Context​

Current symmetric encryption with static keys means key compromise exposes all historical and future data. For an identity protocol handling sensitive personality profiles, forward secrecy is essential.

Decision​

Implement the Double Ratchet Algorithm (Signal Protocol) for session-based encryption:

  1. X25519 Diffie-Hellman key exchange
  2. Per-message key derivation with automatic deletion
  3. Root key, chain key, message key hierarchy
  4. Support for out-of-order message delivery

Implementation​

  • packages/core/src/crypto/ratchet.ts - Double Ratchet implementation (16 tests ✅)
  • packages/sync/src/secure-sync.ts - SecureSyncSession wrapper (17 tests ✅)
  • @noble/curves dependency for X25519
  • See ADR-012 full spec

Consequences​

Positive​

  • Forward secrecy: Compromised keys don't expose historical messages
  • Post-compromise security: Security can recover after compromise
  • Standard algorithm: Based on proven Signal Protocol

Negative​

  • Complexity: Significantly more complex than symmetric encryption
  • State management: Must persist and protect ratchet state
  • Performance overhead: DH operations for each ratchet step

Full Specification​

See docs/proposals/ADR-012-forward-secrecy.md


ADR Template​

When creating a new ADR, use this template:

## ADR-XXX: [Title]

**Status**: Proposed | Accepted | Deprecated | Superseded
**Date**: YYYY-MM-DD
**Authors**: @username1, @username2
**Deciders**: Core Team | Community Vote

### Context

[Describe the problem we're trying to solve. What are the constraints? What has changed that makes this decision necessary now?]

### Decision

[What are we doing? Include technical details, code snippets, configuration, etc.]

### Consequences

#### Positive

- [Benefit 1]
- [Benefit 2]

#### Negative

- [Drawback 1]
- [Drawback 2]

**Mitigation**: [How we're addressing the drawbacks]

### Alternatives Considered

#### Alternative Name

**Pros**:
- Pro 1
- Pro 2

**Cons**:
- Con 1
- Con 2

**Rejected**: [Why we didn't choose this]

### Related Decisions

- [ADR-XXX](#adr-xxx): Related decision

### References

- [Link 1]
- [Link 2]

ADR Maintenance​

Status Changes​

ADRs may change status:

  • Proposed → Accepted: Decision approved
  • Accepted → Deprecated: Decision no longer recommended but still valid
  • Accepted → Superseded: Replaced by new ADR (reference new ADR)

Updating ADRs​

If an implementation differs from an ADR:

  1. Update the ADR to reflect reality
  2. Add a note explaining the deviation
  3. If deviation is significant, create a new ADR

Retiring ADRs​

ADRs are never deleted. When retired:

  1. Mark status as Deprecated or Superseded
  2. Add note about replacement
  3. Keep for historical reference

For questions about these decisions, please open an issue or discussion.