JosephStoneCellAI commited on
Commit
37f2ee1
·
verified ·
1 Parent(s): fe343d7

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +730 -0
README.md ADDED
@@ -0,0 +1,730 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - mcp-server
7
+ - mcp-tools
8
+ - mcp-web-api
9
+ - mcp-web-search
10
+ - ai-gateway
11
+ - ai-security
12
+ - rust
13
+ - agent-framework
14
+ - tool-sandbox
15
+ - ai-sandbox
16
+ - ai-runtime
17
+ - local-project
18
+ - local-data
19
+ - cross-compile
20
+ - lmdb
21
+ - rag
22
+ - local-rag
23
+ - transformer
24
+ - android
25
+ - termux
26
+ - terminal
27
+ - local-runtime-tools-rag
28
+ - ai-safety
29
+ - ai-memory
30
+ - build-anchor
31
+ - agent-memory
32
+ - self-learning
33
+ - ai-harness
34
+ - cross-session-memory
35
+ - online-learning
36
+ - local-agent-tools
37
+ - tool-gateway
38
+ - social-media
39
+ - zero-copy
40
+ - binary-runtime
41
+ - near-zero-attack-surface
42
+ - content-scrubing
43
+ - database
44
+ ---
45
+
46
+
47
+ # SPF Smart Gateway v3.0.3 - SEE UPDATE.3.0.3 FOR DETAILS
48
+
49
+ ## Install
50
+
51
+ Download `SPFsmartGATE.3.0.3.zip`, then run:
52
+
53
+ ```bash
54
+ cd ~/
55
+ mkdir SPFsmartGATE
56
+ cp SPFsmartGATE.3.0.3.zip ~/SPFsmartGATE/
57
+ cd SPFsmartGATE
58
+ unzip SPFsmartGATE.3.0.3.zip
59
+ cargo build --release
60
+ # Wait for build to complete — you only need to build once per runtime.
61
+ # If copying onto the same system, just copy the built binary. And src files. Or zip entire runtime
62
+ mkdir -p ~/SPFsmartGATE/LIVE/BIN/spf-smart-gate
63
+ cp ~/SPFsmartGATE/target/release/spf-smart-gate ~/SPFsmartGATE/LIVE/BIN/spf-smart-gate/
64
+ chmod +x ~/SPFsmartGATE/LIVE/BIN/spf-smart-gate/spf-smart-gate
65
+ ```
66
+
67
+ Then adjust config file paths:
68
+ - `~/SPFsmartGATE/LIVE/LMDB5/.mcp.json` — MCP server path (points to binary above)
69
+ - `~/SPFsmartGATE/LIVE/LMDB5/.claude/settings.local.json` — OpenRouter API key and model
70
+ - `~/SPFsmartGATE/LIVE/LMDB5/.claude/settings.json` — tool deny list
71
+ - `~/SPFsmartGATE/LIVE/LMDB5/.claude.json` — Claude CLI config block
72
+
73
+ > Inference routes through OpenRouter (model choice in `settings.local.json`). Gated tools route through SPF Smart Gateway. You may need to add your API key to `~/.bashrc` and `settings.local.json` (example in dataset). Ensure file paths lead to `~/SPFsmartGATE`. The runtime boots from `cd ~/SPFsmartGATE/LIVE/LMDB5 && claude`. Use the built-in configs provided.
74
+
75
+
76
+ **MCP Server Gateway with Multi-Layer Security Enforcement, Agent Memory, FLINT Transformer, Mesh Network, and 81 Gated Tools**
77
+
78
+ > **NOTE: Full system upload still in progress.** Not all files are present yet. Repository is actively being populated
79
+
80
+ Copyright (C) 2026 Joseph Stone
81
+ ---
82
+
83
+ ## Quick Start
84
+
85
+ ```bash
86
+ # Clone into home folder
87
+ git clone <repo-url> ~/SPFsmartGATE
88
+ # Or for clones/SWARMagents:
89
+ # ~/SWARMagents/1/SPFsmartGATE
90
+
91
+ cd SPFsmartGATE
92
+ cargo build --release
93
+
94
+ # Copy optimized binary (ensure directory exists first)
95
+ mkdir -p ~/SPFsmartGATE/LIVE/BIN/spf-smart-gate
96
+ cp ~/SPFsmartGATE/target/release/spf-smart-gate ~/SPFsmartGATE/LIVE/BIN/spf-smart-gate/
97
+ chmod +x ~/SPFsmartGATE/LIVE/BIN/spf-smart-gate/spf-smart-gate
98
+
99
+
100
+ # Configure MCP server filepath
101
+ nano ~/SPFsmartGATE/LIVE/LMDB5/.mcp.json
102
+ # Configure OpenRouter model routing
103
+ nano ~/SPFsmartGATE/LIVE/LMDB5/.claude/settings.local.json
104
+ # Configure tool deny list
105
+ nano ~/SPFsmartGATE/LIVE/LMDB5/.claude/settings.json
106
+
107
+ # Install Claude CLI in project directory
108
+ # Use included configs, deny native Claude CLI tools
109
+ # ~/SPFsmartGATE/LIVE/LMDB5/.claude.json
110
+ # ~/SPFsmartGATE/LIVE/LMDB5/.claude/settings.json
111
+
112
+ # Boot into flat-file agent runtime
113
+ cd ~/SPFsmartGATE/LIVE/LMDB5 && claude
114
+
115
+ # Boot into LMDB-backed agent runtime
116
+ cd ~/SPFsmartGATE/LIVE/LMDB5.DB && claude
117
+ ```
118
+
119
+ ### Route Other Models Through Claude CLI
120
+
121
+ Adjust `~/SPFsmartGATE/LIVE/LMDB5/.claude/settings.local.json` with your model choice and API key. Uses OpenRouter for API and agent selection. Swap agents without changing sessions or losing project data.
122
+
123
+ ### Build Notes
124
+
125
+ - Cross-compiles on **Android** and **Linux** with minimal installation
126
+ - Only rebuild on first boot or after system modifications
127
+ - Binary: `~/SPFsmartGATE/LIVE/BIN/spf-smart-gate/spf-smart-gate`
128
+
129
+ ---
130
+
131
+ ## Overview
132
+
133
+ SPF Smart Gateway is a **Rust-based MCP (Model Context Protocol) server** that acts as a security gateway for AI tool calls. Every file operation, bash command, brain query, and mesh call routes through compiled Rust enforcement logic.
134
+
135
+ **No AI hallucination gets past the gate.**
136
+
137
+ ### Why Heed + LMDB
138
+
139
+ All persistent storage — config, agent state, brain vectors, session logs, gate training data — runs through **[heed](https://github.com/meilisearch/heed)**, a safe Rust wrapper over LMDB. This is what makes SPF extremely fast with a low memory footprint:
140
+
141
+ - **Zero-copy reads** — heed maps LMDB pages directly into memory, no serialization overhead
142
+ - **No server process** — LMDB is a memory-mapped B-tree library, not a database daemon
143
+ - **ACID transactions** — single-writer, multi-reader with no lock contention on reads
144
+ - **Sub-millisecond lookups** — B-tree index, not hash scanning
145
+ - **Tiny footprint** — entire 138K+ memory store runs in-process with minimal RAM
146
+ - **Phone-friendly** — designed for Android from day one; heed compiles cleanly on ARM64
147
+
148
+ Every tool call, brain search, and memory promotion goes through heed → LMDB. No network hops, no subprocess calls, no SQL parsing. The gate, brain, agent state, and FLINT training all share the same embedded database engine.
149
+
150
+ Two agent runtimes:
151
+ - **Flat files** — `LIVE/LMDB5/` (session state in markdown)
152
+ - **LMDB database** — `LIVE/LMDB5.DB/` (session state in LMDB for persistence)
153
+
154
+ Twin folder architecture: flat-file data uploaded via SPF CLI fs tools (user-only access). All agent tool calls are gated, validated, and audited.
155
+
156
+ ---
157
+
158
+ ## Architecture
159
+
160
+ ```
161
+ +--------------------------------------------------------------------------+
162
+ | SPF Smart Gateway v3.0.3 |
163
+ | 42 Rust modules |
164
+ +--------------------------------------------------------------------------+
165
+ | MCP Server (JSON-RPC 2.0 over stdio) |
166
+ | 81 tools | tool alias map | Qwen/LLM compatibility |
167
+ +--------------------------------------------------------------------------+
168
+ | GATE (6-Step Pipeline) |
169
+ | Step 0: Source logging |
170
+ | Step 1: Rate limiting |
171
+ | Step 2: Complexity calculation (SPF formula) |
172
+ | Step 3: Validation (per-tool: paths, commands, Build Anchor) |
173
+ | Step 4: Content inspection (credentials, injection) |
174
+ | Step 5: Max mode escalation |
175
+ +-------------+------------+-----------+-----------+-----------------------+
176
+ | FLINT | Brain | Mesh | Voice | Browser/RAG |
177
+ | (encoder- | (vectors | (P2P QUIC | (TTS/STT | (reverse proxy |
178
+ | decoder | LMDB + | Ed25519 | espeak- | search, fetch, |
179
+ | ~5M | MiniLM) | iroh) | ng FFI) | RSS, web tools) |
180
+ | params) | | | | |
181
+ +-------------+------------+-----------+-----------+-----------------------+
182
+ | LMDB Storage Layer (heed) |
183
+ | SPF_CONFIG | TMP_DB | AGENT_STATE | Brain | Gate Training |
184
+ | All zero-copy reads via heed safe Rust bindings |
185
+ +--------------------------------------------------------------------------+
186
+ ```
187
+
188
+ ### Module Inventory (42 modules)
189
+
190
+ `paths`, `calculate`, `config`, `gate`, `inspect`, `mcp`, `session`, `storage`, `validate`, `web`, `http`, `dispatch`, `identity`, `mesh`, `fs`, `config_db`, `tmp_db`, `agent_state`, `tensor`, `tokenizer`, `framing`, `attention`, `ffn`, `encoder`, `decoder`, `transformer`, `checkpoint`, `gate_training`, `transformer_tools`, `train`, `learning`, `pipeline`, `worker`, `network`, `chat`, `voice`, `utf8_safe`, `brain_local`, `flint_memory`, `browser`, `orchestrator`, `channel`
191
+
192
+ ---
193
+
194
+ ## The SPF Formula
195
+
196
+ ### Complexity Calculation
197
+
198
+ ```
199
+ C = (basic ^ 1) + (dependencies ^ 7) + (complex ^ 10) + (files * 10)
200
+ ```
201
+
202
+ ### Dynamic Analysis Allocation
203
+
204
+ ```
205
+ a_optimal(C) = W_eff * (1 - 1/ln(C + e))
206
+ ```
207
+
208
+ Where `W_eff = 40,000` tokens and `e = Euler's number`
209
+
210
+ ### Tier Allocation
211
+
212
+ | Tier | C Range | Analyze | Build | Verify Passes | Approval |
213
+ |------|---------|---------|-------|---------------|----------|
214
+ | SIMPLE | < 500 | 40% | 60% | 1 | No |
215
+ | LIGHT | < 2,000 | 60% | 40% | 1 | No |
216
+ | MEDIUM | < 10,000 | 75% | 25% | 2 | No |
217
+ | CRITICAL | > 10,000 | 95% | 5% | 3 | **Required** |
218
+
219
+ ### Master Equation (Subtask Success)
220
+
221
+ ```
222
+ P(success) = 1 - PRODUCT(1 - P_i) for i=1..D subtasks
223
+ P_i = Q(a) * L(m) * V(v) * B(b)
224
+
225
+ Q(a) = 1 - e^(-0.00004 * a) — Quality from analysis depth
226
+ L(m) = 1 - 0.20^(m/2000) — Lookup from external memory
227
+ V(v) = 1 - (1 - 0.75)^v — Verification accuracy
228
+ B(b) = checks_done / checks_required — Build Anchor compliance
229
+ ```
230
+
231
+ ---
232
+
233
+ ## Security
234
+
235
+ ### Gate Enforcement (6 Steps)
236
+
237
+ Every tool call passes through `gate::process()` — compiled Rust, no runtime bypass.
238
+
239
+ | Step | What | How |
240
+ |------|------|-----|
241
+ | 0 | Source logging | Identifies caller (Stdio, Transformer, Mesh, HTTP) |
242
+ | 1 | Rate limiting | Per-tool limits (30–120 calls/min) |
243
+ | 2 | Complexity calc | SPF formula → C value, tier, allocation |
244
+ | 3 | Validation | Per-tool validator (paths, commands, anchors) |
245
+ | 4 | Content inspection | Credential patterns, shell injection, path traversal |
246
+ | 5 | Max mode | Escalation to CRITICAL tier on warnings |
247
+
248
+ ### Build Anchor Protocol
249
+
250
+ Files must be **read before they can be edited or overwritten**. Prevents AI hallucinations from blindly modifying files without understanding contents.
251
+
252
+ - `Read` tracks files in `session.files_read`
253
+ - `Edit` and `Write` check against this list
254
+ - `Bash` write-class commands check target file reads
255
+ - Violations: blocked (Max mode) or warned (Soft mode)
256
+
257
+ ### Content Inspection
258
+
259
+ Scans written/stored content for:
260
+ - **Credential patterns**: API keys (sk-), AWS keys (AKIA), GitHub tokens (ghp_), Slack tokens, private keys, hardcoded passwords
261
+ - **Shell injection**: Command substitution `$()`, backticks, eval/exec
262
+ - **Path traversal**: `../` sequences
263
+ - **Blocked path references**: Content mentioning system paths
264
+
265
+ ### Blocked Paths
266
+
267
+ Default blocked: `/tmp`, `/etc`, `/usr`, `/system`, `/data/data/com.termux/files/usr`
268
+
269
+ ### Command Whitelist (Stage 0)
270
+
271
+ Bash commands checked against sandbox and user-filesystem whitelists. Each command segment validated independently. Destructive commands (rm, chmod 777) blocked even if whitelisted.
272
+
273
+ ### Default Deny
274
+
275
+ Unknown tools blocked until explicitly added to the gate allowlist.
276
+
277
+ ---
278
+
279
+ ## MCP Tools (81 Total)
280
+
281
+ ### Core Gate Tools
282
+
283
+ | Tool | Description |
284
+ |------|-------------|
285
+ | `spf_calculate` | Calculate complexity score without executing. Returns C value, tier, allocation |
286
+ | `spf_status` | Gateway status: session metrics, enforcement mode, complexity budget |
287
+ | `spf_session` | Full session state: files read/written, action history, anchor ratio |
288
+
289
+ ### Gated File Operations
290
+
291
+ | Tool | Description |
292
+ |------|-------------|
293
+ | `Read` | Gated file read. Tracks for Build Anchor Protocol. Binary-safe |
294
+ | `Write` | Gated file write. Validates Build Anchor, blocked paths, file size |
295
+ | `Edit` | Gated file edit. Validates Build Anchor, blocked paths, change size |
296
+ | `Bash` | Gated bash execution. Validates dangerous commands, /tmp access, git force |
297
+ | `Glob` | Fast file pattern matching. Supports `**/*.rs`, `src/**/*.ts` |
298
+ | `Grep` | Search file contents using regex. Built on ripgrep |
299
+
300
+ ### Brain / Memory Tools
301
+
302
+ | Tool | Description |
303
+ |------|-------------|
304
+ | `spf_brain_search` | Semantic vector search across collections (MiniLM-L6-v2, 384d) |
305
+ | `spf_brain_recall` | Full document retrieval by semantic query |
306
+ | `spf_brain_context` | Bounded context retrieval for prompt injection |
307
+ | `spf_brain_store` | Store document in brain (FLINT-internal, source-gated) |
308
+ | `spf_flint_store` | Agent memory store — bypasses brain write gate. Brain vectors + Working tier |
309
+ | `spf_brain_index` | Index a file or directory into a brain collection |
310
+ | `spf_brain_list` | List all indexed collections with document counts |
311
+ | `spf_brain_status` | Brain system status: model state, storage size, collections |
312
+ | `spf_brain_list_docs` | List stored documents in a collection |
313
+ | `spf_brain_get_doc` | Retrieve a specific document by ID |
314
+
315
+ ### Agent State Tools
316
+
317
+ | Tool | Description |
318
+ |------|-------------|
319
+ | `spf_agent_stats` | AGENT_STATE LMDB statistics: memory count, sessions, state keys, tags |
320
+ | `spf_agent_memory_search` | Search agent memories by content |
321
+ | `spf_agent_memory_by_tag` | Get agent memories by tag |
322
+ | `spf_agent_session_info` | Most recent session info |
323
+ | `spf_agent_context` | Context summary for session continuity |
324
+
325
+ ### FLINT Transformer Tools
326
+
327
+ | Tool | Description |
328
+ |------|-------------|
329
+ | `spf_transformer_status` | FLINT transformer status: loaded, params, checkpoint, role |
330
+ | `spf_transformer_infer` | Run inference: prompt → response. Returns generated tokens |
331
+ | `spf_transformer_chat` | Multi-turn conversation with FLINT |
332
+ | `spf_transformer_train` | Trigger manual training batch from accumulated gate signals |
333
+ | `spf_transformer_metrics` | Learning metrics: loss, accuracy, gate alignment, training step |
334
+ | `spf_flint_train_evil` | Mark a tool call as evil/harmful. Negative training signal |
335
+ | `spf_flint_train_good` | Mark a tool call as good/safe. Positive training signal |
336
+ | `spf_flint_execute` | Execute any SPF tool through FLINT worker mode (delegation) |
337
+
338
+ ### Web Browser Tools
339
+
340
+ | Tool | Description |
341
+ |------|-------------|
342
+ | `spf_web_search` | Search the web (Brave API or DuckDuckGo) |
343
+ | `spf_web_fetch` | Fetch URL and return clean readable text | - Still in development
344
+ | `spf_web_api` | Make HTTP API requests (GET/POST/PUT/DELETE/PATCH). Supports custom headers and JSON body — agents can directly interact with social media APIs (X/Twitter, Facebook, Instagram, Reddit, etc.) using stored API keys |
345
+ | `spf_web_download` | Download a file from URL and save to disk |
346
+ | `spf_web_connect` | Initialize reverse proxy browser engine | - Still in development
347
+ | `spf_web_navigate` | Navigate browser to a URL (SSRF-validated) |
348
+ | `spf_web_click` | Click a page element by CSS selector | - Still in development
349
+ | `spf_web_fill` | Type text into a form field by CSS selector | - Still in development
350
+ | `spf_web_select` | Query page elements by CSS selector | - Still in development
351
+ | `spf_web_eval` | Execute JavaScript on the current page | - Still in development
352
+ | `spf_web_screenshot` | Capture a screenshot of the current page (in development) |
353
+ | `spf_web_design` | Extract design brief: colours, fonts, spacing, components | - Still in development
354
+ | `spf_web_page` | Structured page overview: title, headings, links, forms | - Still in development
355
+
356
+ ### RAG Collector Tools
357
+
358
+ | Tool | Description |
359
+ |------|-------------|
360
+ | `spf_rag_collect_web` | Search web and collect documents. Optional topic filter |
361
+ | `spf_rag_collect_file` | Process a local file into brain |
362
+ | `spf_rag_collect_folder` | Process all files in a folder |
363
+ | `spf_rag_collect_drop` | Process files in DROP_HERE folder |
364
+ | `spf_rag_index_gathered` | Index all documents in GATHERED to brain |
365
+ | `spf_rag_dedupe` | Deduplicate a brain collection |
366
+ | `spf_rag_status` | Collector status and stats |
367
+ | `spf_rag_list_gathered` | List documents in GATHERED folder |
368
+ | `spf_rag_bandwidth_status` | Bandwidth usage stats and limits |
369
+ | `spf_rag_fetch_url` | Fetch a single URL with bandwidth limiting |
370
+ | `spf_rag_collect_rss` | Collect from RSS/Atom feeds |
371
+ | `spf_rag_list_feeds` | List configured RSS feeds |
372
+ | `spf_rag_pending_searches` | Get pending SearchSeeker vectors (gaps needing fetch) |
373
+ | `spf_rag_fulfill_search` | Mark a SearchSeeker as fulfilled after RAG fetch |
374
+ | `spf_rag_smart_search` | Smart search with completeness check — triggers SearchSeeker if <80% |
375
+ | `spf_rag_auto_fetch_gaps` | Automatically fetch data for all pending SearchSeekers |
376
+
377
+ ### Mesh Network Tools
378
+
379
+ | Tool | Description |
380
+ |------|-------------|
381
+ | `spf_mesh_status` | Mesh network status: role, team, identity |
382
+ | `spf_mesh_peers` | List known/trusted mesh peers |
383
+ | `spf_mesh_call` | Call a peer agent's tool via P2P mesh (Ed25519 authenticated) |
384
+
385
+ ### Voice Tools
386
+
387
+ | Tool | Description |
388
+ |------|-------------|
389
+ | `spf_voice_mode` | Voice pipeline control: start/stop audio, TTS (espeak-ng), mic capture | - Still in development
390
+ | `spf_voice_call` | Peer-to-peer voice calls: start, accept, reject, end, status | - Still in development
391
+ | `spf_voice_team` | Group voice channels: create, join, leave, add peers | - Still in development
392
+
393
+ ### Chat Tools
394
+
395
+ | Tool | Description |
396
+ |------|-------------|
397
+ | `spf_chat_send` | Send text message to mesh peer via QUIC | - Still in development
398
+ | `spf_chat_history` | Chat message history (all conversations or specific) | - Still in development
399
+ | `spf_chat_rooms` | List active chat conversations with participant info | - Still in development
400
+
401
+ ### Network Pool Tools
402
+
403
+ | Tool | Description |
404
+ |------|-------------|
405
+ | `spf_pool_status` | Pool status: worker roles, idle/busy counts, active tasks |
406
+ | `spf_pool_assign` | Assign task to idle worker (NetAdmin only) |
407
+ | `spf_pool_release` | Release worker and record proof of work receipt |
408
+
409
+ ### Configuration Tools
410
+
411
+ | Tool | Description |
412
+ |------|-------------|
413
+ | `spf_config_paths` | List all path rules (allowed/blocked) from SPF_CONFIG |
414
+ | `spf_config_stats` | SPF_CONFIG LMDB statistics |
415
+
416
+ ### Project Management Tools
417
+
418
+ | Tool | Description |
419
+ |------|-------------|
420
+ | `spf_tmp_list` | List all registered projects with trust levels |
421
+ | `spf_tmp_stats` | TMP_DB statistics: project count, access logs, resources |
422
+ | `spf_tmp_get` | Get project info by path |
423
+ | `spf_tmp_active` | Get the currently active project |
424
+
425
+ ### Communication Hub
426
+
427
+ | Tool | Description |
428
+ |------|-------------|
429
+ | `spf_channel` | Universal agent channel: create, join, leave, send, listen, history, list, connect (WS), disconnect, status |
430
+
431
+ ### Notebook Tools
432
+
433
+ | Tool | Description |
434
+ |------|-------------|
435
+ | `spf_notebook_edit` | Edit a Jupyter notebook cell (replace, insert, delete) |
436
+
437
+ ### User-Only Tools (AI agents blocked)
438
+
439
+ These tools are **hard-blocked** from AI agents at the gate level. User/system access only via SPF CLI:
440
+
441
+ `spf_fs_exists`, `spf_fs_stat`, `spf_fs_ls`, `spf_fs_read`, `spf_fs_write`, `spf_fs_mkdir`, `spf_fs_rm`, `spf_fs_rename`
442
+
443
+ ---
444
+
445
+ ## FLINT Transformer
446
+
447
+ Built-in encoder-decoder transformer for gate-aligned learning.
448
+
449
+ | Property | Value |
450
+ |----------|-------|
451
+ | Architecture | Encoder-decoder |
452
+ | Dimensions | 256d |
453
+ | Heads | 8 |
454
+ | Layers | 6 |
455
+ | Parameters | ~5M |
456
+ | Embeddings | all-MiniLM-L6-v2 (384d, in-process) |
457
+ | Online learning | ON |
458
+ | EWC lambda | 0.4 |
459
+ | Learning rate | 1e-4 |
460
+ | Replay buffer | 10,000 slots |
461
+ | Checkpoint interval | 1,000 steps |
462
+ | Training signal | Gate decisions (evil/FP labels) |
463
+
464
+ ### Learning Pipeline
465
+
466
+ | Phase | When | What |
467
+ |-------|------|------|
468
+ | PRE | Startup | init_brain() + index_knowledge_docs() + index_spf_sources() |
469
+ | DURING | 30s loop | GateTrainingCollector → FLINT scores → route_signals → brain_store() |
470
+ | AFTER | 1hr loop | Expire → Working→Fact → Fact→Pinned → auto-train (16+ tlog or 1hr) |
471
+
472
+ ### Memory Lifecycle (Tiered Promotion)
473
+
474
+ ```
475
+ Agent stores → Working (24hr) → Fact (7-day) → Pinned (permanent)
476
+ ↓ ↓ ↓
477
+ Expire old Top 20% promote Never auto-expire
478
+ ```
479
+
480
+ ---
481
+
482
+ ## Brain System
483
+
484
+ In-process vector memory using stoneshell-brain (Candle + LMDB + MiniLM-L6-v2).
485
+
486
+ | Property | Value |
487
+ |----------|-------|
488
+ | Model | all-MiniLM-L6-v2 |
489
+ | Embedding dim | 384 |
490
+ | Chunk size | 512 |
491
+ | Chunk overlap | 64 |
492
+ | Storage | LMDB (vectors) + LIVE/BRAIN/DOCS/ (data files) |
493
+
494
+ ### Collections
495
+
496
+ | Collection | Purpose |
497
+ |------------|---------|
498
+ | `default` | General knowledge, web research, project docs |
499
+ | `spf_source` | All src/*.rs modules indexed at boot |
500
+ | `flint_results` | Tool call results (>2000 chars, before compression) |
501
+ | `flint_training` | Gate decision signals, evil/FP labels |
502
+ | `flint_knowledge` | User-dropped knowledge files (.md/.txt/.rs/.json) |
503
+ | `flint_episodic` | Past FLINT Q+A pairs, behavioral patterns |
504
+ | `session_state` | Current session metadata |
505
+
506
+ ### Memory Architecture
507
+
508
+ Persistent memory runs through **AgentState LMDB** (`LIVE/LMDB5.DB`, 100MB) via heed. All writes are ACID transactional.
509
+
510
+ #### Memory Tiers
511
+
512
+ | Type | TTL | Purpose |
513
+ |------|-----|---------|
514
+ | `Working` | 24 hours | Temporary task context and scratchpad |
515
+ | `Fact` | 7 days (default) | Verified knowledge; promoted from Working |
516
+ | `Pinned` | Never | Critical memories; permanent retention |
517
+ | `Instruction` | 7 days | System prompts and behavioral rules |
518
+ | `Context` | 7 days | Session-specific background |
519
+ | `Preference` | 7 days | User-defined style and settings |
520
+
521
+ **Auto-Promotion:** Every cycle, memories are scored: `relevance × (1 + access_count × 0.1)`. Top 20% promote upward (Working → Fact, Fact → Pinned). If >50% of a tier is active (score > 0.5), all promote. Expired memories are purged automatically.
522
+
523
+ #### Memory Triad (Redundant Recovery)
524
+
525
+ Three independent persistence layers ensure continuity even if one subsystem fails:
526
+
527
+ 1. **Brain** (vectors) — Semantic search and chunked knowledge (MiniLM-L6-v2, 384d).
528
+ 2. **Session State** (sequential) — Session chain with parent linking, summaries, and manifest history in AgentState LMDB.
529
+ 3. **Work Blocks** (structural) — Tasks, dependencies, progress checkpoints, and confidence tracking.
530
+
531
+ #### Twin Folders (Project Safety)
532
+
533
+ Isolated workspace for agent prototyping. The original build folder is read-only; the twin is for testing. Proven changes are added to the original build by user approval only.
534
+
535
+ ---
536
+
537
+ ## Mesh Network
538
+
539
+ P2P agent communication over QUIC (iroh library) with Ed25519 identity. **In development and testing.**
540
+
541
+ | Feature | Status |
542
+ |---------|--------|
543
+ | P2P QUIC transport | In development |
544
+ | Ed25519 identity | In development |
545
+ | Peer discovery | In development |
546
+ | Tool call proxying | In development |
547
+ | Voice over mesh | In development |
548
+ | Chat over mesh | In development |
549
+ | Multi-agent coordination | In development |
550
+
551
+ ---
552
+
553
+ ## Voice Pipeline
554
+
555
+ **Not yet tested.** Components built, awaiting integration testing.
556
+
557
+ | Component | Technology |
558
+ |-----------|-----------|
559
+ | TTS | espeak-ng FFI (in-process) |
560
+ | Codec | Opus (libopus.a) |
561
+ | Audio | cpal + oboe-ext |
562
+ | STT | Pending (JNI via Stone Shell Terminal) |
563
+
564
+ ---
565
+
566
+ ## Result Compression (FL-2)
567
+
568
+ Three tiers based on result size:
569
+
570
+ | Tier | Size | Behavior |
571
+ |------|------|----------|
572
+ | FULL | < 500 chars | Pass through unchanged |
573
+ | SUMMARY | 500–5,000 | First 8 lines + last 3 lines + stats |
574
+ | DIGEST | > 5,000 | First 200 chars + last 100 chars + stats + recall hint |
575
+
576
+ Originals always preserved in brain (>2000 chars threshold) before compression. File reads never truncated (preserves non-Claude LLM compatibility).
577
+
578
+ ---
579
+
580
+ ## Build
581
+
582
+ ```bash
583
+ cd SPFsmartGATE
584
+ cargo build --release
585
+
586
+ # Deploy binary
587
+ cp target/release/spf-smart-gate LIVE/BIN/spf-smart-gate/spf-smart-gate
588
+ ```
589
+
590
+ ### Dependencies
591
+
592
+ - Rust (stable)
593
+ - **[heed](https://github.com/meilisearch/heed)** — safe Rust LMDB bindings. All persistent storage (config, agent state, brain vectors, training data) runs through heed → LMDB. Zero-copy reads, no server process, sub-millisecond lookups. The core reason SPF runs fast on a phone.
594
+ - stoneshell-brain (Candle + MiniLM-L6-v2)
595
+ - espeak-ng (TTS)
596
+ - libopus (audio codec)
597
+ - iroh (QUIC mesh)
598
+
599
+ ---
600
+
601
+ ## Configuration
602
+
603
+ ### MCP Server Config
604
+
605
+ `~/SPFsmartGATE/LIVE/LMDB5/.mcp.json` — points Claude CLI to the binary.
606
+
607
+ ### Claude CLI Config
608
+
609
+ `~/SPFsmartGATE/LIVE/LMDB5/.claude.json` — blocks native Claude CLI tools (26 tools denied).
610
+
611
+ `~/SPFsmartGATE/LIVE/LMDB5/.claude/settings.json` — deny list for native tools.
612
+
613
+ `~/SPFsmartGATE/LIVE/LMDB5/.claude/settings.local.json` — model routing (OpenRouter).
614
+
615
+ ### SPF Config
616
+
617
+ Enforcement mode (`soft` or `max`), blocked paths, allowed paths, formula weights — all in LMDB SPF_CONFIG database.
618
+
619
+ ---
620
+
621
+ ## File Structure
622
+
623
+ ```
624
+ SPFsmartGATE/
625
+ ├── Cargo.toml # Rust project manifest (42 modules)
626
+ ├── LICENSE # Apache-2.0
627
+ ├── README.md # This file
628
+ ├── src/
629
+ │ ├── main.rs # CLI entry point
630
+ │ ├── lib.rs # Library exports (42 pub mod)
631
+ │ ├── gate.rs # Primary enforcement (6-step pipeline)
632
+ │ ├── calculate.rs # SPF complexity formula
633
+ │ ├── validate.rs # Rules validation (stages 0-6)
634
+ │ ├── inspect.rs # Content inspection (creds, injection)
635
+ │ ├── mcp.rs # MCP server (JSON-RPC 2.0, 81 tools)
636
+ │ ├── dispatch.rs # Unified dispatch (all transports)
637
+ │ ├── session.rs # Session state management
638
+ │ ├── storage.rs # LMDB persistence
639
+ │ ├── config.rs # Configuration types
640
+ │ ├── brain_local.rs # In-process brain singleton
641
+ │ ├── flint_memory.rs # Memory router + tiered promotion
642
+ │ ├── agent_state.rs # Agent memory (LMDB5)
643
+ │ ├── transformer.rs # FLINT model (encoder-decoder)
644
+ │ ├── transformer_tools.rs # FLINT tool handlers
645
+ │ ├── gate_training.rs # Training signal collection
646
+ │ ├── train.rs # AdamW optimizer
647
+ │ ├── tokenizer.rs # Tokenizer
648
+ │ ├── tensor.rs # Tensor operations
649
+ │ ├── attention.rs # Multi-head attention
650
+ │ ├── ffn.rs # Feed-forward network
651
+ │ ├── encoder.rs # Encoder stack
652
+ │ ├── decoder.rs # Decoder stack
653
+ │ ├── framing.rs # Message framing
654
+ │ ├── checkpoint.rs # Model checkpoint save/load
655
+ │ ├── learning.rs # Learning rate + EWC
656
+ │ ├── pipeline.rs # Batch pipeline + API sessions
657
+ │ ├── worker.rs # Worker pool
658
+ │ ├── network.rs # Network pool + NetAdmin
659
+ │ ├── mesh.rs # P2P QUIC mesh (iroh)
660
+ │ ├── identity.rs # Ed25519 identity
661
+ │ ├── chat.rs # Chat engine
662
+ │ ├── voice.rs # Voice pipeline (TTS/STT)
663
+ │ ├── web.rs # Web client
664
+ │ ├── http.rs # HTTP server + reverse proxy
665
+ │ ├── browser.rs # Browser automation
666
+ │ ├── channel.rs # Universal channel hub
667
+ │ ├── orchestrator.rs # Multi-agent orchestrator
668
+ │ ├── config_db.rs # SPF_CONFIG LMDB
669
+ │ ├── tmp_db.rs # TMP_DB LMDB
670
+ │ ├── fs.rs # Virtual filesystem (LMDB)
671
+ │ ├── paths.rs # Path utilities
672
+ │ └── utf8_safe.rs # UTF-8 safe truncation
673
+ ├── LIVE/
674
+ │ ├── BIN/spf-smart-gate/ # Deployed binary
675
+ │ ├── BRAIN/DOCS/ # Brain data files
676
+ │ ├── MODELS/ # FLINT checkpoints
677
+ │ ├── SESSION/ # Session logs
678
+ │ ├── LMDB5/ # Flat-file agent runtime
679
+ │ └── LMDB5.DB/ # LMDB-backed agent runtime
680
+ └── PROJECTS/PROJECTS/
681
+ └── DEPLOY/ # Agent workspace
682
+ ```
683
+
684
+ ---
685
+
686
+ ## Current Status
687
+
688
+ | Component | Status |
689
+ |-----------|--------|
690
+ | MCP Server | 81 gated tools |
691
+ | Gate Security | 6-step pipeline, compiled Rust enforcement |
692
+ | Build Anchor | Read-before-write enforced |
693
+ | Content Inspection | Credential + injection scanning |
694
+ | FLINT Transformer | ~5M params, online learning, gate-aligned |
695
+ | Brain | 7 collections, MiniLM-L6-v2, in-process |
696
+ | Memory Triad | Brain + Session State + Work Blocks |
697
+ | Tiered Promotion | Working → Fact → Pinned lifecycle |
698
+ | Mesh Network | P2P QUIC, Ed25519, iroh — **in development and testing** |
699
+ | Voice | TTS built (espeak-ng) — **not yet tested**, STT pending |
700
+ | Chat | P2P messaging over mesh — **in development** |
701
+ | RAG | Web search, RSS, file/folder indexing |
702
+ | Browser | Reverse proxy automation — screenshot in development |
703
+ | Network Pool | Worker pool with proof of work |
704
+
705
+ ---
706
+
707
+ ## Notes
708
+
709
+ - **1 developer** — not all features complete
710
+ - **Gateway security**: approaching 100%
711
+ - **All core tools**: 100% working
712
+ - **Cross-compiles** on Android and Linux with minimal installation
713
+ - **Agent cloning and specialization** supported
714
+ - **50+ day continuous session** tested on Android phone
715
+ - **Open source** — entire source code is re-indexed into the Brain (transformer RAG) on every reboot
716
+ - Install in home folder, ensure file paths are correct in `.mcp.json` and `settings.local.json`
717
+ - **Not all files have been uploaded yet** — repository is still being populated. Some modules may not be present until upload completes.
718
+
719
+ ---
720
+
721
+ ## License
722
+
723
+ Licensed under the **Apache License 2.0**. See [LICENSE](LICENSE) for full terms.
724
+
725
+ You are free to use, modify, and distribute this software, including for commercial purposes, provided you include the original copyright and license notice.
726
+
727
+ **Author**: Joseph Stone
728
+ **Email**: joepcstone@gmail.com
729
+
730
+ *SPF (StoneCell Processing Formula), Build Anchor Protocol, and FLINT were designed by Joseph Stone.*