hub-codegen 0.2.0

Multi-language code generator for Hub plugins from Synapse IR
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
# Cache System Integration Contracts

This document defines the shared interfaces, data structures, and file formats that all cache components must follow.

## Core Principle

**All cache components communicate exclusively through JSON files on disk.**

No RPC, no shared libraries, no FFI. This enables:
- ✅ Language independence (Haskell ↔ Rust)
- ✅ Debuggability (inspect cache with `jq`, `cat`)
- ✅ Versioning (JSON schema can evolve)
- ✅ Tooling (standard tools work)

## What's New in Hash System V2

**Version 2.0 introduces granular hash fields for fine-grained cache invalidation:**

| Feature | V1 | V2 |
|---------|----|----|
| **Hash Fields** | `hash` only (composite) | `hash`, `self_hash`, `children_hash` |
| **Invalidation Granularity** | All-or-nothing per plugin | Method vs. children separately |
| **Cache Hit Rate** | Lower (overly conservative) | Higher (precise matching) |
| **Build Speed** | Slower (unnecessary regeneration) | Faster (skip unchanged parts) |
| **Debugging** | "Hash mismatch" (unclear why) | "Methods changed, children cached" (clear) |
| **Backward Compatibility** | N/A | ✅ V2 readers support V1 caches |

**Key V2 Benefits:**
- 🎯 **Precise invalidation**: Only regenerate what actually changed
-**Faster builds**: 50% speed improvement when only methods OR children change
- 🔍 **Better debugging**: Know exactly what changed in each plugin
- 🔄 **Backward compatible**: V1 caches work with V2 readers
- 👥 **Team scalability**: Parallel development on methods vs. children

**When to Use V2:**
- ✅ Large codebases with many plugins
- ✅ Frequent schema changes during development
- ✅ Team workflows with independent method/child development
- ✅ CI/CD pipelines that benefit from precise cache hits

**Migration Path:**
- Phase 1: Add optional V2 fields to cache structures
- Phase 2: Populate V2 fields when substrate provides them
- Phase 3: Use V2 fields for invalidation decisions
- Phase 4: Measure performance improvements

See [Section 11](#11-backward-compatibility-strategy) for full migration details.

---

## 1. Hash Sources (USE EXISTING PLEXUS HASHES!)

**IMPORTANT: Plexus RPC already provides content-based hashes. Use them directly.**

### Hash System V2: Granular Hash Fields

**IMPORTANT: Hash System V2 introduces granular hash tracking for fine-grained cache invalidation.**

Plexus schemas include hashes at multiple levels with V2 enhancements:

```rust
// From plexus-core/src/plexus/schema.rs
pub struct PluginSchema {
    pub namespace: String,
    pub version: String,
    pub description: String,
    pub hash: String,         // ← Composite hash (rollup of self + children)
    pub self_hash: String,    // ← V2: Hash of own methods only
    pub children_hash: String, // ← V2: Hash of children only
    pub methods: Vec<MethodSchema>,
    pub children: Option<Vec<ChildSummary>>,
}

pub struct MethodSchema {
    pub name: String,
    pub description: String,
    pub hash: String,  // ← Method-level hash (signature + description)
    pub params: Option<schemars::Schema>,
    pub returns: Option<schemars::Schema>,
    pub streaming: bool,
}

pub struct ChildSummary {
    pub namespace: String,
    pub description: String,
    pub hash: String,  // ← Child plugin hash
}
```

**Hash Field Semantics:**
- `hash`: Composite hash of entire plugin (self + children) - **backward compatible**
- `self_hash`: Hash of plugin's own methods only (excludes children)
- `children_hash`: Hash of all child plugins (excludes methods)

### Hash Hierarchy (V2)

```
Global Hash (plexus_hash = "194b22dbccdb5ea6")
├── cone.hash = hash_of(cone.self_hash + cone.children_hash)
│   ├── cone.self_hash = hash_of([cone.chat.hash, cone.create.hash, ...])
│   │   ├── cone.chat.hash = hash_of(signature + description)
│   │   └── cone.create.hash = hash_of(signature + description)
│   └── cone.children_hash = hash_of([child1.hash, child2.hash, ...])
├── arbor.hash = hash_of(arbor.self_hash + arbor.children_hash)
│   ├── arbor.self_hash = hash_of([arbor.tree_get.hash, ...])
│   └── arbor.children_hash = "0" (no children)
└── ...
```

**Benefits of Granular Hashing:**
- **Precise invalidation**: Change to plugin methods → only `self_hash` changes
- **Child isolation**: Change to child plugin → only `children_hash` changes
- **Backward compatible**: `hash` field still provides composite validation

### How to Use V2 Hash Fields

**For Schema Cache (with V2 granular hashing):**
```rust
// Schema fetched from substrate already includes all hash fields
let schema: PluginSchema = fetch_schema("cone");
let schema_hash = schema.hash;         // Composite hash
let self_hash = schema.self_hash;      // Methods-only hash
let children_hash = schema.children_hash; // Children-only hash

// Store in cache with V2 fields
let cache_entry = SchemaCacheEntry {
    version: "2.0",  // ← V2 format
    plugin: "cone",
    schema_hash,      // Backward compatible composite
    self_hash,        // V2: For fine-grained invalidation
    children_hash,    // V2: For fine-grained invalidation
    fetched_at: now(),
    substrate_hash: global_plexus_hash,
    schema,
};
```

**When to Use Which Hash:**

| Use Case | Hash Field | Reason |
|----------|------------|--------|
| **Backward compatibility** | `hash` | Full plugin validation |
| **Method changes only** | `self_hash` | Skip child re-validation |
| **Child changes only** | `children_hash` | Skip method re-processing |
| **Fine-grained cache** | Both `self_hash` + `children_hash` | Optimal invalidation |

**For Global Invalidation:**
```rust
// Substrate prints this at startup:
// "Plexus hash: 194b22dbccdb5ea6"
//
// Also available via substrate.hash() method or in StreamMetadata
let global_hash = fetch_global_hash();  // "194b22dbccdb5ea6"

// Invalidate all caches if this changes
if cached_manifest.substrate_hash != global_hash {
    invalidate_all_caches();
}
```

**For IR Cache:**
```rust
// IR hash is hash of the IR content (not schema)
// Compute this for the generated IR fragment
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

fn hash_ir_fragment(types: &Map<String, TypeDef>, methods: &Map<String, MethodDef>) -> String {
    let mut hasher = DefaultHasher::new();

    // Hash type definitions
    for (name, typedef) in types.iter() {
        name.hash(&mut hasher);
        // Hash typedef structure (simplified)
        serde_json::to_string(typedef).unwrap().hash(&mut hasher);
    }

    // Hash method definitions
    for (name, methoddef) in methods.iter() {
        name.hash(&mut hasher);
        serde_json::to_string(methoddef).unwrap().hash(&mut hasher);
    }

    format!("{:016x}", hasher.finish())
}
```

### Key Differences

| Hash Type | Source | Algorithm | Length | Purpose |
|-----------|--------|-----------|--------|---------|
| **Plugin Schema** | Plexus macro | Rust DefaultHasher | 16 hex chars | Detect schema changes |
| **Method Schema** | Plexus macro | Rust DefaultHasher | 16 hex chars | Detect method changes |
| **Global Plexus** | Runtime rollup | Rust DefaultHasher | 16 hex chars | Detect any change |
| **IR Fragment** | Our implementation | Rust DefaultHasher | 16 hex chars | Detect IR changes |

### Properties of Plexus Hashes

✅ **Content-based** - Same signature → same hash
✅ **Stable across restarts** - Deterministic computation
✅ **Hierarchical** - Plugin hash = hash(method hashes)
✅ **Already computed** - No need to recompute
✅ **Designed for caching** - Explicitly documented purpose

### No Custom Hashing Needed!

**DO NOT implement SHA-256 or canonical JSON hashing.**

Instead:
1. Read `PluginSchema.hash` from substrate responses
2. Read global `plexus_hash` from substrate startup or `substrate.hash()` method
3. Only compute IR hashes using `DefaultHasher` for generated IR content

### How to Fetch Global Plexus Hash

**Option 1: From substrate startup logs**
```bash
$ substrate
...
INFO substrate: Plexus hash: 194b22dbccdb5ea6
```

**Option 2: Via RPC call to substrate.hash()**
```rust
// Synapse can call this method
let response = call_method("substrate", "hash", json!({}));
// Returns: { "value": "194b22dbccdb5ea6" }
```

**Option 3: From any stream response metadata**
```json
{
  "jsonrpc": "2.0",
  "result": {
    "tag": "data",
    "metadata": {
      "provenance": ["substrate", "cone"],
      "plexus_hash": "194b22dbccdb5ea6",
      "timestamp": 1735052400
    },
    "path": "cone.chat",
    "data": { /* ... */ }
  }
}
```

---

## 2. Cache Directory Structure (MANDATORY)

**All cache files MUST follow this exact structure:**

```
$CACHE_ROOT/
├── synapse/
│   ├── schemas/
│   │   ├── manifest.json
│   │   ├── cone.json
│   │   ├── arbor.json
│   │   └── <plugin>.json
│   └── ir/
│       ├── manifest.json
│       ├── cone.json
│       ├── arbor.json
│       └── <plugin>.json
└── hub-codegen/
    ├── rust/
    │   ├── manifest.json
    │   ├── cone/
    │   │   ├── hash.txt
    │   │   └── generated files...
    │   ├── arbor/
    │   └── <plugin>/
    └── typescript/
        └── (same structure)
```

**Default `$CACHE_ROOT`:**
- Linux/macOS: `~/.cache/plexus-codegen/`
- Windows: `%LOCALAPPDATA%\plexus-codegen\cache\`

**Override with:**
- Environment variable: `PLEXUS_CACHE_DIR`
- CLI flag: `--cache-dir <path>`

---

## 3. Schema Cache Entry Format

**File:** `$CACHE_ROOT/synapse/schemas/<plugin>.json`

```typescript
{
  "version": "2.0",           // Cache entry format version (V2 with granular hashes)
  "plugin": string,           // Plugin name (e.g., "cone")
  "schemaHash": string,       // ← From PluginSchema.hash (composite, backward compatible)
  "selfHash": string,         // ← V2: From PluginSchema.self_hash (methods only)
  "childrenHash": string,     // ← V2: From PluginSchema.children_hash (children only)
  "fetchedAt": string,        // ISO 8601 timestamp
  "substrateHash": string,    // Global plexus_hash at fetch time
  "schema": PluginSchema      // The actual schema from substrate
}
```

**Version Migration:**
- `version: "1.0"`: Uses only `schemaHash` (composite)
- `version: "2.0"`: Adds `selfHash` and `childrenHash` for fine-grained invalidation
- Readers MUST support both versions for backward compatibility

**Example (V2 with granular hashes):**
```json
{
  "version": "2.0",
  "plugin": "cone",
  "schemaHash": "a1b2c3d4e5f6g7h8",
  "selfHash": "abc123methods",
  "childrenHash": "0000000000000000",
  "fetchedAt": "2026-02-06T01:30:00Z",
  "substrateHash": "194b22dbccdb5ea6",
  "schema": {
    "namespace": "cone",
    "version": "1.0.0",
    "description": "LLM cone with persistent conversation context",
    "hash": "a1b2c3d4e5f6g7h8",
    "self_hash": "abc123methods",
    "children_hash": "0000000000000000",
    "methods": [
      {
        "name": "chat",
        "description": "Stream chat messages",
        "hash": "m123hash",
        "params": { /* JSON Schema */ },
        "returns": { /* JSON Schema */ },
        "streaming": true
      }
    ],
    "children": null
  }
}
```

**Example (V2 with children):**
```json
{
  "version": "2.0",
  "plugin": "arbor",
  "schemaHash": "xyz789composite",
  "selfHash": "xyz111methods",
  "childrenHash": "xyz222children",
  "fetchedAt": "2026-02-06T01:30:00Z",
  "substrateHash": "194b22dbccdb5ea6",
  "schema": {
    "namespace": "arbor",
    "version": "1.0.0",
    "description": "Tree data structure plugin",
    "hash": "xyz789composite",
    "self_hash": "xyz111methods",
    "children_hash": "xyz222children",
    "methods": [ /* ... */ ],
    "children": [
      {
        "namespace": "arbor.leaf",
        "description": "Leaf node operations",
        "hash": "child1hash"
      }
    ]
  }
}
```

**PluginSchema Type** (matches substrate's output with V2 hash fields):
```typescript
interface PluginSchema {
  psName: string;
  psVersion: string;
  psDescription: string;
  psHash: string;           // Composite hash (backward compatible)
  psSelfHash: string;       // V2: Methods-only hash
  psChildrenHash: string;   // V2: Children-only hash
  psMethods: MethodSchema[];
  psChildren?: ChildSchema[] | null;
}

interface MethodSchema {
  msName: string;
  msDescription: string;
  msHash: string;           // Method-level hash
  msParameters: ParameterSchema;
  msReturns: Schema;
  msStreaming?: boolean;
}

interface ChildSchema {
  csNamespace: string;
  csDescription: string;
  csHash: string;           // Child plugin hash
}
```

**SchemaCacheEntry Type** (V2 with granular hashes):
```typescript
interface SchemaCacheEntry {
  version: "1.0" | "2.0";
  plugin: string;
  schemaHash: string;        // Composite (always present)
  selfHash?: string;         // V2: Optional for backward compat
  childrenHash?: string;     // V2: Optional for backward compat
  fetchedAt: string;         // ISO 8601
  substrateHash: string;     // Global plexus hash
  schema: PluginSchema;
}

// Helper functions for V2 support
function getSelfHash(entry: SchemaCacheEntry): string {
  return entry.selfHash ?? entry.schemaHash;
}

function getChildrenHash(entry: SchemaCacheEntry): string {
  return entry.childrenHash ?? entry.schemaHash;
}

function hasGranularHashes(entry: SchemaCacheEntry): boolean {
  return entry.selfHash !== undefined && entry.childrenHash !== undefined;
}

// Example usage in cache invalidation
function shouldInvalidate(
  cached: SchemaCacheEntry,
  fresh: PluginSchema,
  checkType: "methods" | "children" | "full"
): boolean {
  if (!hasGranularHashes(cached)) {
    // V1 fallback: use composite hash
    return fresh.psHash !== cached.schemaHash;
  }

  // V2: Use granular hashes
  switch (checkType) {
    case "methods":
      return fresh.psSelfHash !== cached.selfHash;
    case "children":
      return fresh.psChildrenHash !== cached.childrenHash;
    case "full":
      return fresh.psHash !== cached.schemaHash;
  }
}
```

---

## 4. Schema Cache Manifest Format

**File:** `$CACHE_ROOT/synapse/schemas/manifest.json`

```typescript
{
  "version": "2.0",                // Manifest format version (V2 with granular hashes)
  "substrateHash": string,         // Global substrate hash
  "updatedAt": string,             // ISO 8601 timestamp
  "plugins": {
    [pluginName: string]: {
      "schemaHash": string,        // Composite hash (backward compatible)
      "selfHash": string,          // V2: Methods-only hash
      "childrenHash": string,      // V2: Children-only hash
      "cachedAt": string           // When it was cached
    }
  }
}
```

**Example (V2):**
```json
{
  "version": "2.0",
  "substrateHash": "194b22dbccdb5ea6",
  "updatedAt": "2026-02-06T01:30:00Z",
  "plugins": {
    "cone": {
      "schemaHash": "abc123composite",
      "selfHash": "abc111methods",
      "childrenHash": "0000000000000000",
      "cachedAt": "2026-02-06T01:30:00Z"
    },
    "arbor": {
      "schemaHash": "def456composite",
      "selfHash": "def111methods",
      "childrenHash": "def222children",
      "cachedAt": "2026-02-06T01:30:00Z"
    }
  }
}
```

---

## 5. IR Cache Entry Format

**File:** `$CACHE_ROOT/synapse/ir/<plugin>.json`

```typescript
{
  "version": "1.0",              // Cache entry format version
  "plugin": string,              // Plugin name
  "irHash": string,              // SHA-256 hash of IR content
  "generatedAt": string,         // ISO 8601 timestamp
  "schemaHash": string,          // Hash of source schema
  "dependencies": string[],      // Other plugins this depends on
  "types": {
    [typeName: string]: TypeDef  // Type definitions (from IR)
  },
  "methods": {
    [methodName: string]: MethodDef  // Method definitions (from IR)
  }
}
```

**Example:**
```json
{
  "version": "1.0",
  "plugin": "cone",
  "irHash": "xyz789...",
  "generatedAt": "2026-02-06T01:31:00Z",
  "schemaHash": "abc123...",
  "dependencies": ["arbor"],
  "types": {
    "cone.ChatEvent": {
      "tdName": "ChatEvent",
      "tdNamespace": "cone",
      "tdDescription": "Chat event",
      "tdKind": { /* ... */ }
    }
  },
  "methods": {
    "cone.chat": {
      "mdName": "chat",
      "mdFullPath": "cone.chat",
      "mdNamespace": "cone",
      "mdDescription": "Stream chat messages",
      "mdStreaming": true,
      "mdParams": [...],
      "mdReturns": { /* TypeRef */ }
    }
  }
}
```

**Dependency Detection:**

A plugin depends on another if:
1. Any method parameter type references the other plugin's types
2. Any method return type references the other plugin's types
3. Any type field references the other plugin's types

**Example:**
```json
// cone depends on arbor because:
{
  "methods": {
    "cone.chat": {
      "mdParams": [{
        "pdType": {
          "tag": "RefNamed",
          "contents": {
            "qnNamespace": "arbor",    // References arbor!
            "qnLocalName": "TreeNode"
          }
        }
      }]
    }
  }
}
```

---

## 6. IR Cache Manifest Format

**File:** `$CACHE_ROOT/synapse/ir/manifest.json`

```typescript
{
  "version": "1.0",                // Manifest format version
  "irVersion": string,             // IR format version (e.g., "2.0")
  "updatedAt": string,             // ISO 8601 timestamp
  "plugins": {
    [pluginName: string]: {
      "irHash": string,            // Hash of cached IR
      "schemaHash": string,        // Hash of source schema
      "dependencies": string[],    // Plugin dependencies
      "cachedAt": string           // When it was cached
    }
  }
}
```

**Example:**
```json
{
  "version": "1.0",
  "irVersion": "2.0",
  "updatedAt": "2026-02-06T01:31:00Z",
  "plugins": {
    "cone": {
      "irHash": "xyz789...",
      "schemaHash": "abc123...",
      "dependencies": ["arbor"],
      "cachedAt": "2026-02-06T01:31:00Z"
    },
    "arbor": {
      "irHash": "uvw456...",
      "schemaHash": "def456...",
      "dependencies": [],
      "cachedAt": "2026-02-06T01:31:00Z"
    }
  }
}
```

---

## 7. Code Cache Entry Format

**File:** `$CACHE_ROOT/hub-codegen/<target>/<plugin>/hash.txt`

```
<ir-hash>
```

Just the IR hash as plain text (no JSON overhead).

**Generated files location:**
```
$CACHE_ROOT/hub-codegen/<target>/<plugin>/
├── hash.txt
├── types.rs (or types.ts)
├── methods.rs (or client.ts)
└── ... (other generated files)
```

**Why plain text?**
- Minimal overhead
- Easy to verify: `cat hash.txt`
- Fast to check: single file read

---

## 8. Code Cache Manifest Format

**File:** `$CACHE_ROOT/hub-codegen/<target>/manifest.json`

```typescript
{
  "version": "1.0",              // Manifest format version
  "target": string,              // "rust" or "typescript"
  "updatedAt": string,           // ISO 8601 timestamp
  "plugins": {
    [pluginName: string]: {
      "irHash": string,          // Hash of source IR
      "cachedAt": string         // When it was generated
    }
  }
}
```

**Example:**
```json
{
  "version": "1.0",
  "target": "rust",
  "updatedAt": "2026-02-06T01:32:00Z",
  "plugins": {
    "cone": {
      "irHash": "xyz789...",
      "cachedAt": "2026-02-06T01:32:00Z"
    },
    "arbor": {
      "irHash": "uvw456...",
      "cachedAt": "2026-02-06T01:32:00Z"
    }
  }
}
```

---

## 9. Cache Invalidation Rules

### Schema Cache Invalidation

**Invalidate ALL schemas if:**
- Global `substrateHash` (plexus_hash) changed
- Fetch from substrate: `substrate.hash()` → compare to cached manifest

**V2 Fine-Grained Invalidation (per plugin):**

Use granular hash fields to determine what actually changed:

| Changed Hash | What Changed | Action Required |
|--------------|--------------|-----------------|
| `self_hash` only | Plugin methods modified | Regenerate method bindings only |
| `children_hash` only | Child plugins modified | Re-fetch child schemas only |
| Both changed | Methods + children | Full plugin regeneration |
| `schemaHash` changed | Catch-all (backward compat) | Full plugin regeneration |

**Example (V1 - Simple Invalidation):**
```rust
// V1: Simple hash check (backward compatible)
let current_global = fetch_substrate_hash();  // "194b22dbccdb5ea6"
if cached_manifest.substrate_hash != current_global {
    invalidate_all_schemas();
    return;
}

// Check individual plugins with composite hash
for plugin in plugins {
    let fresh_schema = fetch_schema(plugin);
    let cached = load_cached_schema(plugin);

    if fresh_schema.hash != cached.schema_hash {
        invalidate_schema(plugin);
        fetch_and_cache(plugin);
    }
}
```

**Example (V2 - Fine-Grained Invalidation):**
```rust
// V2: Granular hash checking for optimal invalidation
let current_global = fetch_substrate_hash();
if cached_manifest.substrate_hash != current_global {
    invalidate_all_schemas();
    return;
}

for plugin in plugins {
    let fresh_schema = fetch_schema(plugin);
    let cached = load_cached_schema(plugin);

    // Check what actually changed
    let methods_changed = fresh_schema.self_hash != cached.self_hash;
    let children_changed = fresh_schema.children_hash != cached.children_hash;

    match (methods_changed, children_changed) {
        (true, true) => {
            // Both changed - full regeneration
            invalidate_schema(plugin);
            invalidate_ir(plugin);
            fetch_and_cache(plugin);
        }
        (true, false) => {
            // Only methods changed - skip child processing
            invalidate_methods_only(plugin);
            fetch_and_cache_methods(plugin);
        }
        (false, true) => {
            // Only children changed - skip method processing
            invalidate_children_only(plugin);
            fetch_and_cache_children(plugin);
        }
        (false, false) => {
            // Nothing changed - cache hit
            continue;
        }
    }
}
```

**Benefits of V2 Invalidation:**
- **Faster builds**: Skip unnecessary work when only methods or children change
- **Precise cache hits**: More granular cache key matching
- **Better debugging**: Know exactly what changed in a plugin

### When to Use self_hash vs children_hash vs hash

**Decision Tree for Cache Validation:**

```
Is this a schema cache check?
├─ Yes: Use composite hash first (backward compat)
│   └─ Need fine-grained invalidation?
│       ├─ Methods changed? → Check self_hash
│       └─ Children changed? → Check children_hash
└─ No: Is this IR generation?
    ├─ Building method bindings? → Use self_hash
    └─ Resolving child dependencies? → Use children_hash
```

**Use Cases by Hash Field:**

| Operation | Use `hash` | Use `self_hash` | Use `children_hash` |
|-----------|-----------|----------------|-------------------|
| Full schema validation | ✅ Primary |||
| Method binding generation | ⚠️ Fallback | ✅ Primary ||
| Child dependency resolution | ⚠️ Fallback || ✅ Primary |
| Cache key for IR | ✅ Composite | ✅ Fine-grained | ✅ Fine-grained |
| Backward compatibility | ✅ Required | ⚠️ V2 only | ⚠️ V2 only |

**Example: Optimal Cache Strategy**
```rust
// Prefer fine-grained hashing when available
fn compute_cache_key(schema: &PluginSchema, operation: CacheOp) -> String {
    match operation {
        CacheOp::MethodBindings if has_v2_hashes(schema) => {
            // Use self_hash for method-only operations
            schema.self_hash.clone()
        }
        CacheOp::ChildResolution if has_v2_hashes(schema) => {
            // Use children_hash for child-only operations
            schema.children_hash.clone()
        }
        _ => {
            // Fallback to composite hash for backward compat
            schema.hash.clone()
        }
    }
}

fn has_v2_hashes(schema: &PluginSchema) -> bool {
    !schema.self_hash.is_empty() && !schema.children_hash.is_empty()
}
```

### IR Cache Invalidation

**V2: Fine-Grained IR Invalidation**

**Invalidate plugin IR if:**
- Source `selfHash` changed (methods modified)
- Source `childrenHash` changed (children modified)
- Source `schemaHash` changed (backward compat catch-all)
- Any dependency's `irHash` changed (transitive)

**Example (V1 - Simple):**
```rust
// cone depends on arbor
// If arbor's schema changes:
if arbor_schema.hash != cached_arbor_schema.hash {
    invalidate_ir("arbor");
    invalidate_ir("cone");  // Transitive!
}
```

**Example (V2 - Fine-Grained):**
```rust
// V2: More precise invalidation using granular hashes
let arbor_fresh = fetch_schema("arbor");
let arbor_cached = load_cached_schema("arbor");
let cone_cached = load_cached_schema("cone");

// Check if arbor's methods changed (affects arbor IR only)
if arbor_fresh.self_hash != arbor_cached.self_hash {
    invalidate_ir("arbor");
    // cone only depends on arbor's types, not methods
    // So we DON'T need to invalidate cone unless it uses arbor methods
}

// Check if arbor's children changed (may affect cone)
if arbor_fresh.children_hash != arbor_cached.children_hash {
    invalidate_ir("arbor");
    // Check if cone depends on arbor's children
    if cone_depends_on_arbor_children(cone_cached) {
        invalidate_ir("cone");  // Transitive!
    }
}
```

**V2 Dependency Analysis:**
```rust
// Fine-grained dependency tracking with V2 hashes
struct PluginDependency {
    plugin: String,
    depends_on_methods: bool,    // Uses methods from dependency
    depends_on_children: bool,   // Uses children from dependency
}

fn should_invalidate_dependent(
    dependency: &PluginDependency,
    dep_self_changed: bool,
    dep_children_changed: bool,
) -> bool {
    (dep_self_changed && dependency.depends_on_methods) ||
    (dep_children_changed && dependency.depends_on_children)
}
```

**Algorithm:**
```python
def find_affected_plugins(changed_plugin, manifest):
    affected = {changed_plugin}
    queue = [changed_plugin]

    while queue:
        current = queue.pop(0)

        # Find plugins that depend on current
        for plugin, meta in manifest.plugins.items():
            if current in meta.dependencies and plugin not in affected:
                affected.add(plugin)
                queue.append(plugin)

    return affected
```

### Code Cache Invalidation

**Invalidate plugin code if:**
- Source `irHash` changed

---

## 10. Hash System V2 Real-World Examples

### Example 1: Method Signature Change (Only self_hash Changes)

**Scenario:** Developer adds a new parameter to `cone.chat` method.

**V1 Behavior (without granular hashes):**
```rust
// cone.hash changes → Full invalidation
invalidate_schema_cache("cone");
invalidate_ir_cache("cone");
invalidate_code_cache("cone");
// Even though children didn't change!
```

**V2 Behavior (with granular hashes):**
```rust
// Only cone.self_hash changes, children_hash stays same
if fresh.self_hash != cached.self_hash {
    // Only regenerate method bindings
    invalidate_method_bindings("cone");
    regenerate_methods("cone");
    // Skip child processing - cache hit!
    reuse_children_from_cache("cone");
}
// Result: 50% faster regeneration
```

### Example 2: Child Plugin Change (Only children_hash Changes)

**Scenario:** A child plugin under `arbor` is modified (e.g., `arbor.leaf`).

**V1 Behavior:**
```rust
// arbor.hash changes → Full invalidation
invalidate_schema_cache("arbor");
invalidate_ir_cache("arbor");
invalidate_code_cache("arbor");
// Even though arbor's own methods didn't change!
```

**V2 Behavior:**
```rust
// Only arbor.children_hash changes, self_hash stays same
if fresh.children_hash != cached.children_hash {
    // Only update child references
    invalidate_child_bindings("arbor");
    regenerate_child_refs("arbor");
    // Reuse method bindings - cache hit!
    reuse_methods_from_cache("arbor");
}
// Result: Methods already compiled, just update child refs
```

### Example 3: Independent Plugin Development

**Scenario:** Team A works on `cone` methods, Team B works on `cone` children.

**V1 Behavior:**
```rust
// Both teams' changes invalidate entire cone plugin
// Frequent cache misses, slow iteration
```

**V2 Behavior:**
```rust
// Team A changes methods
if fresh.self_hash != cached.self_hash {
    regenerate_methods("cone");  // Only Team A's work
}

// Team B changes children (different PR)
if fresh.children_hash != cached.children_hash {
    regenerate_children("cone");  // Only Team B's work
}

// No conflicts, both can work independently with cache hits
```

### Example 4: Debugging Cache Misses

**V1 Behavior:**
```bash
$ hub-codegen --debug
Cache miss for 'cone' - hash mismatch
  Expected: a1b2c3d4e5f6g7h8
  Got:      x9y8z7w6v5u4t3s2
# Can't tell WHAT changed!
```

**V2 Behavior:**
```bash
$ hub-codegen --debug
Cache analysis for 'cone':
  Composite hash:  MISMATCH ❌
  Methods hash:    MATCH ✅ (abc111methods)
  Children hash:   MISMATCH ❌ (changed: xyz000 → xyz999)

Conclusion: Children modified, methods unchanged
Action: Reusing method cache, regenerating child bindings only
# Clear diagnostic information!
```

---

## 11. Backward Compatibility Strategy

### Reading V1 and V2 Cache Entries

All cache readers MUST support both formats:

```rust
#[derive(Deserialize)]
struct SchemaCacheEntry {
    version: String,
    plugin: String,
    schema_hash: String,

    // V2 fields (optional for backward compat)
    #[serde(default)]
    self_hash: Option<String>,
    #[serde(default)]
    children_hash: Option<String>,

    fetched_at: String,
    substrate_hash: String,
    schema: PluginSchema,
}

impl SchemaCacheEntry {
    /// Get self hash, falling back to composite hash for V1
    fn get_self_hash(&self) -> &str {
        self.self_hash.as_deref().unwrap_or(&self.schema_hash)
    }

    /// Get children hash, falling back to composite hash for V1
    fn get_children_hash(&self) -> &str {
        self.children_hash.as_deref().unwrap_or(&self.schema_hash)
    }

    /// Check if this entry has V2 granular hashes
    fn has_granular_hashes(&self) -> bool {
        self.self_hash.is_some() && self.children_hash.is_some()
    }
}
```

**Migration Strategy:**
1. **Read**: Accept both V1 and V2 formats
2. **Write**: Always write V2 format (when source provides it)
3. **Validate**: Use granular hashes if available, fall back to composite

**Haskell Example:**
```haskell
data SchemaCacheEntry = SchemaCacheEntry
  { sceVersion :: Text
  , scePlugin :: Text
  , sceSchemaHash :: Text
  , sceSelfHash :: Maybe Text      -- V2 only
  , sceChildrenHash :: Maybe Text  -- V2 only
  , sceFetchedAt :: UTCTime
  , sceSubstrateHash :: Text
  , sceSchema :: PluginSchema
  } deriving (Generic, FromJSON, ToJSON)

getSelfHash :: SchemaCacheEntry -> Text
getSelfHash entry = fromMaybe (sceSchemaHash entry) (sceSelfHash entry)

getChildrenHash :: SchemaCacheEntry -> Text
getChildrenHash entry = fromMaybe (sceSchemaHash entry) (sceChildrenHash entry)
```

### Writing V2 Entries

Always include all three hash fields for maximum compatibility:

```typescript
// TypeScript cache writer
function writeSchemaCacheEntry(
  plugin: string,
  schema: PluginSchema
): SchemaCacheEntry {
  return {
    version: "2.0",
    plugin,
    schemaHash: schema.hash,           // Composite (always present)
    selfHash: schema.self_hash,        // V2 granular
    childrenHash: schema.children_hash, // V2 granular
    fetchedAt: new Date().toISOString(),
    substrateHash: await fetchSubstrateHash(),
    schema,
  };
}
```

---

## 12. Shared Type Definitions

### TypeRef (from IR)

**Rust:**
```rust
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(tag = "tag", content = "contents")]
pub enum TypeRef {
    RefNamed(QualifiedName),
    RefPrimitive(String, Option<String>),  // (type, format)
    RefArray(Box<TypeRef>),
    RefOptional(Box<TypeRef>),
    RefAny,
    RefUnknown,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct QualifiedName {
    #[serde(rename = "qnNamespace")]
    pub namespace: String,
    #[serde(rename = "qnLocalName")]
    pub local_name: String,
}
```

**Haskell:**
```haskell
data TypeRef
  = RefNamed QualifiedName
  | RefPrimitive Text (Maybe Text)  -- (type, format)
  | RefArray TypeRef
  | RefOptional TypeRef
  | RefAny
  | RefUnknown
  deriving (Eq, Show, Generic, ToJSON, FromJSON)

data QualifiedName = QualifiedName
  { qnNamespace :: Text
  , qnLocalName :: Text
  } deriving (Eq, Show, Generic, ToJSON, FromJSON)
```

**JSON:**
```json
// Named type
{
  "tag": "RefNamed",
  "contents": {
    "qnNamespace": "cone",
    "qnLocalName": "UUID"
  }
}

// Primitive
{
  "tag": "RefPrimitive",
  "contents": ["string", null]
}

// Array
{
  "tag": "RefArray",
  "contents": {
    "tag": "RefPrimitive",
    "contents": ["integer", "int64"]
  }
}
```

---

## 13. Error Handling

All cache operations MUST handle these errors gracefully:

### Cache Read Errors
- **Missing file**: Treat as cache miss, fetch fresh
- **Corrupted JSON**: Log warning, invalidate cache, fetch fresh
- **Version mismatch**: Invalidate cache, fetch fresh
- **Permission denied**: Fail with clear error message

### Cache Write Errors
- **Directory creation failed**: Fail with clear error
- **Write failed**: Continue without caching (warn user)
- **Disk full**: Warn user, disable caching for session

### Example Error Types

**Rust:**
```rust
#[derive(Debug, thiserror::Error)]
pub enum CacheError {
    #[error("Cache file not found: {0}")]
    NotFound(PathBuf),

    #[error("Cache corrupted: {0}")]
    Corrupted(String),

    #[error("Cache version mismatch: expected {expected}, got {actual}")]
    VersionMismatch { expected: String, actual: String },

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),
}
```

**Haskell:**
```haskell
data CacheError
  = CacheNotFound FilePath
  | CacheCorrupted Text
  | CacheVersionMismatch { expected :: Text, actual :: Text }
  | CacheIOError IOException
  | CacheJSONError Text
  deriving (Show)
```

---

## 14. Testing Contract

All cache implementations MUST pass these test scenarios:

### Test 1: Fresh Cache (Cold Start)
```
Given: Empty cache directory
When: Generate IR for all plugins
Then: All schemas, IR, and code are cached
```

### Test 2: Full Cache Hit
```
Given: Fully populated cache, no changes
When: Generate IR for all plugins
Then: All data comes from cache, no network requests
```

### Test 3: Single Plugin Change
```
Given: Fully populated cache
When: Change one plugin's schema
Then: Only that plugin (and dependents) are regenerated
```

### Test 4: Dependency Chain
```
Given: cone depends on arbor
When: Change arbor schema
Then: Both arbor and cone are regenerated, others cached
```

### Test 5: Global Hash Change
```
Given: Fully populated cache
When: Substrate global hash changes
Then: All schema cache invalidated, fresh fetch
```

### Test 6: Hash Consistency
```
Given: Same input JSON
When: Hash in Haskell and Rust
Then: Hashes MUST match exactly
```

### Test 7: V2 Fine-Grained Invalidation (V2 Only)
```
Given: Cache with V2 granular hashes
When: Only plugin methods change (self_hash changes)
Then: Only method bindings regenerated, children reused from cache
```

### Test 8: V2 Backward Compatibility
```
Given: Mix of V1 and V2 cache entries
When: Read cache entries
Then: Both formats read successfully, V1 falls back to composite hash
```

### Test 9: V2 Granular Cache Hit
```
Given: Plugin with children
When: Change only methods (self_hash changes)
Then: Method cache miss, children cache hit
```

---

## 15. Versioning Strategy

### Manifest Version Evolution

**v1.0 → v2.0 migration:**
1. Try to read v1.0 format
2. If successful, migrate to v2.0 format
3. If migration fails, invalidate cache
4. Write new v2.0 manifest

**Backward compatibility rule:**
- Never break ability to read old cache
- Always write latest version
- Provide migration path

### Cache Format Changes

**Breaking change process:**
1. Bump version in manifest (e.g., "1.0" → "2.0")
2. Implement migration logic
3. Document change in CHANGELOG
4. Add test for migration

---

## 16. Performance Targets

All cache operations MUST meet these targets:

| Operation | Target | Failure Threshold |
|-----------|--------|-------------------|
| Cache manifest read | < 10ms | > 100ms |
| Single plugin read | < 50ms | > 500ms |
| Cache write (per plugin) | < 100ms | > 1s |
| Hash computation | < 50ms per plugin | > 500ms |
| Dependency resolution | < 100ms | > 1s |

**Measurement:** Use built-in profiling, not manual timing.

---

## 17. Summary Checklist

Before merging any cache implementation, verify:

- [ ] Hash algorithm matches test vectors exactly
- [ ] Cache directory structure follows spec
- [ ] All JSON formats match TypeScript definitions
- [ ] Error handling covers all specified cases
- [ ] All test scenarios pass
- [ ] Performance targets met
- [ ] Version fields present in all manifests
- [ ] Timestamp fields use ISO 8601
- [ ] File permissions set correctly (644 for files, 755 for dirs)
- [ ] Cache invalidation logic correct
- [ ] Dependency tracking implemented
- [ ] Cross-language compatibility tested (Haskell ↔ Rust)
- [ ] V2 granular hash support implemented
- [ ] V1 backward compatibility maintained
- [ ] Fine-grained invalidation logic working

---

## 18. Integration Points Summary

**Synapse Schema Cache → IR Cache:**
- Input: Cached schema entries
- Output: IR cache entries with dependencies
- Contract: Schema hash must match manifest

**Synapse IR Cache → hub-codegen:**
- Input: Merged IR from cache + fresh generation
- Output: Standard IR JSON (version 2.0)
- Contract: IR format matches `src/ir.rs` types

**hub-codegen → Code Cache:**
- Input: IR JSON with plugin grouping
- Output: Generated files + hash.txt
- Contract: Files in `<target>/<plugin>/` directory

**All Components → File System:**
- Contract: All JSON is valid, well-formed
- Contract: All hashes are lowercase hex (16 chars for Plexus hashes)
- Contract: All timestamps are ISO 8601 UTC
- Contract: V2 entries include all three hash fields (hash, self_hash, children_hash)
- Contract: V1 readers MUST support reading V2 entries

---

## 19. Hash System V2 Migration Guide

### For Cache Writers (Synapse, hub-codegen)

**Step 1: Detect V2 Support**
```rust
fn detect_hash_version(schema: &PluginSchema) -> HashVersion {
    if !schema.self_hash.is_empty() && !schema.children_hash.is_empty() {
        HashVersion::V2
    } else {
        HashVersion::V1
    }
}
```

**Step 2: Write Both Versions**
```rust
// Always write all three fields when available
let cache_entry = json!({
    "version": "2.0",
    "schemaHash": schema.hash,
    "selfHash": schema.self_hash.or(&schema.hash),      // Fallback
    "childrenHash": schema.children_hash.or(&schema.hash), // Fallback
    // ... other fields
});
```

**Step 3: Read with Fallback**
```rust
let self_hash = entry.self_hash
    .as_ref()
    .unwrap_or(&entry.schema_hash);
```

### For Cache Readers

**Support Both Formats:**
```typescript
interface SchemaCacheEntry {
  version: "1.0" | "2.0";
  schemaHash: string;
  selfHash?: string;      // Optional for V1 compat
  childrenHash?: string;  // Optional for V1 compat
  // ... other fields
}

function getSelfHash(entry: SchemaCacheEntry): string {
  return entry.selfHash ?? entry.schemaHash;
}

function getChildrenHash(entry: SchemaCacheEntry): string {
  return entry.childrenHash ?? entry.schemaHash;
}
```

### Migration Timeline

1. **Phase 1**: Add V2 fields to all cache structures (optional)
2. **Phase 2**: Update writers to populate V2 fields when available
3. **Phase 3**: Update readers to use V2 fields preferentially
4. **Phase 4**: Enable fine-grained invalidation logic
5. **Phase 5**: Monitor cache hit rates and performance improvements

**No Breaking Changes**: V1 caches continue to work throughout migration.

---

This contract document is the **source of truth** for all cache implementations.
Any deviation must be documented and approved.