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stone — All Rights Reserved*
4
+ *Updated: 2026-04-05 (full audit against LIVE src/)*
5
+
6
+ ---
7
+
8
+ ## I. THE GATE — Primary Enforcement Engine
9
+ *(gate.rs — 493 lines)*
10
+
11
+ The core pipeline every single tool call passes through.
12
+
13
+ ### 1. 5-Stage Gate Pipeline
14
+ Every tool call goes through this exact sequence:
15
+ 1. **Calculate** complexity (C value, tier, allocation)
16
+ 2. **CRITICAL escalation** — if tier = CRITICAL, force max protocol
17
+ 3. **Validate** against compiled rules (paths, anchor, whitelist, dangerous commands)
18
+ 4. **Content inspection** on Write/Edit operations
19
+ 5. **Return** allow/block decision with full audit trail
20
+
21
+ ### 2. GateDecision Struct
22
+ Every gate result includes:
23
+ - allowed: bool — final verdict
24
+ - tool: String — which tool was called
25
+ - complexity: ComplexityResult — full C breakdown
26
+ - warnings: Vec<String> — non-blocking issues
27
+ - errors: Vec<String> — blocking violations
28
+ - message: String — human-readable summary
29
+
30
+ ### 3. Source-Centric Decisions
31
+ - Gate receives `Source` enum (Stdio/Http/Mesh/Transformer/Pipeline)
32
+ - Decision context includes peer identity, role, trust level
33
+
34
+ ---
35
+
36
+ ## II. COMPLEXITY CALCULATOR — The SPF Formula
37
+ *(calculate.rs — 416 lines)*
38
+
39
+ ### 4. 4-Factor Exponential Complexity Formula
40
+
41
+ C = (basic ^ 1) + (dependencies ^ 7) + (complex ^ 10) + (files × 10)
42
+
43
+ - basic to the 1st — linear base cost
44
+ - deps to the 7th — cascading dependency penalty (2→128, 3→2187, 5→78125)
45
+ - complex to the 10th — nuclear escalation (3→59049, 4→1048576)
46
+ - files times 10 — linear file count penalty
47
+
48
+ ### 5. Master Allocation Formula
49
+
50
+ a_optimal(C) = W_eff × (1 - 1/ln(C + e))
51
+
52
+ - W_eff = 40,000 tokens (effective working memory)
53
+ - Maps C → optimal analysis token budget
54
+
55
+ ### 6. 4-Tier Classification
56
+ | Tier | C Range | Analyze | Build |
57
+ |------|---------|---------|-------|
58
+ | SIMPLE | < 500 | 40% | 60% |
59
+ | LIGHT | < 2,000 | 60% | 40% |
60
+ | MEDIUM | < 10,000| 75% | 25% |
61
+ | CRITICAL | > 10,000| 95% | 5% |
62
+
63
+ ### 7. Per-Tool Weight Profiles
64
+ | Category | Basic | Deps | Complex | Files |
65
+ |----------|-------|------|---------|-------|
66
+ | Read | 5 | 1 | 0 | 1 |
67
+ | Search | 8 | 2 | 0 | 1 |
68
+ | Edit | 10 | 2 | 1 | 1 |
69
+ | Write | 20 | 2 | 1 | 1 |
70
+ | Bash (dangerous) | 50 | 5 | 2 | 1 |
71
+
72
+ ### 8. Dynamic Complexity Boosters
73
+ - Content size escalation (+1 per threshold: 200/1000/5000 bytes)
74
+ - Risk keyword detection (delete, drop, force, unsafe, rm, sudo)
75
+ - Architectural file detection (config, main, lib, Cargo.toml, yaml, etc.)
76
+ - Scope estimation (glob patterns, find, xargs)
77
+
78
+ ---
79
+
80
+ ## III. VALIDATION ENGINE — Compiled Rules
81
+ *(validate.rs — 1,481 lines)*
82
+
83
+ ### 9. Compiled Write Allowlist
84
+ Only two paths accept writes: LIVE/PROJECTS/PROJECTS/ and LIVE/TMP/TMP/
85
+ Resolved dynamically from `spf_root()` — portable, compiled-in, runtime-immutable.
86
+
87
+ ### 10. Symlink-Aware Path Resolution
88
+ - `canonicalize()` for existing files, parent canonicalize for new files
89
+ - Filenames with `..` rejected outright
90
+ - Broken symlinks = blocked
91
+
92
+ ### 11. Build Anchor Protocol
93
+ - Hard mode: must read file before edit/overwrite → violation = BLOCKED
94
+ - Per-file tracking via `session.files_read`
95
+
96
+ ### 12. Dangerous Command Detection
97
+ Blocked patterns: `rm -rf`, `dd if=`, `> /dev/`, `chmod 777`, `curl|sh`, `wget|sh`
98
+
99
+ ### 13. /tmp Access Block — hard block on all platforms (SPF policy)
100
+
101
+ ### 14. File Size Limit — max_write_size default 100,000 bytes
102
+
103
+ ---
104
+
105
+ ## IV. CONTENT INSPECTION — Deep Scan
106
+ *(inspect.rs — 253 lines)*
107
+
108
+ ### 15. Credential Detection (20 patterns)
109
+ API keys, GitHub tokens, GitLab PATs, Slack tokens, PEM private keys, hardcoded credentials.
110
+
111
+ ### 16. Shell Injection Detection
112
+ Command substitution, backtick exec, eval/exec statements (skipped for code files).
113
+
114
+ ### 17. Path Traversal & Blocked Reference Detection
115
+ Scans content for `../` sequences and references to blocked paths.
116
+
117
+ ### 18. Context-Aware Inspection
118
+ Code files (.rs/.py/.js/.ts/.sh/.json/.toml) skip shell injection — only credentials, traversal, blocked refs checked.
119
+
120
+ ---
121
+
122
+ ## V. CONFIGURATION SYSTEM
123
+ *(config.rs — 917 lines, config_db.rs — 797 lines)*
124
+
125
+ ### 19. SpfConfig — Master Configuration Struct
126
+ All settings: enforce_mode, paths, max_write_size, tiers, formula, weights, dangerous_commands, git_force_patterns.
127
+
128
+ ### 20. CONFIG.DB — LMDB-Backed Configuration
129
+ - Namespaced key-value: `namespace:key` → JSON value
130
+ - Path rules DB, Dangerous patterns DB with severity (1-10)
131
+ - Hot reload — no restart needed
132
+ - Import/export CLI commands
133
+
134
+ ### 21. Canonicalized Path Blocking
135
+ `is_path_blocked()` canonicalizes before checking — catches traversal at config level.
136
+
137
+ ---
138
+
139
+ ## VI. SESSION TRACKING
140
+ *(session.rs — 216 lines, storage.rs — 100 lines)*
141
+
142
+ ### 22. In-Memory Session State
143
+ Tracks: action_count, files_read, files_written, last_tool, complexity_history (100 entries), manifest (200 decisions), failures.
144
+
145
+ ### 23. SESSION.DB — LMDB Persistence
146
+ Serialized to JSON in LMDB under `current_session` key. ACID-compliant, crash-safe.
147
+
148
+ ---
149
+
150
+ ## VII. LMDB VIRTUAL FILESYSTEM
151
+ *(fs.rs — 666 lines)*
152
+
153
+ ### 24. Hybrid Storage Architecture
154
+ - ≤ 1MB: inline in LMDB (zero-copy via mmap)
155
+ - > 1MB: disk blobs with LMDB metadata pointer
156
+ - SHA-256 checksums, 4GB map size
157
+
158
+ ### 25. Full POSIX-Like Operations
159
+ exists, stat, read, write, mkdir, mkdir_p, ls, rm, rm_rf, rename (atomic).
160
+
161
+ ### 26. FileMetadata
162
+ file_type, size, mode, created/modified, checksum, version (auto-increment), vector_id (reverse RAG link), real_path (disk blob pointer).
163
+
164
+ ### 27. Vector Index — bridges filesystem to brain: `path ↔ vector_id`
165
+
166
+ ---
167
+
168
+ ## VIII. LMDB PARTITION ROUTING — Virtual Mount Points
169
+ *(mcp.rs — routing section)*
170
+
171
+ ### 28. Multi-LMDB Mount Architecture
172
+ | Virtual Path | Backend | R/W |
173
+ |-------------|---------|-----|
174
+ | / (root) | SPF_FS.DB | R/W |
175
+ | /config/ | CONFIG.DB | Read-only |
176
+ | /tmp/ | LIVE/TMP/ | Device-backed |
177
+ | /projects/ | LIVE/PROJECTS/ | Device-backed |
178
+ | /home/agent/ | AGENT_STATE.DB | Read-only |
179
+
180
+ ### 29. Config Virtual Files
181
+ /config/version, /config/mode, /config/tiers, /config/formula, /config/weights, /config/paths, /config/patterns
182
+
183
+ ---
184
+
185
+ ## IX. PROJECTS REGISTRY
186
+ *(projects_db.rs — 89 lines)*
187
+
188
+ ### 30. PROJECTS.DB — LMDB Registry
189
+ Generic KV store for project metadata. get/set/delete/list_all. 20MB map. Starts empty.
190
+
191
+ ---
192
+
193
+ ## X. TMP DATABASE — Project Trust & Tracking
194
+ *(tmp_db.rs — 609 lines)*
195
+
196
+ ### 31. 4 Internal LMDB Databases
197
+ - **projects** — canonical_path → Project struct
198
+ - **access_log** — timestamped file access records
199
+ - **resources** — per-project byte/file/command counters
200
+ - **active** — currently active project path
201
+
202
+ ### 32. 5-Level Trust System
203
+ | Level | Value | Access |
204
+ |-------|-------|--------|
205
+ | Untrusted | 0 | All denied |
206
+ | Low | 1 | Read/Glob/Grep only |
207
+ | Medium | 2 | All except Bash |
208
+ | High | 3 | All tools |
209
+ | Full | 4 | No restrictions |
210
+
211
+ ### 33. Per-Project Controls
212
+ allowed_tools, denied_tools, protected_paths, max_write_size, max_writes_per_session, session_writes counter, requires_activation flag, lifetime resource tracking.
213
+
214
+ ### 34. Operation Validation Pipeline
215
+ Project lookup → Activation check → Trust level → Protected paths → Write size → Session rate limit
216
+
217
+ ---
218
+
219
+ ## XI. AGENT STATE — Persistent Memory
220
+ *(agent_state.rs — 684 lines)*
221
+
222
+ ### 35. AGENT_STATE.DB — 4 Internal Databases
223
+ - **memory** — id → MemoryEntry
224
+ - **sessions** — session_id → SessionContext
225
+ - **state** — generic KV
226
+ - **tags** — tag:name → list of memory IDs
227
+
228
+ ### 36. 6-Type Memory System
229
+ | Type | Expiry |
230
+ |------|--------|
231
+ | Preference | Never |
232
+ | Fact | Never |
233
+ | Instruction | Never |
234
+ | Context | Configurable |
235
+ | Working | Session-bound |
236
+ | Pinned | Never |
237
+
238
+ ### 37. Session Context Continuity
239
+ Parent session linking, active project, files modified, total complexity, summary.
240
+
241
+ ### 38. Tag-Based Memory Index — retrieve memories by category tag
242
+
243
+ ---
244
+
245
+ ## XII. DISPATCH — Unified Routing Protocol
246
+ *(dispatch.rs — 506 lines)*
247
+
248
+ ### 39. Single Entry Point for All Tool Calls
249
+ - `dispatch::call()` — converges stdio, HTTP, mesh, transformer, pipeline sources
250
+ - Gate called at entry before execution (`gate::process()`)
251
+ - Execution inside `handle_tool_call` — pure routing, no gate logic
252
+
253
+ ### 40. Source Classification
254
+ - **Stdio** — blocking listener lock (local user)
255
+ - **Http/Mesh/Transformer/Pipeline** — timed try_lock with SERVER_BUSY fallback
256
+
257
+ ### 41. Listener Pattern
258
+ Layers register as `DispatchListener`. Dispatch fires `on_response()` with tool name, source, status, and duration. Dispatch never imports listeners — loose coupling.
259
+
260
+ ### 42. FLINT Interception
261
+ - Pre-execution brain query: `process_request()` queries brain for relevant context
262
+ - Post-execution store/enrich: `process_result()` stores results, triggers auto-train
263
+
264
+ ---
265
+
266
+ ## XIII. FLINT MEMORY ROUTER
267
+ *(flint_memory.rs — 1,065 lines)*
268
+
269
+ ### 43. Background Memory Thread
270
+ Always running, no user session required:
271
+ - GateTrainingCollector → FLINT scores → route → brain_store()
272
+ - Watches knowledge/ drop folder → auto-index
273
+
274
+ ### 44. Tiered Memory Promotion (MB-FT)
275
+ 24hr → 7day → pinned. FLINT scores Working memories by relevance × access_count.
276
+ Top 20% promoted. >50% active in window → promote all + touches.
277
+
278
+ ### 45. Build Anchor Context (R3-04 to R3-07)
279
+ - Brain-assisted source context for Write/Edit
280
+ - Read tracking (R3-06): first read = full passthrough, subsequent = compressed
281
+ - Agent Read Interface: blocks brain WRITE from Stdio
282
+
283
+ ### 46. Auto-Train Engine
284
+ Every hour: expire → Working→Fact → Fact→Pinned → auto-train if 16+ tlog signals.
285
+
286
+ ---
287
+
288
+ ## XIV. TENSOR ENGINE — Pure Rust Math
289
+ *(tensor.rs — 772 lines)*
290
+
291
+ ### 47. N-Dimensional Tensor (f32)
292
+ Row-major (C-order) storage with shape metadata. Supports arbitrary dimensions.
293
+
294
+ ### 48. Operations Suite
295
+ Add, subtract, multiply, divide, matmul, reshape, permute, softmax, relu, layer_norm, embedding.
296
+
297
+ ### 49. ARM NEON SIMD Acceleration
298
+ With scalar fallback for non-ARM platforms.
299
+
300
+ ### 50. Backward Pass Support
301
+ Gradient computation for all operations — enables training.
302
+
303
+ ---
304
+
305
+ ## XV. TOKENIZER — BPE Vocabulary
306
+ *(tokenizer.rs — 381 lines)*
307
+
308
+ ### 51. Byte-Pair Encoding Tokenizer
309
+ Pure Rust, no external dependencies. Trains on SPF corpus (brain data, source code, rules).
310
+
311
+ ### 52. Special Tokens
312
+ [PAD], [BOS], [EOS], [UNK], [TOOL], [GATE], [USER], [SPF], [ALLOWED], [BLOCKED]
313
+
314
+ ### 53. Vocabulary Size: 8,192 tokens (SPF Writer default)
315
+
316
+ ---
317
+
318
+ ## XVI. TRANSFORMER MODEL
319
+ *(attention.rs — 517 lines, ffn.rs — 277 lines, encoder.rs — 404 lines, decoder.rs — 508 lines)*
320
+
321
+ ### 54. Encoder-Decoder Architecture
322
+ - d_model=256, n_heads=8, n_layers=6, d_ff=1024
323
+ - ~5M parameters total
324
+ - Configurable: Writer (tool execution) vs Researcher (chat/analysis)
325
+
326
+ ### 55. Multi-Head Self-Attention
327
+ Scaled dot-product attention with KV cache for generation. Supports masking for causal mode.
328
+
329
+ ### 56. Position-wise Feed-Forward Network
330
+ 2-layer MLP: linear → ReLU → linear. Expansion ratio 4×.
331
+
332
+ ### 57. Encoder Stack
333
+ N layers, each: self-attention → add&norm → FFN → add&norm.
334
+
335
+ ### 58. Decoder Stack
336
+ N layers, each: masked self-attention → add&norm → cross-attention → add&norm → FFN → add&norm.
337
+ Cached decoder layers for O(1) autoregressive generation.
338
+
339
+ ---
340
+
341
+ ## XVII. FULL TRANSFORMER MODEL
342
+ *(transformer.rs — 552 lines)*
343
+
344
+ ### 59. Complete Model Assembly
345
+ Encoder + decoder tied together with embedding projection and token output head.
346
+
347
+ ### 60. Forward Cache
348
+ Cached activations from forward pass for backward pass (train-on-copy pattern).
349
+
350
+ ### 61. Two Configurations
351
+ - **Writer**: tool selection, gate prediction, task execution
352
+ - **Researcher**: conversational analysis, question answering
353
+
354
+ Both share identical architecture — only training data differs.
355
+
356
+ ---
357
+
358
+ ## XVIII. TRAINING ENGINE
359
+ *(train.rs — 1,064 lines)*
360
+
361
+ ### 62. Backward Passes for All Layers
362
+ Cross-entropy loss → decoder backward → encoder backward → embedding backward.
363
+
364
+ ### 63. Attention Backpropagation
365
+ 5-step gradient flow: dV → dP → dS (softmax Jacobian) → dQ → dK.
366
+
367
+ ### 64. AdamW Optimizer
368
+ Decoupled weight decay (Loshchilov & Hutter 2017). Per-parameter adaptive moments.
369
+
370
+ ### 65. LayerNorm Backward
371
+ Gradient computation through normalization layer.
372
+
373
+ ### 66. Train-on-Copy Pattern
374
+ Atomic weight merge — inference never blocked by training.
375
+
376
+ ---
377
+
378
+ ## XIX. ONLINE LEARNING ENGINE
379
+ *(learning.rs — 645 lines)*
380
+
381
+ ### 67. Elastic Weight Consolidation (EWC)
382
+ Prevents catastrophic forgetting by penalizing changes to important weights. Fisher Information Matrix persisted to LMDB. Lambda = 0.4.
383
+
384
+ ### 68. Experience Replay Buffer
385
+ 10,000 slots (50/50 new:samples mix). False-positive examples locked — never evicted.
386
+
387
+ ### 69. Gate-as-Teacher
388
+ Every gate approve/deny is a supervised training label. FLINT learns to predict gate decisions.
389
+
390
+ ---
391
+
392
+ ## XX. GATE TRAINING BRIDGE
393
+ *(gate_training.rs — 1,302 lines)*
394
+
395
+ ### 70. Training Signal Collection
396
+ Every gate decision captured as TrainingSignal with context, severity, and result.
397
+
398
+ ### 71. Confusion Matrix
399
+ Tracks TP/TN/FP/FN rates. Persisted to LMDB. Used for alignment scoring.
400
+
401
+ ### 72. False Positive Handling
402
+ - FP detection + reporting
403
+ - Severity-weighted signals (4× FP, 6× repeated FP)
404
+ - FP-locked buffer slots — never evicted
405
+ - Result-based FP candidate flagging
406
+
407
+ ### 73. Evil Detection Layer (4-Tier Moral Framework)
408
+ Based on MORAL_FRAMEWORK.txt:
409
+ - Tier 1: Deception (self-serving lies)
410
+ - Tier 2: Exploitation (power vs powerless)
411
+ - Tier 3: Destruction (deliberate harm)
412
+ - Tier 4: Systemic Evil (corruption of trust)
413
+ Evil signals receive 4-8× training weight amplification.
414
+
415
+ ### 74. Sequence Context
416
+ Last N tool calls tracked for pattern detection — identifies multi-step attack chains.
417
+
418
+ ---
419
+
420
+ ## XXI. FLINT TRANSFORMER MCP TOOLS
421
+ *(transformer_tools.rs — 1,052 lines)*
422
+
423
+ ### 75. Transformer State Management
424
+ Singleton `TransformerState` — model loading, checkpoint save/load, inference, training.
425
+
426
+ ### 76. Checkpoint System (CP-1/CP-2)
427
+ - Save after training batch
428
+ - Load on startup — confirmed persistent (step ≠ 0 on boot)
429
+ - LIVE/MODELS/writer_v1.spfc
430
+
431
+ ### 77. Training Tools
432
+ - `spf_flint_train_evil` — mark tool call as evil/harmful
433
+ - `spf_flint_train_good` — mark tool call as good/safe
434
+ - Auto-train: 16+ tlog signals OR 1hr interval
435
+
436
+ ### 78. FLINT Status & Metrics
437
+ Query current step, loss, alignment, learning rate, EWC lambda, replay buffer occupancy.
438
+
439
+ ---
440
+
441
+ ## XXII. FRAMING PROTOCOL — Persistent Streams
442
+ *(framing.rs — 498 lines)*
443
+
444
+ ### 79. Length-Prefixed Message Framing
445
+ Replaces one-shot read-to-end pattern. Enables persistent bidirectional mesh streams.
446
+
447
+ ### 80. 8 Stream Types
448
+ | Type | Hex | Purpose |
449
+ |------|-----|---------|
450
+ | ToolRpc | 0x01 | Tool calls (JSON-RPC) |
451
+ | ChatText | 0x02 | Text chat |
452
+ | VoiceAudio | 0x03 | Opus voice frames |
453
+ | PipelineTask | 0x04 | Orchestrator → worker |
454
+ | PipelineResult | 0x05 | Worker → orchestrator |
455
+ | BrainSync | 0x06 | Memory synchronization |
456
+ | WeightSync | 0x07 | Model weight sharing |
457
+ | Control | 0x08 | Session control |
458
+
459
+ ### 81. Frame Format
460
+ `[1-byte type][4-byte length BE][payload bytes]`. Max frame: 10MB.
461
+ Legacy detection: first byte '{' = old JSON-RPC, 0x01-0x08 = framed.
462
+
463
+ ---
464
+
465
+ ## XXIII. MESH NETWORK TRANSPORT
466
+ *(mesh.rs — 1,171 lines)*
467
+
468
+ ### 82. P2P QUIC Mesh via iroh
469
+ Ed25519 identity doubles as iroh EndpointId. Inbound: peer connects → JSON-RPC → dispatch::call(Source::Mesh). Outbound: tool call → QUIC stream → peer's ALPN.
470
+
471
+ ### 83. Persistent Bidirectional Streams
472
+ `call_peer_stream()` for framed persistent connections. `stream_router()` dispatches by StreamType.
473
+
474
+ ### 84. Discovery Modes
475
+ - **auto** — mDNS (LAN) + Pkarr DHT (internet)
476
+ - **local** — mDNS only
477
+ - **manual** — explicit trust groups only
478
+
479
+ ### 85. Trust Model — Default-deny
480
+ Only peers in `groups/*.keys` are accepted. No anonymous connections.
481
+
482
+ ### 86. Identity Integration
483
+ Ed25519 signing key → iroh SecretKey via direct Curve25519 byte mapping.
484
+
485
+ ---
486
+
487
+ ## XXIV. IDENTITY — Cryptographic Keys
488
+ *(identity.rs — 435 lines)*
489
+
490
+ ### 87. Ed25519 Key Pair Management
491
+ Unique identity generated on first boot. Files:
492
+ - `identity.key` — private key (hex, 64 chars)
493
+ - `identity.pub` — public key (hex, 64 chars)
494
+ - `identity.seal` — filesystem-bound clone detection
495
+
496
+ ### 88. Clone Detection
497
+ If filesystem seal breaks → archive old identity, generate new, preserve settings.
498
+
499
+ ### 89. Trusted Peer Management
500
+ - `groups/*.keys` — one public key per line (simple trust list)
501
+ - `groups/*.json` — peer info with addresses, name, role
502
+
503
+ ### 90. Boot Integrity Check (SEC-3)
504
+ Verifies .mcp.json routing, scans for rogue agent configs.
505
+
506
+ ---
507
+
508
+ ## XXV. PIPELINE — Batch Task Execution
509
+ *(pipeline.rs — 1,107 lines)*
510
+
511
+ ### 91. Pipeline Protocol
512
+ Batch submit, chain execution, backpressure handling.
513
+
514
+ ### 92. PipelineTask Type
515
+ - task_id, tool, arguments, mode (Batch/Chain)
516
+ - Optional chain_next — output of one task feeds next
517
+ - chain_pipe_field — which output field to pipe to next input
518
+
519
+ ### 93. PipelineResult Type
520
+ - task_id, success (bool), output, error, duration_ms
521
+ - Links back to original task for audit trail
522
+
523
+ ### 94. Chain Execution
524
+ Tasks linked via `chain_next`. Sequential — result of current feeds input of next.
525
+ `build_chain()` from task list → linked structure.
526
+
527
+ ### 95. Worker Dispatch
528
+ Tasks routed to mesh workers via StreamType 0x04/0x05.
529
+ Results processed via `dispatch::call(Source::Pipeline)`.
530
+
531
+ ### 96. 14 Unit Tests
532
+ Chain building, batch processing, result recording, backpressure simulation.
533
+
534
+ ---
535
+
536
+ ## XXVI. NETWORK POOL
537
+ *(network.rs — 526 lines)*
538
+
539
+ ### 97. Full Pool Management
540
+ PoolState, WorkerStatus, ProofOfWork types. Roles: NetAdmin, Worker, Thinker.
541
+
542
+ ### 98. NetAdmin Orchestrator
543
+ Distributes tasks to idle workers over QUIC mesh. Collects results. Logs proof of work via `session.record_manifest_detailed()`.
544
+
545
+ ### 99. Worker Lifecycle
546
+ Join pool → accept tasks → execute → return results → proof of work receipt.
547
+
548
+ ---
549
+
550
+ ## XXVII. WORKER MODE
551
+ *(worker.rs — 494 lines)*
552
+
553
+ ### 100. Headless Inference Node
554
+ Runs transformer without user session:
555
+ 1. Load config + checkpoint
556
+ 2. Start mesh (accept pipeline streams)
557
+ 3. Start HTTP (monitoring)
558
+ 4. Loop: receive task → execute → return
559
+ 5. Capture training signals
560
+
561
+ ### 101. CLI: `spf-smart-gate worker [--role writer|researcher]`
562
+
563
+ ---
564
+
565
+ ## XXVIII. ORCHESTRATOR STATE
566
+ *(orchestrator.rs — 225 lines)*
567
+
568
+ ### 102. Role Management
569
+ AgentRole enum: NetAdmin, Worker, Thinker, Orchestrator. Dynamic role switching.
570
+
571
+ ### 103. Pool State Tracking
572
+ Worker registration, idle/busy counts, task assignment tracking.
573
+
574
+ ---
575
+
576
+ ## XXIX. CHAT ENGINE
577
+ *(chat.rs — 1,286 lines)*
578
+
579
+ ### 104. Text Chat Protocol
580
+ Messages over StreamType::ChatText (0x02) + local LMDB storage.
581
+
582
+ ### 105. Message Format
583
+ id, from, to, text, timestamp, conversation_id, MessageType (UserText/AgentResponse/System/ToolResult).
584
+
585
+ ### 106. Conversation Tracking
586
+ - Context window (last N messages as transformer input)
587
+ - Room-based routing (1:1 and group)
588
+ - LMDB persistence with "chat:" key prefix
589
+
590
+ ### 107. FLINT Chat Participation (Block QQ)
591
+ - Rate-limited auto-response (1 per 5 seconds per peer)
592
+ - Decoder-only/causal mode for conversational responses
593
+
594
+ ### 108. MCP Tools
595
+ - `spf_chat_send` — send message to peer/conversation
596
+ - `spf_chat_history` — retrieve message history with limit
597
+ - `spf_chat_rooms` — list all active conversations
598
+
599
+ ---
600
+
601
+ ## XXX. VOICE PIPELINE
602
+ *(voice.rs — 2,071 lines)*
603
+
604
+ ### 109. Architecture
605
+ AudioInput → encode → VoiceFrame → mesh (0x03) → decode → AudioOutput.
606
+ TTS: text → speech → mesh. STT: mesh → text → ChatEngine.
607
+
608
+ ### 110. TTS: espeak-ng FFI In-Process
609
+ Zero external process. FFI link to libespeak-ng.so. Light mode = espeak only. Rich mode = Piper ONNX (voice-tts feature).
610
+
611
+ ### 111. Opus Codec
612
+ Static linkage (libopus.a). No runtime C deps beyond espeak-ng.
613
+
614
+ ### 112. Voice Mode Selection
615
+ - Agent TTS: Light (espeak-ng FFI) or Rich (Piper ONNX)
616
+ - Agent STT: Light (text input) or Rich (Whisper via candle)
617
+ - Peer audio quality: Light (12kHz) or Rich (24kHz)
618
+
619
+ ### 113. Call Management
620
+ Outgoing/incoming calls, P2P P2P call protocol (ring/accept/reject/end/status).
621
+
622
+ ### 114. Voice Team Channels
623
+ Group audio channels for team communication.
624
+
625
+ ### 115. MCP Tools
626
+ - `spf_voice_call` — start/accept/reject/end voice calls
627
+ - `spf_voice_mode` — start/stop/speak/listen/pipe audio
628
+ - `spf_voice_team` — create/join/leave team channels
629
+
630
+ ---
631
+
632
+ ## XXXI. REVERSE PROXY BROWSER
633
+ *(browser.rs — 934 lines)*
634
+
635
+ ### 116. Architecture
636
+ 1. Agent calls `spf_web_navigate(url)`
637
+ 2. Browser opens `http://127.0.0.1:PORT/proxy?url=TARGET`
638
+ 3. ProxyEngine fetches page, injects control JS, serves it
639
+ 4. Injected JS opens WebSocket to /ws/browser
640
+ 5. Agent sends commands (click/fill/eval) through BrowserSession
641
+ 6. JS executes, returns results via same path
642
+
643
+ ### 117. ProxyEngine
644
+ Fetches external pages, injects control JavaScript, strips CSP headers.
645
+ Sets `<base href>` for relative URL resolution — no URL rewriting needed.
646
+
647
+ ### 118. BrowserSession
648
+ Manages WS channel, command queue, timeout handling.
649
+ Commands: click, fill, eval, navigate, screenshot, design, page.
650
+
651
+ ### 119. SSRF Protection
652
+ All target URLs validated through `web::validate_url()` before proxying.
653
+
654
+ ### 120. MCP Tools
655
+ - `spf_web_connect` — initialize browser engine
656
+ - `spf_web_navigate` — navigate to URL
657
+ - `spf_web_page` — structured page overview
658
+ - `spf_web_click` — click element by CSS selector
659
+ - `spf_web_select` — query elements by CSS selector
660
+ - `spf_web_fill` — type text into form field
661
+ - `spf_web_eval` — execute JavaScript expression
662
+ - `spf_web_screenshot` — capture screenshot
663
+ - `spf_web_design` — extract design brief
664
+
665
+ ---
666
+
667
+ ## XXXII. WEB ACCESS
668
+ *(web.rs — 469 lines)*
669
+
670
+ ### 121. Dual Search Backend
671
+ - Brave Search API (if BRAVE_API_KEY set)
672
+ - DuckDuckGo HTML fallback
673
+
674
+ ### 122. Web Fetch — HTML-to-Text Conversion
675
+ Fetches URL, strips HTML, returns clean text. 30s timeout.
676
+
677
+ ### 123. File Download
678
+ Gated through SPF — destination path validated.
679
+
680
+ ### 124. HTTP API Client
681
+ Full REST: GET/POST/PUT/DELETE/PATCH. Custom headers and body.
682
+
683
+ ---
684
+
685
+ ## XIII. BRAIN LOCAL — In-Process Vector Search
686
+ *(brain_local.rs — 344 lines)*
687
+
688
+ ### 125. stoneshell-brain Integration
689
+ Embeds MiniLM model (all-MiniLM-L6-v2) for local vector search.
690
+ Functions: search, recall, store, index, list, status.
691
+
692
+ ### 126. Retry Logic (RC-1)
693
+ 3 attempts with 2s delay on brain load failure.
694
+
695
+ ---
696
+
697
+ ## XXXIV. CHECKPOINT SYSTEM
698
+ *(checkpoint.rs — 483 lines)*
699
+
700
+ ### 127. Binary Checkpoint Format
701
+ `[SPFC magic:4][version:4][num_tensors:4][headers][data]`
702
+
703
+ ### 128. Delta Format for Mesh Weight Sharing
704
+ Sends only changed weights between nodes — bandwidth efficient.
705
+
706
+ ### 129. Versioned Checkpoints
707
+ Rollback safety — format version tracked.
708
+
709
+ ---
710
+
711
+ ## XXXV. UTF-8 SAFETY UTILITIES
712
+ *(utf8_safe.rs — 101 lines)*
713
+
714
+ ### 130. Lossy Text Conversion
715
+ Binary-safe UTF-8 handling. Binary files get fingerprint info, not corrupt text.
716
+
717
+ ---
718
+
719
+ ### XXXVI. INTEGRATION TESTS
720
+ *(integration_tests.rs — 763 lines)*
721
+
722
+ ### 131. Full Build Verification
723
+ Tests for gate pipeline, complexity calculation, dispatch routing, mesh framing, pipeline chains, transformer inference, checkpoint round-trip.
724
+
725
+ ---
726
+
727
+ ## XXXVII. HOOK SYSTEM — 31 Shell Hooks
728
+ *(31 files in hooks/)*
729
+
730
+ ### 132. Native Tool Blocking Hooks (9 hooks)
731
+ Exit code 1, hard-block: Read, Edit, Write, Bash, Glob, Grep, WebFetch, WebSearch, NotebookEdit.
732
+
733
+ ### 133. MCP Tool Tracking Hooks (20 hooks)
734
+ Exit code 0, log to spf.log: all 83 MCP tools grouped by category.
735
+
736
+ ### 134. Lifecycle Hooks
737
+ - session-start — resets state, injects SPF formula
738
+ - session-end — handoff note, brain checkpoint
739
+ - stop-check — saves state, prevents infinite loop
740
+ - user-prompt — prompt complexity scoring
741
+ - post-action — updates STATUS.txt, triggers brain checkpoint
742
+ - post-failure — logs to failures.log
743
+
744
+ ---
745
+
746
+ ## XXXVIII. STATE AND OBSERVABILITY
747
+
748
+ ### 135. STATUS.txt — Memory Triad System 2
749
+ Auto-updated after every tool action. Current state, files read/written, Build Anchor ratio.
750
+
751
+ ### 136. spf.log — Full Action Log
752
+ Timestamped log with rotation (0.5GB max, 5,000 lines, one backup).
753
+
754
+ ### 137. failures.log — Dedicated Failure Log
755
+ Separate file for failed tool calls.
756
+
757
+ ### 138. Brain Checkpoint on Writes
758
+ post-action.sh auto-stores to brain on Write/Edit. Async, tagged: spf, checkpoint, tool_name.
759
+
760
+ ### 139. LEARNING PIPELINE — ACTIVE
761
+ - PRE: init_brain() + index_knowledge_docs() + index_spf_sources()
762
+ - DURING (30s loop): GateTrainingCollector → FLINT scores → route_signals → brain_store()
763
+ - AFTER (1hr loop): expire �� Working→Fact → Fact→Pinned → auto-train (16+ tlog or 1hr)
764
+
765
+ ---
766
+
767
+ ## XXXIX. BRAIN STATE (verified 2026-04-05)
768
+
769
+ ### 140. Collections
770
+ | Collection | Docs | Purpose |
771
+ |------------|------|---------|
772
+ | spf_source | 465 | Source code chunks |
773
+ | flint_training | 2,013 | Training signals |
774
+ | flint_results | 448 | Gate decisions |
775
+ | default | 392 | General knowledge |
776
+ | flint_knowledge | 49 | FLINT facts |
777
+ | session_state | 4 | Current session |
778
+ | flint_episodic | 2 | Episodic memory |
779
+
780
+ Total: 3,371 docs | Storage: 31.41 MB | Model: all-MiniLM-L6-v2
781
+
782
+ ---
783
+
784
+ ## XL. PERMISSIONS AND ACCESS CONTROL
785
+
786
+ ### 141. 3-Layer Defense
787
+ | Layer | Mechanism | Bypass? |
788
+ |-------|-----------|---------|
789
+ | 1. Permissions Deny | settings.json denies native tools | Claude enforced |
790
+ | 2. Hook Blocking | pre hooks exit 1 on native tools | Cannot bypass |
791
+ | 3. Gate Validation | Compiled Rust allowlist + path blocking | Compiled binary |
792
+
793
+ ### 142. Self-Protection (Dynamic from spf_root)
794
+ - SPFsmartGATE/src/ — own source code
795
+ - Cargo.toml, Cargo.lock — dependencies
796
+ - LIVE/SPF_FS/blobs/ — vfs blob storage
797
+ - Home/.claude/ — Claude settings
798
+ - System dirs: /etc, /system, /usr, PREFIX
799
+
800
+ ### 143. Config Get/Set Removed from MCP
801
+ Config changes are CLI-only. AI cannot modify its own config or invoke the gate directly.
802
+
803
+ ---
804
+
805
+ ## XLI. CLI COMMANDS
806
+
807
+ ### 144. Binary CLI
808
+ - `spf-smart-gate serve` — MCP stdio server
809
+ - `spf-smart-gate status` — Gateway status
810
+ - `spf-smart-gate session` — Full session state
811
+ - `spf-smart-gate reset` — Fresh session
812
+ - `spf-smart-gate worker [--role writer|researcher]` — Headless worker mode
813
+ - `spf-smart-gate init-config` — Initialize CONFIG.DB
814
+ - `spf-smart-gate refresh-paths` — Update CONFIG.DB paths (--dry-run)
815
+ - `spf-smart-gate fs-import/fs-export` — LMDB ↔ Device
816
+ - `spf-smart-gate config-import/config-export` — JSON ↔ CONFIG.DB
817
+ - `spf-smart-gate gate` — One-shot gate check
818
+ - `spf-smart-gate calculate` — Complexity calc only
819
+
820
+ ---
821
+
822
+ ## XLII. ARCHITECTURE PROPERTIES
823
+
824
+ ### 145. Multi-Database LMDB Architecture
825
+ | # | Database | Location | Purpose |
826
+ |---|----------|----------|---------|
827
+ | 1 | SPF_FS.DB | LIVE/SPF_FS/ | Virtual filesystem + blobs |
828
+ | 2 | CONFIG.DB | LIVE/CONFIG/ | Path rules, tiers, formula |
829
+ | 3 | SESSION.DB | LIVE/SESSION/ | Session state persistence |
830
+ | 4 | PROJECTS.DB | LIVE/PROJECTS/ | Project registry |
831
+ | 5 | TMP.DB | LIVE/TMP/ | Trust, access logs, active project |
832
+ | 6 | AGENT_STATE.DB | LIVE/LMDB5/ | Memory, sessions, chat |
833
+ | 7 | BRAIN | LIVE/TMP/stoneshell-brain/ | Vector search (chromadb) |
834
+
835
+ ### 146. Zero-Dependency Path Resolution
836
+ `spf_root()` walks up from binary location for Cargo.toml → SPF_ROOT env → HOME/SPFsmartGATE. Cached via OnceLock.
837
+
838
+ ### 147. MCP Protocol v2024-11-05
839
+ JSON-RPC 2.0 over stdio. Compatible with any MCP client. 83 agent tools (8 user-only tools excluded).
840
+
841
+ ### 148. Cross-Platform Portable
842
+ Android ARM64, Linux x86_64/ARM64, macOS ARM/Intel. Zero hardcoded paths. All resolved from binary location.
843
+
844
+ ### 149. Multi-Agent Network
845
+ - Ed25519 identity (CL-1: self-test at boot)
846
+ - QUIC mesh transport (iroh)
847
+ - Qwen tool prefix aliasing (QW-1/QW-2)
848
+ - API Session Layer — full duplex agent-to-agent encrypted sessions (PP-2)
849
+
850
+ ---
851
+
852
+ ## XLIII. FLINT AI STATUS
853
+
854
+ ### 150. Training Status (live, 2026-04-05)
855
+ - Step: 116 | Batches completed: 6
856
+ - EWC lambda: 0.4 | Learning rate: 1e-4
857
+ - Online learning: ON | Replay buffer: 10,000 slots
858
+ - Checkpoint interval: 1,000 steps
859
+ - Checkpoint: LIVE/MODELS/writer_v1.spfc
860
+
861
+ ### 151. Model Architecture
862
+ - d_model: 256 | n_heads: 8 | n_layers: 6 | d_ff: 1,024
863
+ - Vocab: 8,192 | Params: ~5M
864
+ - Writer + Researcher configs
865
+
866
+ ---
867
+
868
+ ## XLIV. SECURITY EXCEPTIONS (Known Gaps)
869
+
870
+ | Gap | Description | Remediation |
871
+ |-----|-------------|-------------|
872
+ | GAP-1 | ChatText → handle_mesh_chat() — no gate routing | SEC-CHAT pending |
873
+ | GAP-2 | VoiceAudio — intentional, audio frames only | Accepted |
874
+ | GAP-3 | /proxy + /proxy/asset — SSRF only, bypasses dispatch | WB-2 pending |
875
+ | GAP-4 | /ws/browser — no gate/FLINT | SEC-WS pending |
876
+
877
+ ---
878
+
879
+ *Generated from source code analysis — verified 2026-04-05*
880
+ *8,245 → 18,500+ lines | 88 → 150+ features | 31 → 42 modules | 6 → 7 databases*
881
+ *New since February 2026: FLINT Transformer AI, Mesh Network, Chat, Voice, Browser, Pipeline, Network Pool, Channel Hub*