noormme 1.0.5 → 1.1.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.
Files changed (63) hide show
  1. package/README.md +61 -51
  2. package/dist/cjs/agentic/CapabilityManager.d.ts +9 -4
  3. package/dist/cjs/agentic/CapabilityManager.js +88 -6
  4. package/dist/cjs/agentic/Cortex.d.ts +8 -1
  5. package/dist/cjs/agentic/Cortex.js +19 -3
  6. package/dist/cjs/agentic/improvement/CortexJanitor.d.ts +1 -1
  7. package/dist/cjs/agentic/improvement/CortexJanitor.js +38 -22
  8. package/dist/cjs/agentic/improvement/CuriosityEngine.d.ts +2 -2
  9. package/dist/cjs/agentic/improvement/CuriosityEngine.js +47 -42
  10. package/dist/cjs/agentic/improvement/EvolutionRitual.d.ts +24 -0
  11. package/dist/cjs/agentic/improvement/EvolutionRitual.js +91 -0
  12. package/dist/cjs/agentic/improvement/EvolutionaryPilot.d.ts +5 -0
  13. package/dist/cjs/agentic/improvement/EvolutionaryPilot.js +64 -1
  14. package/dist/cjs/agentic/improvement/GovernanceManager.d.ts +3 -4
  15. package/dist/cjs/agentic/improvement/GovernanceManager.js +78 -44
  16. package/dist/cjs/agentic/improvement/HiveLink.d.ts +9 -0
  17. package/dist/cjs/agentic/improvement/HiveLink.js +108 -21
  18. package/dist/cjs/agentic/improvement/KnowledgeDistiller.d.ts +2 -0
  19. package/dist/cjs/agentic/improvement/KnowledgeDistiller.js +57 -19
  20. package/dist/cjs/agentic/improvement/RecursiveReasoner.d.ts +7 -1
  21. package/dist/cjs/agentic/improvement/RecursiveReasoner.js +68 -7
  22. package/dist/cjs/agentic/improvement/RitualOrchestrator.js +6 -0
  23. package/dist/cjs/agentic/improvement/SkillSynthesizer.d.ts +48 -0
  24. package/dist/cjs/agentic/improvement/SkillSynthesizer.js +273 -0
  25. package/dist/cjs/agentic/improvement/StrategicPlanner.d.ts +12 -6
  26. package/dist/cjs/agentic/improvement/StrategicPlanner.js +223 -96
  27. package/dist/cjs/agentic/telemetry/ResearchAlchemist.js +9 -3
  28. package/dist/cjs/cli/index.js +0 -0
  29. package/dist/cjs/helpers/agent-schema.js +1 -0
  30. package/dist/cjs/index.d.ts +17 -15
  31. package/dist/cjs/noormme.js +3 -1
  32. package/dist/cjs/types/index.d.ts +56 -2
  33. package/dist/esm/agentic/CapabilityManager.d.ts +9 -4
  34. package/dist/esm/agentic/CapabilityManager.js +88 -6
  35. package/dist/esm/agentic/Cortex.d.ts +8 -1
  36. package/dist/esm/agentic/Cortex.js +19 -3
  37. package/dist/esm/agentic/improvement/CortexJanitor.d.ts +1 -1
  38. package/dist/esm/agentic/improvement/CortexJanitor.js +38 -22
  39. package/dist/esm/agentic/improvement/CuriosityEngine.d.ts +2 -2
  40. package/dist/esm/agentic/improvement/CuriosityEngine.js +47 -42
  41. package/dist/esm/agentic/improvement/EvolutionRitual.d.ts +24 -0
  42. package/dist/esm/agentic/improvement/EvolutionRitual.js +88 -0
  43. package/dist/esm/agentic/improvement/EvolutionaryPilot.d.ts +5 -0
  44. package/dist/esm/agentic/improvement/EvolutionaryPilot.js +64 -1
  45. package/dist/esm/agentic/improvement/GovernanceManager.d.ts +3 -4
  46. package/dist/esm/agentic/improvement/GovernanceManager.js +78 -44
  47. package/dist/esm/agentic/improvement/HiveLink.d.ts +9 -0
  48. package/dist/esm/agentic/improvement/HiveLink.js +108 -21
  49. package/dist/esm/agentic/improvement/KnowledgeDistiller.d.ts +2 -0
  50. package/dist/esm/agentic/improvement/KnowledgeDistiller.js +57 -19
  51. package/dist/esm/agentic/improvement/RecursiveReasoner.d.ts +7 -1
  52. package/dist/esm/agentic/improvement/RecursiveReasoner.js +68 -7
  53. package/dist/esm/agentic/improvement/RitualOrchestrator.js +6 -0
  54. package/dist/esm/agentic/improvement/SkillSynthesizer.d.ts +48 -0
  55. package/dist/esm/agentic/improvement/SkillSynthesizer.js +270 -0
  56. package/dist/esm/agentic/improvement/StrategicPlanner.d.ts +12 -6
  57. package/dist/esm/agentic/improvement/StrategicPlanner.js +223 -96
  58. package/dist/esm/agentic/telemetry/ResearchAlchemist.js +9 -3
  59. package/dist/esm/helpers/agent-schema.js +1 -0
  60. package/dist/esm/index.d.ts +17 -15
  61. package/dist/esm/noormme.js +3 -1
  62. package/dist/esm/types/index.d.ts +56 -2
  63. package/package.json +46 -42
package/README.md CHANGED
@@ -1,63 +1,64 @@
1
+ ![NOORMME: The Agentic Data Engine](/Users/bozoegg/.gemini/antigravity/brain/af239a4f-144c-41a9-b1c4-9d534b5243f8/noormme_hero_banner_1771742014638.png)
2
+
1
3
  # NOORMME: The Agentic Data Engine
2
4
 
3
- **NOORMME** is a sovereign persistence layer and cognitive operating system designed for **Autonomous AI Agents**. It transcends legacy ORM patterns by providing a self-healing, evolutionary data infrastructure that functions as an extension of the agent's internal reasoning loop.
5
+ **NOORMME** is a sovereign persistence layer and cognitive operating system designed for **Autonomous AI Agents**. It transcends legacy ORM patterns by providing a self-healing, evolutionary data infrastructure that functions as a high-fidelity extension of the agent's internal reasoning loop.
4
6
 
5
7
  [![Version](https://img.shields.io/npm/v/noormme.svg)](https://www.npmjs.com/package/noormme)
6
8
  [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
7
- [![Cognitive](https://img.shields.io/badge/Intelligence-Autonomous_Governance-purple.svg)](#-autonomous-governance)
9
+ [![Cognitive](https://img.shields.io/badge/Intelligence-Autonomous_Governance-purple.svg)](./docs/agentic-intelligence.md)
10
+ [![Evolution](https://img.shields.io/badge/Evolution-Ultra_Scale-blueviolet.svg)](./docs/ultra-scale-orchestration.md)
8
11
 
9
12
  ---
10
13
 
11
- ## 🏗 The Agentic Data Loop
14
+ ## 🧠 The Cognitive Loop
15
+
16
+ NOORMME implements a closed-loop system where data is not merely "stored" but continuously distilled, questioned, and evolved. It turns your database into a living world model.
12
17
 
13
- NOORMME implements a closed-loop system where data is not merely "stored" but continuously distilled, questioned, and evolved.
18
+ ```mermaid
19
+ graph LR
20
+ A[Raw Ingestion] --> B{Distillation}
21
+ B --> C[Knowledge Base]
22
+ C --> D[Reasoning Engine]
23
+ D --> E[Action / Outcome]
24
+ E --> F{Reflection}
25
+ F -->|Success| G[Goal Reinforcement]
26
+ F -->|Failure| H[Strategic Mutation]
27
+ H --> B
28
+ ```
14
29
 
15
- ### 🧠 Cognitive Orchestration
16
- - **Strategic Planner**: Proactively suggests and applies persona mutations (roles, policies, capabilities) based on real-time success/latency telemetry.
17
- - **Knowledge Distiller**: Extracts structured entities and facts from raw history using Jaccard similarity-based consolidation and confidence gradients.
18
- - **Curiosity Engine**: Identifies "Knowledge Gaps" and "Factual Contradictions," generating research hypotheses and active questions for the agent to resolve.
19
- - **Ablation Labs**: Conducts "Zombie Pruning" and "Impact Tests"—temporarily disabling knowledge to evaluate its necessity in the reasoning path.
30
+ ### Advanced Orchestration
31
+ - **🎭 Tiered Model Routing**: Optimize cost/performance by routing batch discovery to **Fast LLMs** and mutation logic to **Premium LLMs**.
32
+ - **🔥 Predictive Pre-warming**: Background AI optimization of skills nearing promotion to eliminate cold-start latency.
33
+ - **🌐 Goal Cross-Pollination**: Breakthroughs in individual persona mutations are automatically distilled into global **Systemic Best-Practices**.
34
+ - **🌸 Bloom Filter Heuristics**: Ultra-scale knowledge de-duplication at 100x speed vs traditional DB hits.
20
35
 
21
36
  ---
22
37
 
23
- ## 💎 Technical Moats
38
+ ## 🧬 Evolutionary Infrastructure (DNA Inversion)
24
39
 
25
- ### 🧬 Evolutionary Infrastructure & "DNA Inversion"
26
- NOORMME allows agents to autonomously mutate their own schema.
27
- - **Dynamic DDL**: Agents can propose `CREATE TABLE`, `ADD COLUMN`, or `CREATE INDEX` mutations via the **Evolutionary Pilot**.
28
- - **Structural Rollback**: The **DNA Inverter** automatically generates inverse SQL for any DDL mutation (e.g., inverting an `ADD COLUMN` to a `DROP COLUMN`) to ensure safe structural experimentation.
29
- - **Real-Time Type Synthesis**: TypeScript interfaces and types are regenerated and written to disk the moment a structural change is committed.
40
+ NOORMME allows agents to autonomously mutate their own structural DNA while maintaining 100% safety.
30
41
 
31
- ### 🚥 Autonomous Governance (Logic Probes)
32
- The **Self-Test Registry** enables agents to maintain their own integrity through automated "probes":
33
- - **Integrity Audits**: Detects orphaned records and semantic memory failures.
34
- - **Performance Drift**: Detects when autonomous schema changes cause query latency to drift more than 50% from a rolling 100-query baseline.
35
- - **Consistency Probes**: Verifies that new knowledge doesn't contradict established "Hive" facts.
36
-
37
- ### 📊 Deep Behavioral Telemetry
38
- A three-layered telemetry stack for research and production observation:
39
- 1. **Raw Event Harvester**: High-fidelity capture of every interaction, pivot, and failure.
40
- 2. **Cognitive Synthesizer**: Serializes the strategic "Evolution Path" and calculates dynamic **Autonomy Levels**.
41
- 3. **Research Alchemist**: Transmutes events into high-order metrics like **Time-to-Magic**, **Discovery Index**, and **Trust Signals**.
42
+ - **Dynamic DDL**: Agents can propose `CREATE TABLE`, `ADD COLUMN`, or `CREATE INDEX` mutations via the **Evolutionary Pilot**.
43
+ - **Structural Rollback**: The **DNA Inverter** automatically generates inverse SQL for any DDL mutation to ensure safe structural experimentation.
44
+ - **Meta-Meta Evolution**: A self-tuning system that modulates its own **Mutation Aggressiveness** and **Verification Windows** based on systemic success rates.
42
45
 
43
46
  ---
44
47
 
45
- ## Performance Engineering
46
-
47
- ### Query Intelligence
48
- - **N+1 Detection**: Real-time pattern analysis to identify and warn about inefficient recursive queries.
49
- - **Semantic Caching**: Context-aware result caching that understands query patterns rather than just raw SQL.
50
- - **Dialect Optimization**: Native WAL-mode management for SQLite and optimized JSONB/Vector operations for PostgreSQL.
48
+ ## 🚥 Autonomous Governance
51
49
 
52
- ### High-Fidelity Infrastructure
53
- - **Unified Vector Abstraction**: Seamless semantic search across `PGVector`, `SQLite-vss`, and a optimized **Manual Cosine Fallback**.
54
- - **Ritual Orchestration**: Automated background "rituals" for semantic compression, stale history pruning, and database vacuuming.
50
+ - **Self-Healing Indexing**: Proactively applies performance indexes based on the agent's own observation of "slow" query contexts.
51
+ - **Conflict Resolution**: Scans cognitive rules for semantic overlaps and logical contradictions.
52
+ - **Zombie Pruning**: Automatically identifies and removes deprecated or unused knowledge items.
53
+ - **Z-Score Sensitivity**: Monitors for performance collapse (latency or success rate) and triggers emergency rollbacks.
55
54
 
56
55
  ---
57
56
 
58
- ## 🚀 Implementation
57
+ ## 🚀 Getting Started
58
+
59
+ ### 1. Provision the Mind
60
+ Initialize your database with a single line to provision 25+ agentic tables for goals, knowledge, episodes, and logic probes.
59
61
 
60
- ### Initializing the Mind
61
62
  ```typescript
62
63
  import { NOORMME } from 'noormme';
63
64
 
@@ -65,37 +66,48 @@ const db = new NOORMME({
65
66
  dialect: 'sqlite',
66
67
  connection: { database: './mind.sqlite' },
67
68
  agentic: {
68
- enableSelfEvolution: true,
69
- enableSelfHealing: true
69
+ llm: primaryModel,
70
+ llmFast: gpt4oMini, // For high-throughput batching
71
+ llmPremium: claude35, // For complex mutations
72
+ enableSelfEvolution: true
70
73
  }
71
74
  });
72
75
 
73
- // Provisions 20+ tables for goals, knowledge, episodes, and logic probes
74
76
  await db.initialize();
75
77
  ```
76
78
 
77
- ### Strategic Interaction
79
+ ### 2. Strategic Interaction
78
80
  ```typescript
79
- // Access the higher-order cognitive facade
80
81
  const cortex = db.agent.cortex;
81
82
 
82
- // Execute a background knowledge distillation ritual
83
+ // Execute background rituals (Compression, Pruning, Evolution)
83
84
  await cortex.rituals.runPendingRituals();
84
85
 
85
86
  // Challenge existing knowledge with new evidence
86
- await cortex.knowledge.challengeKnowledge('SystemArchitecture', 'New facts contradict old.', 0.95);
87
+ await cortex.knowledge.challengeKnowledge('SystemArch', 'New audit results.', 0.95);
87
88
  ```
88
89
 
89
90
  ---
90
91
 
91
- ## 🗄 Dialect Matrix
92
+ ## 🗄 Dialect Power Matrix
92
93
 
93
94
  | Feature | SQLite (Edge) | PostgreSQL (Enterprise) |
94
95
  | :--- | :--- | :--- |
95
- | **Search** | `sqlite-vss` / Fallback | `pgvector` |
96
- | **Persistence** | WAL Mode | Native Pooling / SSL |
97
- | **Evolution** | DNA Inversion | Structural Migrations |
98
- | **Reliability** | Local Atomicity | Multi-Tenant Isolation |
96
+ | **Search** | `sqlite-vss` / Fallback | `pgvector` / FTS |
97
+ | **Logic** | In-Process Atomicity | Multi-Tenant Governance |
98
+ | **Evolution** | Sequential Snapshotting | Clustered Mutation |
99
+ | **Throughput** | Sequential Direct | Bloom-Heuristic Parallel |
100
+
101
+ ---
102
+
103
+ ## 📚 Explore the Documentation
104
+ Dive into our deep-dive guides to unlock the full potential of NOORMME:
105
+
106
+ - [**Ultra-Scale Orchestration**](./docs/ultra-scale-orchestration.md)
107
+ - [**Strategic Evolution Guides**](./docs/strategic-evolution.md)
108
+ - [**Skill Lifecycle & DNA**](./docs/skill-lifecycle.md)
109
+ - [**Sovereign Meta-Evolution**](./docs/meta-evolution.md)
110
+ - [**Agentic Intelligence Deep-Dive**](./docs/agentic-intelligence.md)
99
111
 
100
112
  ---
101
113
 
@@ -104,6 +116,4 @@ NOORMME is an Apache 2.0 open-source project. We invite AI researchers and data
104
116
 
105
117
  [Contribution Guide](CONTRIBUTING.md) | [Security Audit](SECURITY.md)
106
118
 
107
- ---
108
-
109
119
  *Transforming passive records into sovereign intelligence.*
@@ -1,10 +1,12 @@
1
1
  import type { Kysely } from '../kysely.js';
2
- import type { AgenticConfig, AgentCapability } from '../types/index.js';
2
+ import { AgenticConfig, AgentCapability } from '../types/index.js';
3
+ import type { Cortex } from './Cortex.js';
3
4
  export interface CapabilityTable {
4
5
  id: number | string;
5
6
  name: string;
6
7
  version: string;
7
8
  description: string | null;
9
+ status: 'experimental' | 'verified' | 'blacklisted';
8
10
  reliability: number;
9
11
  metadata: string | null;
10
12
  created_at: string | Date;
@@ -19,9 +21,11 @@ export interface CapabilityDatabase {
19
21
  */
20
22
  export declare class CapabilityManager {
21
23
  private db;
24
+ private cortex;
22
25
  private config;
23
26
  private capabilitiesTable;
24
- constructor(db: Kysely<any>, config?: AgenticConfig);
27
+ private evolutionConfig;
28
+ constructor(db: Kysely<any>, cortex: Cortex, config?: AgenticConfig);
25
29
  private get typedDb();
26
30
  /**
27
31
  * Register or update a capability (skill)
@@ -29,6 +33,7 @@ export declare class CapabilityManager {
29
33
  registerCapability(name: string, version: string, description?: string, metadata?: Record<string, any>): Promise<AgentCapability>;
30
34
  /**
31
35
  * Update reliability based on action outcome using a damped moving average.
36
+ * Manages the lifecycle of emergent skills (sandbox -> verified / blacklisted).
32
37
  */
33
38
  reportOutcome(name: string, success: boolean): Promise<void>;
34
39
  /**
@@ -36,8 +41,8 @@ export declare class CapabilityManager {
36
41
  */
37
42
  getReliability(name: string): Promise<number>;
38
43
  /**
39
- * Get all registered capabilities
44
+ * Get all registered capabilities, optionally filtered by status
40
45
  */
41
- getCapabilities(): Promise<AgentCapability[]>;
46
+ getCapabilities(status?: AgentCapability['status']): Promise<AgentCapability[]>;
42
47
  private parseCapability;
43
48
  }
@@ -7,12 +7,22 @@ exports.CapabilityManager = void 0;
7
7
  */
8
8
  class CapabilityManager {
9
9
  db;
10
+ cortex;
10
11
  config;
11
12
  capabilitiesTable;
12
- constructor(db, config = {}) {
13
+ evolutionConfig;
14
+ constructor(db, cortex, config = {}) {
13
15
  this.db = db;
16
+ this.cortex = cortex;
14
17
  this.config = config;
15
18
  this.capabilitiesTable = config.capabilitiesTable || 'agent_capabilities';
19
+ this.evolutionConfig = {
20
+ verificationWindow: config.evolution?.verificationWindow ?? 20,
21
+ rollbackThresholdZ: config.evolution?.rollbackThresholdZ ?? 2.5,
22
+ enableHiveLink: config.evolution?.enableHiveLink ?? true,
23
+ mutationAggressiveness: config.evolution?.mutationAggressiveness ?? 0.5,
24
+ maxSandboxSkills: config.evolution?.maxSandboxSkills ?? 5
25
+ };
16
26
  }
17
27
  get typedDb() {
18
28
  return this.db;
@@ -33,6 +43,7 @@ class CapabilityManager {
33
43
  .updateTable(this.capabilitiesTable)
34
44
  .set({
35
45
  description: description || existing.description,
46
+ status: existing.status || 'experimental',
36
47
  metadata: JSON.stringify({ ...JSON.parse(existing.metadata || '{}'), ...metadata }),
37
48
  updated_at: new Date()
38
49
  })
@@ -47,6 +58,7 @@ class CapabilityManager {
47
58
  name,
48
59
  version,
49
60
  description: description || null,
61
+ status: metadata.initialStatus || 'experimental',
50
62
  reliability: 1.0,
51
63
  metadata: JSON.stringify({ ...metadata, successCount: 0, totalCount: 0 }),
52
64
  created_at: new Date(),
@@ -59,6 +71,7 @@ class CapabilityManager {
59
71
  }
60
72
  /**
61
73
  * Update reliability based on action outcome using a damped moving average.
74
+ * Manages the lifecycle of emergent skills (sandbox -> verified / blacklisted).
62
75
  */
63
76
  async reportOutcome(name, success) {
64
77
  await this.db.transaction().execute(async (trx) => {
@@ -80,11 +93,75 @@ class CapabilityManager {
80
93
  const newReliability = success
81
94
  ? Math.min(1.0, currentReliability * (1 - alpha) + alpha)
82
95
  : Math.max(0.0, currentReliability * (1 - alpha));
96
+ let newStatus = cap.status || 'experimental';
97
+ // --- Emergent Skill Evolution Optimization ---
98
+ const successStreak = (metadata.successStreak || 0) + (success ? 1 : 0);
99
+ const failureStreak = success ? 0 : (metadata.failureStreak || 0) + 1;
100
+ const streakSuccess = success ? successStreak : 0;
101
+ const winRate = successCount / totalCount;
102
+ const windowSize = this.evolutionConfig.verificationWindow || 20;
103
+ const minSampleSize = Math.ceil(windowSize * 0.75);
104
+ // Fast-Track Promotion: 5 consecutive successes bypasses sample size
105
+ const isPromotable = (totalCount >= minSampleSize && winRate >= 0.8) || (streakSuccess >= 5);
106
+ // Early-Exit Rollback: 3 consecutive failures at the start immediately blacklists
107
+ const isCatastrophic = !success && failureStreak >= 3 && totalCount <= 5;
108
+ // Pass 6: Predictive Pre-warming Trigger
109
+ // If a skill is close to promotion, pre-warm its optimized description
110
+ const promoThreshold = Math.ceil(minSampleSize * 0.8);
111
+ const isNearingPromotion = (totalCount >= promoThreshold && winRate >= 0.8) || (streakSuccess === 4);
112
+ if (isNearingPromotion && newStatus === 'experimental' && this.cortex.skillSynthesizer) {
113
+ // Trigger async background pre-warming
114
+ this.cortex.skillSynthesizer.preWarmSkill(name).catch(() => { });
115
+ }
116
+ // --- Production Hardening: Dynamic Performance Baselining ---
117
+ const historyAlpha = 0.05; // Slower moving average for baseline
118
+ const baseline = metadata.performanceBaseline ?? winRate;
119
+ const newBaseline = (baseline * (1 - historyAlpha)) + (winRate * historyAlpha);
120
+ // Variance tracking for Z-score calculation
121
+ const variance = metadata.performanceVariance ?? 0.01;
122
+ const diff = winRate - baseline;
123
+ const newVariance = (variance * (1 - historyAlpha)) + (Math.pow(diff, 2) * historyAlpha);
124
+ const stdDev = Math.sqrt(newVariance);
125
+ // Z-Score: How many standard deviations is current performance from baseline?
126
+ const zScore = stdDev > 0 ? (winRate - baseline) / stdDev : 0;
127
+ // Promotion/Demotion Logic
128
+ if (isCatastrophic && (newStatus === 'experimental' || newStatus === 'sandbox')) {
129
+ console.error(`[CapabilityManager] Skill '${name}' FAILED early-exit safety check (Streak: ${failureStreak}). Blacklisting immediately.`);
130
+ newStatus = 'blacklisted';
131
+ }
132
+ else if (isPromotable && (newStatus === 'experimental' || newStatus === 'sandbox')) {
133
+ console.log(`[CapabilityManager] Skill '${name}' PASSED fast-track verification (Streak: ${streakSuccess}, Rate: ${(winRate * 100).toFixed(1)}%). Promoting to Verified.`);
134
+ newStatus = 'verified';
135
+ }
136
+ else if (totalCount >= minSampleSize) {
137
+ if (winRate < 0.4) {
138
+ console.log(`[CapabilityManager] Skill '${name}' FAILED statistical verification (Rate: ${(winRate * 100).toFixed(1)}%). Blacklisting.`);
139
+ newStatus = 'blacklisted';
140
+ }
141
+ else if (newStatus === 'verified' && zScore < -2.0) {
142
+ // Performance Collapse: Z-score indicates current run is significantly below historical baseline
143
+ console.warn(`[CapabilityManager] Verified skill '${name}' PERFORMANCE COLLAPSE (Z: ${zScore.toFixed(2)}, Rate: ${(winRate * 100).toFixed(1)}%). Demoting to Experimental.`);
144
+ newStatus = 'experimental';
145
+ }
146
+ }
147
+ if (newStatus !== cap.status) {
148
+ console.log(`[CapabilityManager] EVOLVING STATUS: ${name} (${cap.status} -> ${newStatus})`);
149
+ }
83
150
  await trx
84
151
  .updateTable(this.capabilitiesTable)
85
152
  .set({
86
153
  reliability: newReliability,
87
- metadata: JSON.stringify({ ...metadata, totalCount, successCount }),
154
+ status: newStatus,
155
+ metadata: JSON.stringify({
156
+ ...metadata,
157
+ totalCount,
158
+ successCount,
159
+ successStreak: streakSuccess,
160
+ failureStreak,
161
+ performanceBaseline: newBaseline,
162
+ performanceVariance: newVariance,
163
+ lastOutcomeType: success ? 'success' : 'failure' // Categorization point
164
+ }),
88
165
  updated_at: new Date()
89
166
  })
90
167
  .where('id', '=', cap.id)
@@ -105,12 +182,16 @@ class CapabilityManager {
105
182
  return cap ? cap.reliability : 0.0;
106
183
  }
107
184
  /**
108
- * Get all registered capabilities
185
+ * Get all registered capabilities, optionally filtered by status
109
186
  */
110
- async getCapabilities() {
111
- const list = await this.typedDb
187
+ async getCapabilities(status) {
188
+ let query = this.typedDb
112
189
  .selectFrom(this.capabilitiesTable)
113
- .selectAll()
190
+ .selectAll();
191
+ if (status) {
192
+ query = query.where('status', '=', status);
193
+ }
194
+ const list = await query
114
195
  .orderBy('name', 'asc')
115
196
  .execute();
116
197
  return list.map(c => this.parseCapability(c));
@@ -121,6 +202,7 @@ class CapabilityManager {
121
202
  name: cap.name,
122
203
  version: cap.version,
123
204
  description: cap.description,
205
+ status: cap.status || 'experimental',
124
206
  reliability: cap.reliability,
125
207
  metadata: typeof cap.metadata === 'string' ? JSON.parse(cap.metadata) : (cap.metadata || {}),
126
208
  createdAt: new Date(cap.created_at),
@@ -1,5 +1,5 @@
1
1
  import type { Kysely } from '../kysely.js';
2
- import type { AgenticConfig, AgentMessage, NOORMConfig } from '../types/index.js';
2
+ import type { AgenticConfig, AgentMessage, NOORMConfig, LLMProvider } from '../types/index.js';
3
3
  import { SessionManager } from './SessionManager.js';
4
4
  import { ContextBuffer } from './ContextBuffer.js';
5
5
  import { VectorIndexer } from './VectorIndexer.js';
@@ -29,6 +29,8 @@ import { StrategicPlanner } from './improvement/StrategicPlanner.js';
29
29
  import { AblationEngine } from './improvement/AblationEngine.js';
30
30
  import { SelfTestRegistry } from './improvement/SelfTestRegistry.js';
31
31
  import { TelemetryOrchestrator } from './telemetry/TelemetryOrchestrator.js';
32
+ import { SkillSynthesizer } from './improvement/SkillSynthesizer.js';
33
+ import { EvolutionRitual } from './improvement/EvolutionRitual.js';
32
34
  /**
33
35
  * Cortex is the unified facade for agentic operations.
34
36
  * It coordinates sessions, memory, reflection, and knowledge.
@@ -65,6 +67,11 @@ export declare class Cortex {
65
67
  ablation: AblationEngine;
66
68
  tests: SelfTestRegistry;
67
69
  telemetry: TelemetryOrchestrator;
70
+ skillSynthesizer: SkillSynthesizer;
71
+ evolutionRitual: EvolutionRitual;
72
+ llm: LLMProvider | null;
73
+ llmFast: LLMProvider | null;
74
+ llmPremium: LLMProvider | null;
68
75
  agenticConfig: AgenticConfig;
69
76
  constructor(db: Kysely<any>, config: NOORMConfig);
70
77
  /**
@@ -30,6 +30,8 @@ const StrategicPlanner_js_1 = require("./improvement/StrategicPlanner.js");
30
30
  const AblationEngine_js_1 = require("./improvement/AblationEngine.js");
31
31
  const SelfTestRegistry_js_1 = require("./improvement/SelfTestRegistry.js");
32
32
  const TelemetryOrchestrator_js_1 = require("./telemetry/TelemetryOrchestrator.js");
33
+ const SkillSynthesizer_js_1 = require("./improvement/SkillSynthesizer.js");
34
+ const EvolutionRitual_js_1 = require("./improvement/EvolutionRitual.js");
33
35
  /**
34
36
  * Cortex is the unified facade for agentic operations.
35
37
  * It coordinates sessions, memory, reflection, and knowledge.
@@ -66,12 +68,20 @@ class Cortex {
66
68
  ablation;
67
69
  tests;
68
70
  telemetry;
71
+ skillSynthesizer;
72
+ evolutionRitual;
73
+ llm;
74
+ llmFast;
75
+ llmPremium;
69
76
  agenticConfig;
70
77
  constructor(db, config) {
71
78
  this.db = db;
72
79
  this.config = config;
73
80
  const agenticConfig = config.agentic || {};
74
81
  this.agenticConfig = agenticConfig;
82
+ this.llm = agenticConfig.llm || null;
83
+ this.llmFast = agenticConfig.llmFast || this.llm;
84
+ this.llmPremium = agenticConfig.llmPremium || this.llm;
75
85
  this.telemetry = new TelemetryOrchestrator_js_1.TelemetryOrchestrator(db, agenticConfig);
76
86
  this.sessions = new SessionManager_js_1.SessionManager(db, agenticConfig, this.telemetry);
77
87
  this.buffer = new ContextBuffer_js_1.ContextBuffer({ maxMessages: agenticConfig.contextWindowSize });
@@ -83,7 +93,7 @@ class Cortex {
83
93
  this.actions = new ActionJournal_js_1.ActionJournal(db, agenticConfig, this.telemetry);
84
94
  this.resources = new ResourceMonitor_js_1.ResourceMonitor(db, agenticConfig);
85
95
  this.episodes = new EpisodicMemory_js_1.EpisodicMemory(db, agenticConfig);
86
- this.capabilities = new CapabilityManager_js_1.CapabilityManager(db, agenticConfig);
96
+ this.capabilities = new CapabilityManager_js_1.CapabilityManager(db, this, agenticConfig);
87
97
  this.policies = new PolicyEnforcer_js_1.PolicyEnforcer(db, agenticConfig);
88
98
  this.metrics = new SovereignMetrics_js_1.SovereignMetrics(db, agenticConfig);
89
99
  this.evolution = new SelfEvolution_js_1.SelfEvolution(db, config);
@@ -103,6 +113,8 @@ class Cortex {
103
113
  this.strategy = new StrategicPlanner_js_1.StrategicPlanner(db, this, agenticConfig);
104
114
  this.ablation = new AblationEngine_js_1.AblationEngine(db, this, agenticConfig);
105
115
  this.tests = new SelfTestRegistry_js_1.SelfTestRegistry(db, this, agenticConfig);
116
+ this.skillSynthesizer = new SkillSynthesizer_js_1.SkillSynthesizer(db, this, agenticConfig);
117
+ this.evolutionRitual = new EvolutionRitual_js_1.EvolutionRitual(db, this, agenticConfig);
106
118
  }
107
119
  /**
108
120
  * The "Soul-Searching" Loop: A top-level orchestration of all self-improvement rituals.
@@ -125,9 +137,13 @@ class Cortex {
125
137
  await this.ablation.monitorAblationPerformance();
126
138
  // 4. Mutation & Strategy
127
139
  await this.strategy.mutateStrategy();
128
- // 5. Broadcast knowledge
140
+ // 5. High-Throughput Evolution Pulse
141
+ await this.evolutionRitual.execute();
142
+ // 6. Broadcast knowledge & skills
129
143
  await this.hive.broadcastKnowledge();
130
- // 6. Evolutionary pulse
144
+ // 6b. Emergent Skill Synthesis
145
+ await this.skillSynthesizer.discoverAndSynthesize();
146
+ // 7. Evolutionary pulse
131
147
  await this.pilot.runSelfImprovementCycle();
132
148
  console.log('[Cortex] Soul-Searching loop completed.');
133
149
  }
@@ -30,7 +30,7 @@ export declare class CortexJanitor {
30
30
  pruneMetrics(daysToKeep?: number): Promise<number>;
31
31
  /**
32
32
  * Autonomous Indexing: Detects common query patterns and suggests missing indexes.
33
- * Production Hardening: Uses introspection and usage patterns.
33
+ * Production Hardening: Uses introspection and usage patterns from metrics.
34
34
  */
35
35
  autonomousIndexing(): Promise<string[]>;
36
36
  /**
@@ -83,39 +83,55 @@ class CortexJanitor {
83
83
  }
84
84
  /**
85
85
  * Autonomous Indexing: Detects common query patterns and suggests missing indexes.
86
- * Production Hardening: Uses introspection and usage patterns.
86
+ * Production Hardening: Uses introspection and usage patterns from metrics.
87
87
  */
88
88
  async autonomousIndexing() {
89
89
  console.log('[CortexJanitor] Analyzing query patterns for autonomous indexing...');
90
90
  const applied = [];
91
- // 1. Identify slow-moving tables or columns without indexes
92
- // For now, we focus on the core agentic tables
93
- const agenticTables = [
94
- this.knowledgeTable,
95
- this.config.memoriesTable || 'agent_memories',
96
- this.config.messagesTable || 'agent_messages'
91
+ // 1. Structural Heuristics: Core Identity Indexes
92
+ const coreIdentityTables = [
93
+ { table: this.knowledgeTable, col: 'entity' },
94
+ { table: this.config.memoriesTable || 'agent_memories', col: 'entity' },
95
+ { table: this.config.messagesTable || 'agent_messages', col: 'session_id' }
97
96
  ];
98
- for (const table of agenticTables) {
97
+ for (const target of coreIdentityTables) {
99
98
  try {
100
- // Heuristic: Ensure entity column is indexed in knowledge/memories
101
- if (table === this.knowledgeTable || table === (this.config.memoriesTable || 'agent_memories')) {
102
- const indexName = `idx_${table}_entity_v2`;
103
- await (0, sql_js_1.sql) `CREATE INDEX IF NOT EXISTS ${sql_js_1.sql.raw(indexName)} ON ${sql_js_1.sql.table(table)}(entity)`.execute(this.db);
104
- applied.push(`Ensured index ${indexName} exists`);
105
- }
106
- // Heuristic: Index status and confidence for high-volume filtering
107
- if (table === this.knowledgeTable) {
108
- const indexName = `idx_${table}_status_conf`;
109
- await (0, sql_js_1.sql) `CREATE INDEX IF NOT EXISTS ${sql_js_1.sql.raw(indexName)} ON ${sql_js_1.sql.table(table)}(status, confidence)`.execute(this.db);
110
- applied.push(`Ensured index ${indexName} exists`);
111
- }
99
+ const indexName = `idx_${target.table}_${target.col}_v2`;
100
+ await (0, sql_js_1.sql) `CREATE INDEX IF NOT EXISTS ${sql_js_1.sql.raw(indexName)} ON ${sql_js_1.sql.table(target.table)}(${sql_js_1.sql.raw(target.col)})`.execute(this.db);
101
+ applied.push(`Standardized identity index: ${indexName}`);
112
102
  }
113
103
  catch (err) {
114
- console.warn(`[CortexJanitor] Failed to apply autonomous index to ${table}:`, err);
104
+ console.warn(`[CortexJanitor] Identity indexing failed for ${target.table}:`, err);
105
+ }
106
+ }
107
+ // 2. Data-Driven Heuristics: Hotspot Injection
108
+ // We look for tables mentioned in slow-query metrics recently
109
+ const slowQueries = await this.db
110
+ .selectFrom(this.metricsTable)
111
+ .select('metadata')
112
+ .where('metric_name', '=', 'query_latency')
113
+ .where('metric_value', '>', 300) // Slower than 300ms
114
+ .limit(50)
115
+ .execute();
116
+ const tablesToRemoveFriction = new Set();
117
+ for (const q of slowQueries) {
118
+ try {
119
+ const meta = typeof q.metadata === 'string' ? JSON.parse(q.metadata) : (q.metadata || {});
120
+ if (meta.table)
121
+ tablesToRemoveFriction.add(meta.table);
122
+ }
123
+ catch (e) { /* ignore */ }
124
+ }
125
+ for (const table of tablesToRemoveFriction) {
126
+ // Hotspot logic: if it's high-traffic knowledge, index the status/confidence pair for promoting/demoting
127
+ if (table === this.knowledgeTable) {
128
+ const indexName = `idx_${table}_hotspot_lifecycle`;
129
+ await (0, sql_js_1.sql) `CREATE INDEX IF NOT EXISTS ${sql_js_1.sql.raw(indexName)} ON ${sql_js_1.sql.table(table)}(status, confidence)`.execute(this.db);
130
+ applied.push(`Injected hotspot index for lifecycle: ${indexName}`);
115
131
  }
116
132
  }
117
133
  if (applied.length > 0) {
118
- await this.logRitual('optimization', 'success', { action: 'autonomous_indexing', applied });
134
+ await this.logRitual('optimization', 'success', { action: 'autonomous_indexing', applied_count: applied.length });
119
135
  }
120
136
  return applied;
121
137
  }
@@ -12,7 +12,7 @@ export declare class CuriosityEngine {
12
12
  private get typedDb();
13
13
  /**
14
14
  * Analyze current knowledge to identify "Gaps" or contradictions.
15
- * Detects entities with low confidence or competing high-confidence facts.
15
+ * Detects entities with low confidence, unverified status, or competing high-confidence facts.
16
16
  */
17
17
  identifyKnowledgeGaps(): Promise<{
18
18
  entity: string;
@@ -36,7 +36,7 @@ export declare class CuriosityEngine {
36
36
  suggestQuestions(entity: string): Promise<string[]>;
37
37
  /**
38
38
  * Generate "Relationship Hypotheses" between high-confidence entities.
39
- * Suggests that entities with similar tags might be related.
39
+ * Suggests that entities with multi-tag overlaps might be related.
40
40
  */
41
41
  generateHypotheses(): Promise<string[]>;
42
42
  /**