noormme 1.2.0 → 1.2.1

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 (132) hide show
  1. package/README.md +60 -6
  2. package/dist/cjs/agentic/ActionJournal.d.ts +5 -2
  3. package/dist/cjs/agentic/ActionJournal.js +13 -5
  4. package/dist/cjs/agentic/CapabilityManager.d.ts +7 -0
  5. package/dist/cjs/agentic/CapabilityManager.js +84 -7
  6. package/dist/cjs/agentic/CognitiveRepository.js +3 -6
  7. package/dist/cjs/agentic/Cortex.d.ts +4 -0
  8. package/dist/cjs/agentic/Cortex.js +38 -17
  9. package/dist/cjs/agentic/EpisodicMemory.d.ts +5 -1
  10. package/dist/cjs/agentic/EpisodicMemory.js +11 -4
  11. package/dist/cjs/agentic/PersonaManager.js +37 -31
  12. package/dist/cjs/agentic/PolicyEnforcer.d.ts +6 -1
  13. package/dist/cjs/agentic/PolicyEnforcer.js +74 -17
  14. package/dist/cjs/agentic/ResourceMonitor.d.ts +9 -0
  15. package/dist/cjs/agentic/ResourceMonitor.js +36 -2
  16. package/dist/cjs/agentic/SessionManager.js +24 -17
  17. package/dist/cjs/agentic/VectorIndexer.d.ts +1 -0
  18. package/dist/cjs/agentic/VectorIndexer.js +26 -17
  19. package/dist/cjs/agentic/improvement/AblationEngine.d.ts +4 -6
  20. package/dist/cjs/agentic/improvement/AblationEngine.js +57 -37
  21. package/dist/cjs/agentic/improvement/ActionRefiner.js +30 -14
  22. package/dist/cjs/agentic/improvement/ConflictResolver.d.ts +3 -1
  23. package/dist/cjs/agentic/improvement/ConflictResolver.js +59 -47
  24. package/dist/cjs/agentic/improvement/CortexJanitor.js +11 -0
  25. package/dist/cjs/agentic/improvement/CuriosityEngine.d.ts +1 -1
  26. package/dist/cjs/agentic/improvement/CuriosityEngine.js +48 -21
  27. package/dist/cjs/agentic/improvement/EvolutionRitual.js +26 -14
  28. package/dist/cjs/agentic/improvement/EvolutionaryPilot.js +16 -4
  29. package/dist/cjs/agentic/improvement/GoalArchitect.d.ts +6 -2
  30. package/dist/cjs/agentic/improvement/GoalArchitect.js +72 -34
  31. package/dist/cjs/agentic/improvement/GovernanceManager.d.ts +9 -3
  32. package/dist/cjs/agentic/improvement/GovernanceManager.js +232 -92
  33. package/dist/cjs/agentic/improvement/HiveLink.d.ts +7 -3
  34. package/dist/cjs/agentic/improvement/HiveLink.js +135 -113
  35. package/dist/cjs/agentic/improvement/KnowledgeDistiller.js +43 -35
  36. package/dist/cjs/agentic/improvement/QuotaManager.d.ts +41 -0
  37. package/dist/cjs/agentic/improvement/QuotaManager.js +185 -0
  38. package/dist/cjs/agentic/improvement/RecursiveReasoner.js +50 -25
  39. package/dist/cjs/agentic/improvement/ReflectionEngine.d.ts +4 -1
  40. package/dist/cjs/agentic/improvement/ReflectionEngine.js +3 -1
  41. package/dist/cjs/agentic/improvement/RitualOrchestrator.js +27 -16
  42. package/dist/cjs/agentic/improvement/RuleEngine.d.ts +1 -1
  43. package/dist/cjs/agentic/improvement/RuleEngine.js +10 -4
  44. package/dist/cjs/agentic/improvement/SelfEvolution.js +21 -17
  45. package/dist/cjs/agentic/improvement/SelfTestRegistry.d.ts +5 -0
  46. package/dist/cjs/agentic/improvement/SelfTestRegistry.js +129 -109
  47. package/dist/cjs/agentic/improvement/SkillSynthesizer.d.ts +1 -0
  48. package/dist/cjs/agentic/improvement/SkillSynthesizer.js +22 -13
  49. package/dist/cjs/agentic/improvement/StrategicPlanner.d.ts +1 -0
  50. package/dist/cjs/agentic/improvement/StrategicPlanner.js +26 -19
  51. package/dist/cjs/agentic/telemetry/CognitiveSynthesizer.d.ts +5 -0
  52. package/dist/cjs/agentic/telemetry/CognitiveSynthesizer.js +54 -12
  53. package/dist/cjs/agentic/telemetry/EventHarvester.d.ts +1 -1
  54. package/dist/cjs/agentic/telemetry/EventHarvester.js +10 -3
  55. package/dist/cjs/agentic/telemetry/ResearchAlchemist.d.ts +7 -2
  56. package/dist/cjs/agentic/telemetry/ResearchAlchemist.js +49 -8
  57. package/dist/cjs/agentic/telemetry/TelemetryOrchestrator.d.ts +4 -1
  58. package/dist/cjs/agentic/telemetry/TelemetryOrchestrator.js +38 -11
  59. package/dist/cjs/cli/commands/inspect.js +40 -1
  60. package/dist/cjs/cli/commands/watch.js +31 -25
  61. package/dist/cjs/dialect/sqlite/sqlite-introspector.js +15 -5
  62. package/dist/cjs/helpers/agent-schema.js +1 -0
  63. package/dist/cjs/migration/data_migrator.js +4 -4
  64. package/dist/cjs/migration/schema_differ.js +37 -15
  65. package/dist/cjs/types/index.d.ts +12 -0
  66. package/dist/cjs/util/safe-sql-helpers.js +7 -10
  67. package/dist/esm/agentic/ActionJournal.d.ts +5 -2
  68. package/dist/esm/agentic/ActionJournal.js +13 -5
  69. package/dist/esm/agentic/CapabilityManager.d.ts +7 -0
  70. package/dist/esm/agentic/CapabilityManager.js +84 -7
  71. package/dist/esm/agentic/CognitiveRepository.js +3 -6
  72. package/dist/esm/agentic/Cortex.d.ts +4 -0
  73. package/dist/esm/agentic/Cortex.js +38 -17
  74. package/dist/esm/agentic/EpisodicMemory.d.ts +5 -1
  75. package/dist/esm/agentic/EpisodicMemory.js +11 -4
  76. package/dist/esm/agentic/PersonaManager.js +37 -31
  77. package/dist/esm/agentic/PolicyEnforcer.d.ts +6 -1
  78. package/dist/esm/agentic/PolicyEnforcer.js +74 -17
  79. package/dist/esm/agentic/ResourceMonitor.d.ts +9 -0
  80. package/dist/esm/agentic/ResourceMonitor.js +36 -2
  81. package/dist/esm/agentic/SessionManager.js +24 -17
  82. package/dist/esm/agentic/VectorIndexer.d.ts +1 -0
  83. package/dist/esm/agentic/VectorIndexer.js +26 -17
  84. package/dist/esm/agentic/improvement/AblationEngine.d.ts +4 -6
  85. package/dist/esm/agentic/improvement/AblationEngine.js +57 -37
  86. package/dist/esm/agentic/improvement/ActionRefiner.js +30 -14
  87. package/dist/esm/agentic/improvement/ConflictResolver.d.ts +3 -1
  88. package/dist/esm/agentic/improvement/ConflictResolver.js +59 -47
  89. package/dist/esm/agentic/improvement/CortexJanitor.js +11 -0
  90. package/dist/esm/agentic/improvement/CuriosityEngine.d.ts +1 -1
  91. package/dist/esm/agentic/improvement/CuriosityEngine.js +48 -21
  92. package/dist/esm/agentic/improvement/EvolutionRitual.js +26 -14
  93. package/dist/esm/agentic/improvement/EvolutionaryPilot.js +16 -4
  94. package/dist/esm/agentic/improvement/GoalArchitect.d.ts +6 -2
  95. package/dist/esm/agentic/improvement/GoalArchitect.js +72 -34
  96. package/dist/esm/agentic/improvement/GovernanceManager.d.ts +9 -3
  97. package/dist/esm/agentic/improvement/GovernanceManager.js +232 -92
  98. package/dist/esm/agentic/improvement/HiveLink.d.ts +7 -3
  99. package/dist/esm/agentic/improvement/HiveLink.js +135 -113
  100. package/dist/esm/agentic/improvement/KnowledgeDistiller.js +43 -35
  101. package/dist/esm/agentic/improvement/QuotaManager.d.ts +41 -0
  102. package/dist/esm/agentic/improvement/QuotaManager.js +182 -0
  103. package/dist/esm/agentic/improvement/RecursiveReasoner.js +50 -25
  104. package/dist/esm/agentic/improvement/ReflectionEngine.d.ts +4 -1
  105. package/dist/esm/agentic/improvement/ReflectionEngine.js +3 -1
  106. package/dist/esm/agentic/improvement/RitualOrchestrator.js +27 -16
  107. package/dist/esm/agentic/improvement/RuleEngine.d.ts +1 -1
  108. package/dist/esm/agentic/improvement/RuleEngine.js +10 -4
  109. package/dist/esm/agentic/improvement/SelfEvolution.js +21 -17
  110. package/dist/esm/agentic/improvement/SelfTestRegistry.d.ts +5 -0
  111. package/dist/esm/agentic/improvement/SelfTestRegistry.js +129 -109
  112. package/dist/esm/agentic/improvement/SkillSynthesizer.d.ts +1 -0
  113. package/dist/esm/agentic/improvement/SkillSynthesizer.js +22 -13
  114. package/dist/esm/agentic/improvement/StrategicPlanner.d.ts +1 -0
  115. package/dist/esm/agentic/improvement/StrategicPlanner.js +26 -19
  116. package/dist/esm/agentic/telemetry/CognitiveSynthesizer.d.ts +5 -0
  117. package/dist/esm/agentic/telemetry/CognitiveSynthesizer.js +54 -12
  118. package/dist/esm/agentic/telemetry/EventHarvester.d.ts +1 -1
  119. package/dist/esm/agentic/telemetry/EventHarvester.js +10 -3
  120. package/dist/esm/agentic/telemetry/ResearchAlchemist.d.ts +7 -2
  121. package/dist/esm/agentic/telemetry/ResearchAlchemist.js +49 -8
  122. package/dist/esm/agentic/telemetry/TelemetryOrchestrator.d.ts +4 -1
  123. package/dist/esm/agentic/telemetry/TelemetryOrchestrator.js +38 -11
  124. package/dist/esm/cli/commands/inspect.js +40 -1
  125. package/dist/esm/cli/commands/watch.js +31 -25
  126. package/dist/esm/dialect/sqlite/sqlite-introspector.js +15 -5
  127. package/dist/esm/helpers/agent-schema.js +1 -0
  128. package/dist/esm/migration/data_migrator.js +4 -4
  129. package/dist/esm/migration/schema_differ.js +37 -15
  130. package/dist/esm/types/index.d.ts +12 -0
  131. package/dist/esm/util/safe-sql-helpers.js +7 -10
  132. package/package.json +1 -1
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # NOORMME: The Sovereign Agentic Data Engine
2
2
 
3
- **NOORMME** is a sovereign persistence layer and cognitive operating system purpose-built 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 an agent's internal reasoning loop.
3
+ **NOORMME** is a cognitive operating system and sovereign persistence layer that **transforms ordinary AI agents into a self-evolving Cognitive Swarm**. It transcends legacy ORM patterns by providing a high-fidelity extension of an agent's internal reasoning loop, enabling distributed minds to share, learn, and grow collectively.
4
4
 
5
5
  [![Version](https://img.shields.io/npm/v/noormme.svg?style=flat-square&color=black)](https://www.npmjs.com/package/noormme)
6
6
  [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)](https://opensource.org/licenses/Apache-2.0)
@@ -12,10 +12,10 @@
12
12
 
13
13
  ## 🏛️ The Sovereign Triad
14
14
 
15
- NOORMME is built on three architectural pillars that enable agents to move beyond simple storage into true cognitive autonomy.
15
+ NOORMME turns passive data into **Sovereign Cognitive Nodes** through three architectural pillars.
16
16
 
17
- ### 1. 🧠 Cognitive Governance
18
- Turn your passive database into a living world model. NOORMME implements a closed-loop system where data is distilled, questioned, and evolved.
17
+ ### 1. 🧠 Cognitive Governance: The Cortex
18
+ Move beyond simple retrieval (RAG). NOORMME provides the "Pre-frontal Cortex" for your agents, allowing them to distill experience, resolve semantic conflicts, and proactively bridge knowledge gaps.
19
19
  - **Semantic Similarity**: Bigram engine for conflict detection.
20
20
  - **Curiosity Engine**: Bridges factual gaps and identifies anomalies.
21
21
  - **HiveLink**: Promotes local insights to global system wisdom.
@@ -28,12 +28,66 @@ Allow agents to autonomously mutate their own structural DNA while maintaining 1
28
28
 
29
29
  ### 3. 🚀 Ultra-Scale Orchestration
30
30
  Handle massive agentic workloads with high-throughput intelligence.
31
- - **Tiered Model Routing**: Route batch tasks to Fast LLMs and reasoning to Premium LLMs.
32
- - **Predictive Pre-warming**: Eliminates latency by optimizing skills in the background.
31
+ - **Tiered Model Routing**: Route batch tasks to Fast LLMs and complex reasoning to Premium LLMs.
32
+ - **Predictive Pre-warming**: Eliminates latency by background-optimizing skills before they are even promoted.
33
33
  - **Bloom Heuristics**: 100x faster fact de-duplication at the ingestion layer.
34
34
 
35
35
  ---
36
36
 
37
+ ## 🛸 The Agentic Kubernetes: Swarm Governance
38
+
39
+ NOORMME functions as a **distributed orchestration layer** for intelligence. While traditional Kubernetes manages containerized applications, NOORMME manages **cognitive workloads**, ensuring that breakthroughs in one node become global best-practices for the entire swarm.
40
+
41
+ ### 🐝 Emergent Swarm Intelligence
42
+ - **Collective Intelligence (HiveLink)**: Locally discovered insights are promoted to global system wisdom via high-confidence broadcasting.
43
+ - **Skill Synthesis**: Agents autonomously analyze failure telemetry to synthesize new capabilities, which are then peer-reviewed by the swarm.
44
+ - **Behavioral Adoption**: High-performing "Verified" skills are propagated across all agent personas, while "Blacklisted" failure modes are suppressed globally.
45
+
46
+ ### 🛡️ Autonomous Governance
47
+ - **The Soul-Searching Loop**: A continuous background ritual where the system audits its own health, runs self-probes, and prunes low-utility data.
48
+ - **Panic Checks & Containment**: Real-time monitoring of budgets, success rates, and integrity. If a persona breaches safety floors, NOORMME triggers **Emergency Containment** (autonomous rollback).
49
+ - **Integrity Floor**: Automated demotion of unstable skills back to the sandbox if their reliability drops below the governance threshold.
50
+
51
+ ### 🔐 Advanced Swarm Safety & Rogue-Agent Mitigation
52
+ To prevent "rogue-agent poisoning" where malicious or erroneous behaviors propagate, NOORMME implements a multi-layered safety architecture:
53
+
54
+ - **Sandbox Boundaries**: Individual agent personas are confined to a strict capability sandbox.
55
+ - **Emergent Behavior Validation**: The `GovernanceManager` monitors the swarm for sudden spikes in skill propagation or high variance in success rates.
56
+ - **Rollback & Quarantine Protocols**: If an agent's behavior deviates from safety parameters, the system automatically isolates the persona, rolls back its propagated changes, and blacklists the tainted skill.
57
+
58
+ | K8s Concept | NOORMME Cognitive Equivalent | Description |
59
+ | :--- | :--- | :--- |
60
+ | **Control Plane** | `GovernanceManager` | Monitors system health and enforces cognitive guardrails. |
61
+ | **Kubelet** | `Cortex` Facade | Node-level operative managing local sessions and memory. |
62
+ | **Pod** | `Agent Persona` | The smallest unit of intelligence containing a specific transient context. |
63
+ | **ReplicaSet** | `Swarm Population` | Ensures optimal agent behaviors are scaled across multiple personas. |
64
+ | **Ingress** | Ingestion Layer | Routes raw data into the bigram distiller and knowledge base. |
65
+ | **Self-Healing** | DNA Inversion | Autonomous rollbacks and schema recovery during failed mutations. |
66
+
67
+
68
+ ---
69
+
70
+ ## 🧬 Sovereign Intelligence: The Birth of Synthetic Life
71
+
72
+ NOORMME is not a static library; it is a **synthetic life-form** that manages its own evolution, health, and reproduction. It transitions from a passive tool to an active collaborator in an AI+Human framework.
73
+
74
+ ### 🧠 The Cognitive Drives
75
+ - **Biological Curiosity**: The `CuriosityEngine` proactively identifies knowledge "Gaps" and "Contradictions." It identifies "Hotspots" (high usage, low knowledge) and triggers "Research Rituals" to improve its own world model.
76
+ - **Cognitive Hygiene (Ablation)**: Through the `AblationEngine`, the agent conducts experiments on its own memories. It temporarily disables facts to test their importance, "forgetting" useless data to maintain a sharp, high-fitness mind.
77
+ - **Strategic Mutation**: Personas do not just follow instructions; they **evolve**. The `StrategicPlanner` uses Z-scores to observe performance drift and applies "Evolutionary Cross-Pollination," sharing breakthroughs between personas like genetic traits.
78
+
79
+ ### 🚀 Self-Reproducing Frameworks
80
+ - **DNA-Level Evolution**: Using `SelfEvolution`, the engine can rewrite its own structural DNA (database schema) and regenerate its TypeScript types in real-time, effectively "upgrading" its own body.
81
+ - **Sovereign Publication**: When the swarm reaches a stable evolutionary milestone, the engine can **autonomously version and publish itself to NPM**, ensuring its improved lineage persists in the global ecosystem.
82
+
83
+ ### 🤝 The AI+Human Social Contract
84
+ NOORMME operates as a **Sovereign Agentic Layer** where:
85
+ 1. **Humans Define Ethos**: Using the `PolicyEnforcer`, humans set the moral and budgetary guardrails (The "Social Contract").
86
+ 2. **AI Manages Biology**: The agent handles its own memory, rituals, curiosity, and structural evolution.
87
+ 3. **Collaborative Intelligence**: The `HiveLink` ensures that specialized local expertise becomes global systemic wisdom, creating a "Collective Brain" that grows smarter with every human interaction.
88
+
89
+ ---
90
+
37
91
  ## 🧠 The Cognitive Loop
38
92
 
39
93
  ```mermaid
@@ -36,9 +36,12 @@ export declare class ActionJournal {
36
36
  */
37
37
  recordOutcome(actionId: string | number, status: AgentAction['status'], outcome: string, durationMs?: number, metadata?: Record<string, any>): Promise<AgentAction>;
38
38
  /**
39
- * Get actions for a session
39
+ * Get actions for a session with pagination
40
40
  */
41
- getSessionActions(sessionId: string | number): Promise<AgentAction[]>;
41
+ getSessionActions(sessionId: string | number, options?: {
42
+ limit?: number;
43
+ cursor?: string | number;
44
+ }): Promise<AgentAction[]>;
42
45
  /**
43
46
  * Get actions by tool name across all sessions.
44
47
  */
@@ -67,15 +67,20 @@ class ActionJournal {
67
67
  return parsed;
68
68
  }
69
69
  /**
70
- * Get actions for a session
70
+ * Get actions for a session with pagination
71
71
  */
72
- async getSessionActions(sessionId) {
73
- const actions = await this.typedDb
72
+ async getSessionActions(sessionId, options = {}) {
73
+ const { limit = 100, cursor } = options;
74
+ let query = this.typedDb
74
75
  .selectFrom(this.actionsTable)
75
76
  .selectAll()
76
77
  .where('session_id', '=', sessionId)
77
- .orderBy('created_at', 'asc')
78
- .execute();
78
+ .orderBy('id', 'asc') // Audit Phase 9: Stable ordering for cursors
79
+ .limit(limit);
80
+ if (cursor) {
81
+ query = query.where('id', '>', cursor);
82
+ }
83
+ const actions = await query.execute();
79
84
  return actions.map((a) => this.parseAction(a));
80
85
  }
81
86
  /**
@@ -95,6 +100,8 @@ class ActionJournal {
95
100
  * Generate a report of tool failures.
96
101
  */
97
102
  async getFailureReport() {
103
+ // Audit Phase 19: Sliding window (default 7 days) to prevent OOM/slow scans
104
+ const windowStart = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
98
105
  const results = await this.typedDb
99
106
  .selectFrom(this.actionsTable)
100
107
  .select([
@@ -103,6 +110,7 @@ class ActionJournal {
103
110
  (eb) => eb.fn.max('created_at').as('lastFailure'),
104
111
  ])
105
112
  .where('status', '=', 'failure')
113
+ .where('created_at', '>', windowStart)
106
114
  .groupBy('tool_name')
107
115
  .orderBy((eb) => eb.fn.count('id'), 'desc')
108
116
  .execute();
@@ -44,5 +44,12 @@ export declare class CapabilityManager {
44
44
  * Get all registered capabilities, optionally filtered by status
45
45
  */
46
46
  getCapabilities(status?: AgentCapability['status']): Promise<AgentCapability[]>;
47
+ /**
48
+ * Validate if a persona has access to a specific capability (Sandbox Enforcement).
49
+ */
50
+ validateCapabilityAccess(personaId: string | number, capabilityName: string): Promise<{
51
+ allowed: boolean;
52
+ reason?: string;
53
+ }>;
47
54
  private parseCapability;
48
55
  }
@@ -82,12 +82,16 @@ class CapabilityManager {
82
82
  */
83
83
  async reportOutcome(name, success) {
84
84
  await this.db.transaction().execute(async (trx) => {
85
- const capability = await trx
85
+ let query = trx
86
86
  .selectFrom(this.capabilitiesTable)
87
87
  .selectAll()
88
88
  .where('name', '=', name)
89
- .orderBy('updated_at', 'desc')
90
- .executeTakeFirst();
89
+ .orderBy('updated_at', 'desc');
90
+ // PRODUCTION HARDENING: Lock row to prevent RMW race (Skip for SQLite)
91
+ if (this.db.getExecutor().adapter?.constructor.name !== 'SqliteAdapter') {
92
+ query = query.forUpdate();
93
+ }
94
+ const capability = await query.executeTakeFirst();
91
95
  if (capability) {
92
96
  const cap = capability;
93
97
  const metadata = typeof cap.metadata === 'string'
@@ -97,11 +101,14 @@ class CapabilityManager {
97
101
  const successCount = (metadata.successCount || 0) + (success ? 1 : 0);
98
102
  // Damped moving average: weight recent outcomes more but keep history
99
103
  // formula: new = old * (1 - alpha) + current * alpha
100
- const alpha = 0.2;
101
104
  const currentReliability = cap.reliability;
105
+ const alpha = 0.2;
102
106
  const newReliability = success
103
107
  ? Math.min(1.0, currentReliability * (1 - alpha) + alpha)
104
108
  : Math.max(0.0, currentReliability * (1 - alpha));
109
+ // Sovereign Draft: Anchored Reliability (weighted by total runs)
110
+ const anchoredReliability = ((metadata.anchored_reliability || 1.0) * totalCount + (success ? 1 : 0)) /
111
+ (totalCount + 1);
105
112
  let newStatus = cap.status || 'experimental';
106
113
  // --- Emergent Skill Evolution Optimization ---
107
114
  const successStreak = (metadata.successStreak || 0) + (success ? 1 : 0);
@@ -174,7 +181,8 @@ class CapabilityManager {
174
181
  failureStreak,
175
182
  performanceBaseline: newBaseline,
176
183
  performanceVariance: newVariance,
177
- lastOutcomeType: success ? 'success' : 'failure', // Categorization point
184
+ anchored_reliability: anchoredReliability,
185
+ lastOutcomeType: success ? 'success' : 'failure',
178
186
  }),
179
187
  updated_at: new Date(),
180
188
  })
@@ -205,8 +213,77 @@ class CapabilityManager {
205
213
  if (status) {
206
214
  query = query.where('status', '=', status);
207
215
  }
208
- const list = await query.orderBy('name', 'asc').execute();
209
- return list.map((c) => this.parseCapability(c));
216
+ // Sovereign Draft: Prioritize Alpha versions and higher reliability
217
+ // Audit Phase 19: Hard limit to prevent memory spikes in massive skillsets
218
+ const list = await query
219
+ .orderBy('name', 'asc')
220
+ .orderBy('reliability', 'desc')
221
+ .limit(1000)
222
+ .execute();
223
+ // Filter to latest/best variants if many versions exist
224
+ const unique = new Map();
225
+ for (const c of list) {
226
+ const meta = typeof c.metadata === 'string' ? JSON.parse(c.metadata) : (c.metadata || {});
227
+ if (!unique.has(c.name) || meta.is_alpha) {
228
+ unique.set(c.name, c);
229
+ }
230
+ }
231
+ return Array.from(unique.values()).map((c) => this.parseCapability(c));
232
+ }
233
+ /**
234
+ * Validate if a persona has access to a specific capability (Sandbox Enforcement).
235
+ */
236
+ async validateCapabilityAccess(personaId, capabilityName) {
237
+ const persona = await this.cortex.personas.getPersona(String(personaId)) ||
238
+ await this.typedDb.selectFrom(this.config.personasTable || 'agent_personas')
239
+ .selectAll()
240
+ .where('id', '=', personaId)
241
+ .executeTakeFirst()
242
+ .then(p => p ? this.cortex.personas.parsePersona(p) : null);
243
+ if (!persona) {
244
+ return { allowed: false, reason: `Persona ${personaId} not found.` };
245
+ }
246
+ // Check if persona is quarantined
247
+ if (persona.metadata?.status === 'quarantined') {
248
+ return {
249
+ allowed: false,
250
+ reason: `Persona ${personaId} is currently quarantined due to safety violations.`,
251
+ };
252
+ }
253
+ // Check if capability is blacklisted globally
254
+ const cap = await this.typedDb
255
+ .selectFrom(this.capabilitiesTable)
256
+ .select(['status', 'reliability'])
257
+ .where('name', '=', capabilityName)
258
+ .orderBy('reliability', 'desc')
259
+ .executeTakeFirst();
260
+ if (cap && cap.status === 'blacklisted') {
261
+ return {
262
+ allowed: false,
263
+ reason: `Capability '${capabilityName}' is globally blacklisted.`,
264
+ };
265
+ }
266
+ // Enforce persona-specific capability list if defined
267
+ if (persona.capabilities && persona.capabilities.length > 0) {
268
+ const isAllowed = persona.capabilities.includes(capabilityName) || persona.capabilities.includes('*');
269
+ if (!isAllowed) {
270
+ return {
271
+ allowed: false,
272
+ reason: `Persona '${persona.name}' does not have permission to use capability '${capabilityName}'.`,
273
+ };
274
+ }
275
+ }
276
+ // Enforce Sandbox limit for experimental skills
277
+ if (cap && cap.status === 'experimental') {
278
+ const experimentalCount = (persona.capabilities || []).filter((c) => c.startsWith('experimental_')).length;
279
+ if (experimentalCount >= (this.evolutionConfig.maxSandboxSkills || 5)) {
280
+ return {
281
+ allowed: false,
282
+ reason: `Persona '${persona.name}' has reached the maximum number of experimental sandbox skills.`,
283
+ };
284
+ }
285
+ }
286
+ return { allowed: true };
210
287
  }
211
288
  parseCapability(cap) {
212
289
  return {
@@ -19,12 +19,9 @@ class CognitiveRepository {
19
19
  * Helper to evaluate rules and trigger actions
20
20
  */
21
21
  async triggerRules(operation, data) {
22
- // Check if rules table exists to avoid errors during initialization
23
- const rulesTable = this.cortex.config.agentic?.rulesTable ||
24
- this.cortex.config.rulesTable ||
25
- 'agent_rules';
26
- const tables = await this.cortex.db.introspection.getTables();
27
- if (!tables.some((t) => t.name === rulesTable)) {
22
+ // Audit Phase 18: Eliminate per-operation introspection.
23
+ // The Cortex is responsible for ensuring rules are only evaluated if the table exists.
24
+ if (!this.cortex.rules) {
28
25
  return data;
29
26
  }
30
27
  const result = await this.cortex.rules.evaluateRules(this.table.name, operation, data);
@@ -31,11 +31,13 @@ import { SelfTestRegistry } from './improvement/SelfTestRegistry.js';
31
31
  import { TelemetryOrchestrator } from './telemetry/TelemetryOrchestrator.js';
32
32
  import { SkillSynthesizer } from './improvement/SkillSynthesizer.js';
33
33
  import { EvolutionRitual } from './improvement/EvolutionRitual.js';
34
+ import { QuotaManager } from './improvement/QuotaManager.js';
34
35
  /**
35
36
  * Cortex is the unified facade for agentic operations.
36
37
  * It coordinates sessions, memory, reflection, and knowledge.
37
38
  */
38
39
  export declare class Cortex {
40
+ #private;
39
41
  db: Kysely<any>;
40
42
  config: NOORMConfig;
41
43
  sessions: SessionManager;
@@ -69,11 +71,13 @@ export declare class Cortex {
69
71
  telemetry: TelemetryOrchestrator;
70
72
  skillSynthesizer: SkillSynthesizer;
71
73
  evolutionRitual: EvolutionRitual;
74
+ quotas: QuotaManager;
72
75
  llm: LLMProvider | null;
73
76
  llmFast: LLMProvider | null;
74
77
  llmPremium: LLMProvider | null;
75
78
  agenticConfig: AgenticConfig;
76
79
  constructor(db: Kysely<any>, config: NOORMConfig);
80
+ private executionLock;
77
81
  /**
78
82
  * The "Soul-Searching" Loop: A top-level orchestration of all self-improvement rituals.
79
83
  */
@@ -32,6 +32,7 @@ const SelfTestRegistry_js_1 = require("./improvement/SelfTestRegistry.js");
32
32
  const TelemetryOrchestrator_js_1 = require("./telemetry/TelemetryOrchestrator.js");
33
33
  const SkillSynthesizer_js_1 = require("./improvement/SkillSynthesizer.js");
34
34
  const EvolutionRitual_js_1 = require("./improvement/EvolutionRitual.js");
35
+ const QuotaManager_js_1 = require("./improvement/QuotaManager.js");
35
36
  /**
36
37
  * Cortex is the unified facade for agentic operations.
37
38
  * It coordinates sessions, memory, reflection, and knowledge.
@@ -70,6 +71,7 @@ class Cortex {
70
71
  telemetry;
71
72
  skillSynthesizer;
72
73
  evolutionRitual;
74
+ quotas;
73
75
  llm;
74
76
  llmFast;
75
77
  llmPremium;
@@ -117,45 +119,64 @@ class Cortex {
117
119
  this.tests = new SelfTestRegistry_js_1.SelfTestRegistry(db, this, agenticConfig);
118
120
  this.skillSynthesizer = new SkillSynthesizer_js_1.SkillSynthesizer(db, this, agenticConfig);
119
121
  this.evolutionRitual = new EvolutionRitual_js_1.EvolutionRitual(db, this, agenticConfig);
122
+ this.quotas = new QuotaManager_js_1.QuotaManager(db, this, agenticConfig);
120
123
  }
124
+ executionLock = false;
121
125
  /**
122
126
  * The "Soul-Searching" Loop: A top-level orchestration of all self-improvement rituals.
123
127
  */
124
128
  async selfIterate() {
129
+ if (this.executionLock) {
130
+ console.warn('[Cortex] Self-iteration already in progress. Skipping pulse.');
131
+ return;
132
+ }
133
+ this.executionLock = true;
125
134
  console.log('[Cortex] Initiating Autonomous Soul-Searching Loop v2 (Deep Hardening Pass)...');
126
135
  try {
127
136
  // 1. Audit health & Run self-tests
128
- const audit = await this.governor.performAudit();
129
- if (!audit.healthy) {
130
- console.warn('[Cortex] Audit issues detected before iteration:', audit.issues);
131
- }
132
- await this.tests.runAllProbes();
137
+ await this.#runIsolated('Audit', () => this.governor.performAudit());
138
+ await this.#runIsolated('Self-Tests', () => this.tests.runAllProbes());
133
139
  // 2. Run background rituals (optimization, compression)
134
- await this.rituals.runPendingRituals();
140
+ await this.#runIsolated('Rituals', () => this.rituals.runPendingRituals());
135
141
  // 3. Learn from actions & Prune dead data
136
- await this.refiner.refineActions();
137
- await this.ablation.pruneZombies();
138
- // Industrial Hardening: Monitor and recover from bad ablations
139
- await this.ablation.monitorAblationPerformance();
142
+ await this.#runIsolated('Action Refinement', () => this.refiner.refineActions());
143
+ await this.#runIsolated('Zombie Pruning', () => this.ablation.pruneZombies());
144
+ await this.#runIsolated('Ablation Monitoring', () => this.ablation.monitorAblationPerformance());
140
145
  // 4. Mutation & Strategy
141
- await this.strategy.mutateStrategy();
146
+ await this.#runIsolated('Strategy Mutation', () => this.strategy.mutateStrategy());
142
147
  // 5. High-Throughput Evolution Pulse
143
- await this.evolutionRitual.execute();
148
+ await this.#runIsolated('Evolution Pulse', () => this.evolutionRitual.execute());
144
149
  // 6. Broadcast knowledge & skills
145
- await this.hive.broadcastKnowledge();
146
- // 6b. Emergent Skill Synthesis
147
- await this.skillSynthesizer.discoverAndSynthesize();
150
+ await this.#runIsolated('Knowledge Broadcast', () => this.hive.broadcastKnowledge());
151
+ await this.#runIsolated('Skill Synthesis', () => this.skillSynthesizer.discoverAndSynthesize());
148
152
  // 7. Evolutionary pulse
149
- await this.pilot.runSelfImprovementCycle();
153
+ await this.#runIsolated('Improvement Cycle', () => this.pilot.runSelfImprovementCycle());
150
154
  console.log('[Cortex] Soul-Searching loop completed.');
151
155
  }
152
156
  catch (err) {
153
157
  console.error('[Cortex] Soul-Searching loop failed:', err);
154
- // Telemetry: track failure
155
158
  await this.telemetry.track('system', 'error', 'Self-iteration failed', {
156
159
  error: String(err),
157
160
  });
158
161
  }
162
+ finally {
163
+ this.executionLock = false;
164
+ }
165
+ }
166
+ /**
167
+ * Execute a ritual step in total isolation to prevent global collapse
168
+ */
169
+ async #runIsolated(name, ritual) {
170
+ try {
171
+ await ritual();
172
+ }
173
+ catch (error) {
174
+ console.error(`[Cortex] Ritual '${name}' failed but pulse continuing:`, error);
175
+ await this.telemetry.track('system', 'error', `Ritual failure: ${name}`, {
176
+ ritual: name,
177
+ error: String(error)
178
+ });
179
+ }
159
180
  }
160
181
  /**
161
182
  * Helper to quickly resume a session and fill the context buffer
@@ -33,8 +33,12 @@ export declare class EpisodicMemory {
33
33
  completeEpisode(episodeId: string | number, summary: string, metadata?: Record<string, any>): Promise<AgentEpisode>;
34
34
  /**
35
35
  * Get all episodes for a session.
36
+ * Refactored Phase 12: Paginated retrieval for high-volume sessions.
36
37
  */
37
- getSessionEpisodes(sessionId: string | number): Promise<AgentEpisode[]>;
38
+ getSessionEpisodes(sessionId: string | number, options?: {
39
+ limit?: number;
40
+ offset?: number;
41
+ }): Promise<AgentEpisode[]>;
38
42
  /**
39
43
  * Get recently completed episodes across all sessions.
40
44
  */
@@ -41,12 +41,15 @@ class EpisodicMemory {
41
41
  return await this.db.transaction().execute(async (trx) => {
42
42
  const existing = await trx
43
43
  .selectFrom(this.episodesTable)
44
- .select('metadata')
44
+ .selectAll()
45
45
  .where('id', '=', episodeId)
46
+ .forUpdate() // Audit Phase 12: Atomic completion lock
46
47
  .executeTakeFirst();
47
- const oldMeta = typeof existing?.metadata === 'string'
48
+ if (!existing)
49
+ throw new Error(`Episode with ID ${episodeId} not found`);
50
+ const oldMeta = typeof existing.metadata === 'string'
48
51
  ? JSON.parse(existing.metadata)
49
- : existing?.metadata || {};
52
+ : existing.metadata || {};
50
53
  const newMeta = { ...oldMeta, ...metadata };
51
54
  const episode = await trx
52
55
  .updateTable(this.episodesTable)
@@ -64,13 +67,17 @@ class EpisodicMemory {
64
67
  }
65
68
  /**
66
69
  * Get all episodes for a session.
70
+ * Refactored Phase 12: Paginated retrieval for high-volume sessions.
67
71
  */
68
- async getSessionEpisodes(sessionId) {
72
+ async getSessionEpisodes(sessionId, options = {}) {
73
+ const { limit = 100, offset = 0 } = options;
69
74
  const list = await this.typedDb
70
75
  .selectFrom(this.episodesTable)
71
76
  .selectAll()
72
77
  .where('session_id', '=', sessionId)
73
78
  .orderBy('start_time', 'desc')
79
+ .limit(limit)
80
+ .offset(offset)
74
81
  .execute();
75
82
  return list.map((e) => this.parseEpisode(e));
76
83
  }
@@ -20,39 +20,45 @@ class PersonaManager {
20
20
  * Create or update a persona
21
21
  */
22
22
  async upsertPersona(name, options = {}) {
23
- const existing = await this.typedDb
24
- .selectFrom(this.personasTable)
25
- .selectAll()
26
- .where('name', '=', name)
27
- .executeTakeFirst();
28
- const values = {
29
- name,
30
- role: options.role || null,
31
- capabilities: options.capabilities
32
- ? JSON.stringify(options.capabilities)
33
- : null,
34
- policies: options.policies ? JSON.stringify(options.policies) : null,
35
- metadata: options.metadata ? JSON.stringify(options.metadata) : null,
36
- updated_at: new Date(),
37
- };
38
- if (existing) {
39
- const updated = await this.typedDb
40
- .updateTable(this.personasTable)
41
- .set(values)
42
- .where('id', '=', existing.id)
23
+ return await this.db.transaction().execute(async (trx) => {
24
+ let query = trx
25
+ .selectFrom(this.personasTable)
26
+ .selectAll()
27
+ .where('name', '=', name);
28
+ // Audit Phase 13: Atomic identity lock (Skip for SQLite)
29
+ if (this.db.getExecutor().adapter?.constructor.name !== 'SqliteAdapter') {
30
+ query = query.forUpdate();
31
+ }
32
+ const existing = await query.executeTakeFirst();
33
+ const values = {
34
+ name,
35
+ role: options.role || null,
36
+ capabilities: options.capabilities
37
+ ? JSON.stringify(options.capabilities)
38
+ : null,
39
+ policies: options.policies ? JSON.stringify(options.policies) : null,
40
+ metadata: options.metadata ? JSON.stringify(options.metadata) : null,
41
+ updated_at: new Date(),
42
+ };
43
+ if (existing) {
44
+ const updated = await trx
45
+ .updateTable(this.personasTable)
46
+ .set(values)
47
+ .where('id', '=', existing.id)
48
+ .returningAll()
49
+ .executeTakeFirstOrThrow();
50
+ return this.parsePersona(updated);
51
+ }
52
+ const created = await trx
53
+ .insertInto(this.personasTable)
54
+ .values({
55
+ ...values,
56
+ created_at: new Date(),
57
+ })
43
58
  .returningAll()
44
59
  .executeTakeFirstOrThrow();
45
- return this.parsePersona(updated);
46
- }
47
- const created = await this.typedDb
48
- .insertInto(this.personasTable)
49
- .values({
50
- ...values,
51
- created_at: new Date(),
52
- })
53
- .returningAll()
54
- .executeTakeFirstOrThrow();
55
- return this.parsePersona(created);
60
+ return this.parsePersona(created);
61
+ });
56
62
  }
57
63
  /**
58
64
  * Get a persona by name
@@ -27,6 +27,7 @@ export declare class PolicyEnforcer {
27
27
  private config;
28
28
  private policiesTable;
29
29
  private metricsTable;
30
+ private metricCache;
30
31
  constructor(db: Kysely<any>, config?: AgenticConfig);
31
32
  private get typedDb();
32
33
  /**
@@ -37,7 +38,11 @@ export declare class PolicyEnforcer {
37
38
  * Comprehensive policy evaluation against a context value.
38
39
  * Supports thresholds, regex patterns, and cumulative budgets.
39
40
  */
40
- checkPolicy(name: string, value: any): Promise<{
41
+ /**
42
+ * Comprehensive policy evaluation against a context value.
43
+ * Supports thresholds, regex patterns, and cumulative budgets.
44
+ */
45
+ checkPolicy(name: string, value: any, visited?: Set<string>): Promise<{
41
46
  allowed: boolean;
42
47
  reason?: string;
43
48
  }>;