nexo-brain 0.10.0-beta.7 → 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.7](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.7** — 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.7",
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
+ }
package/src/db.py CHANGED
@@ -950,6 +950,59 @@ def _m9_maintenance_schedule(conn):
950
950
  )
951
951
 
952
952
 
953
+ def _m11_core_rules(conn):
954
+ """Core system rules table — versioned behavioral rules with migration support."""
955
+ conn.executescript("""
956
+ CREATE TABLE IF NOT EXISTS core_rules (
957
+ id TEXT PRIMARY KEY,
958
+ category TEXT NOT NULL,
959
+ rule TEXT NOT NULL,
960
+ why TEXT NOT NULL,
961
+ importance INTEGER NOT NULL DEFAULT 4,
962
+ type TEXT NOT NULL DEFAULT 'advisory' CHECK(type IN ('blocking', 'advisory')),
963
+ added_in TEXT NOT NULL DEFAULT '1.0.0',
964
+ removed_in TEXT DEFAULT NULL,
965
+ is_active INTEGER NOT NULL DEFAULT 1,
966
+ created_at TEXT DEFAULT (datetime('now'))
967
+ );
968
+
969
+ CREATE TABLE IF NOT EXISTS core_rules_version (
970
+ id INTEGER PRIMARY KEY CHECK(id = 1),
971
+ version TEXT NOT NULL DEFAULT '0.0.0',
972
+ updated_at TEXT DEFAULT (datetime('now'))
973
+ );
974
+
975
+ INSERT OR IGNORE INTO core_rules_version (id, version) VALUES (1, '0.0.0');
976
+ """)
977
+ # Seed rules from core-rules.json if available
978
+ _seed_core_rules(conn)
979
+
980
+
981
+ def _seed_core_rules(conn):
982
+ """Load rules from core-rules.json into the database."""
983
+ import json
984
+ rules_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rules", "core-rules.json")
985
+ if not os.path.exists(rules_file):
986
+ return
987
+
988
+ with open(rules_file) as f:
989
+ data = json.load(f)
990
+
991
+ version = data["_meta"]["version"]
992
+
993
+ for cat_key, cat in data["categories"].items():
994
+ for rule in cat["rules"]:
995
+ conn.execute(
996
+ """INSERT OR REPLACE INTO core_rules (id, category, rule, why, importance, type, added_in)
997
+ VALUES (?, ?, ?, ?, ?, ?, ?)""",
998
+ (rule["id"], cat_key, rule["rule"], rule["why"],
999
+ rule["importance"], rule["type"], rule.get("added_in", version))
1000
+ )
1001
+
1002
+ conn.execute("UPDATE core_rules_version SET version = ?, updated_at = datetime('now') WHERE id = 1", (version,))
1003
+ conn.commit()
1004
+
1005
+
953
1006
  # Migration registry — APPEND ONLY, never reorder or delete
954
1007
  MIGRATIONS = [
955
1008
  (1, "learnings_columns", _m1_learnings_columns),
@@ -962,6 +1015,7 @@ MIGRATIONS = [
962
1015
  (8, "adaptive_log_and_somatic", _m8_adaptive_log_and_somatic),
963
1016
  (9, "maintenance_schedule", _m9_maintenance_schedule),
964
1017
  (10, "diary_archive", _m10_diary_archive),
1018
+ (11, "core_rules", _m11_core_rules),
965
1019
  ]
966
1020
 
967
1021
 
@@ -0,0 +1,231 @@
1
+ """Core Rules plugin — query and manage versioned behavioral rules."""
2
+
3
+ import json
4
+ import os
5
+
6
+
7
+ def _get_db():
8
+ from db import get_db
9
+ return get_db()
10
+
11
+
12
+ def _seed_if_empty():
13
+ """Seed rules from JSON if table is empty (first run after migration)."""
14
+ conn = _get_db()
15
+ count = conn.execute("SELECT COUNT(*) FROM core_rules WHERE is_active = 1").fetchone()[0]
16
+ if count > 0:
17
+ return
18
+
19
+ rules_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
20
+ "rules", "core-rules.json")
21
+ if not os.path.exists(rules_file):
22
+ return
23
+
24
+ with open(rules_file) as f:
25
+ data = json.load(f)
26
+
27
+ version = data["_meta"]["version"]
28
+ for cat_key, cat in data["categories"].items():
29
+ for rule in cat["rules"]:
30
+ conn.execute(
31
+ """INSERT OR REPLACE INTO core_rules (id, category, rule, why, importance, type, added_in)
32
+ VALUES (?, ?, ?, ?, ?, ?, ?)""",
33
+ (rule["id"], cat_key, rule["rule"], rule["why"],
34
+ rule["importance"], rule["type"], rule.get("added_in", version))
35
+ )
36
+
37
+ conn.execute("UPDATE core_rules_version SET version = ?, updated_at = datetime('now') WHERE id = 1", (version,))
38
+ conn.commit()
39
+
40
+
41
+ def handle_rules_check(area: str = "", importance_min: int = 0) -> str:
42
+ """Get applicable core rules for a given area or action.
43
+
44
+ Returns BLOCKING rules that must be followed and ADVISORY rules as guidance.
45
+ Call this before taking any significant action.
46
+
47
+ Args:
48
+ area: Area of work — 'code', 'delegation', 'communication', 'memory', or empty for all.
49
+ Maps to categories: code→execution+integrity, delegation→delegation, etc.
50
+ importance_min: Minimum importance level (1-5, default 0 = all rules)
51
+ """
52
+ _seed_if_empty()
53
+ conn = _get_db()
54
+
55
+ area_to_categories = {
56
+ "code": ("integrity", "execution"),
57
+ "edit": ("integrity", "execution"),
58
+ "delegation": ("delegation",),
59
+ "delegate": ("delegation",),
60
+ "subagent": ("delegation",),
61
+ "communication": ("communication",),
62
+ "respond": ("communication",),
63
+ "memory": ("memory",),
64
+ "learn": ("memory",),
65
+ "proactivity": ("proactivity",),
66
+ "protect": ("proactivity",),
67
+ }
68
+
69
+ where = "WHERE is_active = 1"
70
+ params = []
71
+
72
+ if area and area.lower() in area_to_categories:
73
+ cats = area_to_categories[area.lower()]
74
+ placeholders = ",".join("?" * len(cats))
75
+ where += f" AND category IN ({placeholders})"
76
+ params.extend(cats)
77
+
78
+ if importance_min > 0:
79
+ where += " AND importance >= ?"
80
+ params.append(importance_min)
81
+
82
+ rows = conn.execute(
83
+ f"SELECT id, category, rule, why, importance, type FROM core_rules {where} ORDER BY importance DESC, category, id",
84
+ params
85
+ ).fetchall()
86
+
87
+ if not rows:
88
+ return "No rules found for this area."
89
+
90
+ # Get version
91
+ ver = conn.execute("SELECT version FROM core_rules_version WHERE id = 1").fetchone()
92
+ version = ver[0] if ver else "unknown"
93
+
94
+ blocking = [r for r in rows if r["type"] == "blocking"]
95
+ advisory = [r for r in rows if r["type"] == "advisory"]
96
+
97
+ lines = [f"CORE RULES (v{version}) — {len(blocking)} BLOCKING, {len(advisory)} ADVISORY"]
98
+ if area:
99
+ lines[0] += f" [area: {area}]"
100
+ lines.append("")
101
+
102
+ if blocking:
103
+ lines.append("## BLOCKING (must follow)")
104
+ for r in blocking:
105
+ lines.append(f" {r['id']}. {r['rule']}")
106
+ lines.append(f" Why: {r['why']}")
107
+ lines.append("")
108
+
109
+ if advisory:
110
+ lines.append("## ADVISORY (recommended)")
111
+ for r in advisory:
112
+ lines.append(f" {r['id']}. {r['rule']}")
113
+ lines.append(f" Why: {r['why']}")
114
+
115
+ return "\n".join(lines)
116
+
117
+
118
+ def handle_rules_list() -> str:
119
+ """List all core rules with their status, grouped by category."""
120
+ _seed_if_empty()
121
+ conn = _get_db()
122
+
123
+ ver = conn.execute("SELECT version FROM core_rules_version WHERE id = 1").fetchone()
124
+ version = ver[0] if ver else "unknown"
125
+
126
+ rows = conn.execute(
127
+ "SELECT id, category, rule, importance, type, is_active, added_in, removed_in FROM core_rules ORDER BY category, id"
128
+ ).fetchall()
129
+
130
+ lines = [f"CORE RULES v{version} — {len([r for r in rows if r['is_active']])} active, {len([r for r in rows if not r['is_active']])} removed", ""]
131
+
132
+ current_cat = None
133
+ for r in rows:
134
+ if r["category"] != current_cat:
135
+ current_cat = r["category"]
136
+ lines.append(f"### {current_cat.upper()}")
137
+
138
+ status = "✓" if r["is_active"] else "✗"
139
+ tag = "BLOCK" if r["type"] == "blocking" else "ADVSR"
140
+ lines.append(f" [{status}] {r['id']} [{tag}] imp={r['importance']} — {r['rule']}")
141
+ if r["removed_in"]:
142
+ lines.append(f" Removed in v{r['removed_in']}")
143
+
144
+ return "\n".join(lines)
145
+
146
+
147
+ def handle_rules_migrate(dry_run: bool = False) -> str:
148
+ """Sync core rules from the JSON definition file to the database.
149
+
150
+ Adds new rules, marks removed ones as inactive. Safe to run multiple times.
151
+
152
+ Args:
153
+ dry_run: If True, show what would change without applying
154
+ """
155
+ conn = _get_db()
156
+ rules_file = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
157
+ "rules", "core-rules.json")
158
+ if not os.path.exists(rules_file):
159
+ return "ERROR: core-rules.json not found"
160
+
161
+ with open(rules_file) as f:
162
+ data = json.load(f)
163
+
164
+ new_version = data["_meta"]["version"]
165
+ ver = conn.execute("SELECT version FROM core_rules_version WHERE id = 1").fetchone()
166
+ current_version = ver[0] if ver else "0.0.0"
167
+
168
+ # Collect all rule IDs from JSON
169
+ json_ids = set()
170
+ json_rules = {}
171
+ for cat_key, cat in data["categories"].items():
172
+ for rule in cat["rules"]:
173
+ json_ids.add(rule["id"])
174
+ json_rules[rule["id"]] = {**rule, "category": cat_key}
175
+
176
+ # Collect active IDs from DB
177
+ db_ids = set()
178
+ for r in conn.execute("SELECT id FROM core_rules WHERE is_active = 1").fetchall():
179
+ db_ids.add(r[0])
180
+
181
+ added = json_ids - db_ids
182
+ removed = db_ids - json_ids
183
+ unchanged = json_ids & db_ids
184
+
185
+ lines = [
186
+ f"RULES MIGRATION: v{current_version} → v{new_version}",
187
+ f" Added: {len(added)} — {', '.join(sorted(added)) if added else 'none'}",
188
+ f" Removed: {len(removed)} — {', '.join(sorted(removed)) if removed else 'none'}",
189
+ f" Unchanged: {len(unchanged)}",
190
+ ]
191
+
192
+ if dry_run:
193
+ lines.append(" Mode: DRY RUN (no changes applied)")
194
+ return "\n".join(lines)
195
+
196
+ # Apply additions
197
+ for rid in added:
198
+ r = json_rules[rid]
199
+ conn.execute(
200
+ """INSERT OR REPLACE INTO core_rules (id, category, rule, why, importance, type, added_in, is_active)
201
+ VALUES (?, ?, ?, ?, ?, ?, ?, 1)""",
202
+ (r["id"], r["category"], r["rule"], r["why"], r["importance"], r["type"], r.get("added_in", new_version))
203
+ )
204
+
205
+ # Apply removals (soft delete)
206
+ for rid in removed:
207
+ conn.execute(
208
+ "UPDATE core_rules SET is_active = 0, removed_in = ? WHERE id = ?",
209
+ (new_version, rid)
210
+ )
211
+
212
+ # Update existing rules (content might have changed)
213
+ for rid in unchanged:
214
+ r = json_rules[rid]
215
+ conn.execute(
216
+ "UPDATE core_rules SET rule = ?, why = ?, importance = ?, type = ?, category = ? WHERE id = ?",
217
+ (r["rule"], r["why"], r["importance"], r["type"], r["category"], rid)
218
+ )
219
+
220
+ conn.execute("UPDATE core_rules_version SET version = ?, updated_at = datetime('now') WHERE id = 1", (new_version,))
221
+ conn.commit()
222
+
223
+ lines.append(" Status: APPLIED")
224
+ return "\n".join(lines)
225
+
226
+
227
+ TOOLS = [
228
+ (handle_rules_check, "nexo_rules_check", "Get applicable core rules for an area before acting. Returns BLOCKING and ADVISORY rules."),
229
+ (handle_rules_list, "nexo_rules_list", "List all core rules with status, grouped by category."),
230
+ (handle_rules_migrate, "nexo_rules_migrate", "Sync rules from JSON definition to database. Adds new, soft-deletes removed."),
231
+ ]
@@ -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
+ ]
File without changes