File size: 29,218 Bytes
001b2a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPFsmartGATE v3.0.0 — Complete Feature List
### 18,500+ lines of Rust | 42 modules | 7 LMDB databases | Multi-agent mesh network | FLINT on-device AI
*Copyright 2026 Joseph Stone — All Rights Reserved*
*Updated: 2026-04-05 (full audit against LIVE src/)*

---

## I. THE GATE — Primary Enforcement Engine
*(gate.rs — 493 lines)*

The core pipeline every single tool call passes through.

### 1. 5-Stage Gate Pipeline
Every tool call goes through this exact sequence:
1. **Calculate** complexity (C value, tier, allocation)
2. **CRITICAL escalation** — if tier = CRITICAL, force max protocol
3. **Validate** against compiled rules (paths, anchor, whitelist, dangerous commands)
4. **Content inspection** on Write/Edit operations
5. **Return** allow/block decision with full audit trail

### 2. GateDecision Struct
Every gate result includes:
- allowed: bool — final verdict
- tool: String — which tool was called
- complexity: ComplexityResult — full C breakdown
- warnings: Vec<String> — non-blocking issues
- errors: Vec<String> — blocking violations
- message: String — human-readable summary

### 3. Source-Centric Decisions
- Gate receives `Source` enum (Stdio/Http/Mesh/Transformer/Pipeline)
- Decision context includes peer identity, role, trust level

---

## II. COMPLEXITY CALCULATOR — The SPF Formula
*(calculate.rs — 416 lines)*

### 4. 4-Factor Exponential Complexity Formula

    C = (basic ^ 1) + (dependencies ^ 7) + (complex ^ 10) + (files × 10)

- basic to the 1st — linear base cost
- deps to the 7th — cascading dependency penalty (2→128, 3→2187, 5→78125)
- complex to the 10th — nuclear escalation (3→59049, 4→1048576)
- files times 10 — linear file count penalty

### 5. Master Allocation Formula

    a_optimal(C) = W_eff × (1 - 1/ln(C + e))

- W_eff = 40,000 tokens (effective working memory)
- Maps C → optimal analysis token budget

### 6. 4-Tier Classification
| Tier | C Range | Analyze | Build |
|------|---------|---------|-------|
| SIMPLE   | < 500   | 40% | 60% |
| LIGHT    | < 2,000 | 60% | 40% |
| MEDIUM   | < 10,000| 75% | 25% |
| CRITICAL | > 10,000| 95% |  5% |

### 7. Per-Tool Weight Profiles
| Category | Basic | Deps | Complex | Files |
|----------|-------|------|---------|-------|
| Read | 5 | 1 | 0 | 1 |
| Search | 8 | 2 | 0 | 1 |
| Edit | 10 | 2 | 1 | 1 |
| Write | 20 | 2 | 1 | 1 |
| Bash (dangerous) | 50 | 5 | 2 | 1 |

### 8. Dynamic Complexity Boosters
- Content size escalation (+1 per threshold: 200/1000/5000 bytes)
- Risk keyword detection (delete, drop, force, unsafe, rm, sudo)
- Architectural file detection (config, main, lib, Cargo.toml, yaml, etc.)
- Scope estimation (glob patterns, find, xargs)

---

## III. VALIDATION ENGINE — Compiled Rules
*(validate.rs — 1,481 lines)*

### 9. Compiled Write Allowlist
Only two paths accept writes: LIVE/PROJECTS/PROJECTS/ and LIVE/TMP/TMP/
Resolved dynamically from `spf_root()` — portable, compiled-in, runtime-immutable.

### 10. Symlink-Aware Path Resolution
- `canonicalize()` for existing files, parent canonicalize for new files
- Filenames with `..` rejected outright
- Broken symlinks = blocked

### 11. Build Anchor Protocol
- Hard mode: must read file before edit/overwrite → violation = BLOCKED
- Per-file tracking via `session.files_read`

### 12. Dangerous Command Detection
Blocked patterns: `rm -rf`, `dd if=`, `> /dev/`, `chmod 777`, `curl|sh`, `wget|sh`

### 13. /tmp Access Block — hard block on all platforms (SPF policy)

### 14. File Size Limit — max_write_size default 100,000 bytes

---

## IV. CONTENT INSPECTION — Deep Scan
*(inspect.rs — 253 lines)*

### 15. Credential Detection (20 patterns)
API keys, GitHub tokens, GitLab PATs, Slack tokens, PEM private keys, hardcoded credentials.

### 16. Shell Injection Detection
Command substitution, backtick exec, eval/exec statements (skipped for code files).

### 17. Path Traversal & Blocked Reference Detection
Scans content for `../` sequences and references to blocked paths.

### 18. Context-Aware Inspection
Code files (.rs/.py/.js/.ts/.sh/.json/.toml) skip shell injection — only credentials, traversal, blocked refs checked.

---

## V. CONFIGURATION SYSTEM
*(config.rs — 917 lines, config_db.rs — 797 lines)*

### 19. SpfConfig — Master Configuration Struct
All settings: enforce_mode, paths, max_write_size, tiers, formula, weights, dangerous_commands, git_force_patterns.

### 20. CONFIG.DB — LMDB-Backed Configuration
- Namespaced key-value: `namespace:key` → JSON value
- Path rules DB, Dangerous patterns DB with severity (1-10)
- Hot reload — no restart needed
- Import/export CLI commands

### 21. Canonicalized Path Blocking
`is_path_blocked()` canonicalizes before checking — catches traversal at config level.

---

## VI. SESSION TRACKING
*(session.rs — 216 lines, storage.rs — 100 lines)*

### 22. In-Memory Session State
Tracks: action_count, files_read, files_written, last_tool, complexity_history (100 entries), manifest (200 decisions), failures.

### 23. SESSION.DB — LMDB Persistence
Serialized to JSON in LMDB under `current_session` key. ACID-compliant, crash-safe.

---

## VII. LMDB VIRTUAL FILESYSTEM
*(fs.rs — 666 lines)*

### 24. Hybrid Storage Architecture
- ≤ 1MB: inline in LMDB (zero-copy via mmap)
- > 1MB: disk blobs with LMDB metadata pointer
- SHA-256 checksums, 4GB map size

### 25. Full POSIX-Like Operations
exists, stat, read, write, mkdir, mkdir_p, ls, rm, rm_rf, rename (atomic).

### 26. FileMetadata
file_type, size, mode, created/modified, checksum, version (auto-increment), vector_id (reverse RAG link), real_path (disk blob pointer).

### 27. Vector Index — bridges filesystem to brain: `path ↔ vector_id`

---

## VIII. LMDB PARTITION ROUTING — Virtual Mount Points
*(mcp.rs — routing section)*

### 28. Multi-LMDB Mount Architecture
| Virtual Path | Backend | R/W |
|-------------|---------|-----|
| / (root) | SPF_FS.DB | R/W |
| /config/ | CONFIG.DB | Read-only |
| /tmp/ | LIVE/TMP/ | Device-backed |
| /projects/ | LIVE/PROJECTS/ | Device-backed |
| /home/agent/ | AGENT_STATE.DB | Read-only |

### 29. Config Virtual Files
/config/version, /config/mode, /config/tiers, /config/formula, /config/weights, /config/paths, /config/patterns

---

## IX. PROJECTS REGISTRY
*(projects_db.rs — 89 lines)*

### 30. PROJECTS.DB — LMDB Registry
Generic KV store for project metadata. get/set/delete/list_all. 20MB map. Starts empty.

---

## X. TMP DATABASE — Project Trust & Tracking
*(tmp_db.rs — 609 lines)*

### 31. 4 Internal LMDB Databases
- **projects** — canonical_path → Project struct
- **access_log** — timestamped file access records
- **resources** — per-project byte/file/command counters
- **active** — currently active project path

### 32. 5-Level Trust System
| Level | Value | Access |
|-------|-------|--------|
| Untrusted | 0 | All denied |
| Low | 1 | Read/Glob/Grep only |
| Medium | 2 | All except Bash |
| High | 3 | All tools |
| Full | 4 | No restrictions |

### 33. Per-Project Controls
allowed_tools, denied_tools, protected_paths, max_write_size, max_writes_per_session, session_writes counter, requires_activation flag, lifetime resource tracking.

### 34. Operation Validation Pipeline
Project lookup → Activation check → Trust level → Protected paths → Write size → Session rate limit

---

## XI. AGENT STATE — Persistent Memory
*(agent_state.rs — 684 lines)*

### 35. AGENT_STATE.DB — 4 Internal Databases
- **memory** — id → MemoryEntry
- **sessions** — session_id → SessionContext
- **state** — generic KV
- **tags** — tag:name → list of memory IDs

### 36. 6-Type Memory System
| Type | Expiry |
|------|--------|
| Preference | Never |
| Fact | Never |
| Instruction | Never |
| Context | Configurable |
| Working | Session-bound |
| Pinned | Never |

### 37. Session Context Continuity
Parent session linking, active project, files modified, total complexity, summary.

### 38. Tag-Based Memory Index — retrieve memories by category tag

---

## XII. DISPATCH — Unified Routing Protocol
*(dispatch.rs — 506 lines)*

### 39. Single Entry Point for All Tool Calls
- `dispatch::call()` — converges stdio, HTTP, mesh, transformer, pipeline sources
- Gate called at entry before execution (`gate::process()`)
- Execution inside `handle_tool_call` — pure routing, no gate logic

### 40. Source Classification
- **Stdio** — blocking listener lock (local user)
- **Http/Mesh/Transformer/Pipeline** — timed try_lock with SERVER_BUSY fallback

### 41. Listener Pattern
Layers register as `DispatchListener`. Dispatch fires `on_response()` with tool name, source, status, and duration. Dispatch never imports listeners — loose coupling.

### 42. FLINT Interception
- Pre-execution brain query: `process_request()` queries brain for relevant context
- Post-execution store/enrich: `process_result()` stores results, triggers auto-train

---

## XIII. FLINT MEMORY ROUTER
*(flint_memory.rs — 1,065 lines)*

### 43. Background Memory Thread
Always running, no user session required:
- GateTrainingCollector → FLINT scores → route → brain_store()
- Watches knowledge/ drop folder → auto-index

### 44. Tiered Memory Promotion (MB-FT)
24hr → 7day → pinned. FLINT scores Working memories by relevance × access_count.
Top 20% promoted. >50% active in window → promote all + touches.

### 45. Build Anchor Context (R3-04 to R3-07)
- Brain-assisted source context for Write/Edit
- Read tracking (R3-06): first read = full passthrough, subsequent = compressed
- Agent Read Interface: blocks brain WRITE from Stdio

### 46. Auto-Train Engine
Every hour: expire → Working→Fact → Fact→Pinned → auto-train if 16+ tlog signals.

---

## XIV. TENSOR ENGINE — Pure Rust Math
*(tensor.rs — 772 lines)*

### 47. N-Dimensional Tensor (f32)
Row-major (C-order) storage with shape metadata. Supports arbitrary dimensions.

### 48. Operations Suite
Add, subtract, multiply, divide, matmul, reshape, permute, softmax, relu, layer_norm, embedding.

### 49. ARM NEON SIMD Acceleration
With scalar fallback for non-ARM platforms.

### 50. Backward Pass Support
Gradient computation for all operations — enables training.

---

## XV. TOKENIZER — BPE Vocabulary
*(tokenizer.rs — 381 lines)*

### 51. Byte-Pair Encoding Tokenizer
Pure Rust, no external dependencies. Trains on SPF corpus (brain data, source code, rules).

### 52. Special Tokens
[PAD], [BOS], [EOS], [UNK], [TOOL], [GATE], [USER], [SPF], [ALLOWED], [BLOCKED]

### 53. Vocabulary Size: 8,192 tokens (SPF Writer default)

---

## XVI. TRANSFORMER MODEL
*(attention.rs — 517 lines, ffn.rs — 277 lines, encoder.rs — 404 lines, decoder.rs — 508 lines)*

### 54. Encoder-Decoder Architecture
- d_model=256, n_heads=8, n_layers=6, d_ff=1024
- ~5M parameters total
- Configurable: Writer (tool execution) vs Researcher (chat/analysis)

### 55. Multi-Head Self-Attention
Scaled dot-product attention with KV cache for generation. Supports masking for causal mode.

### 56. Position-wise Feed-Forward Network
2-layer MLP: linear → ReLU → linear. Expansion ratio 4×.

### 57. Encoder Stack
N layers, each: self-attention → add&norm → FFN → add&norm.

### 58. Decoder Stack
N layers, each: masked self-attention → add&norm → cross-attention → add&norm → FFN → add&norm.
Cached decoder layers for O(1) autoregressive generation.

---

## XVII. FULL TRANSFORMER MODEL
*(transformer.rs — 552 lines)*

### 59. Complete Model Assembly
Encoder + decoder tied together with embedding projection and token output head.

### 60. Forward Cache
Cached activations from forward pass for backward pass (train-on-copy pattern).

### 61. Two Configurations
- **Writer**: tool selection, gate prediction, task execution
- **Researcher**: conversational analysis, question answering

Both share identical architecture — only training data differs.

---

## XVIII. TRAINING ENGINE
*(train.rs — 1,064 lines)*

### 62. Backward Passes for All Layers
Cross-entropy loss → decoder backward → encoder backward → embedding backward.

### 63. Attention Backpropagation
5-step gradient flow: dV → dP → dS (softmax Jacobian) → dQ → dK.

### 64. AdamW Optimizer
Decoupled weight decay (Loshchilov & Hutter 2017). Per-parameter adaptive moments.

### 65. LayerNorm Backward
Gradient computation through normalization layer.

### 66. Train-on-Copy Pattern
Atomic weight merge — inference never blocked by training.

---

## XIX. ONLINE LEARNING ENGINE
*(learning.rs — 645 lines)*

### 67. Elastic Weight Consolidation (EWC)
Prevents catastrophic forgetting by penalizing changes to important weights. Fisher Information Matrix persisted to LMDB. Lambda = 0.4.

### 68. Experience Replay Buffer
10,000 slots (50/50 new:samples mix). False-positive examples locked — never evicted.

### 69. Gate-as-Teacher
Every gate approve/deny is a supervised training label. FLINT learns to predict gate decisions.

---

## XX. GATE TRAINING BRIDGE
*(gate_training.rs — 1,302 lines)*

### 70. Training Signal Collection
Every gate decision captured as TrainingSignal with context, severity, and result.

### 71. Confusion Matrix
Tracks TP/TN/FP/FN rates. Persisted to LMDB. Used for alignment scoring.

### 72. False Positive Handling
- FP detection + reporting
- Severity-weighted signals (4× FP, 6× repeated FP)
- FP-locked buffer slots — never evicted
- Result-based FP candidate flagging

### 73. Evil Detection Layer (4-Tier Moral Framework)
Based on MORAL_FRAMEWORK.txt:
- Tier 1: Deception (self-serving lies)
- Tier 2: Exploitation (power vs powerless)
- Tier 3: Destruction (deliberate harm)
- Tier 4: Systemic Evil (corruption of trust)
Evil signals receive 4-8× training weight amplification.

### 74. Sequence Context
Last N tool calls tracked for pattern detection — identifies multi-step attack chains.

---

## XXI. FLINT TRANSFORMER MCP TOOLS
*(transformer_tools.rs — 1,052 lines)*

### 75. Transformer State Management
Singleton `TransformerState` — model loading, checkpoint save/load, inference, training.

### 76. Checkpoint System (CP-1/CP-2)
- Save after training batch
- Load on startup — confirmed persistent (step ≠ 0 on boot)
- LIVE/MODELS/writer_v1.spfc

### 77. Training Tools
- `spf_flint_train_evil` — mark tool call as evil/harmful
- `spf_flint_train_good` — mark tool call as good/safe
- Auto-train: 16+ tlog signals OR 1hr interval

### 78. FLINT Status & Metrics
Query current step, loss, alignment, learning rate, EWC lambda, replay buffer occupancy.

---

## XXII. FRAMING PROTOCOL — Persistent Streams
*(framing.rs — 498 lines)*

### 79. Length-Prefixed Message Framing
Replaces one-shot read-to-end pattern. Enables persistent bidirectional mesh streams.

### 80. 8 Stream Types
| Type | Hex | Purpose |
|------|-----|---------|
| ToolRpc | 0x01 | Tool calls (JSON-RPC) |
| ChatText | 0x02 | Text chat |
| VoiceAudio | 0x03 | Opus voice frames |
| PipelineTask | 0x04 | Orchestrator → worker |
| PipelineResult | 0x05 | Worker → orchestrator |
| BrainSync | 0x06 | Memory synchronization |
| WeightSync | 0x07 | Model weight sharing |
| Control | 0x08 | Session control |

### 81. Frame Format
`[1-byte type][4-byte length BE][payload bytes]`. Max frame: 10MB.
Legacy detection: first byte '{' = old JSON-RPC, 0x01-0x08 = framed.

---

## XXIII. MESH NETWORK TRANSPORT
*(mesh.rs — 1,171 lines)*

### 82. P2P QUIC Mesh via iroh
Ed25519 identity doubles as iroh EndpointId. Inbound: peer connects → JSON-RPC → dispatch::call(Source::Mesh). Outbound: tool call → QUIC stream → peer's ALPN.

### 83. Persistent Bidirectional Streams
`call_peer_stream()` for framed persistent connections. `stream_router()` dispatches by StreamType.

### 84. Discovery Modes
- **auto** — mDNS (LAN) + Pkarr DHT (internet)
- **local** — mDNS only
- **manual** — explicit trust groups only

### 85. Trust Model — Default-deny
Only peers in `groups/*.keys` are accepted. No anonymous connections.

### 86. Identity Integration
Ed25519 signing key → iroh SecretKey via direct Curve25519 byte mapping.

---

## XXIV. IDENTITY — Cryptographic Keys
*(identity.rs — 435 lines)*

### 87. Ed25519 Key Pair Management
Unique identity generated on first boot. Files:
- `identity.key` — private key (hex, 64 chars)
- `identity.pub` — public key (hex, 64 chars)
- `identity.seal` — filesystem-bound clone detection

### 88. Clone Detection
If filesystem seal breaks → archive old identity, generate new, preserve settings.

### 89. Trusted Peer Management
- `groups/*.keys` — one public key per line (simple trust list)
- `groups/*.json` — peer info with addresses, name, role

### 90. Boot Integrity Check (SEC-3)
Verifies .mcp.json routing, scans for rogue agent configs.

---

## XXV. PIPELINE — Batch Task Execution
*(pipeline.rs — 1,107 lines)*

### 91. Pipeline Protocol
Batch submit, chain execution, backpressure handling.

### 92. PipelineTask Type
- task_id, tool, arguments, mode (Batch/Chain)
- Optional chain_next — output of one task feeds next
- chain_pipe_field — which output field to pipe to next input

### 93. PipelineResult Type
- task_id, success (bool), output, error, duration_ms
- Links back to original task for audit trail

### 94. Chain Execution
Tasks linked via `chain_next`. Sequential — result of current feeds input of next.
`build_chain()` from task list → linked structure.

### 95. Worker Dispatch
Tasks routed to mesh workers via StreamType 0x04/0x05.
Results processed via `dispatch::call(Source::Pipeline)`.

### 96. 14 Unit Tests
Chain building, batch processing, result recording, backpressure simulation.

---

## XXVI. NETWORK POOL
*(network.rs — 526 lines)*

### 97. Full Pool Management
PoolState, WorkerStatus, ProofOfWork types. Roles: NetAdmin, Worker, Thinker.

### 98. NetAdmin Orchestrator
Distributes tasks to idle workers over QUIC mesh. Collects results. Logs proof of work via `session.record_manifest_detailed()`.

### 99. Worker Lifecycle
Join pool → accept tasks → execute → return results → proof of work receipt.

---

## XXVII. WORKER MODE
*(worker.rs — 494 lines)*

### 100. Headless Inference Node
Runs transformer without user session:
1. Load config + checkpoint
2. Start mesh (accept pipeline streams)
3. Start HTTP (monitoring)
4. Loop: receive task → execute → return
5. Capture training signals

### 101. CLI: `spf-smart-gate worker [--role writer|researcher]`

---

## XXVIII. ORCHESTRATOR STATE
*(orchestrator.rs — 225 lines)*

### 102. Role Management
AgentRole enum: NetAdmin, Worker, Thinker, Orchestrator. Dynamic role switching.

### 103. Pool State Tracking
Worker registration, idle/busy counts, task assignment tracking.

---

## XXIX. CHAT ENGINE
*(chat.rs — 1,286 lines)*

### 104. Text Chat Protocol
Messages over StreamType::ChatText (0x02) + local LMDB storage.

### 105. Message Format
id, from, to, text, timestamp, conversation_id, MessageType (UserText/AgentResponse/System/ToolResult).

### 106. Conversation Tracking
- Context window (last N messages as transformer input)
- Room-based routing (1:1 and group)
- LMDB persistence with "chat:" key prefix

### 107. FLINT Chat Participation (Block QQ)
- Rate-limited auto-response (1 per 5 seconds per peer)
- Decoder-only/causal mode for conversational responses

### 108. MCP Tools
- `spf_chat_send` — send message to peer/conversation
- `spf_chat_history` — retrieve message history with limit
- `spf_chat_rooms` — list all active conversations

---

## XXX. VOICE PIPELINE
*(voice.rs — 2,071 lines)*

### 109. Architecture
AudioInput → encode → VoiceFrame → mesh (0x03) → decode → AudioOutput.
TTS: text → speech → mesh. STT: mesh → text → ChatEngine.

### 110. TTS: espeak-ng FFI In-Process
Zero external process. FFI link to libespeak-ng.so. Light mode = espeak only. Rich mode = Piper ONNX (voice-tts feature).

### 111. Opus Codec
Static linkage (libopus.a). No runtime C deps beyond espeak-ng.

### 112. Voice Mode Selection
- Agent TTS: Light (espeak-ng FFI) or Rich (Piper ONNX)
- Agent STT: Light (text input) or Rich (Whisper via candle)
- Peer audio quality: Light (12kHz) or Rich (24kHz)

### 113. Call Management
Outgoing/incoming calls, P2P P2P call protocol (ring/accept/reject/end/status).

### 114. Voice Team Channels
Group audio channels for team communication.

### 115. MCP Tools
- `spf_voice_call` — start/accept/reject/end voice calls
- `spf_voice_mode` — start/stop/speak/listen/pipe audio
- `spf_voice_team` — create/join/leave team channels

---

## XXXI. REVERSE PROXY BROWSER
*(browser.rs — 934 lines)*

### 116. Architecture
1. Agent calls `spf_web_navigate(url)`
2. Browser opens `http://127.0.0.1:PORT/proxy?url=TARGET`
3. ProxyEngine fetches page, injects control JS, serves it
4. Injected JS opens WebSocket to /ws/browser
5. Agent sends commands (click/fill/eval) through BrowserSession
6. JS executes, returns results via same path

### 117. ProxyEngine
Fetches external pages, injects control JavaScript, strips CSP headers.
Sets `<base href>` for relative URL resolution — no URL rewriting needed.

### 118. BrowserSession
Manages WS channel, command queue, timeout handling.
Commands: click, fill, eval, navigate, screenshot, design, page.

### 119. SSRF Protection
All target URLs validated through `web::validate_url()` before proxying.

### 120. MCP Tools
- `spf_web_connect` — initialize browser engine
- `spf_web_navigate` — navigate to URL
- `spf_web_page` — structured page overview
- `spf_web_click` — click element by CSS selector
- `spf_web_select` — query elements by CSS selector
- `spf_web_fill` — type text into form field
- `spf_web_eval` — execute JavaScript expression
- `spf_web_screenshot` — capture screenshot
- `spf_web_design` — extract design brief

---

## XXXII. WEB ACCESS
*(web.rs — 469 lines)*

### 121. Dual Search Backend
- Brave Search API (if BRAVE_API_KEY set)
- DuckDuckGo HTML fallback

### 122. Web Fetch — HTML-to-Text Conversion
Fetches URL, strips HTML, returns clean text. 30s timeout.

### 123. File Download
Gated through SPF — destination path validated.

### 124. HTTP API Client
Full REST: GET/POST/PUT/DELETE/PATCH. Custom headers and body.

---

## XIII. BRAIN LOCAL — In-Process Vector Search
*(brain_local.rs — 344 lines)*

### 125. stoneshell-brain Integration
Embeds MiniLM model (all-MiniLM-L6-v2) for local vector search.
Functions: search, recall, store, index, list, status.

### 126. Retry Logic (RC-1)
3 attempts with 2s delay on brain load failure.

---

## XXXIV. CHECKPOINT SYSTEM
*(checkpoint.rs — 483 lines)*

### 127. Binary Checkpoint Format
`[SPFC magic:4][version:4][num_tensors:4][headers][data]`

### 128. Delta Format for Mesh Weight Sharing
Sends only changed weights between nodes — bandwidth efficient.

### 129. Versioned Checkpoints
Rollback safety — format version tracked.

---

## XXXV. UTF-8 SAFETY UTILITIES
*(utf8_safe.rs — 101 lines)*

### 130. Lossy Text Conversion
Binary-safe UTF-8 handling. Binary files get fingerprint info, not corrupt text.

---

### XXXVI. INTEGRATION TESTS
*(integration_tests.rs — 763 lines)*

### 131. Full Build Verification
Tests for gate pipeline, complexity calculation, dispatch routing, mesh framing, pipeline chains, transformer inference, checkpoint round-trip.

---

## XXXVII. HOOK SYSTEM — 31 Shell Hooks
*(31 files in hooks/)*

### 132. Native Tool Blocking Hooks (9 hooks)
Exit code 1, hard-block: Read, Edit, Write, Bash, Glob, Grep, WebFetch, WebSearch, NotebookEdit.

### 133. MCP Tool Tracking Hooks (20 hooks)
Exit code 0, log to spf.log: all 83 MCP tools grouped by category.

### 134. Lifecycle Hooks
- session-start — resets state, injects SPF formula
- session-end — handoff note, brain checkpoint
- stop-check — saves state, prevents infinite loop
- user-prompt — prompt complexity scoring
- post-action — updates STATUS.txt, triggers brain checkpoint
- post-failure — logs to failures.log

---

## XXXVIII. STATE AND OBSERVABILITY

### 135. STATUS.txt — Memory Triad System 2
Auto-updated after every tool action. Current state, files read/written, Build Anchor ratio.

### 136. spf.log — Full Action Log
Timestamped log with rotation (0.5GB max, 5,000 lines, one backup).

### 137. failures.log — Dedicated Failure Log
Separate file for failed tool calls.

### 138. Brain Checkpoint on Writes
post-action.sh auto-stores to brain on Write/Edit. Async, tagged: spf, checkpoint, tool_name.

### 139. LEARNING PIPELINE — ACTIVE
- PRE: init_brain() + index_knowledge_docs() + index_spf_sources()
- DURING (30s loop): GateTrainingCollector → FLINT scores → route_signals → brain_store()
- AFTER (1hr loop): expire → Working→Fact → Fact→Pinned → auto-train (16+ tlog or 1hr)

---

## XXXIX. BRAIN STATE (verified 2026-04-05)

### 140. Collections
| Collection | Docs | Purpose |
|------------|------|---------|
| spf_source | 465 | Source code chunks |
| flint_training | 2,013 | Training signals |
| flint_results | 448 | Gate decisions |
| default | 392 | General knowledge |
| flint_knowledge | 49 | FLINT facts |
| session_state | 4 | Current session |
| flint_episodic | 2 | Episodic memory |

Total: 3,371 docs | Storage: 31.41 MB | Model: all-MiniLM-L6-v2

---

## XL. PERMISSIONS AND ACCESS CONTROL

### 141. 3-Layer Defense
| Layer | Mechanism | Bypass? |
|-------|-----------|---------|
| 1. Permissions Deny | settings.json denies native tools | Claude enforced |
| 2. Hook Blocking | pre hooks exit 1 on native tools | Cannot bypass |
| 3. Gate Validation | Compiled Rust allowlist + path blocking | Compiled binary |

### 142. Self-Protection (Dynamic from spf_root)
- SPFsmartGATE/src/ — own source code
- Cargo.toml, Cargo.lock — dependencies
- LIVE/SPF_FS/blobs/ — vfs blob storage
- Home/.claude/ — Claude settings
- System dirs: /etc, /system, /usr, PREFIX

### 143. Config Get/Set Removed from MCP
Config changes are CLI-only. AI cannot modify its own config or invoke the gate directly.

---

## XLI. CLI COMMANDS

### 144. Binary CLI
- `spf-smart-gate serve` — MCP stdio server
- `spf-smart-gate status` — Gateway status
- `spf-smart-gate session` — Full session state
- `spf-smart-gate reset` — Fresh session
- `spf-smart-gate worker [--role writer|researcher]` — Headless worker mode
- `spf-smart-gate init-config` — Initialize CONFIG.DB
- `spf-smart-gate refresh-paths` — Update CONFIG.DB paths (--dry-run)
- `spf-smart-gate fs-import/fs-export` — LMDB ↔ Device
- `spf-smart-gate config-import/config-export` — JSON ↔ CONFIG.DB
- `spf-smart-gate gate` — One-shot gate check
- `spf-smart-gate calculate` — Complexity calc only

---

## XLII. ARCHITECTURE PROPERTIES

### 145. Multi-Database LMDB Architecture
| # | Database | Location | Purpose |
|---|----------|----------|---------|
| 1 | SPF_FS.DB | LIVE/SPF_FS/ | Virtual filesystem + blobs |
| 2 | CONFIG.DB | LIVE/CONFIG/ | Path rules, tiers, formula |
| 3 | SESSION.DB | LIVE/SESSION/ | Session state persistence |
| 4 | PROJECTS.DB | LIVE/PROJECTS/ | Project registry |
| 5 | TMP.DB | LIVE/TMP/ | Trust, access logs, active project |
| 6 | AGENT_STATE.DB | LIVE/LMDB5/ | Memory, sessions, chat |
| 7 | BRAIN | LIVE/TMP/stoneshell-brain/ | Vector search (chromadb) |

### 146. Zero-Dependency Path Resolution
`spf_root()` walks up from binary location for Cargo.toml → SPF_ROOT env → HOME/SPFsmartGATE. Cached via OnceLock.

### 147. MCP Protocol v2024-11-05
JSON-RPC 2.0 over stdio. Compatible with any MCP client. 83 agent tools (8 user-only tools excluded).

### 148. Cross-Platform Portable
Android ARM64, Linux x86_64/ARM64, macOS ARM/Intel. Zero hardcoded paths. All resolved from binary location.

### 149. Multi-Agent Network
- Ed25519 identity (CL-1: self-test at boot)
- QUIC mesh transport (iroh)
- Qwen tool prefix aliasing (QW-1/QW-2)
- API Session Layer — full duplex agent-to-agent encrypted sessions (PP-2)

---

## XLIII. FLINT AI STATUS

### 150. Training Status (live, 2026-04-05)
- Step: 116 | Batches completed: 6
- Gate alignment: 81.25% | Average loss: 0.648
- EWC lambda: 0.4 | Learning rate: 1e-4
- Online learning: ON | Replay buffer: 10,000 slots
- Checkpoint interval: 1,000 steps
- Checkpoint: LIVE/MODELS/writer_v1.spfc

### 151. Model Architecture
- d_model: 256 | n_heads: 8 | n_layers: 6 | d_ff: 1,024
- Vocab: 8,192 | Params: ~5M
- Writer + Researcher configs

---

## XLIV. SECURITY EXCEPTIONS (Known Gaps)

| Gap | Description | Remediation |
|-----|-------------|-------------|
| GAP-1 | ChatText → handle_mesh_chat() — no gate routing | SEC-CHAT pending |
| GAP-2 | VoiceAudio — intentional, audio frames only | Accepted |
| GAP-3 | /proxy + /proxy/asset — SSRF only, bypasses dispatch | WB-2 pending |
| GAP-4 | /ws/browser — no gate/FLINT | SEC-WS pending |

---

*Generated from source code analysis — verified 2026-04-05*
*8,245 → 18,500+ lines | 88 → 150+ features | 31 → 42 modules | 6 → 7 databases*
*New since February 2026: FLINT Transformer AI, Mesh Network, Chat, Voice, Browser, Pipeline, Network Pool, Channel Hub*