Logotipo de Nw Fp Domain Modeling

Nw Fp Domain Modeling

Organización
nWave-ai
nw-fp-domain-modeling

Domain modeling with algebraic data types, smart constructors, and type-level error handling

Descripción general

EditornWave-ai
RepositorionWave
Nombre de la habilidadnw-fp-domain-modeling
Estrellas
616
Forks
65
Archivos incluidos
Solo instrucciones
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por nWave-ai en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Nw Fp Domain Modeling en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/nWave-ai/nWave/tree/main/nWave/skills/nw-fp-domain-modeling
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/nWave-ai/nWave.git /tmp/nWave
mkdir -p .claude/skills
cp -r /tmp/nWave/nWave/skills/nw-fp-domain-modeling .claude/skills/nw-fp-domain-modeling
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Nw Fp Domain Modeling en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Nw Fp Domain Modeling automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Nw Fp Domain Modeling no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

FP Domain Modeling

Domain modeling with types. Make illegal states unrepresentable, workflows as pipelines, error handling at the type level.

Cross-references: fp-principles | fp-hexagonal-architecture | fp-algebra-driven-design


1. The Two Building Blocks

[STARTER]

All domain types compose from two operations:

  • AND (Record Types): Value has ALL of these fields. Order requires CustomerInfo AND ShippingAddress AND OrderLines.
  • OR (Choice Types): Value is ONE OF these alternatives. ProductCode is either WidgetCode OR GizmoCode.

Combined recursively, these express virtually any domain structure.


2. Domain Wrappers for Primitives

[STARTER]

Never use primitives directly in the domain model. Each domain concept gets its own wrapper type.

What: Wrap primitives so the compiler distinguishes CustomerId from OrderId. When: Every primitive with domain meaning. Why: Prevents accidental mixing (compiler rejects comparing CustomerId with OrderId). Each wrapper carries its own validation rules. The type name IS the documentation.


3. Validated Construction (Smart Constructors)

[STARTER]

Raw constructor is private. A create function validates input and returns a Result type, making validation failure explicit.

Pattern: UnitQuantity must be between 1 and 1000. Its create function rejects values outside that range. A companion value function provides read access to the inner primitive.

When: Every domain wrapper with validation rules. Why: Once constructed, a value is guaranteed valid. No defensive checks deeper in the code.


4. Making Illegal States Unrepresentable

[STARTER]

The central design guideline. Instead of flags and runtime checks, model the domain so invalid states cannot be constructed.

Replace Flags with Distinct Types

Instead of { EmailAddress; IsVerified: bool }, create separate VerifiedEmailAddress and UnverifiedEmailAddress types. Functions requiring verification take VerifiedEmailAddress, making misuse a compile error.

Replace Optional Fields with Choice Types

Instead of { Email: option; Address: option } (where both could be None), create: EmailOnly | AddressOnly | EmailAndAddress. The "at least one required" rule becomes structurally enforced.

NonEmptyList for "At Least One" Rules

Define a type guaranteeing at least one element. Order with OrderLines: NonEmptyList<OrderLine> cannot have zero lines.


5. Workflows as Functions

[STARTER]

Every business workflow is a single function: Command in, Events out.

PlaceOrderWorkflow : PlaceOrderCommand -> AsyncResult<PlaceOrderEvent list>

Pipeline Composition

Workflows decompose into steps, each transforming one document type into the next:

UnvalidatedOrder -> ValidatedOrder -> PricedOrder -> Events

Each step is stateless, pure, has single input/output type, and is independently testable. The workflow assembles by piping steps together.

Why: Pipeline makes the business process visible. Each step name is a domain concept.


6. Document Lifecycle as State Types

[INTERMEDIATE]

Rather than one Order type with flags, create separate types for each lifecycle stage:

  • UnvalidatedOrder (raw input, all fields strings)
  • ValidatedOrder (all fields checked)
  • PricedOrder (prices calculated)

A top-level Order choice type unifies all states. New states (e.g., Refunded) added without breaking existing code.

When: Domain entities with distinct lifecycle stages where different data is available at each stage.


7. State Machines with Types

[INTERMEDIATE]

When an entity has distinct states with different data and different allowed operations, model each state as a separate type.

ShoppingCart = EmptyCart | ActiveCart of ActiveCartData | PaidCart of PaidCartData

Transition functions take the choice type, pattern-match on current state, return new state.

Benefits: All states explicit | each state has own data | invalid transitions prevented by types | pattern matching warnings reveal unhandled edge cases.


8. Error-Track Pipelines (Railway Pattern)

[INTERMEDIATE]

Each function returns a Result type. Pipeline short-circuits on first failure.

rawInput
  |> validateOrder           -- Result<ValidOrder, Error>
  |> bind calculateTotal     -- Result<PricedOrder, Error>
  |> bind checkInventory     -- Result<ConfirmedOrder, Error>
  |> bind chargePayment      -- Result<PaidOrder, Error>
  |> map generateReceipt     -- Result<Receipt, Error>

Key combinators:

  • map: Transform success value (one-track into two-track)
  • bind: Chain a function that itself returns Result
  • mapError: Transform error value
  • tee: Perform side effect without changing value (logging)

Error Classification

CategoryExamplesStrategy
Domain ErrorsValidation failure, out of stockModel as types, return via Result
PanicsOut of memory, null referenceThrow exceptions, catch at top level
Infrastructure ErrorsNetwork timeout, auth failureCase-by-case

Unifying Error Types

Each step may have its own error type. Define a common error choice type and use mapError to lift step errors before composing.

Collecting All Errors (Applicative Validation)

[ADVANCED]

Standard bind short-circuits on first error. For validation where you want ALL errors, use Applicative style -- runs all validations and accumulates errors into a list. See fp-principles section 5.

When: Form validation | batch input checking | any place user needs all errors at once.


9. Modeling Dependencies

[INTERMEDIATE]

Each workflow step declares exactly the functions it needs as parameters:

CheckProductCodeExists : ProductCode -> bool
GetProductPrice        : ProductCode -> Price

Convention: Dependencies first in parameter list, primary input last. Enables partial application (functional DI).

Public vs. internal: Top-level workflow hides dependencies from callers. Internal steps make them explicit.

See fp-hexagonal-architecture section 5 for full DI decision tree.


10. Persistence Ignorance

[INTERMEDIATE]

Domain model has no awareness of databases. Two distinct type hierarchies:

  • Domain types: Rich, nested, use choice types, validated wrappers. Not serialization-friendly.
  • DTO types: Flat, primitives, nullable, arrays. Designed for serialization.

Conversion Pattern

  • fromDomain: Domain -> DTO. Always succeeds.
  • toDomain: DTO -> Result<Domain, Error>. May fail (validation happens here).

Serialization as Pipeline Steps

JSON -> deserialize -> DTO -> toDomain -> [WORKFLOW] -> fromDomain -> DTO -> serialize -> JSON

Domain workflow never sees JSON or DTOs directly.


11. Bounded Contexts

[ADVANCED]

Each context has its own dialect of domain language. Contexts communicate only through events and DTOs. Design for autonomy.

Trust boundaries: Input gate validates and converts incoming DTOs to domain types. Output gate converts domain types to DTOs, deliberately dropping private information.

Inter-context relationships: Shared Kernel (shared design) | Customer/Supplier (downstream defines contract) | Anti-Corruption Layer (translator preventing external model from corrupting internal domain).


Decision Tree: How to Model This Domain Concept?

Is it a simple value with validation rules?
  YES --> Domain Wrapper + Smart Constructor
  NO -->
    Does it represent one of several alternatives?
      YES --> Choice Type (sum type)
      NO -->
        Does it group several values together?
          YES --> Record Type (product type)
          NO -->
            Does it have distinct lifecycle stages?
              YES --> State Machine with Types (section 7)
              NO -->
                Is it an operation that transforms data through stages?
                  YES --> Workflow Pipeline (section 5)
                  NO --> Evaluate whether it needs modeling at all

12. Key Design Heuristics

  1. Start from events and workflows, not data structures
  2. Let the domain expert drive naming -- their vocabulary, not technical jargon
  3. Use types to enforce business rules at compile time -- every rule in the type system needs no unit test
  4. Document effects in signatures -- Result for errors | Async for I/O | Option for missing data
  5. Separate domain types from serialization types -- domain is pure; serialization is infrastructure
  6. Prefer explicit over implicit -- every input and dependency is a function parameter

Naming Patterns

  • Types as nouns: Order | ProductCode | CustomerInfo
  • Workflows as verbs: ValidateOrder | PriceOrder | PlaceOrder
  • Events in past tense: OrderPlaced | OrderShipped
  • Commands in imperative: PlaceOrder | ShipOrder | CancelOrder
  • Lifecycle prefixes: UnvalidatedOrder | ValidatedOrder | PricedOrder

Preguntas frecuentes

¿Qué hace la habilidad de IA Nw Fp Domain Modeling?

Domain modeling with algebraic data types, smart constructors, and type-level error handling

¿Por qué usar Nw Fp Domain Modeling en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Nw Fp Domain Modeling está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Nw Fp Domain Modeling en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/nWave-ai/nWave/tree/main/nWave/skills/nw-fp-domain-modeling. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Nw Fp Domain Modeling?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Nw Fp Domain Modeling?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Nw Fp Domain Modeling con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Nw Fp Domain Modeling?

Sí. nWave-ai la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇