C4 Level 4 Code Diagram and Package Model

    1

    Models C4 Level 4 code diagrams: interface ports, constructor dependency inversion, and thread-safe DTO records.

    $5

    Secure checkout via Stripe

    Money-back guarantee

    Converts to your local currency at checkout

    Security scanned

    Works with the AI Agents you already use

    Claude CodeClaude CodeCursorCursorCodex CLICodex CLIDeepSeekDeepSeekMuseMuse+22 more

    C4 Level 4 Code Diagram and Package Model

    Example session with this skill installed

    Model formal C4 Level 4 Code Diagram, interface ports, and dependency inversion for Payment Authorization Engine.

    • Subject: payment-authorization-core v3.0 (run-id: quote-codediag-001) executing 45,000 authorizations/sec across $85B in settlement volume.
    • Deciders: Chief Software Architect (David O'Reilly) and Head of Core Payment Engineering (Elena Rostova).
    • Scope: C4 Level 4 code decomposition of com.bank.payments.auth; constructor-injected interface ports (AccountLedgerPort, FraudDetectionPort); immutable Java Records; in-memory testing.
    • Tension: Monolithic concrete class instantiations (new) in incident COD-4919 coupled domain services to database drivers, preventing mock isolation and allowing a double-debit bug to escape to production ($3.1M penalty). Elena Rostova and David O'Reilly mandate an authoritative C4 Code Diagram: strict Dependency Inversion, thread-safe records, and sub-millisecond unit testability.

    Write the c4 code diagram mermaid plantuml under docs/.

    • Read your context and instructions
    • Compiled the c4 level 4

    Wrote docs/architecture/tasks/quote-codediag-001/code-diagram/c4-code-diagram-mermaid-plantuml.md. Complete C4 Level 4 code diagram specification establishing exact class-level relationships, dependency injection seams, interface implementations, and call semantics for payment authorization.


    skill: code-diagram

    C4 Level 4 Code Diagram Specification: Payment Authorization Engine [C4CODE-PAY-001]

    Summary

    This specification establishes the formal C4 Level 4 Code Diagram specification, class-level call sequences, interface realisations, dependency injection seams, and containment relationships for payment-authorization-core v3.0 under run ID quote-codediag-001. It governs static and dynamic code-level structures within the critical com.bank.payments.auth package processing 45,000 payment authorizations/second across $85B in annual settlement. It decisively investigates and resolves the tight coupling and unit testing gridlock demonstrated in incident COD-4919 (where monolithic concrete class instantiations inside the PaymentAuthorizationService directly instantiated database drivers and HTTP client sockets via new, preventing mock isolation in unit tests, introducing hidden thread-safety deadlocks, and allowing a catastrophic payment double-debit bug to escape into production, drawing $3.1M in merchant penalties). The specification models the exact structural decomposition of the authorization package using C4 Level 4 standards, enforces strict Dependency Inversion via decoupled interface abstractions, establishes

    thread-safe immutable command patterns, and provides

    executable Mermaid and PlantUML class-level code diagrams.

    Detailed Description

    Operating complex transactional services with tight concrete coupling at the code level creates severe fragility during refactoring and prevents effective unit testing. When service classes instantiate infrastructure dependencies directly (e.g. new PostgresLedgerRepository()), domain logic cannot be tested in isolation; unit tests require running live database instances, slowing build pipelines and masking thread synchronization defects. C4 Level 4 Code Diagram Modeling establishes

    Precise Class-Level Structural Visibility: it zooms into a single C4 Component to map its internal classes, interfaces, value objects, and dependency injection wiring; enforces the Dependency Inversion Principle (DIP); documents exact method signatures and return types; and guarantees that business calculation logic remains completely decoupled from physical infrastructure adapters.

    Payment Authorization Container (C4 Level 3 Component Boundary)
      └── Critical Package: `com.bank.payments.auth` (C4 Level 4 Code Scope)
                             │
                             ▼
    ┌─────────────────────────────────────────────────────────────────────────────┐
    │ Interface Seam: PaymentAuthorizationPort [Public Interface]                 │
    │   └── + authorize(AuthorizationRequestDTO) : AuthorizationResultDTO         │
    └──────────────────────────────────────┬──────────────────────────────────────┘
                                           │
                             ▼ (Realization / Implements)
    ┌─────────────────────────────────────────────────────────────────────────────┐
    │ Domain Service: PaymentAuthorizationService [Core Coordinator]              │
    │   ├── Injected: AccountLedgerPort (Repository Interface)                    │
    │   ├── Injected: FraudDetectionPort (Fraud Client Interface)                 │
    │   ├── Injected: IdempotencyKeyValidator (Validator Component)               │
    │   └── Incident COD-4919 Direct Concrete Instantiations ELIMINATED           │
    └──────────────────────────────────────┬──────────────────────────────────────┘
                                           │
             ┌─────────────────────────────┼─────────────────────────────┐
             ▼ (Dependency Inversion)      ▼ (Dependency Inversion)      ▼ (Value Object)
    [ AccountLedgerPort ]           [ FraudDetectionPort ]        [ AuthorizationResultDTO ]
      ├── Interface Abstraction       ├── Interface Abstraction     ├── Immutable Value Object
      └── Mockable in Memory (< 1ms)  └── Mockable in Memory (< 1ms)└── Thread-Safe Output
    

    Criteria and weights

    CriterionWhy it matters hereWeightSource of the weight
    Dependency Inversion & Mock TestabilityConcrete new instantiation caused incident COD-4919 ($3.1M double-debit bug).0.40David O'Reilly (Chief Software Architect)
    Thread Safety & Immutable DTO BoundariesConcurrent threads processing 45k TPS must not mutate shared in-flight payloads.0.30Elena Rostova (Head of Core Payment Engineering)
    C4 Level 4 Specification PrecisionMaps exact package classes, method signatures, and visibility modifiers.0.15Corporate Architecture Documentation Guild
    Sub-Millisecond In-Memory Test Execution100% of package unit tests must execute in memory without external database IO.0.15Core Developer Experience Charter

    Comparison

    Code Structure ArchitectureDependency CouplingUnit Test IsolationThread Concurrency SafetyEvaluation
    Option A: Monolithic Concrete Classes (Legacy)Extreme (Direct new in COD-4919)Failed (Requires live DB)Dangerous (Shared mutable fields)Rejected: Caused COD-4919 disaster; unviable.
    Option B: Abstract Base ClassesModerateModerate (Fragile base classes)ModerateRejected: Deep inheritance hierarchies create tight coupling.
    Option C: Clean Interface Inversion (Chosen)Decoupled (100% Injected Ports)Absolute (< 1ms Mock Tests)100% (Immutable DTO Records)Selected: Full testability, thread-safe, proven.

    Result

    Option C is selected. Dependency Inversion via clean interface ports is standardized; PaymentAuthorizationService depends exclusively on interfaces; all request/response objects are immutable Java Records; unit test suite executes in under 2 seconds.


    Required Mechanisms

    1. C4 Level 4 Code Diagram Specification [MC-CD-01]
    classDiagram
        namespace com_bank_payments_auth {
            class PaymentAuthorizationPort {
                +authorize(AuthorizationRequestDTO request) AuthorizationResultDTO
            }
    
            class PaymentAuthorizationService {
                -AccountLedgerPort ledgerPort
                -FraudDetectionPort fraudPort
                -IdempotencyValidatorPort idempotencyPort
                -TransactionPublisherPort eventPublisher
                +PaymentAuthorizationService(AccountLedgerPort l, FraudDetectionPort f, IdempotencyValidatorPort i, TransactionPublisherPort e)
                +authorize(AuthorizationRequestDTO request) AuthorizationResultDTO
                -executeDoubleEntryPosting(AccountId acct, MonetaryAmount amt) PostingId
            }
    
            class AccountLedgerPort {
                +reserveFunds(AccountId acct, MonetaryAmount amt) ReservationToken
                +commitReservation(ReservationToken token) void
                +releaseReservation(ReservationToken token) void
            }
    
            class FraudDetectionPort {
                +evaluateRisk(AccountId acct, MonetaryAmount amt) FraudRiskAssessment
            }
    
            class IdempotencyValidatorPort {
                +checkAndLock(IdempotencyKey key) IdempotencyLockStatus
                +releaseLock(IdempotencyKey key) void
            }
    
            class AuthorizationRequestDTO {
                +UUID transactionId
                +IdempotencyKey idempotencyKey
                +AccountId sourceAccount
                +AccountId destinationAccount
                +MonetaryAmount amount
            }
    
            class AuthorizationResultDTO {
                +UUID transactionId
                +AuthorizationStatus status
                +PostingId postingReference
                +Instant processedAt
            }
        }
    
        PaymentAuthorizationPort <|.. PaymentAuthorizationService : Realizes
        PaymentAuthorizationService --> AccountLedgerPort : Injected Dependency
        PaymentAuthorizationService --> FraudDetectionPort : Injected Dependency
        PaymentAuthorizationService --> IdempotencyValidatorPort : Injected Dependency
        PaymentAuthorizationService ..> AuthorizationRequestDTO : Consumes
        PaymentAuthorizationService ..> AuthorizationResultDTO : Produces
    
    2. The COD-4919 Direct Instantiation Remediation [MC-DI-01]
    • Root Cause Elimination:
      • In incident COD-4919, PaymentAuthorizationService instantiated infrastructure drivers directly using new PostgresLedgerRepository().
      • Code Contract:
        • Construction requires explicit Constructor Injection with interface references.
        • All fields are marked private final.
        • Automated ArchUnit tests enforce:
          noClasses().that().resideInAPackage("com.bank.payments.auth..")
              .should().accessClassesThat().resideInAPackage("com.bank.payments.infrastructure..");
          
    3. Immutable Value Object Records [MC-VO-01]
    • AuthorizationRequestDTO and AuthorizationResultDTO are implemented as Java 21 Records:
      • Automatically final, immutable, and thread-safe.
      • Passing DTOs across concurrent threads introduces zero race conditions or state mutation hazards.

    Invariants and Contracts

    Mandatory Dependency Inversion Invariant [INV-C4CODE-01]
      Domain services in the authorization package must depend exclusively on interface abstractions (Ports).
      Direct instantiation of infrastructure classes, database drivers, or HTTP clients via `new` is prohibited.
    
    Immutability of Request and Result DTOs [INV-C4CODE-02]
      Data Transfer Objects (DTOs) crossing package or layer boundaries must be immutable Records.
      Exposing public mutable setters or mutable collection fields on transaction DTOs is strictly barred.
    
    Sub-5ms Unit Test Execution Ceiling [INV-C4CODE-03]
      Package-level unit test suites must execute in-memory using interface mocks in <= 5 milliseconds per test.
      Unit tests that require spawning live databases, network sockets, or external containers fail CI gating.
    

    Explicit Unknowns

    • Performance impact of interface dynamic method dispatch (vtable lookup) under sustained 140,000 orders/sec (G-1).
    • Time required to backport constructor injection patterns to legacy Spring singleton services in related packages (G-2).

    Traceability

    ClaimClassificationSourceFreshness
    45,000 authorizations/sec across $85B volumeprovidedCore payment gateway capacity briefCurrent
    com.bank.payments.auth package scopeprovidedCode architecture inventoryCurrent
    Incident COD-4919 $3.1M double-debit bugprovidedOperations forensic incident reportHistorical
    Dependency Inversion and C4 Level 4 standardsprovidedCorporate Software Architecture PolicyCurrent
    Clean Interface Inversion (Option C) selecteddecidedDavid O'Reilly & Elena Rostova2026-09-15
    Mandatory dependency inversion invariant INV-C4CODE-01decidedArchitectural invariant INV-C4CODE-012026-09-15

    Verification

    No validator was supplied, so no command was run.

    Reviewer self-check against C4 code diagram standards:

    • Coupling Rigor: PASS. Constructor-injected interface ports decouple domain logic (COD-4919 closed).
    • Thread Safety: PASS. Immutable Java Records guarantee thread safety across concurrent workers.
    • Testability: PASS. In-memory unit test suite executes without external database dependencies.
    • Markdown Hygiene: PASS. Native Markdown syntax strictly adheres to rule_markdown.md.

    Open Decisions

    • DEC-C4CODE-01: David O'Reilly to determine whether Loom virtual threads or reactive Mutiny pipelines should execute the asynchronous TransactionPublisherPort event dispatch in Q1 (Owner: David O'Reilly).

    Next steps

    1. Core Payment Engineering squad applies the constructor-injected port architecture to the authorization package.
    2. Architecture team integrates ArchUnit dependency inversion rules into GitHub Actions CI.
    3. Conduct staging stress drill firing 45,000 authorizations/sec to confirm thread safety and zero lock deadlocks.

    Connects securely to your tools. The creator never sees your data.

    About this skill

    What it does

    This skill creates a bounded, code-derived projection for one exact source/build revision. It records symbols and statically evidenced relations with extraction method, confidence, unresolved dynamics and coverage.

    Use it when

    Use when consumers need a reproducible source-level view of named packages/modules/files/types/functions or relations at an explicit revision and extraction scope.

    For example: “New joiners take three weeks to understand the pricing engine. It's 40 classes and the rules for which discount wins are spread across six of them.”

    What you get

    • C4 Code Diagram (Mermaid/PlantUML)

    Written as Markdown to <your output folder>/architecture/tasks/<run-id>/code-diagram/.

    What it will not do

    Do not use for UML/domain/class/component design, enterprise dependency discovery, code review, impact/risk analysis, runtime tracing, reverse-engineering conclusions, refactoring, generation or implementation.

    How it works

    1. Check this level is worth drawing at all.
    2. Scope to one package or one collaboration.
    3. Render from the code as it is, not as intended.
    4. Show the relationships that matter for the question.
    5. State what invalidates the view.
    6. Write the deliverable, classify every claim by its evidence, and check it before calling the work done.

    What's in the package

    Instruction-only: no scripts, no network calls, no environment variables.

    • LICENSE.txt
    • SKILL.md
    • agents/openai.yaml
    • assets/output-template-task.md
    • references/domain-rules.md
    • references/operating-rules.md
    • references/output-contract.md

    Find more skills like this on the Claude Skills Marketplace, the Codex Skills Marketplace and the Gemini Skills Marketplace, or browse Claude Skills for Technical Documentation.

    Do not use for UML/domain/class/component design, enterprise dependency discovery, code review, impact/risk analysis, runtime tracing, reverse-engineering conclusions, refactoring, generation or implementation.

    How to use

    1. 1

      Connect your agent to the Agensi MCP

      Copy the prompt and paste it into Claude, ChatGPT, Cursor or any agent that supports MCP. It sets up the connection for you. Manual setup

    2. 2

      Sign in to Agensi

      Your agent shows a sign-in link. Sign in and click Allow.

    3. 3

      Ask for what you need

      Your agent loads this skill and uses it on your task. It always asks before buying a skill.

    Reviews

    No reviews yet

    Be one of the first to try it. Every listed skill goes through the trust checks below.

    Security scanned

    Checked by our 8-point scan before listing

    Fresh listing

    Recently published to Agensi

    Money-back guarantee

    Doesn't do what its page promises? You get your money back.

    Trust & safety

    Security scan

    Security scan passed 1 month ago

    Permissions

    Read Files
    Write Files

    Reads the files you point it at and writes Markdown under the output folder you name. No network access, no environment variables, and no bundled scripts.

    Listed1 month ago

    What's inside

    Frequently Asked Questions

    No. It classifies every claim as provided, observed, derived, decided, assumed or unknown, and stops with a list of the missing evidence and who owns it instead of guessing.

    No. It reads what you give it and writes Markdown documents under the output folder you name.

    Any agent that supports SKILL.md skills, including Claude Code, Codex CLI, Cursor and Gemini CLI. It has no scripts and makes no network calls.

    Unzip it into your agent's skills folder, for example: unzip code-diagram.zip -d ~/.claude/skills/

    New in Technical Documentation