The Ontology

A canon of software architecture you can query: every principle with its relations and its repair, every term with its definition, every algorithm with its contract, the reasoning that derives them, the layers they live in and the resolution of every tension between them. Every reference one record makes to another is a link, so any record is a starting point.

Principles

446 of 446 shown

AI / Model Architecture

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_artificial_intelligence_architecture["Artificial Intelligence Architecture"]
    n_machine_learning_architecture["Machine Learning Architecture"]
    n_model_governance["Model Governance"]
    n_model_evaluation["Model Evaluation"]
    n_model_inference["Model Inference"]
    n_retrieval_augmented_generation["Retrieval-Augmented Generation (RAG)"]
    n_vector_search["Vector Search"]
    n_knowledge_graphs["Knowledge Graphs"]
    n_explainability["Explainability"]
    n_ai_safety["AI Safety"]
    n_prompt_engineering["Prompt Engineering"]
    n_model_drift_monitoring["Model Drift Monitoring"]
    n_agentic_architecture["Agentic Architecture"]
    n_artificial_intelligence_architecture --> n_model_governance
    n_artificial_intelligence_architecture --> n_model_evaluation
    n_artificial_intelligence_architecture --> n_ai_safety
    n_artificial_intelligence_architecture -.-> n_explainability
    n_machine_learning_architecture --> n_model_governance
    n_model_governance --> n_ai_safety
    n_model_evaluation --> n_ai_safety
    n_model_inference --> n_artificial_intelligence_architecture
    n_retrieval_augmented_generation --> n_explainability
    n_vector_search --> n_retrieval_augmented_generation
    n_knowledge_graphs --> n_explainability
    n_ai_safety --> n_model_governance
    n_prompt_engineering --> n_model_inference
    n_prompt_engineering --> n_model_evaluation
    n_model_drift_monitoring --> n_model_evaluation
    n_model_drift_monitoring --> n_model_governance
    n_agentic_architecture --> n_model_inference
    n_agentic_architecture --> n_explainability
    n_agentic_architecture --> n_ai_safety

Artificial Intelligence Architecture

  • Kind: model
  • Severity: contextual/mandatory for AI systems
  • Scope: AI system, application, platform
  • Layer: Correctness Core
Details
Violated by
model behavior integrated without evaluation/governance
Detected by
AI calls without tests, logging, fallback, policy
Measured by
model quality/safety/evaluation coverage
Refactored by
Add Evaluation Harness, Add Model Boundary, Add Guardrails
Enforced by
AI governance gates
Before
async function answerFoo(prompt: string) { return model.generate(prompt); }
After
async function answerFoo(request: FooRequest) { const input = FooRequestSchema.parse(request); const context = await fooRetriever.retrieve(input.query); const output = await fooModel.generate(buildFooPrompt(input, context)); return FooResponseSchema.parse(output); }

Machine Learning Architecture

Details
Violated by
unversioned data/model/config
Detected by
missing lineage, untracked training inputs
Measured by
reproducibility, drift, evaluation metrics
Refactored by
Add ML Pipeline, Version Data/Model/Config
Enforced by
MLOps gates
Before
const model = trainFoo(loadAllData()); serve(model);
After
const dataset = datasetRegistry.load("foo", "v3"); const features = fooFeaturePipeline.transform(dataset); const model = trainFoo(features, versionedTrainingConfig); modelRegistry.register(model, evaluateFooModel(model, validationSet));

Model Governance

Details
Violated by
deploying unapproved/untracked models
Detected by
model without lineage/approval/eval
Measured by
governance coverage
Refactored by
Add Registry, Add Approval Workflow, Add Eval Gates
Enforced by
CI/CD model gates
Before
deployModel(newestModelFile());
After
const candidate = modelRegistry.get("foo-model", "1.4.0"); requireApproval(candidate, ["model-owner", "risk-owner"]); requirePolicyCompliance(candidate, fooModelPolicies); deployModel(candidate);

Model Evaluation

Details
Violated by
model change without evaluation
Detected by
missing eval report/gate
Measured by
task metrics, safety metrics, regression rate
Refactored by
Add Eval Suite, Add Regression Dataset
Enforced by
model CI gates
Before
if (model.accuracy > 0.8) deploy(model);
After
const evaluation = evaluateModel(model, { datasets: [fooValidationSet, fooStressSet], metrics: [precision, recall, calibration, latencyP95], slices: ["foo-kind", "foo-region"], }); requireThresholds(evaluation, fooModelThresholds);

Model Inference

Details
Violated by
inference without validation/observability/fallback
Detected by
raw model calls in business logic
Measured by
latency, error rate, output quality
Refactored by
Add Inference Service, Add Adapter/Contract
Enforced by
serving standards
Before
const output = model.predict(input as any);
After
const input = FooInferenceSchema.parse(rawInput); const output = await inferenceRuntime.predict(fooModelVersion, input, { timeoutMs: 500, traceId, }); return FooPredictionSchema.parse(output);

Retrieval-Augmented Generation (RAG)

Details
Violated by
answers generated without relevant retrieved context where required
Detected by
missing citations/context in grounded tasks
Measured by
retrieval precision/recall, groundedness
Refactored by
Add Retriever, Add Reranker, Add Citation Grounding
Enforced by
RAG evals
Before
const answer = await model.generate(`Answer: ${question}`);
After
const query = normalizeFooQuery(question); const documents = await fooRetriever.search(query, { topK: 8 }); const groundedPrompt = buildGroundedFooPrompt(question, documents); const answer = await model.generate(groundedPrompt); return attachCitations(answer, documents);

Knowledge Graphs

Details
Violated by
relation-heavy domain modeled only as unstructured text
Detected by
repeated need for entity relationship traversal
Measured by
graph coverage, query accuracy
Refactored by
Extract Entities/Relations, Build Graph
Enforced by
schema/ontology validation
Before
const fooLinks = new Map<string, string[]>(); fooLinks.set(foo.id, [bar.id, baz.id]);
After
const graph = new KnowledgeGraph(); graph.addNode(foo.id, "Foo", foo); graph.addNode(bar.id, "Bar", bar); graph.addEdge(foo.id, "DEPENDS_ON", bar.id); graph.addEdge(bar.id, "PRODUCES", baz.id);

Explainability

Details
Violated by
consequential model decisions without explanation/evidence
Detected by
missing rationale/feature attribution/citations
Measured by
explanation coverage/quality
Refactored by
Add Explanation Layer, Add Evidence Trace
Enforced by
AI governance gates
Before
return model.predict(foo.features);
After
const prediction = await model.predict(foo.features); const explanation = await explainer.explain({ modelVersion: model.version, input: foo.features, prediction, }); return { prediction, explanation };

AI Safety

Details
Violated by
unsafe outputs/actions without guardrails
Detected by
safety eval failures, missing policy filters
Measured by
safety incident rate, eval pass rate
Refactored by
Add Guardrails, Add Human Review, Add Safety Evals
Enforced by
safety gates, runtime monitors
Before
return model.generate(userPrompt);
After
const input = await safety.validateInput(userPrompt); const draft = await model.generate(input); const checked = await safety.validateOutput(draft, { policy: "foo-assistant-v2" }); if (!checked.allowed) return safeRefusal(checked.reasons); return checked.output;

Prompt Engineering

Details
Violated by
prompts inlined and duplicated across call sites
Detected by
scattered prompt string literals
Measured by
duplicated prompt count
Refactored by
Centralize and Version Prompts
Enforced by
AI design review
Before
const answer = await model.generate("summarize: " + text);
After
const prompt = fooPromptTemplate.render({ task: "summarize", input: text, format: "bullet-points", maxWords: 100 }); const answer = await model.generate(prompt, { temperature: 0, stop: ["\n\n"] });

Model Drift Monitoring

Details
Violated by
model quality assumed stable after deployment
Detected by
no ongoing evaluation of live model outputs
Measured by
drift in accuracy/quality metrics over time
Refactored by
Instrument Drift Monitoring
Enforced by
model governance review
Before
serveModel(fooModel);
After
monitor.track(fooModel, { metrics: [inputDistribution, predictionConfidence, groundTruthLag], alertOn: { populationStabilityIndex: 0.2 }, });

Agentic Architecture

  • Kind: pattern
  • Severity: contextual/mandatory in regulated AI
  • Scope: AI system, reasoning, decision flow
  • Layer: Correctness Core
Details
Violated by
an unbounded model loop acting with no guardrails
Detected by
agent actions without tool scoping or step limits
Measured by
unguarded agent action rate
Refactored by
Bound the Agent with Tools, Limits, and Review
Enforced by
AI safety review
Before
const answer = await model.generate(question);
After
const agent = createFooAgent({ tools: [searchFoos, calculator, fooStore], maxSteps: 8 }); const answer = await agent.run(question);

anti-patterns

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_big_ball_of_mud["Big Ball of Mud"]
    n_god_object["God Object"]
    n_concrete_coupling["Concrete Coupling"]
    n_schema_drift["Schema Drift"]
    n_implicit_contract["Implicit Contract"]
    n_hardcoded_configuration["Hardcoded Configuration"]
    n_shared_mutable_state["Shared Mutable State"]
    n_boundary_leakage["Boundary Leakage"]
    n_manual_only_governance["Manual-Only Governance"]
    n_opaque_runtime_behavior["Opaque Runtime Behavior"]
    n_unowned_risk["Unowned Risk"]
    n_unobservable_failure["Unobservable Failure"]
    n_unversioned_breaking_change["Unversioned Breaking Change"]
    n_distributed_monolith["Distributed Monolith"]
    n_shotgun_surgery["Shotgun Surgery"]
    n_divergent_change["Divergent Change"]
    n_feature_envy["Feature Envy"]
    n_inappropriate_intimacy["Inappropriate Intimacy"]
    n_message_chain["Message Chain"]
    n_middle_man["Middle Man"]
    n_data_clumps["Data Clumps"]
    n_primitive_obsession["Primitive Obsession"]
    n_stringly_typed_programming["Stringly Typed Programming"]
    n_boolean_trap["Boolean Trap"]
    n_long_parameter_list["Long Parameter List"]
    n_magic_value["Magic Value"]
    n_speculative_generality["Speculative Generality"]
    n_premature_abstraction["Premature Abstraction"]
    n_over_abstraction["Over-Abstraction"]
    n_golden_hammer["Golden Hammer"]
    n_pattern_cargo_cult["Pattern Cargo Cult"]
    n_lava_flow["Lava Flow"]
    n_zombie_code["Zombie Code"]
    n_temporal_coupling["Temporal Coupling"]
    n_hidden_side_effect["Hidden Side Effect"]
    n_action_at_a_distance["Action at a Distance"]
    n_ambient_context["Ambient Context"]
    n_inconsistent_error_model["Inconsistent Error Model"]
    n_exception_control_flow["Exception Control Flow"]
    n_null_semantics_drift["Null Semantics Drift"]
    n_anemic_domain_model["Anemic Domain Model"]
    n_transaction_script_sprawl["Transaction Script Sprawl"]
    n_fat_controller["Fat Controller"]
    n_repository_dump["Repository Dump"]
    n_utility_dump["Utility Dump"]
    n_framework_leakage["Framework Leakage"]
    n_vendor_lock_in_leakage["Vendor Lock-In Leakage"]
    n_circular_dependency["Circular Dependency"]
    n_cyclic_deployment_dependency["Cyclic Deployment Dependency"]
    n_synchronous_chain_trap["Synchronous Chain Trap"]
    n_chatty_interface["Chatty Interface"]
    n_n_plus_one_query["N Plus One Query"]
    n_cache_poisoning_by_design["Cache Poisoning by Design"]
    n_retry_storm["Retry Storm"]
    n_timeout_omission["Timeout Omission"]
    n_missing_backpressure["Missing Backpressure"]
    n_silent_data_corruption["Silent Data Corruption"]
    n_lost_update["Lost Update"]
    n_dual_write["Dual Write"]
    n_read_your_writes_violation["Read-Your-Writes Violation"]
    n_security_theater["Security Theater"]
    n_authorization_scattering["Authorization Scattering"]
    n_secret_sprawl["Secret Sprawl"]
    n_pii_oversharing["PII Oversharing"]
    n_observability_noise["Observability Noise"]
    n_log_as_control_flow["Log-as-Control-Flow"]
    n_manual_runbook_dependency["Manual Runbook Dependency"]
    n_big_bang_release["Big-Bang Release"]
    n_irreversible_migration["Irreversible Migration"]
    n_big_upfront_frozen_architecture["Big-Upfront Frozen Architecture"]
    n_architecture_astronaut["Architecture Astronaut"]
    n_feature_only_design["Feature-Only Design"]
    n_test_pyramid_inversion["Test Pyramid Inversion"]
    n_mock_mirage["Mock Mirage"]
    n_flaky_test_normalization["Flaky Test Normalization"]
    n_ai_prompt_sprawl["AI Prompt Sprawl"]
    n_ungrounded_ai_output["Ungrounded AI Output"]
    n_model_version_ambiguity["Model Version Ambiguity"]

Big Ball of Mud

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Allow boundaries to remain implicit, permit unrestricted dependencies, mix concerns freely, share mutable state broadly, and accumulate changes without architectural segmentation.
Detected by
cyclic_dependencies, high_graph_density, unowned_modules, cross_layer_imports, large_change_blast_radius
Measured by
none
Refactored by
define_boundaries, split_modules, enforce_dependency_rules, assign_ownership, add_fitness_functions
Enforced by
none
Before
function handle(req) { const foo = db.query(req.body.sql); render(foo); email(foo); audit(foo); cache(foo); }
After
class CreateFoo { constructor(private readonly foos: FooRepository, private readonly events: EventPublisher) {} execute(input: CreateFooInput) { const foo = Foo.create(input); this.foos.save(foo); this.events.publish(fooCreated(foo)); } }

God Object

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Centralize unrelated responsibilities into one object, route unrelated behavior through it, accumulate state and dependencies, and make the object the default modification point.
Detected by
large_class, many_unrelated_methods, many_dependencies, high_fan_in, multiple_reasons_to_change
Measured by
none
Refactored by
extract_class, split_responsibilities, move_method, extract_domain_service, introduce_facade_only_if_boundary_needed
Enforced by
none
Before
class FooManager { createFoo() {} priceFoo() {} renderFoo() {} emailFoo() {} auditFoo() {} shipFoo() {} }
After
class FooFactory { create(input: CreateFooInput): Foo {} } class FooPricer { price(foo: Foo): Money {} } class FooShipper { ship(foo: Foo): void {} }

Concrete Coupling

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Let high-level policy depend directly on low-level implementations, vendor APIs, framework classes, or concrete constructors, then spread those concrete assumptions across the core.
Detected by
domain_imports_infrastructure, vendor_sdk_in_core, new_dependency_inside_business_logic, missing_interface_boundary
Measured by
none
Refactored by
extract_interface, introduce_port, extract_adapter, inject_dependency, apply_DIP
Enforced by
none
Before
class FooService { private readonly store = new SqlFooStore(); }
After
class FooService { constructor(private readonly store: FooStore) {} }

Schema Drift

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Allow producers, consumers, storage models, and documentation to evolve independently without versioned schema governance, then let payload meaning diverge over time.
Detected by
schema_diff_failure, missing_schema_registry, consumer_parse_errors, undocumented_field_changes, nullability_mismatch
Measured by
none
Refactored by
define_schema_contract, version_schema, add_compatibility_tests, centralize_schema_registry, validate_payloads
Enforced by
none
Before
type FooApi = { id: string; label: string }; type FooDb = { id: string; name: string; extra: string };
After
const FooSchema = schema({ id: fooIdSchema, name: nonEmptyString }); type Foo = Infer<typeof FooSchema>; fooApi.use(FooSchema); fooDb.use(FooSchema);

Implicit Contract

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Encode assumptions in code behavior, naming, ordering, timing, side effects, or undocumented payload shapes instead of declaring them as explicit contracts.
Detected by
public_API_without_schema, undocumented_side_effect, dynamic_map_boundary, tests_depend_on_internal_behavior, tribal_knowledge_required
Measured by
none
Refactored by
add_explicit_contract, define_preconditions, define_postconditions, add_schema, add_contract_tests
Enforced by
none
Before
function saveFoo(foo) { return db.insert(foo); }
After
interface Foo { id: FooId; name: NonEmptyString; } function saveFoo(foo: Foo): Promise<void> { return fooStore.save(foo); }

Hardcoded Configuration

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Embed environment, path, credential, feature, service endpoint, or policy values directly into code, then duplicate those assumptions across runtime contexts.
Detected by
hardcoded_URL, hardcoded_path, hardcoded_secret, environment_branching_in_code, duplicated_config_literal
Measured by
none
Refactored by
externalize_configuration, add_config_schema, centralize_config_source, validate_environment, remove_secret_from_code
Enforced by
none
Before
const client = new FooClient("https://foo.prod.example", "sk_live_abc123");
After
const config = FooConfigSchema.parse({ url: process.env.FOO_URL, key: process.env.FOO_KEY }); const client = new FooClient(config);

Shared Mutable State

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Expose writable state across modules, allow multiple actors to mutate it, omit ownership and synchronization, and let behavior depend on mutation order.
Detected by
global_mutable_object, public_mutable_fields, shared_cache_without_policy, race_condition, order_dependent_tests
Measured by
none
Refactored by
encapsulate_state, assign_owner, make_immutable, add_transaction_boundary, apply_concurrency_control
Enforced by
none
Before
let currentFoo = null; function setFoo(f) { currentFoo = f; } function useFoo() { return currentFoo.name; }
After
class FooContext { constructor(private readonly foo: Foo) {} name() { return this.foo.name; } }

Boundary Leakage

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Permit internal models, infrastructure types, persistence structures, or private module APIs to cross intended architectural boundaries.
Detected by
internal_package_imported_externally, database_entity_exposed_as_API, vendor_type_in_domain, private_module_used_by_other_module
Measured by
none
Refactored by
restrict_exports, introduce_DTO, add_adapter, add_facade, enforce_import_rules
Enforced by
none
Before
app.get("/foo/:id", async (req, res) => res.json(await ormFoo.findByPk(req.params.id)));
After
app.get("/foo/:id", async (req, res) => res.json(toFooDto(await getFoo.execute(req.params.id))));

Manual-Only Governance

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Encode architecture rules in documents, meetings, or reviewer memory without executable checks, metrics, or automated enforcement.
Detected by
rule_exists_only_in_docs, no_CI_gate, reviewer_specific_enforcement, repeated_same_violation, missing_fitness_function
Measured by
none
Refactored by
create_fitness_function, add_static_check, add_policy_as_code, add_architecture_test, track_rule_metrics
Enforced by
none
Before
const CONVENTION = "remember to prefix every foo id with foo_";
After
export const rule = { id: "valid-foo-id", check: (id: string) => id.startsWith("foo_") };

Opaque Runtime Behavior

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Let runtime behavior emerge from hidden reflection, implicit registration, undocumented configuration, side effects, or untraced dynamic binding.
Detected by
dynamic_binding_without_manifest, missing_startup_report, unlogged_plugin_loading, implicit_reflection_scan, untraceable_side_effect
Measured by
none
Refactored by
add_manifest, log_binding_decisions, emit_runtime_topology, add_capability_declaration, add_discovery_validation
Enforced by
none
Before
function processFoo(foo) { doWork(foo); }
After
function processFoo(foo: Foo) { logger.info("foo.process.start", { fooId: foo.id }); const result = doWork(foo); logger.info("foo.process.done", { fooId: foo.id, outcome: result.status }); }

Unowned Risk

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Identify a risk without assigning owner, severity, mitigation, review date, acceptance status, or escalation path.
Detected by
risk_without_owner, ADR_missing_consequence_owner, security_finding_unassigned, known_gap_without_due_date, accepted_risk_without_expiry
Measured by
none
Refactored by
assign_owner, classify_severity, define_mitigation, record_acceptance, schedule_review
Enforced by
none
Before
await payment.charge(foo);
After
const outcome = await payment.charge(foo); if (!outcome.ok) { logger.error("foo.charge.failed", outcome); throw new ChargeFailedError(foo.id); }

Unobservable Failure

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Permit operations to fail without structured logs, metrics, alerts, traces, audit records, or user-visible error contracts.
Detected by
empty_catch, swallowed_exception, missing_error_log, no_alert_on_critical_path, missing_trace_span, missing_audit_record
Measured by
none
Refactored by
add_error_boundary, emit_structured_log, add_metric, add_alert, add_trace_span, add_audit_log
Enforced by
none
Before
try { await ship(foo); } catch { }
After
try { await ship(foo); } catch (error) { logger.error("foo.ship.failed", error); metrics.increment("foo.ship.failure"); throw new ShipFailedError(foo.id); }

Unversioned Breaking Change

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Change a public API, schema, event, protocol, behavior, or package contract incompatibly without version bump, deprecation path, compatibility test, or migration notice.
Detected by
API_diff_breaking, schema_field_removed, type_narrowed, event_semantics_changed, no_version_bump, no_deprecation_window
Measured by
none
Refactored by
bump_version, add_compatibility_adapter, deprecate_gradually, add_contract_tests, publish_migration_guide
Enforced by
none
Before
app.get("/foo", () => ({ label: foo.name }));
After
app.get("/v2/foo", () => ({ name: foo.name })); app.get("/v1/foo", () => ({ label: foo.name }));

Distributed Monolith

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Split deployment units without splitting data ownership, transaction boundaries, failure isolation, contracts, or autonomous release capability.
Detected by
shared_database, cross_service_transactions, lockstep_deployments, deep_sync_call_chain, shared_business_logic_package, consumer_breakage_on_service_change
Measured by
none
Refactored by
own_data_per_service, define_service_contracts, introduce_events, add_outbox, split_bounded_context, enable_independent_deployment
Enforced by
none
Before
async function createFoo(foo) { await http.post("bar-service/validate", foo); await http.post("baz-service/price", foo); await http.post("qux-service/save", foo); }
After
async function createFoo(input: CreateFooInput) { const foo = Foo.create(input); await fooStore.save(foo); await outbox.append(fooCreated(foo)); }

Shotgun Surgery

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Scatter one conceptual responsibility across many files so one change requires many coordinated edits.
Detected by
same_change_touches_many_files, repeated_commit_cochanges, duplicated_rule_fragments
Measured by
none
Refactored by
centralize_rule, extract_module, move_behavior_to_owner, add_single_source_of_truth
Enforced by
none
Before
const taxA = value * 0.2; const taxB = other * 0.2; const taxC = more * 0.2;
After
const FOO_TAX_RATE = 0.2; function taxFoo(value: number) { return value * FOO_TAX_RATE; }

Divergent Change

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Place unrelated responsibilities in the same module so unrelated change reasons repeatedly modify one artifact.
Detected by
unrelated_commits_touch_same_file, mixed_methods, mixed_dependencies
Measured by
none
Refactored by
split_module, extract_class, separate_concerns, move_method
Enforced by
none
Before
class Foo { renderHtml() {} saveToSql() {} sendEmail() {} parseCsv() {} }
After
class Foo {} class FooView { render(foo: Foo): string {} } class FooStore { save(foo: Foo): Promise<void> {} }

Feature Envy

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Let one module repeatedly inspect or manipulate another module’s data instead of moving behavior to the data owner.
Detected by
many_getters_from_other_object, logic_using_foreign_fields, domain_rule_outside_owner
Measured by
none
Refactored by
move_method, encapsulate_state, add_domain_behavior, introduce_service_boundary
Enforced by
none
Before
function totalFoo(bar: Bar) { return bar.items.reduce((s, i) => s + i.price * i.qty, 0); }
After
class Bar { total(): Money { return this.items.reduce((s, i) => s + i.subtotal(), 0); } }

Inappropriate Intimacy

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Allow modules or classes to rely on each other’s internals, private structure, lifecycle, or undocumented state.
Detected by
friend-like access, private API usage, tests_reach_internals, internal_package_import
Measured by
none
Refactored by
hide_internal, introduce_public_contract, add_facade, restrict_exports
Enforced by
none
Before
bar.foo._internalState.status = "ready";
After
bar.foo.markReady();

Message Chain

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Require clients to traverse a chain of objects to reach behavior or data, exposing internal object graph structure.
Detected by
a.getB().getC().doX, deep_property_access, repeated_navigation_paths
Measured by
none
Refactored by
hide_delegate, introduce_facade_method, move_behavior_to_owner
Enforced by
none
Before
const city = foo.getOwner().getAddress().getCity().getName();
After
const city = foo.ownerCityName();

Middle Man

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Insert a module that delegates almost everything without adding policy, abstraction, validation, orchestration, or simplification.
Detected by
thin_methods_only_delegate, low_logic_density, one_to_one_wrapper_methods
Measured by
none
Refactored by
remove_layer, inline_delegate, promote_to_real_facade_if_boundary_needed
Enforced by
none
Before
class FooService { save(foo: Foo) { return this.store.save(foo); } find(id: FooId) { return this.store.find(id); } }
After
const fooStore: FooStore = new SqlFooStore();

Data Clumps

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Pass the same group of fields together repeatedly without naming the group as a value object or contract.
Detected by
same_parameters_repeated, same_fields_appear_together, DTO_shape_duplicated
Measured by
none
Refactored by
introduce_value_object, add_DTO, name_concept, validate_as_group
Enforced by
none
Before
function shipFoo(street: string, city: string, zip: string, country: string) {}
After
interface Address { street: string; city: string; zip: string; country: string; } function shipFoo(address: Address) {}

Primitive Obsession

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Represent meaningful domain concepts as raw strings, numbers, booleans, or maps without type, validation, or behavior.
Detected by
many_string_ids, repeated_validation, boolean_flags, magic_values
Measured by
none
Refactored by
introduce_value_object, narrow_type, add_enum, encapsulate_validation
Enforced by
none
Before
function transfer(fooId: string, amount: number, currency: string) {}
After
class Money { constructor(readonly amount: number, readonly currency: Currency) {} } function transfer(fooId: FooId, money: Money) {}

Stringly Typed Programming

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Encode behavior, types, states, permissions, or protocols as unchecked strings.
Detected by
string_mode_switch, repeated_string_constants, string_permissions, string_status_values
Measured by
none
Refactored by
add_enum, add_discriminated_union, centralize_constants, schema_validate
Enforced by
none
Before
if (foo.status === "reddy") ship(foo);
After
enum FooStatus { Ready, Shipped } if (foo.status === FooStatus.Ready) ship(foo);

Boolean Trap

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Use boolean parameters or flags that hide intent and create ambiguous call sites or combinatorial behavior.
Detected by
method(true, false), multiple_boolean_params, flag_argument_controls_behavior
Measured by
none
Refactored by
replace_boolean_with_enum, split_method, introduce_options_object, name_intent
Enforced by
none
Before
createFoo(true, false, true);
After
createFoo({ active: true, archived: false, notify: true });

Long Parameter List

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Grow function or constructor signatures until related inputs, optional modes, and dependencies become hard to understand or validate.
Detected by
arity_above_threshold, repeated_parameter_groups, many_optional_params
Measured by
none
Refactored by
introduce_parameter_object, builder, value_object, dependency_container
Enforced by
none
Before
function makeFoo(a, b, c, d, e, f, g) {}
After
interface MakeFooInput { a: A; b: B; c: C; d: D; e: E; f: F; g: G; } function makeFoo(input: MakeFooInput) {}

Magic Value

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Encode policy, thresholds, status, timing, permissions, or domain rules as unexplained literals.
Detected by
repeated_number_literal, unexplained_string_literal, inline_threshold, hidden_timeout
Measured by
none
Refactored by
name_constant, centralize_rule, externalize_config_if_runtime_variable, document_semantics
Enforced by
none
Before
if (foo.retries > 3) fail(foo);
After
const MAX_FOO_RETRIES = 3; if (foo.retries > MAX_FOO_RETRIES) fail(foo);

Speculative Generality

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Build abstractions, extension points, layers, or configuration for variation that has no evidence of existing or near-term need.
Detected by
single_implementation_interface, unused_extension_point, config_never_varies, abstract_base_without_variants
Measured by
none
Refactored by
inline_abstraction, remove_unused_extension, defer_generalization, apply_minimum_viable_architecture
Enforced by
none
Before
abstract class AbstractFooProviderFactoryBase<T> { abstract create(): T; }
After
function createFoo(input: CreateFooInput): Foo { return Foo.create(input); }

Premature Abstraction

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Extract a shared abstraction before variation is understood, causing the abstraction to fit no use case well.
Detected by
many_flags_in_shared_abstraction, subclasses_override_most_behavior, callers_work_around_abstraction
Measured by
none
Refactored by
duplicate_until_pattern_stabilizes, split_abstraction, extract_later_from_evidence
Enforced by
none
Before
interface FooStrategy { run(): void; } class OnlyFooStrategy implements FooStrategy { run() {} }
After
function runFoo() {}

Over-Abstraction

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Add too many interfaces, layers, factories, adapters, or generic types relative to actual variability.
Detected by
deep_call_stack_for_simple_task, one_method_interfaces, factory_of_factory, abstraction_ratio_too_high
Measured by
none
Refactored by
collapse_layers, inline_interface, remove_unused_indirection, preserve_only_real_boundaries
Enforced by
none
Before
const foo = fooFactoryProvider.getFactory().createBuilder().build();
After
const foo = Foo.create(input);

Golden Hammer

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Apply a familiar pattern, framework, architecture style, or technology to problems regardless of fit.
Detected by
same_pattern_everywhere, solution_precedes_problem, ADR_missing_alternatives, high_workaround_count
Measured by
none
Refactored by
force_analysis, tradeoff_matrix, ADR_with_alternatives, contextual_pattern_selection
Enforced by
none
Before
const config = parseFooConfig(runRegexOverEverything(rawYaml));
After
const config = FooConfigSchema.parse(yaml.load(rawYaml));

Pattern Cargo Cult

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Copy named patterns or architecture styles without implementing their required forces, contracts, constraints, or validation gates.
Detected by
ports_without_boundary_rules, plugins_without_contracts, events_without_idempotency, microservices_without_autonomy
Measured by
none
Refactored by
validate_required_forces, add_missing_contracts, rename_if_not_pattern, remove_pattern_shell
Enforced by
none
Before
class FooSingletonFactoryObserverProxy {}
After
class FooService { constructor(private readonly store: FooStore) {} }

Lava Flow

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Preserve obsolete, half-migrated, or unexplained code paths because nobody knows whether they are still needed.
Detected by
old_paths_never_called, deprecated_code_without_removal_date, feature_flags_stuck_on_or_off, comments_say_do_not_touch
Measured by
none
Refactored by
usage_instrumentation, owner_assignment, deprecation_plan, delete_after_evidence
Enforced by
none
Before
function saveFoo(foo) { legacySaveV1(foo); if (false) legacySaveV2(foo); newSave(foo); }
After
function saveFoo(foo: Foo) { return fooStore.save(foo); }

Zombie Code

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Leave unreachable, unused, or disabled code in the system where it continues to confuse readers and sometimes reactivates accidentally.
Detected by
unused_exports, unreachable_branches, dead_feature_flags, zero_runtime_hits
Measured by
none
Refactored by
delete_code, archive_reference, remove_exports, add_dead_code_check
Enforced by
none
Before
function computeFoo() {} function computeFooOld() {} function computeFooDeprecated() {}
After
function computeFoo() {}

Temporal Coupling

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Require operations to be called in a specific undocumented order for correctness.
Detected by
must_call_initialize_first, method_fails_before_setup, order_dependent_tests, state_machine_hidden_in_calls
Measured by
none
Refactored by
encode_state_machine, constructor_valid_state, make_order_explicit, add_precondition
Enforced by
none
Before
foo.init(); foo.configure(); foo.start();
After
const foo = Foo.start(config);

Hidden Side Effect

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Make an operation appear like a query or pure function while it mutates state, performs I/O, emits events, or changes global context.
Detected by
getter_mutates_state, query_writes, function_emits_event_unexpectedly, global_context_modified
Measured by
none
Refactored by
rename_command, separate_query_from_command, make_effect_explicit, move_to_effect_boundary
Enforced by
none
Before
function getFoo(id: FooId) { audit.log(id); return fooStore.find(id); }
After
function getFoo(id: FooId) { return fooStore.find(id); } function auditFooAccess(id: FooId) { audit.log(id); }

Action at a Distance

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Let one part of the system change behavior far away through globals, monkey patches, shared registries, ambient context, or implicit event listeners.
Detected by
monkey_patch, global_registry_mutation, ambient_context_write, implicit_subscriber_side_effect
Measured by
none
Refactored by
explicit_dependency, localize_effect, trace_causation, restrict_global_mutation
Enforced by
none
Before
globalThis.fooFlag = true; function runFoo() { if (globalThis.fooFlag) go(); }
After
function runFoo(options: { enabled: boolean }) { if (options.enabled) go(); }

Ambient Context

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Read user, tenant, locale, transaction, permissions, or request state from implicit global context instead of explicit parameters or scoped context objects.
Detected by
global_current_user, thread_local_business_data, implicit_tenant_lookup, hidden_transaction_context
Measured by
none
Refactored by
pass_context_explicitly, scope_context_object, inject_request_context, limit_ambient_use_to_infrastructure
Enforced by
none
Before
function saveFoo(foo) { return CurrentTenant.get().db.save(foo); }
After
function saveFoo(foo: Foo, tenant: Tenant) { return tenant.db.save(foo); }

Inconsistent Error Model

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Mix exceptions, nulls, booleans, strings, partial objects, console logging, and silent failure for the same error class.
Detected by
same_error_returns_null_or_throws, mixed_error_shapes, string_errors, partial_success_without_contract
Measured by
none
Refactored by
typed_result, standard_error_contract, error_boundary, normalize_failure_modes
Enforced by
none
Before
function a() { return null; } function b() { throw "bad"; } function c() { return { error: true }; }
After
function a(): Result<Foo, FooError> {} function b(): Result<Bar, FooError> {} function c(): Result<Baz, FooError> {}

Exception Control Flow

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Use exceptions for expected branching, normal absence, validation alternatives, or loop control.
Detected by
try_catch_for_lookup_absence, exceptions_in_hot_loop, catch_chooses_normal_path
Measured by
none
Refactored by
return_result_type, use_option_type, validate_before_call, branch_explicitly
Enforced by
none
Before
try { return await fooStore.find(id); } catch (notFound) { return fooStore.create(id); }
After
const foo = await fooStore.find(id); return foo ?? fooStore.create(id);

Null Semantics Drift

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Use null, undefined, empty string, zero, false, missing field, and empty collection interchangeably.
Detected by
null_and_empty_string_same_field, optional_field_without_semantics, truthy_checks_for_domain_state
Measured by
none
Refactored by
define_absence_semantics, use_option_result, schema_nullability, normalize_input
Enforced by
none
Before
const foo = find(id); if (foo) use(foo);
After
const foo = find(id) ?? Foo.none(); foo.use();

Anemic Domain Model

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Store domain data in passive objects while business rules live in services, controllers, handlers, or scripts.
Detected by
entities_with_getters_setters_only, services_contain_all_rules, validation_outside_aggregate
Measured by
none
Refactored by
move_behavior_to_domain, add_value_object, add_aggregate_invariant, encapsulate_state
Enforced by
none
Before
class Foo { status: string; } function shipFoo(foo: Foo) { if (foo.status === "ready") foo.status = "shipped"; }
After
class Foo { private status = FooStatus.Ready; ship() { if (this.status !== FooStatus.Ready) throw new NotReadyError(); this.status = FooStatus.Shipped; } }

Transaction Script Sprawl

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Encode business processes as procedural scripts that directly coordinate validation, persistence, external calls, and domain decisions.
Detected by
large_service_method, business_rules_in_controller, repeated_procedure_blocks
Measured by
none
Refactored by
extract_domain_model, extract_use_case, separate_ports, move_rules_to_domain
Enforced by
none
Before
function createFooHandler(req) { validate(req); price(req); tax(req); persist(req); notify(req); }
After
class CreateFoo { constructor(private readonly foos: FooRepository) {} execute(input: CreateFooInput) { const foo = Foo.create(input); return this.foos.save(foo); } }

Fat Controller

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Put validation, business rules, persistence orchestration, mapping, authorization, and response formatting in the controller layer.
Detected by
controller_method_too_large, repository_calls_plus_business_rules, domain_logic_in_route_handler
Measured by
none
Refactored by
extract_use_case, move_domain_logic, add_request_mapper, add_application_service
Enforced by
none
Before
class FooController { create(req) { const foo = { ...req.body }; if (!foo.name) throw 0; db.insert(foo); email(foo); } }
After
class FooController { constructor(private readonly createFoo: CreateFoo) {} create(req: Request) { return this.createFoo.execute(req.body); } }

Repository Dump

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Place business-specific querying, orchestration, mapping, caching, validation, and policy into a repository until it becomes a second service layer.
Detected by
repository_methods_encode_business_process, authorization_in_repository, repository_calls_external_services
Measured by
none
Refactored by
extract_query_service, move_policy_to_domain_or_use_case, split_repository, define_persistence_contract
Enforced by
none
Before
class FooRepository { findActiveFoosForBarInRegionSortedByBaz() {} }
After
class FooRepository { find(spec: FooSpecification): Foo[] { return this.query(spec.toQuery()); } }

Utility Dump

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Accumulate unrelated helper functions in generic utility modules without ownership, cohesion, or domain language.
Detected by
utils_file_growth, unrelated_helpers, many_modules_import_same_dump, generic_names
Measured by
none
Refactored by
move_helper_to_owner, split_by_domain, extract_value_object, name_concept
Enforced by
none
Before
export function formatFoo() {} export function parseBar() {} export function hashBaz() {}
After
export const fooFormatter = { format(foo: Foo): string {} }; export const barParser = { parse(raw: string): Bar {} };

Framework Leakage

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Let framework classes, decorators, lifecycle assumptions, request objects, ORM entities, or infrastructure annotations enter core domain logic.
Detected by
request_object_in_domain, ORM_entity_as_domain, framework_annotation_in_core, container_lookup_in_business_logic
Measured by
none
Refactored by
add_adapter, map_to_domain_model, introduce_port, move_framework_outward
Enforced by
none
Before
class Foo { @Column() name: string; @OneToMany() bars: Bar[]; }
After
class Foo { constructor(readonly name: string, readonly bars: readonly Bar[]) {} } class FooEntity { @Column() name: string; }

Vendor Lock-In Leakage

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Spread vendor-specific APIs, models, exceptions, identifiers, or configuration throughout application and domain code.
Detected by
vendor_imports_outside_adapter, vendor_error_types_in_domain, vendor_schema_as_canonical_model
Measured by
none
Refactored by
extract_vendor_adapter, define_port, translate_errors, own_canonical_model
Enforced by
none
Before
import { BlobStore } from "acme-blob-sdk"; function saveFoo(foo) { return new BlobStore().putObject(foo); }
After
interface FooBlobStore { put(foo: Foo): Promise<void>; } function saveFoo(foo: Foo, store: FooBlobStore) { return store.put(foo); }

Circular Dependency

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Allow modules to depend on each other directly or indirectly until no module can change, test, deploy, or initialize independently.
Detected by
dependency_cycle, mutual_imports, bootstrap_order_hacks, bidirectional_service_calls
Measured by
none
Refactored by
invert_dependency, extract_interface, split_shared_contract, introduce_event_or_mediator
Enforced by
none
Before
import { bar } from "./bar"; export const foo = () => bar(); import { foo } from "./foo"; export const bar = () => foo();
After
export const foo = (run: () => void) => run(); export const bar = () => {}; foo(bar);

Cyclic Deployment Dependency

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Require two or more services or packages to deploy in lockstep because each depends on the other’s current behavior.
Detected by
coordinated_release_required, consumer_breaks_without_provider_release, mutual_contract_change
Measured by
none
Refactored by
version_contract, backward_compatible_change, consumer_driven_contract_tests, adapter_phase_migration
Enforced by
none
Before
fooService.callsAtStartup(barService); barService.callsAtStartup(fooService);
After
fooService.publishes(fooReady); barService.subscribes(fooReady);

Synchronous Chain Trap

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Build deep request-time chains across services or modules, making latency, availability, and failure behavior multiplicative.
Detected by
sync_depth_above_threshold, request_path_many_remote_calls, cascading_timeout
Measured by
none
Refactored by
collapse_reads, introduce_async_event, cache_read_model, apply_timeout_bulkhead
Enforced by
none
Before
const foo = await a(); const bar = await b(foo); const baz = await c(bar); return slowSyncCall(a, b, c);
After
const [foo, bar, baz] = await Promise.all([a(), b(), c()]);

Chatty Interface

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Require many small remote calls to complete one user or business operation.
Detected by
N_plus_1_API_calls, many_calls_per_screen, loop_contains_remote_call
Measured by
none
Refactored by
coarse_grained_endpoint, batch_api, query_projection, data_loader
Enforced by
none
Before
const results = []; for (const id of fooIds) results.push(await fooApi.get(id));
After
const results = await fooApi.getMany(fooIds);

N Plus One Query

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Fetch a collection, then issue one query or remote call per item rather than fetching required related data intentionally.
Detected by
query_inside_loop, remote_call_inside_loop, query_count_scales_with_rows
Measured by
none
Refactored by
batch_fetch, join_or_include, preload, cache_projection
Enforced by
none
Before
const foos = await fooStore.all(); for (const foo of foos) foo.bar = await barStore.find(foo.barId);
After
const foos = await fooStore.all(); const bars = await barStore.findMany(foos.map(f => f.barId));

Cache Poisoning by Design

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Cache data without key correctness, tenant isolation, authorization context, freshness, invalidation, or schema version.
Detected by
cache_key_missing_user_or_tenant, cache_without_version, no_invalidation, authorization_not_in_cache_key
Measured by
none
Refactored by
define_cache_contract, include_context_in_key, add_invalidation, add_ttl_and_version
Enforced by
none
Before
fooCache.set(request.path, response);
After
if (response.ok && response.cacheable) { fooCache.set(cacheKey(request.identity, request.path), response, { ttlMs: 60_000 }); }

Retry Storm

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Allow many clients or workers to retry failed dependencies aggressively and synchronously, increasing pressure on the failing system.
Detected by
no_backoff, no_jitter, unbounded_retries, retry_on_non_idempotent_operation
Measured by
none
Refactored by
bounded_retry, exponential_backoff, jitter, circuit_breaker, idempotency_key
Enforced by
none
Before
while (true) { try { return await call(); } catch { } }
After
return retry(call, { attempts: 5, backoff: exponentialJitter(), giveUp: dlq });

Timeout Omission

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Call external systems without explicit timeouts, cancellation, or deadline propagation.
Detected by
HTTP_call_without_timeout, DB_query_without_timeout, missing_cancellation_token, no_deadline_propagation
Measured by
none
Refactored by
add_timeout, propagate_deadline, add_cancellation, fallback_or_failfast
Enforced by
none
Before
const foo = await fetch(fooUrl);
After
const foo = await fetch(fooUrl, { signal: AbortSignal.timeout(5000) });

Missing Backpressure

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Accept work faster than the system can process it without queue limits, admission control, rate limits, or shedding.
Detected by
unbounded_queue, no_rate_limit, no_admission_control, memory_grows_with_load
Measured by
none
Refactored by
bounded_queue, rate_limit, load_shed, apply_backpressure_signal
Enforced by
none
Before
stream.on("data", d => queue.push(process(d)));
After
stream.pipe(new BoundedFooProcessor({ highWaterMark: 100 }));

Silent Data Corruption

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Accept, transform, or persist invalid data without validation, checksums, invariants, reconciliation, or audit.
Detected by
missing_boundary_validation, no_invariant_check, impossible_state_in_database, reconciliation_failures
Measured by
none
Refactored by
validate_at_boundary, add_invariants, add_reconciliation, audit_data_changes
Enforced by
none
Before
const total = Number(a) + Number(b); save(total);
After
const total = Money.add(Money.parse(a), Money.parse(b)); save(total);

Lost Update

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Allow concurrent writers to overwrite each other without version checks, locks, compare-and-swap, or transaction isolation.
Detected by
last_write_wins_without_version, no_optimistic_lock, concurrent_update_defects
Measured by
none
Refactored by
optimistic_locking, pessimistic_locking, merge_policy, transaction_isolation
Enforced by
none
Before
const foo = await load(id); foo.count += 1; await save(foo);
After
await fooStore.update(id, { count: increment(1) }, { expectedVersion: foo.version });

Dual Write

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Write related state to two systems without atomicity, outbox, saga, reconciliation, or compensation.
Detected by
database_write_then_message_publish, two_databases_updated_without_transaction_or_outbox, manual_repair_needed
Measured by
none
Refactored by
transactional_outbox, saga, idempotent_consumer, reconciliation_job
Enforced by
none
Before
await db.save(foo); await searchIndex.add(foo);
After
await db.save(foo); await outbox.append(fooCreatedEvent(foo));

Read-Your-Writes Violation

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Let users or processes perform a write and then read from a stale replica, cache, projection, or eventually consistent view without explicit consistency contract.
Detected by
write_then_stale_read_defect, cache_not_invalidated_after_write, replica_read_after_write
Measured by
none
Refactored by
read_from_primary_after_write, invalidate_cache, show_pending_state, define_consistency_contract
Enforced by
none
Before
await primaryDb.write(foo); const view = await replicaDb.read(foo.id);
After
await primaryDb.write(foo); const view = await readAfterWrite(foo.id, { consistency: "read-your-writes" });

Security Theater

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Add visible security controls that do not reduce the actual threat model or can be bypassed by alternate paths.
Detected by
control_not_linked_to_threat, bypass_endpoint, client_only_security, audit_passes_but_attack_succeeds
Measured by
none
Refactored by
threat_model, server_side_enforcement, penetration_test, policy_as_code
Enforced by
none
Before
if (password.length > 0) grantFooAccess(user);
After
const verified = await verifyPassword(password, user.passwordHash); if (!verified) throw new UnauthorizedError(); grantFooAccess(user);

Authorization Scattering

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Spread authorization checks across controllers, services, repositories, UI, and ad hoc conditionals without a central policy model.
Detected by
repeated_role_checks, missing_policy_engine, endpoint_without_authz, inconsistent_resource_access
Measured by
none
Refactored by
centralize_policy, policy_as_code, ABAC_or_RBAC_model, authorization_tests
Enforced by
none
Before
if (user.role === "admin") deleteFoo(); if (user.role === "admin" || user.id === foo.owner) editFoo();
After
if (policy.can(user, "delete", foo)) deleteFoo(); if (policy.can(user, "edit", foo)) editFoo();

Secret Sprawl

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Store credentials, tokens, keys, certificates, or sensitive configuration across code, config files, logs, tickets, and local environments.
Detected by
secret_in_repo, secret_in_log, shared_static_token, manual_secret_distribution
Measured by
none
Refactored by
secret_manager, rotate_secret, scan_repository, least_privilege_credential
Enforced by
none
Before
const key = "sk_live_abc123"; const dbPass = "hunter2";
After
const key = await secrets.get("foo.api.key"); const dbPass = await secrets.get("foo.db.password");

PII Oversharing

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Collect, store, log, transmit, or expose more personal data than needed for the declared purpose.
Detected by
PII_in_logs, unused_sensitive_fields, broad_export, missing_data_minimization
Measured by
none
Refactored by
data_minimization, field_redaction, purpose_binding, retention_policy
Enforced by
none
Before
logger.info("created foo", { email: user.email, ssn: user.ssn });
After
logger.info("created foo", { userId: user.id });

Observability Noise

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Emit excessive, low-signal logs, metrics, traces, or alerts without severity, ownership, cardinality control, or actionability.
Detected by
high_alert_ack_without_action, high_cardinality_metrics, logs_without_context, duplicate_alerts
Measured by
none
Refactored by
define_signal_quality, reduce_cardinality, add_runbook_owner, sample_or_aggregate
Enforced by
none
Before
logger.info("entering loop"); for (const f of foos) logger.info("iter", f);
After
logger.info("foo.batch.processed", { count: foos.length, durationMs });

Log-as-Control-Flow

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Log errors or warnings as if logging itself handles the failure, while the system continues without recovery, propagation, or safe fallback.
Detected by
catch_log_continue, logged_error_without_return_or_throw, critical_log_no_alert
Measured by
none
Refactored by
return_typed_error, fail_fast_or_fallback, add_recovery_policy, alert_critical_failure
Enforced by
none
Before
if (lastFooLogLine.includes("FooReady")) startBarProcessor();
After
fooEvents.on("FooReady", startBarProcessor);

Manual Runbook Dependency

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Rely on humans to perform repeatable operational actions during incidents, deploys, migrations, or recovery.
Detected by
same_manual_incident_steps, manual_migration_sequence, operator_specific_knowledge
Measured by
none
Refactored by
automate_runbook, add_guardrails, validate_preconditions, record_execution_log
Enforced by
none
Before
const RUNBOOK = "on failure, ssh in and run restart-foo.sh";
After
health.onUnhealthy(() => orchestrator.restart("foo"));

Big-Bang Release

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Ship a large, irreversible, all-user change without staged rollout, feature flags, canary, rollback, or blast-radius control.
Detected by
no_canary, no_feature_flag, no_rollback_plan, large_release_batch
Measured by
none
Refactored by
feature_flag, canary_deploy, blue_green, rollback_plan, small_batch_release
Enforced by
none
Before
deployEverything("foo", "bar", "baz");
After
release("foo", { strategy: canary(0.1) });

Irreversible Migration

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Apply schema, data, or infrastructure changes that cannot safely run alongside old versions or be rolled back.
Detected by
drop_column_before_consumers_removed, destructive_data_transform_no_backup, no_backward_compatible_phase
Measured by
none
Refactored by
expand_contract_migration, backup, dual_read_write_temporarily, rollback_test
Enforced by
none
Before
await db.exec("ALTER TABLE foo DROP COLUMN legacy_name");
After
await migrate({ up: addFooName, down: restoreFooName });

Big-Upfront Frozen Architecture

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Lock in major architectural decisions before validating domain forces, quality attributes, operational realities, and change vectors.
Detected by
heavy_architecture_before_usage, ADR_without_evidence, future-proofing_without_feedback
Measured by
none
Enforced by
none
Before
const ARCHITECTURE = designAllModulesForNextFiveYears();
After
const foo = defineModule("foo", { exports: { createFoo } }); registry.add(foo);

Architecture Astronaut

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Prefer abstract frameworks, taxonomies, meta-models, and generic engines over concrete user, domain, and operational needs.
Detected by
generic_platform_before_product_need, few_real_consumers, high_framework_workaround_count
Measured by
none
Refactored by
anchor_to_use_cases, prove_with_vertical_slice, delete_unused_generality, measure_delivery_cost
Enforced by
none
Before
class AbstractFooMetaStrategyOrchestrationEngineFactory {}
After
class CreateFoo { execute(input: CreateFooInput): Foo {} }

Feature-Only Design

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Optimize architecture for immediate feature delivery while ignoring quality attributes such as security, operability, scalability, maintainability, and evolvability.
Detected by
no_SLOs, no_security_review, no_operability_requirements, quality_attribute_absent_from_ADR
Measured by
none
Refactored by
define_quality_scenarios, add_fitness_functions, architecture_review, risk_register
Enforced by
none
Before
function addFooFeature() { hack(); patch(); bypassLint(); }
After
function addFooFeature(input: CreateFooInput) { return createFoo.execute(input); }

Test Pyramid Inversion

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Rely mainly on slow, brittle end-to-end tests while unit, contract, component, and property tests are sparse.
Detected by
high_E2E_ratio, slow_CI, flaky_integration_tests, low_unit_contract_coverage
Measured by
none
Refactored by
add_unit_tests, contract_tests, component_tests, property_tests, reduce_E2E_scope
Enforced by
none
Before
test.e2e("create foo", fullBrowserFlow); test.e2e("rename foo", fullBrowserFlow); test.e2e("delete foo", fullBrowserFlow);
After
test.unit("FooValidator rejects an empty name", () => expect(() => validateFoo({ name: "" })).toThrow()); test.integration("FooRepository persists a Foo", async () => { await fooRepository.save(foo); expect(await fooRepository.find(foo.id)).toEqual(foo); }); test.e2e("the critical signup path", criticalPathOnly);

Mock Mirage

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Overuse mocks so tests verify internal calls rather than observable behavior or contracts.
Detected by
tests_fail_on_refactor_without_behavior_change, assert_called_everywhere, no_contract_tests
Measured by
none
Refactored by
test_observable_behavior, contract_test, use_fake_at_boundary, reduce_internal_mocks
Enforced by
none
Before
const store = { save: fn(), find: fn().returns(foo) };
After
const store = new InMemoryFooStore(); runFooStoreContract(store);

Flaky Test Normalization

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Accept intermittent test failures as normal and rerun until green instead of fixing nondeterminism or isolation defects.
Detected by
rerun_to_pass, quarantined_tests_never_fixed, time_order_random_test_failures
Measured by
none
Refactored by
isolate_state, control_time_randomness, fix_race, remove_external_dependency
Enforced by
none
Before
test.retry(5)("foo works sometimes", async () => { await sleep(random()); expect(await getFoo()).toBeTruthy(); });
After
test("foo is created deterministically", async () => { const foo = await createFoo.execute(input); expect(foo.id).toBe(expectedId); });

AI Prompt Sprawl

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Scatter prompts, retrieval rules, model parameters, safety instructions, and output schemas across code without versioning, evaluation, or ownership.
Detected by
prompt_literals_in_many_files, no_prompt_registry, no_eval_for_prompt_change, model_params_scattered
Measured by
none
Refactored by
prompt_registry, version_prompt, add_eval_suite, centralize_model_config
Enforced by
none
Before
const a = model.run("summarize this foo: " + foo); const b = model.run("pls summarize foo " + foo);
After
const summary = model.run(FOO_PROMPTS.summarize({ foo }));

Ungrounded AI Output

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Violated by
Generate answers, classifications, plans, or decisions without evidence retrieval, source references, confidence limits, or unsupported-claim handling.
Detected by
answer_without_sources_when_sources_required, no_retrieval_trace, unsupported_claims, confidence_not_disclosed
Measured by
none
Refactored by
RAG_boundary, evidence_citation, claim_validation, abstain_or_disclose_uncertainty
Enforced by
none
Before
const answer = await model.run(question); return answer;
After
const context = await retrieve(question); const answer = await model.run(FOO_PROMPTS.answer({ question, context })); return withCitations(answer, context);

Model Version Ambiguity

Details
Requires
none
Reinforces
none
Enables
none
In tension with
none
Conflicts with
none
Referenced by
Violated by
Use AI models, embeddings, prompts, or evaluation artifacts without recording version, configuration, dataset, or inference context.
Detected by
model_name_missing_version, embedding_index_unversioned, eval_results_without_config, prompt_not_versioned
Measured by
none
Refactored by
model_registry, version_prompt_dataset_index, record_inference_context, governance_log
Enforced by
none
Before
const result = await model.run(prompt);
After
const result = await model.run(prompt, { model: "foo-llm-2024-06", temperature: 0 }); logger.info("foo.inference", { model: result.model });

Architecture Review / Evolution / Governance Artifacts

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_assessment["Assessment"]
    n_architecture_review["Architecture Review"]
    n_design_review["Design Review"]
    n_code_review["Code Review"]
    n_impact_analysis["Impact Analysis"]
    n_gap_analysis["Gap Analysis"]
    n_fitness_functions["Fitness Functions"]
    n_quality_attributes["Quality Attributes"]
    n_architecture_decision_records["Architecture Decision Records (ADR)"]
    n_evolutionary_architecture["Evolutionary Architecture"]
    n_minimum_viable_architecture["Minimum Viable Architecture"]
    n_greenfield_development["Greenfield Development"]
    n_first_principles_design["First-Principles Design"]
    n_reference_architecture["Reference Architecture"]
    n_pattern_consistency["Pattern Consistency"]
    n_architectural_consistency["Architectural Consistency"]
    n_standardization["Standardization"]
    n_assessment --> n_quality_attributes
    n_architecture_review --> n_architecture_decision_records
    n_architecture_review --> n_architectural_consistency
    n_fitness_functions --> n_evolutionary_architecture
    n_quality_attributes --> n_architecture_review
    n_evolutionary_architecture --> n_fitness_functions
    n_greenfield_development --> n_first_principles_design
    n_reference_architecture --> n_standardization
    n_architectural_consistency --> n_pattern_consistency

Assessment

Details
Violated by
decisions without assessment criteria
Detected by
missing evaluation artifacts
Measured by
assessment coverage
Refactored by
Add Assessment Checklist/Report
Enforced by
review process
Before
approveFooArchitecture();
After
const assessment = assess(fooArchitecture, { dimensions: ["modularity", "reliability", "security", "operability"], evidence: collectArchitectureEvidence(fooSystem), }); requirePassingAssessment(assessment);

Architecture Review

Details
Violated by
major architecture change without review
Detected by
unapproved dependency/style changes
Measured by
review coverage
Refactored by
Add Review, Resolve Findings
Enforced by
pull request gates
Before
mergeFooDesign();
After
const review = architectureReview({ context: fooContext, decisions: fooDecisions, risks: fooRisks, qualityAttributes: fooQualityAttributes, }); review.requireApproval(["architecture-owner", "security-owner"]);

Design Review

Details
Violated by
complex feature without design check
Detected by
missing design record
Measured by
design review finding rate
Refactored by
Revise Design, Add Boundary/Contract
Enforced by
review checklist
Before
implementFooDesign(fooDesign);
After
const review = designReview(fooDesign, { contracts: validateContracts, failureModes: analyzeFailureModes, testability: assessTestability, }); if (!review.approved) throw new Error("design rejected");

Code Review

Details
Violated by
unreviewed production code changes
Detected by
missing approval/review
Measured by
review coverage, defect escape rate
Refactored by
Apply Review Feedback
Enforced by
branch protection
Before
git.merge(fooChange);
After
const review = codeReview(fooChange); review.require({ approvals: 2, passingChecks: ["tests", "types", "security", "architecture"] }); git.merge(review.approvedCommit);

Impact Analysis

Details
Violated by
breaking dependent behavior without awareness
Detected by
change touching dependencies without impact note
Measured by
affected component count
Refactored by
Add Dependency Map, Add Regression Tests
Enforced by
PR template, dependency tooling
Before
renameFooField("name", "label");
After
const impact = dependencyGraph.impactOf({ contract: "FooV1.name", change: "rename-to-label", }); for (const consumer of impact.consumers) requireMigration(consumer); renameFooField("name", "label");

Gap Analysis

Details
Violated by
missing comparison against required controls/principles
Detected by
unknown compliance/architecture status
Measured by
gap count/severity
Refactored by
Add Remediation Plan
Enforced by
governance process
Before
declareFooSystemReady();
After
const target = fooTargetArchitecture(); const current = inspectFooArchitecture(); const gaps = compareArchitecture(current, target); for (const gap of gaps) assignRemediation(gap);

Fitness Functions

Details
Violated by
architecture rule not continuously checked
Detected by
missing executable architecture checks
Measured by
fitness pass/fail trend
Refactored by
Add Fitness Test, Codify Rule
Enforced by
CI architecture tests
Before
architectureGuidelines.write("Foo domain must not import infrastructure");
After
const fitness = forbidImports({ from: "src/foo/domain/**", to: "src/foo/infrastructure/**" }); pipeline.enforce(fitness);

Quality Attributes

Details
Violated by
no explicit nonfunctional requirements
Detected by
missing quality scenarios/SLOs
Measured by
quality attribute scenario pass rate
Refactored by
Define Scenarios, Add Fitness Functions
Before
designFooService();
After
const attributes = defineQualityAttributes({ availability: "99.95%", p95LatencyMs: 200, recoveryTimeMinutes: 5, dataLossSeconds: 0, }); designFooService(attributes);

Architecture Decision Records (ADR)

Details
Violated by
major decision not recorded
Detected by
architecture change without ADR
Measured by
ADR coverage
Refactored by
Add ADR, Link to Change
Enforced by
PR template, review policy
Before
chooseFooDatabase("postgres");
After
const adr = recordDecision({ id: "ADR-0042", title: "Use PostgreSQL for Foo persistence", status: "accepted", context: fooPersistenceForces, decision: "postgres", consequences: fooPersistenceConsequences, });

Evolutionary Architecture

Details
Violated by
architecture decay without feedback loops
Detected by
accumulating unmeasured drift
Measured by
fitness trend, architecture debt
Refactored by
Add Fitness Functions, Refactor Incrementally
Enforced by
CI/CD architecture checks
Before
designFinalFooArchitecture(); freezeArchitectureForever();
After
const fooArchitecture = evolveArchitecture({ current: minimumFooArchitecture, fitnessFunctions: fooFitnessFunctions, nextChange: highestValueArchitectureChange, });

Minimum Viable Architecture

Details
Violated by
adding complex patterns before need
Detected by
unused abstractions/infrastructure
Measured by
architecture complexity vs need
Refactored by
Simplify, Defer Optional Mechanisms
Enforced by
Before
buildServiceMesh(); buildGlobalEventBus(); buildPluginPlatform(); createFooEndpoint();
After
const architecture = defineMinimumArchitecture({ useCase: "create-and-read-foo", components: ["foo-api", "foo-store"], deferredUntilForced: ["service-mesh", "plugin-platform"], });

Greenfield Development

Details
Violated by
premature irreversible architecture choices
Detected by
heavy structure without validated need
Measured by
initial complexity, adaptability
Refactored by
Start Modular, Add ADRs, Define Boundaries
Before
copyLegacyFooModule(); retainLegacyFooFlags(); retainLegacyFooSchema();
After
const fooSystem = designFromCurrentForces({ domain: fooDomain, constraints: currentConstraints, contracts: currentContracts, });

First-Principles Design

Details
Violated by
applying patterns without problem fit
Detected by
unjustified pattern selection
Measured by
decision rationale quality
Refactored by
Re-evaluate Constraints, Remove Misfit Pattern
Enforced by
ADR review
Before
useMicroservicesBecauseIndustryUsesMicroservices();
After
const forces = identifyForces(fooProblem); const invariants = deriveInvariants(forces); const design = synthesizeArchitecture({ forces, invariants });

Reference Architecture

Details
Violated by
inconsistent implementations without rationale
Detected by
deviation without ADR
Measured by
conformance/deviation rate
Refactored by
Align to Reference or Document Exception
Before
teamA.buildFooOneWay(); teamB.buildFooAnotherWay();
After
const fooReference = defineReferenceArchitecture({ modules: ["api", "application", "domain", "adapters"], allowedDependencies: fooDependencyRules, }); teamA.instantiate(fooReference); teamB.instantiate(fooReference);

Pattern Consistency

Details
Violated by
same problem solved with incompatible patterns
Detected by
inconsistent implementations of same concern
Measured by
pattern variance count
Refactored by
Normalize Pattern, Extract Shared Convention
Enforced by
linting, review, scaffolding
Before
fooModule.useRepository(); barModule.queryDatabaseDirectly(); bazModule.useActiveRecord();
After
const persistencePattern = "repository" as const; fooModule.use(persistencePattern); barModule.use(persistencePattern); bazModule.use(persistencePattern);

Architectural Consistency

Details
Violated by
unapproved boundary/layer/dependency deviations
Detected by
architecture fitness failures
Measured by
violation trend
Refactored by
Align Dependency/Layer/Boundary
Enforced by
architecture tests
Before
fooDomain.imports(sqlClient); barDomain.imports(httpClient);
After
architectureRules.enforce([ forbid("domain", "infrastructure"), requirePortFor("external-io"), ]);

Standardization

Details
Violated by
inconsistent tooling/formats/patterns
Detected by
standards deviation
Measured by
conformance rate
Refactored by
Normalize Tooling/Format/Pattern
Enforced by
CI policies, templates
Before
teamA.emit({ foo_id: foo.id }); teamB.emit({ id: foo.id, type: "foo" });
After
const FooCreatedV1 = standardEvent({ type: "FooCreated", version: 1, fields: { fooId: FooIdSchema }, }); teamA.emit(FooCreatedV1.create(foo)); teamB.emit(FooCreatedV1.create(foo));

Behavioral Patterns

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_strategy_pattern["Strategy Pattern"]
    n_template_method_pattern["Template Method Pattern"]
    n_observer_pattern["Observer Pattern"]
    n_mediator_pattern["Mediator Pattern"]
    n_command_pattern["Command Pattern"]
    n_state_pattern["State Pattern"]
    n_chain_of_responsibility_pattern["Chain of Responsibility Pattern"]
    n_iterator_pattern["Iterator Pattern"]
    n_visitor_pattern["Visitor Pattern"]
    n_memento_pattern["Memento Pattern"]
    n_null_object_pattern["Null Object Pattern"]
    n_finite_state_machine["Finite State Machine"]
    n_statecharts["Statecharts"]
    n_finite_state_machine --> n_state_pattern
    n_statecharts --> n_finite_state_machine
    n_statecharts --> n_finite_state_machine

Strategy Pattern

Details
Violated by
switch over behavior modes
Detected by
conditional strategy selection with duplicated behavior
Measured by
conditional complexity
Refactored by
Extract Strategy
Enforced by
complexity thresholds, review
Before
function priceFoo(kind: string, value: number) { if (kind === "standard") return value; if (kind === "double") return value * 2; return 0; }
After
interface FooPricing { price(value: number): number; } const standard: FooPricing = { price: value => value }; const doubled: FooPricing = { price: value => value * 2 }; function priceFoo(strategy: FooPricing, value: number) { return strategy.price(value); }

Template Method Pattern

Details
Violated by
copied workflows with small variations
Detected by
duplicated method sequences
Measured by
workflow duplication
Refactored by
Introduce Template Method
Enforced by
Before
function importJsonFoo(raw: string) { validateJson(raw); return saveFoo(parseJson(raw)); } function importCsvFoo(raw: string) { validateCsv(raw); return saveFoo(parseCsv(raw)); }
After
abstract class FooImporter { import(raw: string) { this.validate(raw); return saveFoo(this.parse(raw)); } protected abstract validate(raw: string): void; protected abstract parse(raw: string): Foo; }

Observer Pattern

Details
Violated by
hardcoded notification targets
Detected by
direct calls to multiple listeners
Measured by
subscriber coupling count
Refactored by
Introduce Observer/Event Publisher
Enforced by
event contract tests
Before
class FooEditor { save(foo: Foo) { fooStore.save(foo); refreshFooView(foo); sendFooEmail(foo); } }

Mediator Pattern

Details
Violated by
many-to-many object dependencies
Detected by
dense object dependency graph
Measured by
interaction graph density
Refactored by
Introduce Mediator
Enforced by
dependency graph checks
Before
fooEditor.notify(fooList, fooDetails, fooToolbar, foo); fooList.update(fooDetails, fooToolbar, foo);
After
class FooMediator { constructor(private readonly list: FooList, private readonly details: FooDetails) {} handle(event: FooEvent) { this.list.apply(event); this.details.apply(event); } }

Command Pattern

Details
Violated by
inline conditional dispatch on an action name
Detected by
switch/if chains selecting an operation to run
Measured by
dispatch-branch count per action site
Refactored by
Encapsulate Invocation as a Command object
Enforced by
Before
button.onClick = () => fooEditor.delete(foo.id);
After
interface FooCommand { execute(): void; undo(): void; } class DeleteFooCommand implements FooCommand { constructor(private readonly id: FooId) {} execute() { fooStore.delete(this.id); } undo() { fooStore.restore(this.id); } } history.run(new DeleteFooCommand(foo.id));

State Pattern

Details
Violated by
behavior branched on scattered status flags
Detected by
repeated conditionals on a status field
Measured by
status-conditional density
Refactored by
Replace State-Conditional with State objects
Enforced by
Before
function handleFoo(foo: Foo, event: string) { if (foo.status === "draft" && event === "submit") foo.status = "review"; if (foo.status === "review" && event === "approve") foo.status = "published"; }
After
interface FooState { submit(): FooState; approve(): FooState; } const published: FooState = { submit: () => published, approve: () => published }; const review: FooState = { submit: () => review, approve: () => published }; const draft: FooState = { submit: () => review, approve: () => draft }; class Foo { constructor(private state: FooState = draft) {} submit() { this.state = this.state.submit(); } approve() { this.state = this.state.approve(); } }

Chain of Responsibility Pattern

Details
Violated by
one handler with nested conditionals for every case
Detected by
long if/else ladders handling heterogeneous requests
Measured by
handler cyclomatic complexity
Refactored by
Extract Handler Chain
Enforced by
Before
function handleFoo(request: FooRequest) { if (request.size > MAX_SIZE) return reject(request); if (!request.authorized) return deny(request); return process(request); }
After
type FooHandler = (request: FooRequest, next: () => FooResult) => FooResult; const enforceSize: FooHandler = (request, next) => request.size > MAX_SIZE ? reject(request) : next(); const enforceAuth: FooHandler = (request, next) => request.authorized ? next() : deny(request); const chain = composeHandlers([enforceSize, enforceAuth, () => process(request)]); chain(request);

Iterator Pattern

Details
Violated by
callers walking a structure's internal fields directly
Detected by
index/pointer traversal of another type's internals
Measured by
internal-structure access count
Refactored by
Introduce Iterator
Enforced by
Before
for (let i = 0; i < fooTree.nodes.length; i += 1) visit(fooTree.nodes[i]);
After
class FooTree { #roots: FooNode[] = []; *[Symbol.iterator](): Iterator<Foo> { for (const node of this.#roots) yield* this.walk(node); } } for (const foo of fooTree) visit(foo);

Visitor Pattern

Details
Violated by
operations added by editing every element type
Detected by
type-tag switches repeated per operation
Measured by
type-switch duplication across operations
Refactored by
Introduce Visitor
Enforced by
Before
function renderFoo(node: FooNode) { if (node.kind === "text") return node.value; if (node.kind === "group") return node.children.map(renderFoo).join(""); }
After
interface FooVisitor<T> { text(node: TextNode): T; group(node: GroupNode): T; } class RenderFooVisitor implements FooVisitor<string> { text(node: TextNode) { return node.value; } group(node: GroupNode) { return node.children.map(child => child.accept(this)).join(""); } }

Memento Pattern

Details
Violated by
callers copying an object's private fields to save state
Detected by
external code reconstructing internal state
Measured by
private-field external access count
Refactored by
Capture State as a Memento
Enforced by
Before
const backupName = foo.name; const backupTags = [...foo.tags]; foo.rename(newName); if (cancelled) { foo.name = backupName; foo.tags = backupTags; }
After
class FooMemento { constructor(readonly snapshot: Readonly<Foo>) {} } const memento = foo.save(); foo.rename(newName); if (cancelled) foo.restore(memento);

Null Object Pattern

Details
Violated by
null-guards scattered across every call site
Detected by
repeated null checks before the same operation
Measured by
null-guard density
Refactored by
Introduce Null Object
Enforced by
Before
const logger = config.logger; if (logger) logger.info("foo saved");
After
interface FooLogger { info(message: string): void; } const NoopFooLogger: FooLogger = { info() {} }; const logger = config.logger ?? NoopFooLogger; logger.info("foo saved");

Finite State Machine

Details
Violated by
behavior driven by ad-hoc combinations of scattered status booleans
Detected by
impossible or contradictory state combinations reachable at runtime
Measured by
count of representable-but-illegal states
Refactored by
Model states and transitions as an explicit FSM
Enforced by
state model review
Before
let isOpen = false, isLoading = false, isError = false; function onClick() { isLoading = true; if (isOpen) isOpen = false; }
After
type FooState = "closed" | "loading" | "open" | "error"; const transitions: Record<FooState, Partial<Record<FooEvent, FooState>>> = { closed: { open: "loading" }, loading: { ready: "open", fail: "error" }, open: { close: "closed" }, error: { retry: "loading" }, }; function next(state: FooState, event: FooEvent): FooState { return transitions[state][event] ?? state; }

Statecharts

Details
Violated by
a flat FSM duplicating shared transitions across many near-identical states
Detected by
combinatorial state growth from independent concerns modeled in one flat machine
Measured by
transition duplication across sibling states
Refactored by
Introduce nested and parallel statechart regions
Enforced by
state model review
Before
type S = "idleMuted" | "idleLoud" | "playingMuted" | "playingLoud";
After
const fooChart = { initial: "idle", states: { idle: {}, playing: {} }, parallel: { volume: { states: { muted: {}, loud: {} } } }, };

Causality / Ordering / Distributed Time

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_causality["Causality"]
    n_causal_consistency["Causal Consistency"]
    n_happens_before_relationship["Happens-Before Relationship"]
    n_event_ordering["Event Ordering"]
    n_causal_dependency["Causal Dependency"]
    n_dependency_graph["Dependency Graph"]
    n_directed_acyclic_graph["Directed Acyclic Graph (DAG)"]
    n_vector_clocks["Vector Clocks"]
    n_lamport_clocks["Lamport Clocks"]
    n_hybrid_logical_clocks["Hybrid Logical Clocks"]
    n_crdts["CRDTs"]
    n_total_order_broadcast["Total-Order Broadcast"]
    n_cap_theorem["CAP Theorem"]
    n_pacelc_theorem["PACELC Theorem"]
    n_causality --> n_event_ordering
    n_event_ordering --> n_causality
    n_causal_dependency --> n_causality
    n_vector_clocks --> n_causal_consistency
    n_hybrid_logical_clocks --> n_happens_before_relationship
    n_hybrid_logical_clocks --> n_causal_consistency
    n_hybrid_logical_clocks --> n_event_ordering
    n_crdts --> n_causal_consistency
    n_total_order_broadcast --> n_event_ordering
    n_cap_theorem --> n_causal_consistency
    n_pacelc_theorem --> n_cap_theorem
    n_pacelc_theorem --> n_cap_theorem

Causality

Details
Violated by
processing effects without known cause/order
Detected by
missing causation/correlation metadata
Measured by
causal trace completeness
Refactored by
Add Causation ID, Add Ordering Rules
Enforced by
event schema and workflow tests
Before
events.push({ type: "BarCreated", at: Date.now() }); events.push({ type: "FooCreated", at: Date.now() });
After
const fooCreated = append({ type: "FooCreated" }); append({ type: "BarCreated", causedBy: fooCreated.id });

Causal Consistency

Details
Violated by
observing effect before cause
Detected by
order anomaly tests
Measured by
causal anomaly rate
Refactored by
Add Causal Metadata, Enforce Read-Your-Writes
Enforced by
consistency tests
Before
replica.apply(barCreated); replica.apply(fooCreated);
After
replica.applyWhenReady(barCreated, { requires: [fooCreated.id], }); replica.apply(fooCreated);

Happens-Before Relationship

Details
Violated by
assuming unordered operations are ordered
Detected by
race detectors, missing synchronization
Measured by
ordering violation count
Refactored by
Add Synchronization, Add Ordering Constraint
Enforced by
concurrency tests
Before
const a = { id: "a", at: Date.now() }; const b = { id: "b", at: Date.now() };
After
const a = { id: "a", ordinal: 1 }; const b = { id: "b", ordinal: 2, after: [a.id] }; assert(happensBefore(a, b));

Event Ordering

Details
Violated by
stateful consumers processing out of order
Detected by
missing ordering key/sequence checks
Measured by
out-of-order rate
Refactored by
Add Partition Key, Sequence Number, Reorder Buffer
Enforced by
stream config, consumer tests
Before
events.sort((a, b) => a.timestamp - b.timestamp);
After
events.sort((a, b) => a.streamOrdinal - b.streamOrdinal);

Causal Dependency

Details
Violated by
implicit dependency not represented in workflow/event metadata
Detected by
undocumented call/event dependency
Measured by
hidden dependency count
Refactored by
Declare Dependency, Add Causation Link
Enforced by
dependency graph checks
Before
processBar(barEvent);
After
if (!projection.has(barEvent.fooEventId)) defer(barEvent); else processBar(barEvent);

Dependency Graph

Details
Violated by
undeclared dependencies
Detected by
graph extraction mismatch
Measured by
cycle count, graph density
Refactored by
Break Cycle, Invert Dependency
Enforced by
dependency graph CI checks
Before
const tasks = [loadFoo, buildBar, publishBaz]; await Promise.all(tasks.map(task => task()));
After
const graph = new DependencyGraph(); graph.add("buildBar", { dependsOn: ["loadFoo"] }); graph.add("publishBaz", { dependsOn: ["buildBar"] }); await graph.execute();

Directed Acyclic Graph (DAG)

  • Kind: constraint
  • Severity: mandatory for dependency architecture
  • Scope: dependency graph, workflow, build
  • Layer: Causality Core
Details
Violated by
dependency cycle
Detected by
Measured by
cycle count
Refactored by
Invert Dependency, Extract Interface, Split Module
Enforced by
graph checks
Before
graph.addEdge("foo", "bar"); graph.addEdge("bar", "foo");
After
const dag = new Dag(); dag.addEdge("foo", "bar"); if (dag.wouldCreateCycle("bar", "foo")) throw new Error("cycle rejected");

Vector Clocks

Details
Violated by
unresolved concurrent writes
Detected by
lost causality in distributed updates
Measured by
conflict detection accuracy
Refactored by
Add Version Vector
Enforced by
replication protocol tests
Before
const winner = a.updatedAt > b.updatedAt ? a : b;
After
const relation = compareVectorClocks(a.clock, b.clock); if (relation === "concurrent") return mergeFoo(a, b); return relation === "after" ? a : b;

Lamport Clocks

Details
Violated by
ordering by unsynchronized wall clocks
Detected by
timestamp ordering anomalies
Measured by
ordering anomaly rate
Refactored by
Add Logical Clock
Enforced by
protocol tests
Before
const event = { at: Date.now(), value: foo };
After
const event = { logicalTime: lamport.tick(), value: foo }; lamport.observe(remoteEvent.logicalTime);

Hybrid Logical Clocks

  • Kind: mechanism
  • Severity: mandatory for distributed systems
  • Scope: event, distributed state, time
  • Layer: Causality Core
Details
Violated by
ordering events solely by wall-clock timestamps
Detected by
last-writer-wins on physical time
Measured by
out-of-causal-order event rate
Refactored by
Adopt Hybrid Logical Clocks
Enforced by
distributed-systems review
Before
const event = { at: Date.now(), value: foo };
After
const event = { hlc: hlc.now(), value: foo }; hlc.update(remoteEvent.hlc);

CRDTs

Details
Violated by
concurrent replica edits silently overwriting each other
Detected by
lost updates under concurrent replication
Measured by
merge-conflict data-loss rate
Refactored by
Model State as a CRDT
Enforced by
replication design review
Before
foo.tags = incoming.updatedAt > foo.updatedAt ? incoming.tags : foo.tags;
After
foo.tags = orSet.merge(foo.tags, incoming.tags);

Total-Order Broadcast

  • Kind: mechanism
  • Severity: mandatory for distributed systems
  • Scope: event, distributed state, ordering
  • Layer: Causality Core
Details
Violated by
replicas applying events in divergent orders
Detected by
state divergence across nodes given same events
Measured by
cross-node order divergence rate
Refactored by
Introduce Total-Order Broadcast
Enforced by
distributed-systems review
Before
replica.apply(event);
After
const sequenced = await totalOrder.broadcast(event); replica.applyInOrder(sequenced.sequence, sequenced.event);

CAP Theorem

  • Kind: model
  • Severity: mandatory for distributed systems
  • Scope: distributed state, consistency, availability
  • Layer: Causality Core
Details
Violated by
a distributed store assumed to be both strongly consistent and fully available under partition
Detected by
split-brain writes or stalls during network partitions
Measured by
consistency/availability violations during partition events
Refactored by
Choose CP or AP explicitly per data class under partition
Enforced by
distributed-systems review
Before
await Promise.all(replicas.map(r => r.write(foo))); return "always consistent and available";
After
const policy = partitionPolicyFor(foo.class); return policy === "CP" ? writeWithQuorum(foo) : writeAvailableAndReconcile(foo);

PACELC Theorem

  • Kind: model
  • Severity: contextual
  • Scope: distributed state, consistency, latency
  • Layer: Causality Core
Details
Violated by
consistency treated as free when the network is healthy, ignoring the latency it costs
Detected by
tail latency driven by synchronous cross-region consistency during normal operation
Measured by
latency-vs-staleness tradeoff per read class
Refactored by
Decide else-branch latency-vs-consistency per read class (PACELC)
Enforced by
distributed-systems review
Before
const foo = await readFromAllRegionsStrongly(id);
After
const foo = tolerateStaleness(id.class) ? await readLocalReplica(id) : await readStronglyAcrossRegions(id);

Codebase / System Architecture Styles

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_ports_and_adapters_architecture["Ports and Adapters Architecture"]
    n_hexagonal_architecture["Hexagonal Architecture"]
    n_clean_architecture["Clean Architecture"]
    n_layered_architecture["Layered Architecture"]
    n_component_based_architecture["Component-Based Architecture"]
    n_package_by_feature["Package by Feature"]
    n_microservices["Microservices"]
    n_monolith_architecture["Monolith Architecture"]
    n_pipes_and_filters["Pipes and Filters"]
    n_service_oriented_architecture["Service-Oriented Architecture"]
    n_space_based_architecture["Space-Based Architecture"]
    n_hexagonal_architecture --> n_clean_architecture

Ports and Adapters Architecture

Details
Violated by
domain/application importing infrastructure
Detected by
inward/outward dependency violations
Measured by
adapter coverage, boundary purity
Refactored by
Introduce Port, Extract Adapter
Enforced by
layer dependency rules
Before
class FooService { save(foo: Foo) { return sql.query("insert into foo values (?)", foo); } }
After
interface SaveFooPort { save(foo: Foo): Promise<void>; } class FooService { constructor(private readonly port: SaveFooPort) {} save(foo: Foo) { return this.port.save(foo); } } class SqlFooAdapter implements SaveFooPort { save(foo: Foo) { return sqlFooStore.save(foo); } }

Hexagonal Architecture

Details
Violated by
framework/data types in core
Detected by
dependency direction violations
Measured by
core purity score
Refactored by
Move Framework Outward, Add Ports
Enforced by
architecture tests
Before
app.post("/foo", async request => sqlFooStore.save(await request.json()));
After
class CreateFooUseCase { constructor(private readonly foos: FooRepository, private readonly events: EventPublisher) {} execute(input: CreateFoo) { return createFooCore(input, this.foos, this.events); } } httpAdapter.bind("POST", "/foo", input => useCase.execute(input));

Clean Architecture

Details
Violated by
outer layers imported by inner layers
Detected by
dependency rule violations
Measured by
inward dependency compliance
Refactored by
Move Logic Inward, Extract Interface, Add Adapter
Enforced by
dependency graph rules
Before
class FooController { async create(request: Request) { return orm.foo.create(await request.json()); } }
After
interface CreateFooGateway { save(foo: Foo): Promise<void>; } class CreateFooInteractor { constructor(private readonly gateway: CreateFooGateway) {} execute(input: CreateFooInput) { return this.gateway.save(Foo.create(input)); } } class FooController { constructor(private readonly useCase: CreateFooInteractor) {} }

Layered Architecture

Details
Violated by
presentation accessing persistence directly
Detected by
forbidden layer imports
Measured by
layer violation count
Refactored by
Move Logic, Introduce Service/Repository Boundary
Enforced by
layer rules
Before
function createFoo(request: Request) { return sql.query("insert into foo values (?)", JSON.parse(request.body)); }
After
class FooController { constructor(private readonly service: FooService) {} } class FooService { constructor(private readonly repository: FooRepository) {} } class SqlFooRepository implements FooRepository { save(foo: Foo) { return fooTable.insert(foo); } }

Component-Based Architecture

Details
Violated by
component internals accessed externally
Detected by
boundary import violations
Measured by
component cohesion/coupling
Refactored by
Extract Component, Define Contract
Enforced by
component ownership rules
Before
const app = { createFoo, createBar, renderFoo, saveBar, publishBaz, };
After
const fooComponent = defineComponent({ name: "foo", exports: { createFoo, FooView }, requires: { FooStore, EventBus }, });

Package by Feature

Details
Violated by
feature logic scattered across technical folders
Detected by
change sets spanning many layer packages
Measured by
change locality
Refactored by
Repackage by Feature, Move Classes
Enforced by
package conventions
Before
src/controllers/foo.ts src/controllers/bar.ts src/services/foo.ts src/services/bar.ts src/repositories/foo.ts src/repositories/bar.ts
After
src/foo/controller.ts src/foo/service.ts src/foo/repository.ts src/bar/controller.ts src/bar/service.ts src/bar/repository.ts

Microservices

Details
Violated by
shared databases, synchronous service chains
Detected by
deployment coupling, cross-service transactions
Measured by
deploy independence, coupling metrics
Refactored by
Split Service, Own Data, Add Events
Enforced by
service ownership, API contracts
Before
class SharedApplication { createFoo(foo: Foo) { return sharedDb.insert("foo", foo); } createBar(bar: Bar) { return sharedDb.insert("bar", bar); } }
After
class FooService { constructor(private readonly fooStore: FooStore, private readonly outbox: Outbox) {} create(foo: Foo) { return transact(() => [this.fooStore.save(foo), this.outbox.append(fooCreated(foo))]); } } class BarService { constructor(private readonly barStore: BarStore) {} }

Monolith Architecture

Details
Violated by
unclear internal boundaries
Detected by
cyclic packages, high global coupling
Measured by
module boundary health
Refactored by
Modularize Internally, Add Boundaries
Enforced by
modular monolith rules
Before
await http.post("foo-service", foo); await http.post("bar-service", bar); await http.post("baz-service", baz);
After
class ModularMonolith { constructor(readonly foo: FooModule, readonly bar: BarModule, readonly baz: BazModule) {} } await app.foo.create(foo); await app.bar.create(bar);

Pipes and Filters

  • Kind: style
  • Severity: recommended
  • Scope: application, data processing, composition
  • Layer: Structural Core
Details
Violated by
one function performing every transform step inline
Detected by
long sequential transform bodies
Measured by
transform-step count per function
Refactored by
Extract Filters, Connect via Pipeline
Enforced by
Before
function processFoo(raw: string) { const parsed = parseFoo(raw); const cleaned = cleanFoo(parsed); return enrichFoo(cleaned); }
After
const filters: FooFilter[] = [parseFoo, cleanFoo, enrichFoo]; const fooPipeline = connect(filters); fooPipeline.run(raw);

Service-Oriented Architecture

Details
Violated by
capabilities bundled in one application object
Detected by
unrelated operations sharing one class/module
Measured by
capability cohesion per module
Refactored by
Expose Capabilities as Contracted Services
Before
class Application { createFoo() {} createBar() {} createBaz() {} }
After
const fooService = registerService("FooService", { create: createFoo }, { contract: FooServiceContract }); serviceBus.expose(fooService);

Space-Based Architecture

  • Kind: style
  • Severity: contextual
  • Scope: application, scalability, distributed state
  • Layer: Structural Core
Details
Violated by
all reads/writes funneled through one central database
Detected by
single datastore as the scaling limit
Measured by
central-datastore contention rate
Refactored by
Adopt a Replicated Data Space
Before
const foo = await centralDatabase.find(id);
After
const foo = await fooSpace.read(id); fooSpace.on("write", replicateToPeers);

Contracts / Interfaces / Compatibility

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_design_by_contract["Design by Contract"]
    n_explicit_contracts["Explicit Contracts"]
    n_stable_interfaces["Stable Interfaces"]
    n_interface_based_design["Interface-Based Design"]
    n_contract_first_design["Contract-First Design"]
    n_api_contract["API Contract"]
    n_service_contract["Service Contract"]
    n_data_contract["Data Contract"]
    n_schema_contract["Schema Contract"]
    n_semantic_contracts["Semantic Contracts"]
    n_preconditions["Preconditions"]
    n_postconditions["Postconditions"]
    n_invariants["Invariants"]
    n_backward_compatibility["Backward Compatibility"]
    n_forward_compatibility["Forward Compatibility"]
    n_versioning["Versioning"]
    n_protocol_compatibility["Protocol Compatibility"]
    n_interoperability["Interoperability"]
    n_uniform_interface["Uniform Interface"]
    n_consumer_driven_contracts["Consumer-Driven Contracts"]
    n_design_by_contract --> n_preconditions
    n_design_by_contract --> n_postconditions
    n_design_by_contract --> n_invariants
    n_explicit_contracts --> n_stable_interfaces
    n_explicit_contracts --> n_interoperability
    n_explicit_contracts --> n_contract_first_design
    n_stable_interfaces --> n_versioning
    n_stable_interfaces --> n_backward_compatibility
    n_interface_based_design --> n_stable_interfaces
    n_contract_first_design --> n_explicit_contracts
    n_contract_first_design --> n_schema_contract
    n_contract_first_design --> n_interoperability
    n_contract_first_design --> n_backward_compatibility
    n_api_contract --> n_versioning
    n_api_contract --> n_stable_interfaces
    n_api_contract --> n_interoperability
    n_service_contract --> n_api_contract
    n_data_contract --> n_interoperability
    n_schema_contract --> n_data_contract
    n_preconditions --> n_design_by_contract
    n_postconditions --> n_invariants
    n_backward_compatibility --> n_versioning
    n_backward_compatibility --> n_stable_interfaces
    n_versioning --> n_stable_interfaces
    n_versioning --> n_backward_compatibility
    n_protocol_compatibility --> n_versioning
    n_protocol_compatibility --> n_interoperability
    n_consumer_driven_contracts --> n_explicit_contracts
    n_consumer_driven_contracts --> n_backward_compatibility
    n_consumer_driven_contracts --> n_contract_first_design

Design by Contract

Details
Violated by
undocumented assumptions, unchecked inputs
Detected by
missing assertions, missing validation, vague public APIs
Measured by
contract coverage
Refactored by
Add Preconditions, Add Postconditions, Add Invariants
Enforced by
assertions, contract tests, static analysis
Before
function divideFoo(total: number, count: number) { return total / count; }
After
function divideFoo(total: number, count: number): number { if (!Number.isFinite(total)) throw new Error("pre: total must be finite"); if (!Number.isInteger(count) || count <= 0) throw new Error("pre: count must be positive"); const result = total / count; if (!Number.isFinite(result)) throw new Error("post: result must be finite"); return result; }

Explicit Contracts

Details
Violated by
untyped boundaries, undocumented payloads
Detected by
public methods without DTO/schema, dynamic maps at boundaries
Measured by
boundary contract coverage
Refactored by
Add DTO, Add Schema, Add Interface
Enforced by
schema validation, API linting
Before
function saveFoo(foo: any): any { return fooStore.save(foo); }
After
interface SaveFoo { execute(input: Readonly<{ id: FooId; name: string }>): Promise<{ saved: true; version: number }>; } const saveFoo: SaveFoo = { execute: input => fooStore.save(input) };

Stable Interfaces

Details
Violated by
signature churn, schema drift
Detected by
incompatible API diffs
Measured by
breaking-change frequency
Refactored by
Add Version, Add Adapter, Deprecate Gradually
Enforced by
API diff checks, contract tests
Before
class FooService { createFoo(name: string, tags: string[], notify: boolean, source: string) {} }
After
type CreateFooRequest = Readonly<{ name: string; tags: readonly string[]; extensions: Readonly<Record<string, unknown>>; }>; interface FooService { create(request: CreateFooRequest): Promise<FooId>; }

Interface-Based Design

Details
Violated by
direct dependency on implementations
Detected by
concrete constructor dependencies
Measured by
interface-to-implementation boundary ratio
Refactored by
Extract Interface, Inject Dependency
Enforced by
dependency rules
Before
function processFoo(store: SqlFooStore, foo: Foo) { return store.insert(foo); }
After
interface FooWriter { save(foo: Foo): Promise<void>; } function processFoo(store: FooWriter, foo: Foo) { return store.save(foo); }

Contract-First Design

Details
Violated by
generated contracts from unstable implementation
Detected by
absent contract before implementation
Measured by
contract-first coverage
Refactored by
Define Contract, Generate Stubs, Add Contract Tests
Enforced by
CI contract gates
Before
app.post("/foo", async request => fooStore.save(await request.json()));
After
type CreateFooRequest = { name: string }; type CreateFooResponse = { id: FooId; version: 1 }; interface CreateFooContract { request: CreateFooRequest; response: CreateFooResponse; } app.post("/foo", implement<CreateFooContract>(createFoo));

API Contract

Details
Violated by
undocumented endpoints, inconsistent status/error formats
Detected by
OpenAPI drift, missing endpoint schemas
Measured by
contract coverage, breaking diff count
Refactored by
Add OpenAPI, Normalize Responses, Version API
Enforced by
OpenAPI linting, contract tests
Before
app.get("/foo/:id", async request => fooStore.find(request.params.id));
After
const getFooApi = endpoint({ method: "GET", path: "/v1/foo/{id}", request: FooIdSchema, response: FooResponseSchema, errors: ["FOO_NOT_FOUND"] as const, });

Service Contract

Details
Violated by
undocumented side effects, unstable service behavior
Detected by
consumer failures after service changes
Measured by
consumer contract pass rate
Refactored by
Add Consumer Contract, Define SLA, Version Service
Enforced by
contract tests, deployment gates
Before
class FooClient { create(body: any) { return http.post("/foo", body); } }
After
interface FooServiceContract { create(input: CreateFoo): Promise<Result<FooCreated, FooError>>; } class FooClient implements FooServiceContract { create(input: CreateFoo) { return transport.call("Foo.Create", input); } }

Data Contract

Details
Violated by
untyped maps, implicit fields, undocumented nullability
Detected by
data validation failures, schema mismatch
Measured by
schema conformance rate
Refactored by
Add DTO, Add Schema, Normalize Field Semantics
Enforced by
schema registry, validation gates
Before
type FooMessage = Record<string, unknown>; queue.publish("foo", payload);
After
type FooMessageV1 = Readonly<{ type: "FooCreated"; version: 1; fooId: FooId; name: string; }>; queue.publish<FooMessageV1>("foo.created.v1", message);

Schema Contract

Details
Violated by
unvalidated payloads, undocumented field changes
Detected by
schema diff failures
Measured by
schema validation coverage
Refactored by
Add JSON Schema, Protobuf, Avro, OpenAPI
Enforced by
schema registry, CI schema checks
Before
const foo = JSON.parse(raw) as Foo;
After
const FooSchema = object({ id: string(), count: integer() }); const foo: Foo = FooSchema.parse(JSON.parse(raw));

Semantic Contracts

Details
Violated by
same term with different meanings
Detected by
conflicting field meanings, overloaded names
Measured by
semantic conflict count
Refactored by
Rename, Introduce Bounded Context, Add Anti-Corruption Layer
Enforced by
domain glossary, contract review
Before
function reserveFoo(count: number) { return fooStore.decrement(count); }
After
type PositiveCount = number & { readonly __brand: "PositiveCount" }; function reserveFoo(count: PositiveCount): Promise<{ reserved: true }> { return fooInventory.reserveExactly(count); }

Preconditions

Details
Violated by
accepting invalid state/input
Detected by
missing validation before state transition
Measured by
invalid-input handling coverage
Refactored by
Add Guard Clause, Add Validator
Before
function renameFoo(foo: Foo, name: string) { foo.name = name; }
After
function renameFoo(foo: Foo, name: string) { if (foo.status !== "active") throw new Error("pre: Foo must be active"); if (name.trim().length === 0) throw new Error("pre: name required"); foo.rename(name.trim()); }

Postconditions

Details
Violated by
returning invalid output state
Detected by
missing assertions on results
Measured by
property test coverage
Refactored by
Add Assertions, Add Result Type, Add Contract Tests
Enforced by
property tests, invariant checks
Before
async function createFoo(foo: Foo) { return fooStore.save(foo); }
After
async function createFoo(foo: Foo): Promise<FooId> { await fooStore.save(foo); const saved = await fooStore.find(foo.id); if (!saved) throw new Error("post: Foo must be persisted"); return saved.id; }

Invariants

Details
Violated by
invalid domain states, broken aggregate rules
Detected by
mutable public state, missing invariant checks
Measured by
invariant test coverage
Refactored by
Encapsulate State, Add Factory, Add Validation
Enforced by
domain tests, constructors, type system
Before
class FooAccount { balance = 0; withdraw(amount: number) { this.balance -= amount; } }
After
class FooAccount { #balance = 0; withdraw(amount: number) { if (amount <= 0 || amount > this.#balance) throw new Error("invariant: balance >= 0"); this.#balance -= amount; } }

Backward Compatibility

Details
Violated by
removing fields, changing semantics, narrowing types
Detected by
API/schema diff
Measured by
breaking-change count
Refactored by
Add Version, Deprecate, Add Adapter
Enforced by
compatibility tests, API diff gates
Before
app.get("/foo", () => ({ label: "Foo", tags: [] }));
After
app.get("/v1/foo", () => ({ name: "Foo" })); app.get("/v2/foo", () => ({ label: "Foo", tags: [] }));

Forward Compatibility

Details
Violated by
rejecting unknown safe fields
Detected by
parser failures on additive changes
Measured by
forward-compatibility test pass rate
Refactored by
Add Extension Points, Ignore Unknown Fields Safely
Enforced by
compatibility test matrix
Before
function readFoo(input: { name: string }) { if (Object.keys(input).length !== 1) throw new Error("unknown field"); return input.name; }
After
type FooEnvelope = { name: string; extensions?: Record<string, unknown> }; function readFoo(input: FooEnvelope) { return { name: input.name, extensions: input.extensions ?? {} }; }

Versioning

Details
Violated by
unversioned breaking changes
Detected by
incompatible diff without version bump
Measured by
version compliance, deprecation window
Refactored by
Add Semantic Versioning, Add API Version
Enforced by
release gates, API checks
Before
queue.publish("foo.created", { id: foo.id, name: foo.name });
After
queue.publish("foo.created.v2", { schemaVersion: 2, id: foo.id, label: foo.name, });

Protocol Compatibility

Details
Violated by
unsupported protocol changes
Detected by
protocol conformance failure
Measured by
conformance test pass rate
Refactored by
Add Adapter, Normalize Protocol
Enforced by
conformance tests
Before
socket.send(JSON.stringify({ action: "save", foo }));
After
type FooFrameV1 = { protocol: "foo/1"; type: "save"; payload: Foo }; socket.send(encodeFrame<FooFrameV1>({ protocol: "foo/1", type: "save", payload: foo }));

Interoperability

Details
Violated by
incompatible formats, hidden assumptions
Detected by
integration test failures
Measured by
interoperability test coverage
Refactored by
Standardize Format, Add Adapter, Add Schema
Enforced by
contract tests, standards checks
Before
fooClient.send(serializeWithPrivateFormat(foo));
After
const payload: JsonFooV1 = toJsonFooV1(foo); fooClient.send(JSON.stringify(payload), { contentType: "application/json" });

Uniform Interface

Details
Violated by
inconsistent verbs, response shapes, error formats
Detected by
API lint violations
Measured by
endpoint consistency score
Refactored by
Normalize API, Standardize Error Model
Enforced by
API style guide, OpenAPI linting
Before
fooApi.createFoo(foo); barApi.post("/bar", bar); bazApi.execute("DELETE_BAZ", baz.id);
After
resourceClient.post("/foos", foo); resourceClient.post("/bars", bar); resourceClient.delete(`/bazes/${baz.id}`);

Consumer-Driven Contracts

Details
Violated by
providers changing responses with no consumer expectation check
Detected by
integration breaks discovered only in production
Measured by
consumer-break incident rate
Refactored by
Introduce Consumer-Driven Contract tests
Enforced by
contract test gate
Before
fooProvider.deploy(newFooApi);
After
const expectations = collectContractsFrom(["bar-service", "baz-service"]); const result = verifyProvider(newFooApi, expectations); if (!result.satisfied) throw new BrokenConsumerContractError(result.violations); fooProvider.deploy(newFooApi);

Control / Coordination / Centralization

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_control_plane["Control Plane"]
    n_orchestration["Orchestration"]
    n_centralized_configuration["Centralized Configuration"]
    n_centralized_authentication["Centralized Authentication"]
    n_centralized_logging["Centralized Logging"]
    n_decentralization["Decentralization"]
    n_leader_election["Leader Election"]
    n_consensus["Consensus"]
    n_choreography["Choreography"]
    n_control_plane --> n_orchestration
    n_orchestration --> n_control_plane
    n_leader_election --> n_consensus
    n_leader_election --> n_control_plane
    n_choreography --> n_decentralization

Control Plane

Details
Violated by
unmanaged distributed configuration/control
Detected by
manual node/service control
Measured by
control coverage, control-plane availability
Refactored by
Add Control Plane, Externalize Policy
Enforced by
platform architecture
Before
for (const node of fooNodes) { node.configure({ retries: 3, timeoutMs: 500 }); }
After
controlPlane.apply("foo-service", { retries: 3, timeoutMs: 500, rollout: "progressive", });

Orchestration

Details
Violated by
implicit fragile workflow spread across services
Detected by
unclear workflow ownership
Measured by
workflow observability/completion
Refactored by
Add Orchestrator, Define Workflow
Enforced by
workflow tests
Before
await fooService.create(foo); await barService.create(bar); await bazService.create(baz);
After
await orchestrator.run("CreateFooFlow", { steps: [ step("foo", () => fooService.create(foo)), step("bar", () => barService.create(bar)), step("baz", () => bazService.create(baz)), ], });

Centralized Configuration

Details
Violated by
duplicated divergent configs
Detected by
config drift
Measured by
config drift count
Refactored by
Move to Central Config, Add Schema
Enforced by
config policy
Before
const fooConfig = loadLocalFooConfig(); const barConfig = loadLocalBarConfig(); const bazConfig = loadLocalBazConfig();
After
const config = await configService.readVersioned("platform/v3"); fooApp.apply(config.foo); barApp.apply(config.bar); bazApp.apply(config.baz);

Centralized Authentication

Details
Violated by
custom auth per service without federation
Detected by
duplicated credential stores
Measured by
auth centralization coverage
Refactored by
Introduce IdP, Federate Auth
Enforced by
Before
fooService.verifyToken(token); barService.verifyToken(token); bazService.verifyToken(token);
After
const identity = await identityProvider.authenticate(token); await fooService.handle({ identity }); await barService.handle({ identity }); await bazService.handle({ identity });

Centralized Logging

Details
Violated by
logs only available per instance
Detected by
missing log shipping
Measured by
log ingestion coverage
Refactored by
Add Log Forwarder, Standardize Fields
Enforced by
observability policy
Before
fooService.writeLocalLog(event); barService.writeLocalLog(event); bazService.writeLocalLog(event);
After
const sink = new CentralLogSink(); fooService.useLogger(structuredLogger(sink)); barService.useLogger(structuredLogger(sink)); bazService.useLogger(structuredLogger(sink));

Decentralization

Details
Violated by
central bottleneck for independent decisions/runtime
Detected by
centralized team/service dependency
Measured by
decision/deployment dependency count
Refactored by
Delegate Ownership, Split Service/Control
Enforced by
ownership model
Before
const coordinator = new GlobalFooCoordinator(); await coordinator.approveEveryFoo(foo);
After
await fooNode.validate(foo); await fooNode.commit(foo); await fooNode.publish({ type: "FooCommitted", fooId: foo.id });

Leader Election

  • Kind: mechanism
  • Severity: mandatory for distributed systems
  • Scope: distributed system, coordination, availability
  • Layer: Execution Core
Details
Violated by
multiple nodes assuming the coordinator role at once
Detected by
concurrent leader actions / split-brain
Measured by
split-brain incident rate
Refactored by
Introduce Leader Election
Enforced by
distributed-systems review
Before
if (process.env.IS_LEADER === "true") runFooScheduler();
After
const lease = await fooCoordinator.acquireLeadership("foo-scheduler", { ttlMs: 10_000 }); lease.onAcquired(() => runFooScheduler()); lease.onLost(() => stopFooScheduler());

Consensus

  • Kind: mechanism
  • Severity: mandatory for distributed systems
  • Scope: distributed system, agreement, consistency
  • Layer: Execution Core
Details
Violated by
nodes committing values without quorum agreement
Detected by
divergent committed state across replicas
Measured by
agreement-violation rate
Refactored by
Adopt a Consensus Protocol
Enforced by
distributed-systems review
Before
fooNodeA.setValue(value);
After
const committed = await fooCluster.propose(value, { quorum: majority(fooNodes) }); if (!committed.accepted) throw new NoQuorumError();

Choreography

Details
Violated by
one orchestrator commanding every step of a cross-service flow
Detected by
a central coordinator coupled to all participants
Measured by
orchestrator fan-out coupling
Refactored by
Coordinate via Choreographed Events
Before
await orchestrator.run("CreateFoo", [ () => createFoo(foo), () => reserveBar(foo), () => notifyBaz(foo), ]);
After
fooEvents.on("FooCreated", event => barService.reserve(event.fooId)); barEvents.on("BarReserved", event => bazService.notify(event.fooId));

Core Modular Design

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_single_responsibility["Single Responsibility Principle (SRP)"]
    n_separation_of_concerns["Separation of Concerns"]
    n_duplicate_code["Do Not Repeat Yourself (DRY)"]
    n_high_cohesion["High Cohesion"]
    n_low_coupling["Low Coupling"]
    n_encapsulation["Encapsulation"]
    n_information_hiding["Information Hiding"]
    n_abstraction["Abstraction"]
    n_modularity["Modularity"]
    n_composability["Composability"]
    n_composition_over_inheritance["Composition Over Inheritance"]
    n_reusability["Reusability"]
    n_replaceability["Replaceability"]
    n_interchangeability["Interchangeability"]
    n_independence["Independence"]
    n_autonomy["Autonomy"]
    n_single_responsibility --> n_high_cohesion
    n_single_responsibility --> n_separation_of_concerns
    n_single_responsibility --> n_modularity
    n_single_responsibility --> n_replaceability
    n_single_responsibility --> n_reusability
    n_separation_of_concerns --> n_abstraction
    n_separation_of_concerns --> n_single_responsibility
    n_separation_of_concerns --> n_modularity
    n_separation_of_concerns --> n_replaceability
    n_duplicate_code --> n_abstraction
    n_duplicate_code --> n_reusability
    n_high_cohesion --> n_single_responsibility
    n_high_cohesion --> n_modularity
    n_high_cohesion --> n_encapsulation
    n_high_cohesion --> n_replaceability
    n_low_coupling --> n_abstraction
    n_low_coupling --> n_modularity
    n_low_coupling --> n_replaceability
    n_encapsulation --> n_information_hiding
    n_encapsulation --> n_abstraction
    n_encapsulation --> n_low_coupling
    n_information_hiding --> n_encapsulation
    n_information_hiding --> n_low_coupling
    n_information_hiding --> n_replaceability
    n_abstraction --> n_low_coupling
    n_abstraction --> n_replaceability
    n_modularity --> n_high_cohesion
    n_modularity --> n_low_coupling
    n_modularity --> n_separation_of_concerns
    n_modularity --> n_composability
    n_modularity --> n_replaceability
    n_composability --> n_low_coupling
    n_composability --> n_modularity
    n_composability --> n_reusability
    n_composition_over_inheritance --> n_low_coupling
    n_composition_over_inheritance --> n_replaceability
    n_reusability --> n_abstraction
    n_reusability --> n_duplicate_code
    n_reusability --> n_composability
    n_replaceability --> n_low_coupling
    n_interchangeability --> n_replaceability
    n_independence --> n_low_coupling
    n_independence --> n_autonomy
    n_autonomy --> n_independence

Single Responsibility Principle (SRP)

  • Kind: principle
  • Severity: mandatory
  • Scope: class, module, service
  • Aliases: SRP, Single Responsibility Principle (SRP)
  • Layer: Structural Core
Details
Violated by
Mixed Responsibilities, Multi-Reason Change
Detected by
high fan-in/fan-out, unrelated methods, unrelated dependencies
Measured by
cohesion score, responsibility count, change-coupling
Refactored by
Extract Class, Extract Module, Split Service, Move Method
Enforced by
architecture tests, package boundaries, static analysis
Before
class FooService { save(foo: Foo) { fooDb.insert(foo); } send(foo: Foo) { fooMail.send(foo); } report(foo: Foo) { return `${foo.id}:${foo.name}`; } }
After
class FooRepository { save(foo: Foo) { return fooDb.insert(foo); } } class FooNotifier { send(foo: Foo) { return fooMail.send(foo); } } class FooReporter { report(foo: Foo) { return `${foo.id}:${foo.name}`; } }

Separation of Concerns

Details
Violated by
business logic in controllers, persistence logic in domain
Detected by
layer imports, mixed naming roles, cross-boundary logic
Measured by
dependency direction, layer purity, concern overlap
Refactored by
Extract Layer, Move Logic, Introduce Boundary
Enforced by
import rules, dependency graph checks
Before
function handleFoo(request: Request) { const foo = JSON.parse(request.body); fooDb.insert(foo); return `<div>${foo.name}</div>`; }
After
function parseFoo(request: Request): Foo { return decodeFoo(request.body); } function saveFoo(foo: Foo) { return fooDb.insert(foo); } function renderFoo(foo: Foo) { return `<div>${foo.name}</div>`; }

Do Not Repeat Yourself (DRY)

Details
Violated by
duplicated logic, duplicated constants, duplicated schemas
Detected by
clone detection, duplicated branches, repeated literals
Measured by
duplication percentage, clone count
Refactored by
Extract Function, Extract Module, Parameterize, Centralize Rule
Enforced by
clone analyzers, lint rules, review gates
Before
function validateFoo(foo: Foo) { if (!foo.name || foo.name.length > 40) throw new Error("invalid name"); } function validateBar(bar: Bar) { if (!bar.name || bar.name.length > 40) throw new Error("invalid name"); }
After
function validateName(name: string) { if (!name || name.length > 40) throw new Error("invalid name"); } function validateFoo(foo: Foo) { validateName(foo.name); } function validateBar(bar: Bar) { validateName(bar.name); }

High Cohesion

Details
Violated by
unrelated methods, unrelated fields, unstable responsibility grouping
Detected by
low LCOM, scattered dependencies, unrelated public API
Measured by
cohesion metrics, change locality
Refactored by
Extract Class, Split Module, Move Method
Enforced by
module ownership, architecture review
Before
class FooManager { saveFoo(foo: Foo) { return fooDb.insert(foo); } resizeImage(image: Image) { return image.resize(100, 100); } parseBar(raw: string) { return JSON.parse(raw) as Bar; } }
After
class FooRepository { save(foo: Foo) { return fooDb.insert(foo); } load(id: FooId) { return fooDb.find(id); } remove(id: FooId) { return fooDb.delete(id); } } class ImageResizer { resize(image: Image) { return image.resize(100, 100); } } class BarParser { parse(raw: string) { return JSON.parse(raw) as Bar; } }

Low Coupling

Details
Violated by
concrete imports, global state, bidirectional dependencies
Detected by
dependency cycles, high afferent/efferent coupling
Measured by
coupling metrics, dependency graph density
Refactored by
Introduce Interface, Dependency Injection, Adapter Extraction
Enforced by
dependency rules, architecture fitness tests
Before
class FooService { save(foo: Foo) { const db = new SqlDatabase("foo-prod"); barIndex.update(foo); return db.table("foos").insert(foo); } }
After
class FooService { constructor(private readonly events: EventSink) {} save(foo: Foo) { return this.events.emit({ type: "FooSaved", foo }); } }

Encapsulation

Details
Violated by
public mutable fields, leaky getters, direct state mutation
Detected by
public state, excessive setters, external invariant manipulation
Measured by
public surface area, mutation exposure
Refactored by
Hide Field, Introduce Method, Restrict Visibility
Enforced by
visibility rules, linting, API review
Before
class FooCounter { count = 0; } const counter = new FooCounter(); counter.count = -100;
After
class FooCounter { #count = 0; increment() { this.#count += 1; } value() { return this.#count; } }

Information Hiding

Details
Violated by
exposing implementation details, shared internals
Detected by
internal packages imported externally, exposed persistence models
Measured by
internal API exposure, dependency leakage
Refactored by
Introduce Facade, Hide Module, Restrict Exports
Enforced by
package visibility, module export rules
Before
class FooStore { public readonly rows = new Map<string, Foo>(); } fooStore.rows.set(foo.id, foo);
After
interface FooStore { save(foo: Foo): void; find(id: string): Foo | undefined; } class MapFooStore implements FooStore { #rows = new Map<string, Foo>(); save(foo: Foo) { this.#rows.set(foo.id, foo); } find(id: string) { return this.#rows.get(id); } }

Abstraction

Details
Violated by
hardcoded implementation dependency, implementation leakage
Detected by
concrete type usage across boundaries
Measured by
abstraction ratio, interface stability
Refactored by
Extract Interface, Introduce Port, Generalize Dependency
Enforced by
architecture tests, dependency inversion rules
Before
function saveFoo(foo: Foo) { return sqlClient.query("insert into foos(id,name) values($1,$2)", [foo.id, foo.name]); }
After
interface FooRepository { save(foo: Foo): Promise<void>; } class SqlFooRepository implements FooRepository { save(foo: Foo) { return sqlClient.query("insert into foos(id,name) values($1,$2)", [foo.id, foo.name]); } } class HttpFooRepository implements FooRepository { save(foo: Foo) { return http.post("/foos", foo); } } function saveFoo(foo: Foo, repository: FooRepository) { return repository.save(foo); }

Modularity

Details
Detected by
dependency cycles, unstable module graph
Measured by
modularity score, graph density, instability
Refactored by
Split Module, Introduce Boundary, Invert Dependency
Enforced by
module rules, package ownership, fitness functions
Before
class FooApplication { parse(raw: string) { return JSON.parse(raw) as Foo; } save(foo: Foo) { return fooDb.insert(foo); } publish(foo: Foo) { return fooBus.emit(foo); } }
After
export const fooParser = { parse: (raw: string) => decodeFoo(raw) }; export const fooRepository = { save: (foo: Foo) => fooDb.insert(foo) }; export const fooPublisher = { publish: (foo: Foo) => fooBus.emit(foo) };

Composability

Details
Detected by
non-chainable APIs, incompatible contracts
Measured by
composition count, interface compatibility
Refactored by
Normalize Interface, Extract Component, Introduce Adapter
Enforced by
contract tests, type checks
Before
function processFoo(raw: string) { const foo = JSON.parse(raw) as Foo; const normalized = { ...foo, name: foo.name.trim() }; return fooDb.insert(normalized); }
After
const parseFoo = (raw: string): Foo => decodeFoo(raw); const normalizeFoo = (foo: Foo): Foo => ({ ...foo, name: foo.name.trim() }); const saveFoo = (foo: Foo) => fooDb.insert(foo); const processFoo = flow(parseFoo, normalizeFoo, saveFoo);

Composition Over Inheritance

Details
Violated by
fragile base class, inherited behavior misuse
Detected by
inheritance depth, overridden behavior conflicts
Measured by
inheritance depth, composition ratio
Refactored by
Replace Inheritance with Delegation, Extract Strategy
Enforced by
inheritance depth limits, review rules
Before
class RetryingSqlFooStore extends SqlFooStore { async save(foo: Foo) { for (let attempt = 0; attempt < 3; attempt += 1) { try { return await super.save(foo); } catch (error) { if (attempt === 2) throw error; } } } }
After
class RetryingFooStore implements FooStore { constructor(private readonly inner: FooStore, private readonly attempts: number) {} async save(foo: Foo) { for (let attempt = 0; attempt < this.attempts; attempt += 1) { try { return await this.inner.save(foo); } catch (error) { if (attempt === this.attempts - 1) throw error; } } } }

Reusability

Details
Violated by
hardcoded context, hidden assumptions
Detected by
environment-specific logic in reusable code
Measured by
reuse count, dependency portability
Refactored by
Parameterize, Extract Library, Remove Context Coupling
Enforced by
API review, dependency rules
Before
function saveAdminFoo(foo: Foo) { return adminFooDb.insert(foo); } function savePublicFoo(foo: Foo) { return publicFooDb.insert(foo); }
After
function saveFoo(store: FooStore, foo: Foo) { return store.save(foo); } const saveAdminFoo = (foo: Foo) => saveFoo(adminFooStore, foo); const savePublicFoo = (foo: Foo) => saveFoo(publicFooStore, foo);

Replaceability

Details
Violated by
direct vendor SDK usage in domain/application
Detected by
infrastructure imports in core layers
Measured by
adapter coverage, boundary purity
Refactored by
Introduce Port, Extract Adapter, Invert Dependency
Enforced by
import restrictions, adapter tests
Before
class FooService { private readonly store = new SqlFooStore(); save(foo: Foo) { return this.store.save(foo); } }
After
class FooService { constructor(private readonly store: FooStore) {} save(foo: Foo) { return this.store.save(foo); } } test("saves without a database", async () => { const store = new MemoryFooStore(); await new FooService(store).save(foo); expect(store.find(foo.id)).toEqual(foo); });

Interchangeability

Details
Violated by
non-conforming substitutes
Detected by
contract test failure, incompatible schema
Measured by
conformance score, compatibility tests
Refactored by
Normalize Interface, Add Adapter, Align Contract
Enforced by
contract tests, schema validation
Before
function loadFoo(kind: "sql" | "memory", id: FooId) { if (kind === "sql") return sqlFooStore.find(id); return memoryFooStore.get(id); }
After
interface FooStore { find(id: FooId): Promise<Foo | undefined>; } function loadFoo(store: FooStore, id: FooId) { return store.find(id); }

Independence

Details
Violated by
shared database coupling, synchronous dependency chains
Detected by
shared mutable resources, deployment coupling
Measured by
independent deployability, dependency count
Refactored by
Split Boundary, Introduce Events, Decouple Persistence
Enforced by
deployment rules, service ownership
Before
class FooModule { create(foo: Foo) { barModule.refresh(foo.id); bazModule.rebuild(foo.id); return fooDb.insert(foo); } }
After
class FooModule { constructor(private readonly store: FooStore, private readonly events: EventSink) {} async create(foo: Foo) { await this.store.save(foo); this.events.emit({ type: "FooCreated", fooId: foo.id }); } }

Autonomy

Details
Violated by
cross-service database writes, shared business logic ownership
Detected by
external writes to owned data, cross-team coupling
Measured by
ownership clarity, deployment independence
Refactored by
Own Data, Split Context, Introduce Events
Enforced by
ownership boundaries, API policies
Before
async function createFoo(foo: Foo) { const bar = await barService.get(foo.barId); await bazService.validate(foo, bar); return fooStore.save(foo); }
After
async function createFoo(foo: Foo) { await fooStore.save(foo); await outbox.append({ type: "FooCreated", fooId: foo.id, barId: foo.barId }); }

Correctness / Determinism / Verification

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_determinism["Determinism"]
    n_predictability["Predictability"]
    n_referential_transparency["Referential Transparency"]
    n_pure_functions["Pure Functions"]
    n_immutability["Immutability"]
    n_reproducibility["Reproducibility"]
    n_repeatability["Repeatability"]
    n_correctness["Correctness"]
    n_formal_verification["Formal Verification"]
    n_specification_based_testing["Specification-Based Testing"]
    n_property_based_testing["Property-Based Testing"]
    n_static_analysis["Static Analysis"]
    n_testability["Testability"]
    n_validation["Validation"]
    n_verification["Verification"]
    n_determinism --> n_predictability
    n_determinism --> n_reproducibility
    n_predictability --> n_determinism
    n_referential_transparency --> n_pure_functions
    n_referential_transparency --> n_immutability
    n_referential_transparency --> n_determinism
    n_referential_transparency --> n_testability
    n_pure_functions --> n_testability
    n_pure_functions --> n_determinism
    n_pure_functions --> n_referential_transparency
    n_immutability --> n_predictability
    n_reproducibility --> n_determinism
    n_repeatability --> n_verification
    n_repeatability --> n_predictability
    n_correctness --> n_validation
    n_formal_verification --> n_correctness
    n_specification_based_testing --> n_correctness
    n_property_based_testing --> n_correctness
    n_testability --> n_pure_functions
    n_validation --> n_correctness
    n_verification --> n_correctness

Determinism

Details
Violated by
nondeterministic behavior without explicit source
Detected by
flaky tests, hidden random/time calls
Measured by
flake rate, reproducibility score
Refactored by
Inject Clock/RNG, Control State
Enforced by
deterministic test rules
Before
function makeFoo(name: string) { return { id: crypto.randomUUID(), name, createdAt: new Date() }; }
After
function makeFoo(name: string, id: FooId, createdAt: Date): Foo { return { id, name, createdAt }; }

Predictability

Details
Violated by
surprising side effects, implicit ordering
Detected by
nondeterministic tests, ambiguous APIs
Measured by
flake/misuse rate
Refactored by
Make Behavior Explicit, Add Contracts
Enforced by
tests, contracts, linting
Before
function saveFoo(foo: Foo) { if (Math.random() > 0.5) return memoryStore.save(foo); return sqlStore.save(foo); }
After
function saveFoo(store: FooStore, foo: Foo) { return store.save(foo); }

Referential Transparency

Details
Violated by
same input producing different output
Detected by
hidden dependency on time/random/global state
Measured by
pure function coverage
Refactored by
Extract Pure Function, Inject Dependency
Enforced by
code review, functional boundaries
Before
function fooTotal(values: number[]) { globalCounter += 1; return values.reduce((a, b) => a + b, 0) + globalCounter; }
After
function fooTotal(values: readonly number[]) { return values.reduce((a, b) => a + b, 0); }

Pure Functions

Details
Violated by
mutation, IO, global reads/writes
Detected by
side-effect calls inside pure layer
Measured by
pure core ratio
Refactored by
Extract Pure Logic, Move IO Outward
Enforced by
layer rules, tests
Before
function normalizeFoo(foo: Foo) { foo.name = foo.name.trim(); fooStore.save(foo); return foo; }
After
function normalizeFoo(foo: Foo): Foo { return { ...foo, name: foo.name.trim() }; }

Immutability

Details
Violated by
mutating value objects, exposed mutable collections
Detected by
setters on value objects, mutable public fields
Measured by
mutable state count
Refactored by
Make Immutable, Copy-on-Write
Enforced by
type system, lint rules
Before
type Foo = { name: string; tags: string[] }; function addTag(foo: Foo, tag: string) { foo.tags.push(tag); return foo; }
After
type Foo = Readonly<{ name: string; tags: readonly string[] }>; function addTag(foo: Foo, tag: string): Foo { return { ...foo, tags: [...foo.tags, tag] }; }

Reproducibility

Details
Violated by
unpinned dependencies, nondeterministic builds
Detected by
build output drift
Measured by
reproducible build/test pass rate
Refactored by
Pin Versions, Lock Inputs, Capture Environment
Enforced by
lockfiles, build verification
Before
const result = trainFoo(data, { seed: Math.random() });
After
const config = { seed: 42, datasetVersion: "foo-v3", algorithmVersion: "1.2.0" } as const; const result = trainFoo(data, config);

Repeatability

Details
Violated by
tests depending on ordering/time/external state
Detected by
flaky test results
Measured by
rerun consistency
Refactored by
Isolate Environment, Mock External Inputs
Enforced by
CI rerun policy
Before
test("foo", () => expect(runFoo(Date.now())).toEqual(snapshot()));
After
test("foo", () => { const clock = new FixedClock("2026-01-01T00:00:00Z"); expect(runFoo(clock)).toEqual(expectedFoo); });

Correctness

Details
Violated by
behavior diverging from specification
Detected by
failing tests, invariant violations
Measured by
defect rate, spec coverage
Refactored by
Add Tests, Fix Logic, Add Contracts
Enforced by
CI, formal/static checks
Before
function averageFoo(total: number, count: number) { return total / count; }
After
function averageFoo(total: number, count: number) { if (!Number.isFinite(total)) throw new Error("invalid total"); if (!Number.isInteger(count) || count <= 0) throw new Error("invalid count"); return total / count; }

Formal Verification

Details
Violated by
critical logic without proof where required
Detected by
missing formal model for critical invariant
Measured by
proven property coverage
Refactored by
Specify Model, Prove Invariant
Enforced by
proof tooling
Before
function transferFoo(a: FooBalance, b: FooBalance, amount: number) { a.value -= amount; b.value += amount; }
After
function transferFoo(state: FooState, amount: PositiveAmount): FooState { requires(state.from >= amount.value); const next = { from: state.from - amount.value, to: state.to + amount.value }; ensures(next.from + next.to === state.from + state.to); return next; }

Specification-Based Testing

Details
Violated by
tests coupled to implementation details
Detected by
lack of spec-derived tests
Measured by
spec coverage
Refactored by
Add Spec Tests
Enforced by
test gates
Before
test("saveFoo", async () => expect(await saveFoo(foo)).toBeTruthy());
After
describeContract("FooStore", store => { it("returns the saved Foo", async () => { await store.save(foo); expect(await store.find(foo.id)).toEqual(foo); }); });

Property-Based Testing

Details
Violated by
invariant-heavy code with only example tests
Detected by
missing generative tests for critical properties
Measured by
property coverage, counterexample count
Refactored by
Define Property, Add Generator
Enforced by
property test suite
Before
test("normalizeFoo", () => expect(normalizeFoo({ name: " Foo " }).name).toBe("Foo"));
After
property(string(), name => { const once = normalizeFoo({ name }); const twice = normalizeFoo(once); expect(twice).toEqual(once); });

Static Analysis

Details
Violated by
ignored analyzer findings
Detected by
static analysis rule failures
Measured by
issue count, false-positive rate
Refactored by
Fix Violations, Tune Rules
Enforced by
CI quality gates
Before
const foo: any = loadFoo(); foo.nmae.toUpperCase();
After
const foo: Foo = loadFoo(); foo.name.toUpperCase(); runTypeCheck({ noImplicitAny: true, strictNullChecks: true });

Testability

Details
Violated by
hardcoded dependencies, global state, nondeterminism
Detected by
difficult setup, excessive mocking, flaky tests
Measured by
test setup complexity, coverage, flake rate
Refactored by
Inject Dependencies, Isolate Side Effects
Enforced by
Before
function createFoo(name: string) { return fooDb.save({ id: crypto.randomUUID(), name, createdAt: new Date() }); }
After
function createFoo(name: string, ids: IdSource, clock: Clock, store: FooStore) { return store.save({ id: ids.nextFooId(), name, createdAt: clock.now() }); }

Validation

Details
Violated by
unvalidated user/system assumptions
Detected by
missing acceptance tests
Measured by
acceptance coverage
Refactored by
Add Validation Rules, Add Acceptance Tests
Enforced by
CI gates, QA policy
Before
function createFoo(input: any) { return fooStore.save(input); }
After
function createFoo(input: unknown) { const foo = CreateFooSchema.parse(input); return fooStore.save(foo); }

Verification

Details
Reinforces
In tension with
Referenced by
Violated by
code lacking spec conformance checks
Detected by
missing tests/static checks
Measured by
verification coverage
Refactored by
Add Tests, Add Static Checks
Enforced by
CI gates
Before
await fooStore.save(foo); return { ok: true };
After
await fooStore.save(foo); const persisted = await fooStore.find(foo.id); if (!persisted || persisted.version !== foo.version) throw new Error("verification failed"); return { ok: true } as const;

Creational Patterns

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_factory_pattern["Factory Pattern"]
    n_factory_method_pattern["Factory Method Pattern"]
    n_abstract_factory_pattern["Abstract Factory Pattern"]
    n_builder_pattern["Builder Pattern"]
    n_prototype_pattern["Prototype Pattern"]
    n_singleton_pattern["Singleton Pattern"]

Factory Pattern

Details
Violated by
duplicated conditional construction
Detected by
repeated constructors/switches
Measured by
construction duplication count
Refactored by
Extract Factory
Enforced by
creation policy review
Before
const foo = new Foo("foo", 0, [], new Date(), "draft");
After
function makeFoo(name: string): Foo { return new Foo(fooId(), name, 0, [], clock.now(), "draft"); }

Factory Method Pattern

Details
Violated by
fixed construction in base workflow
Detected by
base class directly instantiates variant
Measured by
variant construction duplication
Refactored by
Introduce Factory Method
Enforced by
Before
class FooImporter { import(raw: string) { return new JsonFooParser().parse(raw); } }
After
abstract class FooImporter { protected abstract parser(): FooParser; import(raw: string) { return this.parser().parse(raw); } } class JsonFooImporter extends FooImporter { protected parser() { return new JsonFooParser(); } }

Abstract Factory Pattern

Details
Violated by
incompatible product combinations
Detected by
manual selection of related product classes
Measured by
family mismatch defects
Refactored by
Introduce Abstract Factory
Enforced by
factory conformance tests
Before
const store = env === "test" ? new MemoryFooStore() : new SqlFooStore(); const bus = env === "test" ? new MemoryFooBus() : new KafkaFooBus();
After
interface FooPlatformFactory { store(): FooStore; bus(): FooBus; } class TestFooPlatformFactory implements FooPlatformFactory { store() { return new MemoryFooStore(); } bus() { return new MemoryFooBus(); } }

Builder Pattern

Details
Violated by
constructors with many optional params
Detected by
high-arity constructors
Measured by
constructor parameter count
Refactored by
Introduce Builder
Enforced by
API review
Before
const foo = new Foo("foo_1", "Foo", [], 0, false, undefined, "draft");
After
const foo = new FooBuilder() .withId("foo_1") .withName("Foo") .withStatus("draft") .build();

Prototype Pattern

Details
Violated by
expensive repeated setup
Detected by
duplicate initialization flows
Measured by
initialization duplication/cost
Refactored by
Introduce Prototype, Add Clone Semantics
Enforced by
clone tests
Before
function copyFoo(foo: Foo) { return new Foo(foo.id, foo.name, [...foo.tags], foo.settings.theme, foo.settings.mode); }
After
class FooPrototype { constructor(private readonly base: Foo) {} clone(overrides: Partial<Foo> = {}): Foo { return structuredClone({ ...this.base, ...overrides }); } } const template = new FooPrototype(await buildExpensiveFoo()); const draft = template.clone({ name: "quick" });

Singleton Pattern

  • Kind: pattern
  • Severity: contextual/discouraged unless justified
  • Scope: object creation, lifetime, composition root
  • Layer: Design Patterns Core
Details
Violated by
a global mutable instance reached from anywhere
Detected by
static global access to a shared service
Measured by
global-instance reach-in count
Refactored by
Compose Single Instance at the Root, Inject It
Enforced by
composition-root review
Before
let instance: FooService | undefined; function getFooService() { return instance ??= new FooService(); }
After
class FooService {} export function composeApp() { const fooService = new FooService(); return { fooService, fooController: new FooController(fooService) }; }

Domain Architecture

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_domain_driven_design["Domain-Driven Design (DDD)"]
    n_domain_model["Domain Model"]
    n_bounded_context["Bounded Context"]
    n_context_mapping["Context Mapping"]
    n_anti_corruption_layer["Anti-Corruption Layer"]
    n_explicit_boundaries["Explicit Boundaries"]
    n_aggregate["Aggregate"]
    n_value_object["Value Object"]
    n_entity["Entity"]
    n_domain_service["Domain Service"]
    n_domain_driven_design --> n_bounded_context
    n_domain_driven_design --> n_domain_model
    n_bounded_context --> n_explicit_boundaries
    n_bounded_context --> n_context_mapping
    n_context_mapping --> n_bounded_context
    n_context_mapping --> n_explicit_boundaries
    n_context_mapping --> n_anti_corruption_layer
    n_aggregate --> n_explicit_boundaries
    n_entity --> n_domain_model
    n_entity -.-> n_value_object
    n_domain_service --> n_domain_model
    n_domain_service -.-> n_aggregate

Domain-Driven Design (DDD)

  • Kind: style
  • Severity: contextual
  • Scope: domain, bounded context, system
  • Aliases: DDD
  • Layer: Domain Modeling
Details
Violated by
domain logic in infrastructure/controllers
Detected by
anemic models, scattered business rules
Measured by
domain logic locality
Refactored by
Extract Domain Model, Add Aggregate, Split Context
Enforced by
layer rules, domain tests
Before
function updateFoo(row: FooRow, name: string) { row.name = name; row.updated_at = Date.now(); return fooTable.save(row); }
After
class Foo { private constructor(readonly id: FooId, private name: string) {} rename(name: FooName) { this.name = name.value; } } foo.rename(FooName.create(name));

Domain Model

Details
Violated by
business rules outside domain objects/services
Detected by
procedural domain logic in services/controllers
Measured by
rule locality, invariant coverage
Refactored by
Move Logic to Domain, Add Value Object, Add Aggregate
Enforced by
domain layer rules, tests
Before
type Foo = { status: string; count: number }; function closeFoo(foo: Foo) { foo.status = "closed"; }
After
class Foo { #status: "open" | "closed" = "open"; close() { if (this.#status === "closed") throw new Error("Foo already closed"); this.#status = "closed"; } }

Bounded Context

Details
Violated by
cross-context model leakage
Detected by
shared domain entities across contexts
Measured by
context coupling
Refactored by
Split Model, Add Anti-Corruption Layer, Define Context Map
Enforced by
package/service boundaries
Before
type FooStatus = "A" | "D"; function priceBar(status: FooStatus) { return status === "A" ? 10 : 0; }
After
type FooStatus = "active" | "disabled"; type BarEligibility = "eligible" | "ineligible"; function toBarEligibility(status: FooStatus): BarEligibility { return status === "active" ? "eligible" : "ineligible"; }

Context Mapping

Details
Violated by
undocumented service/domain relationships
Detected by
unclear ownership, ambiguous integration flows
Measured by
undocumented dependency count
Refactored by
Define Context Map, Classify Upstream/Downstream
Enforced by
architecture docs, dependency reviews
Before
fooService.writeDirectly(barDatabase, foo); barService.readDirectly(fooDatabase, foo.id);
After
const contextMap = { upstream: "FooContext", downstream: "BarContext", relationship: "published-language", } as const; fooEvents.publish(toBarIntegrationEvent(foo));

Anti-Corruption Layer

Details
Violated by
external model leaking into domain
Detected by
external DTOs used in domain layer
Measured by
leakage count, adapter coverage
Refactored by
Add Translator, Add Adapter, Introduce Boundary DTO
Enforced by
import rules, layer tests
Before
function createBar(fooResponse: FooApiResponse) { return barService.create({ foo_status: fooResponse.state_code }); }
After
type BarInput = { eligible: boolean }; function fromFoo(response: FooApiResponse): BarInput { return { eligible: response.state_code === "A" }; } barService.create(fromFoo(fooResponse));

Explicit Boundaries

Details
Violated by
internal imports, shared mutable internals
Detected by
forbidden imports, cyclic dependencies
Measured by
boundary violation count
Refactored by
Move Code, Extract API, Restrict Exports
Enforced by
module rules, architecture tests
Before
import { fooDatabase } from "../../foo/infrastructure/database"; export function loadBar(id: string) { return fooDatabase.query(id); }
After
export interface FooGateway { find(id: FooId): Promise<FooSnapshot>; } export function loadBar(id: FooId, foos: FooGateway) { return foos.find(id); }

Aggregate

Details
Violated by
invariants enforced by services outside the entity cluster
Detected by
cross-entity invariant checks scattered in services
Measured by
out-of-aggregate invariant enforcement count
Refactored by
Define Aggregate Root, Enforce Invariants Within
Enforced by
domain model review
Before
fooOrder.total -= item.price; fooOrderItems.delete(item.id);
After
class FooOrder { #items: FooItem[] = []; #total = 0; removeItem(id: FooItemId) { this.#items = this.#items.filter(item => item.id !== id); this.#total = this.#items.reduce((sum, item) => sum + item.price, 0); } }

Value Object

Details
Violated by
domain concepts carried as bare primitives
Detected by
repeated validation of the same primitive shape
Measured by
primitive-typed domain concept count
Refactored by
Introduce Value Object
Enforced by
domain model review
Before
function priceFoo(amount: number, currency: string) { return { amount, currency }; }
After
class Money { private constructor(readonly amount: number, readonly currency: string) {} static of(amount: number, currency: string): Money { if (amount < 0) throw new Error("negative money"); return new Money(amount, currency); } equals(other: Money) { return this.amount === other.amount && this.currency === other.currency; } add(other: Money): Money { return Money.of(this.amount + other.amount, this.currency); } }

Entity

Details
Violated by
identity equated by attribute comparison
Detected by
equality by field value where identity is meant
Measured by
attribute-equality misuse count
Refactored by
Model Identity Explicitly
Enforced by
domain model review
Before
type Foo = { id: string; name: string; status: string }; foo.status = "active";
After
class Foo { constructor(readonly id: FooId, private name: string, private status: FooStatus) {} equals(other: Foo) { return this.id === other.id; } activate() { this.status = "active"; } }

Domain Service

Details
Violated by
multi-entity domain rules living in controllers
Detected by
domain logic in application/transport layers
Measured by
misplaced domain-rule count
Refactored by
Extract Domain Service
Enforced by
domain model review
Before
class FooAccount { transferTo(other: FooAccount, amount: number) { this.balance -= amount; other.balance += amount; } }
After
class FooTransferService { transfer(from: FooAccount, to: FooAccount, amount: Money) { from.withdraw(amount); to.deposit(amount); } }

Error Handling / Resilience

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_defensive_programming["Defensive Programming"]
    n_fail_fast["Fail Fast"]
    n_fail_safe["Fail Safe"]
    n_fail_secure["Fail Secure"]
    n_graceful_degradation["Graceful Degradation"]
    n_fault_tolerance["Fault Tolerance"]
    n_resilience["Resilience"]
    n_robustness_principle["Robustness Principle"]
    n_error_handling["Error Handling"]
    n_error_boundaries["Error Boundaries"]
    n_fallback_pattern["Fallback Pattern"]
    n_retry_pattern["Retry Pattern"]
    n_timeout_pattern["Timeout Pattern"]
    n_circuit_breaker_pattern["Circuit Breaker Pattern"]
    n_bulkhead_pattern["Bulkhead Pattern"]
    n_backpressure["Backpressure"]
    n_defensive_programming --> n_error_handling
    n_defensive_programming --> n_fail_fast
    n_fail_fast -.-> n_graceful_degradation
    n_fail_safe --> n_resilience
    n_graceful_degradation --> n_fault_tolerance
    n_fault_tolerance --> n_error_handling
    n_fault_tolerance --> n_resilience
    n_resilience --> n_fault_tolerance
    n_error_handling --> n_resilience
    n_error_boundaries --> n_resilience
    n_fallback_pattern --> n_graceful_degradation
    n_retry_pattern --> n_fault_tolerance
    n_circuit_breaker_pattern --> n_fault_tolerance
    n_circuit_breaker_pattern --> n_backpressure
    n_backpressure --> n_resilience

Defensive Programming

Details
Violated by
unchecked assumptions
Detected by
null/empty/range unsafe access
Measured by
guard coverage, runtime exception rate
Refactored by
Add Guards, Validate Inputs
Enforced by
linting, tests
Before
function renameFoo(foo: Foo, name: string) { foo.name = name.trim(); }
After
function renameFoo(foo: Foo | undefined, name: unknown) { if (!foo) throw new Error("Foo required"); if (typeof name !== "string" || name.trim().length === 0) throw new Error("valid name required"); return { ...foo, name: name.trim() }; }

Fail Fast

Details
Violated by
swallowing invalid state
Detected by
ignored exceptions, default fallbacks masking errors
Measured by
late failure rate
Refactored by
Add Guard Clause, Throw Explicit Error
Enforced by
validation tests
Before
const fooUrl = process.env.FOO_URL ?? "http://localhost:3000"; startFooApp(fooUrl);
After
const fooUrl = process.env.FOO_URL; if (!fooUrl) throw new Error("FOO_URL is required"); startFooApp(new URL(fooUrl));

Fail Safe

Details
Violated by
continuing in unsafe state
Detected by
fallback to unsafe behavior
Measured by
unsafe failure modes
Refactored by
Add Safe Fallback, Stop Unsafe Operation
Enforced by
failure-mode tests
Before
try { await openFooGate(); } catch { fooGate.unlock(); }
After
try { await openFooGate(); } catch { fooGate.lock(); throw new Error("Foo gate remains locked"); }

Fail Secure

Details
Violated by
allowing access after auth/policy failure
Detected by
fail-open branches
Measured by
fail-open count
Refactored by
Default Deny, Add Explicit Allow
Enforced by
security tests, policy checks
Before
function authorizeFoo(token?: string) { if (!token) return { role: "admin" }; return decodeToken(token); }
After
function authorizeFoo(token?: string): FooIdentity { if (!token) throw new UnauthorizedError(); const identity = verifyToken(token); if (!identity) throw new UnauthorizedError(); return identity; }

Graceful Degradation

Details
Violated by
total outage from noncritical dependency failure
Detected by
critical path dependency on optional service
Measured by
partial availability under failure
Refactored by
Add Fallback, Isolate Optional Dependency
Enforced by
chaos tests
Before
async function renderFooPage() { const foo = await fooService.get(); const bar = await barRecommendations.get(); return render(foo, bar); }
After
async function renderFooPage() { const foo = await fooService.get(); const bar = await barRecommendations.get().catch(() => [] as Bar[]); return render(foo, bar); }

Fault Tolerance

Details
Violated by
unrecoverable dependency failure
Detected by
no retry/failover/fallback for critical path
Measured by
failure recovery rate, availability
Refactored by
Add Retry, Failover, Redundancy
Enforced by
resilience tests
Before
const foo = await fooReplicaA.read(id);
After
const foo = await firstSuccessful([ () => fooReplicaA.read(id), () => fooReplicaB.read(id), () => fooReplicaC.read(id), ]);

Resilience

Details
Violated by
cascading failures
Detected by
failure propagation, lack of isolation
Measured by
MTTR, error budget, availability
Refactored by
Add Circuit Breaker, Bulkhead, Retry, Timeout
Enforced by
chaos testing, SLO gates
Before
async function loadFoo(id: FooId) { return remoteFoo.get(id); }
After
async function loadFoo(id: FooId) { return circuitBreaker.execute(() => retry.withBackoff(() => remoteFoo.get(id), { attempts: 3 })); }

Robustness Principle

Details
Violated by
rejecting harmless compatible input variations
Detected by
parser brittleness
Measured by
compatibility failure rate
Refactored by
Normalize Input, Validate Semantics
Enforced by
compatibility test suite
Before
function readFoo(message: any) { return { id: message.id, name: message.name }; } function writeFoo(foo: Foo) { return { ...foo, debug: globalThis }; }
After
function readFoo(message: unknown) { const value = FooEnvelopeSchema.parse(message); return { id: value.id, name: value.name }; } function writeFoo(foo: Foo): FooEnvelopeV1 { return { version: 1, id: foo.id, name: foo.name }; }

Error Handling

Details
Violated by
ignored errors, generic catches, lost context
Detected by
empty catch blocks, unchecked result errors
Measured by
unhandled error count
Refactored by
Add Error Type, Propagate Context, Handle Explicitly
Enforced by
linting, tests
Before
async function loadFoo(id: FooId) { try { return await fooStore.find(id); } catch { return null; } }
After
type LoadFooResult = | { ok: true; value: Foo } | { ok: false; error: "NOT_FOUND" | "STORE_UNAVAILABLE" }; async function loadFoo(id: FooId): Promise<LoadFooResult> { return fooStore.findResult(id); }

Error Boundaries

Details
Violated by
uncontained failures crashing whole system
Detected by
uncaught exceptions crossing boundary
Measured by
blast radius
Refactored by
Add Boundary Handler, Isolate Component
Enforced by
failure tests
Before
function renderApp() { return renderFooPanel(loadFoo()); }
After
function FooBoundary({ render }: { render(): View }) { try { return render(); } catch (error) { return renderFooError(toFooError(error)); } } const app = FooBoundary({ render: () => renderFooPanel(loadFoo()) });

Fallback Pattern

Details
Violated by
no alternate path for noncritical dependency
Detected by
hard dependency in optional path
Measured by
fallback coverage
Refactored by
Add Fallback Response/Provider
Enforced by
failure injection tests
Before
const foo = await primaryFooStore.find(id);
After
const foo = await primaryFooStore.find(id).catch(() => replicaFooStore.find(id)); if (!foo) throw new FooUnavailableError(id);

Retry Pattern

Details
Violated by
blind retry without backoff/idempotency
Detected by
retry loops without timeout/backoff
Measured by
retry success rate, retry storm rate
Refactored by
Add Exponential Backoff, Idempotency Key
Enforced by
resilience libraries, policy checks
Before
await remoteFoo.save(foo);
After
await retry.withBackoff( () => remoteFoo.save(foo), { attempts: 3, retryIf: isTransientError, jitter: true }, );

Timeout Pattern

Details
Violated by
external calls without timeout
Detected by
missing timeout config
Measured by
timeout coverage, latency tail
Refactored by
Add Timeout, Propagate Deadline
Enforced by
lint/config checks
Before
const foo = await remoteFoo.find(id);
After
const foo = await withTimeout(remoteFoo.find(id), 500, () => new FooTimeoutError(id));

Circuit Breaker Pattern

Details
Violated by
continuing calls to failing dependency
Detected by
high failure dependency calls without breaker
Measured by
breaker trip rate, downstream error rate
Refactored by
Add Circuit Breaker
Before
async function loadFoo(id: FooId) { return remoteFoo.find(id); }
After
const fooBreaker = new CircuitBreaker({ failureThreshold: 5, resetAfterMs: 30_000 }); async function loadFoo(id: FooId) { return fooBreaker.execute(() => remoteFoo.find(id)); }

Bulkhead Pattern

Details
Violated by
one dependency consuming all threads/connections
Detected by
shared pools across critical/noncritical workloads
Measured by
resource saturation isolation
Refactored by
Split Resource Pools, Add Isolation
Enforced by
resource policy
Before
const pool = new WorkerPool(100); pool.submit(fooTask); pool.submit(barTask);
After
const fooPool = new WorkerPool(20); const barPool = new WorkerPool(20); fooPool.submit(fooTask); barPool.submit(barTask);

Backpressure

Details
Violated by
unbounded queues, uncontrolled producers
Detected by
queue growth without throttling
Measured by
queue depth, rejection/throttle rate
Refactored by
Add Rate Limit, Bounded Queue, Demand Signal
Enforced by
load tests, runtime policies
Before
stream.on("data", foo => processFoo(foo));
After
for await (const foo of stream) { await capacity.acquire(); void processFoo(foo).finally(() => capacity.release()); }

Event / Messaging / Asynchronous Architecture

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_event_driven_architecture["Event-Driven Architecture"]
    n_publish_subscribe_pattern["Publish/Subscribe Pattern"]
    n_message_queue["Message Queue"]
    n_message_broker["Message Broker"]
    n_event_bus["Event Bus"]
    n_event_stream["Event Stream"]
    n_event_sourcing["Event Sourcing"]
    n_command_query_responsibility_segregation["CQRS"]
    n_domain_events["Domain Events"]
    n_integration_events["Integration Events"]
    n_asynchronous_communication["Asynchronous Communication"]
    n_service_autonomy["Service Autonomy"]
    n_eventual_consistency["Eventual Consistency"]
    n_saga_pattern["Saga Pattern"]
    n_outbox_pattern["Outbox Pattern"]
    n_compensating_transaction["Compensating Transaction"]
    n_append_only_log["Append-Only Log"]
    n_dead_letter_queue["Dead-Letter Queue"]
    n_idempotent_consumer["Idempotent Consumer"]
    n_competing_consumers["Competing Consumers"]
    n_event_driven_architecture --> n_asynchronous_communication
    n_event_driven_architecture --> n_event_sourcing
    n_event_driven_architecture --> n_command_query_responsibility_segregation
    n_event_bus --> n_event_driven_architecture
    n_event_sourcing --> n_append_only_log
    n_event_sourcing --> n_domain_events
    n_command_query_responsibility_segregation --> n_event_sourcing
    n_command_query_responsibility_segregation -.-> n_eventual_consistency
    n_domain_events --> n_event_driven_architecture
    n_asynchronous_communication --> n_event_driven_architecture
    n_saga_pattern --> n_eventual_consistency
    n_compensating_transaction --> n_saga_pattern
    n_append_only_log --> n_event_sourcing
    n_dead_letter_queue --> n_message_queue
    n_idempotent_consumer --> n_eventual_consistency
    n_competing_consumers --> n_message_queue

Event-Driven Architecture

Details
Violated by
non-idempotent consumers, undocumented event schemas
Detected by
missing correlation IDs, direct synchronous chains
Measured by
event contract coverage, retry safety
Refactored by
Publish Event, Add Outbox, Add Consumer Contract
Enforced by
schema registry, idempotency tests
Before
async function createFoo(foo: Foo) { await fooStore.save(foo); await barService.refresh(foo.id); await bazService.notify(foo.id); }
After
async function createFoo(foo: Foo) { await fooStore.save(foo); await events.publish({ type: "FooCreated", fooId: foo.id }); } events.on("FooCreated", updateBarProjection); events.on("FooCreated", notifyBaz);

Publish/Subscribe Pattern

Details
Violated by
publisher knowing all subscribers
Detected by
direct calls to subscriber list
Measured by
publisher-subscriber coupling
Refactored by
Introduce Topic/Event Bus
Enforced by
messaging contracts
Before
function saveFoo(foo: Foo) { fooStore.save(foo); auditFoo(foo); indexFoo(foo); }
After
publisher.publish("foo.saved", { fooId: foo.id }); subscriber.on("foo.saved", auditFoo); subscriber.on("foo.saved", indexFoo);

Message Queue

Details
Violated by
unbounded in-memory work queues
Detected by
synchronous blocking chains for async work
Measured by
queue depth, retry/dead-letter rates
Refactored by
Introduce Queue, Add Worker
Enforced by
infrastructure policy, load tests
Before
for (const foo of foos) await processFoo(foo);
After
for (const foo of foos) await fooQueue.enqueue({ type: "ProcessFoo", foo }); fooWorker.consume(fooQueue, message => processFoo(message.foo));

Message Broker

Details
Violated by
broker bypass for async integration
Detected by
direct service calls in async workflows
Measured by
broker usage coverage
Refactored by
Add Broker, Route Messages
Enforced by
architecture policy
Before
await fooService.sendToBar(barMessage); await fooService.sendToBaz(bazMessage);
After
await broker.publish("foo.created", fooMessage, { durable: true }); broker.subscribe("foo.created", { group: "bar-consumer", ack: "manual" }, handleBar); broker.subscribe("foo.created", { group: "baz-consumer", ack: "manual" }, handleBaz);

Event Bus

Details
Violated by
hidden implicit event dependencies
Detected by
undocumented subscribers
Measured by
event dependency visibility
Refactored by
Introduce Event Bus, Register Handlers
Enforced by
handler registry validation
Before
fooEditor.onSave = foo => fooView.refresh(foo); fooEditor.onDelete = id => fooView.remove(id);
After
eventBus.emit({ type: "FooSaved", foo }); eventBus.emit({ type: "FooDeleted", fooId: id }); eventBus.on("FooSaved", event => fooView.refresh(event.foo));

Event Stream

Details
Violated by
non-replayable event processing
Detected by
missing offsets, missing event schema
Measured by
replay success, lag
Refactored by
Add Stream, Add Offset Tracking
Enforced by
stream contract tests
Before
const latest = await fooApi.getCurrentState(fooId);
After
const stream = fooEvents.stream(fooId); for await (const event of stream) fooProjection.apply(event);

Event Sourcing

Details
Violated by
mutating state without event record
Detected by
state changes lacking events
Measured by
event/state consistency
Refactored by
Persist Events, Build Projections
Enforced by
event append rules
Before
type FooRow = { id: FooId; name: string; status: string }; await fooTable.update(foo);
After
type FooEvent = FooCreated | FooRenamed | FooClosed; await fooEventStore.append(foo.id, foo.uncommittedEvents()); const foo = fooEventStore.read(fooId).reduce(applyFooEvent, emptyFoo());

CQRS

Details
Violated by
queries mutating state, commands returning complex read models
Detected by
command/query side-effect violations
Measured by
read/write separation compliance
Refactored by
Split Command and Query Models
Enforced by
handler conventions, tests
Before
class FooRepository { save(foo: Foo) {} search(query: string): Foo[] { return complexJoin(query); } }
After
class FooCommandStore { save(foo: Foo) { return fooDb.write(foo); } } class FooQueryStore { search(query: string) { return fooReadModel.search(query); } } commandBus.execute(new SaveFoo(foo)); queryBus.execute(new SearchFoos(query));

Domain Events

Details
Violated by
events named after technical operations only
Detected by
CRUD-named domain events
Measured by
semantic event quality
Refactored by
Rename Event, Emit from Aggregate
Enforced by
domain review
Before
class Foo { rename(name: string) { this.name = name; } }
After
class Foo { #events: FooDomainEvent[] = []; rename(name: string) { this.name = name; this.#events.push({ type: "FooRenamed", fooId: this.id, name }); } }

Integration Events

Details
Violated by
exposing internal domain events directly to external consumers
Detected by
internal event schema published externally
Measured by
boundary event contract coverage
Refactored by
Map Domain Event to Integration Event
Enforced by
event schema review
Before
barService.consume(fooDomainEvent);
After
const integrationEvent: FooCreatedV1 = { type: "com.example.foo-created.v1", fooId: event.fooId, occurredAt: clock.now().toISOString(), }; integrationBus.publish(integrationEvent);

Asynchronous Communication

Details
Violated by
synchronous call chain for non-immediate work
Detected by
long blocking chains
Measured by
sync dependency depth
Refactored by
Introduce Queue/Event, Add Callback/Projection
Before
const bar = await barService.createFromFoo(foo); const baz = await bazService.createFromBar(bar);
After
await outbox.append({ type: "FooCreated", fooId: foo.id }); return { accepted: true, fooId: foo.id };

Service Autonomy

Details
Violated by
external writes to service-owned data
Detected by
shared schema writes, cross-service table access
Measured by
ownership violation count
Refactored by
Encapsulate Data, Add API/Event Boundary
Enforced by
database permissions, service contracts
Before
async function saveFoo(foo: Foo) { await barDb.verify(foo.barId); await bazDb.reserve(foo.bazId); await fooDb.save(foo); }
After
async function saveFoo(foo: Foo) { await fooDb.save(foo); await outbox.append({ type: "FooSaved", fooId: foo.id, barId: foo.barId, bazId: foo.bazId }); }

Eventual Consistency

Details
Violated by
assuming immediate cross-service consistency
Detected by
synchronous compensation hacks
Measured by
convergence time, inconsistency window
Refactored by
Add Projection, Add Reconciliation, Add Saga
Enforced by
consistency tests
Before
await fooStore.save(foo); await fooSearch.update(foo); await fooAnalytics.update(foo);
After
await fooStore.save(foo); fooEvents.emit({ type: "FooSaved", foo }); const view = await fooSearchView.find(foo.id); const converged = view.version >= foo.version; return { foo: view, converged };

Saga Pattern

Details
Violated by
cross-service transaction requiring atomic database commit
Detected by
distributed transaction attempts
Measured by
compensation coverage
Refactored by
Introduce Saga, Add Compensation
Enforced by
workflow tests
Before
const tx = coordinator.begin(); await fooService.prepare(tx, foo); await barService.prepare(tx, bar); await bazService.prepare(tx, baz); await coordinator.commit(tx);
After
await saga([ { action: () => fooService.create(foo), compensate: id => fooService.cancel(id) }, { action: () => barService.create(bar), compensate: id => barService.cancel(id) }, { action: () => bazService.create(baz), compensate: id => bazService.cancel(id) }, ]).run();

Outbox Pattern

Details
Violated by
database write followed by direct publish without atomicity
Detected by
dual-write patterns
Measured by
lost-message rate, outbox coverage
Refactored by
Add Outbox Table, Add Relay Worker
Enforced by
persistence rules, integration tests
Before
await fooStore.save(foo); await eventBus.publish({ type: "FooSaved", fooId: foo.id });
After
await database.transaction(async tx => { await tx.foos.save(foo); await tx.outbox.insert({ id: eventId(), type: "FooSaved", fooId: foo.id }); }); await outboxRelay.publishPending();

Compensating Transaction

Details
Violated by
unrecoverable partial workflow failure
Detected by
saga steps without compensation
Measured by
compensation coverage
Refactored by
Add Compensation Action
Enforced by
workflow tests
Before
await fooService.create(foo); await barService.create(bar);
After
const fooId = await fooService.create(foo); try { await barService.create(bar); } catch (error) { await fooService.compensateCreate(fooId); throw error; }

Append-Only Log

Details
Violated by
updating historical records destructively
Detected by
mutable event rows
Measured by
append-only compliance
Refactored by
Append Events, Add Snapshot/Compaction
Enforced by
database constraints
Before
fooState.set(foo.id, foo); fooState.delete(foo.id);
After
type FooLogEntry = FooCreated | FooUpdated | FooRemoved; fooLog.append({ seq: nextSeq(), type: "FooRemoved", fooId: foo.id }); const state = projectFooLog(fooLog.read());

Dead-Letter Queue

  • Kind: pattern
  • Severity: mandatory for production systems
  • Scope: service, messaging, resilience
  • Layer: Execution Core
Details
Violated by
unprocessable messages redelivered forever
Detected by
retry storms on a single poison message
Measured by
redelivery count per failed message
Refactored by
Route Failures to a Dead-Letter Queue
Enforced by
messaging design review
Before
worker.consume(fooQueue, async message => { await processFoo(message); });
After
worker.consume(fooQueue, async message => { try { await processFoo(message); } catch (error) { if (message.attempts >= 5) return fooDeadLetterQueue.send(message, error); throw error; } });

Idempotent Consumer

  • Kind: pattern
  • Severity: mandatory for distributed systems
  • Scope: service, messaging, correctness
  • Layer: Execution Core
Details
Violated by
a redelivered message applied twice
Detected by
duplicate effects under at-least-once delivery
Measured by
duplicate-processing incident rate
Refactored by
Make the Consumer Idempotent
Enforced by
messaging design review
Before
worker.consume(fooQueue, message => chargeFoo(message.fooId, message.amount));
After
worker.consume(fooQueue, async message => { if (await processedMessages.has(message.id)) return; await chargeFoo(message.fooId, message.amount); await processedMessages.add(message.id); });

Competing Consumers

Details
Violated by
one consumer serially draining a growing backlog
Detected by
queue depth rising with a single processor
Measured by
consumer utilization vs backlog growth
Refactored by
Scale Out Competing Consumers
Enforced by
messaging design review
Before
fooWorker.consume(fooQueue, processFoo);
After
for (let worker = 0; worker < WORKER_COUNT; worker += 1) { new FooWorker(worker).consume(fooQueue, processFoo); }

Metadata / Self-Description / Declarative Systems

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_self_describing_architecture["Self-Describing Architecture"]
    n_self_describing_api["Self-Describing API"]
    n_self_describing_structures["Self-Describing Structures"]
    n_metadata_driven_design["Metadata-Driven Design"]
    n_declarative_configuration["Declarative Configuration"]
    n_convention_over_configuration["Convention over Configuration"]
    n_capability_declaration["Capability Declaration"]
    n_manifest_based_design["Manifest-Based Design"]
    n_self_describing_architecture --> n_capability_declaration
    n_metadata_driven_design --> n_declarative_configuration
    n_manifest_based_design --> n_self_describing_architecture
    n_manifest_based_design --> n_capability_declaration

Self-Describing Architecture

Details
Violated by
behavior not represented in metadata/contracts
Detected by
undocumented runtime capability
Measured by
metadata coverage
Refactored by
Add Manifest, Add Metadata, Add Schema
Enforced by
manifest validation, metadata tests
Before
const modules = [new FooModule(), new BarModule()];
After
type ModuleDescriptor = { name: string; version: string; provides: readonly string[]; requires: readonly string[] }; const fooModule = defineModule({ name: "foo", version: "1.0.0", provides: ["FooStore"], requires: ["EventBus"] });

Self-Describing API

Details
Violated by
undocumented endpoints, opaque error responses
Detected by
missing OpenAPI/metadata
Measured by
API documentation/contract coverage
Refactored by
Add OpenAPI, Add Metadata, Normalize Responses
Enforced by
API linting, docs gates
Before
app.post("/foo", createFoo);
After
const createFooApi = defineEndpoint({ method: "POST", path: "/foos", request: CreateFooSchema, response: FooCreatedSchema, errors: FooErrorSchema, });

Self-Describing Structures

Details
Violated by
data requiring external hidden assumptions
Detected by
missing type/schema markers
Measured by
metadata completeness
Refactored by
Add Type Tags, Add Schema, Add Manifest
Before
const node = ["foo", "foo_1", 3, true];
After
const node = { kind: "foo", id: "foo_1", count: 3, active: true } as const;

Metadata-Driven Design

Details
Violated by
unvalidated metadata, hidden magic
Detected by
metadata/config drift
Measured by
metadata coverage, config error rate
Refactored by
Extract Metadata, Add Schema, Validate Config
Enforced by
metadata schema tests
Before
if (field === "name") renderText(); if (field === "count") renderNumber();
After
const fooFields = { name: { kind: "text", required: true }, count: { kind: "integer", min: 0 }, } as const; renderForm(fooFields);

Declarative Configuration

Details
Violated by
behavior hidden in code constants
Detected by
hardcoded environment values
Measured by
configuration externalization coverage
Refactored by
Extract Config, Add Config Schema
Enforced by
config linting, validation
Before
const app = new FooApp(); app.enableCache(); app.setRetries(3); app.register(new BarPlugin());
After
const config = defineFooConfig({ cache: { enabled: true }, retries: 3, plugins: ["bar"], }); const app = FooApp.fromConfig(config);

Convention over Configuration

Details
Violated by
inconsistent project conventions
Detected by
convention deviations
Measured by
convention compliance score
Refactored by
Normalize Structure, Remove Redundant Config
Enforced by
scaffolding, lint rules
Before
registerHandler("foo", "./handlers/foo-handler", "FooHandler"); registerHandler("bar", "./handlers/bar-handler", "BarHandler");
After
const handlers = discoverHandlers("./handlers/*.handler.ts");

Capability Declaration

Details
Violated by
capability exists but is undocumented/unregistered
Detected by
manifest-code mismatch
Measured by
declared/actual capability match rate
Refactored by
Add Manifest Entry, Add Capability Interface
Enforced by
manifest validation, conformance tests
Before
try { await plugin.exportFoo(foo); } catch (error) { if (isMissingMethod(error)) return; }
After
type FooPlugin = { capabilities: readonly ("read" | "write" | "export")[]; exportFoo?: (foo: Foo) => Promise<void>; }; if (plugin.capabilities.includes("export")) await plugin.exportFoo!(foo);

Manifest-Based Design

Details
Violated by
undeclared dependencies/capabilities
Detected by
manifest mismatch, load failure
Measured by
manifest validation pass rate
Refactored by
Add Manifest, Validate Manifest, Generate Manifest
Enforced by
CI validation
Before
loadPlugin("./foo.js"); loadPlugin("./bar.js");
After
const manifest = { name: "foo-suite", plugins: [ { name: "foo", entry: "./foo.js", version: "1.0.0" }, { name: "bar", entry: "./bar.js", version: "1.0.0" }, ], } as const; loadManifest(manifest);

Metaprogramming / Language-Oriented Architecture

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_homoiconicity["Homoiconicity"]
    n_code_as_data["Code as Data"]
    n_metaprogramming["Metaprogramming"]
    n_reflection["Reflection"]
    n_introspection["Introspection"]
    n_compile_time_evaluation["Compile-Time Evaluation"]
    n_runtime_code_generation["Runtime Code Generation"]
    n_domain_specific_language["Domain-Specific Language (DSL)"]
    n_language_oriented_programming["Language-Oriented Programming"]
    n_model_driven_architecture["Model-Driven Architecture"]
    n_homoiconicity --> n_metaprogramming
    n_code_as_data --> n_homoiconicity
    n_reflection --> n_introspection

Homoiconicity

Details
Violated by
not applicable as compliance principle unless language supports it
Detected by
language capability check
Measured by
macro/code-as-data usage
Refactored by
Use AST/DSL/Macro Representation
Enforced by
language/tooling constraints
Before
function evaluateFoo(foo: Foo) { return foo.value * 2; } const fooRule = { operation: "multiply", operand: 2 };
After
type Expr = | { op: "value"; key: keyof Foo } | { op: "const"; value: number } | { op: "multiply"; left: Expr; right: Expr }; const fooRule: Expr = { op: "multiply", left: { op: "value", key: "value" }, right: { op: "const", value: 2 } }; const result = evaluate(fooRule, foo);

Code as Data

Details
Violated by
unsafe string eval/generation
Detected by
dynamic eval/string code construction
Measured by
unsafe eval count
Refactored by
Use AST Builder, Typed DSL
Enforced by
banned API rules
Before
function fooRule(foo: Foo) { return foo.count > 3 && foo.active; }
After
const fooRule = { op: "and", args: [ { op: "gt", field: "count", value: 3 }, { op: "eq", field: "active", value: true }, ], } as const; executeRule(fooRule, foo);

Metaprogramming

Details
Violated by
unsafe/opaque generated behavior
Detected by
dynamic generation without tests/schema
Measured by
generated code coverage, complexity
Refactored by
Add Generator Tests, Make Metadata Explicit
Enforced by
generator validation
Before
class FooDto { id!: string; name!: string; } class BarDto { id!: string; name!: string; }
After
const entity = defineEntity({ id: string(), name: string() }); const FooDto = generateType("FooDto", entity); const BarDto = generateType("BarDto", entity);

Reflection

Details
Violated by
reflection used to bypass contracts/visibility
Detected by
reflective access to internals
Measured by
unsafe reflection count
Refactored by
Replace with Explicit Interface/Metadata
Enforced by
lint/security rules
Before
const fields = ["id", "name", "count"]; for (const field of fields) renderField(foo[field]);
After
for (const [field, metadata] of reflect(FooSchema).entries()) { renderField(field, metadata, foo[field]); }

Introspection

Details
Violated by
relying on undocumented internal structure
Detected by
introspection of private internals
Measured by
introspection usage risk
Refactored by
Add Public Metadata API
Enforced by
API boundaries
Before
function supportsExport(plugin: any) { try { plugin.exportFoo(foo); return true; } catch { return false; } }
After
function supportsExport(plugin: Plugin) { return introspect(plugin).methods.includes("exportFoo"); }

Compile-Time Evaluation

Details
Violated by
runtime work that could be validated/generated at compile time
Detected by
repeated runtime reflection/validation
Measured by
compile-time coverage
Refactored by
Move Check/Generation to Compile Time
Enforced by
compiler plugins/build checks
Before
const fooRoutes = buildRoutesAtStartup(fooRouteDefinitions);
After
const fooRoutes = compileTime(() => buildRoutes(fooRouteDefinitions)); export const routeTable = fooRoutes;

Runtime Code Generation

Details
Violated by
unsafe eval, untrusted code generation
Detected by
dynamic eval with external input
Measured by
unsafe generation paths
Refactored by
Use Safe Generator, Sandbox, Precompile
Enforced by
Before
function mapFoo(row: any) { return { id: row["foo_id"], name: row["foo_name"], count: row["foo_count"] }; }
After
const mapFoo = generateMapper<FooRow, Foo>({ foo_id: "id", foo_name: "name", foo_count: "count", });

Domain-Specific Language (DSL)

Details
Violated by
ambiguous ad-hoc mini-language
Detected by
stringly-typed rules without parser/schema
Measured by
DSL validation coverage
Refactored by
Define Grammar, Add Parser/Validator
Enforced by
DSL tests, schema/grammar checks
Before
createWorkflow([ { type: "validate", target: "foo" }, { type: "save", target: "foo" }, { type: "publish", target: "foo.created" }, ]);
After
fooWorkflow("create", flow => flow.validate(FooSchema) .save("FooStore") .publish("FooCreated") );

Language-Oriented Programming

Details
Violated by
proliferation of informal unvalidated DSLs
Detected by
multiple inconsistent rule/config syntaxes
Measured by
language consistency/tooling
Refactored by
Consolidate DSL, Add Tooling
Enforced by
grammar/schema validation
Before
function processFoo(config: Record<string, unknown>) { interpretAdHocConfig(config); }
After
const FooPolicyLanguage = defineLanguage({ expressions: ["field", "equals", "all", "any"], typeChecker: fooPolicyTypeChecker, evaluator: fooPolicyEvaluator, }); FooPolicyLanguage.run(fooPolicy, foo);

Model-Driven Architecture

Details
Violated by
generated code manually edited/diverged
Detected by
model-code drift
Measured by
generation conformance
Refactored by
Regenerate, Lock Generated Files, Update Model
Enforced by
generation CI
Before
class FooController {} class FooService {} class FooRepository {} class FooDto {}
After
const fooModel = defineModel({ entity: "Foo", fields: { id: "FooId", name: "string" }, operations: ["create", "read", "rename"], }); generateApplication(fooModel);

Observability / Auditability / Traceability

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_observability["Observability"]
    n_logging["Logging"]
    n_monitoring["Monitoring"]
    n_alerting["Alerting"]
    n_auditability["Auditability"]
    n_audit_logging["Audit Logging"]
    n_traceability["Traceability"]
    n_correlation_id["Correlation ID"]
    n_causation_id["Causation ID"]
    n_distributed_tracing["Distributed Tracing"]
    n_slo_sli["SLO/SLI"]
    n_dashboards["Dashboards"]
    n_logging --> n_traceability
    n_alerting --> n_monitoring
    n_auditability --> n_audit_logging
    n_auditability --> n_traceability
    n_audit_logging --> n_auditability
    n_audit_logging --> n_traceability
    n_traceability --> n_correlation_id
    n_traceability --> n_auditability
    n_correlation_id --> n_distributed_tracing
    n_distributed_tracing --> n_observability
    n_slo_sli --> n_monitoring
    n_slo_sli --> n_observability
    n_slo_sli --> n_alerting
    n_dashboards --> n_monitoring
    n_dashboards --> n_observability
    n_dashboards --> n_traceability

Observability

Details
Violated by
production behavior cannot be inferred
Detected by
missing telemetry around critical paths
Measured by
telemetry coverage, MTTR
Refactored by
Add Logs/Metrics/Traces
Enforced by
observability standards
Before
async function processFoo(foo: Foo) { await fooStore.save(foo); }
After
async function processFoo(foo: Foo, telemetry: Telemetry) { return telemetry.trace("foo.process", { fooId: foo.id }, async span => { await fooStore.save(foo); span.event("foo.saved"); telemetry.count("foo.processed", 1); }); }

Logging

Details
Violated by
missing or unstructured critical logs
Detected by
absence of logs on error/business events
Measured by
log coverage, signal/noise ratio
Refactored by
Add Structured Logs, Add Context
Enforced by
logging policy, linting
Before
console.log("saved", foo);
After
logger.info("foo.saved", { fooId: foo.id, version: foo.version });

Monitoring

Details
Violated by
no metrics for critical resources/SLIs
Detected by
missing dashboards/SLI metrics
Measured by
metric coverage, detection latency
Refactored by
Add Metrics, Define SLIs
Enforced by
production readiness checklist
Before
setInterval(() => report(fooQueue.length), 60_000);
After
metrics.gauge("foo.queue.depth", () => fooQueue.length); metrics.histogram("foo.processing.duration_ms", fooProcessingDuration);

Alerting

Details
Violated by
critical failures without alert
Detected by
incident discovered by users before systems
Measured by
MTTD, alert precision
Refactored by
Add Alert, Tune Thresholds
Enforced by
on-call policy
Before
if (errorRate > 0.05) notify("foo errors");
After
alerts.define("FooErrorBudgetBurn", { condition: rate("foo.errors", "5m") > 0.05, for: "10m", severity: "critical", });

Auditability

Details
Violated by
critical action without audit record
Detected by
missing audit event for sensitive operation
Measured by
audit event coverage
Refactored by
Add Audit Log, Add Actor/Reason Metadata
Enforced by
compliance gates
Before
function renameFoo(foo: Foo, name: string) { foo.name = name; }
After
function renameFoo(foo: Foo, name: string, actor: Actor) { const previous = foo.name; foo.rename(name); audit.append({ action: "FooRenamed", fooId: foo.id, actorId: actor.id, previous, next: name }); }

Audit Logging

  • Kind: mechanism
  • Severity: mandatory for sensitive systems
  • Scope: security, compliance, data mutation
  • Layer: Observability
Details
Enables
In tension with
Conflicts with
Referenced by
Violated by
sensitive operation without immutable record
Detected by
missing audit instrumentation
Measured by
audit coverage
Refactored by
Add Audit Event, Protect Audit Store
Enforced by
Before
logger.info(`user ${user.id} changed foo ${foo.id}`);
After
auditLog.append({ eventId: eventId(), action: "FOO_UPDATE", actorId: user.id, resourceId: foo.id, occurredAt: clock.now().toISOString(), });

Traceability

Details
Violated by
uncorrelated logs/events
Detected by
missing correlation propagation
Measured by
trace completeness
Refactored by
Add Correlation ID, Propagate Context
Enforced by
middleware, tracing policy
Before
await processFoo(foo);
After
const trace = traceContext.start({ operation: "processFoo", fooId: foo.id }); await processFoo(foo, trace); trace.finish();

Correlation ID

  • Kind: mechanism
  • Severity: mandatory for distributed systems
  • Scope: request, message, workflow
  • Layer: Observability
Details
Violated by
logs/events without correlation identifier
Detected by
missing correlation field
Measured by
correlation coverage
Refactored by
Add Middleware, Propagate Header
Enforced by
logging/tracing standards
Before
await http.post("/bar", { fooId: foo.id });
After
const correlationId = request.headers.get("X-Correlation-ID") ?? idSource.next(); await http.post("/bar", { fooId: foo.id }, { headers: { "X-Correlation-ID": correlationId } });

Causation ID

Details
Violated by
event chains without parent cause
Detected by
missing causation field in event metadata
Measured by
causation coverage
Refactored by
Add Causation Metadata
Enforced by
event schema rules
Before
events.publish({ id: eventId(), type: "BarCreated", fooId: event.fooId });
After
events.publish({ id: eventId(), type: "BarCreated", fooId: event.fooId, correlationId: event.correlationId, causationId: event.id, });

Distributed Tracing

  • Kind: mechanism
  • Severity: mandatory for distributed systems
  • Scope: distributed system, service mesh
  • Layer: Observability
Details
Violated by
service calls without trace propagation
Detected by
broken traces, missing spans
Measured by
trace completeness, span coverage
Refactored by
Add Tracing Middleware, Propagate Context
Enforced by
observability policy
Before
await fooService.call(); await barService.call();
After
await tracer.span("foo.request", async span => { await fooService.call({ traceparent: span.traceparent }); await barService.call({ traceparent: span.traceparent }); });

SLO/SLI

  • Kind: constraint
  • Severity: mandatory for production systems
  • Scope: service, reliability, operations
  • Layer: Observability
Details
Violated by
reliability judged by subjective feel
Detected by
no measured indicator behind reliability claims
Measured by
SLO attainment vs error budget
Refactored by
Define SLIs and SLOs
Enforced by
reliability review
Before
alert.when(latency > 1000);
After
const fooLatencySli = ratio("foo.requests.fast", "foo.requests.total"); defineSLO("foo-latency", { sli: fooLatencySli, objective: 0.99, window: "30d", errorBudget: 0.01 });

Dashboards

Details
Violated by
operators grepping raw logs to judge health
Detected by
no curated view of key signals
Measured by
time-to-diagnose during incidents
Refactored by
Build Signal Dashboards
Enforced by
operations review
Before
grepLogsForFooErrors();
After
const fooDashboard = dashboard("foo-health", { panels: [rate("foo.errors"), histogram("foo.latency"), gauge("foo.queue.depth")], });

Plugin / Extensibility / IoC

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_plugin_architecture["Plugin Architecture"]
    n_extension_points["Extension Points"]
    n_inversion_of_control["Inversion of Control (IoC)"]
    n_dependency_injection["Dependency Injection"]
    n_service_registry["Service Registry"]
    n_registry_pattern["Registry Pattern"]
    n_service_locator_pattern["Service Locator Pattern"]
    n_feature_toggle["Feature Toggle"]
    n_plugin_architecture --> n_extension_points
    n_extension_points --> n_plugin_architecture
    n_inversion_of_control --> n_dependency_injection

Plugin Architecture

Details
Violated by
core importing plugin implementations
Detected by
direct plugin imports, central switch for plugins
Measured by
plugin isolation score
Refactored by
Introduce SPI, Add Registry, Extract Extension Point
Enforced by
plugin contract tests, dependency rules
Before
class FooApp { run() { new FooExport().run(); new BarExport().run(); } }
After
interface FooPlugin { name: string; setup(app: FooApp): void; } class FooApp { constructor(private readonly plugins: readonly FooPlugin[]) {} run() { this.plugins.forEach(plugin => plugin.setup(this)); } }

Extension Points

Details
Violated by
modifying internals to add behavior
Detected by
repeated core edits for variants
Measured by
extension coverage
Refactored by
Add Hook, Add SPI, Extract Interface
Enforced by
extension tests, API review
Before
function saveFoo(foo: Foo) { validateFoo(foo); fooStore.save(foo); sendFooEmail(foo); }
After
type FooHooks = { beforeSave: Array<(foo: Foo) => void>; afterSave: Array<(foo: Foo) => void> }; function saveFoo(foo: Foo, hooks: FooHooks) { hooks.beforeSave.forEach(hook => hook(foo)); fooStore.save(foo); hooks.afterSave.forEach(hook => hook(foo)); }

Inversion of Control (IoC)

Details
Violated by
application manually controlling framework-owned lifecycle
Detected by
scattered object lifecycle construction
Measured by
composition centralization
Refactored by
Introduce Container, Extract Composition Root
Enforced by
lifecycle rules
Before
class FooJob { run() { const store = new SqlFooStore(); return store.save(makeFoo()); } }
After
class FooJob { constructor(private readonly make: () => Foo, private readonly store: FooStore) {} run() { return this.store.save(this.make()); } } container.run(FooJob);

Dependency Injection

Details
Violated by
newing dependencies inside business logic
Detected by
direct construction of external dependencies
Measured by
injected dependency ratio
Refactored by
Inject Constructor Parameter, Add Factory
Enforced by
lint rules, dependency review
Before
class FooService { private readonly clock = new SystemClock(); private readonly store = new SqlFooStore(); }
After
class FooService { constructor(private readonly clock: Clock, private readonly store: FooStore) {} }

Service Registry

Details
Violated by
manual endpoint/plugin lookup
Detected by
static lookup tables
Measured by
registry coverage
Refactored by
Register Service, Add Discovery Client
Enforced by
startup checks, health checks
Before
const fooService = new FooService(new SqlFooStore()); const barService = new BarService(new SqlBarStore());
After
const services = new ServiceRegistry(); services.register("FooStore", () => new SqlFooStore()); services.register("FooService", r => new FooService(r.resolve("FooStore")));

Registry Pattern

Details
Violated by
ungoverned global registry
Detected by
mutable global maps without lifecycle
Measured by
registry consistency
Refactored by
Encapsulate Registry, Add Typed Keys
Enforced by
registry validation
Before
function makeFoo(kind: string) { if (kind === "foo") return new Foo1(); if (kind === "bar") return new Bar(); throw new Error("unknown kind"); }
After
type FooFactory = () => Foo; const registry = new Map<string, FooFactory>(); export const registerFoo = (kind: string, factory: FooFactory) => registry.set(kind, factory); export const makeFoo = (kind: string) => registry.get(kind)?.() ?? fail(`unknown ${kind}`);

Service Locator Pattern

Details
Violated by
hidden dependencies through global locator
Detected by
service locator calls inside domain logic
Measured by
hidden dependency count
Refactored by
Replace with Dependency Injection
Enforced by
banned API rules
Before
class FooController { save(foo: Foo) { const store = serviceLocator.resolve<FooStore>("FooStore"); return store.save(foo); } }
After
class FooController { constructor(private readonly store: FooStore) {} save(foo: Foo) { return this.store.save(foo); } }

Feature Toggle

Details
Violated by
release paths gated by a hardcoded boolean constant
Detected by
compile-time flags requiring redeploy to flip
Measured by
redeploys per behavior change
Refactored by
Introduce Runtime Feature Flags
Enforced by
release review
Before
if (NEW_FOO_FLOW_ENABLED) runNewFooFlow(); else runOldFooFlow();
After
if (featureFlags.enabled("new-foo-flow", { user, percentage: 10 })) runNewFooFlow(); else runOldFooFlow();

Portability / Infrastructure / Deployment

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_portability["Portability"]
    n_platform_independence["Platform Independence"]
    n_environment_parity["Environment Parity"]
    n_containerization["Containerization"]
    n_infrastructure_as_code["Infrastructure as Code"]
    n_standards_compliance["Standards Compliance"]
    n_protocol_independence["Protocol Independence"]
    n_configuration_externalization["Configuration Externalization"]
    n_immutable_infrastructure["Immutable Infrastructure"]
    n_platform_independence --> n_portability
    n_environment_parity --> n_configuration_externalization
    n_environment_parity --> n_infrastructure_as_code
    n_containerization --> n_portability
    n_containerization --> n_environment_parity
    n_protocol_independence --> n_portability
    n_configuration_externalization --> n_portability
    n_configuration_externalization --> n_environment_parity
    n_immutable_infrastructure --> n_infrastructure_as_code
    n_immutable_infrastructure --> n_environment_parity

Portability

Details
Violated by
direct dependency on non-abstracted platform APIs
Detected by
platform-specific imports in core
Measured by
portability violation count
Refactored by
Add Adapter, Externalize Platform Dependency
Enforced by
dependency rules
Before
const path = "C:\\foo\\data\\foos.json"; const processId = windowsApi.currentProcessId();
After
const path = join(config.dataDirectory, "foos.json"); const processId = runtime.processId();

Platform Independence

Details
Violated by
hardcoded platform assumptions
Detected by
OS-specific paths/APIs in portable layers
Measured by
cross-platform test pass rate
Refactored by
Abstract Platform API, Normalize Paths
Enforced by
cross-platform CI
Before
function saveFoo(foo: Foo) { return winRegistry.write("Foo", foo); }
After
interface FooPersistence { save(foo: Foo): Promise<void>; } function saveFoo(foo: Foo, persistence: FooPersistence) { return persistence.save(foo); }

Environment Parity

Details
Violated by
environment-specific behavior not config-driven
Detected by
works-in-dev-only defects
Refactored by
Containerize, Externalize Config, Use IaC
Enforced by
environment drift checks
Before
if (env === "dev") useMemoryFooStore(); if (env === "prod") useSqlFooStore();
After
const container = buildFooImage("foo-app:1.0.0"); runEnvironment("dev", container, devConfig); runEnvironment("prod", container, prodConfig);

Containerization

Details
Violated by
undeclared host dependency
Detected by
manual host setup requirements
Measured by
image reproducibility
Refactored by
Add Containerfile, Externalize Runtime Dependencies
Enforced by
image scans, build pipeline
Before
installFooDependenciesOnHost(); startFooWithHostRuntime();
After
const image = containerImage({ base: "node:22-alpine", copy: ["dist", "package.json"], command: ["node", "dist/main.js"], });

Infrastructure as Code

  • Kind: activity
  • Severity: mandatory for managed infrastructure
  • Scope: infrastructure, deployment
  • Aliases: IaC
  • Layer: Resource Core
Details
Violated by
untracked manual infra mutation
Detected by
drift between code and live infra
Measured by
drift count, IaC coverage
Refactored by
Codify Resource, Import State
Enforced by
policy-as-code, drift detection
Before
operator.createDatabase("foo-prod"); operator.openPort(5432);
After
const fooDatabase = databaseResource({ name: "foo-prod", engine: "postgres", encrypted: true, networkPolicy: "foo-only", });

Standards Compliance

Details
Violated by
nonconforming implementation
Detected by
conformance test failure
Measured by
standard compliance score
Refactored by
Align Implementation, Add Conformance Tests
Enforced by
standards checks
Before
const payload = encodePrivateFooBinary(foo);
After
const payload: JsonFooV1 = toJsonFoo(foo); http.send(JSON.stringify(payload), { contentType: "application/json; charset=utf-8" });

Protocol Independence

Details
Violated by
HTTP/gRPC/etc. types in domain core
Detected by
protocol imports in core layer
Measured by
protocol leakage count
Refactored by
Add Port, Add Protocol Adapter
Enforced by
import rules
Before
class FooService { handleHttp(request: HttpRequest) { return fooStore.save(request.body); } }
After
class CreateFoo { constructor(private readonly store: FooStore) {} execute(input: CreateFooInput) { return this.store.save(Foo.create(input)); } } httpAdapter.bind(createFoo); grpcAdapter.bind(createFoo);

Configuration Externalization

Details
Violated by
environment values hardcoded in code
Detected by
hardcoded URLs/secrets/paths
Measured by
externalized config coverage
Refactored by
Move to Config, Add Validation
Enforced by
secret/config scans
Before
const config = { fooUrl: "https://foo.prod.example", retries: 3, };
After
type FooConfig = Readonly<{ fooUrl: URL; retries: number }>; const config = FooConfigSchema.parse({ fooUrl: process.env.FOO_URL, retries: process.env.FOO_RETRIES, });

Immutable Infrastructure

  • Kind: approach
  • Severity: mandatory for managed infrastructure
  • Scope: infrastructure, deployment, reproducibility
  • Layer: Resource Core
Details
Violated by
patching running servers in place
Detected by
SSH mutation of live instances
Measured by
config drift across instances
Refactored by
Replace Instances from Immutable Images
Enforced by
deployment review
Before
ssh(server, "apt-get update && systemctl restart foo");
After
const image = buildFooImage("foo:1.4.0"); replaceInstances("foo", image);

Runtime Discovery / Dynamic Binding

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_runtime_discovery["Runtime Discovery"]
    n_service_discovery["Service Discovery"]
    n_auto_discovery["Auto-Discovery"]
    n_dynamic_binding["Dynamic Binding"]
    n_late_binding["Late Binding"]
    n_runtime_binding["Runtime Binding"]
    n_dynamic_dispatch["Dynamic Dispatch"]
    n_runtime_extensibility["Runtime Extensibility"]
    n_runtime_discovery --> n_runtime_extensibility
    n_runtime_discovery --> n_service_discovery
    n_auto_discovery --> n_runtime_discovery
    n_late_binding --> n_dynamic_binding
    n_late_binding --> n_runtime_extensibility
    n_runtime_binding --> n_dynamic_binding

Runtime Discovery

Details
Violated by
hardcoded dependency discovery
Detected by
manual class/service lists
Measured by
discovery coverage
Refactored by
Add Registry, Add Scanner, Add Manifest
Enforced by
startup validation
Before
import { FooHandler } from "./foo-handler"; import { BarHandler } from "./bar-handler"; const handlers = [new FooHandler(), new BarHandler()];
After
const modules = await discover<HandlerModule>("./handlers/*.handler.js"); const handlers = modules.map(module => module.create());

Service Discovery

Details
Violated by
fixed service addresses in code
Detected by
hardcoded URLs, missing registry lookup
Measured by
dynamic resolution coverage
Refactored by
Introduce Discovery Client, Externalize Endpoint
Enforced by
config scans, deployment policy
Before
const fooUrl = "http://10.0.0.14:8080"; await http.get(`${fooUrl}/foo/${id}`);
After
const endpoint = await serviceDiscovery.resolve("foo-service"); await http.get(new URL(`/foo/${id}`, endpoint));

Auto-Discovery

Details
Violated by
manual enumeration of discoverable components
Detected by
static lists of handlers/plugins
Measured by
manual registration count
Refactored by
Add Scanner, Add Annotation, Add Manifest
Enforced by
registry validation
Before
register(new FooPlugin()); register(new BarPlugin()); register(new BazPlugin());
After
for (const plugin of await scan<Plugin>("./plugins/*.plugin.js")) register(plugin);

Dynamic Binding

Details
Violated by
fixed concrete binding where runtime selection required
Detected by
hardcoded implementation selection
Measured by
runtime binding coverage
Refactored by
Introduce Factory, Registry, Strategy
Enforced by
integration tests
Before
const formatter = new JsonFooFormatter(); formatter.format(foo);
After
const formatter = formatterRegistry.get(config.format); if (!formatter) throw new Error(`unknown formatter: ${config.format}`); formatter.format(foo);

Late Binding

Details
Violated by
premature concrete resolution
Detected by
compile-time dependency on runtime extension
Measured by
late-bound extension count
Refactored by
Add Interface, Defer Resolution, Add Registry
Enforced by
dependency checks
Before
const store = new SqlFooStore(); export const fooService = new FooService(store);
After
export function bootstrap(config: Config) { const store = storeRegistry.create(config.fooStore); return new FooService(store); }

Runtime Binding

Details
Violated by
compile-time wiring of runtime choices
Detected by
fixed binding tables
Measured by
configurable binding coverage
Refactored by
Add DI Container, Add Registry
Enforced by
composition root tests
Before
import { FooPolicy } from "./foo-policy"; const policy = new FooPolicy();
After
const policyModule = await import(config.fooPolicyModule); const policy: FooPolicy = policyModule.create(config.fooPolicyOptions);

Dynamic Dispatch

Details
Violated by
manual dispatch over concrete type
Detected by
switch/if chains on type
Measured by
conditional dispatch count
Refactored by
Introduce Polymorphic Method, Strategy
Enforced by
lint rules, review
Before
function execute(kind: string, foo: Foo) { if (kind === "save") return saveFoo(foo); if (kind === "publish") return publishFoo(foo); }
After
const commands: Record<string, (foo: Foo) => unknown> = { save: saveFoo, publish: publishFoo, }; function execute(kind: string, foo: Foo) { const command = commands[kind]; if (!command) throw new Error(`unknown command ${kind}`); return command(foo); }

Runtime Extensibility

Details
Violated by
modifying core for every extension
Detected by
repeated core changes for variants
Measured by
extension/core-change ratio
Refactored by
Add Extension Point, Add Plugin Interface
Enforced by
extension conformance tests
Before
switch (pluginName) { case "foo": return new FooPlugin(); case "bar": return new BarPlugin(); }
After
export function registerPlugin(name: string, create: () => Plugin) { pluginRegistry.set(name, create); } const plugin = pluginRegistry.get(pluginName)?.();

Scalability / Performance / Optimization

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_scalability["Scalability"]
    n_horizontal_scaling["Horizontal Scaling"]
    n_vertical_scaling["Vertical Scaling"]
    n_elasticity["Elasticity"]
    n_load_balancing["Load Balancing"]
    n_sharding["Sharding"]
    n_partitioning["Partitioning"]
    n_caching["Caching"]
    n_statelessness["Statelessness"]
    n_concurrency["Concurrency"]
    n_parallelism["Parallelism"]
    n_throughput["Throughput"]
    n_latency["Latency"]
    n_performance_engineering["Performance Engineering"]
    n_algorithmic_efficiency["Algorithmic Efficiency"]
    n_time_complexity["Time Complexity"]
    n_space_complexity["Space Complexity"]
    n_big_o_notation["Big O Notation"]
    n_optimization["Optimization"]
    n_profiling["Profiling"]
    n_benchmarking["Benchmarking"]
    n_bottleneck_analysis["Bottleneck Analysis"]
    n_resource_utilization["Resource Utilization"]
    n_rate_limiting["Rate Limiting"]
    n_memory_efficiency["Memory Efficiency"]
    n_cdn_edge_caching["CDN / Edge Caching"]
    n_read_replica["Read Replica"]
    n_queuing_theory["Queuing Theory"]
    n_scalability --> n_performance_engineering
    n_horizontal_scaling --> n_elasticity
    n_elasticity --> n_scalability
    n_load_balancing --> n_scalability
    n_sharding --> n_horizontal_scaling
    n_partitioning --> n_scalability
    n_partitioning --> n_parallelism
    n_caching --> n_scalability
    n_statelessness --> n_horizontal_scaling
    n_statelessness --> n_load_balancing
    n_concurrency --> n_throughput
    n_parallelism --> n_throughput
    n_throughput --> n_scalability
    n_throughput -.-> n_latency
    n_latency --> n_performance_engineering
    n_performance_engineering --> n_profiling
    n_performance_engineering --> n_benchmarking
    n_performance_engineering --> n_scalability
    n_algorithmic_efficiency --> n_scalability
    n_time_complexity --> n_algorithmic_efficiency
    n_time_complexity -.-> n_space_complexity
    n_space_complexity --> n_resource_utilization
    n_space_complexity -.-> n_time_complexity
    n_big_o_notation --> n_algorithmic_efficiency
    n_optimization --> n_profiling
    n_optimization --> n_performance_engineering
    n_profiling --> n_performance_engineering
    n_benchmarking --> n_performance_engineering
    n_bottleneck_analysis --> n_profiling
    n_bottleneck_analysis --> n_optimization
    n_resource_utilization --> n_performance_engineering
    n_memory_efficiency --> n_scalability
    n_cdn_edge_caching --> n_caching
    n_cdn_edge_caching --> n_latency
    n_read_replica --> n_horizontal_scaling
    n_read_replica --> n_load_balancing
    n_queuing_theory --> n_latency

Scalability

Details
Violated by
single bottleneck preventing growth
Detected by
saturation under load test
Measured by
throughput under increasing load
Refactored by
Add Caching, Partitioning, Async Processing, Scaling
Enforced by
load tests, SLO gates
Before
class FooServer { private readonly foos = new Map<FooId, Foo>(); handle(request: FooRequest) { return processFoo(request, this.foos); } }
After
class FooServer { constructor(private readonly store: DistributedFooStore) {} handle(request: FooRequest) { return processFoo(request, this.store); } }

Horizontal Scaling

Details
Violated by
sticky instance state required for correctness
Detected by
local session/state coupling
Measured by
scale-out efficiency
Refactored by
Externalize State, Add Load Balancer
Enforced by
deployment tests
Before
deployFoo({ replicas: 1, cpu: 32, memoryGb: 128 });
After
deployFoo({ replicas: 12, cpu: 2, memoryGb: 4, stateless: true });

Vertical Scaling

Details
Violated by
relying only on vertical scale past ceiling
Detected by
resource saturation trends
Measured by
utilization/headroom
Refactored by
Optimize Resources, Prepare Horizontal Scale
Before
deployFoo({ cpu: 1, memoryGb: 1 }); queueFooWhenSaturated();
After
deployFoo({ cpu: 8, memoryGb: 32 }); verifyFooCapacity({ targetConcurrency: 200 });

Elasticity

Details
Violated by
capacity not adapting to demand
Detected by
under/over-provisioning patterns
Measured by
scale response time, utilization
Refactored by
Add Scaling Policy, Remove Stateful Constraint
Enforced by
infrastructure policy
Before
deployFooWorkers({ replicas: 10 });
After
deployFooWorkers({ minReplicas: 2, maxReplicas: 50, target: { queueDepthPerReplica: 100 }, });

Load Balancing

Details
Violated by
uneven traffic causing hotspots
Detected by
skewed instance utilization
Measured by
request distribution, latency
Refactored by
Add Load Balancer, Externalize Session State
Enforced by
infrastructure config checks
Before
const endpoint = fooServers[0]; endpoint.handle(request);
After
const endpoint = fooLoadBalancer.next({ key: request.fooId }); endpoint.handle(request);

Sharding

Details
Violated by
unbounded single partition growth
Detected by
hotspot partitions, storage bottleneck
Measured by
shard balance, query fan-out
Refactored by
Introduce Shard Key, Split Data
Enforced by
data architecture review
Before
const foo = await singleFooDatabase.find(id);
After
const shard = fooShardMap.resolve(id); const foo = await shard.find(id);

Partitioning

Details
Violated by
no partitioning for unbounded workload
Detected by
hotspot resource usage
Measured by
partition balance
Refactored by
Add Partition Key, Split Workload
Before
const events = await fooLog.readAll();
After
const partition = hash(fooId) % partitionCount; const events = await fooLog.readPartition(partition);

Caching

Details
Violated by
repeated expensive computation/query with stable result
Detected by
hot repeated reads, high latency calls
Measured by
hit ratio, stale read rate
Refactored by
Add Cache, Define TTL/Invalidation
Enforced by
performance tests
Before
async function loadFoo(id: FooId) { return fooStore.find(id); }
After
async function loadFoo(id: FooId) { const cached = await fooCache.get(id); if (cached) return cached; const foo = await fooStore.find(id); if (foo) await fooCache.set(id, foo, { ttlMs: 60_000 }); return foo; }

Statelessness

Details
Violated by
correctness depends on in-memory instance state
Detected by
mutable static/session-local state
Measured by
state externalization coverage
Refactored by
Move State to Store, Use Token/Session Store
Enforced by
architecture tests
Before
class FooHandler { private currentUser?: User; handle(request: Request) { this.currentUser = request.user; return processFoo(request, this.currentUser); } }
After
class FooHandler { handle(request: Request) { return processFoo(request, request.user); } }

Concurrency

Details
Reinforces
In tension with
Conflicts with
Violated by
unsafe shared mutation
Detected by
data races, flaky concurrent tests
Measured by
throughput, race count
Refactored by
Add Synchronization, Use Immutable State
Enforced by
race detectors, tests
Before
for (const foo of foos) await processFoo(foo);
After
await Promise.all(foos.map(foo => processFoo(foo)));

Parallelism

Details
Violated by
serial processing of independent heavy tasks
Detected by
CPU bottlenecks with independent work
Measured by
speedup, utilization
Refactored by
Split Work, Add Parallel Execution
Enforced by
performance benchmarks
Before
const results = foos.map(foo => cpuHeavyFoo(foo));
After
const results = await workerPool.map(foos, foo => cpuHeavyFoo(foo));

Throughput

Details
Violated by
processing rate below SLO
Detected by
load test failures
Measured by
requests/messages/items per second
Refactored by
Optimize Bottleneck, Add Parallelism, Add Scaling
Enforced by
performance gates
Before
for (const foo of foos) await fooStore.save(foo);
After
for (const batch of chunk(foos, 500)) await fooStore.saveBatch(batch);

Latency

Details
Violated by
response time above SLO
Detected by
trace span delays
Measured by
p50/p95/p99 latency
Refactored by
Cache, Async Offload, Optimize Query
Enforced by
SLO gates
Before
async function renderFoo(id: FooId) { const foo = await fooStore.find(id); const bar = await barStore.find(foo.barId); const baz = await bazStore.find(foo.bazId); return render(foo, bar, baz); }
After
async function renderFoo(id: FooId) { const foo = await fooStore.find(id); const [bar, baz] = await Promise.all([ barStore.find(foo.barId), bazStore.find(foo.bazId), ]); return render(foo, bar, baz); }

Performance Engineering

Details
Violated by
optimization without measurement
Detected by
performance changes lacking benchmark
Measured by
benchmark trend, SLO compliance
Refactored by
Profile, Optimize Bottleneck, Add Benchmark
Enforced by
performance CI
Before
optimizeFooCode();
After
const budget = { p95LatencyMs: 150, throughputPerSecond: 1000 } as const; const profile = await measureFooWorkload(representativeLoad); const change = optimize(profile.hotspot); assertPerformance(change, budget);

Algorithmic Efficiency

Details
Violated by
avoidable quadratic/exponential behavior
Detected by
complexity analysis, benchmark slope
Measured by
time/space complexity
Refactored by
Replace Algorithm, Add Index, Change Data Structure
Enforced by
review, benchmarks
Before
function hasFoo(foos: Foo[], id: FooId) { return foos.some(foo => foo.id === id); }
After
function indexFoos(foos: readonly Foo[]) { return new Map(foos.map(foo => [foo.id, foo])); } const hasFoo = (index: ReadonlyMap<FooId, Foo>, id: FooId) => index.has(id);

Time Complexity

Details
Violated by
unacceptable asymptotic runtime
Detected by
nested loops over large inputs, benchmark slope
Measured by
Big O, runtime scaling
Refactored by
Improve Algorithm, Add Index/Cache
Enforced by
benchmark thresholds
Before
function duplicateFooIds(foos: Foo[]) { return foos.filter((foo, index) => foos.findIndex(x => x.id === foo.id) !== index); }
After
function duplicateFooIds(foos: readonly Foo[]) { const seen = new Set<FooId>(); return foos.filter(foo => seen.has(foo.id) || !seen.add(foo.id)); }

Space Complexity

Details
Violated by
loading unbounded data into memory
Detected by
memory profiling, full materialization
Measured by
Big O space, peak memory
Refactored by
Stream Data, Use Iterator, Chunk Processing
Enforced by
memory benchmarks
Before
function processFoos(stream: AsyncIterable<Foo>) { return collectAll(stream).then(foos => foos.map(transformFoo)); }
After
async function* processFoos(stream: AsyncIterable<Foo>) { for await (const foo of stream) yield transformFoo(foo); }

Big O Notation

Details
Violated by
ignoring growth behavior for large inputs
Detected by
missing complexity note for critical algorithm
Measured by
asymptotic classification
Refactored by
Analyze Complexity, Replace Algorithm
Enforced by
review checklist
Before
function pairFoosWithBars(foos: Foo[], bars: Bar[]) { return foos.flatMap(foo => bars.filter(bar => bar.fooId === foo.id).map(bar => [foo, bar])); }
After
function pairFoosWithBars(foos: readonly Foo[], bars: readonly Bar[]) { const barsByFoo = groupBy(bars, bar => bar.fooId); return foos.flatMap(foo => (barsByFoo.get(foo.id) ?? []).map(bar => [foo, bar])); }

Optimization

Details
Violated by
optimizing without measured bottleneck
Detected by
complex code without performance evidence
Measured by
benchmark delta, SLO improvement
Refactored by
Optimize Bottleneck, Simplify After Optimization
Enforced by
benchmark review
Before
const fooCache = new Map<FooId, Foo>(); function loadFoo(id: FooId) { return fooCache.get(id) ?? expensiveLoad(id); }
After
const profile = profiler.measure("foo.load", representativeFooIds); if (profile.hotspot === "foo-store-read") { enableBoundedFooCache({ maxEntries: 10_000, ttlMs: 30_000 }); }

Profiling

Details
Violated by
performance decisions without profiling
Detected by
missing profile evidence
Measured by
hotspot attribution
Refactored by
Profile Path, Target Hotspot
Enforced by
performance review
Before
rewriteFooParserForSpeed();
After
const profile = await profiler.capture(() => parseFooBatch(batch)); const hotspot = profile.topFrame(); optimizeFooFrame(hotspot);

Benchmarking

Details
Violated by
performance claim without benchmark
Detected by
missing benchmark for perf-sensitive changes
Measured by
benchmark score/trend
Refactored by
Add Benchmark, Stabilize Environment
Enforced by
benchmark CI
Before
const start = clock.now(); runFoo(); report(clock.now() - start);
After
benchmark("foo.parse", { warmup: 100, iterations: 10_000, run: () => parseFoo(fixture), });

Bottleneck Analysis

Details
Violated by
optimizing non-bottleneck code
Detected by
performance work without hotspot evidence
Measured by
bottleneck contribution percentage
Refactored by
Remove Bottleneck, Parallelize, Cache
Enforced by
performance review
Before
addMoreFooWorkers();
After
const trace = await measureFooPipeline(); const bottleneck = trace.stages.sort((a, b) => b.waitMs - a.waitMs)[0]; removeBottleneck(bottleneck);

Resource Utilization

Details
Violated by
persistent saturation or idle waste
Detected by
monitoring metrics
Measured by
CPU/memory/IO/network utilization
Refactored by
Optimize Resource Use, Scale, Tune Config
Enforced by
SLO/capacity policy
Before
deployFoo({ cpu: 16, memoryGb: 64 });
After
const sizing = rightSizeFoo({ cpuP95: metrics.cpu("foo", "p95"), memoryP95: metrics.memory("foo", "p95"), headroom: 0.25, }); deployFoo(sizing);

Rate Limiting

Details
Violated by
unlimited calls to constrained resource
Detected by
missing rate limiter on public/expensive endpoints
Measured by
limit hit rate, overload incidents
Refactored by
Add Rate Limiter, Define Quotas
Enforced by
API gateway/policy
Before
app.post("/foo", createFoo);
After
app.post("/foo", rateLimit({ key: request => request.identity.id, limit: 100, windowMs: 60_000, }), createFoo);

Memory Efficiency

Details
Violated by
loading unbounded data into memory
Detected by
memory profile spikes
Measured by
peak memory, allocation rate
Refactored by
Stream, Chunk, Use Iterator
Enforced by
memory benchmarks
Before
const copies = foos.map(foo => structuredClone(foo));
After
function* fooViews(foos: readonly Foo[]) { for (const foo of foos) yield { id: foo.id, name: foo.name }; }

CDN / Edge Caching

Details
Violated by
every request hitting the origin regardless of locality
Detected by
static assets served from origin per request
Measured by
origin request rate / cache hit ratio
Refactored by
Serve via CDN / Edge Cache
Enforced by
performance review
Before
app.get("/foo/:id/avatar", serveFooAvatarFromOrigin);
After
app.get("/foo/:id/avatar", edgeCache({ ttl: "7d", key: request => request.params.id }), serveFooAvatarFromOrigin, );

Read Replica

Details
Violated by
all reads and writes hitting one primary
Detected by
read load saturating the write primary
Measured by
primary read/write contention ratio
Refactored by
Route Reads to Replicas
Enforced by
database design review
Before
const foo = await primaryDb.query(fooQuery); await primaryDb.write(fooCommand);
After
const foo = await replicaRouter.read(fooQuery); await primaryDb.write(fooCommand);

Queuing Theory

Details
Violated by
worker pool sized by guesswork with no arrival/service-rate model
Detected by
latency collapsing as utilization approaches saturation unexpectedly
Measured by
predicted vs actual queue depth and wait time
Refactored by
Size the system from an M/M/1 (or M/M/c) queuing model
Enforced by
capacity review
Before
const workers = 4;
After
const rho = arrivalRate / (workers * serviceRate); if (rho >= 1) throw new Error("unstable queue: utilization >= 1"); const avgWaitMs = mm1WaitTime({ arrivalRate, serviceRate, servers: workers });

Schema / Canonical Data / Semantics

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_schema_validation["Schema Validation"]
    n_type_safety["Type Safety"]
    n_canonical_model["Canonical Model"]
    n_canonical_data_model["Canonical Data Model"]
    n_canonical_schema["Canonical Schema"]
    n_canonicalization["Canonicalization"]
    n_single_source_of_truth["Single Source of Truth"]
    n_normalization["Normalization"]
    n_semantic_consistency["Semantic Consistency"]
    n_ubiquitous_language["Ubiquitous Language"]
    n_intent_revealing_interface["Intent-Revealing Interface"]
    n_principle_of_least_surprise["Principle of Least Surprise"]
    n_database_normalization["Database Normalization"]
    n_canonical_model --> n_semantic_consistency
    n_canonical_model --> n_ubiquitous_language
    n_canonical_model --> n_single_source_of_truth
    n_canonical_data_model --> n_canonical_model
    n_canonical_data_model --> n_normalization
    n_canonical_schema --> n_canonical_data_model
    n_canonical_schema --> n_schema_validation
    n_semantic_consistency --> n_ubiquitous_language
    n_ubiquitous_language --> n_intent_revealing_interface
    n_intent_revealing_interface --> n_principle_of_least_surprise
    n_principle_of_least_surprise --> n_intent_revealing_interface
    n_database_normalization --> n_single_source_of_truth

Schema Validation

Details
Violated by
accepting unvalidated payloads
Detected by
missing validator at boundary
Measured by
validation coverage
Refactored by
Add Schema Validator, Add DTO
Enforced by
runtime validation, CI schema checks
Before
const foo = JSON.parse(raw) as Foo;
After
const FooSchema = object({ id: string(), name: string().min(1), count: integer().min(0) }); const foo = FooSchema.parse(JSON.parse(raw));

Type Safety

Details
Violated by
any/unknown maps crossing boundaries
Detected by
weak type usage, unsafe casts
Measured by
type coverage, unsafe cast count
Refactored by
Add Types, Replace Map with DTO, Narrow Types
Enforced by
compiler flags, type checker
Before
function loadFoo(id: string): any { return fooStore.get(id); } const count = loadFoo("x").coutn + 1;
After
type FooId = string & { readonly __brand: "FooId" }; type Foo = Readonly<{ id: FooId; count: number }>; function loadFoo(id: FooId): Foo | undefined { return fooStore.get(id); }

Canonical Model

Details
Violated by
duplicate conflicting representations
Detected by
same concept modeled inconsistently
Measured by
model duplication count
Refactored by
Introduce Canonical Model, Add Translator
Enforced by
schema governance, domain review
Before
type ApiFoo = { foo_id: string; label: string }; type DbFoo = { id: string; name: string }; type UiFoo = { key: string; title: string };
After
type Foo = Readonly<{ id: FooId; name: string }>; const fromApi = (value: ApiFoo): Foo => ({ id: fooId(value.foo_id), name: value.label }); const toUi = (foo: Foo): UiFoo => ({ key: foo.id, title: foo.name });

Canonical Data Model

Details
Violated by
point-to-point inconsistent mappings
Detected by
duplicated transformation logic
Measured by
transformation duplication
Refactored by
Centralize Data Mapping, Add Anti-Corruption Layer
Enforced by
data contract review
Before
fooTable.insert({ foo_id: foo.id, foo_name: foo.name }); barTable.insert({ id: foo.id, label: foo.name });
After
type CanonicalFoo = Readonly<{ id: FooId; name: string }>; fooRepository.save(canonicalFoo); barProjection.apply(canonicalFoo);

Canonical Schema

Details
Violated by
divergent schemas for same concept
Detected by
schema diff conflict
Measured by
schema reuse/conformance rate
Refactored by
Align Schema, Add Versioned Schema
Enforced by
schema registry
Before
const fooSchema = { id: "string", name: "string" }; const barFooSchema = { fooId: "text", label: "text" };
After
export const CanonicalFooSchema = schema({ id: fooIdSchema, name: nonEmptyString }); fooApi.use(CanonicalFooSchema); barProjection.use(CanonicalFooSchema);

Canonicalization

Details
Violated by
comparing non-normalized forms
Detected by
duplicate semantically equivalent values
Measured by
normalization defect count
Refactored by
Normalize Input, Canonicalize Before Compare
Enforced by
validation pipeline
Before
const keys = ["Foo", " foo ", "FOO"]; const map = new Map(keys.map(key => [key, loadFoo(key)]));
After
function canonicalFooKey(value: string) { return value.trim().normalize("NFKC").toLowerCase(); } const map = new Map(keys.map(key => [canonicalFooKey(key), loadFoo(canonicalFooKey(key))]));

Single Source of Truth

Details
Violated by
duplicate configs/rules/schemas
Detected by
conflicting definitions
Measured by
duplicate authority count
Refactored by
Centralize Definition, Reference Shared Source
Enforced by
config governance, schema registry
Before
let fooCount = 0; const foos: Foo[] = []; function addFoo(foo: Foo) { foos.push(foo); fooCount += 1; }
After
const foos: Foo[] = []; function addFoo(foo: Foo) { foos.push(foo); } function fooCount() { return foos.length; }

Normalization

Details
Violated by
uncontrolled duplicated data
Detected by
update anomalies, duplicated facts
Measured by
redundancy/anomaly count
Refactored by
Extract Entity, Normalize Table, Add Reference
Enforced by
schema review, database constraints
Before
type Foo = { id: FooId; barName: string; barEmail: string }; const foos: Foo[] = duplicateBarAcrossFoos();
After
type Foo = { id: FooId; barId: BarId }; type Bar = { id: BarId; name: string; email: string }; const foos = new Map<FooId, Foo>(); const bars = new Map<BarId, Bar>();

Semantic Consistency

Details
Violated by
same name with different meanings
Detected by
conflicting glossary/schema definitions
Measured by
semantic conflict count
Refactored by
Rename, Split Context, Add Translator
Enforced by
glossary review, schema review
Before
function createFoo(name: string) {} function renameFoo(label: string) {} function findFoo(title: string) {}
After
type FooName = string & { readonly __brand: "FooName" }; function createFoo(name: FooName) {} function renameFoo(name: FooName) {} function findFoo(name: FooName) {}

Ubiquitous Language

Details
Violated by
inconsistent domain terms
Detected by
synonym drift, ambiguous names
Measured by
naming consistency score
Refactored by
Rename Class/Method/Field, Update Glossary
Enforced by
naming rules, domain review
Before
function changeThingState(record: any, code: string) { record.s = code; }
After
function activateFoo(foo: Foo) { foo.activate(); fooEvents.emit({ type: "FooActivated", fooId: foo.id }); }

Intent-Revealing Interface

  • Kind: principle
  • Severity: recommended
  • Scope: API, method, class, module
  • Aliases: Intent-Revealing Interfaces, Intent-Revealing API
  • Layer: Contracts Core
Details
Violated by
vague method names, boolean traps
Detected by
generic names, unclear parameters
Measured by
API clarity review findings
Refactored by
Rename Method, Replace Boolean with Enum, Add Value Object
Enforced by
naming lint, API review
Before
foo.update("s", "A"); foo.apply(3, true);
After
foo.activate(); foo.reserve({ quantity: 3, notify: true });

Principle of Least Surprise

Details
Violated by
unexpected mutation, nonstandard behavior
Detected by
misleading names, hidden behavior
Measured by
surprise defects, misuse reports
Refactored by
Rename, Make Side Effects Explicit, Normalize Behavior
Enforced by
API review, tests
Before
function getFoo(id: FooId) { fooStore.delete(id); return undefined; }
After
function getFoo(id: FooId) { return fooStore.find(id); } function deleteFoo(id: FooId) { return fooStore.delete(id); }

Database Normalization

Details
Violated by
repeating groups and transitively-dependent columns duplicated across rows
Detected by
the same fact stored in multiple places drifting out of sync
Measured by
update-anomaly incidents and redundant-column count
Refactored by
Normalize to 3NF, extracting dependent attributes into their own relations
Enforced by
schema review
Before
type FooRow = { id: string; customerName: string; customerCity: string; customerCityZip: string };
After
type Foo = { id: FooId; customerId: CustomerId }; type Customer = { id: CustomerId; name: string; cityId: CityId }; type City = { id: CityId; name: string; zip: string };

Security / Privacy / Compliance / Governance

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_security_by_design["Security by Design"]
    n_defense_in_depth["Defense in Depth"]
    n_least_privilege["Least Privilege"]
    n_zero_trust_architecture["Zero Trust Architecture"]
    n_secure_by_default["Secure by Default"]
    n_attack_surface_reduction["Attack Surface Reduction"]
    n_threat_modeling["Threat Modeling"]
    n_authentication["Authentication"]
    n_authorization["Authorization"]
    n_access_control["Access Control"]
    n_role_based_access_control["RBAC"]
    n_attribute_based_access_control["ABAC"]
    n_input_validation["Input Validation"]
    n_output_encoding["Output Encoding"]
    n_encryption_at_rest["Encryption at Rest"]
    n_encryption_in_transit["Encryption in Transit"]
    n_secrets_management["Secrets Management"]
    n_privacy_by_design["Privacy by Design"]
    n_compliance["Compliance"]
    n_governance["Governance"]
    n_policy_enforcement["Policy Enforcement"]
    n_policy_as_code["Policy as Code"]
    n_risk_management["Risk Management"]
    n_continuous_compliance["Continuous Compliance"]
    n_csrf_protection["CSRF Protection"]
    n_parameterized_queries["Parameterized Queries"]
    n_session_management["Session Management"]
    n_security_by_design --> n_threat_modeling
    n_security_by_design --> n_defense_in_depth
    n_security_by_design --> n_compliance
    n_defense_in_depth --> n_security_by_design
    n_least_privilege --> n_access_control
    n_zero_trust_architecture --> n_least_privilege
    n_attack_surface_reduction --> n_security_by_design
    n_threat_modeling --> n_security_by_design
    n_threat_modeling --> n_risk_management
    n_authentication --> n_access_control
    n_authorization --> n_least_privilege
    n_access_control --> n_least_privilege
    n_role_based_access_control --> n_access_control
    n_privacy_by_design --> n_compliance
    n_compliance --> n_governance
    n_compliance --> n_risk_management
    n_governance --> n_compliance
    n_policy_enforcement --> n_compliance
    n_policy_as_code --> n_continuous_compliance
    n_risk_management --> n_compliance
    n_risk_management --> n_security_by_design
    n_continuous_compliance --> n_policy_as_code
    n_continuous_compliance --> n_compliance
    n_csrf_protection --> n_authentication
    n_csrf_protection --> n_defense_in_depth
    n_parameterized_queries --> n_input_validation
    n_parameterized_queries --> n_secure_by_default
    n_session_management --> n_authentication
    n_session_management --> n_access_control
    n_session_management --> n_least_privilege

Security by Design

Details
Violated by
security controls added only at perimeter
Detected by
missing authz/input validation/threat model
Measured by
security control coverage
Refactored by
Add Security Boundary, Validate Input, Enforce Access
Enforced by
security gates, policy-as-code
Before
function createFoo(request: Request) { return fooStore.save(request.body as Foo); }
After
function createFoo(request: Request, identity: Identity) { const input = CreateFooSchema.parse(request.body); authorize(identity, "foo:create"); return fooStore.save(Foo.create(input)); }

Defense in Depth

Details
Violated by
relying on only one security layer
Detected by
missing secondary control
Measured by
control depth
Refactored by
Add Layered Controls
Enforced by
threat model review
Before
app.post("/foo", createFoo);
After
app.post("/foo", authenticate(), authorize("foo:create"), validate(CreateFooSchema), rateLimit({ limit: 100 }), audit("FOO_CREATE"), createFoo, );

Least Privilege

Details
Violated by
excessive permissions
Detected by
overbroad roles/scopes
Measured by
privilege excess count
Refactored by
Narrow Role, Split Permission
Enforced by
IAM policy checks
Before
class FooJob { constructor(private readonly db: AdminDatabase) {} run(foo: Foo) { return this.db.execute(`insert into foo values (?)`, foo); } }
After
interface FooWriter { insert(foo: Foo): Promise<void>; } class FooJob { constructor(private readonly foos: FooWriter) {} run(foo: Foo) { return this.foos.insert(foo); } }

Zero Trust Architecture

Details
Violated by
implicit trust based on network location
Detected by
internal endpoints without authz/authn
Measured by
trustless control coverage
Refactored by
Add AuthN/AuthZ, Segment Network
Enforced by
policy-as-code, gateway rules
Before
if (request.network === "internal") return createFoo(request.body);
After
const identity = authenticate(request.credentials); authorize(identity, "foo:create", { resource: request.body.id }); verifyDevice(request.deviceAttestation); return createFoo(CreateFooSchema.parse(request.body));

Secure by Default

Details
Violated by
default open access, default weak settings
Detected by
insecure default config
Measured by
insecure default count
Refactored by
Change Default to Secure, Require Explicit Opt-In
Enforced by
config policy
Before
const fooApi = createApi({ public: true, tls: false, audit: false });
After
const fooApi = createApi({ public: false, tls: "required", authentication: "required", audit: true, });

Attack Surface Reduction

Details
Violated by
unused open ports/endpoints/permissions
Detected by
exposed unused routes/services
Measured by
exposed surface count
Refactored by
Remove Endpoint, Restrict Access, Disable Feature
Enforced by
attack surface scanning
Before
app.enableDebugConsole(); app.exposeAdminApi(); app.loadAllPlugins();
After
app.register(fooPublicApi); app.disable("debug-console"); app.disable("admin-api"); app.loadPlugins(approvedFooPlugins);

Threat Modeling

  • Kind: activity
  • Severity: mandatory for sensitive systems
  • Scope: feature, system, architecture
  • Layer: Security Core
Details
Violated by
security-sensitive change without threat review
Detected by
missing threat model for sensitive flow
Measured by
threat model coverage
Refactored by
Add Threat Model, Add Mitigation
Enforced by
security review gates
Before
designFooUpload(); shipFooUpload();
After
const threats = modelThreats(fooUploadFlow, ["spoofing", "tampering", "repudiation", "disclosure", "denial", "elevation"]); for (const threat of threats) requireMitigation(threat); shipFooUpload();

Authentication

Details
Violated by
sensitive action without identity verification
Detected by
unauthenticated protected endpoints
Measured by
auth coverage
Refactored by
Add AuthN Middleware/Provider
Enforced by
route policies, tests
Before
const userId = request.headers.get("X-User-ID"); return loadFooFor(userId!);
After
const credential = requireHeader(request, "Authorization"); const identity = await authenticator.verify(credential); if (!identity) throw new UnauthorizedError(); return loadFooFor(identity.subject);

Authorization

Details
Violated by
missing permission check
Detected by
protected operation without authz guard
Measured by
authorization coverage
Refactored by
Add Policy Check, Centralize Authorization
Enforced by
security tests, policy-as-code
Before
const identity = authenticate(request); return fooStore.delete(request.params.id);
After
const identity = authenticate(request); authorize(identity, "foo:delete", { fooId: request.params.id }); return fooStore.delete(request.params.id);

Access Control

Details
Violated by
broad or missing access controls
Detected by
resource endpoint lacking policy
Measured by
access control coverage
Refactored by
Add ACL/RBAC/ABAC Policy
Enforced by
policy tests
Before
if (user.role === "admin") return fooStore.findAll();
After
const decision = accessPolicy.evaluate({ subject: user, action: "foo:list", resource: { tenantId: request.tenantId }, }); if (!decision.allowed) throw new ForbiddenError(); return fooStore.findAll(request.tenantId);

RBAC

Details
Violated by
hardcoded user-specific access logic
Detected by
scattered role checks
Measured by
role-policy consistency
Refactored by
Centralize Role Policy
Enforced by
authorization tests
Before
if (user.name === "Developer") allowDeleteFoo();
After
const roles = new Map([ ["foo-reader", ["foo:read"]], ["foo-editor", ["foo:read", "foo:write"]], ["foo-admin", ["foo:read", "foo:write", "foo:delete"]], ]); authorizeRole(user.roles, "foo:delete", roles);

ABAC

Details
Violated by
complex access logic embedded in code
Detected by
duplicated attribute checks in handlers
Measured by
policy centralization
Refactored by
Extract Policy, Add Policy Engine
Enforced by
Before
if (user.role === "editor") return updateFoo(foo);
After
const decision = policy.evaluate({ subject: { id: user.id, department: user.department }, action: "foo:update", resource: { ownerId: foo.ownerId, classification: foo.classification }, environment: { time: clock.now() }, }); if (!decision.allowed) throw new ForbiddenError();

Input Validation

Details
Violated by
raw external data entering core logic
Detected by
missing boundary validators
Measured by
validation coverage
Refactored by
Add Validator, Add Schema
Enforced by
validation middleware, tests
Before
const input = request.body as Foo; fooStore.save(input);
After
const input = CreateFooSchema.parse(request.body); fooStore.save(input);

Output Encoding

Details
Violated by
unescaped user-controlled output
Detected by
raw HTML/SQL/shell output paths
Measured by
unsafe sink count
Refactored by
Encode Output, Use Safe Templates
Enforced by
security linting
Before
response.html(`<div>${foo.name}</div>`);
After
response.html(`<div>${escapeHtml(foo.name)}</div>`);

Encryption at Rest

Details
Violated by
sensitive data stored unencrypted
Detected by
storage config scan
Measured by
encrypted storage coverage
Refactored by
Enable Encryption, Add KMS
Enforced by
infrastructure policy
Before
await disk.write("foos.json", JSON.stringify(foos));
After
const ciphertext = await keyManager.encrypt("foo-data-key", JSON.stringify(foos)); await disk.write("foos.enc", ciphertext);

Encryption in Transit

Details
Violated by
sensitive traffic over plaintext
Detected by
HTTP/plain socket usage
Measured by
encrypted transport coverage
Refactored by
Enable TLS/mTLS
Enforced by
gateway/network policy
Before
const client = new HttpClient("http://foo.internal");
After
const client = new HttpClient("https://foo.internal", { tls: { minVersion: "TLSv1.3", verifyPeer: true }, });

Secrets Management

Details
Violated by
secrets in code/config files/logs
Detected by
secret scanning
Measured by
secret exposure count
Refactored by
Move to Secret Manager, Rotate Secret
Enforced by
secret scans, CI gates
Before
const fooClient = new FooClient({ apiKey: "foo_live_abc123" });
After
const apiKey = await secretStore.read("services/foo/api-key"); if (!apiKey) throw new Error("missing foo api key"); const fooClient = new FooClient({ apiKey });

Privacy by Design

Details
Violated by
collecting or retaining unnecessary personal data
Detected by
PII flow without policy
Measured by
PII surface, retention compliance
Refactored by
Minimize Data, Add Retention/Delete Controls
Enforced by
privacy review, policy-as-code
Before
auditLog.append({ user, request, foo, headers: request.headers });
After
auditLog.append({ actorId: pseudonymize(user.id), action: "FOO_READ", fooId: foo.id, purpose: "support", });

Compliance

  • Kind: constraint
  • Severity: contextual/mandatory when regulated
  • Scope: system, organization, process
  • Layer: Security Core
Details
Violated by
missing controls/evidence for required regulation
Detected by
compliance gap assessment
Measured by
control pass rate
Refactored by
Add Control, Add Evidence Capture
Enforced by
compliance gates
Before
storeFooData(foo);
After
const classified = classify(foo); const controls = compliance.requirements(classified, "foo-storage"); await enforceControls(controls); await storeFooData(foo);

Governance

Details
Violated by
unmanaged architecture divergence
Detected by
standard violations, undocumented decisions
Measured by
policy compliance
Refactored by
Add Standards, Add Review Process
Enforced by
architecture board, policy-as-code
Before
teams.defineFooApisIndependently();
After
const governance = defineArchitecturePolicy({ apiVersioning: "required", schemaRegistry: "required", ownership: "single-team", }); architectureGate.enforce(governance);

Policy Enforcement

Details
Violated by
unenforced policy
Detected by
policy drift
Measured by
policy violation count
Refactored by
Codify Policy, Add Gate
Enforced by
CI/CD, runtime policy engine
Before
if (!policyAllows(user, foo)) fooLog.record("policy violation"); return updateFoo(foo);
After
if (!policyAllows(user, foo)) throw new ForbiddenError(); return updateFoo(foo);

Policy as Code

Details
Violated by
manual policy checks not represented in code
Detected by
missing policy rule for known control
Measured by
automated policy coverage
Refactored by
Encode Policy, Add CI Gate
Enforced by
Before
document.write("Only foo-admin may delete Foo");
After
const fooDeletePolicy = policy({ action: "foo:delete", allow: input => input.subject.roles.includes("foo-admin"), }); policyGate.enforce(fooDeletePolicy);

Risk Management

Details
Violated by
critical risk without owner/mitigation
Detected by
risk register gaps
Measured by
residual risk score
Refactored by
Add Mitigation, Reduce Exposure
Enforced by
review gates
Before
shipFooFeature();
After
const risk = assessRisk(fooFeature, { likelihood: 3, impact: 5, controls: ["rate-limit", "audit", "rollback"], }); if (risk.residual > riskTolerance) throw new Error("risk not accepted"); shipFooFeature();

Continuous Compliance

Details
Violated by
compliance verified only manually/reactively
Detected by
missing automated compliance checks
Measured by
continuous control pass rate
Refactored by
Add Automated Evidence, Add Policy Gates
Enforced by
CI/CD controls
Before
runComplianceAuditOncePerYear();
After
pipeline.on("change", async change => { const result = await complianceScanner.evaluate(change); if (!result.compliant) throw new ComplianceGateError(result.violations); });

CSRF Protection

Details
Violated by
state-changing requests trusted on cookie presence alone
Detected by
no anti-forgery token on mutating endpoints
Measured by
unprotected state-changing endpoint count
Refactored by
Add CSRF Tokens / SameSite Enforcement
Enforced by
security review
Before
app.post("/foo/delete", deleteFoo);
After
app.post("/foo/delete", verifyCsrfToken(), requireSameSite(), deleteFoo);

Parameterized Queries

Details
Violated by
SQL assembled by concatenating user input
Detected by
string interpolation into query text
Measured by
concatenated-query count
Refactored by
Use Parameterized Queries
Enforced by
security review
Before
db.query(`select * from foos where id = '${id}'`);
After
db.query("select * from foos where id = $1", [id]);

Session Management

  • Kind: mechanism
  • Severity: mandatory for sensitive systems
  • Scope: service, authentication, security
  • Layer: Security Core
Details
Violated by
client-supplied identity trusted without server-side session
Detected by
no expiry/rotation/revocation on sessions
Measured by
unbounded-session count
Refactored by
Introduce Server-Side Session Management
Enforced by
security review
Before
res.cookie("userId", user.id);
After
const session = await sessions.create(user.id, { ttlMs: 3_600_000, rotateOnAuth: true }); res.cookie("sid", session.id, { httpOnly: true, secure: true, sameSite: "strict" });

Self-Healing / Recovery / Deployment Safety

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_self_healing_architecture["Self-Healing Architecture"]
    n_autonomous_recovery["Autonomous Recovery"]
    n_health_checks["Health Checks"]
    n_failover["Failover"]
    n_redundancy["Redundancy"]
    n_replication["Replication"]
    n_auto_scaling["Auto-Scaling"]
    n_auto_remediation["Auto-Remediation"]
    n_rollback["Rollback"]
    n_blue_green_deployment["Blue-Green Deployment"]
    n_canary_deployment["Canary Deployment"]
    n_chaos_engineering["Chaos Engineering"]
    n_graceful_shutdown["Graceful Shutdown"]
    n_raid_redundancy["RAID Redundancy"]
    n_self_healing_architecture --> n_health_checks
    n_self_healing_architecture --> n_autonomous_recovery
    n_failover --> n_redundancy
    n_redundancy --> n_failover
    n_replication --> n_failover
    n_blue_green_deployment --> n_rollback
    n_chaos_engineering --> n_self_healing_architecture
    n_raid_redundancy --> n_redundancy

Self-Healing Architecture

Details
Violated by
detectable failure without automated remediation
Detected by
recurring manual recovery steps
Measured by
MTTR, auto-recovery success
Refactored by
Add Health Checks, Add Restart/Remediation Policy
Enforced by
orchestration policy, runbooks
Before
process.on("error", error => fooLog.record(error));
After
supervisor.watch("foo-worker", { start: startFooWorker, health: fooWorkerHealth, restart: { maxAttempts: 5, backoffMs: 1000 }, });

Autonomous Recovery

Details
Violated by
known remediable failure requiring human action
Detected by
incidents resolved by repetitive manual restart/rollback
Measured by
auto-remediation success rate
Refactored by
Add Auto-Restart, Add Remediation Workflow
Enforced by
orchestration automation
Before
if (fooProjection.failed) operator.rebuild(fooProjection);
After
fooProjection.onFailure(async checkpoint => { await fooProjection.reset(checkpoint.lastValidOffset); await fooProjection.replay(); });

Health Checks

Details
Violated by
traffic routed to unhealthy instance
Detected by
missing or shallow health endpoint
Measured by
health-check accuracy
Refactored by
Add Liveness/Readiness/Dependency Checks
Enforced by
deployment policy
Before
app.get("/health", () => "ok");
After
app.get("/health", async () => { const fooStoreOk = await fooStore.ping(); const eventBusOk = await eventBus.ping(); return { state: fooStoreOk && eventBusOk ? "ready" : "blocked", checks: { fooStore: fooStoreOk, eventBus: eventBusOk }, }; });

Failover

Details
Violated by
no alternate instance/path for critical dependency
Detected by
single active dependency with no failover
Measured by
failover time, availability
Refactored by
Add Replica, Add Failover Routing
Enforced by
disaster recovery tests
Before
const foo = await primaryFooStore.find(id);
After
const foo = await failover.read([ primaryFooStore, secondaryFooStore, ], store => store.find(id));

Redundancy

Details
Violated by
critical singleton dependency
Detected by
SPOF analysis
Measured by
redundancy factor
Refactored by
Add Replica, Add Backup Path
Before
const fooService = deploy({ replicas: 1 });
After
const fooService = deploy({ replicas: 3, spreadAcross: ["zone-a", "zone-b", "zone-c"] });

Replication

Details
Violated by
unreplicated critical state
Detected by
SPOF data stores
Measured by
replication lag, replica count
Refactored by
Add Replica, Define Consistency Model
Enforced by
infrastructure policy
Before
await primaryFooStore.save(foo);
After
await replicatedFooStore.save(foo, { replicas: 3, writeQuorum: 2 });

Auto-Scaling

Details
Violated by
manual-only scaling for variable load
Detected by
saturation under load without scale policy
Measured by
scaling latency, saturation rate
Refactored by
Add Scaling Policy, Make Service Stateless
Enforced by
infrastructure-as-code policy
Before
deployFooWorkers({ replicas: 4 });
After
deployFooWorkers({ minReplicas: 2, maxReplicas: 20, scaleOn: { queueDepthPerWorker: 100 }, scaleInCooldownSeconds: 300, });

Auto-Remediation

Details
Violated by
repeatable failure with no automated response
Detected by
repeated manual runbook actions
Measured by
remediation success, false action rate
Refactored by
Automate Runbook, Add Guardrails
Enforced by
operations policy
Before
alert.on("FooDiskFull", notifyOperator);
After
alert.on("FooDiskFull", async event => { await fooStorage.compact(event.volumeId); await fooStorage.verify(event.volumeId); });

Rollback

Details
Violated by
deployment cannot be reverted
Detected by
no rollback path
Measured by
rollback success time
Refactored by
Add Rollback Plan, Make Migration Backward-Compatible
Enforced by
release gates
Before
deploy(fooVersion);
After
const release = await deploy(fooVersion); if (!(await release.verify())) await release.rollback(previousFooVersion);

Blue-Green Deployment

Details
Violated by
high-risk in-place production deploys
Detected by
no parallel release environment
Measured by
cutover failure rate
Refactored by
Add Blue/Green Environments
Enforced by
deployment pipeline
Before
routeAllTraffic(deployFoo("v2"));
After
const green = await deployFoo("v2"); await verify(green); await router.switch({ from: "blue", to: "green" });

Canary Deployment

Details
Violated by
full rollout without health/error guard
Detected by
no staged traffic policy
Measured by
canary error budget, rollback trigger rate
Refactored by
Add Canary Stage, Add Automated Guardrails
Enforced by
deployment pipeline
Before
await router.route("foo-v2", 100);
After
await router.route("foo-v2", 5); await verifyCanary({ errorRate: 0.01, latencyP95Ms: 200 }); await router.progressiveShift("foo-v2", [25, 50, 100]);

Chaos Engineering

Details
Violated by
resilience assumed but never exercised
Detected by
no fault-injection testing of recovery paths
Measured by
unverified failure-mode count
Refactored by
Introduce Controlled Fault Injection
Enforced by
resilience review
Before
assumeFooSurvivesZoneLoss();
After
chaos.experiment("foo-zone-loss", { inject: () => killZone("zone-a"), hypothesis: () => fooHealth.available(), });

Graceful Shutdown

Details
Violated by
processes terminated mid-request with no drain
Detected by
dropped in-flight work on deploy/restart
Measured by
requests lost per restart
Refactored by
Implement Graceful Drain on Shutdown
Enforced by
operations review
Before
process.on("SIGTERM", () => process.exit(0));
After
process.on("SIGTERM", async () => { server.stopAccepting(); await fooQueue.drain(); await server.close(); process.exit(0); });

RAID Redundancy

  • Kind: technique
  • Severity: mandatory for managed infrastructure
  • Scope: storage, redundancy, infrastructure
  • Layer: Correctness Core
Details
Violated by
durable data written to a single disk with no physical redundancy
Detected by
total data loss when one drive fails
Measured by
tolerated simultaneous disk failures
Refactored by
Place data on a mirrored or parity RAID array (RAID 1/5/10)
Enforced by
storage architecture review
Before
const store = new SingleDiskFooStore("/dev/sda");
After
const store = new FooStore({ volume: raidArray({ level: 10, disks: ["/dev/sda", "/dev/sdb", "/dev/sdc", "/dev/sdd"] }), });

SOLID / Object-Oriented Design

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_interface_segregation["Interface Segregation Principle (ISP)"]
    n_dependency_inversion["Dependency Inversion Principle (DIP)"]
    n_open_closed["Open/Closed Principle (OCP)"]
    n_liskov_substitution["Liskov Substitution Principle (LSP)"]
    n_polymorphism["Polymorphism"]
    n_liskov_substitution --> n_polymorphism
    n_polymorphism --> n_open_closed

Interface Segregation Principle (ISP)

Details
Violated by
clients depending on unused methods
Detected by
unused interface method implementations
Measured by
interface method usage ratio
Refactored by
Split Interface, Extract Role Interface
Enforced by
interface usage analysis, lint rules
Before
interface FooWorker { load(id: FooId): Foo; save(foo: Foo): void; delete(id: FooId): void; export(): string; } class FooReader implements FooWorker {}
After
interface FooReader { load(id: FooId): Foo; } interface FooWriter { save(foo: Foo): void; } interface FooRemover { delete(id: FooId): void; } class CachedFooReader implements FooReader { load(id: FooId) { return fooCache.get(id)!; } }

Dependency Inversion Principle (DIP)

Details
Violated by
domain importing infrastructure
Detected by
dependency direction violations
Measured by
inward dependency ratio
Refactored by
Extract Interface, Introduce Port, Inject Dependency
Enforced by
dependency graph rules, architecture tests
Before
class FooService { private readonly store = new SqlFooStore(); save(foo: Foo) { return this.store.save(foo); } }
After
interface FooStore { save(foo: Foo): Promise<void>; } class FooService { constructor(private readonly store: FooStore) {} save(foo: Foo) { return this.store.save(foo); } }

Open/Closed Principle (OCP)

Details
Violated by
repeated modification of stable core for variants
Detected by
growing conditionals, repeated edits to central classes
Measured by
modification frequency of core modules
Refactored by
Extract Strategy, Add Extension Point, Introduce Plugin
Enforced by
extension policies, change analysis
Before
function priceFoo(kind: string, value: number) { if (kind === "foo") return value; if (kind === "bar") return value * 2; throw new Error("unknown kind"); }
After
interface FooPricing { price(value: number): number; } const registry = new Map<string, FooPricing>(); export function registerPricing(kind: string, pricing: FooPricing) { registry.set(kind, pricing); } export function priceFoo(kind: string, value: number) { const pricing = registry.get(kind); if (!pricing) throw new Error(`unknown kind ${kind}`); return pricing.price(value); } registerPricing("bar", { price: value => value * 2 });

Liskov Substitution Principle (LSP)

Details
Violated by
subclass weakening postconditions or strengthening preconditions
Detected by
overridden method contract divergence
Measured by
contract test pass rate across subtypes
Refactored by
Replace Inheritance, Extract Interface, Split Hierarchy
Enforced by
contract tests, type tests
Before
class FooStore { save(foo: Foo): Promise<Receipt> { return persist(foo); } } class ReadOnlyFooStore extends FooStore { save(): Promise<Receipt> { throw new Error("not supported"); } }
After
class FooStore { save(foo: Foo): Promise<Receipt> { return persist(foo); } } class AuditedFooStore extends FooStore { async save(foo: Foo): Promise<Receipt> { const receipt = await super.save(foo); audit.record(receipt); return receipt; } }

Polymorphism

Details
Violated by
instanceof/switch dispatch over types
Detected by
conditional type checks, duplicated branching
Measured by
polymorphic dispatch ratio
Enforced by
code review, static analysis rules
Before
function renderFoo(kind: string, foo: Foo) { if (kind === "text") return foo.name; if (kind === "json") return JSON.stringify(foo); throw new Error("unknown renderer"); }
After
interface FooRenderer { render(foo: Foo): string; } class TextFooRenderer implements FooRenderer { render(foo: Foo) { return foo.name; } } class JsonFooRenderer implements FooRenderer { render(foo: Foo) { return JSON.stringify(foo); } } function renderFoo(renderer: FooRenderer, foo: Foo) { return renderer.render(foo); }

Streaming / Pipeline / Dataflow Processing

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_streaming_architecture["Streaming Architecture"]
    n_single_pass_processing["Single-Pass Processing"]
    n_pipeline_architecture["Pipeline Architecture"]
    n_lazy_evaluation["Lazy Evaluation"]
    n_sequential_access["Sequential Access"]
    n_forward_only_processing["Forward-Only Processing"]
    n_dataflow_architecture["Dataflow Architecture"]
    n_stateless_processing["Stateless Processing"]
    n_windowing["Windowing"]
    n_fan_out_fan_in["Fan-out/Fan-in"]
    n_batch_vs_stream["Batch-vs-Stream"]
    n_streaming_architecture --> n_single_pass_processing
    n_forward_only_processing --> n_single_pass_processing
    n_dataflow_architecture --> n_pipeline_architecture
    n_windowing --> n_streaming_architecture

Streaming Architecture

Details
Violated by
materializing unbounded streams
Detected by
unbounded collection over stream source
Measured by
lag, throughput, memory usage
Refactored by
Use Stream Processor, Add Backpressure
Enforced by
load/memory tests
Before
const foos = await source.readAll(); const results = foos.map(transformFoo); await sink.writeAll(results);
After
for await (const foo of source.stream()) { await sink.write(transformFoo(foo)); }

Single-Pass Processing

Details
Violated by
repeated scans over large data where avoidable
Detected by
multiple loops/materializations over same large input
Measured by
pass count, memory use
Refactored by
Fuse Passes, Use Iterator/Accumulator
Enforced by
performance review
Before
const names = foos.map(foo => foo.name); const active = foos.filter(foo => foo.active); const total = foos.reduce((sum, foo) => sum + foo.count, 0);
After
const names: string[] = []; const active: Foo[] = []; let total = 0; for (const foo of foos) { names.push(foo.name); if (foo.active) active.push(foo); total += foo.count; }

Pipeline Architecture

Details
Violated by
one giant processor handling all stages
Detected by
long procedural transformation chain
Measured by
stage cohesion, stage contract coverage
Refactored by
Split into Stages, Define Stage Contracts
Enforced by
pipeline tests
Before
function processFoo(raw: string) { const parsed = JSON.parse(raw); const validated = validateFoo(parsed); const normalized = normalizeFoo(validated); return saveFoo(normalized); }
After
const fooPipeline = pipeline( parseJson, validateWith(FooSchema), normalizeFoo, saveFoo, ); fooPipeline.run(raw);

Lazy Evaluation

Details
Violated by
computing/materializing unused results
Detected by
eager loading of large unused data
Measured by
avoided work, memory reduction
Refactored by
Use Iterator/Generator, Defer Computation
Enforced by
performance tests
Before
const normalized = millionFoos.map(normalizeFoo); const active = normalized.filter(foo => foo.active); const firstTen = active.slice(0, 10);
After
const firstTen = sequence(millionFoos) .map(normalizeFoo) .filter(foo => foo.active) .take(10) .toArray();

Sequential Access

Details
Violated by
random access over stream-only source
Detected by
seek/index assumptions on sequential source
Measured by
access pattern cost
Refactored by
Use Buffer/Index or Stream Sequentially
Enforced by
performance tests
Before
for (const id of fooIds) await fooStore.randomRead(id);
After
for await (const foo of fooStore.scan({ orderBy: "id" })) { processFoo(foo); }

Forward-Only Processing

Details
Violated by
requiring prior/future full data in stream path
Detected by
buffering full stream to look back
Measured by
buffer size, pass count
Refactored by
Add Rolling State, Redesign Parser
Enforced by
memory tests
Before
const cursor = fooStream.cursor(); cursor.next(); cursor.previous(); cursor.seek(0);
After
for await (const foo of fooStream) { await processFoo(foo); }

Dataflow Architecture

Details
Violated by
hidden data dependencies between stages
Detected by
implicit shared state in pipeline
Measured by
data dependency clarity
Refactored by
Make Data Edges Explicit, Split Stages
Enforced by
pipeline contracts
Before
controller.runFoo(); controller.runBar(); controller.runBaz();
After
const graph = dataflow() .source("foo", fooSource) .map("bar", "foo", toBar) .map("baz", "bar", toBaz) .sink("output", "baz", bazSink); await graph.run();

Stateless Processing

Details
Violated by
hidden mutable state in processor
Detected by
mutable state across records/requests
Measured by
stateful operator count
Refactored by
Externalize State, Pass State Explicitly
Enforced by
Before
class FooProcessor { private previous?: Foo; process(foo: Foo) { const result = merge(this.previous, foo); this.previous = foo; return result; } }
After
function processFoo(foo: Foo, context: Readonly<FooContext>): FooResult { return deriveFooResult(foo, context); }

Windowing

Details
Violated by
aggregating an unbounded stream into ever-growing state
Detected by
unbounded accumulator over a stream
Measured by
aggregation state growth rate
Refactored by
Aggregate over Windows
Enforced by
streaming design review
Before
const total = allFooEvents.reduce((sum, event) => sum + event.value, 0);
After
for await (const window of fooStream.tumbling({ seconds: 60 })) { emit(window.start, window.events.reduce((sum, event) => sum + event.value, 0)); }

Fan-out/Fan-in

Details
Violated by
independent items processed strictly one at a time
Detected by
serial loop over parallelizable work
Measured by
parallelism utilization
Refactored by
Fan Out Work, Fan In Results
Enforced by
pipeline design review
Before
const report = await buildFullFooReport(foos);
After
const partials = await fanOut(partition(foos), buildPartialFooReport); const report = fanIn(partials, mergeFooReports);

Batch-vs-Stream

Details
Violated by
low-latency needs served by periodic batch jobs
Detected by
batch cadence mismatched to freshness requirements
Measured by
data-freshness lag vs requirement
Refactored by
Choose Batch or Stream by Latency Need
Enforced by
data architecture review
Before
schedule.daily(() => reprocessAllFoos());
After
fooStream.subscribe(foo => processFoo(foo));

Structural Patterns

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_adapter_pattern["Adapter Pattern"]
    n_facade_pattern["Facade Pattern"]
    n_proxy_pattern["Proxy Pattern"]
    n_bridge_pattern["Bridge Pattern"]
    n_decorator_pattern["Decorator Pattern"]
    n_composite_pattern["Composite Pattern"]
    n_flyweight_pattern["Flyweight Pattern"]

Adapter Pattern

Details
Violated by
foreign model leaking into core
Detected by
external SDK types in domain/application
Measured by
external leakage count
Refactored by
Add Adapter, Add Translator
Enforced by
boundary import rules
Before
function saveFoo(foo: Foo) { return legacyClient.put(foo.id, foo.name, foo.count); }
After
class LegacyFooAdapter implements FooStore { constructor(private readonly client: LegacyClient) {} save(foo: Foo) { return this.client.put(foo.id, foo.name, foo.count); } }

Facade Pattern

Details
Violated by
consumers depending on many subsystem internals
Detected by
broad dependency surface to subsystem
Measured by
consumer dependency count
Refactored by
Introduce Facade
Enforced by
API boundary rules
Before
const foo = fooValidator.validate(fooParser.parse(raw)); await fooStore.save(foo); await fooEvents.publish(foo);
After
class FooFacade { async create(raw: string) { const foo = fooValidator.validate(fooParser.parse(raw)); await fooStore.save(foo); await fooEvents.publish(foo); } }

Proxy Pattern

Details
Violated by
uncontrolled direct resource access
Detected by
bypassed access wrapper
Measured by
proxy bypass count
Refactored by
Introduce Proxy
Enforced by
access rules
Before
function loadFoo(id: FooId) { return remoteFooStore.find(id); }
After
class CachingFooStoreProxy implements FooStore { constructor(private readonly target: FooStore) {} async find(id: FooId) { const cached = fooCache.get(id); if (cached) return cached; const foo = await this.target.find(id); fooCache.set(id, foo); return foo; } }

Bridge Pattern

Details
Violated by
subclass explosion for combinations
Detected by
parallel hierarchies / deep variant classes
Measured by
variant class count
Refactored by
Introduce Bridge
Enforced by
Before
class SqlJsonFooExporter {} class SqlCsvFooExporter {} class MemoryJsonFooExporter {} class MemoryCsvFooExporter {}
After
interface FooSource { read(): Promise<readonly Foo[]>; } interface FooFormat { encode(foos: readonly Foo[]): string; } class FooExporter { constructor(private readonly source: FooSource, private readonly format: FooFormat) {} async export() { return this.format.encode(await this.source.read()); } }

Decorator Pattern

Details
Violated by
many subclasses for optional features
Detected by
repeated wrapper-like subclasses
Measured by
variant explosion count
Refactored by
Introduce Decorator
Enforced by
interface conformance tests
Before
class LoggedSqlFooStore extends SqlFooStore { override save(foo: Foo) { logger.info("foo.saved", { fooId: foo.id }); return super.save(foo); } }
After
class LoggedFooStore implements FooStore { constructor(private readonly inner: FooStore, private readonly log: Log) {} save(foo: Foo) { this.log.write(foo.id); return this.inner.save(foo); } }

Composite Pattern

Details
Violated by
callers branching on leaf-vs-container at every node
Detected by
isContainer/isLeaf conditionals during traversal
Measured by
node-kind conditional count
Refactored by
Unify Leaf and Composite behind one interface
Enforced by
Before
function totalFoo(item: Foo | FooGroup): number { if ("children" in item) return item.children.reduce((sum, child) => sum + totalFoo(child), 0); return item.value; }
After
interface FooComponent { total(): number; } class FooLeaf implements FooComponent { constructor(private readonly value: number) {} total() { return this.value; } } class FooGroup implements FooComponent { constructor(private readonly children: readonly FooComponent[]) {} total() { return this.children.reduce((sum, child) => sum + child.total(), 0); } }

Flyweight Pattern

Details
Violated by
identical heavy state duplicated across many instances
Detected by
repeated equal intrinsic state across objects
Measured by
duplicate-state memory footprint
Refactored by
Extract Flyweight, Share Intrinsic State
Enforced by
profiling review
Before
const icons = foos.map(foo => new FooIcon(foo.position, loadSprite(foo.kind)));
After
const spriteCache = new Map<string, Sprite>(); function fooSprite(kind: string) { const cached = spriteCache.get(kind); if (cached) return cached; const sprite = loadSprite(kind); spriteCache.set(kind, sprite); return sprite; } const icons = foos.map(foo => ({ position: foo.position, sprite: fooSprite(foo.kind) }));

Taxonomy / Classification / Naming

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_closed_vocabulary["Closed Vocabulary"]
    n_positional_slot_resolution["Positional Slot Resolution"]
    n_concern_folder_correspondence["Concern-Folder Correspondence"]
    n_glob_resolvable_tree["Glob-Resolvable Tree"]
    n_declared_jurisdiction["Declared Jurisdiction"]
    n_bounded_nesting_depth["Bounded Nesting Depth"]
    n_sideways_overflow["Sideways Overflow"]
    n_one_concern_per_file["One Concern Per File"]
    n_narrowest_concern["Narrowest Concern"]
    n_layer_spine_precedence["Layer Spine Precedence"]
    n_agnostic_first_vocabulary["Agnostic-First Vocabulary"]
    n_guided_vocabulary_refusal["Guided Vocabulary Refusal"]
    n_derived_naming_registry["Derived Naming Registry"]
    n_member_never_restates_the_set["Member Never Restates the Set"]
    n_manual_identity_migration["Manual Identity Migration"]
    n_closed_vocabulary --> n_concern_folder_correspondence
    n_positional_slot_resolution --> n_closed_vocabulary
    n_concern_folder_correspondence --> n_glob_resolvable_tree
    n_glob_resolvable_tree --> n_concern_folder_correspondence
    n_declared_jurisdiction --> n_bounded_nesting_depth
    n_bounded_nesting_depth --> n_sideways_overflow
    n_sideways_overflow --> n_bounded_nesting_depth
    n_one_concern_per_file --> n_narrowest_concern
    n_narrowest_concern --> n_layer_spine_precedence
    n_layer_spine_precedence --> n_narrowest_concern
    n_agnostic_first_vocabulary --> n_closed_vocabulary
    n_guided_vocabulary_refusal --> n_closed_vocabulary
    n_guided_vocabulary_refusal --> n_agnostic_first_vocabulary
    n_derived_naming_registry --> n_declared_jurisdiction

Closed Vocabulary

Details
Violated by
adding a word so a check passes
Detected by
a name slot holding a word absent from its declared array
Measured by
undeclared-word count per governed root
Refactored by
Rename to a Declared Word, Propose by Reasoning
Enforced by
registry-backed naming gate, maintainer approval
Before
<container>/managers/foo.manager.ts -> neither "managers" nor "manager" is a declared word
After
<container>/coordinators/foo.coordinator.ts -> the declared concern that already covers the role

Positional Slot Resolution

Details
Violated by
reading a word by which vocabulary declares it rather than by the slot it lands in
Detected by
a filename whose last segment before the extension is not a declared concern tag
Measured by
unparseable filename count
Refactored by
Split the Compound, Move the Tag to the Concern Slot
Enforced by
filename parser, naming gate
Before
foo-registry.ts -> one fused word, so neither slot resolves
After
foo.registry.ts -> subject "foo", concern "registry"; position decides, so a concern word is legal in the subject slot too

Concern-Folder Correspondence

Details
Violated by
a file whose concern tag differs from its parent folder's label
Detected by
tag/folder mismatch on a filesystem walk
Measured by
mismatched file count
Refactored by
Move to the Matching Concern Folder, Reclassify the File
Enforced by
placement gate, naming gate
Before
<container>/caches/foo.store.ts -> the folder says cache, the tag says store
After
<container>/stores/foo.store.ts -> the tag terminates the name and names the parent folder

Glob-Resolvable Tree

Details
Violated by
anchoring discovery to a depth, so a grouped set falls out of the pattern
Detected by
a pattern that must enumerate depths to collect one concern
Measured by
depth-anchored pattern count
Refactored by
Unanchor the Pattern, Restore the Terminating Tag
Enforced by
aggregator review, placement gate
Before
<root>/*/validators/*.ts and <root>/*/*/validators/*.ts -> one pattern per depth, and a new grouping adds another
After
**/*.validator.ts for the files, **/validators/ for the folders -> two unanchored patterns resolve the concern tree-wide

Declared Jurisdiction

Details
Violated by
inferring jurisdiction from folder shape rather than reading a declaration
Detected by
a folder at a governed root that is in neither the container nor the bucket declaration
Measured by
undeclared root-level folder count
Refactored by
Declare the Root, Place the Folder Inside an Existing Container
Enforced by
jurisdiction gate
Before
"a folder holding no folders is a bucket" -> inferred, so a container that loses its last folder silently reclassifies and its next loose file passes
After
containers{<root>: [...]} + specialContainers{<root>: [...]} -> both kinds declared; a folder in neither is flagged

Bounded Nesting Depth

Details
Violated by
adding a level to relieve collision or breadth pressure
Detected by
a path over the cap, or a role repeated or revisited along it
Measured by
over-cap path count
Refactored by
Take the Variant Slot, Add a Sibling Subject Folder
Enforced by
placement gate
Before
<container>/foo/pools/lru/bar.pool.ts -> one folder past the cap, and the extra level resolves to no role at all
After
<container>/foo/pools/bar.lru.pool.ts -> container, subject, concern, in order and at the cap; the discriminator moved into the variant slot

Sideways Overflow

Details
In tension with
none
Conflicts with
Violated by
relieving pressure downward, by nesting, instead of sideways
Detected by
a folder level introduced where a variant or a sibling subject folder resolves the collision
Measured by
nesting-relief count
Refactored by
Insert a Declared Variant, Split into Sibling Subject Folders
Enforced by
placement gate, reshape review
Before
<container>/caches/lru/foo.cache.ts beside <container>/caches/fifo/foo.cache.ts -> the collision was relieved by a new level
After
<container>/caches/foo.lru.cache.ts beside <container>/caches/foo.fifo.cache.ts -> relieved by the variant slot, at the same depth

One Concern Per File

Details
In tension with
none
Conflicts with
Violated by
forcing a two-role file under an arbitrary tag instead of splitting it
Detected by
a file that classifies equally well under two declared concerns
Measured by
split-candidate count
Refactored by
Split by Responsibility
Enforced by
classification review
Before
foo.store.ts -> holds the state AND validates every write, so its concern is two words
After
foo.store.ts + foo.validator.ts -> the ambiguity was the finding; the split is the fix

Narrowest Concern

Details
Violated by
classifying to a saturated high-level label where a narrower accurate one fits
Detected by
one tag carrying files of several distinct roles
Measured by
files per tag, skew toward the broadest tags
Refactored by
Reclassify to the Narrower Role
Enforced by
classification review
Before
foo.manager.ts -> names a stature, so it fits lifecycle owners, caches, registries and coordinators alike
After
foo.coordinator.ts -> the narrowest declared role that is accurate; a file that cannot choose is doing both

Layer Spine Precedence

Details
Requires
In tension with
none
Conflicts with
Referenced by
Violated by
reading the spine as a dependency-direction rule rather than a classification tie-break
Detected by
an irreducible two-concern overlap resolved by preference rather than by layer
Measured by
unresolved overlap count
Refactored by
Apply the Domain-Ward Tie-Break
Enforced by
classification review
Before
a file that is irreducibly both is tagged by whichever word came to mind first
After
model (domain) beats schema (infrastructure) -> domain-ward wins, and only as a tie-break after the split test fails

Agnostic-First Vocabulary

Details
Violated by
restating an agnostic role in local domain dialect
Detected by
a domain tag whose role a declared agnostic concern already covers
Measured by
domain-tag share of the vocabulary
Refactored by
Classify to the Meta Concern
Enforced by
rejection table, maintainer approval
Before
<container>/managers/ and <container>/helpers/ -> two catch-all words for roles the agnostic set already names
After
<container>/coordinators/ and <container>/predicates/ -> a domain tag is admitted only where no agnostic concern covers the role

Guided Vocabulary Refusal

Details
Violated by
reporting that a word is undeclared without resolving the declared word that covers it
Detected by
a refusal message naming only the rejected word, and a rejection table readable by a person but not by the gate
Measured by
share of refusals carrying a resolved replacement
Refactored by
Index the Rejection Table by Refused Word, Name the Covering Concern in the Refusal
Enforced by
registry-backed naming gate, rejection-table index drift-check
Before
'foo.manager.ts' -> "'manager' is not a declared concern tag" -> the author guesses again, and the table that already answered this sits in prose no gate reads
After
refused word -> rejection-table index -> "'manager' is covered by 'coordinator'" -> foo.coordinator.ts; coverage is decided by the role a file plays, never by a general-language synonym set

Derived Naming Registry

Details
Violated by
keeping the vocabulary in prose the gate cannot read, or the reasoning in the file the gate does read
Detected by
a tag in the document and absent from the registry, or either way round
Measured by
document/registry drift count
Refactored by
Derive the Registry from the Document, Move Reasoning Back to the Document
Enforced by
registry/document cross-check
Before
the vocabulary lives only in prose, so every gate re-reads it by hand and a rule written into the config is read by nobody
After
document holds the reasoning -> registry holds the declarations -> one gate and one classifier read the registry; drift either way is a bug

Member Never Restates the Set

Details
In tension with
none
Conflicts with
Violated by
repeating the grouping folder's subject in the filename
Detected by
a file subject equal to the subject folder above it
Measured by
restated-member count
Refactored by
Drop the Redundant Head
Enforced by
naming gate
Before
<container>/foo/behaviors/foo-bar.behavior.ts -> restates what the folder already said
After
<container>/foo/behaviors/bar.behavior.ts -> the folder names the set, the file names the member

Manual Identity Migration

Details
Violated by
renaming by tool across a tree whose aggregators resolve by pattern
Detected by
a shape-discovered surface whose collected count changed across a rename
Measured by
collected-member delta per aggregator
Refactored by
Re-point the Pattern, Verify the Collected Count
Enforced by
per-container reshape review, gate green between containers
Before
a rename tool rewrites every literal path; **/*.validator.ts now collects nothing and the gate stays green because nothing is left to check
After
one container -> rename -> update every importer -> re-point every pattern -> compare collected counts against the previous run -> gate green before the next container

Transactions / State / Concurrency

Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.

Relations diagram
The relations inside this category.
flowchart LR
    n_idempotency["Idempotency"]
    n_atomicity["Atomicity"]
    n_acid["ACID"]
    n_transaction_boundary["Transaction Boundary"]
    n_unit_of_work_pattern["Unit of Work Pattern"]
    n_consistency["Consistency"]
    n_isolation["Isolation"]
    n_concurrency_control["Concurrency Control"]
    n_optimistic_locking["Optimistic Locking"]
    n_pessimistic_locking["Pessimistic Locking"]
    n_state_isolation["State Isolation"]
    n_controlled_side_effects["Controlled Side Effects"]
    n_petri_nets["Petri Nets"]
    n_atomicity --> n_transaction_boundary
    n_atomicity --> n_consistency
    n_acid --> n_atomicity
    n_acid --> n_consistency
    n_acid --> n_isolation
    n_transaction_boundary --> n_atomicity
    n_transaction_boundary --> n_unit_of_work_pattern
    n_unit_of_work_pattern --> n_transaction_boundary
    n_unit_of_work_pattern --> n_atomicity
    n_unit_of_work_pattern --> n_consistency
    n_isolation --> n_concurrency_control
    n_concurrency_control --> n_isolation
    n_optimistic_locking --> n_concurrency_control
    n_pessimistic_locking --> n_isolation

Idempotency

Details
Violated by
duplicate charges/orders/messages on retry
Detected by
side-effectful handlers without deduplication
Measured by
duplicate-effect defect rate
Refactored by
Add Idempotency Key, Add Dedup Store
Enforced by
retry tests, API policy
Before
app.post("/foo", async request => fooStore.create(await request.json()));
After
app.post("/foo", async request => { const key = requireHeader(request, "Idempotency-Key"); const body = await request.json(); return idempotency.execute(key, () => fooStore.create(body)); });

Atomicity

Details
Violated by
partial updates after failure
Detected by
multi-step writes without transaction/compensation
Measured by
partial failure rate
Refactored by
Add Transaction, Add Saga/Compensation
Enforced by
transaction tests
Before
await fooStore.remove(from, foo.id); await fooStore.add(to, foo.id);
After
await database.transaction(async tx => { await tx.foos.remove(from, foo.id); await tx.foos.add(to, foo.id); });

ACID

Details
Violated by
inconsistent transactional boundaries
Detected by
non-transactional multi-write invariants
Measured by
transactional invariant defects
Refactored by
Define Transaction Boundary, Add Constraints
Enforced by
DB transactions, isolation tests
Before
await fooDb.write(foo); await barDb.write(bar);
After
await database.transaction({ isolation: "serializable" }, async tx => { await tx.foos.save(foo); await tx.bars.save(bar); assertInvariant(foo, bar); });

Transaction Boundary

Details
Violated by
spanning transactions across service boundaries
Detected by
transaction scope leakage
Measured by
transaction size/duration
Refactored by
Shrink Boundary, Add Saga
Enforced by
transaction policy
Before
await beginTransaction(); await controller.parse(request); await service.validate(foo); await repository.save(foo); await commitTransaction();
After
async function createFoo(input: CreateFoo) { const foo = validateFoo(input); return database.transaction(tx => new FooRepository(tx).save(foo)); }

Unit of Work Pattern

  • Kind: pattern
  • Severity: recommended
  • Scope: application service, persistence
  • Aliases: Unit of Work
  • Layer: Atomic Boundary
Details
Violated by
unmanaged partial persistence
Detected by
multiple independent saves in one use case
Measured by
save coordination defects
Refactored by
Introduce Unit of Work
Enforced by
persistence conventions
Before
await fooRepository.save(foo); await barRepository.save(bar); await eventRepository.save(event);
After
const uow = unitOfWork.begin(); uow.foos.save(foo); uow.bars.save(bar); uow.events.append(event); await uow.commit();

Consistency

Details
Violated by
invariant-breaking writes
Detected by
data anomalies, failed invariant checks
Measured by
consistency violation count
Refactored by
Add Constraints, Add Transaction, Add Reconciliation
Enforced by
database constraints, invariant tests
Before
foo.total = foo.items.reduce((sum, item) => sum + item.value, 0); foo.itemCount = externalCount;
After
function rebuildFoo(items: readonly FooItem[]): Foo { return { items, total: sum(items), itemCount: items.length }; } const foo = rebuildFoo(items);

Isolation

Details
Violated by
race-condition state corruption
Detected by
concurrency tests, isolation anomalies
Measured by
anomaly rate, lock contention
Refactored by
Add Locking, Set Isolation Level
Enforced by
DB isolation, concurrency tests
Before
const foo = await fooStore.find(id); foo.count += 1; await fooStore.save(foo);
After
await database.transaction({ isolation: "serializable" }, async tx => { const foo = await tx.foos.lock(id); await tx.foos.save({ ...foo, count: foo.count + 1 }); });

Concurrency Control

Details
Violated by
unsynchronized shared mutation
Detected by
race detectors, flaky concurrent tests
Measured by
race count, contention
Refactored by
Add Locking, Use Immutable State, Add CAS
Enforced by
thread-safety analysis, tests
Before
const foo = await fooStore.find(id); await fooStore.save({ ...foo, count: foo.count + 1 });
After
await fooStore.update(id, current => ({ ...current, count: current.count + 1, }), { expectedVersion: foo.version });

Optimistic Locking

Details
Violated by
Detected by
updates without version check
Measured by
conflict/retry rate
Refactored by
Add Version Column, Add Compare-And-Swap
Enforced by
repository rules, integration tests
Before
await fooTable.update({ id: foo.id, name: foo.name });
After
const updated = await fooTable.update({ id: foo.id, expectedVersion: foo.version, next: { ...foo, version: foo.version + 1 }, }); if (!updated) throw new ConflictError(foo.id);

Pessimistic Locking

Details
Violated by
missing lock around critical mutation
Detected by
concurrent update conflicts
Measured by
lock wait/deadlock rate
Refactored by
Add Lock, Narrow Lock Scope
Enforced by
transactional tests
Before
const foo = await fooTable.find(id); await fooTable.save(change(foo));
After
await database.transaction(async tx => { const foo = await tx.foos.findForUpdate(id); await tx.foos.save(change(foo)); });

State Isolation

Details
Detected by
static mutable fields, shared caches without ownership
Measured by
global state count
Refactored by
Encapsulate State, Pass Explicit State, Use Immutable Data
Enforced by
lint rules, architecture tests
Before
const globalFooState: Foo[] = []; function addFoo(foo: Foo) { globalFooState.push(foo); }
After
class FooSession { #state: Foo[] = []; add(foo: Foo) { this.#state = [...this.#state, foo]; } snapshot() { return [...this.#state]; } }

Controlled Side Effects

Details
Violated by
mutation/network/persistence hidden in pure-looking code
Detected by
side effects in domain/pure functions
Measured by
side-effect boundary violations
Refactored by
Move Side Effect to Boundary, Return Command/Event
Enforced by
effect linting, layer rules
Before
function calculateFoo(foo: Foo) { foo.count += 1; fooLog.record(foo); fooDb.save(foo); return foo.count; }
After
function nextFoo(foo: Foo): Foo { return { ...foo, count: foo.count + 1 }; } async function applyFoo(foo: Foo, store: FooStore, log: Log) { const next = nextFoo(foo); log.write(next); await store.save(next); return next; }

Petri Nets

Details
Violated by
concurrent resource flows coordinated by hand-reasoned lock ordering
Detected by
deadlocks or lost tokens found only at runtime
Measured by
unreachable or deadlock-prone markings
Refactored by
Model concurrent flow as a Petri net and analyze reachability
Enforced by
concurrency model review
Before
acquire(a); acquire(b); work(); release(b); release(a);
After
const net = petriNet({ places: { idle: 1, aHeld: 0, bHeld: 0 }, transitions: [ { name: "takeA", consume: { idle: 1 }, produce: { aHeld: 1 } }, { name: "takeB", consume: { aHeld: 1 }, produce: { bHeld: 1 } }, ], }); assertNoDeadlock(reachableMarkings(net));