Matrix logo

Standards: Patterns, Architecture Heuristics, and Performance Guidance

Reusable implementation heuristics for choosing proven starting points, structuring boundaries, shaping response formats, and managing performance across languages in matrix-core.

Overview

This section covers the policy material in rules/ that defines reusable implementation heuristics for choosing proven starting points, structuring boundaries, and shaping shared response formats across languages. The performance files define how contributors should think about model choice, context management, and web delivery budgets.

Reusable Pattern Guidance

Common patterns baseline

rules/common/patterns.md establishes the repository pattern as the primary boundary between business logic and storage. It standardizes a consistent API response envelope with a success indicator, payload, error message, and pagination metadata. It also documents a contributor workflow for new work: search for battle-tested skeleton projects, evaluate them with parallel agents (security assessment, extensibility analysis, relevance scoring, implementation planning), then clone the best match and iterate inside that structure.

Language-specific pattern files

FileScopeConcrete guidance
rules/web/patterns.mdWeb UI compositionUse compound components when related UI shares state and interaction semantics
rules/typescript/patterns.mdTypeScript/JSDefines ApiResponse<T> (with success, data, error, meta carrying total, page, limit), a useDebounce hook, and a generic Repository<T> interface
rules/python/patterns.mdPythonUses Protocol to define a duck-typed Repository contract with find_by_id and save; defines CreateUserRequest with name, email, optional age
rules/java/patterns.mdJavaConstructor injection, repository interfaces, builder-based criteria objects, sealed result types, record-based response objects
rules/kotlin/patterns.mdKotlin/Android/KMPConstructor injection, MutableStateFlow state in ViewModels, repository interfaces, small use cases with invoke
rules/rust/patterns.mdRustTrait-based repositories, constructor-based service wiring, newtypes for IDs (UserId, OrderId), state enums, ServerConfigBuilder with defaults
rules/swift/patterns.mdSwift/KMPProtocol-oriented design, LoadState<T> enum (idle, loading, loaded, failed), service accepting a repository dependency with a default implementation
rules/php/patterns.mdPHPThin controllers, DTOs and value objects, constructor injection, ORM/SDK isolation behind narrow adapters
rules/perl/patterns.mdPerlDBI or DBIx::Class behind an interface rather than exposing storage details directly
rules/csharp/patterns.mdC#ApiResponse<T> (Success, Data, Error, Meta), IRepository<T>, PaymentsOptions (SectionName, BaseUrl, ApiKeySecretName)
rules/cpp/patterns.mdC++RAII with FileHandle owning std::FILE* file_, closing in the destructor, deleted copy construction and assignment
rules/dart/patterns.mdDart/FlutterRemote-plus-local repository composition, Cubit state mutation, event-driven BLoC handling, notifier-based state holder, consumer widget
rules/zh/patterns.mdChinese mirrorSame skeleton-project, repository, and API response guidance in Chinese

Common themes

  • Constructor injection is the dominant dependency shape in Java, Kotlin, Rust, and Swift.
  • ApiResponse<T>-style response envelopes converge across TypeScript, Python (implicitly), Java, C#, and Dart.
  • rules/web/patterns.md is the only file that steers UI composition (compound components) rather than data or service boundaries.
  • rules/dart/patterns.md is the richest state-pattern example set: Cubit, BLoC, notifier, and widget consumption through a provider.

Performance Guidance

Common performance rules

rules/common/performance.md is a contributor-efficiency playbook:

ModelUse case
Haiku 4.5Lightweight agents with frequent invocation, pair programming, worker agents in multi-agent systems
Sonnet 4.6Main development work, orchestrating multi-agent workflows, complex coding tasks
Opus 4.5Complex architectural decisions, maximum reasoning requirements, research and analysis

Context window management: avoid the last 20% of the context window for large-scale refactoring, feature implementation spanning multiple files, and debugging complex interactions.

Extended thinking is enabled by default (up to 31,999 tokens for internal reasoning). Control via Option+T / Alt+T toggle, alwaysThinkingEnabled in ~/.claude/settings.json, or MAX_THINKING_TOKENS environment variable.

Build failures: use the build-error-resolver agent, analyze error messages, fix incrementally, verify after each fix.

Web performance rules

rules/web/performance.md defines Core Web Vitals targets and delivery budgets:

MetricTarget
LCP< 2.5s
INP< 200ms
CLS< 0.1
FCP< 1.8s
TBT< 200ms

Bundle budgets by page type (gzipped JS and CSS caps). Loading strategy: inline only justified critical CSS, preload only the hero image and primary font, defer non-critical assets, dynamically import heavy libraries.

Chinese mirror

rules/zh/performance.md repeats the same model-selection, context-window, extended-thinking, and build-troubleshooting guidance in Chinese.

Neo Memory Pattern Encoding

neo/internal/memory/pattern.go defines the structured procedural-memory schema and the string codec that maps it onto the flat PatternData.Statement storage field.

PatternSpec properties

PropertyTypeMeaning
NamestringRecipe name
TriggerstringCondition that causes the recipe to apply
Preconditions[]stringChecks to perform before applying the pattern
Steps[]stringOrdered procedure steps
Gotchas[]stringLearned failure modes to avoid
SuccessCriteria[]stringConditions that must be true after execution

Pattern properties

PropertyTypeMeaning
SpecPatternSpecStructured recipe payload
Confidencefloat32Confidence score
CoverageintHow many times the pattern was proven
URIstringSource URI for the retrieved pattern

Public methods

MethodDescription
EncodeMarshals the spec to canonical JSON and prefixes with neo.pattern.v1:; falls back to trimmed Name plus joined Steps on marshal failure
DecodePatternSpecRemoves the version prefix, unmarshals JSON into PatternSpec, falls back to single-step legacy spec for plain statements
IsEmptyReports whether the spec has no usable content after dedupKey normalization
RenderProduces a one-line guidance string with name, trigger, preconditions, steps, gotchas, success criteria, and coverage count

Test coverage

neo/internal/memory/pattern_test.go verifies:

  • TestPatternSpecEncodeDecodeRoundTrip: round-trip of the codec.
  • TestDecodeLegacyPlainStatement: legacy plain-text compatibility.
  • TestDedupKeyPrecedence: Name > Trigger > Steps for deduplication.
  • TestPatternRender: rendered string includes all fields.

Source File Coverage Summary

PathRole
rules/common/patterns.mdShared pattern baseline for skeleton selection, repository boundaries, response envelopes
rules/web/patterns.mdWeb composition rule centered on compound components
rules/typescript/patterns.mdTypeScript patterns for responses, hooks, repositories
rules/python/patterns.mdPython protocol-based repository and request objects
rules/java/patterns.mdJava layering, injection, builders, sealed results
rules/kotlin/patterns.mdKotlin ViewModel and use-case patterns
rules/rust/patterns.mdRust traits, newtypes, state enums, builders
rules/swift/patterns.mdSwift protocol-oriented design and load states
rules/php/patterns.mdPHP service boundaries and DTOs
rules/perl/patterns.mdPerl interface boundaries for DBI/DBIx::Class
rules/csharp/patterns.mdC# response, repository, payment configuration
rules/cpp/patterns.mdC++ RAII with FileHandle
rules/dart/patterns.mdDart repository, Cubit, BLoC, notifier, widget patterns
rules/common/performance.mdModel selection, context management, extended thinking
rules/web/performance.mdWeb delivery budgets and loading strategy
neo/internal/memory/pattern.goProcedural-memory schema, codec, dedup, rendering