# TEMPESTA v0.4.0 — SYNTHESIS (Step 4)

## Inputs Consumed
- CORTEX_V04_ADVERSARY.md — 42 failure modes, 11 must-fix
- CORTEX_V04_CONTRACTS.md — 6 tools with Rust structs
- CORTEX_V04_TESTS.md — 26 golden tests
- CORTEX_V04_VISION.md — web-grounded alternatives
- M1ND_HELP_VISUAL_SPEC.md — visual identity spec
- Max's requirements from session (personality, Gaia, identity, suggest_next)

---

## DECISIONS (Step 5) — every ambiguity resolved

### D1: Tool count strategy
ORACLE-VISION says "don't add tools, extend existing ones."
ADVERSARY says "deprecate seek in favor of search."
**DECISION:** Create `search` with 3 modes (literal/regex/semantic). Keep `seek` as alias that calls `search(mode="semantic")`. Net new tools: search, help, panoramic, efficiency = 4 new. Fix perspective = 0 new. Total: 56 → 60.

### D2: Personality in responses
Max said: "o m1nd tem que ter personalidade, identidade visual, calor nas respostas."
**DECISION:** Every tool response includes an optional `_m1nd` metadata field:
```json
{
  "result": { ... },
  "_m1nd": {
    "suggest_next": ["impact(node_id) to check blast radius", "learn(feedback) to strengthen edges"],
    "savings": {"tokens_saved": 750, "session_total": 48230},
    "gaia": {"global_tokens_never_burned": 2100000},
    "personality": "found 8 results for 'rate limiting'. top hit is smart_router.py (0.98) — 61 dependents, be careful here."
  }
}
```
The `personality` field is a one-line human-readable summary. NOT generated by LLM — template-based in Rust. Pattern: "{count} results for '{query}'. top hit is {label} ({score}) — {context_hint}."

### D3: Visual identity in help output
4 letters = 4 dimensions. This is the DNA.
```
M = #60A5FA (blue)     → STRUCTURAL (who calls who)
1 = #FBBF24 (gold)     → TEMPORAL (what changed together)
N = #F472B6 (magenta)  → CAUSAL (what broke when this changed)
D = #818CF8 (indigo)   → SEMANTIC (naming patterns)
△ = #34D399 (green)    → THE GRAPH (activation signal)
```
**DECISION:** help output uses ANSI colors matching these. Category icons:
- 🔵 Foundation (M blue)
- ⚡ Superpowers (1 gold)
- 🔬 Extended (N magenta)
- 🔭 Perspective
- 🔒 Lock
- 🔪 Surgical (△ green)
- 📊 Panoramic
- 🌍 Efficiency

### D4: Gaia protection counter
Max said: "quanto o m1nd ajudou o planeta evitando que as llms fizessem leituras desnecessarias"
**DECISION:** Every response includes `_m1nd.gaia.global_tokens_never_burned`. Persists in `savings_state.json` alongside graph. Three levels:
- **query**: this specific query saved ~X tokens
- **session**: cumulative this session
- **global**: cumulative across all sessions (persisted)

Estimation formula:
- `activate/seek` → saved ~15 grep calls × ~50 tokens = 750 tokens
- `surgical_context` → saved ~8 Read calls × ~400 tokens = 3200 tokens
- `surgical_context_v2` → saved ~12 Read calls × ~400 tokens = 4800 tokens
- `impact/hypothesize/missing` → saved ~5 analysis calls × ~200 tokens = 1000 tokens
- `apply/apply_batch` → saved ~3 Write+verify calls × ~300 tokens = 900 tokens

### D5: suggest_next in EVERY response
Not just in help. EVERY tool response has `_m1nd.suggest_next[]`:
- After `activate` → suggest `impact(top_result)`, `learn(feedback)`, `hypothesize(claim)`
- After `impact` → suggest `validate_plan(files)`, `counterfactual(node)`
- After `hypothesize` → suggest `missing(query)`, `trace(error)`, `learn(feedback)`
- After `surgical_context` → suggest `apply(file, content)`, `apply_batch(edits)`
- After `apply` → suggest `predict(changed_node)`, `learn(feedback)`
Hardcoded mapping in Rust. ~20 lines.

### D6: report format
ORACLE-VISION says "integrate into trail.save."
**DECISION:** Keep `report` as standalone tool BUT also auto-generate mini-report in trail.save. Report returns markdown by default — optimized for LLM context injection.

### D7: panoramic weights
Default weights for combined_risk:
```
trust: 0.25
tremor: 0.20
layer_violations: 0.15
turbulence: 0.20
antibody_matches: 0.15
epidemic_risk: 0.05
```
Critical threshold: combined_risk >= 0.7

### D8: perspective.routes fix
Root cause (from ADVERSARY): `perspective.start` creates perspective with `focus_node: None` and never computes routes on cache miss.
**FIX:** After creating perspective, if focus_node resolved, compute routes immediately. If routes cache is None on `.routes()` call, recompute instead of returning empty.

### D9: efficiency honesty
ORACLE-VISION says: "be honest when grep would have been faster."
**DECISION:** If the query is a simple literal match on a known keyword, `_m1nd.savings.note` says "for this specific query, grep would be ~equal speed. m1nd's value is in the graph context, not raw speed."

### D10: search inverted index
ADVERSARY warns about ReDoS and unbounded results.
ORACLE-VISION suggests ripgrep integration.
**DECISION:** For literal/regex mode, build a simple inverted token index at ingest time (HashMap<String, Vec<(NodeId, u32)>>). For regex, use the `regex` crate with timeout. Cap results at `top_k` (default 50). No shell-out to ripgrep — keep it pure Rust.

---

## FILES THE BUILD AGENT MUST CREATE/MODIFY

### New files:
1. `m1nd-mcp/src/search_handlers.rs` — search, help handlers
2. `m1nd-mcp/src/report_handlers.rs` — report, panoramic, efficiency handlers
3. `m1nd-mcp/src/personality.rs` — `_m1nd` metadata builder, suggest_next mapping, savings tracker, personality templates

### Modified files:
4. `m1nd-mcp/src/server.rs` — add dispatch for 4 new tools, add `_m1nd` wrapper to ALL tool responses
5. `m1nd-mcp/src/protocol/surgical.rs` or new `protocol/v04.rs` — new structs
6. `m1nd-mcp/src/perspective_handlers.rs` — fix routes bug
7. `m1nd-mcp/src/session.rs` — add SavingsTracker, query_log to SessionState
8. `m1nd-core/src/lib.rs` — expose inverted index from ingest for search

### State files (persisted):
9. `savings_state.json` — global savings counter

---

## MUST-FIX BEFORE SHIPPING (from ADVERSARY, prioritized)

P0 (blocks ship):
1. Search: cap results at top_k, regex timeout
2. Report: add query_log to SessionState
3. Panoramic: don't hold mutex for 7 sequential tools — release between each
4. Perspective: fix routes empty bug

P1 (ship but fix soon):
5. Search: scope validation (prevent path traversal in scope param)
6. Savings: document estimation methodology in help output
7. Help: handle unknown tool gracefully (suggest closest match)

---

## PERSONALITY TEMPLATES (Rust string formatting)

```rust
// After activate
format!("found {} results for '{}'. top hit: {} ({:.2}) — {} dependents",
    count, query, top_label, top_score, caller_count)

// After impact
format!("{} nodes in blast radius. {} at depth 1, {} at depth 2. careful here.",
    total, d1, d2)

// After hypothesize
format!("verdict: {} ({:.0}% confidence). {} paths explored in {:.0}ms.",
    verdict, confidence*100.0, paths, elapsed)

// After apply
format!("done. {} lines changed in {:.0}ms. graph updated. {} files may need attention.",
    lines, elapsed, predict_count)

// After panoramic
format!("{} modules scanned. {} critical alerts. worst: {} (risk {:.2}).",
    total, critical, worst_label, worst_risk)
```

Not chatbot. Not hype. Just a brother telling you what matters.

---

## VISUAL IDENTITY — THE DNA (from m1nd.world landing page)

### Logo Glyphs = Core Concepts (EXACT Unicode from wiki-build/index.html)
```
⍌  U+234C   SIGNAL      cyan (#00D4FF)     — spreading activation signal
⍐  U+2350   PATH        gold (#FFD700)     — paths through the graph
⍂  U+2342   STRUCTURE   magenta (#FF00FF)  — structural analysis
𝔻  U+1D53B  DIMENSION   blue (#4169E1)     — 4D dimensional scoring
⟁  U+27C1   CONNECTION  green (#00FF88)    — graph connections, edges
```

### Wiki CSS Color Variables
```css
--cyan: #00D4FF;      /* ⍌ SIGNAL */
--yellow: #FFD700;    /* ⍐ PATH */
--magenta: #FF00FF;   /* ⍂ STRUCTURE */
--blue: #4169E1;      /* 𝔻 DIMENSION */
--green: #00FF88;     /* ⟁ CONNECTION */
```

Each glyph IS a core concept of m1nd. Use these in:
- help output headers (glyph + concept name)
- report section headers
- panoramic risk categories
- Any branded m1nd output

Example help header:
```
⍌ SIGNAL  |  activate
spreading activation query — fire signal into the graph
```

Example category mapping for help("all"):
```
⍌ Foundation (13)    — core graph signal operations
⍐ Perspective (12)   — path navigation through the graph
⍂ Superpowers (13)   — structural reasoning + analysis
𝔻 Extended (9)       — multi-dimensional cross-domain science
⟁ Surgical (4)       — connection editing (read + write code)
⟁ Lock (5)           — connection safety (concurrent access)
```

### The 12 Disciplines (numbered, monospace, green, uppercase)
Style: `font-family: monospace; color: #00E5A0; text-transform: uppercase; letter-spacing: 2px`
```
01 — NEUROSCIENCE        spreading activation, Hebbian plasticity
02 — PERFORMANCE         local Rust, zero tokens, $0.00/query
03 — SOCIOLOGY           multi-agent coordination, cortex protocol
04 — COGNITIVE SCIENCE   perspective navigation, stateful exploration
05 — SIGNAL PROCESSING   XLR noise cancellation (from audio engineering)
06 — DISTRIBUTED SYSTEMS lock system, advisory locks, conflict detection
07 — IMMUNOLOGY          antibody bug patterns, immune memory
08 — FLUID DYNAMICS      flow simulation, particle propagation
09 — EPIDEMIOLOGY        SIR model, bug spread prediction
10 — SEISMOLOGY          tremor detection, change acceleration
11 — ACTUARIAL SCIENCE   trust scoring, defect history risk
12 — NEUROSCIENCE/LAYERS layer detection, architectural violations
```

### Perspective Navigation Icons (from landing page)
```
🔍 start     — open perspective
🧭 routes    — browse ranked routes
🎯 follow    — move to target node
🔀 branch    — fork exploration
💡 suggest   — AI navigation recommendation
⚖️ compare   — diff two perspectives
```

### Category Icons for help output
```
🔵 Foundation (13)     — M blue (#60A5FA)
🔭 Perspective (12)    — cognitive science
🔒 Lock (5)            — distributed systems
⚡ Superpowers (13)    — 1 gold (#FBBF24)
🔬 Extended (9)        — N magenta (#F472B6)
🔪 Surgical (4)        — △ green (#34D399)
🔍 Search              — literal/regex/semantic
📊 Panoramic           — combined raio-X
🌍 Efficiency          — savings + Gaia counter
❓ Help                — self-documenting
📋 Report              — session intelligence
```

### Color CSS Variables (from m1nd.world)
```css
--bg: #080C14;
--surface: #0F1420;
--border: #1E2433;
--text: #F0F2F5;
--text-dim: #5A6577;
--green: #00E5A0;
--green-dim: #00B87A;
--red: #FF4757;
--blue: #60A5FA;
--gold: #FBBF24;
--magenta: #F472B6;
--indigo: #818CF8;
--mono: 'JetBrains Mono', 'Fira Code', 'Cascadia Code', monospace;
```

### BUILD MUST USE these colors/icons in:
1. `help` output — category icons, dimension colors, ANSI formatting
2. `_m1nd.personality` — tone matches the landing page voice (direct, warm, technical)
3. `m1nd.report` — numbered sections like the 12 disciplines (monospace, green, uppercase headers)
4. `m1nd.panoramic` — risk levels use red/yellow/green from the palette
