# Anatomy of a USEE Piece

## Structural Specification for Protocol Pieces

**Version 1.0**

> **Note on vocabulary:** USEE is a Spanish-originated protocol. File names, field names, CLI arguments, and error identifiers shown in code blocks (`PIEZA.usee`, `nombre`, `ejecutar`, `--ayuda`, etc.) are part of the normative standard and must be used as-is, the same way HTML tags like `<div>` are not translated. The surrounding prose is in English; the identifiers are not.

---

## Overview

A USEE piece is an atomic unit of software that:

- Does a single thing
- Communicates through structured text
- Works independently
- Can be combined with other pieces

This document defines the mandatory structure every piece must follow to be considered compatible with the USEE protocol.

---

## File Structure

Every USEE piece must contain, at minimum:

```
piece-name/
├── PIEZA.usee          # Piece manifest (mandatory)
├── LEEME.md            # Human-facing documentation (mandatory)
├── ENTRADA.ejemplo     # Example of valid input (mandatory)
├── SALIDA.ejemplo      # Example of expected output (mandatory)
├── ejecutar            # Main entry point (mandatory)
├── pruebas/            # Test directory (mandatory)
│   ├── caso-basico.entrada
│   ├── caso-basico.salida
│   └── ...
└── codigo/             # Implementation (free structure)
    └── ...
```

### Mandatory Files

| File | Purpose |
|---------|-----------|
| `PIEZA.usee` | Structured metadata of the piece |
| `LEEME.md` | Human-readable documentation |
| `ENTRADA.ejemplo` | Shows what the piece receives |
| `SALIDA.ejemplo` | Shows what the piece produces |
| `ejecutar` | Command or script that runs the piece |
| `pruebas/` | Test cases for automated validation |

### Optional Files

| File | Purpose |
|---------|-----------|
| `CAMBIOS.md` | Version history |
| `CONFIG.ejemplo` | Configuration example |
| `ejecutar-json` | JSON adapter (Level 3) |
| `ejecutar-http` | HTTP adapter (Level 4) |
| `licencia.txt` | Terms of use |

---

## The PIEZA.usee File

This file contains the piece's metadata in USEE Text Format (FTU).

### Mandatory Fields

```
# Identity
nombre: login
version: 1.0.0
creador: name@email.com
fecha_creacion: 2025-01-15

# Description
descripcion_corta: Authenticates a user with email and password
descripcion_larga: |
  Receives user credentials (email and password) and checks
  whether they match an existing record. Returns a session
  identifier if authentication succeeds, or a descriptive error
  if it fails.

# Classification
categoria: autenticacion
etiquetas: usuario, sesion, seguridad

# Capability
accion: autenticar usuario
entrada_descripcion: User credentials
salida_descripcion: Authentication result with session or error

# Requirements
lenguaje: python
version_lenguaje_minima: 3.6
dependencias_externas: ninguna
dependencias_usee: ninguna

# Commercial
costo_por_uso: 0.001
moneda: usd
modelo_cobro: por_llamada
```

### Optional Fields

```
# Configuration
opciones_configuracion: tiempo_expiracion, intentos_maximos, bloqueo_temporal
configuracion_requerida: no

# Performance
tiempo_respuesta_promedio_ms: 50
memoria_maxima_mb: 64

# Compatibility
sistemas_operativos: linux, macos, windows
arquitecturas: x64, arm64

# Services
requiere_red: no
requiere_almacenamiento: si
base_datos_compatible: sqlite, postgres, mysql

# Available adapters
adaptador_json: si
adaptador_http: si
puerto_http_default: 8080

# Support
documentacion_url: https://example.com/docs/login
codigo_url: https://github.com/example/usee-login
soporte_contacto: support@example.com
```

---

## The LEEME.md File

Human-readable documentation. It must follow this structure:

```markdown
# [Piece Name]

[One sentence describing what it does]

## What It Does

[Paragraph explaining the purpose in plain language]

## What It Does Not Do

[List of things this piece does NOT do, to prevent confusion]

## Quick Start

[The simplest possible example of using the piece]

## Input

[Description of every input field]

### Mandatory Fields

| Field | Type | Description |
|-------|------|-------------|
| ... | ... | ... |

### Optional Fields

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| ... | ... | ... | ... |

## Output

[Description of every output field]

### Successful Output

| Field | Type | Description |
|-------|------|-------------|
| ... | ... | ... |

### Error Output

| Field | Type | Description |
|-------|------|-------------|
| ... | ... | ... |

## Examples

### [Use case name]

[Full example with input and output]

## Configuration

[Available configuration options]

## Common Errors

| Code | Meaning | Solution |
|--------|-------------|----------|
| ... | ... | ... |

## Dependencies

[List of dependencies and why they are necessary]

## Version History

[Summary of changes per version]
```

---

## Input and Output Examples

### ENTRADA.ejemplo

Should show the most common use case:

```
# Example input for the Login piece
# This is the most basic usage

usuario: example@email.com
clave: my_secure_password
```

### SALIDA.ejemplo

Should show the output corresponding to the example input:

```
# Successful output for the example input

estado: ok
sesion_id: usr_abc123xyz789
expira: 2025-01-16T10:30:00Z
usuario_id: usr_001
```

---

## The ejecutar File

The main entry point of the piece.

### Requirements

1. Must be directly executable from a terminal
2. Must read from stdin
3. Must write results to stdout
4. Must write errors to stderr
5. Must return exit code 0 on success, non-zero on error

### Standard Behavior

```bash
# Basic usage (stdin/stdout)
echo "usuario: john@example.com
clave: secret123" | ./ejecutar

# With input file
./ejecutar < input.txt

# With output file
./ejecutar < input.txt > output.txt

# Show help
./ejecutar --ayuda

# Show version
./ejecutar --version
```

### Mandatory Arguments

| Argument | Description |
|-----------|-------------|
| `--ayuda` | Shows usage instructions |
| `--version` | Shows the piece version |

### Standard Optional Arguments

| Argument | Description |
|-----------|-------------|
| `--config [file]` | Use a configuration file |
| `--json` | Input/output in JSON format |
| `--silencioso` | Show only errors |
| `--verbose` | Show debug information |

---

## Test Directory

Tests are mandatory and must be automatically verifiable.

### Structure

```
pruebas/
├── caso-basico.entrada       # Case input
├── caso-basico.salida        # Expected output
├── caso-basico.descripcion   # (Optional) Case description
├── error-clave-vacia.entrada
├── error-clave-vacia.salida
├── error-clave-vacia.codigo  # Expected exit code (e.g., 1)
└── ...
```

### Naming Convention

- `caso-[name].entrada` — Input data
- `caso-[name].salida` — Expected output
- `error-[name].entrada` — Case that should produce an error
- `error-[name].salida` — Expected error message
- `error-[name].codigo` — Expected exit code

### Mandatory Cases

Every piece must include at least:

1. **caso-basico**: The simplest and most common use
2. **caso-completo**: Usage with every optional field
3. **error-entrada-vacia**: Behavior without input
4. **error-campo-faltante**: Behavior without mandatory fields

### Automated Verification

Tests are executed with:

```bash
# Verifier pseudocode
for each *.entrada file in pruebas/:
    name = extract_name(file)
    input = read(name.entrada)
    expected_output = read(name.salida)
    expected_code = read(name.codigo) or 0
    
    actual_output, actual_code = run(piece, input)
    
    assert(actual_output == expected_output)
    assert(actual_code == expected_code)
```

---

## Exit Codes

USEE pieces must use consistent exit codes:

| Code | Meaning |
|--------|-------------|
| 0 | Success — the operation completed correctly |
| 1 | General error — something went wrong |
| 2 | Input error — the input data is invalid |
| 3 | Configuration error — the configuration is invalid |
| 4 | Dependency error — a dependency is not available |
| 5 | Connection error — could not connect to a required service |
| 10-99 | Piece-specific errors (document in LEEME.md) |

---

## Error Format

When a piece fails, it must produce structured output on stderr:

```
estado: error
codigo: error_identifier
mensaje: Human-readable description of the error
detalle: Additional information for debugging
sugerencia: What the user can do to resolve it
```

### Error Fields

| Field | Mandatory | Description |
|-------|-------------|-------------|
| `estado` | Yes | Always "error" |
| `codigo` | Yes | Unique error identifier (snake_case) |
| `mensaje` | Yes | Short human-readable description |
| `detalle` | No | Additional technical information |
| `sugerencia` | No | Recommended action for the user |

### Error Example

```
estado: error
codigo: credenciales_invalidas
mensaje: The email or password is incorrect
detalle: No match was found for the provided email
sugerencia: Check that the email is spelled correctly
```

---

## Configuration

Pieces can accept configuration from multiple sources, in order of priority:

### 1. Command-line arguments (highest priority)

```bash
./ejecutar --tiempo-expiracion=3600
```

### 2. Environment variables

```bash
USEE_LOGIN_TIEMPO_EXPIRACION=3600 ./ejecutar
```

Convention: `USEE_[PIECE_NAME]_[OPTION]`

### 3. Configuration file

```bash
./ejecutar --config=my-config.usee
```

File contents:
```
tiempo_expiracion: 3600
intentos_maximos: 5
bloqueo_temporal: si
```

### 4. Default values (lowest priority)

Defined in the piece's code.

### The USEE Configuration Rule

> A piece must work without any configuration for its most common use case.

Configuration exists to customize, not to enable.

---

## Versioning

USEE pieces follow an adapted semantic versioning scheme:

```
MAJOR.MINOR.PATCH

Example: 1.4.2
```

### When to Increment

| Component | When to increment |
|------------|-------------------|
| **MAJOR** | Never (a USEE piece does not break compatibility) |
| **MINOR** | New optional input/output fields, new functionality |
| **PATCH** | Bug fixes, performance improvements |

### The Golden Rule of USEE Versioning

> If a change would break an input that used to work, it is not an update. It is a new piece.

### Example

- `login 1.0.0` — Initial version
- `login 1.1.0` — Adds optional `recordar_sesion` field
- `login 1.1.1` — Fixes a bug in email validation
- `login 1.2.0` — Adds output field `ultimo_acceso`
- `login2 1.0.0` — New piece that changes the session format (incompatible with login 1.x)

---

## Adapters

### JSON Adapter (Level 3)

File: `ejecutar-json`

Translates input/output between JSON and USEE Text Format (FTU).

**JSON input:**
```json
{
  "usuario": "john@example.com",
  "clave": "secret123"
}
```

**FTU equivalent:**
```
usuario: john@example.com
clave: secret123
```

### HTTP Adapter (Level 4)

File: `ejecutar-http`

Exposes the piece as an HTTP service.

```bash
./ejecutar-http --puerto=8080
```

**Standard endpoints:**

| Method | Route | Description |
|--------|------|-------------|
| POST | `/` | Runs the piece |
| GET | `/salud` | Checks that the piece is running |
| GET | `/version` | Returns the piece version |
| GET | `/ayuda` | Returns the documentation |

**Usage example:**

```bash
curl -X POST http://localhost:8080/ \
  -H "Content-Type: text/plain" \
  -d "usuario: john@example.com
clave: secret123"
```

---

## Publishing Checklist

Before publishing a USEE piece, verify:

### Structure
- [ ] `PIEZA.usee` exists with every mandatory field
- [ ] `LEEME.md` exists with the required structure
- [ ] `ENTRADA.ejemplo` exists with a valid case
- [ ] Matching `SALIDA.ejemplo` exists
- [ ] `ejecutar` exists and is executable
- [ ] `pruebas/` directory exists with the mandatory cases

### Functionality
- [ ] `./ejecutar --ayuda` shows instructions
- [ ] `./ejecutar --version` shows the version
- [ ] All tests pass
- [ ] The piece works without configuration

### Documentation
- [ ] `LEEME.md` explains what it does AND what it does not do
- [ ] Every input field is documented
- [ ] Every output field is documented
- [ ] Every possible error is documented

### Quality
- [ ] The description fits in one sentence
- [ ] The piece does a single thing
- [ ] There are no unnecessary dependencies
- [ ] Errors are descriptive and useful

---

## Full Example: The "Login" Piece

### File Structure

```
login/
├── PIEZA.usee
├── LEEME.md
├── ENTRADA.ejemplo
├── SALIDA.ejemplo
├── ejecutar
├── ejecutar-json
├── ejecutar-http
├── pruebas/
│   ├── caso-basico.entrada
│   ├── caso-basico.salida
│   ├── caso-recordar.entrada
│   ├── caso-recordar.salida
│   ├── error-entrada-vacia.entrada
│   ├── error-entrada-vacia.salida
│   ├── error-entrada-vacia.codigo
│   ├── error-campo-faltante.entrada
│   ├── error-campo-faltante.salida
│   ├── error-campo-faltante.codigo
│   ├── error-credenciales.entrada
│   ├── error-credenciales.salida
│   └── error-credenciales.codigo
└── codigo/
    ├── main.py
    ├── validar.py
    └── sesion.py
```

### PIEZA.usee

```
nombre: login
version: 1.0.0
creador: team@entio.com
fecha_creacion: 2025-01-15

descripcion_corta: Authenticates a user with email and password
descripcion_larga: |
  Receives user credentials (email and password) and checks
  whether they match an existing record. Returns a session
  identifier if authentication succeeds.

categoria: autenticacion
etiquetas: usuario, sesion, seguridad
accion: autenticar usuario
entrada_descripcion: User email and password
salida_descripcion: Active session or authentication error

lenguaje: python
version_lenguaje_minima: 3.6
dependencias_externas: ninguna
dependencias_usee: ninguna

costo_por_uso: 0.001
moneda: usd
modelo_cobro: por_llamada

opciones_configuracion: tiempo_expiracion, intentos_maximos
configuracion_requerida: no
tiempo_respuesta_promedio_ms: 45
adaptador_json: si
adaptador_http: si
```

### ENTRADA.ejemplo

```
# Basic authentication
usuario: maria@example.com
clave: secure_password_123
```

### SALIDA.ejemplo

```
estado: ok
sesion_id: ses_7f8a9b2c3d4e5f6g
expira: 2025-01-16T15:30:00Z
usuario_id: usr_maria_001
```

### Test case: caso-basico.entrada

```
usuario: test@example.com
clave: test123
```

### Test case: caso-basico.salida

```
estado: ok
sesion_id: ses_test_session
expira: 2025-01-16T00:00:00Z
usuario_id: usr_test_001
```

### Test case: error-credenciales.entrada

```
usuario: test@example.com
clave: wrong_password
```

### Test case: error-credenciales.salida

```
estado: error
codigo: credenciales_invalidas
mensaje: The email or password is incorrect
sugerencia: Check your credentials and try again
```

### Test case: error-credenciales.codigo

```
1
```

---

## Summary

A USEE piece is predictable because its structure is predictable.

Every creator knows what to include.
Every user knows what to expect.
Every system knows how to verify.

This uniformity is what allows pieces created by different people, at different times, in different languages, to work together as if they had been built by the same hand.

---

**USEE**: Structure that liberates, not restricts.
