noormme 1.1.0 → 1.2.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 (225) hide show
  1. package/README.md +84 -65
  2. package/dist/cjs/agentic/ActionJournal.js +13 -9
  3. package/dist/cjs/agentic/CapabilityManager.js +35 -21
  4. package/dist/cjs/agentic/CognitiveRepository.js +19 -9
  5. package/dist/cjs/agentic/ContextBuffer.js +24 -12
  6. package/dist/cjs/agentic/Cortex.js +11 -4
  7. package/dist/cjs/agentic/EpisodicMemory.js +7 -5
  8. package/dist/cjs/agentic/PersonaManager.js +16 -8
  9. package/dist/cjs/agentic/PolicyEnforcer.js +31 -12
  10. package/dist/cjs/agentic/ResourceMonitor.js +4 -4
  11. package/dist/cjs/agentic/SessionCompressor.js +22 -14
  12. package/dist/cjs/agentic/SessionManager.js +36 -18
  13. package/dist/cjs/agentic/VectorIndexer.js +22 -18
  14. package/dist/cjs/agentic/improvement/AblationEngine.js +22 -15
  15. package/dist/cjs/agentic/improvement/ActionRefiner.js +12 -10
  16. package/dist/cjs/agentic/improvement/ConflictResolver.js +5 -5
  17. package/dist/cjs/agentic/improvement/CortexJanitor.js +30 -9
  18. package/dist/cjs/agentic/improvement/CuriosityEngine.js +27 -23
  19. package/dist/cjs/agentic/improvement/EvolutionRitual.js +4 -4
  20. package/dist/cjs/agentic/improvement/EvolutionaryPilot.js +16 -6
  21. package/dist/cjs/agentic/improvement/GoalArchitect.d.ts +2 -2
  22. package/dist/cjs/agentic/improvement/GoalArchitect.js +20 -18
  23. package/dist/cjs/agentic/improvement/GovernanceManager.js +19 -11
  24. package/dist/cjs/agentic/improvement/HiveLink.js +22 -15
  25. package/dist/cjs/agentic/improvement/KnowledgeDistiller.js +48 -32
  26. package/dist/cjs/agentic/improvement/RecursiveReasoner.js +40 -17
  27. package/dist/cjs/agentic/improvement/ReflectionEngine.js +10 -8
  28. package/dist/cjs/agentic/improvement/RitualOrchestrator.js +28 -22
  29. package/dist/cjs/agentic/improvement/RuleEngine.js +22 -17
  30. package/dist/cjs/agentic/improvement/SelfEvolution.js +24 -18
  31. package/dist/cjs/agentic/improvement/SelfTestRegistry.js +18 -15
  32. package/dist/cjs/agentic/improvement/SkillSynthesizer.js +42 -27
  33. package/dist/cjs/agentic/improvement/SovereignMetrics.js +19 -17
  34. package/dist/cjs/agentic/improvement/StrategicPlanner.js +120 -55
  35. package/dist/cjs/agentic/telemetry/CognitiveSynthesizer.js +26 -12
  36. package/dist/cjs/agentic/telemetry/EventHarvester.js +3 -2
  37. package/dist/cjs/agentic/telemetry/ResearchAlchemist.js +5 -2
  38. package/dist/cjs/cache/cache-manager.js +7 -4
  39. package/dist/cjs/cli/commands/analyze.js +5 -4
  40. package/dist/cjs/cli/commands/generate.js +81 -44
  41. package/dist/cjs/cli/commands/init.js +7 -3
  42. package/dist/cjs/cli/commands/inspect.js +139 -36
  43. package/dist/cjs/cli/commands/migrate.js +5 -4
  44. package/dist/cjs/cli/commands/optimize.js +4 -4
  45. package/dist/cjs/cli/commands/status.js +9 -7
  46. package/dist/cjs/cli/commands/watch.js +7 -6
  47. package/dist/cjs/cli/index.js +2 -2
  48. package/dist/cjs/cli/ui/spinner.d.ts +15 -0
  49. package/dist/cjs/cli/ui/spinner.js +76 -0
  50. package/dist/cjs/dialect/database-introspector.js +3 -1
  51. package/dist/cjs/dialect/postgresql/postgresql-driver.js +3 -1
  52. package/dist/cjs/dialect/postgresql/postgresql-features.js +18 -8
  53. package/dist/cjs/dialect/postgresql/postgresql-introspector.js +2 -2
  54. package/dist/cjs/dialect/sqlite/sqlite-auto-indexer.js +47 -33
  55. package/dist/cjs/dialect/sqlite/sqlite-auto-optimizer.js +8 -7
  56. package/dist/cjs/dialect/sqlite/sqlite-driver.js +2 -2
  57. package/dist/cjs/dialect/sqlite/sqlite-introspector.js +15 -12
  58. package/dist/cjs/edge-runtime/edge-config.js +21 -19
  59. package/dist/cjs/errors/NoormError.js +22 -20
  60. package/dist/cjs/helpers/agent-schema.js +2 -0
  61. package/dist/cjs/helpers/postgresql.js +7 -4
  62. package/dist/cjs/helpers/schema-evolution.js +31 -6
  63. package/dist/cjs/index.d.ts +3 -3
  64. package/dist/cjs/logging/logger.js +8 -4
  65. package/dist/cjs/migration/data_migrator.js +12 -11
  66. package/dist/cjs/migration/database_migration_manager.js +17 -13
  67. package/dist/cjs/migration/schema_differ.js +22 -14
  68. package/dist/cjs/migration/schema_introspector.js +8 -8
  69. package/dist/cjs/migration/type_mapper.js +68 -67
  70. package/dist/cjs/noormme.js +52 -37
  71. package/dist/cjs/performance/index.js +5 -5
  72. package/dist/cjs/performance/query-optimizer.js +26 -21
  73. package/dist/cjs/performance/services/cache-service.js +26 -16
  74. package/dist/cjs/performance/services/connection-factory.js +28 -23
  75. package/dist/cjs/performance/services/metrics-collector.js +41 -36
  76. package/dist/cjs/performance/utils/query-parser.js +15 -16
  77. package/dist/cjs/relationships/relationship-engine.js +10 -8
  78. package/dist/cjs/repository/repository-factory.js +97 -38
  79. package/dist/cjs/schema/core/coordinators/schema-discovery.coordinator.js +1 -3
  80. package/dist/cjs/schema/core/discovery/relationship-discovery.js +16 -16
  81. package/dist/cjs/schema/core/discovery/table-metadata-discovery.js +9 -9
  82. package/dist/cjs/schema/core/discovery/view-discovery.js +5 -4
  83. package/dist/cjs/schema/core/factories/discovery-factory.js +4 -4
  84. package/dist/cjs/schema/core/utils/name-generator.js +14 -5
  85. package/dist/cjs/schema/core/utils/type-mapper.js +24 -24
  86. package/dist/cjs/schema/dialects/postgresql/postgresql-discovery.coordinator.js +8 -7
  87. package/dist/cjs/schema/dialects/sqlite/discovery/sqlite-constraint-discovery.js +17 -15
  88. package/dist/cjs/schema/dialects/sqlite/discovery/sqlite-index-discovery.js +8 -8
  89. package/dist/cjs/schema/dialects/sqlite/introspection/sqlite-schema-introspector.js +6 -11
  90. package/dist/cjs/schema/dialects/sqlite/sqlite-discovery.coordinator.js +14 -13
  91. package/dist/cjs/schema/test/basic-schema-test.js +11 -9
  92. package/dist/cjs/schema/test/dialect-capabilities.test.js +6 -6
  93. package/dist/cjs/schema/test/discovery-factory.test.js +2 -2
  94. package/dist/cjs/schema/test/error-handling.test.js +8 -6
  95. package/dist/cjs/schema/test/integration.test.js +24 -18
  96. package/dist/cjs/schema/test/schema-discovery-coordinator.test.js +9 -9
  97. package/dist/cjs/schema/test/simple-schema-test.js +9 -9
  98. package/dist/cjs/schema/test/sqlite-discovery-coordinator.test.js +64 -48
  99. package/dist/cjs/schema/test/test-runner.js +3 -3
  100. package/dist/cjs/sqlite-migration/index.d.ts +2 -2
  101. package/dist/cjs/sqlite-migration/sqlite-migration-manager.js +21 -17
  102. package/dist/cjs/sqlite-migration/sqlite-migration-provider.js +38 -34
  103. package/dist/cjs/testing/test-utils.js +36 -34
  104. package/dist/cjs/types/index.d.ts +5 -2
  105. package/dist/cjs/types/index.js +6 -3
  106. package/dist/cjs/types/type-generator.js +46 -42
  107. package/dist/cjs/util/safe-sql-helpers.js +1 -1
  108. package/dist/cjs/util/security-validator.js +20 -9
  109. package/dist/cjs/utils/errorHelpers.js +20 -10
  110. package/dist/cjs/watch/schema-watcher.js +22 -23
  111. package/dist/esm/agentic/ActionJournal.js +13 -9
  112. package/dist/esm/agentic/CapabilityManager.js +35 -21
  113. package/dist/esm/agentic/CognitiveRepository.js +19 -9
  114. package/dist/esm/agentic/ContextBuffer.js +24 -12
  115. package/dist/esm/agentic/Cortex.js +11 -4
  116. package/dist/esm/agentic/EpisodicMemory.js +7 -5
  117. package/dist/esm/agentic/PersonaManager.js +16 -8
  118. package/dist/esm/agentic/PolicyEnforcer.js +31 -12
  119. package/dist/esm/agentic/ResourceMonitor.js +4 -4
  120. package/dist/esm/agentic/SessionCompressor.js +22 -14
  121. package/dist/esm/agentic/SessionManager.js +36 -18
  122. package/dist/esm/agentic/VectorIndexer.js +22 -18
  123. package/dist/esm/agentic/improvement/AblationEngine.js +22 -15
  124. package/dist/esm/agentic/improvement/ActionRefiner.js +12 -10
  125. package/dist/esm/agentic/improvement/ConflictResolver.js +5 -5
  126. package/dist/esm/agentic/improvement/CortexJanitor.js +30 -9
  127. package/dist/esm/agentic/improvement/CuriosityEngine.js +27 -23
  128. package/dist/esm/agentic/improvement/EvolutionRitual.js +4 -4
  129. package/dist/esm/agentic/improvement/EvolutionaryPilot.js +16 -6
  130. package/dist/esm/agentic/improvement/GoalArchitect.d.ts +2 -2
  131. package/dist/esm/agentic/improvement/GoalArchitect.js +20 -18
  132. package/dist/esm/agentic/improvement/GovernanceManager.js +19 -11
  133. package/dist/esm/agentic/improvement/HiveLink.js +22 -15
  134. package/dist/esm/agentic/improvement/KnowledgeDistiller.js +48 -32
  135. package/dist/esm/agentic/improvement/RecursiveReasoner.js +40 -17
  136. package/dist/esm/agentic/improvement/ReflectionEngine.js +10 -8
  137. package/dist/esm/agentic/improvement/RitualOrchestrator.js +28 -22
  138. package/dist/esm/agentic/improvement/RuleEngine.js +22 -17
  139. package/dist/esm/agentic/improvement/SelfEvolution.js +24 -18
  140. package/dist/esm/agentic/improvement/SelfTestRegistry.js +18 -15
  141. package/dist/esm/agentic/improvement/SkillSynthesizer.js +42 -27
  142. package/dist/esm/agentic/improvement/SovereignMetrics.js +19 -17
  143. package/dist/esm/agentic/improvement/StrategicPlanner.js +120 -55
  144. package/dist/esm/agentic/telemetry/CognitiveSynthesizer.js +26 -12
  145. package/dist/esm/agentic/telemetry/EventHarvester.js +3 -2
  146. package/dist/esm/agentic/telemetry/ResearchAlchemist.js +5 -2
  147. package/dist/esm/cache/cache-manager.js +7 -4
  148. package/dist/esm/cli/commands/analyze.js +5 -4
  149. package/dist/esm/cli/commands/generate.js +82 -45
  150. package/dist/esm/cli/commands/init.js +8 -4
  151. package/dist/esm/cli/commands/inspect.js +140 -37
  152. package/dist/esm/cli/commands/migrate.js +5 -4
  153. package/dist/esm/cli/commands/optimize.js +4 -4
  154. package/dist/esm/cli/commands/status.js +9 -7
  155. package/dist/esm/cli/commands/watch.js +7 -6
  156. package/dist/esm/cli/index.js +2 -2
  157. package/dist/esm/cli/ui/spinner.d.ts +15 -0
  158. package/dist/esm/cli/ui/spinner.js +70 -0
  159. package/dist/esm/dialect/database-introspector.js +3 -1
  160. package/dist/esm/dialect/postgresql/postgresql-driver.js +3 -1
  161. package/dist/esm/dialect/postgresql/postgresql-features.js +18 -8
  162. package/dist/esm/dialect/postgresql/postgresql-introspector.js +2 -2
  163. package/dist/esm/dialect/sqlite/sqlite-auto-indexer.js +47 -33
  164. package/dist/esm/dialect/sqlite/sqlite-auto-optimizer.js +8 -7
  165. package/dist/esm/dialect/sqlite/sqlite-driver.js +2 -2
  166. package/dist/esm/dialect/sqlite/sqlite-introspector.js +15 -12
  167. package/dist/esm/dynamic/dynamic.js +1 -1
  168. package/dist/esm/edge-runtime/edge-config.js +21 -19
  169. package/dist/esm/errors/NoormError.js +22 -20
  170. package/dist/esm/helpers/agent-schema.js +2 -0
  171. package/dist/esm/helpers/postgresql.js +7 -4
  172. package/dist/esm/helpers/schema-evolution.js +31 -6
  173. package/dist/esm/index.d.ts +3 -3
  174. package/dist/esm/index.js +2 -2
  175. package/dist/esm/logging/logger.js +8 -4
  176. package/dist/esm/migration/data_migrator.js +12 -11
  177. package/dist/esm/migration/database_migration_manager.js +18 -14
  178. package/dist/esm/migration/schema_differ.js +22 -14
  179. package/dist/esm/migration/schema_introspector.js +8 -8
  180. package/dist/esm/migration/type_mapper.js +68 -67
  181. package/dist/esm/noormme.js +52 -37
  182. package/dist/esm/performance/index.js +5 -5
  183. package/dist/esm/performance/query-optimizer.js +26 -21
  184. package/dist/esm/performance/services/cache-service.js +26 -16
  185. package/dist/esm/performance/services/connection-factory.js +28 -23
  186. package/dist/esm/performance/services/metrics-collector.js +41 -36
  187. package/dist/esm/performance/utils/query-parser.js +15 -16
  188. package/dist/esm/raw-builder/sql.js +1 -1
  189. package/dist/esm/relationships/relationship-engine.js +10 -8
  190. package/dist/esm/repository/repository-factory.js +98 -39
  191. package/dist/esm/schema/builders/alter-table-add-index-builder.js +1 -1
  192. package/dist/esm/schema/builders/create-index-builder.js +2 -2
  193. package/dist/esm/schema/core/coordinators/schema-discovery.coordinator.js +1 -3
  194. package/dist/esm/schema/core/discovery/relationship-discovery.js +16 -16
  195. package/dist/esm/schema/core/discovery/table-metadata-discovery.js +9 -9
  196. package/dist/esm/schema/core/discovery/view-discovery.js +5 -4
  197. package/dist/esm/schema/core/factories/discovery-factory.js +4 -4
  198. package/dist/esm/schema/core/utils/name-generator.js +14 -5
  199. package/dist/esm/schema/core/utils/type-mapper.js +24 -24
  200. package/dist/esm/schema/dialects/postgresql/postgresql-discovery.coordinator.js +8 -7
  201. package/dist/esm/schema/dialects/sqlite/discovery/sqlite-constraint-discovery.js +17 -15
  202. package/dist/esm/schema/dialects/sqlite/discovery/sqlite-index-discovery.js +8 -8
  203. package/dist/esm/schema/dialects/sqlite/introspection/sqlite-schema-introspector.js +6 -11
  204. package/dist/esm/schema/dialects/sqlite/sqlite-discovery.coordinator.js +14 -13
  205. package/dist/esm/schema/test/basic-schema-test.js +11 -9
  206. package/dist/esm/schema/test/dialect-capabilities.test.js +6 -6
  207. package/dist/esm/schema/test/discovery-factory.test.js +2 -2
  208. package/dist/esm/schema/test/error-handling.test.js +8 -6
  209. package/dist/esm/schema/test/integration.test.js +24 -18
  210. package/dist/esm/schema/test/schema-discovery-coordinator.test.js +9 -9
  211. package/dist/esm/schema/test/simple-schema-test.js +9 -9
  212. package/dist/esm/schema/test/sqlite-discovery-coordinator.test.js +64 -48
  213. package/dist/esm/schema/test/test-runner.js +3 -3
  214. package/dist/esm/sqlite-migration/index.d.ts +2 -2
  215. package/dist/esm/sqlite-migration/sqlite-migration-manager.js +21 -17
  216. package/dist/esm/sqlite-migration/sqlite-migration-provider.js +38 -34
  217. package/dist/esm/testing/test-utils.js +36 -34
  218. package/dist/esm/types/index.d.ts +5 -2
  219. package/dist/esm/types/index.js +6 -3
  220. package/dist/esm/types/type-generator.js +46 -42
  221. package/dist/esm/util/safe-sql-helpers.js +1 -1
  222. package/dist/esm/util/security-validator.js +20 -9
  223. package/dist/esm/utils/errorHelpers.js +21 -11
  224. package/dist/esm/watch/schema-watcher.js +22 -23
  225. package/package.json +40 -44
@@ -22,13 +22,15 @@ class ActionRefiner {
22
22
  async refineActions() {
23
23
  const recommendations = [];
24
24
  // 1. Find tools with high failure rates
25
- const failureStats = await this.db
25
+ const failureStats = (await this.db
26
26
  .selectFrom(this.actionsTable)
27
27
  .select('tool_name')
28
28
  .select((eb) => eb.fn.count('id').as('total'))
29
- .select((eb) => eb.fn.sum(eb.case().when('status', '=', 'failure').then(1).else(0).end()).as('failures'))
29
+ .select((eb) => eb.fn
30
+ .sum(eb.case().when('status', '=', 'failure').then(1).else(0).end())
31
+ .as('failures'))
30
32
  .groupBy('tool_name')
31
- .execute();
33
+ .execute());
32
34
  for (const stat of failureStats) {
33
35
  const failures = Number(stat.failures || 0);
34
36
  const total = Number(stat.total || 1);
@@ -40,7 +42,7 @@ class ActionRefiner {
40
42
  }
41
43
  }
42
44
  // 2. Discover missing capabilities based on error patterns
43
- const missingCapabilities = await this.db
45
+ const missingCapabilities = (await this.db
44
46
  .selectFrom(this.actionsTable)
45
47
  .select('tool_name')
46
48
  .where('status', '=', 'failure')
@@ -48,10 +50,10 @@ class ActionRefiner {
48
50
  eb('error', 'like', '%permission denied%'),
49
51
  eb('error', 'like', '%unknown tool%'),
50
52
  eb('error', 'like', '%missing capability%'),
51
- eb('error', 'like', '%not authorized%')
53
+ eb('error', 'like', '%not authorized%'),
52
54
  ]))
53
55
  .groupBy('tool_name')
54
- .execute();
56
+ .execute());
55
57
  for (const row of missingCapabilities) {
56
58
  recommendations.push(`Detected repeated access/existence failures for tool '${row.tool_name}'. Proposing capability expansion.`);
57
59
  await this.proposeCapabilityUpdate(row.tool_name);
@@ -63,14 +65,14 @@ class ActionRefiner {
63
65
  */
64
66
  async proposeReflectionRule(toolName) {
65
67
  const existing = await this.cortex.rules.getActiveRules('agent_actions', 'insert');
66
- const hasRule = existing.some(r => r.metadata?.targetTool === toolName);
68
+ const hasRule = existing.some((r) => r.metadata?.targetTool === toolName);
67
69
  if (!hasRule) {
68
70
  console.log(`[ActionRefiner] Proposing reflection rule for tool: ${toolName}`);
69
71
  await this.cortex.rules.defineRule('agent_actions', 'insert', 'audit', {
70
72
  metadata: {
71
73
  targetTool: toolName,
72
- reason: 'High failure rate detected by ActionRefiner'
73
- }
74
+ reason: 'High failure rate detected by ActionRefiner',
75
+ },
74
76
  });
75
77
  }
76
78
  }
@@ -81,7 +83,7 @@ class ActionRefiner {
81
83
  console.log(`[ActionRefiner] Proposing capability expansion for tool: ${toolName}`);
82
84
  await this.cortex.reflections.reflect('system', 'failure', `Architectural Gap: Missing Capability for '${toolName}'`, [
83
85
  `Identified repeated failures using tool '${toolName}'.`,
84
- `Resolution: Inspect permission sets and ensure the tool is correctly registered in the CapabilityManager.`
86
+ `Resolution: Inspect permission sets and ensure the tool is correctly registered in the CapabilityManager.`,
85
87
  ]);
86
88
  }
87
89
  }
@@ -20,11 +20,11 @@ class ConflictResolver {
20
20
  */
21
21
  async auditRuleConflicts() {
22
22
  console.log('[ConflictResolver] Auditing cognitive rules for conflicts and overlaps...');
23
- const rules = await this.db
23
+ const rules = (await this.db
24
24
  .selectFrom(this.rulesTable)
25
25
  .selectAll()
26
26
  .where('is_enabled', '=', true)
27
- .execute();
27
+ .execute());
28
28
  const conflicts = [];
29
29
  // 1. Direct Conflicts: Same Table + Same Operation
30
30
  const seen = new Map();
@@ -75,18 +75,18 @@ class ConflictResolver {
75
75
  */
76
76
  async resolveConflict(tableName, operation) {
77
77
  console.log(`[ConflictResolver] Resolving conflict for ${tableName}:${operation}`);
78
- const rules = await this.db
78
+ const rules = (await this.db
79
79
  .selectFrom(this.rulesTable)
80
80
  .selectAll()
81
81
  .where('table_name', '=', tableName)
82
82
  .where('operation', '=', operation)
83
83
  .where('is_enabled', '=', true)
84
84
  .orderBy('created_at', 'desc')
85
- .execute();
85
+ .execute());
86
86
  if (rules.length <= 1)
87
87
  return;
88
88
  // Keep the first (newest) one, disable the rest
89
- const toDisable = rules.slice(1).map(r => r.id);
89
+ const toDisable = rules.slice(1).map((r) => r.id);
90
90
  await this.db
91
91
  .updateTable(this.rulesTable)
92
92
  .set({ is_enabled: false })
@@ -45,7 +45,10 @@ class CortexJanitor {
45
45
  .executeTakeFirst();
46
46
  const deletedCount = Number(result.numDeletedRows || 0);
47
47
  if (deletedCount > 0) {
48
- await this.logRitual('optimization', 'success', { action: 'clean_orphans', deletedCount });
48
+ await this.logRitual('optimization', 'success', {
49
+ action: 'clean_orphans',
50
+ deletedCount,
51
+ });
49
52
  }
50
53
  return deletedCount;
51
54
  }
@@ -62,7 +65,10 @@ class CortexJanitor {
62
65
  .executeTakeFirst();
63
66
  const count = Number(result.numUpdatedRows || 0);
64
67
  if (count > 0) {
65
- await this.logRitual('optimization', 'success', { action: 'archive_sessions', count });
68
+ await this.logRitual('optimization', 'success', {
69
+ action: 'archive_sessions',
70
+ count,
71
+ });
66
72
  }
67
73
  return count;
68
74
  }
@@ -77,7 +83,10 @@ class CortexJanitor {
77
83
  .executeTakeFirst();
78
84
  const count = Number(result.numDeletedRows || 0);
79
85
  if (count > 0) {
80
- await this.logRitual('pruning', 'success', { action: 'prune_metrics', count });
86
+ await this.logRitual('pruning', 'success', {
87
+ action: 'prune_metrics',
88
+ count,
89
+ });
81
90
  }
82
91
  return count;
83
92
  }
@@ -92,7 +101,10 @@ class CortexJanitor {
92
101
  const coreIdentityTables = [
93
102
  { table: this.knowledgeTable, col: 'entity' },
94
103
  { table: this.config.memoriesTable || 'agent_memories', col: 'entity' },
95
- { table: this.config.messagesTable || 'agent_messages', col: 'session_id' }
104
+ {
105
+ table: this.config.messagesTable || 'agent_messages',
106
+ col: 'session_id',
107
+ },
96
108
  ];
97
109
  for (const target of coreIdentityTables) {
98
110
  try {
@@ -116,11 +128,15 @@ class CortexJanitor {
116
128
  const tablesToRemoveFriction = new Set();
117
129
  for (const q of slowQueries) {
118
130
  try {
119
- const meta = typeof q.metadata === 'string' ? JSON.parse(q.metadata) : (q.metadata || {});
131
+ const meta = typeof q.metadata === 'string'
132
+ ? JSON.parse(q.metadata)
133
+ : q.metadata || {};
120
134
  if (meta.table)
121
135
  tablesToRemoveFriction.add(meta.table);
122
136
  }
123
- catch (e) { /* ignore */ }
137
+ catch (e) {
138
+ /* ignore */
139
+ }
124
140
  }
125
141
  for (const table of tablesToRemoveFriction) {
126
142
  // Hotspot logic: if it's high-traffic knowledge, index the status/confidence pair for promoting/demoting
@@ -131,7 +147,10 @@ class CortexJanitor {
131
147
  }
132
148
  }
133
149
  if (applied.length > 0) {
134
- await this.logRitual('optimization', 'success', { action: 'autonomous_indexing', applied_count: applied.length });
150
+ await this.logRitual('optimization', 'success', {
151
+ action: 'autonomous_indexing',
152
+ applied_count: applied.length,
153
+ });
135
154
  }
136
155
  return applied;
137
156
  }
@@ -149,7 +168,9 @@ class CortexJanitor {
149
168
  else if (dialect.includes('postgres')) {
150
169
  await (0, sql_js_1.sql) `ANALYZE`.execute(this.db);
151
170
  }
152
- await this.logRitual('optimization', 'success', { action: 'db_maintenance' });
171
+ await this.logRitual('optimization', 'success', {
172
+ action: 'db_maintenance',
173
+ });
153
174
  }
154
175
  async logRitual(type, status, metadata) {
155
176
  try {
@@ -160,7 +181,7 @@ class CortexJanitor {
160
181
  type,
161
182
  status,
162
183
  last_run: new Date(),
163
- metadata: metadata ? JSON.stringify(metadata) : null
184
+ metadata: metadata ? JSON.stringify(metadata) : null,
164
185
  })
165
186
  .execute();
166
187
  }
@@ -26,15 +26,15 @@ class CuriosityEngine {
26
26
  console.log('[CuriosityEngine] Analyzing knowledge base for gaps and contradictions...');
27
27
  const gaps = [];
28
28
  // 1. Find entities with low confidence or unverified/proposed status
29
- const weakKnowledge = await this.typedDb
29
+ const weakKnowledge = (await this.typedDb
30
30
  .selectFrom(this.knowledgeTable)
31
31
  .selectAll()
32
32
  .where((eb) => eb.or([
33
33
  eb('confidence', '<', 0.4), // Critical low confidence
34
34
  eb('status', '=', 'proposed'), // Not yet verified by enough sessions
35
- eb('status', '=', 'disputed') // Flagged by contradiction logic
35
+ eb('status', '=', 'disputed'), // Flagged by contradiction logic
36
36
  ]))
37
- .execute();
37
+ .execute());
38
38
  for (const item of weakKnowledge) {
39
39
  let type = 'unverified';
40
40
  if (item.confidence < 0.4)
@@ -44,7 +44,7 @@ class CuriosityEngine {
44
44
  gaps.push({
45
45
  entity: item.entity,
46
46
  type,
47
- details: `Fact "${item.fact}" is ${type} (Status: ${item.status}, Confidence: ${item.confidence}).`
47
+ details: `Fact "${item.fact}" is ${type} (Status: ${item.status}, Confidence: ${item.confidence}).`,
48
48
  });
49
49
  }
50
50
  // 2. Detect Contradictions: Same entity, multiple facts with high overlap but different claims
@@ -55,12 +55,12 @@ class CuriosityEngine {
55
55
  .having((eb) => eb.fn.count('id'), '>', 1)
56
56
  .execute();
57
57
  for (const row of entities) {
58
- const items = await this.typedDb
58
+ const items = (await this.typedDb
59
59
  .selectFrom(this.knowledgeTable)
60
60
  .selectAll()
61
61
  .where('entity', '=', row.entity)
62
62
  .where('confidence', '>', 0.5)
63
- .execute();
63
+ .execute());
64
64
  if (items.length > 1) {
65
65
  for (let i = 0; i < items.length; i++) {
66
66
  for (let j = i + 1; j < items.length; j++) {
@@ -70,7 +70,7 @@ class CuriosityEngine {
70
70
  gaps.push({
71
71
  entity: row.entity,
72
72
  type: 'contradiction',
73
- details: `Subtle contradiction: "${items[i].fact}" vs "${items[j].fact}" (Similarity: ${(similarity * 100).toFixed(1)}%)`
73
+ details: `Subtle contradiction: "${items[i].fact}" vs "${items[j].fact}" (Similarity: ${(similarity * 100).toFixed(1)}%)`,
74
74
  });
75
75
  }
76
76
  }
@@ -87,14 +87,17 @@ class CuriosityEngine {
87
87
  async identifyKnowledgeHotspots() {
88
88
  const metricsTable = this.config.metricsTable || 'agent_metrics';
89
89
  // 1. Find entities with high hit counts in recent metrics
90
- const topEntities = await this.db
90
+ const topEntities = (await this.db
91
91
  .selectFrom(metricsTable)
92
- .select(['metric_name as entity', (eb) => eb.fn.sum('metric_value').as('references')])
92
+ .select([
93
+ 'metric_name as entity',
94
+ (eb) => eb.fn.sum('metric_value').as('references'),
95
+ ])
93
96
  .where('metric_name', 'like', 'entity_hit_%')
94
97
  .groupBy('metric_name')
95
98
  .orderBy((eb) => eb.fn.sum('metric_value'), 'desc')
96
99
  .limit(10)
97
- .execute();
100
+ .execute());
98
101
  const hotspots = [];
99
102
  for (const top of topEntities) {
100
103
  const entityName = top.entity.replace('entity_hit_', '');
@@ -113,7 +116,7 @@ class CuriosityEngine {
113
116
  entity: entityName,
114
117
  references: refs,
115
118
  density: Number(density.toFixed(2)),
116
- gap: `High cognitive overhead (${refs} refs) vs low factual density (${factCount} facts).`
119
+ gap: `High cognitive overhead (${refs} refs) vs low factual density (${factCount} facts).`,
117
120
  });
118
121
  }
119
122
  }
@@ -132,21 +135,21 @@ class CuriosityEngine {
132
135
  return [
133
136
  `What are the core attributes and defining characteristics of ${entity}?`,
134
137
  `How does ${entity} relate to the broader system architecture?`,
135
- `What are the primary use cases for ${entity} in the current context?`
138
+ `What are the primary use cases for ${entity} in the current context?`,
136
139
  ];
137
140
  }
138
141
  const questions = [];
139
- const facts = knowledge.map(k => k.fact);
142
+ const facts = knowledge.map((k) => k.fact);
140
143
  // Context-aware questions
141
144
  questions.push(`Can we find more supporting evidence for: "${facts[0]}"?`);
142
- const lowConfidenceItems = knowledge.filter(k => k.confidence < 0.6);
145
+ const lowConfidenceItems = knowledge.filter((k) => k.confidence < 0.6);
143
146
  if (lowConfidenceItems.length > 0) {
144
147
  questions.push(`Verify the accuracy of recent claims about ${entity}, specifically regarding "${lowConfidenceItems[0].fact}".`);
145
148
  }
146
149
  // Use tags to generate specific questions
147
150
  const allTags = new Set();
148
- knowledge.forEach(k => {
149
- const tags = typeof k.tags === 'string' ? JSON.parse(k.tags) : (k.tags || []);
151
+ knowledge.forEach((k) => {
152
+ const tags = typeof k.tags === 'string' ? JSON.parse(k.tags) : k.tags || [];
150
153
  tags.forEach((t) => allTags.add(t));
151
154
  });
152
155
  if (allTags.has('database')) {
@@ -171,16 +174,16 @@ class CuriosityEngine {
171
174
  async generateHypotheses() {
172
175
  console.log('[CuriosityEngine] Generating relationship hypotheses...');
173
176
  // 1. Get high-confidence entities
174
- const entities = await this.typedDb
177
+ const entities = (await this.typedDb
175
178
  .selectFrom(this.knowledgeTable)
176
179
  .select(['entity', 'tags'])
177
180
  .where('confidence', '>', 0.7)
178
181
  .where('tags', 'is not', null)
179
- .execute();
182
+ .execute());
180
183
  const hypotheses = [];
181
184
  const entityTagsMap = new Map();
182
185
  for (const row of entities) {
183
- const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : (row.tags || []);
186
+ const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags || [];
184
187
  if (tags.length > 0) {
185
188
  entityTagsMap.set(row.entity, new Set(tags));
186
189
  }
@@ -192,11 +195,12 @@ class CuriosityEngine {
192
195
  const tagsI = entityTagsMap.get(entityNames[i]);
193
196
  const tagsJ = entityTagsMap.get(entityNames[j]);
194
197
  // intersection
195
- const commonTags = [...tagsI].filter(t => tagsJ.has(t));
198
+ const commonTags = [...tagsI].filter((t) => tagsJ.has(t));
196
199
  if (commonTags.length >= 2) {
197
200
  hypotheses.push(`[HYPOTHESIS] "${entityNames[i]}" and "${entityNames[j]}" share a dense tag set (${commonTags.join(', ')}). Is there a structural coupling?`);
198
201
  }
199
- else if (commonTags.length === 1 && (tagsI.size === 1 || tagsJ.size === 1)) {
202
+ else if (commonTags.length === 1 &&
203
+ (tagsI.size === 1 || tagsJ.size === 1)) {
200
204
  // Specific probe for shared lone-tags
201
205
  hypotheses.push(`[HYPOTHESIS] Both "${entityNames[i]}" and "${entityNames[j]}" are uniquely identified by "${commonTags[0]}". Might be aliases or sub-components.`);
202
206
  }
@@ -222,12 +226,12 @@ class CuriosityEngine {
222
226
  proposals.push(hypo);
223
227
  }
224
228
  // Production Hardening: Check for evolutionary density to suggest publication
225
- const evolutionCountResult = await this.db
229
+ const evolutionCountResult = (await this.db
226
230
  .selectFrom(this.config.metricsTable || 'agent_metrics')
227
231
  .select((eb) => eb.fn.count('id').as('count'))
228
232
  .where('metric_name', '=', 'evolution_applied')
229
233
  .where('created_at', '>', new Date(Date.now() - 7 * 24 * 3600000)) // Last 7 days
230
- .executeTakeFirst();
234
+ .executeTakeFirst());
231
235
  const evolutions = Number(evolutionCountResult?.count || 0);
232
236
  if (evolutions > 5) {
233
237
  proposals.push(`[SOVEREIGN RITUAL] The engine has undergone ${evolutions} structural evolutions this week. Consider a 'Sovereign Publication Ritual' to update the registry.`);
@@ -23,7 +23,7 @@ class EvolutionRitual {
23
23
  const results = {
24
24
  synthesized: 0,
25
25
  broadcasted: 0,
26
- domainsSynced: []
26
+ domainsSynced: [],
27
27
  };
28
28
  // 1. Parallel Synthesis: Identify and bridge capability gaps
29
29
  const newSkills = await this.cortex.skillSynthesizer.discoverAndSynthesize();
@@ -49,11 +49,11 @@ class EvolutionRitual {
49
49
  return results;
50
50
  }
51
51
  async checkDomainMaturity(domain) {
52
- const skills = await this.db
52
+ const skills = (await this.db
53
53
  .selectFrom(this.config.capabilitiesTable || 'agent_capabilities')
54
54
  .select(['reliability'])
55
55
  .where('name', 'like', `${domain}%`)
56
- .execute();
56
+ .execute());
57
57
  if (skills.length < 3)
58
58
  return false; // Need a minimum population for maturity
59
59
  const avgReliability = skills.reduce((sum, s) => sum + s.reliability, 0) / skills.length;
@@ -70,7 +70,7 @@ class EvolutionRitual {
70
70
  .execute();
71
71
  const domainScores = new Map();
72
72
  for (const row of result) {
73
- const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : (row.tags || []);
73
+ const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags || [];
74
74
  for (const t of tags) {
75
75
  if (t === 'hive_mind')
76
76
  continue;
@@ -23,25 +23,32 @@ class EvolutionaryPilot {
23
23
  const changes = [];
24
24
  let evolved = false;
25
25
  // 1. Full-Spectrum Observation
26
- const metrics = ['query_latency', 'success_rate', 'total_cost', 'trust_signal'];
26
+ const metrics = [
27
+ 'query_latency',
28
+ 'success_rate',
29
+ 'total_cost',
30
+ 'trust_signal',
31
+ ];
27
32
  const recentMetrics = await this.cortex.metrics.getRecentMetrics(100);
28
33
  for (const metricName of metrics) {
29
34
  const values = recentMetrics
30
- .filter(m => m.metricName === metricName)
31
- .map(m => Number(m.metricValue));
35
+ .filter((m) => m.metricName === metricName)
36
+ .map((m) => Number(m.metricValue));
32
37
  if (values.length < 5)
33
38
  continue;
34
39
  const stats = this.calculateZScore(values);
35
40
  console.log(`[EvolutionaryPilot] Baselining ${metricName}: Mean=${stats.mean.toFixed(2)}, StdDev=${stats.stdDev.toFixed(2)}, Current=${stats.current.toFixed(2)}, Z-Score=${stats.zScore.toFixed(2)}`);
36
41
  // 2. Trigger Evolution based on metric-specific thresholds
37
- if (metricName === 'query_latency' && (stats.zScore > 2.0 || stats.mean > 1000)) {
42
+ if (metricName === 'query_latency' &&
43
+ (stats.zScore > 2.0 || stats.mean > 1000)) {
38
44
  const result = await this.optimizeLatency();
39
45
  if (result) {
40
46
  changes.push(...result);
41
47
  evolved = true;
42
48
  }
43
49
  }
44
- if (metricName === 'success_rate' && (stats.zScore < -1.5 || stats.mean < 0.7)) {
50
+ if (metricName === 'success_rate' &&
51
+ (stats.zScore < -1.5 || stats.mean < 0.7)) {
45
52
  console.warn(`[EvolutionaryPilot] Success rate collapse detected (${stats.mean.toFixed(2)}). Triggering strategic mutation.`);
46
53
  const strategies = await this.cortex.strategy.mutateStrategy();
47
54
  changes.push(...strategies);
@@ -137,7 +144,10 @@ class EvolutionaryPilot {
137
144
  const changes = [];
138
145
  console.log(`[EvolutionaryPilot] Triggering latency optimization...`);
139
146
  const dialect = this.db.getExecutor().dialect;
140
- const isSqlite = this.db.getExecutor().adapter.constructor.name.toLowerCase().includes('sqlite') ||
147
+ const isSqlite = this.db
148
+ .getExecutor()
149
+ .adapter.constructor.name.toLowerCase()
150
+ .includes('sqlite') ||
141
151
  (dialect && dialect.constructor.name.toLowerCase().includes('sqlite'));
142
152
  if (isSqlite) {
143
153
  await (0, sql_js_1.sql) `PRAGMA optimize`.execute(this.db);
@@ -46,8 +46,8 @@ export declare class GoalArchitect {
46
46
  pendingSubGoals: number;
47
47
  }>;
48
48
  /**
49
- * Identify goals that have "stalled" (no status changes in > 7 days)
50
- */
49
+ * Identify goals that have "stalled" (no status changes in > 7 days)
50
+ */
51
51
  trackStalledGoals(daysThreshold?: number): Promise<AgentGoal[]>;
52
52
  private parseGoal;
53
53
  }
@@ -22,11 +22,11 @@ class GoalArchitect {
22
22
  */
23
23
  async deconstructGoal(goalId, subGoals) {
24
24
  return await this.db.transaction().execute(async (trx) => {
25
- const goal = await trx
25
+ const goal = (await trx
26
26
  .selectFrom(this.goalsTable)
27
27
  .selectAll()
28
28
  .where('id', '=', goalId)
29
- .executeTakeFirst();
29
+ .executeTakeFirst());
30
30
  if (!goal)
31
31
  throw new Error(`Goal ${goalId} not found`);
32
32
  console.log(`[GoalArchitect] Deconstructing goal ${goalId}: "${goal.description}" into ${subGoals.length} steps.`);
@@ -35,7 +35,7 @@ class GoalArchitect {
35
35
  const basePriority = (goal.priority || 0) + 1;
36
36
  for (let i = 0; i < subGoals.length; i++) {
37
37
  const desc = subGoals[i];
38
- const subGoal = await trx
38
+ const subGoal = (await trx
39
39
  .insertInto(this.goalsTable)
40
40
  .values({
41
41
  session_id: goal.session_id,
@@ -44,10 +44,10 @@ class GoalArchitect {
44
44
  status: 'pending',
45
45
  priority: basePriority + i, // Sequential priority
46
46
  created_at: new Date(),
47
- updated_at: new Date()
47
+ updated_at: new Date(),
48
48
  })
49
49
  .returningAll()
50
- .executeTakeFirstOrThrow();
50
+ .executeTakeFirstOrThrow());
51
51
  created.push(this.parseGoal(subGoal));
52
52
  }
53
53
  // Update parent status to in_progress if it was pending
@@ -91,18 +91,18 @@ class GoalArchitect {
91
91
  const newMeta = {
92
92
  ...currentMeta,
93
93
  lastStatusChange: Date.now(),
94
- outcome: outcome || currentMeta.outcome
94
+ outcome: outcome || currentMeta.outcome,
95
95
  };
96
- const updated = await this.db
96
+ const updated = (await this.db
97
97
  .updateTable(this.goalsTable)
98
98
  .set({
99
99
  status,
100
100
  metadata: JSON.stringify(newMeta),
101
- updated_at: new Date()
101
+ updated_at: new Date(),
102
102
  })
103
103
  .where('id', '=', goalId)
104
104
  .returningAll()
105
- .executeTakeFirstOrThrow();
105
+ .executeTakeFirstOrThrow());
106
106
  return this.parseGoal(updated);
107
107
  }
108
108
  /**
@@ -118,28 +118,28 @@ class GoalArchitect {
118
118
  if (subGoals.length === 0) {
119
119
  return { canComplete: true, pendingSubGoals: 0 };
120
120
  }
121
- const pending = subGoals.filter(g => g.status !== 'completed' && g.status !== 'failed').length;
121
+ const pending = subGoals.filter((g) => g.status !== 'completed' && g.status !== 'failed').length;
122
122
  return {
123
123
  canComplete: pending === 0,
124
- pendingSubGoals: pending
124
+ pendingSubGoals: pending,
125
125
  };
126
126
  }
127
127
  /**
128
- * Identify goals that have "stalled" (no status changes in > 7 days)
129
- */
128
+ * Identify goals that have "stalled" (no status changes in > 7 days)
129
+ */
130
130
  async trackStalledGoals(daysThreshold = 7) {
131
131
  console.log('[GoalArchitect] Identifying stalled objectives...');
132
132
  const thresholdDate = new Date(Date.now() - daysThreshold * 24 * 3600000);
133
- const stalled = await this.typedDb
133
+ const stalled = (await this.typedDb
134
134
  .selectFrom(this.goalsTable)
135
135
  .selectAll()
136
136
  .where('status', 'in', ['pending', 'in_progress'])
137
137
  .where('updated_at', '<', thresholdDate)
138
- .execute();
138
+ .execute());
139
139
  if (stalled.length > 0) {
140
140
  console.log(`[GoalArchitect] Identified ${stalled.length} stalled goals.`);
141
141
  }
142
- return stalled.map(g => this.parseGoal(g));
142
+ return stalled.map((g) => this.parseGoal(g));
143
143
  }
144
144
  parseGoal(g) {
145
145
  return {
@@ -149,9 +149,11 @@ class GoalArchitect {
149
149
  description: g.description,
150
150
  status: g.status,
151
151
  priority: g.priority,
152
- metadata: typeof g.metadata === 'string' ? JSON.parse(g.metadata) : (g.metadata || {}),
152
+ metadata: typeof g.metadata === 'string'
153
+ ? JSON.parse(g.metadata)
154
+ : g.metadata || {},
153
155
  createdAt: new Date(g.created_at),
154
- updatedAt: new Date(g.updated_at)
156
+ updatedAt: new Date(g.updated_at),
155
157
  };
156
158
  }
157
159
  }
@@ -26,16 +26,18 @@ class GovernanceManager {
26
26
  async performAudit() {
27
27
  const issues = [];
28
28
  // Fetch active policies
29
- const policies = await this.db
29
+ const policies = (await this.db
30
30
  .selectFrom(this.policiesTable)
31
31
  .selectAll()
32
32
  .where('is_enabled', '=', true)
33
- .execute();
33
+ .execute());
34
34
  const getPolicyValue = (name, type, fallback) => {
35
- const p = policies.find(p => p.name === name || p.type === type);
35
+ const p = policies.find((p) => p.name === name || p.type === type);
36
36
  if (!p)
37
37
  return fallback;
38
- const def = typeof p.definition === 'string' ? JSON.parse(p.definition) : p.definition;
38
+ const def = typeof p.definition === 'string'
39
+ ? JSON.parse(p.definition)
40
+ : p.definition;
39
41
  return def.threshold ?? fallback;
40
42
  };
41
43
  // 1. Budgetary Governance: Check for cost spikes in various windows
@@ -88,7 +90,7 @@ class GovernanceManager {
88
90
  console.warn(`[GovernanceManager] AUDIT FAILED [${new Date().toISOString()}]: ${issues.length} compliance issues detected.`);
89
91
  // Phase 1: Emergency Rollbacks
90
92
  const activePersona = await this.getActivePersona();
91
- if (activePersona && (success < 0.4 || hCost > (hourlyLimit * 1.5))) {
93
+ if (activePersona && (success < 0.4 || hCost > hourlyLimit * 1.5)) {
92
94
  console.error(`[GovernanceManager] CRITICAL THRESHOLD BREACH. Initiating emergency containment for persona ${activePersona.id}`);
93
95
  await this.cortex.strategy.rollbackPersona(activePersona.id);
94
96
  issues.push(`Containment: Emergency rollback triggered for persona ${activePersona.id}`);
@@ -100,7 +102,7 @@ class GovernanceManager {
100
102
  }
101
103
  return {
102
104
  healthy: issues.length === 0,
103
- issues
105
+ issues,
104
106
  };
105
107
  }
106
108
  /**
@@ -116,7 +118,9 @@ class GovernanceManager {
116
118
  return null;
117
119
  return {
118
120
  ...active,
119
- metadata: typeof active.metadata === 'string' ? JSON.parse(active.metadata) : (active.metadata || {})
121
+ metadata: typeof active.metadata === 'string'
122
+ ? JSON.parse(active.metadata)
123
+ : active.metadata || {},
120
124
  };
121
125
  }
122
126
  /**
@@ -165,11 +169,15 @@ class GovernanceManager {
165
169
  const slowTables = new Set();
166
170
  for (const q of recentSlowQueries) {
167
171
  try {
168
- const meta = typeof q.metadata === 'string' ? JSON.parse(q.metadata) : (q.metadata || {});
172
+ const meta = typeof q.metadata === 'string'
173
+ ? JSON.parse(q.metadata)
174
+ : q.metadata || {};
169
175
  if (meta.table)
170
176
  slowTables.add(meta.table);
171
177
  }
172
- catch (e) { /* ignore parse errors */ }
178
+ catch (e) {
179
+ /* ignore parse errors */
180
+ }
173
181
  }
174
182
  for (const table of slowTables) {
175
183
  repairs.push(`Table '${table}' is experiencing periodic latency spikes. Suggesting 'CREATE INDEX' for common filters.`);
@@ -182,11 +190,11 @@ class GovernanceManager {
182
190
  // 3. Check for cold storage candidates
183
191
  const sessionsTable = this.config.sessionsTable || 'agent_sessions';
184
192
  const oldThreshold = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); // 30 days
185
- const oldSessions = await this.db
193
+ const oldSessions = (await this.db
186
194
  .selectFrom(sessionsTable)
187
195
  .select((eb) => eb.fn.count('id').as('count'))
188
196
  .where('created_at', '<', oldThreshold)
189
- .executeTakeFirst();
197
+ .executeTakeFirst());
190
198
  if (Number(oldSessions?.count || 0) > 100) {
191
199
  repairs.push(`[STORAGE OPTIMIZATION] Found ${oldSessions.count} sessions older than 30 days. Consider moving to cold storage to reduce primary database size and improve backup speed.`);
192
200
  }