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
@@ -18,11 +18,11 @@ export class ConflictResolver {
18
18
  */
19
19
  async auditRuleConflicts() {
20
20
  console.log('[ConflictResolver] Auditing cognitive rules for conflicts and overlaps...');
21
- const rules = await this.db
21
+ const rules = (await this.db
22
22
  .selectFrom(this.rulesTable)
23
23
  .selectAll()
24
24
  .where('is_enabled', '=', true)
25
- .execute();
25
+ .execute());
26
26
  const conflicts = [];
27
27
  // 1. Direct Conflicts: Same Table + Same Operation
28
28
  const seen = new Map();
@@ -73,18 +73,18 @@ export class ConflictResolver {
73
73
  */
74
74
  async resolveConflict(tableName, operation) {
75
75
  console.log(`[ConflictResolver] Resolving conflict for ${tableName}:${operation}`);
76
- const rules = await this.db
76
+ const rules = (await this.db
77
77
  .selectFrom(this.rulesTable)
78
78
  .selectAll()
79
79
  .where('table_name', '=', tableName)
80
80
  .where('operation', '=', operation)
81
81
  .where('is_enabled', '=', true)
82
82
  .orderBy('created_at', 'desc')
83
- .execute();
83
+ .execute());
84
84
  if (rules.length <= 1)
85
85
  return;
86
86
  // Keep the first (newest) one, disable the rest
87
- const toDisable = rules.slice(1).map(r => r.id);
87
+ const toDisable = rules.slice(1).map((r) => r.id);
88
88
  await this.db
89
89
  .updateTable(this.rulesTable)
90
90
  .set({ is_enabled: false })
@@ -43,7 +43,10 @@ export class CortexJanitor {
43
43
  .executeTakeFirst();
44
44
  const deletedCount = Number(result.numDeletedRows || 0);
45
45
  if (deletedCount > 0) {
46
- await this.logRitual('optimization', 'success', { action: 'clean_orphans', deletedCount });
46
+ await this.logRitual('optimization', 'success', {
47
+ action: 'clean_orphans',
48
+ deletedCount,
49
+ });
47
50
  }
48
51
  return deletedCount;
49
52
  }
@@ -60,7 +63,10 @@ export class CortexJanitor {
60
63
  .executeTakeFirst();
61
64
  const count = Number(result.numUpdatedRows || 0);
62
65
  if (count > 0) {
63
- await this.logRitual('optimization', 'success', { action: 'archive_sessions', count });
66
+ await this.logRitual('optimization', 'success', {
67
+ action: 'archive_sessions',
68
+ count,
69
+ });
64
70
  }
65
71
  return count;
66
72
  }
@@ -75,7 +81,10 @@ export class CortexJanitor {
75
81
  .executeTakeFirst();
76
82
  const count = Number(result.numDeletedRows || 0);
77
83
  if (count > 0) {
78
- await this.logRitual('pruning', 'success', { action: 'prune_metrics', count });
84
+ await this.logRitual('pruning', 'success', {
85
+ action: 'prune_metrics',
86
+ count,
87
+ });
79
88
  }
80
89
  return count;
81
90
  }
@@ -90,7 +99,10 @@ export class CortexJanitor {
90
99
  const coreIdentityTables = [
91
100
  { table: this.knowledgeTable, col: 'entity' },
92
101
  { table: this.config.memoriesTable || 'agent_memories', col: 'entity' },
93
- { table: this.config.messagesTable || 'agent_messages', col: 'session_id' }
102
+ {
103
+ table: this.config.messagesTable || 'agent_messages',
104
+ col: 'session_id',
105
+ },
94
106
  ];
95
107
  for (const target of coreIdentityTables) {
96
108
  try {
@@ -114,11 +126,15 @@ export class CortexJanitor {
114
126
  const tablesToRemoveFriction = new Set();
115
127
  for (const q of slowQueries) {
116
128
  try {
117
- const meta = typeof q.metadata === 'string' ? JSON.parse(q.metadata) : (q.metadata || {});
129
+ const meta = typeof q.metadata === 'string'
130
+ ? JSON.parse(q.metadata)
131
+ : q.metadata || {};
118
132
  if (meta.table)
119
133
  tablesToRemoveFriction.add(meta.table);
120
134
  }
121
- catch (e) { /* ignore */ }
135
+ catch (e) {
136
+ /* ignore */
137
+ }
122
138
  }
123
139
  for (const table of tablesToRemoveFriction) {
124
140
  // Hotspot logic: if it's high-traffic knowledge, index the status/confidence pair for promoting/demoting
@@ -129,7 +145,10 @@ export class CortexJanitor {
129
145
  }
130
146
  }
131
147
  if (applied.length > 0) {
132
- await this.logRitual('optimization', 'success', { action: 'autonomous_indexing', applied_count: applied.length });
148
+ await this.logRitual('optimization', 'success', {
149
+ action: 'autonomous_indexing',
150
+ applied_count: applied.length,
151
+ });
133
152
  }
134
153
  return applied;
135
154
  }
@@ -147,7 +166,9 @@ export class CortexJanitor {
147
166
  else if (dialect.includes('postgres')) {
148
167
  await sql `ANALYZE`.execute(this.db);
149
168
  }
150
- await this.logRitual('optimization', 'success', { action: 'db_maintenance' });
169
+ await this.logRitual('optimization', 'success', {
170
+ action: 'db_maintenance',
171
+ });
151
172
  }
152
173
  async logRitual(type, status, metadata) {
153
174
  try {
@@ -158,7 +179,7 @@ export class CortexJanitor {
158
179
  type,
159
180
  status,
160
181
  last_run: new Date(),
161
- metadata: metadata ? JSON.stringify(metadata) : null
182
+ metadata: metadata ? JSON.stringify(metadata) : null,
162
183
  })
163
184
  .execute();
164
185
  }
@@ -24,15 +24,15 @@ export class CuriosityEngine {
24
24
  console.log('[CuriosityEngine] Analyzing knowledge base for gaps and contradictions...');
25
25
  const gaps = [];
26
26
  // 1. Find entities with low confidence or unverified/proposed status
27
- const weakKnowledge = await this.typedDb
27
+ const weakKnowledge = (await this.typedDb
28
28
  .selectFrom(this.knowledgeTable)
29
29
  .selectAll()
30
30
  .where((eb) => eb.or([
31
31
  eb('confidence', '<', 0.4), // Critical low confidence
32
32
  eb('status', '=', 'proposed'), // Not yet verified by enough sessions
33
- eb('status', '=', 'disputed') // Flagged by contradiction logic
33
+ eb('status', '=', 'disputed'), // Flagged by contradiction logic
34
34
  ]))
35
- .execute();
35
+ .execute());
36
36
  for (const item of weakKnowledge) {
37
37
  let type = 'unverified';
38
38
  if (item.confidence < 0.4)
@@ -42,7 +42,7 @@ export class CuriosityEngine {
42
42
  gaps.push({
43
43
  entity: item.entity,
44
44
  type,
45
- details: `Fact "${item.fact}" is ${type} (Status: ${item.status}, Confidence: ${item.confidence}).`
45
+ details: `Fact "${item.fact}" is ${type} (Status: ${item.status}, Confidence: ${item.confidence}).`,
46
46
  });
47
47
  }
48
48
  // 2. Detect Contradictions: Same entity, multiple facts with high overlap but different claims
@@ -53,12 +53,12 @@ export class CuriosityEngine {
53
53
  .having((eb) => eb.fn.count('id'), '>', 1)
54
54
  .execute();
55
55
  for (const row of entities) {
56
- const items = await this.typedDb
56
+ const items = (await this.typedDb
57
57
  .selectFrom(this.knowledgeTable)
58
58
  .selectAll()
59
59
  .where('entity', '=', row.entity)
60
60
  .where('confidence', '>', 0.5)
61
- .execute();
61
+ .execute());
62
62
  if (items.length > 1) {
63
63
  for (let i = 0; i < items.length; i++) {
64
64
  for (let j = i + 1; j < items.length; j++) {
@@ -68,7 +68,7 @@ export class CuriosityEngine {
68
68
  gaps.push({
69
69
  entity: row.entity,
70
70
  type: 'contradiction',
71
- details: `Subtle contradiction: "${items[i].fact}" vs "${items[j].fact}" (Similarity: ${(similarity * 100).toFixed(1)}%)`
71
+ details: `Subtle contradiction: "${items[i].fact}" vs "${items[j].fact}" (Similarity: ${(similarity * 100).toFixed(1)}%)`,
72
72
  });
73
73
  }
74
74
  }
@@ -85,14 +85,17 @@ export class CuriosityEngine {
85
85
  async identifyKnowledgeHotspots() {
86
86
  const metricsTable = this.config.metricsTable || 'agent_metrics';
87
87
  // 1. Find entities with high hit counts in recent metrics
88
- const topEntities = await this.db
88
+ const topEntities = (await this.db
89
89
  .selectFrom(metricsTable)
90
- .select(['metric_name as entity', (eb) => eb.fn.sum('metric_value').as('references')])
90
+ .select([
91
+ 'metric_name as entity',
92
+ (eb) => eb.fn.sum('metric_value').as('references'),
93
+ ])
91
94
  .where('metric_name', 'like', 'entity_hit_%')
92
95
  .groupBy('metric_name')
93
96
  .orderBy((eb) => eb.fn.sum('metric_value'), 'desc')
94
97
  .limit(10)
95
- .execute();
98
+ .execute());
96
99
  const hotspots = [];
97
100
  for (const top of topEntities) {
98
101
  const entityName = top.entity.replace('entity_hit_', '');
@@ -111,7 +114,7 @@ export class CuriosityEngine {
111
114
  entity: entityName,
112
115
  references: refs,
113
116
  density: Number(density.toFixed(2)),
114
- gap: `High cognitive overhead (${refs} refs) vs low factual density (${factCount} facts).`
117
+ gap: `High cognitive overhead (${refs} refs) vs low factual density (${factCount} facts).`,
115
118
  });
116
119
  }
117
120
  }
@@ -130,21 +133,21 @@ export class CuriosityEngine {
130
133
  return [
131
134
  `What are the core attributes and defining characteristics of ${entity}?`,
132
135
  `How does ${entity} relate to the broader system architecture?`,
133
- `What are the primary use cases for ${entity} in the current context?`
136
+ `What are the primary use cases for ${entity} in the current context?`,
134
137
  ];
135
138
  }
136
139
  const questions = [];
137
- const facts = knowledge.map(k => k.fact);
140
+ const facts = knowledge.map((k) => k.fact);
138
141
  // Context-aware questions
139
142
  questions.push(`Can we find more supporting evidence for: "${facts[0]}"?`);
140
- const lowConfidenceItems = knowledge.filter(k => k.confidence < 0.6);
143
+ const lowConfidenceItems = knowledge.filter((k) => k.confidence < 0.6);
141
144
  if (lowConfidenceItems.length > 0) {
142
145
  questions.push(`Verify the accuracy of recent claims about ${entity}, specifically regarding "${lowConfidenceItems[0].fact}".`);
143
146
  }
144
147
  // Use tags to generate specific questions
145
148
  const allTags = new Set();
146
- knowledge.forEach(k => {
147
- const tags = typeof k.tags === 'string' ? JSON.parse(k.tags) : (k.tags || []);
149
+ knowledge.forEach((k) => {
150
+ const tags = typeof k.tags === 'string' ? JSON.parse(k.tags) : k.tags || [];
148
151
  tags.forEach((t) => allTags.add(t));
149
152
  });
150
153
  if (allTags.has('database')) {
@@ -169,16 +172,16 @@ export class CuriosityEngine {
169
172
  async generateHypotheses() {
170
173
  console.log('[CuriosityEngine] Generating relationship hypotheses...');
171
174
  // 1. Get high-confidence entities
172
- const entities = await this.typedDb
175
+ const entities = (await this.typedDb
173
176
  .selectFrom(this.knowledgeTable)
174
177
  .select(['entity', 'tags'])
175
178
  .where('confidence', '>', 0.7)
176
179
  .where('tags', 'is not', null)
177
- .execute();
180
+ .execute());
178
181
  const hypotheses = [];
179
182
  const entityTagsMap = new Map();
180
183
  for (const row of entities) {
181
- const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : (row.tags || []);
184
+ const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags || [];
182
185
  if (tags.length > 0) {
183
186
  entityTagsMap.set(row.entity, new Set(tags));
184
187
  }
@@ -190,11 +193,12 @@ export class CuriosityEngine {
190
193
  const tagsI = entityTagsMap.get(entityNames[i]);
191
194
  const tagsJ = entityTagsMap.get(entityNames[j]);
192
195
  // intersection
193
- const commonTags = [...tagsI].filter(t => tagsJ.has(t));
196
+ const commonTags = [...tagsI].filter((t) => tagsJ.has(t));
194
197
  if (commonTags.length >= 2) {
195
198
  hypotheses.push(`[HYPOTHESIS] "${entityNames[i]}" and "${entityNames[j]}" share a dense tag set (${commonTags.join(', ')}). Is there a structural coupling?`);
196
199
  }
197
- else if (commonTags.length === 1 && (tagsI.size === 1 || tagsJ.size === 1)) {
200
+ else if (commonTags.length === 1 &&
201
+ (tagsI.size === 1 || tagsJ.size === 1)) {
198
202
  // Specific probe for shared lone-tags
199
203
  hypotheses.push(`[HYPOTHESIS] Both "${entityNames[i]}" and "${entityNames[j]}" are uniquely identified by "${commonTags[0]}". Might be aliases or sub-components.`);
200
204
  }
@@ -220,12 +224,12 @@ export class CuriosityEngine {
220
224
  proposals.push(hypo);
221
225
  }
222
226
  // Production Hardening: Check for evolutionary density to suggest publication
223
- const evolutionCountResult = await this.db
227
+ const evolutionCountResult = (await this.db
224
228
  .selectFrom(this.config.metricsTable || 'agent_metrics')
225
229
  .select((eb) => eb.fn.count('id').as('count'))
226
230
  .where('metric_name', '=', 'evolution_applied')
227
231
  .where('created_at', '>', new Date(Date.now() - 7 * 24 * 3600000)) // Last 7 days
228
- .executeTakeFirst();
232
+ .executeTakeFirst());
229
233
  const evolutions = Number(evolutionCountResult?.count || 0);
230
234
  if (evolutions > 5) {
231
235
  proposals.push(`[SOVEREIGN RITUAL] The engine has undergone ${evolutions} structural evolutions this week. Consider a 'Sovereign Publication Ritual' to update the registry.`);
@@ -21,7 +21,7 @@ export class EvolutionRitual {
21
21
  const results = {
22
22
  synthesized: 0,
23
23
  broadcasted: 0,
24
- domainsSynced: []
24
+ domainsSynced: [],
25
25
  };
26
26
  // 1. Parallel Synthesis: Identify and bridge capability gaps
27
27
  const newSkills = await this.cortex.skillSynthesizer.discoverAndSynthesize();
@@ -47,11 +47,11 @@ export class EvolutionRitual {
47
47
  return results;
48
48
  }
49
49
  async checkDomainMaturity(domain) {
50
- const skills = await this.db
50
+ const skills = (await this.db
51
51
  .selectFrom(this.config.capabilitiesTable || 'agent_capabilities')
52
52
  .select(['reliability'])
53
53
  .where('name', 'like', `${domain}%`)
54
- .execute();
54
+ .execute());
55
55
  if (skills.length < 3)
56
56
  return false; // Need a minimum population for maturity
57
57
  const avgReliability = skills.reduce((sum, s) => sum + s.reliability, 0) / skills.length;
@@ -68,7 +68,7 @@ export class EvolutionRitual {
68
68
  .execute();
69
69
  const domainScores = new Map();
70
70
  for (const row of result) {
71
- const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : (row.tags || []);
71
+ const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags || [];
72
72
  for (const t of tags) {
73
73
  if (t === 'hive_mind')
74
74
  continue;
@@ -21,25 +21,32 @@ export class EvolutionaryPilot {
21
21
  const changes = [];
22
22
  let evolved = false;
23
23
  // 1. Full-Spectrum Observation
24
- const metrics = ['query_latency', 'success_rate', 'total_cost', 'trust_signal'];
24
+ const metrics = [
25
+ 'query_latency',
26
+ 'success_rate',
27
+ 'total_cost',
28
+ 'trust_signal',
29
+ ];
25
30
  const recentMetrics = await this.cortex.metrics.getRecentMetrics(100);
26
31
  for (const metricName of metrics) {
27
32
  const values = recentMetrics
28
- .filter(m => m.metricName === metricName)
29
- .map(m => Number(m.metricValue));
33
+ .filter((m) => m.metricName === metricName)
34
+ .map((m) => Number(m.metricValue));
30
35
  if (values.length < 5)
31
36
  continue;
32
37
  const stats = this.calculateZScore(values);
33
38
  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)}`);
34
39
  // 2. Trigger Evolution based on metric-specific thresholds
35
- if (metricName === 'query_latency' && (stats.zScore > 2.0 || stats.mean > 1000)) {
40
+ if (metricName === 'query_latency' &&
41
+ (stats.zScore > 2.0 || stats.mean > 1000)) {
36
42
  const result = await this.optimizeLatency();
37
43
  if (result) {
38
44
  changes.push(...result);
39
45
  evolved = true;
40
46
  }
41
47
  }
42
- if (metricName === 'success_rate' && (stats.zScore < -1.5 || stats.mean < 0.7)) {
48
+ if (metricName === 'success_rate' &&
49
+ (stats.zScore < -1.5 || stats.mean < 0.7)) {
43
50
  console.warn(`[EvolutionaryPilot] Success rate collapse detected (${stats.mean.toFixed(2)}). Triggering strategic mutation.`);
44
51
  const strategies = await this.cortex.strategy.mutateStrategy();
45
52
  changes.push(...strategies);
@@ -135,7 +142,10 @@ export class EvolutionaryPilot {
135
142
  const changes = [];
136
143
  console.log(`[EvolutionaryPilot] Triggering latency optimization...`);
137
144
  const dialect = this.db.getExecutor().dialect;
138
- const isSqlite = this.db.getExecutor().adapter.constructor.name.toLowerCase().includes('sqlite') ||
145
+ const isSqlite = this.db
146
+ .getExecutor()
147
+ .adapter.constructor.name.toLowerCase()
148
+ .includes('sqlite') ||
139
149
  (dialect && dialect.constructor.name.toLowerCase().includes('sqlite'));
140
150
  if (isSqlite) {
141
151
  await 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
  }
@@ -20,11 +20,11 @@ export class GoalArchitect {
20
20
  */
21
21
  async deconstructGoal(goalId, subGoals) {
22
22
  return await this.db.transaction().execute(async (trx) => {
23
- const goal = await trx
23
+ const goal = (await trx
24
24
  .selectFrom(this.goalsTable)
25
25
  .selectAll()
26
26
  .where('id', '=', goalId)
27
- .executeTakeFirst();
27
+ .executeTakeFirst());
28
28
  if (!goal)
29
29
  throw new Error(`Goal ${goalId} not found`);
30
30
  console.log(`[GoalArchitect] Deconstructing goal ${goalId}: "${goal.description}" into ${subGoals.length} steps.`);
@@ -33,7 +33,7 @@ export class GoalArchitect {
33
33
  const basePriority = (goal.priority || 0) + 1;
34
34
  for (let i = 0; i < subGoals.length; i++) {
35
35
  const desc = subGoals[i];
36
- const subGoal = await trx
36
+ const subGoal = (await trx
37
37
  .insertInto(this.goalsTable)
38
38
  .values({
39
39
  session_id: goal.session_id,
@@ -42,10 +42,10 @@ export class GoalArchitect {
42
42
  status: 'pending',
43
43
  priority: basePriority + i, // Sequential priority
44
44
  created_at: new Date(),
45
- updated_at: new Date()
45
+ updated_at: new Date(),
46
46
  })
47
47
  .returningAll()
48
- .executeTakeFirstOrThrow();
48
+ .executeTakeFirstOrThrow());
49
49
  created.push(this.parseGoal(subGoal));
50
50
  }
51
51
  // Update parent status to in_progress if it was pending
@@ -89,18 +89,18 @@ export class GoalArchitect {
89
89
  const newMeta = {
90
90
  ...currentMeta,
91
91
  lastStatusChange: Date.now(),
92
- outcome: outcome || currentMeta.outcome
92
+ outcome: outcome || currentMeta.outcome,
93
93
  };
94
- const updated = await this.db
94
+ const updated = (await this.db
95
95
  .updateTable(this.goalsTable)
96
96
  .set({
97
97
  status,
98
98
  metadata: JSON.stringify(newMeta),
99
- updated_at: new Date()
99
+ updated_at: new Date(),
100
100
  })
101
101
  .where('id', '=', goalId)
102
102
  .returningAll()
103
- .executeTakeFirstOrThrow();
103
+ .executeTakeFirstOrThrow());
104
104
  return this.parseGoal(updated);
105
105
  }
106
106
  /**
@@ -116,28 +116,28 @@ export class GoalArchitect {
116
116
  if (subGoals.length === 0) {
117
117
  return { canComplete: true, pendingSubGoals: 0 };
118
118
  }
119
- const pending = subGoals.filter(g => g.status !== 'completed' && g.status !== 'failed').length;
119
+ const pending = subGoals.filter((g) => g.status !== 'completed' && g.status !== 'failed').length;
120
120
  return {
121
121
  canComplete: pending === 0,
122
- pendingSubGoals: pending
122
+ pendingSubGoals: pending,
123
123
  };
124
124
  }
125
125
  /**
126
- * Identify goals that have "stalled" (no status changes in > 7 days)
127
- */
126
+ * Identify goals that have "stalled" (no status changes in > 7 days)
127
+ */
128
128
  async trackStalledGoals(daysThreshold = 7) {
129
129
  console.log('[GoalArchitect] Identifying stalled objectives...');
130
130
  const thresholdDate = new Date(Date.now() - daysThreshold * 24 * 3600000);
131
- const stalled = await this.typedDb
131
+ const stalled = (await this.typedDb
132
132
  .selectFrom(this.goalsTable)
133
133
  .selectAll()
134
134
  .where('status', 'in', ['pending', 'in_progress'])
135
135
  .where('updated_at', '<', thresholdDate)
136
- .execute();
136
+ .execute());
137
137
  if (stalled.length > 0) {
138
138
  console.log(`[GoalArchitect] Identified ${stalled.length} stalled goals.`);
139
139
  }
140
- return stalled.map(g => this.parseGoal(g));
140
+ return stalled.map((g) => this.parseGoal(g));
141
141
  }
142
142
  parseGoal(g) {
143
143
  return {
@@ -147,9 +147,11 @@ export class GoalArchitect {
147
147
  description: g.description,
148
148
  status: g.status,
149
149
  priority: g.priority,
150
- metadata: typeof g.metadata === 'string' ? JSON.parse(g.metadata) : (g.metadata || {}),
150
+ metadata: typeof g.metadata === 'string'
151
+ ? JSON.parse(g.metadata)
152
+ : g.metadata || {},
151
153
  createdAt: new Date(g.created_at),
152
- updatedAt: new Date(g.updated_at)
154
+ updatedAt: new Date(g.updated_at),
153
155
  };
154
156
  }
155
157
  }
@@ -24,16 +24,18 @@ export class GovernanceManager {
24
24
  async performAudit() {
25
25
  const issues = [];
26
26
  // Fetch active policies
27
- const policies = await this.db
27
+ const policies = (await this.db
28
28
  .selectFrom(this.policiesTable)
29
29
  .selectAll()
30
30
  .where('is_enabled', '=', true)
31
- .execute();
31
+ .execute());
32
32
  const getPolicyValue = (name, type, fallback) => {
33
- const p = policies.find(p => p.name === name || p.type === type);
33
+ const p = policies.find((p) => p.name === name || p.type === type);
34
34
  if (!p)
35
35
  return fallback;
36
- const def = typeof p.definition === 'string' ? JSON.parse(p.definition) : p.definition;
36
+ const def = typeof p.definition === 'string'
37
+ ? JSON.parse(p.definition)
38
+ : p.definition;
37
39
  return def.threshold ?? fallback;
38
40
  };
39
41
  // 1. Budgetary Governance: Check for cost spikes in various windows
@@ -86,7 +88,7 @@ export class GovernanceManager {
86
88
  console.warn(`[GovernanceManager] AUDIT FAILED [${new Date().toISOString()}]: ${issues.length} compliance issues detected.`);
87
89
  // Phase 1: Emergency Rollbacks
88
90
  const activePersona = await this.getActivePersona();
89
- if (activePersona && (success < 0.4 || hCost > (hourlyLimit * 1.5))) {
91
+ if (activePersona && (success < 0.4 || hCost > hourlyLimit * 1.5)) {
90
92
  console.error(`[GovernanceManager] CRITICAL THRESHOLD BREACH. Initiating emergency containment for persona ${activePersona.id}`);
91
93
  await this.cortex.strategy.rollbackPersona(activePersona.id);
92
94
  issues.push(`Containment: Emergency rollback triggered for persona ${activePersona.id}`);
@@ -98,7 +100,7 @@ export class GovernanceManager {
98
100
  }
99
101
  return {
100
102
  healthy: issues.length === 0,
101
- issues
103
+ issues,
102
104
  };
103
105
  }
104
106
  /**
@@ -114,7 +116,9 @@ export class GovernanceManager {
114
116
  return null;
115
117
  return {
116
118
  ...active,
117
- metadata: typeof active.metadata === 'string' ? JSON.parse(active.metadata) : (active.metadata || {})
119
+ metadata: typeof active.metadata === 'string'
120
+ ? JSON.parse(active.metadata)
121
+ : active.metadata || {},
118
122
  };
119
123
  }
120
124
  /**
@@ -163,11 +167,15 @@ export class GovernanceManager {
163
167
  const slowTables = new Set();
164
168
  for (const q of recentSlowQueries) {
165
169
  try {
166
- const meta = typeof q.metadata === 'string' ? JSON.parse(q.metadata) : (q.metadata || {});
170
+ const meta = typeof q.metadata === 'string'
171
+ ? JSON.parse(q.metadata)
172
+ : q.metadata || {};
167
173
  if (meta.table)
168
174
  slowTables.add(meta.table);
169
175
  }
170
- catch (e) { /* ignore parse errors */ }
176
+ catch (e) {
177
+ /* ignore parse errors */
178
+ }
171
179
  }
172
180
  for (const table of slowTables) {
173
181
  repairs.push(`Table '${table}' is experiencing periodic latency spikes. Suggesting 'CREATE INDEX' for common filters.`);
@@ -180,11 +188,11 @@ export class GovernanceManager {
180
188
  // 3. Check for cold storage candidates
181
189
  const sessionsTable = this.config.sessionsTable || 'agent_sessions';
182
190
  const oldThreshold = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); // 30 days
183
- const oldSessions = await this.db
191
+ const oldSessions = (await this.db
184
192
  .selectFrom(sessionsTable)
185
193
  .select((eb) => eb.fn.count('id').as('count'))
186
194
  .where('created_at', '<', oldThreshold)
187
- .executeTakeFirst();
195
+ .executeTakeFirst());
188
196
  if (Number(oldSessions?.count || 0) > 100) {
189
197
  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.`);
190
198
  }