Implementing
165 documents
Accessibility
Accessibility from day one
All components MUST integrate with platform accessibility APIs from initial implementation:
Dynamic Type
Layouts MUST NOT break at larger text sizes. Use Dynamic Type throughout — avoid fixed font sizes. Custom fonts must ...
Font Scaling
Layouts MUST NOT break at 2x font size. Check `Configuration.fontScale` and test with large font settings enabled.
Code Quality
Architecture
Use MVVM with [CommunityToolkit.Mvvm](https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/) — source-gener...
Completeness: finish the work, don't defer by default
Deliver the full agreed scope. Don't silently mark work out of scope, declare done prematurely, or invoke YAGNI to skip required work.
Dependency Injection
Constructor injection via `Microsoft.Extensions.DependencyInjection`. Use interface types for dependencies, not concr...
File paths
Use `pathlib.Path`, not `os.path`. All path manipulation should go through `pathlib`.
Hilt dependency injection for Android
Use Hilt with KSP and constructor injection for Android DI; scope bindings to the correct Hilt component and reserve @Singleton for app-scoped state.
Linting before the first PR
All projects MUST have linting configured and passing before the first pull request.
Naming
- `PascalCase` for types, methods, properties, public fields, constants, namespaces
No external dependencies in core libraries
`roadmap_lib` uses the standard library only. Do not add PyYAML, requests, or other third-party packages to core libr...
Nullable Reference Types
Enable `<Nullable>enable</Nullable>` in all projects. Treat warnings as design signals — `string` means non-null, `st...
Scope discipline
Only modify what was requested. State the goal before starting. Note but do not fix adjacent issues.
Shell scripts
Shell script `main()` functions must only call other functions — no inline logic. Keep scripts composable and testable.
Small, atomic commits
One logical change per commit. A change may touch multiple files if they are part of the same concept. Commits should...
Type hints
Type hints are welcome but not required. Maintain Python 3.9 compatibility — use `from __future__ import annotations`...
TypeScript strictness configuration
Set strict: true on every new TypeScript project and adopt the stricter index/module flags incrementally.
Use roadmap_lib
Use functions from `roadmap_lib` for all roadmap operations (reading state, parsing frontmatter, finding steps, etc.)...
Value objects over primitive obsession
Wrap domain primitives that carry invariants in small immutable value objects so validation lives in one place and invalid instances cannot be constructed.
Verification harnesses as agent guardrails
Give every agent a runnable pass/fail check it can run on itself, and enforce correctness through deterministic gates rather than prompt text.
Writing code for the AI reader
Favor explicit, greppable, locally-readable code so AI agents can find and modify behavior on the first pass — without sacrificing human readability.
YAML frontmatter
Parse YAML frontmatter with the built-in frontmatter parser in `roadmap_lib`. Do not add a PyYAML dependency. The par...
Concurrency
Adopt Swift 6 strict concurrency incrementally
Migrate to Swift 6 data-race safety module by module, making every type that crosses an isolation boundary Sendable.
Immutability
Mutable shared state is the root cause of most concurrency bugs. Default to immutable values; introduce mutability on...
Kotlin Flow and StateFlow: lifecycle-aware state exposure
Expose UI state as StateFlow via stateIn and collect it lifecycle-aware, injecting dispatchers for testability.
No blocking the main thread
All lengthy work must run on background threads/tasks using platform async primitives:
Data
Access Pattern Analysis
Rules for analyzing query access patterns to drive schema and index decisions, covering read-heavy vs write-heavy tradeoffs, designing for WHERE/JOIN/ORDER BY, identifying missing indexes, and sync-specific batch sizing and transaction patterns.
Advanced database indexing
Match the Postgres index type to the access pattern, build on live tables with CONCURRENTLY, and validate with EXPLAIN ANALYZE.
Clock Systems for Sync
How to choose the right clock system for distributed sync: physical clocks, Lamport timestamps, vector clocks, Hybrid Logical Clocks, and server-assigned monotonic versions.
Conflict Resolution
How to choose and implement a conflict resolution strategy for sync: LWW, server-wins, field-level merge, CRDTs, Operational Transformation, and manual conflict queues.
Connection pooling for server and serverless backends
Front Postgres with a transaction-mode pooler for serverless or many-instance backends, and never depend on session-scoped state.
Constraints and validation
CHECK constraints for SQLite: evaluation rules, enum-like constraints, boolean enforcement, range and pattern validation, NULL truthiness, and limitations.
Data retention and deletion
Define a retention schedule per data category and automate deletion or anonymization that cascades to every derived store.
Data types and type affinity
SQLite type affinity rules, the STRING gotcha, STRICT tables, and type mapping between SQLite and PostgreSQL for cross-database compatibility.
Database
Use SQLite with WAL mode for concurrent read access. No ORM — use direct SQL via the `sqlite3` standard library module.
Database backup and recovery
Prescriptive rules for SQLite backup methods, corruption prevention, integrity checking, recovery procedures, VACUUM strategy, and database size management.
Database naming conventions
Snake_case naming rules for tables, columns, primary keys, foreign keys, indexes, constraints, and triggers — including reserved word avoidance.
Deterministic IDs
Always use the roadmap file's own UUID from its YAML frontmatter. Never generate random UUIDs. IDs must be determinis...
Foreign keys and referential integrity
Enabling and declaring foreign keys in SQLite, ON DELETE/UPDATE actions, deferred constraints, indexing FK columns, and common pitfalls.
Indexing
Rules for creating effective indexes in SQLite and PostgreSQL, covering B-tree fundamentals, composite ordering, covering indexes, partial and expression indexes, sync metadata indexes, and when not to index.
JSON columns and generated columns
JSON storage and extraction in SQLite, json_each for array iteration, generated columns for indexing JSON fields, and when JSON is a schema design smell.
Normalization and denormalization
Start normalized (3NF), denormalize only measured hotspots. SQLite-specific tradeoffs and sync-safe denormalization guidance.
Offline-First Architecture
Design rules for offline-first apps: WAL as the foundation, operation queues, optimistic UI updates, rollback on rejection, offline schema migrations, data expiry, and connectivity-aware sync scheduling.
Primary key strategies
Choosing between INTEGER PRIMARY KEY, AUTOINCREMENT, UUID, and WITHOUT ROWID — including sync compatibility and cross-database PK design.
Query Optimization
Rules for writing efficient SQLite and PostgreSQL queries, including query planner behavior, anti-patterns that cause full table scans, JSON query performance, subquery elimination, and CTE vs subquery tradeoffs.
Relationship patterns
One-to-many, many-to-many, polymorphic FKs, self-referential tables, and tree hierarchy patterns with tradeoffs and SQLite-specific guidance.
Room persistence on Android
Use Room with KSP, Flow-returning observable reads, suspend writes, and @Transaction-wrapped multi-step operations on Android.
Schema evolution and migrations
Migration strategies for SQLite: PRAGMA user_version, ALTER TABLE limitations, the 12-step recreate procedure, and sync-compatible migration rules.
SQLite Sync Tooling
Comparison and selection guide for SQLite sync tools: Session Extension, cr-sqlite, Litestream, ElectricSQL, PowerSync, Turso/libSQL, and sqlite-sync — with a decision matrix and selection criteria.
Sync Engine Design
How to design a client-side sync engine: layered architecture, entity-agnostic Syncable interface, the six-step sync cycle, scheduling strategies, snapshot rebuilding, and error handling with circuit breakers.
Sync Protocol
Rules for designing the sync protocol between client and server: push/pull direction, full vs incremental sync, change tracking, batching, idempotency, the outbox pattern, and retry with backoff.
Sync Schema Design
Schema design rules for databases that sync across devices: UUID primary keys, timestamp columns, soft deletes, dirty tracking, version columns, and sync metadata tables.
Table partitioning and time-series data
Partition large tables only when a measured size or retention need justifies the operational cost, and apply time-series patterns deliberately.
Transaction isolation and serialization-failure retry
Choose an isolation level per transaction and retry serialization failures with bounded, idempotent backoff.
Transactions and Concurrency
Rules for transaction management and concurrency in SQLite, covering WAL mode, journal mode selection, BEGIN IMMEDIATE vs DEFERRED, connection strategies, busy_timeout, PRAGMA tuning, and WAL benefits for sync workloads.
Zero-downtime migrations: expand and contract
Migrate a live database with expand-and-contract: every step backward-compatible with the running app, indexes built concurrently.
Feature Management
A/B testing
Features that may need experimentation SHOULD support variant assignment via an `ExperimentProvider` interface (`vari...
Debug mode
Apps MUST include a debug-only configuration panel (not in release builds):
Feature flags
All features MUST be gated behind feature flags from initial implementation. Define a `FeatureFlagProvider` interface...
Infrastructure
Containerization
Build small, secure container images with multi-stage builds, pinned slim bases, non-root users, cache-ordered layers, and no baked-in secrets.
Kubernetes configuration and secrets
Externalize Kubernetes config via ConfigMaps and treat Secrets as unencrypted base64 — encrypt at rest, tighten RBAC, and prefer external secret managers.
Kubernetes workloads
Run Kubernetes workloads with explicit resource requests/limits, health probes, hardened pod security, and safe rollout strategies.
Twelve-factor configuration
Read config that varies between deploys from the environment and promote one immutable build artifact unchanged across every environment.
Internationalization
Networking
AI Cost Management
AI API calls cost $0.01-$0.10+ each. Systems MUST treat AI calls as a managed resource with budgets, caching, and fallback strategies.
API Design
Use REST with consistent conventions. Follow the platform API guidelines (Microsoft, Google,
Be strict and maintain: Postel reconsidered (RFC 9413)
Parse protocol and API inputs strictly, reject violations loudly, and actively co-evolve spec and implementation instead of tolerating drift.
Caching
Use HTTP caching headers. The server controls cache policy; the client honors it.
Error Responses
Use [RFC 9457 Problem Details](https://www.rfc-editor.org/rfc/rfc9457) format with
HTTP conditional requests and optimistic concurrency
Use ETags with If-None-Match for efficient reads and If-Match for optimistic concurrency on writes to prevent lost updates.
Idempotency keys for write APIs
Accept a client-supplied Idempotency-Key on write endpoints so retries are safe, and reject key reuse with different parameters.
MCP server design
Design MCP servers by choosing the right primitive and giving each tool a precise name, output schema, and annotations.
Offline and Connectivity
For apps that must work offline, design for local-first with background sync.
Pagination
Prefer **cursor pagination** for most APIs — stable under concurrent mutations, consistent
Rate Limiting
Respect server rate limits. Handle 429 responses gracefully.
Real-Time Communication
Choose the simplest technique that meets your needs.
Retry and Resilience
Not every failure is permanent. Retry transient failures with exponential backoff and jitter.
Timeouts
Always set both connection and read timeouts. Never use infinite timeouts.
Web services
Use Flask for web services. The dashboard service runs on Flask with a REST API and SSE/polling for live updates.
Observability
AI Provider Observability
Every call to an AI provider API MUST be logged with structured metadata for cost attribution, debugging, and performance monitoring.
Analytics
All significant user actions MUST be instrumented via an `AnalyticsProvider` interface (`track(event, properties)`). ...
Continuous profiling
Adopt always-on, low-overhead production profiling correlated with traces only when measured perf/cost debugging justifies the pipeline.
Distributed tracing and context propagation
Propagate W3C trace context across every service hop and async boundary, and correlate logs/metrics/traces via a shared trace_id.
Instrumented logging
Every component and flow must be instrumented with structured logging using the platform's best-in-class framework:
Metrics instrumentation: RED and USE
Instrument services with RED metrics and resources with USE so signals correlate and feed SLIs/SLOs.
Service-level objectives and error budgets
Define user-centric SLIs, set SLOs, derive an error budget, and alert on multi-window burn rate rather than resource thresholds.
Platform Integration
App Intents
Expose key app actions and data as App Intents so Siri, Shortcuts, Spotlight, widgets, and the system can invoke them.
Background tasks
Apps that sync data, process uploads, or maintain state SHOULD use platform background execution APIs rather than relying on foreground presence.
Deep linking
All significant feature points and views MUST be deep linkable using the platform's native URL/deep link mechanism:
Handoff and continuity
Apps available on multiple devices SHOULD support continuity features so users can start work on one device and resume on another.
Notifications
Apps SHOULD use the platform notification system for timely, actionable alerts that respect user preferences.
Scriptable and automatable
Components and flows SHOULD be scriptable where the platform supports it:
Search integration
App content SHOULD be discoverable through the platform's system search, enabling users to find content without opening the app.
Share and inter-app data flow
Apps SHOULD participate in the platform's share and inter-app data exchange mechanisms to integrate with other apps and workflows.
Use AppKit and UIKit, not SwiftUI
Use AppKit (macOS) and UIKit (iOS) for all UI. Use SwiftUI only where Apple requires it.
Widgets and glanceable surfaces
Apps with time-sensitive or frequently checked data SHOULD provide widgets and glanceable surfaces on platforms that support them.
Security
Agent guardrails
Wrap agents in deterministic input/output guardrails, least-privilege tool access, human confirmation for irreversible actions, and a kill switch.
Authentication
Use OAuth 2.0 / OpenID Connect with PKCE for all public clients. The Implicit flow is
Authorization
**Server-side authorization is the only real authorization.** Client-side checks (hiding
Consent management
Capture granular, versioned, withdrawable consent in an auditable log and gate all non-essential processing on it.
Content Security Policy
Prevent XSS and injection with a strict CSP. Web apps only.
CORS
Cross-Origin Resource Sharing — get it right or don't enable it.
Data subject rights (DSAR)
Architect every personal-data store to be enumerable, exportable, and deletable by subject id so DSARs are satisfied within the legal SLA.
Dependency Security
Your dependencies are your attack surface. Manage them actively.
Input Validation
**Never trust client input.** Client-side validation is a UX feature, not a security control.
LLM and agentic application security
Treat all model output as untrusted, defend against direct and indirect prompt injection, and constrain tool agency.
MCP server security
Harden MCP servers against tool poisoning, rug-pulls, token passthrough, confused-deputy, session hijacking, and SSRF.
MCP tool input validation
Treat every MCP tool argument as untrusted model-supplied input: schema-validate, authorize per call, and bound resource access.
Passkeys and WebAuthn
Implement phishing-resistant passwordless auth with passkeys/WebAuthn, prefer them over passwords and SMS-OTP, and plan recovery.
PII handling and classification
Classify PII at the schema level, minimize collection, encrypt at rest and in transit, and never write it to logs.
Privacy and security by default
Collect only what is needed. Prefer on-device processing.
Secure Storage
Tokens, credentials, and any sensitive data MUST use platform secure storage. Never store secrets in plaintext config...
Security Headers Checklist
Every web application should set these response headers:
Sender-constrained access tokens
Bind access tokens to the client with DPoP or mTLS so a stolen token cannot be replayed by another party.
Sensitive Data
Minimize what you collect, encrypt what you keep, never log what you shouldn't.
Token Handling
Short-lived (5-15 min). Include only necessary claims — no PII in JWTs
Transport Security
**TLS 1.2 minimum**, prefer TLS 1.3. Disable TLS 1.0 and 1.1 entirely.
Skills And Agents
Agent Structure Reference
Reference for Claude Code agent file format, frontmatter fields, tool access patterns, and permission modes
Authoring Skills and Rules
Best practices for creating Claude Code skills, agents, and rule files.
Context and memory management for agents
Treat context as a finite budget you curate: prune aggressively, isolate large subtasks to subagents, and persist what must survive across sessions.
Performance: Speed and Token Efficiency
Optimize Claude Code extensions for speed and token efficiency through shell scripts, model selection, and progressive disclosure.
Rule Structure Reference
Reference for Claude Code rule file format, quality criteria, optimization guidelines, and comparison with skills and agents
Skill Structure Reference
Reference for Claude Code skill directory layout, frontmatter fields, string substitutions, and invocation control
Testing
Comprehensive unit testing
Prioritize unit tests over integration tests. Test state transitions, edge cases, serialization round-trips. Every im...
Property-Based Testing
When to use: parsers, serializers, data transformers, encoders/decoders, validators — anything
Swift Testing
Use Swift Testing (@Test, #expect/#require, parameterized arguments, suites, traits) for new Swift unit tests.
Test Data
**Construct what you need, per test.** Large shared fixture files SHOULD be avoided.
Test Doubles
Use [Martin Fowler's taxonomy](https://martinfowler.com/bliki/TestDouble.html):
Unit Test Patterns
**Structure — Arrange, Act, Assert (AAA):**
Ui
Always show progress
When the UI is waiting on an async task:
Android edge-to-edge and window insets
Render Android apps edge-to-edge and consume WindowInsets so content is never hidden behind the status bar, navigation bar, or IME.
Android navigation in Compose
Use type-safe Navigation Compose with serializable routes, single-activity architecture, and hoisted nav state.
Android predictive back
Migrate off deprecated back handling to OnBackPressedDispatcher and support the predictive back gesture with progress-driven animations.
Animation & Motion
Motion should be purposeful — guide attention, show spatial relationships, and provide
Apple design language and widgets
Adopt the system Apple design language and materials over custom chrome, and version-gate brand-new design APIs like Liquid Glass.
Color
Use color with intention — never as the sole means of conveying information.
Core Web Vitals and performance budgets
Target LCP <= 2.5s, INP <= 200ms, CLS <= 0.1 at field p75, and enforce a performance budget in CI.
Cross-platform token adaptation
Share one semantic token source across platforms, then render values in each platform's native units, type scale, and idioms.
Dashboard service is display-only
The dashboard service is a generic API and UI layer. It has no knowledge of git, files, or roadmap structure. Agents ...
Data Display
Choose the right pattern for the content type and user task.
Design token distribution
Generate per-platform token artifacts from one source via a build step; never hand-edit the generated outputs.
Design-Time Data
- Use `d:DataContext` and `d:DesignInstance` for XAML designer preview data
Feedback Patterns
Every user action should have visible feedback. The weight of the feedback should match
Fluent Design
Use built-in WinUI 3 controls — they implement Fluent 2 natively. Never custom-draw what a standard control can do.
Form Design
Forms are where users do real work. Reduce friction at every step.
High DPI / Display Scaling
XAML layout uses effective pixels (epx) — scaling is automatic for all XAML-rendered content.
Iconography
Icons supplement text — they do not replace it (except for universally understood symbols
Jetpack Compose performance and stability
Minimize Compose recomposition with stable types, deferred state reads, lazy-list keys, and release-build measurement.
Jetpack Compose side effects
Run side effects through the correct keyed Compose effect API, never directly inside composition.
Jetpack Compose: state hoisting and unidirectional data flow
Hoist UI state to its lowest common owner or the ViewModel, keep composables stateless, and enforce state-down/events-up unidirectional flow.
Layout
Design for the content, not a fixed screen size. Layouts should adapt gracefully from
Material 3 theming on Android
Theme Compose UIs with Material 3 color roles, ColorScheme, type and shape scales, and full dark support.
Modern CSS layout and Baseline-driven adoption
Adopt modern interoperable CSS features (container queries, @layer, :has(), subgrid, nesting, view transitions) gated on Baseline status with fallbacks.
Platform Design Languages
Defer to these canonical sources before applying the defaults in this file:
Previews
All UI components MUST include preview declarations for rapid visual verification during development. Previews should...
Progressive Web App installability
Ship a Web App Manifest plus a service worker with an explicit caching strategy, and account for iOS install/push/storage limits.
Spacing
Use a consistent spatial scale based on a **4px base unit** (8px primary grid). All spacing,
State Design
Every view that loads data or can be empty must handle all four states explicitly. Never
Theming
WinUI 3 supports tri-state theming: Light, Dark, and High Contrast.
Theming with tokens
Implement themes as alternate value sets for the same semantic tokens; swap the active set, never the component code.
Touch & Click Targets
Interactive elements MUST be large enough to tap or click accurately. Defer to the platform
Typography
Use the platform's system font. Establish a type scale with clear roles — don't invent
Visual Hierarchy
Establish clear importance through size, weight, color, and spacing. Every screen should
Windows 11 materials (Mica and Acrylic)
Apply Mica as the backdrop of long-lived windows and Acrylic for transient surfaces, honoring user theme and system settings.