paramdef 0.2.0

Type-safe parameter definition system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
<!-- OPENSPEC:START -->
# OpenSpec Instructions

These instructions are for AI assistants working in this project.

Always open `@/openspec/AGENTS.md` when the request:
- Mentions planning or proposals (words like proposal, spec, change, plan)
- Introduces new capabilities, breaking changes, architecture shifts, or big performance/security work
- Sounds ambiguous and you need the authoritative spec before coding

Use `@/openspec/AGENTS.md` to learn:
- How to create and apply change proposals
- Spec format and conventions
- Project structure and guidelines

Keep this managed block so 'openspec update' can refresh the instructions.

<!-- OPENSPEC:END -->

# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

`paramdef` is a type-safe parameter definition system for Rust, inspired by Blender RNA, Unreal Engine UPROPERTY, and Qt Property System. The goal is to create the "serde of parameter schemas" - a production-ready library for workflow engines, visual programming tools, no-code platforms, and game engines.

**Current Status:** Active development - Phase 1-4.2 complete (Event System, Validation), Phase 4.3+ in progress.

## Build and Test Commands

### Basic Operations
```bash
# Check project
cargo check --workspace --all-targets

# Run tests (default features)
cargo test --workspace

# Run tests with specific features
cargo test --workspace --no-default-features
cargo test --workspace --features visibility
cargo test --workspace --features validation
cargo test --workspace --features serde
cargo test --workspace --features full

# Build documentation
cargo doc --no-deps --all-features
```

### Code Quality
```bash
# Format code
cargo fmt --all

# Lint with Clippy
cargo clippy --workspace --all-features -- -D warnings

# Check MSRV (1.85)
cargo +1.85 check --workspace
```

### Development Tools
```bash
# Run with LLD linker (faster builds)
cargo build  # Uses .cargo/config.toml settings

# Run security audit
cargo audit

# Check licenses
cargo deny check licenses
```

## Architecture Overview

### Three-Layer Architecture

1. **Schema Layer (Immutable)** - Parameter definitions shared via `Arc`
   - Metadata, flags, validators, transformers
   - Shareable across multiple contexts

2. **Runtime Layer (Mutable)** - Per-instance state
   - Current values, state flags (dirty, touched, valid)
   - Validation errors

3. **Value Layer** - Runtime data representation
   - Unified `Value` enum for all parameter types
   - Serialization target

### Node Hierarchy (23 Types)

The system defines 23 node types across five categories:

- **Group (2)**: Group, Panel - root aggregators, no own value, have ValueAccess
- **Decoration (8)**: Notice, Separator, Link, Code, Image, Html, Video, Progress - display-only, no value, no children
- **Container (7)**: Object, List, Mode, Matrix, Routing, Expirable, Reference - have own value + children
- **Leaf (6)**: Text, Number, Boolean, Vector, Select, File - have own value, no children

**Key Invariants:**
- Schema is ALWAYS immutable - runtime state lives in Context
- Group and Layout have no own Value - only delegate via ValueAccess API
- Decoration has no Value and no ValueAccess - pure display element
- Container and Leaf have own Value - Container also has ValueAccess
- Mode is structural, produces `{mode, value}` object (discriminated union)

### Separation of Concerns

**Trait-Based Subtypes (compile-time safe):**
- **NumberSubtype<T>**: Constrained by numeric type (int-only, float-only, any)
- **VectorSubtype<N>**: Constrained by vector size (2, 3, 4, etc.)
- **TextSubtype**: All work with String (runtime validation)
- Macros: `define_number_subtype!`, `define_vector_subtype!` for DRY definitions

**Subtype vs Unit Pattern (Blender-style):**
- **Subtype**: Semantic meaning (WHAT it is) - e.g., `Distance`, `Port`, `Position3D`
- **Unit**: Measurement system (HOW to measure) - e.g., `NumberUnit::Length`
- Benefits: Compile-time safety + 60 subtypes × 17 unit categories

**Soft vs Hard Constraints:**
- **Hard constraints**: Validation enforced (value MUST be in range)
- **Soft constraints**: UI slider hints (user can type beyond)

### Feature Flags

```toml
default = []                  # Core types only
visibility = []               # Visibility trait, Expr
validation = []               # Validators, ValidationConfig
serde = ["dep:serde"]        # Serialization + JSON conversions
events = ["dep:tokio"]       # Event system with broadcast channels
i18n = ["dep:fluent"]        # Fluent localization
chrono = ["dep:chrono"]      # Chrono type conversions
full = ["visibility", "validation", "serde", "events", "i18n", "chrono"]
```

**Design Philosophy:** Core library has zero UI dependencies - works headless (servers, CLI).

## Implementation Guidance

### Code Style and Standards

**Configured via:**
- `rustfmt.toml`: Edition 2024, max_width 100, Unix newlines
- `clippy.toml`: MSRV 1.85, strict linting with missing-docs enforcement
- `deny.toml`: License checking, security advisories

**Requirements:**
- All public APIs must have documentation
- No wildcard imports (enforced by Clippy)
- Cognitive complexity threshold: 25
- Type complexity threshold: 250
- Zero warnings in CI (`RUSTFLAGS=-Dwarnings`)

### Naming Conventions

**Clean names** - Types use `Text`, not `TextParameter`:
```rust
// ✅ Good
pub struct Text { ... }
pub struct Number { ... }

// ❌ Bad
pub struct TextParameter { ... }
pub struct NumberParameter { ... }
```

**Boolean naming** (no BooleanSubtype - use naming conventions):
- Prefixes: `show_`, `use_`, `is_`, `has_`, `enable_`, `hide_`

### Design Patterns

**Composition over proliferation:**
- 23 base types + subtypes + flags = thousands of combinations
- No specialized types like `Password` - use `Text` + `subtype: Secret` + `flags: SENSITIVE`

**Type-safe API without const generics:**
```rust
// Vector uses runtime size (VectorSubtype encodes size)
// Type-safe builders and getters, but flexible schema storage
let position = VectorParameter::vector3("position")
    .default_vec3([0.0, 0.0, 0.0])  // Enforces [f64; 3]
    .build();
```

**Generic RuntimeParameter pattern:**
```rust
pub struct RuntimeParameter<T: Node> {
    node: Arc<T>,      // Immutable schema (shared)
    state: StateFlags, // Mutable state
    errors: Vec<ValidationError>,
}
```

### Validation System (Implemented)

Hybrid validation combining declarative expressions with programmatic validators (see `docs/20-VALIDATION-SYSTEM.md`):

```rust
// Declarative validation (~80% of cases)
let rules = Rules::from_rules([
    Rule::required(),
    Rule::min_length(3),
    Rule::max_length(50),
    Rule::email(),
]);

// Programmatic validation (complex cases)
let custom = Rule::custom("password_match", |value, ctx| {
    let confirm = ctx.get("confirm_password");
    if value != confirm {
        return Err(Error::custom("mismatch", "Passwords must match").into());
    }
    Ok(())
});

// Cross-field validation via ValidationContext
pub trait Validator: Send + Sync + Debug {
    fn validate(&self, value: &Value, ctx: &ValidationContext<'_>) -> ValidationResult;
}
```

**Built-in validators:** `Required`, `Length`, `Range`, `Match`, `PasswordStrength`, `When` (conditional).

**Industry patterns:**
- Declarative expressions (JSON Schema, Zod)
- Cross-field validation (Yup `.when()`)
- Resolver pattern (React Hook Form)
- Thread-local regex cache (performance)

### Event System (Implemented)

Uses `tokio::broadcast` for EventBus (see `docs/19-EVENT-SYSTEM.md`):

```rust
// Event types
pub enum Event {
    ValueChanging { key, old_value, new_value },
    ValueChanged { key, old_value, new_value },
    ValueCleared { key, old_value },
    Validated { key, is_valid, errors },
    Touched { key },
    Dirtied { key },
    Cleaned { key },
    Reset { key },
    BatchBegin { id, description },
    BatchEnd { id },
    ContextReset,
    AllCleaned,
}

// Usage
let bus = EventBus::new(64);
let mut sub = bus.subscribe();
let ctx = Context::with_event_bus(schema, bus);

ctx.set("name", Value::text("Alice")); // Emits events

// Async receive
while let Ok(event) = sub.recv().await {
    match event {
        Event::ValueChanged { key, .. } => println!("{} changed", key),
        _ => {}
    }
}
```

**Industry patterns implemented:**
- `ValueChanging`/`ValueChanged` pair (SurveyJS)
- Batching with `BatchBegin`/`BatchEnd` (MobX transactions)
- `Touched` state (Formik)
- RAII Subscription cleanup (MobX disposer)

**Command Pattern for Undo/Redo (planned):**
- ~100 bytes per command vs ~10KB per snapshot
- Supports command merging (optimization)
- Extensible (custom commands)
- Enables transactions (MacroCommand)

## Key Documentation Files

Essential reading in `docs/`:
- `01-ARCHITECTURE.md` - Core design decisions and philosophy
- `02-TYPE-SYSTEM.md` - Complete reference for all node types
- `17-DESIGN-DECISIONS.md` - Rationale for major architectural choices
- `18-ROADMAP.md` - Implementation plan and milestones
- `19-EVENT-SYSTEM.md` - Event system documentation
- `20-VALIDATION-SYSTEM.md` - Hybrid validation system documentation

**Reading Guide for Full Understanding:**
1. README.md (this overview)
2. docs/01-ARCHITECTURE.md (30 min)
3. docs/02-TYPE-SYSTEM.md (30 min)
4. docs/17-DESIGN-DECISIONS.md (20 min)
5. docs/19-EVENT-SYSTEM.md (15 min) - for reactive features

## Common Patterns

### Adding a New Node Type

1. Must fit into one of 5 categories (Group, Layout, Decoration, Container, Leaf)
2. Implement the `Node` trait + category-specific trait
3. If has own Value: implement `Validatable` trait (if validation feature enabled)
4. If can contain children: implement `ValueAccess` trait
5. All types implement `Visibility` trait (if visibility feature enabled)
6. Add builder pattern with `::builder()` constructor

### Adding a New Subtype

1. Choose appropriate enum: `TextSubtype`, `NumberSubtype`, or `VectorSubtype`
2. Add variant to enum (keep alphabetically sorted within semantic groups)
3. Add helper method if needed (e.g., `is_code()`, `is_sensitive()`)
4. Update tests to cover new variant
5. NO need for new node type - use composition!

### Adding a New Flag

1. Add to `Flags` bitflags in order
2. Add convenience method if commonly used together
3. Document behavior and use cases
4. Update `11-FLAGS-REFERENCE.md`

## Development Workflow

### Before Committing

```bash
# Format and lint
cargo fmt --all
cargo clippy --workspace --all-features -- -D warnings

# Test all feature combinations
cargo test --workspace --no-default-features
cargo test --workspace --features visibility
cargo test --workspace --features validation
cargo test --workspace --features full

# Check documentation
cargo doc --no-deps --all-features

# Verify MSRV
cargo +1.85 check --workspace
```

### CI Pipeline

GitHub Actions runs on push/PR:
- `check`: workspace check with all targets
- `test`: default feature tests
- `test-features`: tests for each feature combination
- `fmt`: format checking
- `clippy`: linting with deny warnings
- `doc`: documentation generation with deny warnings
- `msrv`: Rust 1.85 compatibility check

## Project Structure

```
paramdef/
├── src/
│   ├── lib.rs          # Main library entry
│   ├── core/           # Key, Value, Metadata, Flags, Error
│   ├── types/          # 23 node types (leaf, container, group, decoration)
│   ├── subtype/        # TextSubtype, NumberSubtype, VectorSubtype, Unit
│   ├── schema/         # Schema builder and storage
│   ├── context/        # Runtime context with event integration
│   ├── runtime/        # RuntimeNode, State
│   ├── event/          # Event, EventBus, Subscription (events feature)
│   ├── validation/     # Expr, Rule, Validator, validators (validation feature)
│   └── prelude.rs      # Common imports
├── docs/               # 20 comprehensive design documents
├── .cargo/
│   ├── config.toml     # LLD linker configuration
│   └── audit.toml      # Security audit config
├── .github/
│   └── workflows/
│       └── ci.yml      # CI pipeline
├── .claude/
│   └── skills/         # Claude Code skills (Rust development aids)
├── clippy.toml         # Clippy linting configuration
├── deny.toml           # cargo-deny license/security config
├── rustfmt.toml        # rustfmt style configuration
└── Cargo.toml          # Package manifest (Edition 2024, MSRV 1.85)
```

## Dependencies

**Core:**
- `smartstring` - Stack-allocated short strings (<23 bytes)
- `thiserror` - Error derive macros
- `bitflags` - Type-safe bitfield flags

**Optional:**
- `serde` + `serde_json` - Serialization (serde feature)
- `tokio` - Event system with broadcast channels (events feature)
- `regex` - Pattern validation (validation feature)
- `fluent` - Mozilla Fluent localization (i18n feature)
- `chrono` - Date/time conversions (chrono feature)

## Performance Considerations

**Optimization techniques:**
- `SmartString<LazyCompact>` - Strings <23 bytes on stack
- `Arc<[Value]>` - Immutable arrays, cheap cloning
- `Arc<HashMap>` - Immutable objects, shared
- Const generics for fixed-size vectors - on stack, no heap
- Thread-local regex cache - avoid recompilation
- Lazy expression compilation - compile on first use
- Fast path checks - skip empty transformer/validator lists

## Testing Philosophy

**Target Coverage:**
- Core types: 95%+
- Parameter types: 90%+
- Overall: 90%+

**Allow in tests only** (enforced by Clippy):
- `expect`, `unwrap`, `dbg!`, `print!`
- Outside tests these trigger warnings

## Localization (i18n Feature)

**User-managed approach:**
- Library provides Fluent keys, user provides translations
- No embedded translations in library (zero binary bloat)
- User controls all languages
- Example: `fluent_id("db-host")` → user's `locales/ru/app.ftl`

## Rejected Alternatives

Important architectural decisions from `17-DESIGN-DECISIONS.md`:

- ❌ NO BooleanSubtype - too simple, Blender doesn't use
- ❌ NO ChoiceSubtype - YAGNI, UI variations are presentation not semantics
- ❌ NO const generics for Vector - type erasure kills benefits, VectorSubtype encodes size
- ❌ NO subtype in Value enum - violates separation of concerns
- ❌ NO validation in Value - validation rules belong in schema
- ❌ NO UI coupling in core - must work headless

## Industry Inspiration

paramdef combines best features from:
- **Blender RNA** - Property system architecture, subtype+unit pattern
- **Unreal Engine UPROPERTY** - Metadata and flags system
- **Qt Property System** - Signals and observers, reactive updates
- **Houdini Parameters** - Node-based workflows, soft/hard constraints
- **n8n** - Mode/branching for discriminated unions

With Rust's type safety and zero-cost abstractions.