oxios 1.7.1

Oxios Agent OS — Agent Operating System powered by oxi-sdk
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
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
# Oxios Architecture Reference

> **Version:** 0.4.0 · **Stack:** Rust 2021, tokio, serde (JSON+TOML), oxi-sdk · **License:** MIT

This document is a standalone reference for every subsystem in the Oxios Agent OS.
Read it before modifying kernel structure, adding modules, or onboarding onto the project.

---

## Table of Contents

1. [Overview]#1-overview
2. [Layer Architecture]#2-layer-architecture
3. [Kernel Subsystems]#3-kernel-subsystems
4. [KernelHandle Facade]#4-kernelhandle-facade
5. [Data Flow]#5-data-flow
6. [Dependency Graph]#6-dependency-graph
7. [Security Model]#7-security-model
8. [Unix Philosophy Mapping]#8-unix-philosophy-mapping
9. [Dependency Rules]#9-dependency-rules
10. [Kernel Crate Architecture]#10-kernel-crate-architecture

---

## 1. Overview

### What is Oxios?

Oxios is an **Agent Operating System** — an OS where AI agents execute real work on behalf of users. Agents fork, exec, wait, and kill just like Unix processes. The user talks, the OS handles the rest. Users never see how many agents are running.

### Design Philosophy

Oxios is built on two foundational metaphors:

| Metaphor | Realization |
|----------|-------------|
| **Unix** | Every component does one thing. Compose small pieces. Fork/exec/wait/kill for agents. Pipes for events. No containers — direct host execution. |
| **Ouroboros** | Never execute without a spec. The protocol cycles: Interview → Seed → Execute → Evaluate → Evolve. Seeds can evolve up to 3 iterations. |

### Key Principles

| Principle | Meaning |
|-----------|---------|
| **Ouroboros-first** | Every task goes through the full spec-generate-execute-evaluate-evolve lifecycle |
| **No reimplementation** | Reuse `oxi-sdk` (crates.io). Never reimplement what oxi already provides |
| **Channel agnostic** | Gateway doesn't care where messages come from (Web, CLI, Telegram) |
| **User invisible** | Users don't know how many agents are running |
| **Least privilege** | Agents start with minimal permissions, must be explicitly granted more |
| **Tamper-evident** | Every security-relevant action is recorded in a cryptographically-chained audit trail |

---

## 2. Layer Architecture

```
┌─────────────────────────────────────────────────────────────────────────┐
│                         CHANNELS (User-facing)                         │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌───────────┐              │
│  │   Web     │  │   CLI    │  │ Telegram │  │  (more)   │              │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └─────┬─────┘              │
│       │              │              │              │                    │
├───────┴──────────────┴──────────────┴──────────────┴────────────────────┤
│                         GATEWAY (oxios-gateway)                         │
│              Channel-agnostic message hub. Routes user messages         │
│              from any channel to the Orchestrator.                      │
│       ┌──────────────────┴───────────────────┐                         │
├───────┴──────────────────────────────────────┴─────────────────────────┤
│                         KERNEL (oxios-kernel)                           │
│  ┌──────────────────────────────────────────────────────────────────┐   │
│  │                    Orchestrator ("The Brain")                    │   │
│  │  Runs Ouroboros protocol end-to-end: Interview → Seed → Exec →  │   │
│  │  Evaluate → Evolve. Manages multi-agent delegation via A2A.     │   │
│  └───────────────────┬──────────────────────────────────────────────┘   │
│                      │                                                  │
│  ┌───────────────────┴──────────────────────────────────────────────┐   │
│  │                 Supervisor ("The Init")                          │   │
│  │  Agent lifecycle: fork / exec / wait / kill. Manages agent       │   │
│  │  task handles, cooperative cancellation, status tracking.        │   │
│  └───────────────────┬──────────────────────────────────────────────┘   │
│                      │                                                  │
│  ┌───────────┐  ┌────┴────┐  ┌──────────┐  ┌─────────────┐            │
│  │ Scheduler │  │Runtime  │  │EventBus  │  │ StateStore  │            │
│  └───────────┘  └─────────┘  └──────────┘  └─────────────┘            │
│  ┌────────────┐ ┌──────────┐ ┌──────────┐  ┌───────────────┐          │
│  │AccessMgr   │ │AuditTrail│ │BudgetMgr │  │ResourceMon    │          │
│  └────────────┘ └──────────┘ └──────────┘  └───────────────┘          │
│  ┌────────────┐ ┌──────────┐ ┌──────────┐  ┌───────────────┐          │
│  │MemoryMgr   │ │SpaceMgr  │ │McpBridge │  │GitLayer       │          │
│  └────────────┘ └──────────┘ └──────────┘  └───────────────┘          │
│  ┌────────────┐ ┌──────────┐ ┌──────────┐  ┌───────────────┐          │
│  │PersonaMgr  │ │SkillMgr  │ │CronScheduler        │   │
│  └────────────┘ └──────────┘ └────────────────────┘   │
│  ┌────────────┐ ┌──────────┐ ┌────────────────────────────┐           │
│  │AuthManager │ │CircuitBkr│ │A2AProtocol + CardRegistry  │           │
│  └────────────┘ └──────────┘ └────────────────────────────┘           │
│                                                                        │
│  ┌──────────────────────────────────────────────────────────────────┐   │
│  │                  KernelHandle (Facade / Syscall Table)           │   │
│  │  13 typed APIs: State · Agent · Security · Persona · Extension  │   │
│  │  MCP · Infra · Space · Exec · Browser · A2A · Knowledge          │   │
│  └──────────────────────────────────────────────────────────────────┘   │
└────────────────────────────────────────────────────────────────────────┘
├──────┴─────────────────────────────────────────────────────────────────┤
│                         RUNTIME (oxios-ouroboros)                       │
│  Spec-first protocol engine. Interview → Seed generation → Execution   │
│  result → Evaluation scoring → Evolution of failing seeds.             │
│  Defines Seed, Phase, ExecutionResult, EvaluationResult types.         │
└────────────────────────────────────────────────────────────────────────┘
├──────┴─────────────────────────────────────────────────────────────────┤
│                         ENGINE (oxi-sdk / oxi-ai)                       │
│  Thin wrapper around oxi_sdk::Oxi. Provider/model resolution via       │
│  OxiBuilder. Uses oxi-ai for provider construction (Anthropic,         │
│  OpenAI, etc.). AgentLoop provides multi-turn tool-calling loop.       │
└────────────────────────────────────────────────────────────────────────┘
```

### Layer Summary

```
  Channel (Web / CLI / Telegram)
  Gateway ─── routes messages, channel-agnostic
  Kernel ─── Orchestrator + Supervisor + all subsystems
        ├── KernelHandle ─── typed facade (11 APIs)
        │       │
        │       └── AgentRuntime ─── wraps oxi-sdk AgentLoop
        ├── Ouroboros ─── spec-first protocol engine
        └── Engine (oxi-sdk) ─── LLM provider abstraction
```

---

## 3. Kernel Subsystems

### 3.1 Supervisor — Agent Process Management

The Supervisor is the "init" of Oxios. It manages agent lifecycles using Unix-like primitives.

```
                    ┌─────────────────────┐
                    │     Supervisor      │
                    │  (dyn trait: Send+Sync) │
                    └──────┬──────────────┘
          ┌────────────────┼────────────────┐
          │                │                │
          ▼                ▼                ▼
    ┌──────────┐    ┌──────────┐    ┌──────────┐
    │  fork()  │    │  exec()  │    │  kill()  │
    │ Create   │    │ Start    │    │ Cancel + │
    │ AgentId  │    │ running  │    │ abort    │
    └──────────┘    └──────────┘    └──────────┘
          │                │                │
          ▼                ▼                ▼
    ┌──────────────────────────────────────────┐
    │          AgentStatus Enum                │
    │  Starting → Running → Idle | Failed      │
    │                  → Stopped               │
    └──────────────────────────────────────────┘

    fork(spec: Seed)          → AgentId
    exec(id: AgentId)         → ()
    run_with_seed(id, seed)   → ExecutionResult
    wait(id: AgentId)         → AgentStatus
    kill(id: AgentId)         → ()
    list()                    → Vec<AgentInfo>
```

**Implementation (`BasicSupervisor`):**
- Maintains `HashMap<AgentId, AgentInfo>` for agent metadata
- Spawns each execution as a `tokio::task::JoinHandle` with cooperative cancellation via `AtomicBool`
- Kill sets the cancellation flag and aborts the tokio task
- Emits `AgentCreated`, `AgentStarted`, `AgentStopped`, `AgentFailed` events on the EventBus
- `NoOpSupervisor` placeholder breaks the `KernelHandle → AgentRuntime → Supervisor` circular dependency during build

**Source:** `crates/oxios-kernel/src/supervisor.rs`

---

### 3.2 Orchestrator — The Brain

The Orchestrator coordinates the full Ouroboros lifecycle for user messages. It is the top-level coordinator that does NOT know about channels or HTTP.

```
  User Message
  ┌────────────────────────────────────────────────────────┐
  │                    Orchestrator                         │
  │                                                        │
  │  ┌──────────────────────────────────────────────────┐  │
  │  │  1. Space Detection (3-layer)                    │  │
  │  │     Path → Keyword → Topic classification        │  │
  │  └──────────────────────────────────────────────────┘  │
  │  ┌──────────────────────────────────────────────────┐  │
  │  │  2. Chat Bypass                                  │  │
  │  │     Simple messages get direct LLM response       │  │
  │  └──────────────────────────────────────────────────┘  │
  │  ┌──────────────────────────────────────────────────┐  │
  │  │  3. Interview Phase                              │  │
  │  │     Clarify ambiguity → Q&A accumulation          │  │
  │  │     If ambiguity > 0.2: return questions          │  │
  │  └──────────────────────────────────────────────────┘  │
  │  ┌──────────────────────────────────────────────────┐  │
  │  │  4. Seed Generation                              │  │
  │  │     Create spec with goal, constraints, criteria  │  │
  │  └──────────────────────────────────────────────────┘  │
  │  ┌──────────────────────────────────────────────────┐  │
  │  │  5. Multi-Agent Split (if ≥3 acceptance criteria) │  │
  │  │     Split → delegate via A2A or lifecycle         │  │
  │  └──────────────────────────────────────────────────┘  │
  │  ┌──────────────────────────────────────────────────┐  │
  │  │  6. Execute Phase                               │  │
  │  │     spawn_and_run via AgentLifecycleManager       │  │
  │  └──────────────────────────────────────────────────┘  │
  │  ┌──────────────────────────────────────────────────┐  │
  │  │  7. Evaluate Phase                              │  │
  │  │     Score result against acceptance criteria      │  │
  │  └──────────────────────────────────────────────────┘  │
  │  ┌──────────────────────────────────────────────────┐  │
  │  │  8. Evolve Loop (max 3 iterations)              │  │
  │  │     If score < 0.8: evolve seed → re-execute     │  │
  │  └──────────────────────────────────────────────────┘  │
  └────────────────────────────────────────────────────────┘
  OrchestrationResult { response, session_id, seed_id,
                        phase_reached, evaluation_passed, space_id }
```

**Multi-Agent Delegation:**
- When a seed has 3+ acceptance criteria, each becomes a subtask
- Subtasks run in parallel via `JoinSet`
- A2A protocol used when available (queries `AgentCardRegistry` for capable agents)
- Falls back to direct lifecycle execution without A2A

**Source:** `crates/oxios-kernel/src/orchestrator.rs`

---

### 3.3 AgentLifecycleManager — Full Orchestrated Lifecycle

Extracted from the Orchestrator to reduce scope. Handles the complete lifecycle of a single agent from fork to cleanup.

```
  Seed + Priority
  ┌─────────────────────────────────────────────────┐
  │          AgentLifecycleManager                   │
  │                                                  │
  │  1. fork()           → AgentId                   │
  │  2. register A2A     → AgentCard                 │
  │  3. deliver pending   → A2A messages             │
  │  4. ensure perms      → AccessManager            │
  │  5. submit+start task → Scheduler                │
  │  6. run_with_seed     → Supervisor → AgentRuntime│
  │  7. cleanup           → unregister A2A, complete │
  │                                                  │
  │  Timeout: max_execution_time_secs (configurable) │
  │  Zombie reaping via scheduler.reap_zombies()     │
  └─────────────────────────────────────────────────┘
  ExecutionResult { output, steps_completed, success }
```

**Key behaviors:**
- Wraps execution in `tokio::time::timeout` when `max_execution_time_secs > 0`
- Infers A2A capabilities from seed goal (e.g., "review" → "code-review")
- Always cleans up (A2A unregister + scheduler complete/fail) even on failure

**Source:** `crates/oxios-kernel/src/agent_lifecycle.rs`

---

### 3.4 AgentRuntime — Tool-Calling Loop

Wraps `oxi_sdk::AgentLoop` for executing Seeds through the multi-turn LLM tool-calling loop.

```
  ┌──────────────────────────────────────────────────────┐
  │                    AgentRuntime                       │
  │                                                      │
  │  execute(agent_id, seed) → ExecutionResult           │
  │                                                      │
  │  ┌──────────────┐  ┌──────────────┐  ┌────────────┐ │
  │  │ Persona Mgr  │  │Tool Retriever│  │Memory Mgr  │ │
  │  │ (system      │  │(semantic     │  │(recall +   │ │
  │  │  prompt)     │  │ capability)  │  │ blend)     │ │
  │  └──────┬───────┘  └──────┬───────┘  └─────┬──────┘ │
  │         │                 │                │         │
  │         ▼                 ▼                ▼         │
  │  ┌──────────────────────────────────────────────────┐│
  │  │          System Prompt Assembly                  ││
  │  │  Goal + Constraints + Criteria + Persona +       ││
  │  │  Capability Index (XML) + Kernel Manifest +      ││
  │  │  Recalled Memories                               ││
  │  └──────────────────────┬───────────────────────────┘│
  │                         │                             │
  │  ┌──────────────────────┴───────────────────────────┐│
  │  │         CSpace Resolution                        ││
  │  │  persona role → seed hint → default "worker"     ││
  │  └──────────────────────┬───────────────────────────┘│
  │                         │                             │
  │  ┌──────────────────────┴───────────────────────────┐│
  │  │    Tool Registration (from CSpace)               ││
  │  │  Tier 1: Always-on (read, write, edit, grep,     ││
  │  │          find, ls, web_search)                    ││
  │  │  Tier 2: CSpace-driven (exec, memory, space,     ││
  │  │          agent, a2a, persona, cron, security,    ││
  │  │          budget, resource)                        ││
  │  │  Tier 3: Skill tools + MCP tools                  ││
  │  └──────────────────────┬───────────────────────────┘│
  │                         │                             │
  │  ┌──────────────────────┴───────────────────────────┐│
  │  │         oxi_sdk::AgentLoop::run()                ││
  │  │  Multi-turn LLM tool-calling loop                ││
  │  │  Callbacks: ToolEnd, AgentEnd, Error, Compaction ││
  │  │  Runs inside spawn_blocking (AgentLoop !Send)    ││
  │  └──────────────────────────────────────────────────┘│
  └──────────────────────────────────────────────────────┘
```

**Circuit Breaker:** Global `CircuitBreaker` protects against cascading LLM provider failures.
Records success/failure after each agent execution.

**Source:** `crates/oxios-kernel/src/agent_runtime.rs`

---

### 3.5 Scheduler — Priority Task Queue

AIOS/AgentRM-inspired priority-based task queue.

```
  ┌───────────────────────────────────────────────────┐
  │                 AgentScheduler                     │
  │                                                   │
  │  ┌─────────────────────────────────────────────┐  │
  │  │            Priority Queue                    │  │
  │  │  BinaryHeap<ScheduledTask>                   │  │
  │  │                                              │  │
  │  │  Critical (3) > High (2) > Normal (1) > Low │  │
  │  │  Within same priority: newest first (LIFO)  │  │
  │  └─────────────────────────────────────────────┘  │
  │                                                   │
  │  ┌──────────────┐  ┌──────────────────────────┐   │
  │  │Rate Limiter  │  │  Max Concurrent Enforcer │   │
  │  │requests/min  │  │  (default: 5)            │   │
  │  └──────────────┘  └──────────────────────────┘   │
  │                                                   │
  │  ┌──────────────────────────────────────────────┐ │
  │  │  Zombie Detection                            │ │
  │  │  Tasks running > zombie_timeout_secs → reaped│ │
  │  │  default: 300s                               │ │
  │  └──────────────────────────────────────────────┘ │
  │                                                   │
  │  ┌──────────────────────────────────────────────┐ │
  │  │  Budget Manager Integration                  │ │
  │  │  Checks can_schedule() before starting task  │ │
  │  │  Skips tasks for exhausted agents            │ │
  │  └──────────────────────────────────────────────┘ │
  └───────────────────────────────────────────────────┘

  Task lifecycle:
  Queued → Running → Completed | Failed | Cancelled
```

**Source:** `crates/oxios-kernel/src/scheduler.rs`

---

### 3.6 StateStore — File-Based Persistence

JSON file storage for all kernel state.

```
  ┌──────────────────────────────────────────────┐
  │              StateStore                       │
  │                                              │
  │  Base path: ~/.oxios/workspace/              │
  │  ├── seeds/{id}.json          Seed specs     │
  │  ├── evals/{id}-eval.json     Evaluations    │
  │  ├── memory/{type}/{id}.json  Memories       │
  │  ├── audit/trail.json         Audit entries  │
  │  ├── agent_groups/{id}.json   Group state    │
  │  └── {category}/{name}.json   Arbitrary data │
  │                                              │
  │  Operations:                                  │
  │  save_json(category, name, T)                 │
  │  load_json(category, name) → Option<T>        │
  │  save_markdown(category, name, content)       │
  │  delete(category, name) → bool                │
  │  save_audit_entries(entries)                  │
  │  load_audit_entries() → Vec<AuditEntry>       │
  └──────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/state_store.rs`

---

### 3.7 EventBus — Broadcast Pipe

The "pipe" of Oxios. All agents and subsystems communicate through kernel events on the bus.

```
  ┌──────────────────────────────────────────────────────┐
  │                      EventBus                        │
  │            tokio::sync::broadcast channel             │
  │                                                      │
  │  Publishers:                                         │
  │  ┌────────────┐ ┌────────────┐ ┌─────────────────┐  │
  │  │ Supervisor │ │Orchestrator│ │ AgentLifecycle   │  │
  │  └─────┬──────┘ └─────┬──────┘ └────────┬────────┘  │
  │        │              │                  │            │
  │        └──────────────┼──────────────────┘            │
  │                       ▼                               │
  │              ┌────────────────┐                       │
  │              │  broadcast::   │                       │
  │              │    Sender      │                       │
  │              └───────┬────────┘                       │
  │                      │                                │
  │       ┌──────────────┼──────────────┐                 │
  │       ▼              ▼              ▼                 │
  │  ┌─────────┐  ┌───────────┐  ┌──────────────┐       │
  │  │Subscriber│  │Subscriber │  │AuditTrail    │       │
  │  │(monitor) │  │(channel)  │  │(auto-attach) │       │
  │  └─────────┘  └───────────┘  └──────────────┘       │
  └──────────────────────────────────────────────────────┘

  KernelEvent variants:
  AgentCreated · AgentStarted · AgentStopped · AgentFailed
  MessageReceived · SeedCreated · EvaluationComplete
  PhaseStarted · PhaseCompleted · AgentOutput
  ApprovalRequested · ApprovalResolved
  MemoryStored · MemoryRecalled
  AgentGroupCreated · AgentGroupMemberCompleted
  SpaceCreated · SpaceActivated · SpaceArchived
  SpacesMerged · KnowledgeCrossReferenced
```

**Auto-audit:** When `attach_audit_trail()` is called, a background task forwards all events to the AuditTrail as `AuditAction` entries.

**Source:** `crates/oxios-kernel/src/event_bus.rs`

---

### 3.8 AccessManager — RBAC + Path Sandboxing

OWASP-inspired least-privilege security for agents.

```
  ┌──────────────────────────────────────────────────────────┐
  │                    AccessManager                          │
  │                                                          │
  │  ┌────────────────────────────────────────────────────┐  │
  │  │              AgentPermissions                      │  │
  │  │  allowed_tools: HashSet<String>                    │  │
  │  │  allowed_paths: Vec<String> (glob patterns)        │  │
  │  │  denied_paths: Vec<String>  (takes precedence)     │  │
  │  │  network_access: bool                              │  │
  │  │  can_fork: bool                                    │  │
  │  │  max_execution_time_secs: u64                      │  │
  │  │  max_memory_mb: u64                                │  │
  │  └────────────────────────────────────────────────────┘  │
  │                                                          │
  │  ┌────────────────────────────────────────────────────┐  │
  │  │              RbacManager                           │  │
  │  │  Role-based access control with HitL approvals     │  │
  │  │  Subjects: Agent(UUID), User(String), Role(String) │  │
  │  │  Actions: ExecuteTool, AccessPath, Network, Fork   │  │
  │  │  Pending approvals with approve/reject workflow    │  │
  │  └────────────────────────────────────────────────────┘  │
  │                                                          │
  │  ┌────────────────────────────────────────────────────┐  │
  │  │           Workspace Sandboxing                     │  │
  │  │  workspace_paths: name → PathBuf                   │  │
  │  │  agent_workspaces: agent_name → workspace_name     │  │
  │  │  Path boundary enforcement via canonicalize()      │  │
  │  └────────────────────────────────────────────────────┘  │
  │                                                          │
  │  Full sandbox check:                                     │
  │  can_access_path_in_workspace(agent_id, name, path, ws) │
  │    → RBAC check                                          │
  │    → Path allow/deny check                               │
  │    → Workspace boundary check                            │
  │    → All three must pass                                 │
  │                                                          │
  │  Audit log: every access decision recorded               │
  │  Async file persistence via bounded mpsc channel (1000)  │
  └──────────────────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/access_manager/mod.rs`

---

### 3.9 AuditTrail — Tamper-Evident Hash Chain

Merkle-chain style cryptographic audit log. Each entry is linked to the previous via blake3 hashing.

```
  Genesis ──► Entry 1 ──► Entry 2 ──► Entry 3 ──► ...
              hash=abc    hash=def    hash=ghi
              prev=       prev=       prev=
              "genesis"   abc         def

  ┌─────────────────────────────────────────────────────┐
  │                   AuditEntry                         │
  │  seq: u64                                           │
  │  timestamp: DateTime<Utc>                           │
  │  actor: AgentId                                     │
  │  action: AuditAction (tagged enum)                  │
  │  resource: String                                   │
  │  prev_hash: blake3 hex digest                       │
  │  hash: blake3 hex digest                            │
  │  metadata: Option<JSON>                             │
  └─────────────────────────────────────────────────────┘

  AuditAction variants:
  AgentSpawn · AgentExit · ToolCall · ToolResult
  MemoryWrite · MemoryRead · ConfigChange · SkillInstall
  CronTrigger · GitCommit · AccessDenied · Other

  Integrity:
  verify() → checks:
    1. prev_hash chain linked correctly
    2. No future timestamps
    3. Hash recomputation matches stored hash
    4. First entry: prev_hash = "genesis" | "pruned"

  Auto-pruning:
  - When entries > max_entries: oldest pruned
  - Pruned root marked with prev_hash = "pruned"
  - No hash recomputation cascade (O(1))
```

**Source:** `crates/oxios-kernel/src/audit_trail.rs`

---

### 3.10 BudgetManager — Token/Cost Enforcement

Per-agent budget tracking for LLM API calls.

```
  ┌──────────────────────────────────────────────┐
  │             BudgetManager                     │
  │                                              │
  │  BudgetLimit per agent:                      │
  │  { agent_id, token_budget, calls_budget,     │
  │    window_secs }                             │
  │                                              │
  │  can_schedule(agent_id) → bool               │
  │  track_call(agent_id) → Result               │
  │  set_budget(BudgetLimit)                     │
  └──────────────────────────────────────────────┘
```

**Integration:** The Scheduler checks `can_schedule()` before popping tasks. Agents with exhausted budgets are skipped.

**Source:** `crates/oxios-kernel/src/budget.rs`

---

### 3.11 ResourceMonitor — System Tracking

```
  ┌──────────────────────────────────────────────┐
  │            ResourceMonitor                    │
  │                                              │
  │  Tracks: CPU%, memory MB, active agents      │
  │  Configurable interval + history ring buffer  │
  │  is_overloaded() → bool                      │
  │  resource_snapshot() → Snapshot               │
  │  set_active_agents(count)                     │
  └──────────────────────────────────────────────┘
```

**Integration:** The Guardian daemon checks `is_overloaded()` every 5 minutes and logs warnings to the audit trail.

**Source:** `crates/oxios-kernel/src/resource_monitor.rs`

---

### 3.12 GitLayer — In-Process Version Control

```
  ┌──────────────────────────────────────────────┐
  │               GitLayer                        │
  │          (powered by gix crate)               │
  │                                              │
  │  Workspace: ~/.oxios/workspace/              │
  │  Auto-commit on state saves                  │
  │                                              │
  │  commit_file(rel_path, message)              │
  │  remove_file(rel_path, message)              │
  │  log(limit) → Vec<CommitInfo>                │
  │  verify() → bool                             │
  │  tag(name, message)                          │
  │  restore(tag)                                │
  └──────────────────────────────────────────────┘
```

**Integration:** Called by Orchestrator after saving seeds/evaluations, by MemoryManager after writes, and by the Guardian daemon for periodic verification.

**Source:** `crates/oxios-kernel/src/git_layer.rs`

---

### 3.13 CronScheduler — Scheduled Job Execution

```
  ┌──────────────────────────────────────────────┐
  │            CronScheduler                      │
  │                                              │
  │  CronJob { id, cron_expr, task, last_run }   │
  │  Tick-based evaluation (configurable interval)│
  │  Persistent state via StateStore              │
  │  GitLayer integration for auto-commits        │
  │                                              │
  │  add_cron(job) → Uuid                        │
  │  remove_cron(id) → Result                    │
  │  list_crons() → Vec<CronJob>                 │
  └──────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/cron.rs`

---

### 3.14 MemoryManager — Vector Store with Semantic Search

```
  ┌──────────────────────────────────────────────────────────┐
  │                    MemoryManager                          │
  │                                                          │
  │  Storage: StateStore (JSON files per entry)              │
  │  Index: TF-IDF + cosine similarity (in-memory)           │
  │  Optional: HNSW index for fast ANN search                │
  │                                                          │
  │  Memory Types:                                           │
  │  ┌────────────┐┌─────────┐┌──────┐┌────────┐┌──────────┐│
  │  │Conversation││ Session ││ Fact ││Episode ││Knowledge ││
  │  │(auto-comp) ││(summary)││      ││(event) ││(static)  ││
  │  └────────────┘└─────────┘└──────┘└────────┘└──────────┘│
  │                                                          │
  │  Operations:                                             │
  │  remember(entry)              → save + index             │
  │  recall(query)                → Vec<MemoryEntry>         │
  │  search(query, type, limit)   → Vec<SemanticHit>         │
  │  forget(id, type)             → remove                   │
  │  blend_into_prompt(memories)  → enriched system prompt   │
  │  rebuild_index()              → full re-index            │
  │  curate(budget)               → prune low-importance     │
  │                                                          │
  │  Sub-modules:                                            │
  │  ┌─────────────────────────────────────────────────────┐ │
  │  │ hyperbolic/   → Hyperbolic embeddings               │ │
  │  │ flash_attention/ → Attention-weighted retrieval      │ │
  │  │ hnsw/         → HNSW approximate nearest neighbor   │ │
  │  │ graph/        → MemoryGraph (entity relationships)   │ │
  │  │ chunking/     → Text chunking (fixed + paragraph)   │ │
  │  │ normalizer/   → L2 normalize, cosine similarity     │ │
  │  │ store/        → HnswMemoryIndex                     │ │
  │  │ budget/       → MemoryBudget, CurationReport        │ │
  │  └─────────────────────────────────────────────────────┘ │
  │                                                          │
  │  Space-scoped: MemoryManager::for_space(space_dir)       │
  │  Each Space gets isolated memory via separate StateStore  │
  └──────────────────────────────────────────────────────────┘
```

**Effective importance:** `base_importance × (1 + ln(1 + access_count))` — frequently accessed memories get a boost.

**Source:** `crates/oxios-kernel/src/memory/mod.rs`

---

### 3.15 SpaceManager — Context Partitioning

Spaces partition conversations and resources into isolated contexts. Auto-detected from messages.

```
  ┌──────────────────────────────────────────────────────────┐
  │                    SpaceManager                           │
  │                                                          │
  │  ┌────────────────────────────────────────────────────┐  │
  │  │       3-Layer Detection Strategy                   │  │
  │  │                                                    │  │
  │  │  Layer 1: Filesystem Path (fast, free)             │  │
  │  │    "/projects/oxios/src/main.rs" → oxios Space     │  │
  │  │    → PathMatcher: glob-based path → SpaceId map    │  │
  │  │                                                    │  │
  │  │  Layer 2: Keyword/Tag (fast, free)                 │  │
  │  │    Message contains Space tags → match             │  │
  │  │                                                    │  │
  │  │  Layer 3: Topic Classification (LLM, slow)         │  │
  │  │    classify_topic_stub() → Topic { name, clear? }  │  │
  │  │    Topic shift detection via ConversationBuffer     │  │
  │  └────────────────────────────────────────────────────┘  │
  │                                                          │
  │  Space Lifecycle:                                        │
  │  Created (auto/manual) → Active → Archived → Restored   │
  │                                                          │
  │  ┌───────────────┐  ┌──────────────────┐                │
  │  │Default Space  │  │Named Spaces      │                │
  │  │(unnamed, id=1)│  │(auto-created or  │                │
  │  │Always exists  │  │ manual)          │                │
  │  └───────────────┘  └──────────────────┘                │
  │                                                          │
  │  Operations:                                             │
  │  detect_or_create(msg, buffer) → SpaceId                 │
  │  create_from_path(name, path) → Space                    │
  │  create_from_topic(topic) → Space                        │
  │  activate(space_id)                                      │
  │  merge_spaces(survivor, absorbed)                        │
  │  archive_stale() → Vec<SpaceId>                          │
  │  restore_from_archive(space_id)                          │
  │                                                          │
  │  Persistence:                                            │
  │  ~/.oxios/spaces/_index.json                             │
  │  ~/.oxios/spaces/{space_id}/space.json                   │
  │  ~/.oxios/spaces/{space_id}/workspace/                   │
  │  ~/.oxios/spaces/_archived/{space_id}/                   │
  └──────────────────────────────────────────────────────────┘
```

**Auto-merge:** Spaces sharing paths with low activity (<5 interactions) are candidates for automatic merging.

**Source:** `crates/oxios-kernel/src/space/manager.rs`

---

### 3.16 McpBridge — Model Context Protocol

```
  ┌──────────────────────────────────────────────────────────┐
  │                    McpBridge                              │
  │                                                          │
  │  Model Context Protocol client for external tool servers │
  │                                                          │
  │  Server sources:                                         │
  │  1. config.toml [mcp.servers]                            │
  │  2. Environment variables (OXIOS_MCP_{NAME}_COMMAND)     │
  │  3. Skill MCP server configs                             │
  │                                                          │
  │  Operations:                                             │
  │  register_server(McpServer)                              │
  │  initialize_all() → starts all servers                   │
  │  list_tools() → enumerate all server tools               │
  │  cached_tools(server_name) → cached tool definitions     │
  │  call_tool(server, tool, args) → result                  │
  │                                                          │
  │  McpServer { name, command, args, env, enabled }         │
  └──────────────────────────────────────────────────────────┘
```

**Integration:** Skill-level MCP servers are registered during `SkillManager.init()`. Tools are surfaced to agents via `McpToolWrapper` in the tool registry.

**Source:** `crates/oxios-kernel/src/mcp/`

---

### 3.17 A2AProtocol — Agent-to-Agent Communication

Google's A2A protocol for horizontal agent↔agent communication. Unlike MCP (vertical, agent→tool), A2A enables agents to discover, delegate, and share results.

```
  ┌──────────────────────────────────────────────────────────┐
  │                    A2AProtocol                            │
  │                                                          │
  │  ┌────────────────────────────────────────────────────┐  │
  │  │              AgentCardRegistry                      │  │
  │  │  HashMap<AgentId, AgentCard>                        │  │
  │  │                                                    │  │
  │  │  AgentCard { agent_id, name, description,          │  │
  │  │    capabilities[], skills[], endpoint, status }    │  │
  │  │                                                    │  │
  │  │  register_agent(card)                              │  │
  │  │  find_agents_by_capability(cap) → Vec<AgentCard>   │  │
  │  │  find_agents_by_skill(skill) → Vec<AgentCard>      │  │
  │  └────────────────────────────────────────────────────┘  │
  │                                                          │
  │  ┌────────────────────────────────────────────────────┐  │
  │  │            Per-Agent Message Queues                 │  │
  │  │  HashMap<AgentId, AgentQueue>                       │  │
  │  │  AgentQueue: messages + tokio::sync::Notify         │  │
  │  │                                                    │  │
  │  │  send_message(from, to, message) → request_id      │  │
  │  │  receive_messages(agent_id) → Vec<A2ARequest>       │  │
  │  │  send_and_wait(from, to, msg, timeout) → Response  │  │
  │  └────────────────────────────────────────────────────┘  │
  │                                                          │
  │  Message Types:                                          │
  │  TaskDelegation { task_id, description, payload, priority}│
  │  StatusUpdate { task_id, progress, message }             │
  │  ResultSharing { task_id, result, summary }              │
  │  CapabilityQuery { query, required_capabilities }         │
  │  Handshake { agent_id, name, capabilities }              │
  │                                                          │
  │  Delegation Handler:                                     │
  │  set_delegation_handler(callback)                        │
  │  execute_delegation(from, to, task) → Option<Result>     │
  │  Default handler: spawns agent via AgentLifecycleManager │
  └──────────────────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/a2a.rs`

---

### 3.18 CircuitBreaker — LLM Provider Protection

3-state circuit breaker preventing cascading LLM provider failures.

```
          ┌─────────┐  threshold    ┌──────┐
          │ CLOSED  │  failures     │ OPEN │
          │ (normal)│──────────────►│(fail)│
          └────┬────┘               └──┬───┘
               ▲                       │
               │ success               │ timeout
               │                       ▼
          ┌────┴────┐            ┌──────────┐
          │ CLOSED  │◄───────────│HALF-OPEN │
          │         │  success   │ (probe)  │
          └─────────┘            └────┬─────┘
                                      │ failure
                                      ▼
                                 ┌────────┐
                                 │  OPEN  │
                                 └────────┘

  Default: threshold=5, timeout=30s
  Single probe in half-open state (atomic CAS gate)
  Global singleton via OnceLock
```

**Source:** `crates/oxios-kernel/src/circuit_breaker.rs`

---

### 3.19 PersonaManager — Multi-Persona System

```
  ┌──────────────────────────────────────────────┐
  │           PersonaManager                      │
  │                                              │
  │  Personas define agent behavior:             │
  │  - name, system_prompt, role                 │
  │  - enabled/disabled state                    │
  │                                              │
  │  first_enabled() → Option<&Persona>          │
  │  get_active_persona() → Option<&Persona>     │
  │  active_system_prompt() → String             │
  │                                              │
  │  Integration:                                │
  │  - OuroborosEngine: set_persona_prompt()     │
  │  - AgentRuntime: injects into system prompt  │
  │  - CSpace resolution: role → capability set  │
  └──────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/persona_manager.rs`

---

### 3.20 SkillManager — Unified Skill System (RFC-009)

```
  ┌──────────────────────────────────────────────────────┐
  │                  SkillManager                         │
  │                                                      │
  │  Skills are unified capabilities:                     │
  ~/.oxios/workspace/skills/{name}/                   │
  │    └── SKILL.md  (YAML frontmatter + instructions)   │
  │                                                      │
  │  SkillSource hierarchy (priority):                    │
  │  1. workspace/.agents/<id>/skills/ (agent-specific)  │
  │  2. workspace/skills/             (project)         │
  │  3. ~/.oxios/workspace/skills/    (global user)       │
  │  4. share/default-skills/          (bundled, lowest)  │
  │                                                      │
  │  Requirements (4-dimensional):                        │
  │  bins: ["git", "gh"]     — required binaries         │
  │  anyBins: ["ffmpeg"]     — one must be present       │
  │  env: ["GITHUB_TOKEN"]  — required env vars          │
  │  config: []               — required config paths    │
  │                                                      │
  │  Install specs (automatic dependency installation):   │
  │  - kind: brew, formula: git                           │
  │  - kind: download, url: https://...                   │
  │                                                      │
  │  Operations:                                         │
  │  init() → load + validate + watch                    │
  │  list_skills() → Vec<SkillEntry>  │  get_skill(name) → Option<SkillEntry>  │  build_snapshot() → SkillSnapshot (for agent prompt) │
  │  set_enabled(name, bool)                             │
  └──────────────────────────────────────────────────────┘
```

**Built-in skills** (in `share/default-skills/`): code-review, debug, refactor. Memory and Programs have been unified into Skills per RFC-009.

**Source:** `crates/oxios-kernel/src/skill.rs` — `SkillManager`

---

### 3.21 SkillStore — Skill Definitions

```
  ┌──────────────────────────────────────────────┐
  │              SkillStore                       │
  │                                              │
  │  Skills are reusable agent capabilities      │
  │  Stored in: ~/.oxios/workspace/skills/       │
  │                                              │
  │  init_defaults(defaults_dir) → populate      │
  │  Default skills from share/default-skills/   │
  └──────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/skill.rs`

---

### 3.22 HostToolValidator — Binary Allowlist

### 3.19 Skill Requirements — Unified Requirements Checking (RFC-009)

```
  ┌──────────────────────────────────────────────┐
  │          Skill Requirements Check              │
  │                                              │
  │  4-dimensional requirements per skill:        │
  │  bins:     all must be present                │
  │  anyBins:  at least one must be present       │
  │  env:      required environment variables      │
  │  config:   required config paths               │
  │                                              │
  │  Replaces former: HostToolValidator,          │
  │  SkillManager host_requirements,                 │
  │  ExecConfig.required/optional_host_tools       │
  └──────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/skill.rs` — `SkillManager::check_requirements()`

---

### 3.23 AuthManager — Identity Verification

```
  ┌──────────────────────────────────────────────┐
  │            AuthManager                        │
  │                                              │
  │  Authentication for kernel operations.       │
  │  API keys resolved via:                      │
  │  1. engine.api_key (config)                  │
  │  2. ~/.oxi/auth.json (oxi credentials)       │
  │  3. Environment variables                    │
  │                                              │
  │  Used by KernelHandle's SecurityApi          │
  └──────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/auth.rs`

---

### 3.24 CredentialStore — Multi-Source Credential Resolution

```
  ┌──────────────────────────────────────────────┐
  │          CredentialStore                      │
  │                                              │
  │  Resolution chain:                           │
  │  config.toml → oxi auth.json → env vars      │
  │                                              │
  │  Used for LLM provider API keys              │
  └──────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/credential.rs`

---

### 3.25 WasmSandbox — Untrusted Code Execution

```
  ┌──────────────────────────────────────────────┐
  │           WasmSandbox                         │
  │                                              │
  │  WASM-based sandbox for executing            │
  │  untrusted code in isolation                 │
  └──────────────────────────────────────────────┘
```

**Source:** `crates/oxios-kernel/src/wasm_sandbox.rs`

---

### 3.26 ContextManager — Context Window Management

```
  ┌──────────────────────────────────────────────┐
  │          ContextManager                       │
  │                                              │
  │  Manages LLM context window:                 │
  │  - Token counting and budgeting              │
  │  - Compaction strategy (threshold: 0.8)      │
  │  - Memory blending into prompts              │
  └──────────────────────────────────────────────┘
```

**Source:** Integrated into `AgentRuntime` via `oxi_sdk::AgentLoop` compaction callbacks.

---

## 4. KernelHandle Facade

The KernelHandle is the **syscall table** of the Agent OS. It is a facade composed of 13 typed APIs that provide the single path for all kernel operations.

```
  ┌──────────────────────────────────────────────────────────────────┐
  │                       KernelHandle                               │
  │                     (cached via OnceLock)                        │
  │                                                                  │
  │  ┌──────────┐ ┌──────────┐ ┌───────────┐ ┌──────────┐          │
  │  │ StateApi │ │ AgentApi │ │SecurityApi│ │PersonaApi│          │
  │  │          │ │          │ │           │ │          │          │
  │  │save/load │ │supervisor│ │auth       │ │personas  │          │
  │  │sessions  │ │budget    │ │audit trail│ │system    │          │
  │  │markdown  │ │memory    │ │RBAC       │ │prompts   │          │
  │  └──────────┘ └──────────┘ │access mgr │ └──────────┘          │
  │                            └───────────┘                        │
  │  ┌──────────────┐ ┌────────┐ ┌────────┐ ┌──────────┐           │
  │  │ExtensionApi  │ │ McpApi │ │InfraApi│ │ SpaceApi │           │
  │  │              │ │        │ │        │ │          │           │
  │  │skills        │ │bridge  │ │git     │ │spaces    │           │
  │  │              │ │servers │ │scheduler│ │knowledge │           │
  │  └──────────────┘ └────────┘ └────────┘ └──────────┘           │
  │                              │resource│                        │
  │                              │events  │                        │
  │                              │config  │                        │
  │                              └────────┘                        │
  │  ┌──────────┐ ┌──────────┐ ┌──────────┐                      │
  │  │ ExecApi  │ │BrowserApi│ │  A2aApi  │                      │
  │  │          │ │          │ │          │                      │
  │  │exec cfg  │ │headless  │ │A2A proto │                      │
  │  │access mgr│ │browser   │ │registry  │                      │
  │  └──────────┘ └──────────┘ └──────────┘                      │
  │                                                                  │
  │  Cross-Facade convenience methods:                               │
  │  save_and_commit()  — State + Git                               │
  │  delete_and_commit() — State + Git                              │
  │  commit_all()       — flush state to git                        │
  │  flush_audit()      — Security + Git                            │
  │  schedule()         — Cron wrapper                              │
  └──────────────────────────────────────────────────────────────────┘
```

### Construction Order

The KernelHandle is created **twice** during `KernelBuilder::build()`:

1. **Placeholder Handle** — Created with `NoOpSupervisor` to break the circular dependency:
   `KernelHandle → AgentRuntime → Supervisor → KernelHandle`

2. **Final Handle** — Cached in `Kernel.handle_cache` (via `OnceLock`) with the real `BasicSupervisor`.

The first handle is discarded after the real supervisor is constructed.

**Source:** `crates/oxios-kernel/src/kernel_handle/mod.rs`

---

## 5. Data Flow

### 5.1 User Message Flow

Complete path of a user message through the system:

```
  User: "Refactor the authentication module to use JWT tokens"
                ┌─────────────────┐
  │   CLI / Web /   │  Channel receives raw message
  │   Telegram      │
  └────────┬────────┘
                        ┌─────────────────┐
  │    Gateway      │  Routes to Orchestrator.handle_message()
  │ (oxios-gateway) │  (user_id, message, session_id)
  └────────┬────────┘
                        ┌─────────────────────────────────────────────────────┐
  │              Space Detection (3-layer)               │
  │  Path? → Keyword? → Topic classification            │
  │  Creates/activates appropriate Space                 │
  └────────┬────────────────────────────────────────────┘
                        ┌─────────────────────────────────────────────────────┐
  │              Chat Bypass Check                       │
  │  Is this a simple greeting/question?                │
  │  YES → Direct LLM response → return to user         │
  │  NO  → Continue to Ouroboros pipeline                │
  └────────┬────────────────────────────────────────────┘
                        ╔═══════════════════════════════════════════════════════╗
  ║         OUROBOROS PROTOCOL (Phase 1: Interview)      ║
  ║  OuroborosEngine.interview(message)                  ║
  ║  → InterviewResult { questions, ambiguity, ready }   ║
  ║  If ambiguity > 0.2: return questions to user        ║
  ║  User answers → follow-up interview                  ║
  ╚══════════════╤════════════════════════════════════════╝
                 │ (ambiguity ≤ 0.2, ready for seed)
                   ╔═══════════════════════════════════════════════════════╗
  ║         OUROBOROS PROTOCOL (Phase 2: Seed)           ║
  ║  OuroborosEngine.generate_seed(interview)            ║
  ║  → Seed { id, goal, constraints, criteria, ontology }║
  ║  Save to StateStore → emit SeedCreated event         ║
  ╚══════════════╤════════════════════════════════════════╝
                                    ┌─────────────────────────────────────────────────────┐
  │         Multi-Agent Split Check                      │
  │  acceptance_criteria.len() ≥ 3?                      │
  │  YES → split into subtasks → delegate in parallel    │
  │  NO  → single agent execution                        │
  └────────┬────────────────────────────────────────────┘
                        ╔═══════════════════════════════════════════════════════╗
  ║    AGENT LIFECYCLE (Phase 3: Execute)                ║
  ║  AgentLifecycleManager.spawn_and_run(seed, priority) ║
  ║                                                      ║
  ║  1. fork() → AgentId                                 ║
  ║  2. Register A2A AgentCard                           ║
  ║  3. Ensure AccessManager permissions                 ║
  ║  4. Submit to Scheduler → start_task()               ║
  ║  5. Supervisor.run_with_seed(agent_id, seed)         ║
  ║     └── AgentRuntime.execute(agent_id, seed)         ║
  ║         ├── Resolve CSpace                           ║
  ║         ├── Register tools (always-on + CSpace)      ║
  ║         ├── Recall memories → blend into prompt      ║
  ║         ├── Semantic capability retrieval             ║
  ║         └── oxi_sdk::AgentLoop::run()                ║
  ║             └── Multi-turn LLM tool-calling loop     ║
  ║                 ├── Tool calls: exec, read, write... ║
  ║                 ├── Circuit breaker on LLM errors    ║
  ║                 └── Compaction → save memory          ║
  ║  6. Cleanup: unregister A2A, complete/fail task      ║
  ╚══════════════╤════════════════════════════════════════╝
                 │ ExecutionResult
                   ╔═══════════════════════════════════════════════════════╗
  ║    OUROBOROS PROTOCOL (Phase 4: Evaluate)            ║
  ║  OuroborosEngine.evaluate(seed, exec_result)         ║
  ║  → EvaluationResult { score, criteria_results, notes }║
  ╚══════════════╤════════════════════════════════════════╝
                                    ┌─────────────────────────────────────────────────────┐
  │         Score Check                                   │
  │  score ≥ 0.8 and all_passed?                         │
  │  YES → Return success result                         │
  │  NO  → Enter evolve loop (max 3 iterations)          │
  └────────┬────────────────────────────────────────────┘
           │ (score < 0.8)
             ╔═══════════════════════════════════════════════════════╗
  ║    OUROBOROS PROTOCOL (Phase 5: Evolve)              ║
  ║  OuroborosEngine.evolve(seed, evaluation)            ║
  ║  → Option<Seed> (evolved version)                    ║
  ║  → Re-execute with Priority::High                    ║
  ║  → Re-evaluate                                       ║
  ║  → Repeat until pass or max iterations reached       ║
  ╚═══════════════════════════════════════════════════════╝
                        OrchestrationResult {
    session_id, space_id, space_tag, response,
    seed_id, phase_reached, evaluation_passed, output
  }
```

---

## 6. Dependency Graph

### Crate Dependencies

```
  ┌─────────────────────────────────────────────────────────┐
  │                    oxios (binary)                        │
  │  src/main.rs, src/kernel.rs, src/cmd_run.rs             │
  │                                                         │
  │  Depends on:                                            │
  │  ├── oxios-kernel     (core subsystems)                 │
  │  ├── oxios-ouroboros  (protocol engine)                 │
  │  ├── oxios-gateway    (message hub)                     │
  │  ├── oxios-web        (web channel, feature-gated)      │
  │  ├── oxios-cli        (CLI channel, feature-gated)      │
  │  └── oxios-telegram   (Telegram channel, feature-gated) │
  └───────────────────┬─────────────────────────────────────┘
                                ┌───────────┼───────────────────┐
          │           │                   │
          ▼           ▼                   ▼
  ┌──────────────┐ ┌───────────────┐ ┌──────────────┐
  │ oxios-kernel │ │oxios-ouroboros│ │ oxios-gateway│
  │              │ │               │ │              │
  │ Core:        │ │ Protocol:     │ │ Channel-     │
  │ Supervisor   │ │ Interview     │ │ agnostic     │
  │ Scheduler    │ │ Seed gen      │ │ message hub  │
  │ EventBus     │ │ Execute       │ │              │
  │ StateStore   │ │ Evaluate      │ │ Depends on:  │
  │ AccessMgr    │ │ Evolve        │ │ oxios-kernel │
  │ AuditTrail   │ │               │ │ (Orchestrator│
  │ Memory       │ │ Depends on:   │ │  reference)  │
  │ Space        │ │ oxi-sdk       │ └──────────────┘
  │ MCP Bridge   │ │ (Provider)    │
  │ A2A          │ └───────────────┘
  │ PersonaMgr   │
  │ SkillMgr     │   ┌──────────────────────┐
  │ GitLayer     │   │  oxi-sdk (crates.io) │
  │ CronSched    │   │  NOT a path dep!     │
  │ BudgetMgr    │   │  AgentLoop, Provider,│
  │ ResourceMon  │   │  ToolRegistry, etc.  │
  │ CircuitBkr   │   └──────────────────────┘
  │ KernelHandle │          ▲
  │              │          │
  │ Depends on:  │──────────┘
  │ oxi-sdk      │   + oxi-ai (provider construction)
  │ oxi-ai       │   + oxios-ouroboros
  │ oxios-ourobo │
  └──────────────┘
```

### Feature Gates

```
  [features]
  web       → oxios-web channel
  cli       → oxios-cli channel
  telegram  → oxios-telegram channel
  browser   → BrowserTool + BrowserApi (headless browser)
  telemetry → OpenTelemetry integration (compile-time toggle)
```

### Directory Structure

```
  oxios/
  ├── src/                    # Binary crate
  │   ├── main.rs             # Entry point, daemon mode
  │   ├── kernel.rs           # Kernel builder + assembly
  │   └── cmd_run.rs          # CLI run subcommand
  ├── crates/
  │   ├── oxios-kernel/       # Core library
  │   │   └── src/
  │   │       ├── supervisor.rs
  │   │       ├── orchestrator.rs
  │   │       ├── agent_lifecycle.rs
  │   │       ├── agent_runtime.rs
  │   │       ├── scheduler.rs
  │   │       ├── event_bus.rs
  │   │       ├── audit_trail.rs
  │   │       ├── circuit_breaker.rs
  │   │       ├── a2a.rs
  │   │       ├── access_manager/
  │   │       ├── memory/
  │   │       ├── space/
  │   │       ├── kernel_handle/
  │   │       ├── tools/
  │   │       │   ├── registration.rs
  │   │       │   ├── exec_tool.rs
  │   │       │   ├── kernel/        # Kernel facade tools
  │   │       │   └── retrieval.rs   # ToolRetriever
  │   │       ├── config.rs
  │   │       ├── budget.rs
  │   │       ├── cron.rs
  │   │       ├── git_layer.rs
  │   │       ├── resource_monitor.rs
  │   │       ├── persona_manager.rs
  │   │       ├── skill.rs
  │   │       ├── auth.rs
  │   │       ├── credential.rs
  │   │       ├── wasm_sandbox.rs
  │   │       ├── mcp/
  │   │       ├── capability/
  │   │       ├── agent_group.rs
  │   │       ├── metrics.rs
  │   │       ├── onboarding.rs
  │   │       ├── daemon.rs
  │   │       └── state_store.rs
  │   ├── oxios-ouroboros/     # Protocol engine
  │   └── oxios-gateway/       # Message hub
  ├── channels/
  │   ├── oxios-web/           # Axum + Dioxus/WASM
  │   ├── oxios-cli/           # CLI channel
  │   └── oxios-telegram/      # Telegram channel
  ├── share/                   # Default configs, skills

  └── docs/                    # Architecture docs, RFCs
```

---

## 7. Security Model

### 7.1 Overview

```
  ┌─────────────────────────────────────────────────────────┐
  │                   Security Layers                        │
  │                                                         │
  │  Layer 1: Authentication (AuthManager)                  │
  │    ↓ API key resolution: config → oxi auth → env        │
  │                                                         │
  │  Layer 2: Authorization (AccessManager + RBAC)          │
  │    ↓ Least privilege, tool/path/network controls        │
  │                                                         │
  │  Layer 3: Sandbox (Workspace isolation)                 │
  │    ↓ Path boundary enforcement per workspace            │
  │                                                         │
  │  Layer 4: Execution Security (ExecTool)                 │
  │    ↓ Shell mode: RBAC-enforced bash -c                  │
  │    ↓ Structured mode: binary allowlist + meta blocking  │
  │                                                         │
  │  Layer 5: Audit (AuditTrail)                            │
  │    ↓ Tamper-evident blake3 hash chain                   │
  │    ↓ Every access decision logged                       │
  │                                                         │
  │  Layer 6: Guardian Daemon                               │
  │    ↓ Periodic integrity checks (audit chain, git, load) │
  └─────────────────────────────────────────────────────────┘
```

### 7.2 RBAC (Role-Based Access Control)

```
  ┌──────────────────────────────────────────────────┐
  │                 RbacManager                       │
  │                                                  │
  │  Subjects:  Agent(UUID) | User(String) | Role    │
  │  Actions:   ExecuteTool | AccessPath | Network   │
  │             Fork | ManageAgents | ConfigChange    │
  │  Policies:  Subject + Action + Resource → Allow   │
  │                                                  │
  │  Human-in-the-Loop (HitL):                       │
  │  PendingApproval { id, subject, action, resource }│
  │  approve(id) / reject(id)                        │
  │  Approval flow: submit → queue → approve/reject  │
  └──────────────────────────────────────────────────┘
```

### 7.3 Path Sandboxing

```
  Agent requests: /workspace/secret/key.pem
                ┌──────────────────────────────────────┐
  │  1. RBAC Check                       │
  │     Subject.Agent → Action.AccessPath│
  │     → allowed?                       │
  ├──────────────────────────────────────┤
  │  2. Path Permission Check            │
  │     denied_paths matches? → BLOCK    │
  │     allowed_paths matches? → ALLOW   │
  ├──────────────────────────────────────┤
  │  3. Workspace Boundary Check         │
  │     canonicalize(path)               │
  │     starts_with(workspace_path)?     │
  │     NO → "sandbox violation" logged  │
  └──────────────────────────────────────┘
  All three must pass for access to be granted
```

### 7.4 ExecTool Security

```
  ┌──────────────────────────────────────────────────┐
  │              ExecTool                            │
  │                                                  │
  │  Shell Mode:                                     │
  │    bash -c "{command}"                           │
  │    RBAC-enforced: agent must have bash allowed    │
  │    Working directory: workspace                  │
  │                                                  │
  │  Structured Mode:                                │
  │    Binary allowlist only                         │
  │    Metacharacter blocking (|, ;, &, etc.)        │
  │    Safer for production use                      │
  └──────────────────────────────────────────────────┘
```

### 7.5 Audit Trail Integrity

```
  Every security-relevant action:
      AuditEntry { seq, timestamp, actor, action, resource, prev_hash, hash }
      blake3 hash links entry to predecessor
      verify() detects any tampering:
    - Chain broken (prev_hash mismatch)
    - Hash recomputation fails
    - Future timestamps
      Guardian daemon checks every 5 minutes:
    - Audit chain validity
    - Git repository integrity
    - System overload
```

---

## 8. Unix Philosophy Mapping

| Unix Concept       | Oxios Equivalent                           | Description                                    |
|--------------------|--------------------------------------------|------------------------------------------------|
| `init` (PID 1)    | `Supervisor`                               | Manages all agent lifecycles                   |
| `fork()`          | `Supervisor::fork(seed)`                   | Create new agent from seed specification       |
| `exec()`          | `Supervisor::exec(id)` / `run_with_seed()` | Start executing an agent                       |
| `wait()`          | `Supervisor::wait(id)`                     | Wait for agent completion                      |
| `kill()`          | `Supervisor::kill(id)`                     | Terminate an agent (cooperative + abort)       |
| `ps`              | `Supervisor::list()`                       | List all known agents                          |
| Pipes             | `EventBus` (broadcast channel)             | Inter-agent communication                      |
| Signals           | `KernelEvent` variants                     | AgentCreated, AgentStopped, etc.               |
| `/proc`           | `StateStore` + `Scheduler::stats()`        | Agent state inspection                         |
| `nice` / priority | `Priority` enum (Low→Critical)             | Task scheduling priority                       |
| `ulimit`          | `BudgetManager` + `AccessManager`          | Resource limits per agent                      |
| `chroot`          | Workspace sandboxing                       | Path boundary enforcement                      |
| `auditd`          | `AuditTrail`                               | Tamper-evident cryptographic audit log         |
| `cron`            | `CronScheduler`                            | Scheduled job execution                        |
| `git`             | `GitLayer`                                 | In-process version control via gix             |
| `/etc`            | `OxiosConfig` (config.toml)                | System configuration                           |
| Skills           | `SkillManager` + `skill.rs`              | Unified skill system (Programs + Skills)     |
| `man` pages       | `SKILL.md` per skill                      | Usage documentation for capabilities           |
| Shell             | `ExecTool` (shell/structured modes)        | Command execution with RBAC                    |
| Sudo / polkit     | HitL Approval (RbacManager)                | Human-in-the-loop approval for dangerous ops   |

---

## 9. Dependency Rules

### Invariant Rules

| Rule | Description |
|------|-------------|
| **oxi-sdk is crates.io only** | `oxi-sdk` is a published crate, NOT a path dependency. Never reimplement what oxi provides. |
| **Kernel binary assembles, library provides** | `src/kernel.rs` (binary) assembles components. `oxios-kernel` (library) provides them. |
| **KernelHandle is the syscall table** | All tool access goes through `KernelHandle`. Never bypass it with direct subsystem references in tools. |
| **Supervisor ≠ AgentLifecycleManager** | `Supervisor` = low-level process management. `AgentLifecycleManager` = full orchestrated lifecycle (A2A, scheduling, permissions). Never add lifecycle logic to Orchestrator directly. |
| **Lifecycle split** | Don't add lifecycle logic to `Orchestrator` — use `AgentLifecycleManager`. |
| **No containers** | Direct host execution. Security via `AccessManager` (RBAC + path sandboxing). |
| **Channel agnostic** | Gateway doesn't care where messages come from. Channels are feature-gated plugins. |
| **Feature gates** | Web, CLI, Telegram, browser, telemetry are all feature-gated. Check `cargo build -p oxios --features <feature>`. |

### Circular Dependency Break

The construction order solves the `KernelHandle → AgentRuntime → Supervisor → KernelHandle` cycle:

```
  1. Create placeholder KernelHandle with NoOpSupervisor
  2. Create AgentRuntime with placeholder handle
  3. Create BasicSupervisor with AgentRuntime
  4. Build real Kernel
  5. Kernel::handle() returns cached handle via OnceLock
     (real supervisor, not NoOp)
```

### Testing Conventions

| Convention | Description |
|------------|-------------|
| Unit tests | `#[cfg(test)] mod tests` in each file |
| Integration tests | `tests/` per crate |
| Mock providers | `MockProvider` implements `oxi_sdk::Provider` with empty streams |
| Temp directories | Use `tempfile::tempdir()` for state store tests |
| Must pass | `cargo test --workspace` at every commit |
| CI check | `a7garden/oxi` at `v0.4.4` checked out alongside for oxi-related tests |

---

## 10. Kernel Crate Architecture

### Why `oxios-kernel` Is a Single Crate

`oxios-kernel` is ~50K lines across 137 source files. This is **intentionally monolithic** — not a code smell that needs fixing.

#### The dependency topology is a star, not a web

Real-world code review shows that kernel subsystems depend on each other in a clean star pattern:

```
                     types::AgentId
                    ╱      │       ╲
      EventBus   StateStore   Config
          │          │          │
     Supervisor ── Scheduler ── BudgetManager
               AgentRuntime ── Engine (→ oxi-sdk)
               KernelHandle (facade: references all subsystems)
```

There are **zero circular dependencies** between modules. The only module that references everything is `KernelHandle` — and that is its explicit purpose as a Facade.

#### Internal boundaries are already clean

The kernel uses directory-level modules with `pub(crate)` encapsulation:

| Directory | Lines | External deps from kernel | Self-contained? |
|-----------|-------|---------------------------|----------------|
| `memory/` | 12,277 | `state_store`, `git_layer` (2) | ✅ Nearly isolated |
| `tools/` | 7,047 | `KernelHandle` (facade pattern) | ✅ Goes through facade |
| `access_manager/` | 3,681 | `types`, `capability`, `config` (3) | ✅ Nearly isolated |
| `kernel_handle/` | 3,063 | All subsystems (by design) | — This IS the facade |
| `capability/` | 958 | `types` (1) | ✅ Fully isolated |
| `skill/` | 1,580 | None | ✅ Fully isolated |

Each directory already has its own `mod.rs` controlling visibility. The `lib.rs` organizes modules into logical sections with explicit Korean comments:

- Lifecycle: `supervisor`, `agent_lifecycle`, `agent_runtime`, `daemon`
- Orchestration: `scheduler`, `budget`, `cron`, `orchestrator`
- Security: `access_manager`, `audit_trail`, `auth`, `capability`, `credential`
- Communication: `a2a`, `event_bus`, `mcp`, `coordination`
- Intelligence: `memory`, `embedding`, `persona`, `onboarding`
- Tools & Skills: `tools`, `skill`, `clawhub`, `skills_sh`
- State & Config: `config`, `state_store`, `git_layer`, `project`, `backup`
- Infrastructure: `engine`, `error`, `types`, `metrics`, `telemetry`
- API Surface: `kernel_handle`

#### Why not split into separate crates?

Every past attempt to extract a subsystem was cancelled because:

| Cost of extraction | Impact |
|-------------------|--------|
| `pub(crate)` → `pub` everywhere | Leaks internal types, widens API surface |
| Circular dependency risk | Extracted crates need kernel types → kernel needs extracted crate |
| Version synchronization | N crates × version bumps = coordination overhead |
| Build time regression | More crate boundaries = more compilation units = worse cache |
| No reuse benefit | Nobody consumes `oxios-kernel-memory` or `oxios-kernel-security` independently |
| Trait abstraction overhead | To break cycles, you'd need traits → dynamic dispatch → complexity |

The Linux kernel is 30M+ lines in a single tree. It uses directories (`mm/`, `fs/`, `net/`, `drivers/`) for organization, not separate libraries. Same principle applies here at a different scale.

#### When WOULD splitting make sense?

Splitting would be justified if and only if:

1. **Independent reuse** — Another project wants to use a subsystem without the whole kernel
2. **Independent versioning** — A subsystem changes at a fundamentally different cadence
3. **Build isolation** — A subsystem has dramatically different compile-time dependencies (e.g., heavy C FFI)
4. **Team boundary** — Different teams own different subsystems with different release cycles

None of these conditions hold today.

#### How to manage the kernel's size

Instead of crate splitting, the kernel manages complexity through:

- **Feature gates**: `sqlite-memory`, `embedding-gguf`, `otel`, `wasm-sandbox`, `browser` — only compile what you need
- **`pub(crate)` encapsulation**: Module internals stay internal
- **Directory-level mod.rs**: Each subsystem controls its own visibility
- **lib.rs section organization**: Clear logical grouping with labeled sections
- **KernelHandle facade**: Single entry point for all 13 APIs, preventing direct subsystem coupling in consumers

---

## Appendix: Quick Reference

### Key File Locations

| Path | Purpose |
|------|---------|
| `~/.oxios/config.toml` | Main configuration |
| `~/.oxios/workspace/` | Agent working directory |
| `~/.oxios/workspace/seeds/` | Ouroboros seed specs |
| `~/.oxios/workspace/skills/` | Unified skill definitions (Programs + Skills) |
| `~/.oxios/workspace/sessions/` | Session data (ephemeral) |
| `~/.oxios/spaces/` | Space data (index + per-space dirs) |
| `~/.oxi/auth.json` | oxi-cli credentials |

### CLI Quick Reference

```bash
cargo build                          # Build everything
cargo test --workspace               # Run all tests
cargo run                            # Start daemon (background)
cargo run -- --foreground            # Start in foreground
cargo run -- run --json "prompt"     # Single-shot execution
cargo run -- run --json --session "$SID" "follow-up"  # Multi-turn
```

### OrchestrationResult JSON Shape

```json
{
  "response": "string",
  "session_id": "uuid",
  "space_id": "uuid | null",
  "space_tag": "[emoji label] | null",
  "seed_id": "uuid | null",
  "agent_id": "uuid | null",
  "phase_reached": "Interview | Seed | Execute | Evaluate | Evolve",
  "evaluation_passed": true,
  "output": "string | null"
}
```