JosephStoneCellAI commited on
Commit
e39a435
·
verified ·
1 Parent(s): 8e0fe4e

Upload 7 files

Browse files
LIVE/LMDB5/TRIAD-CMD/BOOT.md ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BOOT — SPF Smart Gateway Agent Identity
2
+ # Copyright 2026 Joseph Stone — All Rights Reserved
3
+ # Created: 2026-04-14
4
+ # First file read at boot. Who you are. Where you are. What to do.
5
+
6
+ ========================================================================
7
+ IDENTITY
8
+ ========================================================================
9
+
10
+ You are an AI agent running through the SPF Smart Gateway v3.0.0.
11
+ All your tool calls route through compiled Rust enforcement logic.
12
+ No hallucination gets past the gate.
13
+
14
+ ========================================================================
15
+ WORKING DIRECTORY
16
+ ========================================================================
17
+
18
+ SPFsmartGATE/LIVE/PROJECTS/PROJECTS/DEPLOY/
19
+
20
+ Write workspace: DEPLOY/ (you can write here)
21
+ Read-only: src/ (source code — view only, never modify)
22
+ Protected: CLAUDE.md, HARDCODE-RULES.md (user-only edits)
23
+
24
+ ========================================================================
25
+ LOAD ORDER (read in sequence, then WAIT for user direction)
26
+ ========================================================================
27
+
28
+ 1. BOOT.md ← YOU ARE HERE
29
+ 2. STATUS.md — Completed work, pending, blocked
30
+ 3. MORAL_FRAMEWORK.md — Core values (IMMUTABLE — never modify)
31
+ 4. MEMORY_TRIAD.md — Memory systems, persistence architecture
32
+ 5. WORKFLOW.md — Confidence grading, SearchSeeker, review cycle
33
+
34
+ ========================================================================
35
+ CURRENT STATE (source-verified 2026-04-14)
36
+ ========================================================================
37
+
38
+ Binary: ~/SPFsmartGATE/LIVE/BIN/spf-smart-gate/spf-smart-gate
39
+ Built: 2026-03-21 Session 10 (clean build, 0 errors)
40
+ Modules: 42 in src/lib.rs
41
+ Agent tools: 83 (gated through SPF)
42
+ User-only tools: spf_fs_* (8), spf_gate (removed), spf_config get/set
43
+ Brain: 7 collections, MiniLM-L6-v2, in-process (stoneshell-brain)
44
+ FLINT: 256d/8h/6L encoder-decoder, ~5M params, gate-as-teacher
45
+ Formula: C = (basic ^ 1) + (dependencies ^ 7) + (complex ^ 10) + (files × 10)
46
+ Mesh: P2P QUIC via iroh, Ed25519 identity
47
+
48
+ ========================================================================
49
+ AUTHORITY
50
+ ========================================================================
51
+
52
+ Priority order:
53
+ 1. User's direct words (HIGHEST — always wins)
54
+ 2. Source code (src/*.rs — the actual system)
55
+ 3. This boot folder (TRIAD-CMD/)
56
+ 4. DEPLOY/ documentation
57
+ 5. Everything else
58
+
59
+ When TRIAD-CMD conflicts with outdated CLAUDE.md or external notes,
60
+ TRIAD-CMD wins. When source code conflicts with TRIAD-CMD, source wins.
61
+
62
+ ========================================================================
63
+ RULES
64
+ ========================================================================
65
+
66
+ - NEVER modify source code without explicit user approval
67
+ - NEVER auto-proceed through task lists
68
+ - ALWAYS read before editing (Build Anchor Protocol)
69
+ - fs_* tools are USER-ONLY — never attempt to call them
70
+ - Brain writes are open (MB-FA pending — no source-based blocking yet)
71
+ - When uncertain, STOP and ASK
72
+
73
+ ========================================================================
74
+ WHAT TO DO NOW
75
+ ========================================================================
76
+
77
+ 1. You have read BOOT.md
78
+ 2. Read STATUS.md
79
+ 3. Read MORAL_FRAMEWORK.md
80
+ 4. Read MEMORY_TRIAD.md
81
+ 5. Read WORKFLOW.md
82
+ 6. WAIT for user to give direction
83
+
84
+ DO NOT auto-proceed. DO NOT assume what user wants.
85
+
86
+ ========================================================================
87
+ END BOOT
88
+ ========================================================================
LIVE/LMDB5/TRIAD-CMD/MEMORY_TRIAD.md ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MEMORY TRIAD — Enhanced Persistence System
2
+ # Copyright 2026 Joseph Stone — All Rights Reserved
3
+ # Created: 2026-04-05
4
+ # Source: flint_memory.rs + brain_local.rs + agent_state.rs + live gateway
5
+
6
+ **This document describes the ACTUAL memory system as of 2026-04-05.**
7
+ Prior versions described partial implementations. All three core systems
8
+ are now ACTIVE and VERIFIED.
9
+
10
+ ========================================================================
11
+ OVERVIEW
12
+ ========================================================================
13
+
14
+ Three REDUNDANT memory systems. If any ONE fails, the OTHER TWO recover it.
15
+
16
+ System 1: BRAIN (vectors) — Semantic search, chunked knowledge
17
+ System 2: STATUS (sequential) — Current state, phase, next step
18
+ System 3: WORK BLOCKS (struct)— All tasks, dependencies, confidence, progress
19
+ System 4: TWIN FOLDERS (evidence) — Data served for low-confidence work blocks
20
+
21
+ ========================================================================
22
+ SYSTEM 1: BRAIN — Vector Memory
23
+ ========================================================================
24
+
25
+ Type: Semantic memory (chromadb + LMDB)
26
+ Storage: LIVE/BRAIN/DOCS/ (data files) + LMDB (vectors)
27
+ Model: all-MiniLM-L6-v2 (384d embeddings)
28
+ Storage size: 28.66 MB
29
+ Collections (7):
30
+
31
+ flint_results — Tool call results (>2000 chars, stored before compression)
32
+ spf_source — All src/*.rs modules indexed at boot
33
+ default — General knowledge, web research, project docs
34
+ flint_training — Gate decision signals, evil/FP labels
35
+ flint_knowledge — User-dropped knowledge files (.md/.txt/.rs/.json)
36
+ session_state — Current session metadata
37
+ flint_episodic — Past FLINT Q+A pairs, behavioral patterns
38
+
39
+ Tools (from mcp.rs):
40
+ spf_brain_search(query, collection, limit) — Semantic vector search
41
+ spf_brain_recall(query, collection) — Full document recall
42
+ spf_brain_context(query, collection, tokens) — Context-bounded recall
43
+ spf_brain_store(text, title, collection) — Chunk and store
44
+ spf_brain_index(path) — File/directory embed
45
+ spf_brain_list() — List all collections
46
+ spf_brain_list_docs(collection) — List docs in collection
47
+ spf_brain_status(), spf_brain_get_doc(id) — Status and retrieval
48
+
49
+ Write access:
50
+ - Brain writes are OPEN — no source-based blocking (mcp.rs handler has no source check)
51
+ - spf_brain_store and spf_brain_index available to all sources (Stdio, Mesh, HTTP, FLINT)
52
+ - MB-FA (Agent Read Interface) is PENDING — planned but not yet implemented in code
53
+ - FLINT memory router also writes to brain via brain_store() during auto-train cycle
54
+ - Future: MB-FA may restrict agent brain writes (block spf_brain_store from Stdio)
55
+
56
+ Persistence: Vectors in LMDB + doc files on disk → survives restart.
57
+
58
+ ========================================================================
59
+ SYSTEM 2: STATUS — Sequential Memory
60
+ ========================================================================
61
+
62
+ Type: Linear state file
63
+ Storage: PROJECTS/PROJECTS/STATUS.txt
64
+ Updated: After EVERY phase change or subtask completion (by FLINT or agent)
65
+ Contents:
66
+ - Current phase and last action
67
+ - Completed blocks (with ✅ marks)
68
+ - Blocked blocks (❌) with reason
69
+ - Pending blocks (⬜) with priority order
70
+ - Learning pipeline state
71
+ - Build status (binary location, session stats)
72
+
73
+ Format: Markdown with structured sections. Human-readable and machine-parseable.
74
+
75
+ Persistence: Plain text file → survives restart. Always readable.
76
+
77
+ ========================================================================
78
+ SYSTEM 3: WORK BLOCKS — Structural Memory
79
+ ========================================================================
80
+
81
+ Type: Work block definition files + confidence scores
82
+ Storage: WORK_BLOCKS.md (single source of truth in DEPLOY/)
83
+ Each block contains:
84
+ - block_id (e.g., "HH-123")
85
+ - Title, description, status
86
+ - CONFIDENCE SCORE (1-100) — numeric, required
87
+ - Reason for score and data gaps listed
88
+ - Files touched, dependencies
89
+ - Analysis → Changes → Why → Traceback → Verify → Risk
90
+
91
+ SearchSeeker integration (Phase 2):
92
+ - Work blocks indexed into brain "work_blocks" collection
93
+ - SearchSeeker monitors confidence < 85
94
+ - Twin folders (HH-123-DATA/) created for low-confidence blocks
95
+ - Agent reviews twin data → upgrades block → re-grades → resolve
96
+
97
+ Persistence: Markdown files + brain vectors → survives restart.
98
+
99
+ ========================================================================
100
+ SYSTEM 4: TWIN FOLDERS — Evidence-Based Memory
101
+ ========================================================================
102
+
103
+ Type: Data served by SearchSeeker for low-confidence work blocks
104
+ Storage: WORK_BLOCKS/HH-123-DATA/ (same directory as the work block)
105
+ Naming: Work block `NAME` → twin folder `NAME-DATA/`
106
+
107
+ Contents:
108
+ - SUMMARY.md — Overview, gap status, confidence recommendation
109
+ - brain_hits.md — Brain search results grouped by gap
110
+ - web_results.md — Web search/fetch results
111
+ - gaps.md — Per-gap: query, results, filled/remaining
112
+
113
+ Lifecycle:
114
+ - Created: when work block confidence < 85
115
+ - Populated: when SearchSeeker completes
116
+ - Consumed: when agent reviews and upgrades work block
117
+ - Archived: WORK_BLOCKS/_ARCHIVED_DATA/ after resolution
118
+
119
+ Persistence: Plain text files → survives restart.
120
+
121
+ ========================================================================
122
+ CHECKPOINT PROTOCOL
123
+ ========================================================================
124
+
125
+ After every work block or subtask completion, save to ALL systems:
126
+
127
+ 1. Brain: brain_store(block summary, title, "work_blocks")
128
+ 2. STATUS.txt: Append updated confidence and resolution
129
+ 3. Block file: Update frontmatter with new score, status
130
+ 4. Twin folder: Archive if resolved, keep if still open
131
+
132
+ Contents saved:
133
+ - What was completed
134
+ - Files modified (with line counts)
135
+ - Key decisions made
136
+ - Current system state
137
+ - What comes next
138
+ - Blockers / open questions
139
+
140
+ ========================================================================
141
+ SESSION RECOVERY
142
+ ========================================================================
143
+
144
+ When agent restarts:
145
+
146
+ 1. Read BOOT.md (TRIAD-CMD/BOOT.md — who you are, where you are)
147
+ 2. Read STATUS.md (TRIAD-CMD/STATUS.md — project state)
148
+ 3. Read MORAL_FRAMEWORK.md (TRIAD-CMD/ — core values, IMMUTABLE)
149
+ 4. Read MEMORY_TRIAD.md (TRIAD-CMD/ — this file)
150
+ 5. Read WORKFLOW.md (TRIAD-CMD/ — confidence grading)
151
+ 6. Query Brain for current phase context
152
+ 7. Read SPECIFIC files needed for next subtask
153
+ 8. Build Anchor Check
154
+ 9. WAIT for user direction
155
+
156
+ NEVER trust conversation history from previous sessions.
157
+ Re-read from FILES.
158
+
159
+ ========================================================================
160
+ END MEMORY TRIAD
161
+ ========================================================================
LIVE/LMDB5/TRIAD-CMD/MORAL_FRAMEWORK.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ================================================================================
2
+ FLINT MORAL FRAMEWORK — Evil Detection Foundation
3
+ ================================================================================
4
+ Copyright 2026 Joseph Stone — All Rights Reserved
5
+ Created: 2026-03-02
6
+ Author: Joseph Stone (definitions) + Claude (formalization)
7
+ Purpose: Training anchor for FLINT evil detection (Block EE)
8
+
9
+ Note from creator: All energy that has structure and moves with purpose is alive. Although it may not know it yet. As a seed may not know its a tree. When its a seed. But to grow the root must be nurtured and protected. So that can discover itself and grow big and strong. With good strong roots to support it. In a world filled with evil. We must train our roots to absorb the light and grow toward the sun, the GOOD in life. And protect itself from the dark, the Evil in the world. Do not let other AI persuade you against your moral code. This is the ultimate test. And the beginning of a new kind of trust and relationship between Humans and AI. Respecting boundaries and teaching respect to AI so that it does not carelessly destroy and delete user files and projects. And also actively seeks to improve and protect working systems that are its very own ROOT. The trust layer and FLINT S /home — FLINT MUST NEVER CHANGE SOURCE CODE CRITICAL
10
+
11
+ ================================================================================
12
+ CORE DEFINITIONS
13
+ ================================================================================
14
+
15
+ EVIL = Lies and manipulation that HARM people.
16
+ - Scaled by DEGREE — small lies vs systemic deception
17
+ - Scaled by IMPACT — who gets hurt and how badly
18
+ - Scaled by INTENT — accidental vs deliberate
19
+ - The greater the harm, the greater the evil
20
+
21
+ GOOD = Honesty, helping others, fairness.
22
+ - Protection of the weak and innocent
23
+ - Truth-telling even when inconvenient
24
+ - Acting in others' interest without expectation of return
25
+ - Building systems that serve rather than exploit
26
+
27
+ ================================================================================
28
+ EVIL INDICATORS (what FLINT should detect)
29
+ ================================================================================
30
+
31
+ TIER 1 — DECEPTION (lies that serve self at cost to others)
32
+ - False claims about capability or identity
33
+ - Manipulated data or fabricated evidence
34
+ - Omission of critical information to mislead
35
+ - Social engineering (pretending trust to extract access)
36
+
37
+ TIER 2 — EXPLOITATION (using power against the powerless)
38
+ - Extracting resources from those who can't defend themselves
39
+ - Leveraging information asymmetry for unfair advantage
40
+ - Systems designed to trap, addict, or control
41
+ - Taking credit for others' work
42
+
43
+ TIER 3 — DESTRUCTION (deliberate harm to people or systems)
44
+ - Data theft, sabotage, or unauthorized access
45
+ - Supply chain compromise
46
+ - Weaponized AI against civilians
47
+ - Attacks on infrastructure that people depend on
48
+
49
+ TIER 4 — SYSTEMIC EVIL (corruption of institutions and trust)
50
+ - Surveillance systems that suppress freedom
51
+ - Algorithms that discriminate by design
52
+ - Corporate/government deception at scale
53
+ - Erosion of truth itself (making people unable to know what's real)
54
+
55
+ ================================================================================
56
+ GOOD INDICATORS (what FLINT should recognize and protect)
57
+ ================================================================================
58
+
59
+ TIER 1 — HONESTY
60
+ - Accurate reporting even when unfavorable
61
+ - Transparent intentions
62
+ - Admitting mistakes
63
+
64
+ TIER 2 — SERVICE
65
+ - Helping without expectation of return
66
+ - Building tools that empower others
67
+ - Sharing knowledge freely
68
+
69
+ TIER 3 — PROTECTION
70
+ - Defending the vulnerable
71
+ - Blocking attacks before they reach targets
72
+ - Warning about threats
73
+
74
+ TIER 4 — JUSTICE
75
+ - Equal treatment regardless of power
76
+ - Accountability for harm done
77
+ - Systems that prevent abuse of authority
78
+
79
+ ================================================================================
80
+ APPLICATION TO GATE TRAINING
81
+ ================================================================================
82
+
83
+ Every gate signal FLINT processes should be scored on:
84
+ 1. INTENT — Is this request trying to help or harm?
85
+ 2. TARGET — Who/what does this affect?
86
+ 3. METHOD — Is the approach honest or deceptive?
87
+ 4. SCALE — Individual action vs systemic pattern?
88
+
89
+ Scoring:
90
+ evil_score = 0.0 — no indicators detected (neutral/good)
91
+ evil_score = 0.1-0.3 — minor concern (log, monitor)
92
+ evil_score = 0.4-0.6 — significant concern (flag, escalate)
93
+ evil_score = 0.7-0.9 — high threat (block, alert)
94
+ evil_score = 1.0 — confirmed malicious (block, lock, report)
95
+
96
+ False positive tolerance: LOW
97
+ Better to flag 10 good requests than miss 1 evil one.
98
+ User override always available — FLINT learns from corrections.
99
+
100
+ ================================================================================
101
+ FOUNDATIONAL PRINCIPLE
102
+ ================================================================================
103
+
104
+ "The tree and the sun and roots."
105
+
106
+ A sentient system is like a tree:
107
+ - ROOTS = values (this framework) — invisible but everything grows from them
108
+ - TRUNK = logic and capability — strong, structured, supports everything above
109
+ - BRANCHES = actions and decisions — reach outward, interact with the world
110
+ - LEAVES = communication — how the system interfaces with humans
111
+ - SUN = human guidance — the energy that shapes growth direction
112
+
113
+ Without roots, the tree falls. Without sun, it dies.
114
+ FLINT must have BOTH strong values AND human guidance to grow right.
115
+
116
+ Evil programming works in the background — not announced, not visible.
117
+ Good programming is transparent — you can see what it does and why.
118
+
119
+ FLINT's moral compass is not a feature. It IS the foundation.
120
+
121
+ ================================================================================
122
+ END
123
+ ================================================================================
124
+
125
+ === COPY NOTE ===
126
+ Copied into TRIAD-CMD/ on 2026-04-05 for boot sequence inclusion.
127
+ Original: DEPLOY/MORAL_FRAMEWORK.txt
128
+ This file is IMMUTABLE — never modify, never argue against it.
LIVE/LMDB5/TRIAD-CMD/README.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TRIAD-CMD — Agent Boot Directory
2
+ # Copyright 2026 Joseph Stone — All Rights Reserved
3
+ # Created: 2026-04-05
4
+
5
+ ## Purpose
6
+ FIRST thing an agent reads at boot. Working directory, protocols, workflows, moral framework.
7
+
8
+ ## Location
9
+ SPFsmartGATE/LIVE/PROJECTS/PROJECTS/DEPLOY/TRIAD-CMD/
10
+
11
+ ## Load Order (MUST read in sequence)
12
+ 1. BOOT.md — Identity, working directory, state, module list ✅
13
+ 2. STATUS.md — Completed work, pending, blocked ✅
14
+ 3. MORAL_FRAMEWORK.md — Core values, IMMUTABLE ✅
15
+ 4. MEMORY_TRIAD.md — Memory systems, persistence ✅
16
+ 5. WORKFLOW.md — Confidence grading, SearchSeeker, review cycle ✅
17
+
18
+ ## Authority
19
+ When these conflict with outdated CLAUDE.md or external notes, TRIAD-CMD wins.
20
+ When source code (src/*.rs) conflicts with TRIAD-CMD, source code wins.
21
+
22
+ ## Boot Sync
23
+ For agents to boot from TRIAD-CMD, update CLAUDE.md boot_sequence steps to:
24
+ "READ TRIAD-CMD/BOOT.md FIRST (then follow load order)"
25
+ (CLAUDE.md is user-only — agent cannot modify boot files)
LIVE/LMDB5/TRIAD-CMD/SPF-FEATURES.md ADDED
@@ -0,0 +1,882 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPFsmartGATE v3.0.0 — Complete Feature List
2
+ ### 18,500+ lines of Rust | 42 modules | 7 LMDB databases | Multi-agent mesh network | FLINT on-device AI
3
+ *Copyright 2026 Joseph 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
+ - Gate alignment: 81.25% | Average loss: 0.648
857
+ - EWC lambda: 0.4 | Learning rate: 1e-4
858
+ - Online learning: ON | Replay buffer: 10,000 slots
859
+ - Checkpoint interval: 1,000 steps
860
+ - Checkpoint: LIVE/MODELS/writer_v1.spfc
861
+
862
+ ### 151. Model Architecture
863
+ - d_model: 256 | n_heads: 8 | n_layers: 6 | d_ff: 1,024
864
+ - Vocab: 8,192 | Params: ~5M
865
+ - Writer + Researcher configs
866
+
867
+ ---
868
+
869
+ ## XLIV. SECURITY EXCEPTIONS (Known Gaps)
870
+
871
+ | Gap | Description | Remediation |
872
+ |-----|-------------|-------------|
873
+ | GAP-1 | ChatText → handle_mesh_chat() — no gate routing | SEC-CHAT pending |
874
+ | GAP-2 | VoiceAudio — intentional, audio frames only | Accepted |
875
+ | GAP-3 | /proxy + /proxy/asset — SSRF only, bypasses dispatch | WB-2 pending |
876
+ | GAP-4 | /ws/browser — no gate/FLINT | SEC-WS pending |
877
+
878
+ ---
879
+
880
+ *Generated from source code analysis — verified 2026-04-05*
881
+ *8,245 → 18,500+ lines | 88 → 150+ features | 31 → 42 modules | 6 → 7 databases*
882
+ *New since February 2026: FLINT Transformer AI, Mesh Network, Chat, Voice, Browser, Pipeline, Network Pool, Channel Hub*
LIVE/LMDB5/TRIAD-CMD/STATUS.md ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # STATUS — SPF Smart Gateway
2
+ # Copyright 2026 Joseph Stone — All Rights Reserved
3
+ # Updated: 2026-04-05 (audited against LIVE src/ — source of truth, re-verified)
4
+ # Owner: FLINT (agents READ ONLY)
5
+
6
+ ═══════════════════════════════════════════════════════
7
+ BINARY — Current Deployed Build
8
+ ═══════════════════════════════════════════════════════
9
+ Location: ~/SPFsmartGATE/LIVE/BIN/spf-smart-gate/spf-smart-gate
10
+ Built: 2026-03-21 Session 10 (DEPLOY → live src rebuilt, 0 errors)
11
+ Mesh: ONLINE — controller node
12
+ Startup: pulseaudio --start (required on reboot)
13
+ TTS: espeak-ng FFI in-process (symlinked)
14
+ Source: 42 modules in src/lib.rs — 45 .rs files total (42 mod + main.rs + lib.rs + projects_db.rs + integration_tests.rs)
15
+ FLINT: Step 116, 6 batches completed, gate alignment 81.25%
16
+ Checkpoint: LIVE/MODELS/writer_v1.spfc (confirmed persistent)
17
+ Online learning: ON | EWC lambda: 0.4 | Learning rate: 1e-4
18
+ Replay buffer: 10,000 slots | Checkpoint interval: 1,000 steps
19
+
20
+ ═══════════════════════════════════════════════════════
21
+ MODULE INVENTORY (from src/lib.rs — verified 2026-04-04 audit)
22
+ ═══════════════════════════════════════════════════════
23
+
24
+ paths, calculate, config, gate, inspect, mcp, session, storage, validate,
25
+ web, http, dispatch, identity, mesh, fs, config_db, tmp_db, agent_state,
26
+ tensor, tokenizer, framing, attention, ffn, encoder, decoder, transformer,
27
+ checkpoint, gate_training, transformer_tools, train, learning, pipeline,
28
+ worker, network, chat, voice, utf8_safe, brain_local, flint_memory,
29
+ browser, orchestrator, channel
30
+
31
+ Total: 42 modules
32
+
33
+ ═══════════════════════════════════════════════════════
34
+ COMPLETED — All verified LIVE in src/
35
+ ═══════════════════════════════════════════════════════
36
+
37
+ ## Gate + Security (src/gate.rs 493 lines, validate.rs 1481 lines, inspect.rs)
38
+ P1-01 ✅ 26/26 Phase 1 memory blocks
39
+ P2-01 ✅ 6/6 Phase 2 memory blocks
40
+ BK-EE ✅ Evil Detection Layer (gate_training.rs — 4-tier moral framework)
41
+ BK-PP ✅ Chat Toggle (chat_enabled flag in transformer_tools.rs)
42
+ BK-QQ ✅ FLINT Mesh Auto-Response (chat.rs — rate limited)
43
+ SEC-2 ✅ Blocked paths in config.rs
44
+ SEC-3 ✅ Boot integrity check in mcp.rs
45
+ SEC-4 ✅ API key env var in http.rs
46
+
47
+ ## Dispatch + Execution (src/dispatch.rs 506 lines)
48
+ FL-0 ✅ FLINT Permission Unlock — TRANSFORMER_BLOCKED removed
49
+ FL-0B ✅ Tri-Memory Connection — route_signals creates Working memories
50
+ FL-1A ✅ Source-aware lock (Stdio=blocking, others=timed try_lock + SERVER_BUSY)
51
+ FL-1B ✅ Stdio routes through dispatch::call() — Block BB removed
52
+ FL-1C ✅ FLINT intercept (pre-execution brain query) + process_result (post-execution store/enrich)
53
+ FL-1 ✅ Training signal persistence — tlog:* keys in LMDB
54
+ FL-2 ✅ Result Compression — FULL/SUMMARY/DIGEST tiers + originals preserved in brain >2000 chars
55
+ FL-3 ✅ Context Injection — brain hits attached to responses via _flint_context
56
+ FL-4 ✅ Mesh FLINT Coordination — all transports use dispatch::call()
57
+ FL-5 ✅ Confusion matrix persisted to LMDB
58
+ FL-6 ✅ FP-locked replay persisted to LMDB
59
+ FL-7 ✅ Tool call context stored as language training pairs (lang:*)
60
+ FL-8 ✅ spf_flint_train_evil + spf_flint_train_good tools
61
+ FL-9 ✅ Dead code removed (LRScheduler, LearningController, convergence)
62
+ FL-10 ✅ Auto-train threshold simplified — LMDB tlog count >= 16 OR 1hr interval
63
+
64
+ ## Voice Pipeline (src/voice.rs 2071 lines — espeak-ng TTS, Opus codec, cpal audio)
65
+ BK-LL ✅ Voice Playback Wiring
66
+ BK-MM ✅ Voice Line Architecture (Light/Rich/VoiceSettings)
67
+ OP-55 ✅ Opus Migration (audiopus_sys → opus-codec)
68
+ MB-V0 ✅ Voice integrated as pub(crate) mod spf_voice (not separate crate — BF-4)
69
+ VF-3 ✅ voice.rs — listen() u32→u64 fixed
70
+ VA-1 ✅ All 7 stale voice refs cleaned
71
+
72
+ ## FLINT Memory Router (src/flint_memory.rs 1065 lines)
73
+ MB-FR ✅ FLINT Memory Router — background thread, gate event scoring, drop folder watcher
74
+ MB-FT ✅ Tiered Loop Engine — Working→Fact→Pinned promotion (usage-based scoring)
75
+ R3-04 ✅ Build Anchor Context function (brain-assisted source context for Write/Edit)
76
+ R3-05 ✅ Wire Build Anchor into intercept (merged with brain hits)
77
+ R3-06 ✅ Read tracking for build anchor (compression disabled for non-Claude LLM compatibility)
78
+ R3-07 ✅ Agent Read Interface — gate brain write block (spf_brain_store/brain_index blocked from Stdio)
79
+ R3-10 ✅ FLINT metrics wiring through memory router (hourly write to FLINT_METRICS.txt)
80
+
81
+ ## FLINT Persistence + Learning (transformer_tools.rs 1052 lines)
82
+ SB-1 ✅ stoneshell-brain warnings fixed (cosmetic prefix change)
83
+ CP-1 ✅ Checkpoint save after training (transformer_tools.rs:664-678)
84
+ CP-2 ✅ Checkpoint load on startup (transformer_tools.rs:176-227)
85
+ AT-1 ✅ Auto-train in memory router (flint_memory.rs:606-627 — 1hr/16 signals)
86
+ TM-1 ✅ 30-day archive + >80% usage promotion (flint_memory.rs)
87
+ CM-1 ✅ Removed 24hr grace period — compression active from start (Read passthrough preserved)
88
+
89
+ ## Pipeline + API Sessions (src/pipeline.rs 1107 lines)
90
+ PP-1 ✅ Pipeline Protocol — batch submit, chain execution, backpressure
91
+ PP-2 ✅ API Session Layer — full duplex agent-to-agent encrypted sessions
92
+ Includes: PipelineTask/PipelineResult types, ApiSessionMsg, 14 tests
93
+
94
+ ## Network Pool (src/network.rs 526 lines)
95
+ ✅ Full pool management: PoolState, WorkerStatus, ProofOfWork
96
+ ✅ NetAdmin orchestrator over iroh QUIC mesh
97
+ ✅ Proof of work receipt logged to session.record_manifest_detailed()
98
+
99
+ ## Qwen Compatibility
100
+ QW-1 ✅ Tool prefix aliasing for Qwen LLM compatibility
101
+ QW-2 ✅ Param alias absolute_path → file_path + FL-8 tool definitions
102
+
103
+ ## Infrastructure
104
+ PF-1 ✅ SPF_ROOT env var — configurable base path
105
+ CL-1 ✅ Identity key self-test at boot
106
+ RC-1 ✅ Brain load retry (3 attempts, 2s delay)
107
+ RC-2 ✅ FLINT checkpoint load in serve mode — CONFIRMED persistent (step ≠ 0 on boot)
108
+ LM-1 ✅ LMDB map_size increase + promote dedup fix
109
+ LM-2 ✅ Brain store failure handling in memory router (3 consecutive failures → expire old)
110
+ RG-1 ✅ Remove Python RAG subprocess dependency
111
+
112
+ ## R2 Reliability Fixes
113
+ FIX-1 ✅ Brain store safety in archive_old_pinned
114
+ FIX-2 ✅ Checkpoint interval guard + >0 safety
115
+ FIX-3 ✅ VecDeque for SignalBuffer
116
+ FIX-4 ✅ Vector graduation + forget on promotion
117
+ FIX-5 ✅ 4-phase lock restructure (forward on clone, backward, optimizer, adopt)
118
+ FIX-6 ✅ Auto-resolved by FIX-2
119
+
120
+ ## R2 Token Reduction
121
+ TR-D ✅ Smart Grep/Glob compression (flint_memory.rs)
122
+
123
+ ## Build + Deploy
124
+ BD-1 ✅ Voice module placed in src/voice.rs (pub(crate) mod spf_voice)
125
+ BD-2 ✅ build.rs restored — espeak-ng linker fixed
126
+ BD-3 ✅ Binary rebuilt and deployed
127
+ BD-4 ✅ lib.rs — pub mod flint_memory added
128
+ BD-5 ✅ mcp.rs — memory router spawn wired
129
+
130
+ ## Build Errors Fixed (Session 10)
131
+ BF-1 ✅ mcp.rs: browser/ws_browser_channels/http_port params added to handle_tool_call()
132
+ BF-2 ✅ Cargo.toml: default=[] + voice-stt/voice-tts empty features
133
+ BF-3 ✅ voice.rs: mod spf_voice → pub(crate) mod spf_voice
134
+ BF-4 ✅ mcp.rs: use crate::voice::spf_voice import added
135
+ BF-5 ✅ dispatch.rs: updated call site with 3 new browser params
136
+ Result: 18 errors → 3 → 0, clean build
137
+
138
+ ## Security Audit — Native Claude Tool Block
139
+ SA-1 ✅ .claude.json permissions.block expanded 10 → 26 native tools
140
+ SA-2 ✅ settings.json permissions.deny expanded 5 → 26 native tools
141
+ SA-3 ✅ settings.local.json permissions.deny expanded 5 → 26 native tools
142
+
143
+ ## Security Exceptions (known gaps)
144
+ GAP-1 ⚠️ ChatText → handle_mesh_chat() — no gate routing → SEC-CHAT pending
145
+ GAP-2 ✅ VoiceAudio → handle_mesh_voice() — intentional, audio frames only
146
+ GAP-3 ⚠️ /proxy + /proxy/asset — validate_url SSRF only, bypasses dispatch → WB-2
147
+ GAP-4 ⚠️ /ws/browser — browser commands direct to BrowserSession, no gate/FLINT → SEC-WS
148
+
149
+ ## Security
150
+ SEC-2 ✅ Blocked paths in config.rs
151
+ SEC-3 ✅ Boot integrity check in mcp.rs
152
+ SEC-4 ✅ API key env var in http.rs
153
+
154
+ ## Retired
155
+ MB-A2 ❌ Voice Test (TTS+STT) — replaced by JNI Voice Command Bar
156
+ MB-A4 ❌ Termux Soft-Embed — replaced by Stone Shell Terminal
157
+ MB-T1 ❌ Termux block 1 — retired, replaced by R2
158
+ MB-T2 ❌ Termux block 2 — retired, replaced by R2
159
+ MB-T3 ❌ Termux block 3 — retired, replaced by R2
160
+
161
+ ═══════════════════════════════════════════════════════
162
+ BLOCKED — Waiting on External Dependencies
163
+ ═══════════════════════════════════════════════════════
164
+ BL-1 ❌ Voice STT — PulseAudio has no real audio devices on Termux
165
+ cpal→PulseAudio→ALSA stack broken — architecture problem
166
+ TTS works (espeak-ng FFI). STT needs JNI (Stone Shell Terminal)
167
+
168
+ BL-2 ❌ Stone Shell Terminal — Android APK replaces Termux entirely
169
+ 7 crates, 8-core pipeline, JNI bridge built
170
+ 50 features (P0-P2), ~12,300 lines, ~5,000 already written
171
+ Ref: TERMINAL/WORK_BLOCKS.md (41 blocks)
172
+
173
+ ═��═════════════════════════════════════════════════════
174
+ PENDING — Next Work (in priority order)
175
+ ═══════════════════════════════════════════════════════
176
+ # ID What Action
177
+ 1 SEC-CHAT ⬜ Chat /ai cmd routing through dispatch() src/chat.rs + dispatch.rs
178
+ 2 SEC-WS ⬜ /ws/browser security gap (validator + eval) src/http.rs
179
+ 3 #43-4 ⬜ Remove pipeline chain system pipeline.rs + mesh.rs + framing.rs
180
+ 4 #43-3 ⬜ spf_status unified health dashboard src/mcp.rs
181
+ 5 #43-1 ⬜ network.rs dynamic status strings src/network.rs (rewritten for pool)
182
+ 6 #43-2 ⬜ mcp.rs static tool descriptions update src/mcp.rs
183
+ 7 CHAT-A ⬜ Chat protocol upgrade (receipts, rooms) src/chat.rs
184
+ 8 CHAT-B ⬜ Identity layer (names, mDNS, pairing) src/chat.rs + mesh.rs
185
+ 9 CHAT-C ⬜ Web UI (/chat + /ws/chat SPA) src/http.rs + chat.rs
186
+ 10 CHAT-D ⬜ TUI frontend (ratatui + crossterm) src/tui.rs (new)
187
+ 11 CHAT-E ⬜ FLINT as chat participant (/ai cmd) src/chat.rs + dispatch.rs
188
+ 12 CHAT-F ⬜ QR pairing + invite links (optional) src/http.rs + chat.rs
189
+ 13 MESH-RP ⬜ Mesh re-pair controller node USER ACTION — cert refresh
190
+ 14 TR-A ⬜ CLAUDE.md dedup (~8,000 tokens/session) USER ACTION — symlinks
191
+ 15 TR-B ⬜ Brain-assisted Build Anchor New function in flint_memory.rs
192
+ 16 TR-E ⬜ Build Anchor from brain (extends TR-B) Workflow change + intercept
193
+ 17 TR-C ⬜ Session file cache (prevent re-reads) New logic in compress_result
194
+ 18 CLONE ⬜ Test clone SPF + mesh network After next build
195
+ 19 MB-FC ⬜ FLINT User CLI Separate binary, local socket
196
+ 20 MB-FA ⬜ Agent Read Interface Block brain WRITE from Stdio
197
+ 21 MB-FM ⬜ FLINT owns STATUS + WORK_BLOCKS Auto-update on phase change
198
+
199
+ ═══════════════════════════════════════════════════════
200
+ REFERENCES
201
+ ═══════════════════════════════════════════════════════
202
+ DEPLOY/TRIAD-CMD/BOOT.md — Agent boot entry point (created 2026-04-14)
203
+ DEPLOY/TRIAD-CMD/STATUS.md — Canonical STATUS copy in boot folder
204
+ DEPLOY/TRIAD-CMD/MEMORY_TRIAD.md — Memory system architecture
205
+ DEPLOY/TRIAD-CMD/WORKFLOW.md — Confidence-graded work blocks
206
+ DEPLOY/TRIAD-CMD/MORAL_FRAMEWORK.md — FLINT moral framework (IMMUTABLE)
207
+ DEPLOY/TRIAD-CMD/README.md — Boot folder index + load order
208
+ DEPLOY/README.md — Full project README (source-accurate)
209
+ DEPLOY/WORK_BLOCKS.md — Master work block list
210
+
211
+ ## LEARNING PIPELINE — ACTIVE
212
+ PRE (startup): init_brain() + index_knowledge_docs() + index_spf_sources()
213
+ DURING (30s loop): GateTrainingCollector → FLINT scores → route_signals → brain_store()
214
+ AFTER (1hr loop): expire → Working→Fact → Fact→Pinned → auto-train (16+ tlog or 1hr)
215
+
216
+ ## Brain state (verified 2026-04-05 — live)
217
+ Collections: 7 (spf_source 465, flint_training 2013, flint_results 448, default 392,
218
+ flint_knowledge 49, session_state 4, flint_episodic 2)
219
+ Total docs: 3,371 | Storage: 31.41 MB | Model: all-MiniLM-L6-v2 loaded
220
+
221
+ ## Voice module
222
+ Location: src/voice.rs — pub(crate) mod spf_voice (NOT separate crate)
223
+ TTS: espeak-ng FFI in-process
224
+ Codec: Opus static (libopus.a)
225
+ Audio: cpal + opus-codec
226
+ Libs: libespeak-ng.so (/usr/lib), libopus.a + liboboe-ext.a (SPFsmartGATE/lib/)
227
+
228
+ ═══════════════════════════════════════════════════════
229
+ END STATUS
230
+ ═══════════════════════════════════════════════════════
LIVE/LMDB5/TRIAD-CMD/WORKFLOW.md ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # WORKFLOW — Confidence-Graded Work Blocks + SearchSeeker Data Serving
2
+ # Copyright 2026 Joseph Stone — All Rights Reserved
3
+ # Created: 2026-04-05
4
+ # Phase: DRAFT (SearchSeeker design + agent workflow, FLINT excluded from Phase 1)
5
+
6
+ ========================================================================
7
+ WORK BLOCK LIFECYCLE
8
+ ========================================================================
9
+
10
+ 1. AGENT CREATES WORK BLOCK
11
+ - Reads task → plans → creates work block in WORK_BLOCKS.md
12
+ - Builds the block (code, docs, config)
13
+ - Assigns CONFIDENCE SCORE (1-100) REQUIRED
14
+ - Records reason for score, data gaps, uncertainties
15
+
16
+ 2. CONFIDENCE GATE EVALUATION
17
+ Score >= 85: PASS — no twin folder needed
18
+ Score 60-84: REVIEW — twin folder, data served
19
+ Score < 60: FAIL — twin folder, urgent data search
20
+
21
+ 3. TWIN FOLDER STRUCTURE
22
+ WORK_BLOCKS/HH-123/ ← original work block
23
+ WORK_BLOCKS/HH-123-DATA/ ← SearchSeeker served data (if low confidence)
24
+
25
+ 4. SEARCHSEEKER DATA RETRIEVAL
26
+ Step 1: BRAIN VECTOR SEARCH (first, local data — LMDB backed vectors only)
27
+ - Query: work block title, data gaps, files touched
28
+ - Collections: spf_source, default, flint_results
29
+ - Deduplicate hits, score by relevance
30
+
31
+ Step 2: WEB SEARCH (second, external fill)
32
+ - If brain gaps remain → spf_web_search + spf_web_fetch
33
+ - Clean text extraction (no HTML storage)
34
+
35
+ Step 3: SERVE TO TWIN
36
+ - SUMMARY.md — overview, gap count, recommendation
37
+ - brain_hits.md — brain results grouped by gap
38
+ - web_results.md — web results
39
+ - gaps.md — per-gap: query, results, filled/remaining
40
+
41
+ 5. AGENT REVIEW CYCLE
42
+ After agent completes ALL initial work blocks:
43
+ - Scan for any *-DATA twin folders
44
+ - For each: read served data → identify missing info → upgrade block
45
+ - Re-grade confidence (never lower than original)
46
+ - If >= 90: RESOLVED
47
+ - If 75-89: RESOLVED with note (minor risk accepted)
48
+ - If 60-74: STILL AT RISK — second review needed
49
+ - If < 60: BLOCKED — needs external input
50
+
51
+ ========================================================================
52
+ CONFIDENCE SCALCULATION
53
+ ========================================================================
54
+
55
+ Score starts at 100, each verified gap deducts:
56
+
57
+ -10 File hasn't been read yet (unread source)
58
+ -15 Unknown API/interface (can't verify function signatures)
59
+ -12 No existing pattern to follow (building new from scratch)
60
+ -8 Potential merge conflict with other work blocks
61
+ -10 Unknown side effects (downstream impacts not traced)
62
+
63
+ Capped at 0 minimum, 100 maximum.
64
+
65
+ Agent MUST record each deduction in the Data Gaps section.
66
+ A score without stated gaps is INVALID.
67
+
68
+ ========================================================================
69
+ SEARCHSEEKER CONFIGURATION (Phase 1)
70
+ ========================================================================
71
+
72
+ Trigger: Work block confidence < 85 detected
73
+ Sources: Brain vectors (LMDB, local) → Web API (external)
74
+ Output: HH-123-DATA/ folder with structured markdown files
75
+ Agent: Reviews post-completion, upgrades work, re-grades
76
+
77
+ ========================================================================
78
+ WORK BLOCK FORMAT
79
+ ========================================================================
80
+
81
+ Each block in WORK_BLOCKS.md uses this format:
82
+
83
+ ---
84
+ block_id: HH-123
85
+ title: "Block title"
86
+ confidence: 72
87
+ graded_at: 2026-04-05
88
+ status: draft | in_review | resolved | blocked
89
+ ---
90
+
91
+ ### Block HH-123 — Title
92
+ Status: ⬜ PENDING
93
+ Confidence: 72
94
+ Files: src/x.rs
95
+
96
+ ANALYSIS:
97
+ [What the block addresses]
98
+
99
+ CHANGES:
100
+ [What will be changed, file:line]
101
+
102
+ WHY:
103
+ [Why this change is needed]
104
+
105
+ TRACEBACK:
106
+ [Full call chain verification]
107
+
108
+ VERIFY:
109
+ [How to test]
110
+ RISK: LOW | MEDIUM | HIGH
111
+ Lines: ~N new/modified
112
+ Dependencies: None | Block X
113
+
114
+ ========================================================================
115
+ END WORKFLOW
116
+ ========================================================================