peat-schema 0.9.0-rc.9

Wire format (Protobuf) definitions for the Peat Coordination Protocol
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# Peat Protocol Interface Control Document (ICD)

**Document Number**: CAP-ICD-001
**Version**: 0.0.1
**Status**: DRAFT
**Date**: 2025-11-06
**Classification**: UNCLASSIFIED

---

## Document Control

### Revision History

| Version | Date | Author | Changes | Approval |
|---------|------|--------|---------|----------|
| 0.0.1 | 2025-11-06 | CAP Development Team | Initial release | DRAFT |

### Approval Authority

| Role | Name | Organization | Signature | Date |
|------|------|--------------|-----------|------|
| Technical Lead | TBD | TBD | | |
| Architecture Review Board | TBD | TBD | | |
| Product Owner | TBD | TBD | | |

### Distribution List

- CAP Development Team
- Integration Partners
- Open Source Community (upon public release)

---

## 1. Introduction

### 1.1 Purpose

This Interface Control Document (ICD) defines the message schemas, data formats, and protocol interfaces for the **Capability Aggregation Protocol (CAP)**. It establishes the contractual interface between:

- Peat Protocol implementations (Rust, Python, Java, C++)
- External systems integrating with CAP (ROS2, gRPC, C2 systems)
- Storage backends (Ditto, Automerge, custom implementations)
- Transport layers (HTTP, gRPC, WebSocket, MQTT, ROS2 DDS)

### 1.2 Scope

This ICD covers:

- **Message Schemas**: Protocol Buffer definitions for all CAP messages
- **Data Formats**: Serialization formats, encoding rules, field constraints
- **Interface Specifications**: API contracts for transport adapters and storage backends
- **Version Control**: Schema versioning, backward compatibility rules
- **Semantic Constraints**: CRDT operations, validation rules, ontology

This ICD does **not** cover:

- Internal implementation details of specific CAP libraries
- Transport-specific protocols (covered by transport specifications)
- Storage backend internals (covered by storage specifications)

### 1.3 Applicable Documents

| Document ID | Title | Version | Date |
|-------------|-------|---------|------|
| ADR-012 | Schema Definition and Protocol Extensibility | 1.0 | 2025-11-06 |
| ADR-011 | CRDT + Networking Stack Selection | 1.0 | 2025-11-06 |
| SCHEMAS.md | Peat Protocol Schema Reference | 1.0 | 2025-11-06 |
| README.md | peat-schema Documentation | 1.0 | 2025-11-06 |

### 1.4 Points of Contact

| Role | Organization | Email | Phone |
|------|--------------|-------|-------|
| Technical Lead | TBD | TBD | TBD |
| Schema Working Group Chair | TBD | TBD | TBD |
| Integration Support | TBD | TBD | TBD |

---

## 2. System Overview

### 2.1 Peat Protocol Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                    External Systems                          │
│  (ROS2 Robots, C2 Systems, Python Clients, Java Services)  │
└─────────────────────┬───────────────────────────────────────┘
                      │ Uses: Protobuf Schemas (ICD-controlled)
┌─────────────────────────────────────────────────────────────┐
│                   peat-schema (This ICD)                      │
│                                                               │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐   │
│  │ common   │  │capability│  │   node   │  │   cell   │   │
│  │   .v1    │  │   .v1    │  │   .v1    │  │   .v1    │   │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘   │
│                                                               │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐   │
│  │  zone    │  │   role   │  │  beacon  │  │composition│   │
│  │   .v1    │  │   .v1    │  │   .v1    │  │   .v1    │   │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘   │
└─────────────────────┬───────────────────────────────────────┘
                      │ Implemented by:
┌─────────────────────────────────────────────────────────────┐
│              Peat Protocol Implementations                    │
│    (peat-protocol, peat-transport, peat-persistence)           │
└─────────────────────────────────────────────────────────────┘
```

### 2.2 Three-Tier Hierarchy

CAP implements a three-tier organizational hierarchy:

1. **Nodes** (Tier 1): Individual platforms (UAVs, UGVs, soldier systems)
2. **Cells** (Tier 2): Tactical squads (2-8 nodes with complementary capabilities)
3. **Zones** (Tier 3): Strategic coordination (multiple cells under zone commander)

### 2.3 Protocol Phases

1. **Discovery Phase**: Nodes broadcast beacons, discover neighbors
2. **Cell Formation Phase**: Nodes form cells based on capability composition
3. **Hierarchical Operations Phase**: Cells coordinate within zones

---

## 3. Interface Specifications

### 3.1 Schema Packages

All schemas are defined using **Protocol Buffers v3** syntax.

#### 3.1.1 Package Naming Convention

```
cap.<domain>.v<major_version>
```

Examples:
- `cap.common.v1` - Common types
- `cap.node.v1` - Node schemas
- `cap.cell.v2` - Cell schemas (future major version)

#### 3.1.2 Schema Inventory

| Package | File | Purpose | Message Count | Status |
|---------|------|---------|---------------|--------|
| `cap.common.v1` | `common.proto` | Foundation types | 5 | STABLE |
| `cap.capability.v1` | `capability.proto` | Capabilities | 4 | STABLE |
| `cap.node.v1` | `node.proto` | Nodes & operators | 8 | STABLE |
| `cap.cell.v1` | `cell.proto` | Cell formation | 6 | STABLE |
| `cap.zone.v1` | `zone.proto` | Zone hierarchy | 7 | STABLE |
| `cap.role.v1` | `role.proto` | Tactical roles | 7 | STABLE |
| `cap.beacon.v1` | `beacon.proto` | Discovery | 4 | STABLE |
| `cap.composition.v1` | `composition.proto` | Composition rules | 4 | STABLE |

**Total**: 8 packages, 45 message types

### 3.2 Data Type Specifications

#### 3.2.1 Common Types (`cap.common.v1`)

```protobuf
// Unique identifier (UUID v4)
message Uuid {
  string value = 1;  // Format: "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
}

// Timestamp (Unix epoch)
message Timestamp {
  uint64 seconds = 1;  // Seconds since 1970-01-01T00:00:00Z
  uint32 nanos = 2;    // Nanoseconds (0-999,999,999)
}

// Geographic position (WGS84)
message Position {
  double latitude = 1;   // Degrees, range: [-90.0, 90.0]
  double longitude = 2;  // Degrees, range: [-180.0, 180.0]
  double altitude = 3;   // Meters above sea level
}

// Confidence score
message Confidence {
  float value = 1;  // Range: [0.0, 1.0]
}

// Generic metadata
message Metadata {
  map<string, string> fields = 1;
}
```

**Constraints**:
- `Uuid.value`: MUST match UUID v4 format (RFC 4122)
- `Timestamp.seconds`: MUST be non-negative
- `Timestamp.nanos`: MUST be in range [0, 999999999]
- `Position.latitude`: MUST be in range [-90.0, 90.0]
- `Position.longitude`: MUST be in range [-180.0, 180.0]
- `Confidence.value`: MUST be in range [0.0, 1.0]

#### 3.2.2 Enumerations

All enumerations MUST include an `_UNSPECIFIED = 0` value per Protobuf best practices.

**Example**:
```protobuf
enum CapabilityType {
  CAPABILITY_TYPE_UNSPECIFIED = 0;  // Default/unknown
  CAPABILITY_TYPE_SENSOR = 1;
  CAPABILITY_TYPE_COMPUTE = 2;
  CAPABILITY_TYPE_COMMUNICATION = 3;
  CAPABILITY_TYPE_MOBILITY = 4;
  CAPABILITY_TYPE_PAYLOAD = 5;
  CAPABILITY_TYPE_EMERGENT = 6;
}
```

### 3.3 Message Size Limits

| Message Type | Max Size | Rationale |
|--------------|----------|-----------|
| `Beacon` | 10 KB | Must fit in single UDP packet for efficiency |
| `NodeConfig` | 50 KB | Support up to 100 capabilities per node |
| `CellState` | 100 KB | Support max 8 members with full capabilities |
| `ZoneState` | 500 KB | Support max 10 cells with aggregated data |
| `CompositionResult` | 100 KB | Support complex rule sets |

**Enforcement**: Implementations SHOULD validate message sizes and reject oversized messages.

---

## 4. Versioning and Compatibility

### 4.1 Semantic Versioning

Schema versions follow **semantic versioning** (SemVer 2.0.0):

```
<major>.<minor>.<patch>
```

- **Major**: Breaking changes (incompatible API changes)
- **Minor**: Backward-compatible functionality additions
- **Patch**: Backward-compatible bug fixes

### 4.2 Backward Compatibility Rules

#### 4.2.1 MUST NOT (Breaking Changes)

1. ❌ Remove a field
2. ❌ Change a field number
3. ❌ Change a field type
4. ❌ Rename a package
5. ❌ Remove or rename an enum value

#### 4.2.2 MUST (Compatibility Preservation)

1. ✅ Mark deprecated fields with `[deprecated = true]`
2. ✅ Add new optional fields only
3. ✅ Provide default values for all new fields
4. ✅ Document migration path for deprecated features

#### 4.2.3 Example: Field Deprecation

```protobuf
message NodeConfig {
  string id = 1;

  // DEPRECATED: Use capabilities_v2 instead (since v1.5.0)
  repeated Capability capabilities = 2 [deprecated = true];

  // New field with improved design (added v1.5.0)
  repeated CapabilityV2 capabilities_v2 = 3;
}
```

### 4.3 Version Migration

When creating a new major version (e.g., v1 → v2):

1. **Create new package**: `cap.node.v2`
2. **Maintain parallel support**: Keep v1 and v2 for minimum 6 months
3. **Provide migration utilities**: Code-generated converters
4. **Document breaking changes**: CHANGELOG.md with migration guide
5. **Deprecation notice**: Mark v1 as deprecated with sunset date

**Example Migration Utility**:
```rust
impl From<cap::node::v1::NodeConfig> for cap::node::v2::NodeConfig {
    fn from(v1: cap::node::v1::NodeConfig) -> Self {
        // Migration logic
    }
}
```

---

## 5. CRDT Semantics

Peat Protocol uses **Conflict-free Replicated Data Types (CRDTs)** for distributed consistency.

### 5.1 CRDT Operations by Schema

| Schema | Field | CRDT Type | Operations |
|--------|-------|-----------|------------|
| `node.v1` | `capabilities` | G-Set | Add only (monotonic) |
| `node.v1` | `position`, `health`, `phase` | LWW-Register | Last-write-wins (timestamp) |
| `node.v1` | `fuel_minutes` | PN-Counter | Increment/decrement |
| `cell.v1` | `leader_id` | LWW-Register | Last-write-wins |
| `cell.v1` | `members` | OR-Set | Add wins over remove |
| `cell.v1` | `capabilities` | G-Set | Add only (aggregated) |
| `zone.v1` | `coordinator_id` | LWW-Register | Last-write-wins |
| `zone.v1` | `cells` | OR-Set | Add wins over remove |
| `zone.v1` | `aggregated_capabilities` | G-Set | Add only |

### 5.2 Conflict Resolution Rules

#### 5.2.1 Last-Write-Wins (LWW-Register)

**Rule**: Compare `timestamp` field; highest timestamp wins.

**Example**:
```protobuf
message NodeState {
  Position position = 1;
  Timestamp timestamp = 7;  // Used for LWW resolution
}
```

**Implementation**:
```rust
pub fn merge(&mut self, other: &NodeState) {
    if other.timestamp > self.timestamp {
        self.position = other.position.clone();
        self.timestamp = other.timestamp.clone();
    }
}
```

#### 5.2.2 Observed-Remove Set (OR-Set)

**Rule**: Add operation wins over concurrent remove operation.

**Example**:
```protobuf
message CellState {
  repeated string members = 3;  // OR-Set
  Timestamp timestamp = 6;
}
```

#### 5.2.3 Grow-Only Set (G-Set)

**Rule**: Elements can only be added, never removed.

**Example**:
```protobuf
message NodeConfig {
  repeated Capability capabilities = 3;  // G-Set
}
```

---

## 6. Validation Rules

### 6.1 Required Field Validation

All implementations MUST validate:

1. **Non-empty strings**: `id`, `name`, `platform_type` fields MUST NOT be empty
2. **Range constraints**: See Section 3.2.1 for numeric ranges
3. **Enum values**: MUST be valid enum members (not UNSPECIFIED unless documented)
4. **Timestamps**: MUST be non-negative and reasonable (not far future)

### 6.2 Semantic Validation

| Validation | Rule | Error Code |
|------------|------|------------|
| Cell size | `members.len() <= config.max_size` | `CELL_FULL` |
| Cell validity | `members.len() >= config.min_size` | `CELL_INVALID` |
| Leader in members | `leader_id` MUST be in `members` | `INVALID_LEADER` |
| Confidence range | `0.0 <= confidence <= 1.0` | `INVALID_CONFIDENCE` |
| Position validity | Lat in [-90, 90], Lon in [-180, 180] | `INVALID_POSITION` |

### 6.3 Example Validation Code

```rust
pub fn validate_cell_state(state: &CellState) -> Result<(), ValidationError> {
    // Check leader is in members
    if let Some(leader_id) = &state.leader_id {
        if !state.members.contains(leader_id) {
            return Err(ValidationError::InvalidLeader);
        }
    }

    // Check size constraints
    if let Some(config) = &state.config {
        if state.members.len() > config.max_size as usize {
            return Err(ValidationError::CellFull);
        }
    }

    Ok(())
}
```

---

## 7. Change Control Process

### 7.1 Schema Change Request (SCR)

All schema changes MUST follow this process:

1. **Proposal**: Submit SCR via GitHub issue with template
2. **Review**: Schema Working Group reviews (1 week)
3. **Comment Period**: Public comment period (2 weeks for major changes)
4. **Approval**: Architecture Review Board approves
5. **Implementation**: Update `.proto` files, regenerate code
6. **Testing**: Backward compatibility tests pass
7. **Release**: Publish new version with CHANGELOG

### 7.2 SCR Template

```markdown
## Schema Change Request

**Type**: [ ] Minor (backward compatible) [ ] Major (breaking change)
**Affected Package**: cap.<package>.v<version>
**Proposed Version**: <new version>

### Motivation
Why is this change needed?

### Proposed Changes
- [ ] Add field X to message Y
- [ ] Deprecate field Z

### Backward Compatibility Impact
How does this affect existing implementations?

### Migration Path
How should users migrate from old to new version?

### Testing Plan
How will backward compatibility be verified?
```

### 7.3 Approval Authority

| Change Type | Approval Required |
|-------------|-------------------|
| Patch (bug fix) | Technical Lead |
| Minor (new optional field) | Schema Working Group |
| Major (breaking change) | Architecture Review Board + Public Comment |

---

## 8. Implementation Requirements

### 8.1 Conformance Levels

Implementations MUST support one of these conformance levels:

#### 8.1.1 Level 1: Core Schemas (REQUIRED)

- `cap.common.v1`- `cap.capability.v1`- `cap.node.v1`- `cap.beacon.v1`
#### 8.1.2 Level 2: Cell Formation (RECOMMENDED)

- Level 1 +
- `cap.cell.v1`- `cap.composition.v1`
#### 8.1.3 Level 3: Full Hierarchy (OPTIONAL)

- Level 2 +
- `cap.zone.v1`- `cap.role.v1`
### 8.2 Code Generation Requirements

All implementations MUST:

1. ✅ Use official Protocol Buffers compiler (`protoc`)
2. ✅ Generate code from `.proto` files (no manual schemas)
3. ✅ Include validation utilities
4. ✅ Support JSON encoding (for HTTP/REST APIs)
5. ✅ Support binary encoding (for gRPC/efficient transport)

### 8.3 Testing Requirements

All implementations MUST pass:

1. **Schema validation tests**: All required fields present
2.**Round-trip serialization**: `deserialize(serialize(msg)) == msg`
3.**Backward compatibility tests**: v1 messages readable by v1.x parsers
4.**Forward compatibility tests**: v1.x messages readable by v1 parsers (with defaults)

---

## 9. Security Considerations

### 9.1 Input Validation

All implementations MUST validate:

1. ✅ Message size limits (prevent DoS)
2. ✅ String length limits (prevent buffer overflows)
3. ✅ Numeric ranges (prevent invalid states)
4. ✅ Enum values (reject unknown values)

### 9.2 Sanitization

Implementations SHOULD sanitize:

1. ✅ User-provided strings (strip control characters)
2. ✅ Metadata fields (validate key-value pairs)
3. ✅ File paths (prevent directory traversal)

### 9.3 Encryption

- **At Rest**: Protobuf messages MAY be encrypted by storage backend
- **In Transit**: Protobuf messages SHOULD be encrypted via TLS/mTLS

---

## 10. Appendices

### Appendix A: Glossary

| Term | Definition |
|------|------------|
| CRDT | Conflict-free Replicated Data Type |
| ICD | Interface Control Document |
| G-Set | Grow-only Set (CRDT) |
| LWW | Last-Write-Wins (CRDT) |
| OR-Set | Observed-Remove Set (CRDT) |
| PN-Counter | Positive-Negative Counter (CRDT) |
| SCR | Schema Change Request |
| WGS84 | World Geodetic System 1984 (GPS coordinate system) |

### Appendix B: References

- **Protocol Buffers**: https://protobuf.dev/
- **SemVer 2.0**: https://semver.org/
- **RFC 4122**: UUID Specification
- **CRDT Theory**: https://crdt.tech/
- **ADR-012**: Schema Definition and Protocol Extensibility

### Appendix C: Schema Source Files

All official schema files are maintained at:

```
https://github.com/<org>/peat/tree/main/peat-schema/proto/
```

- `common.proto`
- `capability.proto`
- `node.proto`
- `cell.proto`
- `zone.proto`
- `role.proto`
- `beacon.proto`
- `composition.proto`

### Appendix D: License

This ICD and all associated schema files are released under:

**License**: Apache 2.0 (or as determined by governing foundation)

**Copyright**: © 2025 Peat Protocol Contributors

---

## Document End

**Document Number**: CAP-ICD-001
**Version**: 1.0.0
**Status**: DRAFT
**Next Review Date**: 2026-02-06 (3 months)