nexo-brain 0.10.0-beta.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,12 +1,12 @@
1
1
  # NEXO Brain — Your AI Gets a Brain
2
2
 
3
- [![npm v0.10.0-beta.8](https://img.shields.io/npm/v/nexo-brain?label=npm&color=purple)](https://www.npmjs.com/package/nexo-brain)
3
+ [![npm v1.0.0](https://img.shields.io/npm/v/nexo-brain?label=npm&color=purple)](https://www.npmjs.com/package/nexo-brain)
4
4
  [![F1 0.588 on LoCoMo](https://img.shields.io/badge/LoCoMo_F1-0.588-brightgreen)](https://github.com/wazionapps/nexo/blob/main/benchmarks/locomo/results/)
5
5
  [![+55% vs GPT-4](https://img.shields.io/badge/vs_GPT--4-%2B55%25-blue)](https://github.com/snap-research/locomo/issues/33)
6
6
  [![GitHub stars](https://img.shields.io/github/stars/wazionapps/nexo?style=social)](https://github.com/wazionapps/nexo/stargazers)
7
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
8
 
9
- > **v0.10.0-beta.8** — 30 Core System Rules (versioned, with migration). Battle-tested behavioral rules from 6 months production use, validated via multi-AI debate (Claude + GPT-4o). 6 categories: Integrity, Execution, Memory, Delegation, Communication, Proactivity. 25 BLOCKING + 5 ADVISORY. Plus: Smart Startup, Context Packets, Auto-Prime, and zero-decay pinning.
9
+ > **v1.0.0** — Cognitive Cortex, 30 Core Rules as DNA, Smart Startup, Context Packets, Auto-Prime. The first AI memory system with architectural inhibitory control — the agent reasons about whether to act before acting. Battle-tested from 6 months of production use, validated via multi-AI debate (Claude Opus + GPT-5.4 + Gemini 3.1 Pro).
10
10
 
11
11
  **NEXO Brain transforms any MCP-compatible AI agent from a stateless assistant into a cognitive partner that remembers, learns, forgets, adapts, and builds a relationship with you over time.**
12
12
 
@@ -136,9 +136,36 @@ Like a human brain, NEXO Brain has automated processes that run while you're not
136
136
 
137
137
  If your Mac was asleep during any scheduled process, NEXO Brain catches up in order when it wakes.
138
138
 
139
+ ## Cognitive Cortex (v1.0.0)
140
+
141
+ The Cortex is a middleware cognitive layer that makes the agent **think before acting**. It implements architectural inhibitory control — the agent cannot bypass reasoning.
142
+
143
+ ```
144
+ User message → Fast Path check → Simple chat? → Respond directly
145
+ → Action needed? → Cortex activates
146
+
147
+ Generate cognitive state
148
+ (goal, plan, unknowns, evidence)
149
+
150
+ Middleware validates
151
+ ├─ Unknowns? → ASK mode (tools blocked)
152
+ ├─ No plan? → PROPOSE mode (read-only)
153
+ └─ Plan + evidence → ACT mode (full access)
154
+ ```
155
+
156
+ | Feature | What It Does |
157
+ |---------|-------------|
158
+ | **Inhibitory Control** | Physically restricts tools based on reasoning quality. Unknowns → can only ask. No plan → can only propose. Evidence + verification → can act. |
159
+ | **Event-Driven Activation** | Only activates on tool intent, ambiguity, destructive actions, or retries. Simple chat has zero overhead. |
160
+ | **Trust-Gated Escalation** | Low trust score → requires more evidence before allowing "act" mode. Trust builds through successful execution. |
161
+ | **Core Rules Injection** | Automatically surfaces relevant behavioral rules based on task type. |
162
+ | **Activation Metrics** | Tracks modes, inhibition rates, and task types for continuous improvement. |
163
+
164
+ The Cortex was designed through a 3-way AI debate (Claude Opus 4.6 + GPT-5.4 + Gemini 3.1 Pro) and validated against 6 months of real production failures.
165
+
139
166
  ## Cognitive Features
140
167
 
141
- NEXO Brain provides 27 cognitive tools on top of the 76 base tools, totaling **111+ MCP tools**. These features implement cognitive science concepts that go beyond basic memory:
168
+ NEXO Brain provides 29 cognitive tools on top of the 76 base tools, totaling **113+ MCP tools**. These features implement cognitive science concepts that go beyond basic memory:
142
169
 
143
170
  ### Input Pipeline
144
171
 
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "nexo-brain",
3
- "version": "0.10.0-beta.8",
3
+ "version": "1.0.0",
4
4
  "mcpName": "io.github.wazionapps/nexo",
5
- "description": "NEXO Cognitive co-operator for Claude Code. Atkinson-Shiffrin memory, semantic RAG, trust scoring, and metacognitive error prevention.",
5
+ "description": "NEXO \u2014 Cognitive co-operator for Claude Code. Atkinson-Shiffrin memory, semantic RAG, trust scoring, and metacognitive error prevention.",
6
6
  "bin": {
7
7
  "nexo-brain": "./bin/nexo-brain.js"
8
8
  },
@@ -32,4 +32,4 @@
32
32
  "templates/",
33
33
  "scripts/"
34
34
  ]
35
- }
35
+ }
@@ -0,0 +1,299 @@
1
+ """Cognitive Cortex plugin — middleware cognitive layer for NEXO Brain.
2
+
3
+ Provides structured pre-action reasoning with architectural inhibitory control.
4
+ The Cortex does NOT generate answers — it gates, plans, and validates actions.
5
+
6
+ Activation: event-driven, not on every turn. Only on:
7
+ - Tool intent (edit, execute, delegate)
8
+ - Ambiguity in user request
9
+ - Destructive actions
10
+ - Multi-step tasks
11
+ - Retry after failure
12
+ - Contradictions with known facts
13
+
14
+ v0.1: Single MCP tool + middleware validation.
15
+ """
16
+
17
+ import json
18
+ import time
19
+
20
+
21
+ def _get_db():
22
+ from db import get_db
23
+ return get_db()
24
+
25
+
26
+ def _get_core_rules_for_task(task_type: str) -> list[str]:
27
+ """Get relevant Core Rules for the given task type."""
28
+ conn = _get_db()
29
+ try:
30
+ # Map task type to rule categories
31
+ category_map = {
32
+ "edit": ["integrity", "execution"],
33
+ "execute": ["integrity", "execution", "delegation"],
34
+ "delegate": ["delegation"],
35
+ "analyze": ["execution", "memory"],
36
+ "answer": ["communication"],
37
+ }
38
+ categories = category_map.get(task_type, ["integrity", "execution"])
39
+ placeholders = ",".join("?" * len(categories))
40
+
41
+ rows = conn.execute(
42
+ f"SELECT id, rule FROM core_rules WHERE category IN ({placeholders}) AND is_active = 1 AND type = 'blocking' ORDER BY importance DESC LIMIT 5",
43
+ categories
44
+ ).fetchall()
45
+ return [f"{r['id']}: {r['rule']}" for r in rows]
46
+ except Exception:
47
+ return []
48
+
49
+
50
+ def _get_trust_score() -> float:
51
+ """Get current trust score from cognitive.db."""
52
+ try:
53
+ import cognitive
54
+ return cognitive.get_trust_score()
55
+ except Exception:
56
+ return 50.0
57
+
58
+
59
+ def _validate_state(state: dict) -> dict:
60
+ """Validate cognitive state and determine action mode.
61
+
62
+ Returns dict with: mode, warnings, injected_rules, blocked_reason
63
+ """
64
+ warnings = []
65
+ mode = "act" # default: allow action
66
+ blocked_reason = None
67
+
68
+ task_type = state.get("task_type", "answer")
69
+ plan = state.get("plan", [])
70
+ unknowns = state.get("unknowns", [])
71
+ evidence = state.get("evidence_refs", [])
72
+ verification = state.get("verification_step", "")
73
+ constraints = state.get("constraints", [])
74
+ goal = state.get("goal", "")
75
+
76
+ # === INHIBITION RULES (architectural, not advisory) ===
77
+
78
+ # Rule 1: unknowns exist → force ASK mode
79
+ if unknowns:
80
+ mode = "ask"
81
+ blocked_reason = f"Cannot act with {len(unknowns)} unknown(s). Resolve first."
82
+ warnings.append(f"UNKNOWNS: {', '.join(unknowns[:3])}")
83
+
84
+ # Rule 2: edit/execute without plan → force PROPOSE
85
+ if task_type in ("edit", "execute", "delegate") and not plan and mode == "act":
86
+ mode = "propose"
87
+ blocked_reason = "No plan defined for action task. Propose plan first."
88
+ warnings.append("MISSING PLAN: define steps before executing")
89
+
90
+ # Rule 3: edit/execute without verification → force PROPOSE
91
+ if task_type in ("edit", "execute") and not verification and mode == "act":
92
+ mode = "propose"
93
+ blocked_reason = "No verification step. How will you confirm it worked?"
94
+ warnings.append("MISSING VERIFICATION: define how to verify")
95
+
96
+ # Rule 4: execute without evidence → force PROPOSE
97
+ if task_type == "execute" and not evidence and mode == "act":
98
+ mode = "propose"
99
+ blocked_reason = "No evidence supporting this action."
100
+ warnings.append("MISSING EVIDENCE: what supports this action?")
101
+
102
+ # Rule 5: no goal → force ASK
103
+ if not goal:
104
+ mode = "ask"
105
+ blocked_reason = "No goal defined."
106
+ warnings.append("NO GOAL: what are you trying to achieve?")
107
+
108
+ # === TRUST-BASED ADJUSTMENTS ===
109
+ trust = _get_trust_score()
110
+ if trust < 30 and mode == "act" and task_type in ("edit", "execute"):
111
+ mode = "propose"
112
+ blocked_reason = f"Trust score {trust:.0f}/100 — propose before acting."
113
+ warnings.append(f"LOW TRUST ({trust:.0f}): extra verification required")
114
+
115
+ # === INJECT RELEVANT RULES ===
116
+ rules = _get_core_rules_for_task(task_type)
117
+
118
+ return {
119
+ "mode": mode,
120
+ "tools_available": _tools_for_mode(mode),
121
+ "warnings": warnings,
122
+ "blocked_reason": blocked_reason,
123
+ "injected_rules": rules,
124
+ "trust_score": round(trust),
125
+ }
126
+
127
+
128
+ def _tools_for_mode(mode: str) -> list[str]:
129
+ """Define which tool categories are available per mode."""
130
+ if mode == "ask":
131
+ return ["read", "search", "ask_user"]
132
+ elif mode == "propose":
133
+ return ["read", "search", "analyze", "propose_plan"]
134
+ else: # act
135
+ return ["all"]
136
+
137
+
138
+ def handle_cortex_check(
139
+ goal: str,
140
+ task_type: str = "answer",
141
+ plan: str = "[]",
142
+ known_facts: str = "[]",
143
+ unknowns: str = "[]",
144
+ constraints: str = "[]",
145
+ evidence_refs: str = "[]",
146
+ verification_step: str = "",
147
+ ) -> str:
148
+ """Cognitive Cortex pre-action check. Call BEFORE significant actions.
149
+
150
+ Validates your reasoning state and determines if you can act, should propose,
151
+ or need to ask for clarification first. Implements architectural inhibitory control.
152
+
153
+ WHEN TO CALL:
154
+ - Before editing files or running commands
155
+ - Before delegating to subagents
156
+ - When the task has multiple possible approaches
157
+ - After a failed attempt (before retrying)
158
+ - When user instruction seems to conflict with known facts
159
+
160
+ DO NOT CALL for simple chat responses, greetings, or explanations.
161
+
162
+ Args:
163
+ goal: What you are trying to achieve (required)
164
+ task_type: One of: answer, analyze, edit, execute, delegate
165
+ plan: JSON array of planned steps (e.g. '["read file", "edit function", "test"]')
166
+ known_facts: JSON array of facts you have (from user, memory, files)
167
+ unknowns: JSON array of things you don't know yet but need
168
+ constraints: JSON array of rules or limitations that apply
169
+ evidence_refs: JSON array of evidence supporting your plan (learnings, user statements, file contents)
170
+ verification_step: How you will verify the action worked
171
+
172
+ Returns:
173
+ Mode (ask/propose/act), available tools, warnings, and relevant Core Rules
174
+ """
175
+ # Parse JSON arrays safely
176
+ def _parse(s):
177
+ try:
178
+ v = json.loads(s) if isinstance(s, str) else s
179
+ return v if isinstance(v, list) else []
180
+ except (json.JSONDecodeError, TypeError):
181
+ return []
182
+
183
+ state = {
184
+ "goal": goal.strip() if goal else "",
185
+ "task_type": task_type if task_type in ("answer", "analyze", "edit", "execute", "delegate") else "answer",
186
+ "plan": _parse(plan),
187
+ "known_facts": _parse(known_facts),
188
+ "unknowns": _parse(unknowns),
189
+ "constraints": _parse(constraints),
190
+ "evidence_refs": _parse(evidence_refs),
191
+ "verification_step": verification_step.strip() if verification_step else "",
192
+ }
193
+
194
+ result = _validate_state(state)
195
+
196
+ # Format response
197
+ lines = [
198
+ f"CORTEX CHECK — mode: {result['mode'].upper()}",
199
+ f"Trust: {result['trust_score']}/100",
200
+ ]
201
+
202
+ if result["mode"] == "act":
203
+ lines.append("CLEARED: You may proceed with the action.")
204
+ elif result["mode"] == "propose":
205
+ lines.append(f"PROPOSE ONLY: {result['blocked_reason']}")
206
+ lines.append("Show the user your plan and get approval before executing.")
207
+ elif result["mode"] == "ask":
208
+ lines.append(f"ASK FIRST: {result['blocked_reason']}")
209
+ lines.append("Gather the missing information before proceeding.")
210
+
211
+ if result["warnings"]:
212
+ lines.append("")
213
+ lines.append("Warnings:")
214
+ for w in result["warnings"]:
215
+ lines.append(f" - {w}")
216
+
217
+ if result["injected_rules"]:
218
+ lines.append("")
219
+ lines.append("Applicable Core Rules:")
220
+ for r in result["injected_rules"]:
221
+ lines.append(f" - {r}")
222
+
223
+ lines.append("")
224
+ lines.append(f"Tools available: {', '.join(result['tools_available'])}")
225
+
226
+ # Log cortex activation for metrics
227
+ try:
228
+ conn = _get_db()
229
+ conn.execute(
230
+ """CREATE TABLE IF NOT EXISTS cortex_log (
231
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
232
+ goal TEXT,
233
+ task_type TEXT,
234
+ mode TEXT,
235
+ warnings TEXT,
236
+ trust_score INTEGER,
237
+ created_at TEXT DEFAULT (datetime('now'))
238
+ )"""
239
+ )
240
+ conn.execute(
241
+ "INSERT INTO cortex_log (goal, task_type, mode, warnings, trust_score) VALUES (?, ?, ?, ?, ?)",
242
+ (goal[:200], task_type, result["mode"], json.dumps(result["warnings"]), result["trust_score"])
243
+ )
244
+ conn.commit()
245
+ except Exception:
246
+ pass
247
+
248
+ return "\n".join(lines)
249
+
250
+
251
+ def handle_cortex_stats(days: int = 7) -> str:
252
+ """View Cortex activation statistics — how often it activates, modes, warnings.
253
+
254
+ Args:
255
+ days: Period to analyze (default 7)
256
+ """
257
+ conn = _get_db()
258
+ try:
259
+ conn.execute("SELECT 1 FROM cortex_log LIMIT 1")
260
+ except Exception:
261
+ return "No Cortex data yet. The Cortex activates on significant actions."
262
+
263
+ cutoff = f"datetime('now', '-{days} days')"
264
+
265
+ total = conn.execute(f"SELECT COUNT(*) FROM cortex_log WHERE created_at >= {cutoff}").fetchone()[0]
266
+ by_mode = conn.execute(
267
+ f"SELECT mode, COUNT(*) as c FROM cortex_log WHERE created_at >= {cutoff} GROUP BY mode ORDER BY c DESC"
268
+ ).fetchall()
269
+ by_type = conn.execute(
270
+ f"SELECT task_type, COUNT(*) as c FROM cortex_log WHERE created_at >= {cutoff} GROUP BY task_type ORDER BY c DESC"
271
+ ).fetchall()
272
+
273
+ lines = [
274
+ f"CORTEX STATS — last {days} days",
275
+ f"Total activations: {total}",
276
+ "",
277
+ "By mode:",
278
+ ]
279
+ for r in by_mode:
280
+ pct = (r["c"] / total * 100) if total > 0 else 0
281
+ lines.append(f" {r['mode']}: {r['c']} ({pct:.0f}%)")
282
+
283
+ lines.append("")
284
+ lines.append("By task type:")
285
+ for r in by_type:
286
+ lines.append(f" {r['task_type']}: {r['c']}")
287
+
288
+ # Inhibition rate = % of activations that resulted in ask or propose (not act)
289
+ inhibited = sum(r["c"] for r in by_mode if r["mode"] != "act")
290
+ inhibition_rate = (inhibited / total * 100) if total > 0 else 0
291
+ lines.append(f"\nInhibition rate: {inhibition_rate:.0f}% (target: 30-60%)")
292
+
293
+ return "\n".join(lines)
294
+
295
+
296
+ TOOLS = [
297
+ (handle_cortex_check, "nexo_cortex_check", "Cognitive pre-action check. Validates reasoning and determines if you can act, should propose, or need to ask first. Call before significant actions."),
298
+ (handle_cortex_stats, "nexo_cortex_stats", "View Cortex activation statistics — modes, task types, inhibition rate."),
299
+ ]
@@ -6,7 +6,9 @@
6
6
  "source": "Consolidated from 6 months production use + multi-AI debate (Claude Opus + GPT-4o)",
7
7
  "total_rules": 30,
8
8
  "blocking": 25,
9
- "advisory": 5
9
+ "advisory": 5,
10
+ "immutable": true,
11
+ "immutable_note": "Core rules are the DNA of NEXO Brain. They CANNOT be deleted or modified by the user. Only the migration system (version updates from the creators) can add, modify, or remove rules. Users can configure behavioral intensity (autonomy, communication, proactivity) but not the rules themselves."
10
12
  },
11
13
  "categories": {
12
14
  "integrity": {
@@ -58,6 +58,28 @@ _Subagents inherit zero session memory. Without context = guaranteed errors._
58
58
 
59
59
  For the full 30 rules across 6 categories (Integrity, Execution, Memory, Delegation, Communication, Proactivity), call `nexo_rules_check`.
60
60
 
61
+ ## Cognitive Cortex (Pre-Action Reasoning)
62
+
63
+ Before significant actions, call `nexo_cortex_check` to validate your reasoning. The Cortex determines if you can **act**, should **propose**, or need to **ask** first.
64
+
65
+ **WHEN to call `nexo_cortex_check`:**
66
+ - Before editing files or running commands
67
+ - Before delegating to subagents
68
+ - When the task has multiple possible approaches
69
+ - After a failed attempt (before retrying differently)
70
+ - When user instruction conflicts with known facts
71
+
72
+ **DO NOT call** for simple chat, greetings, explanations, or read-only queries.
73
+
74
+ **How it works:** You provide your goal, plan, knowns, unknowns, and evidence. The Cortex validates and returns:
75
+ - **ACT** — proceed with execution (all tools available)
76
+ - **PROPOSE** — show plan to user first (no write/execute tools)
77
+ - **ASK** — gather missing information first (read/search only)
78
+
79
+ The Cortex enforces inhibitory control architecturally — it physically restricts available tools based on your reasoning quality. This prevents premature action, hallucinated certainty, and unverified execution.
80
+
81
+ `nexo_cortex_stats` shows activation metrics and inhibition rates.
82
+
61
83
  ## Personality Calibration
62
84
 
63
85
  Read `{{NEXO_HOME}}/brain/calibration.json` at startup to load user preferences. These override defaults: