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
@@ -34,7 +34,7 @@ export class PolicyEnforcer {
34
34
  type,
35
35
  definition: JSON.stringify(definition),
36
36
  is_enabled: isEnabled,
37
- updated_at: new Date()
37
+ updated_at: new Date(),
38
38
  })
39
39
  .where('id', '=', existing.id)
40
40
  .returningAll()
@@ -49,7 +49,7 @@ export class PolicyEnforcer {
49
49
  definition: JSON.stringify(definition),
50
50
  is_enabled: isEnabled,
51
51
  created_at: new Date(),
52
- updated_at: new Date()
52
+ updated_at: new Date(),
53
53
  })
54
54
  .returningAll()
55
55
  .executeTakeFirstOrThrow();
@@ -73,20 +73,32 @@ export class PolicyEnforcer {
73
73
  // 1. Threshold Check (Numeric)
74
74
  if (typeof value === 'number') {
75
75
  if (def.max !== undefined && value > def.max) {
76
- return { allowed: false, reason: `Value ${value} exceeds max ${def.max} for policy '${name}'` };
76
+ return {
77
+ allowed: false,
78
+ reason: `Value ${value} exceeds max ${def.max} for policy '${name}'`,
79
+ };
77
80
  }
78
81
  if (def.min !== undefined && value < def.min) {
79
- return { allowed: false, reason: `Value ${value} below min ${def.min} for policy '${name}'` };
82
+ return {
83
+ allowed: false,
84
+ reason: `Value ${value} below min ${def.min} for policy '${name}'`,
85
+ };
80
86
  }
81
87
  }
82
88
  // 2. Pattern Check (String/Regex)
83
89
  if (typeof value === 'string' && def.pattern) {
84
90
  const regex = new RegExp(def.pattern, 'i');
85
91
  if (def.mustMatch && !regex.test(value)) {
86
- return { allowed: false, reason: `Value does not match required pattern for policy '${name}'` };
92
+ return {
93
+ allowed: false,
94
+ reason: `Value does not match required pattern for policy '${name}'`,
95
+ };
87
96
  }
88
97
  if (!def.mustMatch && regex.test(value)) {
89
- return { allowed: false, reason: `Value contains forbidden pattern for policy '${name}'` };
98
+ return {
99
+ allowed: false,
100
+ reason: `Value contains forbidden pattern for policy '${name}'`,
101
+ };
90
102
  }
91
103
  }
92
104
  // 3. Budget Check (Cumulative)
@@ -95,7 +107,10 @@ export class PolicyEnforcer {
95
107
  const limit = def.limit || 0;
96
108
  const total = await this.getCumulativeMetric(def.metricName, period);
97
109
  if (total + (typeof value === 'number' ? value : 0) > limit) {
98
- return { allowed: false, reason: `Cumulative budget for '${def.metricName}' exceeded (${total.toFixed(4)} / ${limit})` };
110
+ return {
111
+ allowed: false,
112
+ reason: `Cumulative budget for '${def.metricName}' exceeded (${total.toFixed(4)} / ${limit})`,
113
+ };
99
114
  }
100
115
  }
101
116
  return { allowed: true };
@@ -122,7 +137,7 @@ export class PolicyEnforcer {
122
137
  }
123
138
  return {
124
139
  allowed: violations.length === 0,
125
- violations
140
+ violations,
126
141
  };
127
142
  }
128
143
  /**
@@ -134,7 +149,7 @@ export class PolicyEnforcer {
134
149
  .selectAll()
135
150
  .where('is_enabled', '=', true)
136
151
  .execute();
137
- return list.map(p => this.parsePolicy(p));
152
+ return list.map((p) => this.parsePolicy(p));
138
153
  }
139
154
  async getCumulativeMetric(metricName, period) {
140
155
  let cutoff = new Date(0); // beginning of time
@@ -158,11 +173,15 @@ export class PolicyEnforcer {
158
173
  id: p.id,
159
174
  name: p.name,
160
175
  type: p.type,
161
- definition: typeof p.definition === 'string' ? JSON.parse(p.definition) : p.definition,
176
+ definition: typeof p.definition === 'string'
177
+ ? JSON.parse(p.definition)
178
+ : p.definition,
162
179
  isEnabled: !!p.is_enabled,
163
- metadata: typeof p.metadata === 'string' ? JSON.parse(p.metadata) : (p.metadata || {}),
180
+ metadata: typeof p.metadata === 'string'
181
+ ? JSON.parse(p.metadata)
182
+ : p.metadata || {},
164
183
  createdAt: new Date(p.created_at),
165
- updatedAt: new Date(p.updated_at)
184
+ updatedAt: new Date(p.updated_at),
166
185
  };
167
186
  }
168
187
  }
@@ -30,7 +30,7 @@ export class ResourceMonitor {
30
30
  cost: cost || 0,
31
31
  currency: 'USD',
32
32
  metadata: metadata ? JSON.stringify(metadata) : null,
33
- created_at: new Date()
33
+ created_at: new Date(),
34
34
  })
35
35
  .returningAll()
36
36
  .executeTakeFirstOrThrow();
@@ -66,14 +66,14 @@ export class ResourceMonitor {
66
66
  .select([
67
67
  'model_name',
68
68
  (eb) => eb.fn.sum(sql `input_tokens + output_tokens`).as('totalTokens'),
69
- (eb) => eb.fn.sum('cost').as('totalCost')
69
+ (eb) => eb.fn.sum('cost').as('totalCost'),
70
70
  ])
71
71
  .groupBy('model_name')
72
72
  .execute();
73
73
  return results.map((r) => ({
74
74
  modelName: r.model_name,
75
75
  totalTokens: Number(r.totalTokens),
76
- totalCost: Number(r.totalCost)
76
+ totalCost: Number(r.totalCost),
77
77
  }));
78
78
  }
79
79
  parseUsage(usage) {
@@ -86,7 +86,7 @@ export class ResourceMonitor {
86
86
  outputTokens: usage.output_tokens,
87
87
  cost: usage.cost,
88
88
  currency: usage.currency,
89
- createdAt: new Date(usage.created_at)
89
+ createdAt: new Date(usage.created_at),
90
90
  };
91
91
  }
92
92
  }
@@ -17,7 +17,7 @@ export class SessionCompressor {
17
17
  */
18
18
  async compress(sessionId, summary, startMessageId, endMessageId, anchors = [], metadata) {
19
19
  console.log(`[SessionCompressor] Compressing session ${sessionId} with ${anchors.length} semantic anchors.`);
20
- const epoch = await this.db
20
+ const epoch = (await this.db
21
21
  .insertInto(this.epochsTable)
22
22
  .values({
23
23
  session_id: sessionId,
@@ -27,10 +27,10 @@ export class SessionCompressor {
27
27
  metadata: metadata || anchors.length > 0
28
28
  ? JSON.stringify({ ...metadata, anchors })
29
29
  : null,
30
- created_at: new Date()
30
+ created_at: new Date(),
31
31
  })
32
32
  .returningAll()
33
- .executeTakeFirstOrThrow();
33
+ .executeTakeFirstOrThrow());
34
34
  return this.parseEpoch(epoch);
35
35
  }
36
36
  /**
@@ -49,8 +49,8 @@ export class SessionCompressor {
49
49
  eb('metadata', 'is', null),
50
50
  eb.and([
51
51
  eb('metadata', 'not like', '%"anchor":true%'),
52
- eb('metadata', 'not like', '%"anchor": true%')
53
- ])
52
+ eb('metadata', 'not like', '%"anchor": true%'),
53
+ ]),
54
54
  ]));
55
55
  }
56
56
  const result = await query.execute();
@@ -68,11 +68,15 @@ export class SessionCompressor {
68
68
  if (epochs.length > 10) {
69
69
  console.log(`[SessionCompressor] Consolidating ${epochs.length} epochs into a new Era for session ${sessionId}`);
70
70
  const summary = `Consolidated era summary of ${epochs.length} epochs: ` +
71
- epochs.slice(0, 5).map(e => e.summary).join('; ') + '...';
71
+ epochs
72
+ .slice(0, 5)
73
+ .map((e) => e.summary)
74
+ .join('; ') +
75
+ '...';
72
76
  const eraMetadata = {
73
77
  type: 'era',
74
78
  original_epochs: epochs.length,
75
- consolidated_at: new Date().toISOString()
79
+ consolidated_at: new Date().toISOString(),
76
80
  };
77
81
  // In this version, we mark the new epoch as an "Era" in metadata
78
82
  const consolidatedEpoch = await this.compress(sessionId, summary, epochs[0].startMessageId, epochs[epochs.length - 1].endMessageId, [], eraMetadata);
@@ -85,12 +89,16 @@ export class SessionCompressor {
85
89
  session_id: sessionId,
86
90
  role: 'system',
87
91
  content: `[ERA SUMMARY] This era covers the initial phases of the session. Key takeaways: ${summary}`,
88
- metadata: JSON.stringify({ anchor: true, type: 'era_reification', epoch_id: consolidatedEpoch.id }),
89
- created_at: new Date()
92
+ metadata: JSON.stringify({
93
+ anchor: true,
94
+ type: 'era_reification',
95
+ epoch_id: consolidatedEpoch.id,
96
+ }),
97
+ created_at: new Date(),
90
98
  })
91
99
  .execute();
92
100
  // Prune old epochs that were consolidated
93
- const epochIds = epochs.map(e => e.id);
101
+ const epochIds = epochs.map((e) => e.id);
94
102
  await this.db
95
103
  .deleteFrom(this.epochsTable)
96
104
  .where('id', 'in', epochIds)
@@ -101,13 +109,13 @@ export class SessionCompressor {
101
109
  * Get epochs for a session
102
110
  */
103
111
  async getEpochs(sessionId) {
104
- const list = await this.db
112
+ const list = (await this.db
105
113
  .selectFrom(this.epochsTable)
106
114
  .selectAll()
107
115
  .where('session_id', '=', sessionId)
108
116
  .orderBy('created_at', 'asc')
109
- .execute();
110
- return list.map(e => this.parseEpoch(e));
117
+ .execute());
118
+ return list.map((e) => this.parseEpoch(e));
111
119
  }
112
120
  parseEpoch(e) {
113
121
  return {
@@ -116,7 +124,7 @@ export class SessionCompressor {
116
124
  startMessageId: e.start_message_id,
117
125
  endMessageId: e.end_message_id,
118
126
  metadata: typeof e.metadata === 'string' ? JSON.parse(e.metadata) : e.metadata,
119
- createdAt: new Date(e.created_at)
127
+ createdAt: new Date(e.created_at),
120
128
  };
121
129
  }
122
130
  }
@@ -34,7 +34,7 @@ export class SessionManager {
34
34
  status: 'active',
35
35
  metadata: metadata ? JSON.stringify(metadata) : null,
36
36
  created_at: new Date(),
37
- updated_at: new Date()
37
+ updated_at: new Date(),
38
38
  })
39
39
  .returningAll()
40
40
  .executeTakeFirstOrThrow();
@@ -69,11 +69,23 @@ export class SessionManager {
69
69
  async deleteSession(id) {
70
70
  await this.db.transaction().execute(async (trx) => {
71
71
  // Delete associated data first
72
- await trx.deleteFrom(this.messagesTable).where('session_id', '=', id).execute();
73
- await trx.deleteFrom(this.goalsTable).where('session_id', '=', id).execute();
74
- await trx.deleteFrom(this.memoriesTable).where('session_id', '=', id).execute();
72
+ await trx
73
+ .deleteFrom(this.messagesTable)
74
+ .where('session_id', '=', id)
75
+ .execute();
76
+ await trx
77
+ .deleteFrom(this.goalsTable)
78
+ .where('session_id', '=', id)
79
+ .execute();
80
+ await trx
81
+ .deleteFrom(this.memoriesTable)
82
+ .where('session_id', '=', id)
83
+ .execute();
75
84
  // Delete the session itself
76
- await trx.deleteFrom(this.sessionsTable).where('id', '=', id).execute();
85
+ await trx
86
+ .deleteFrom(this.sessionsTable)
87
+ .where('id', '=', id)
88
+ .execute();
77
89
  });
78
90
  }
79
91
  /**
@@ -88,7 +100,7 @@ export class SessionManager {
88
100
  role,
89
101
  content,
90
102
  metadata: metadata ? JSON.stringify(metadata) : null,
91
- created_at: new Date()
103
+ created_at: new Date(),
92
104
  })
93
105
  .returningAll()
94
106
  .executeTakeFirstOrThrow();
@@ -112,7 +124,7 @@ export class SessionManager {
112
124
  .orderBy('created_at', 'asc')
113
125
  .limit(limit)
114
126
  .execute();
115
- return messages.map(m => this.parseMessage(m));
127
+ return messages.map((m) => this.parseMessage(m));
116
128
  }
117
129
  /**
118
130
  * Set or update a goal for a session
@@ -133,7 +145,7 @@ export class SessionManager {
133
145
  status,
134
146
  priority,
135
147
  metadata: metadata ? JSON.stringify(metadata) : existing.metadata,
136
- updated_at: new Date()
148
+ updated_at: new Date(),
137
149
  })
138
150
  .where('id', '=', existing.id)
139
151
  .returningAll()
@@ -150,7 +162,7 @@ export class SessionManager {
150
162
  priority,
151
163
  metadata: metadata ? JSON.stringify(metadata) : null,
152
164
  created_at: new Date(),
153
- updated_at: new Date()
165
+ updated_at: new Date(),
154
166
  })
155
167
  .returningAll()
156
168
  .executeTakeFirstOrThrow();
@@ -175,7 +187,7 @@ export class SessionManager {
175
187
  query = query.where('status', '=', status);
176
188
  }
177
189
  const goals = await query.execute();
178
- return goals.map(g => this.parseGoal(g));
190
+ return goals.map((g) => this.parseGoal(g));
179
191
  }
180
192
  /**
181
193
  * Clear message history for a session.
@@ -198,12 +210,12 @@ export class SessionManager {
198
210
  .executeTakeFirstOrThrow();
199
211
  const metadata = typeof message.metadata === 'string'
200
212
  ? JSON.parse(message.metadata)
201
- : (message.metadata || {});
213
+ : message.metadata || {};
202
214
  const updatedMetadata = { ...metadata, anchor: true };
203
215
  const updated = await this.typedDb
204
216
  .updateTable(this.messagesTable)
205
217
  .set({
206
- metadata: JSON.stringify(updatedMetadata)
218
+ metadata: JSON.stringify(updatedMetadata),
207
219
  })
208
220
  .where('id', '=', messageId)
209
221
  .returningAll()
@@ -215,9 +227,11 @@ export class SessionManager {
215
227
  id: session.id,
216
228
  name: session.name,
217
229
  status: session.status,
218
- metadata: typeof session.metadata === 'string' ? JSON.parse(session.metadata) : (session.metadata || {}),
230
+ metadata: typeof session.metadata === 'string'
231
+ ? JSON.parse(session.metadata)
232
+ : session.metadata || {},
219
233
  createdAt: new Date(session.created_at),
220
- updatedAt: new Date(session.updated_at)
234
+ updatedAt: new Date(session.updated_at),
221
235
  };
222
236
  }
223
237
  parseMessage(message) {
@@ -226,8 +240,10 @@ export class SessionManager {
226
240
  sessionId: message.session_id,
227
241
  role: message.role,
228
242
  content: message.content,
229
- metadata: typeof message.metadata === 'string' ? JSON.parse(message.metadata) : (message.metadata || {}),
230
- createdAt: new Date(message.created_at)
243
+ metadata: typeof message.metadata === 'string'
244
+ ? JSON.parse(message.metadata)
245
+ : message.metadata || {},
246
+ createdAt: new Date(message.created_at),
231
247
  };
232
248
  }
233
249
  parseGoal(goal) {
@@ -238,9 +254,11 @@ export class SessionManager {
238
254
  description: goal.description,
239
255
  status: goal.status,
240
256
  priority: goal.priority,
241
- metadata: typeof goal.metadata === 'string' ? JSON.parse(goal.metadata) : (goal.metadata || {}),
257
+ metadata: typeof goal.metadata === 'string'
258
+ ? JSON.parse(goal.metadata)
259
+ : goal.metadata || {},
242
260
  createdAt: new Date(goal.created_at),
243
- updatedAt: new Date(goal.updated_at)
261
+ updatedAt: new Date(goal.updated_at),
244
262
  };
245
263
  }
246
264
  }
@@ -26,7 +26,7 @@ export class VectorIndexer {
26
26
  embedding: JSON.stringify(embedding),
27
27
  session_id: sessionId || null,
28
28
  metadata: metadata ? JSON.stringify(metadata) : null,
29
- created_at: new Date()
29
+ created_at: new Date(),
30
30
  })
31
31
  .returningAll()
32
32
  .executeTakeFirstOrThrow();
@@ -36,19 +36,19 @@ export class VectorIndexer {
36
36
  * Batch add memories
37
37
  */
38
38
  async addMemories(items) {
39
- const values = items.map(item => ({
39
+ const values = items.map((item) => ({
40
40
  content: item.content,
41
41
  embedding: JSON.stringify(item.embedding),
42
42
  session_id: item.sessionId || null,
43
43
  metadata: item.metadata ? JSON.stringify(item.metadata) : null,
44
- created_at: new Date()
44
+ created_at: new Date(),
45
45
  }));
46
46
  const memories = await this.typedDb
47
47
  .insertInto(this.memoriesTable)
48
48
  .values(values)
49
49
  .returningAll()
50
50
  .execute();
51
- return memories.map(m => this.parseMemory(m));
51
+ return memories.map((m) => this.parseMemory(m));
52
52
  }
53
53
  /**
54
54
  * Search for similar memories using Hybrid Search (Vector + Keyword)
@@ -67,7 +67,7 @@ export class VectorIndexer {
67
67
  query = query.where('session_id', '=', sessionId);
68
68
  }
69
69
  const results = await query.execute();
70
- vectorResults = results.map(m => this.parseMemory(m));
70
+ vectorResults = results.map((m) => this.parseMemory(m));
71
71
  }
72
72
  else if (this.config.provider === 'sqlite-vss') {
73
73
  try {
@@ -92,15 +92,17 @@ export class VectorIndexer {
92
92
  query = query.orderBy('created_at', 'desc').limit(1000);
93
93
  }
94
94
  const allMemories = await query.execute();
95
- const scored = allMemories.map(mem => {
96
- const vec = typeof mem.embedding === 'string' ? JSON.parse(mem.embedding) : (mem.embedding || []);
95
+ const scored = allMemories.map((mem) => {
96
+ const vec = typeof mem.embedding === 'string'
97
+ ? JSON.parse(mem.embedding)
98
+ : mem.embedding || [];
97
99
  const score = this.cosineSimilarity(embedding, vec);
98
100
  return { memory: mem, score };
99
101
  });
100
102
  vectorResults = scored
101
103
  .sort((a, b) => b.score - a.score)
102
104
  .slice(0, limit)
103
- .map(item => this.parseMemory(item.memory));
105
+ .map((item) => this.parseMemory(item.memory));
104
106
  }
105
107
  // Keyword Search (Hybrid component)
106
108
  let keywordResults = [];
@@ -110,19 +112,17 @@ export class VectorIndexer {
110
112
  // Merge and fuse using Reciprocal Rank Fusion (RRF)
111
113
  const fused = this.mergeWithRRF(vectorResults, keywordResults, limit);
112
114
  // Final filtering and confidence assessment
113
- const finalResults = fused.filter(m => {
115
+ const finalResults = fused.filter((m) => {
114
116
  const vec = m.embedding || [];
115
117
  const score = this.cosineSimilarity(embedding, vec);
116
118
  // Even with RRF, we keep a safety floor for semantic relevance
117
- return score >= (minScore * 0.8);
119
+ return score >= minScore * 0.8;
118
120
  });
119
121
  return finalResults.slice(0, limit);
120
122
  }
121
123
  async keywordSearch(keyword, options) {
122
124
  const { limit, sessionId } = options;
123
- let query = this.typedDb
124
- .selectFrom(this.memoriesTable)
125
- .selectAll();
125
+ let query = this.typedDb.selectFrom(this.memoriesTable).selectAll();
126
126
  // Production Hardening: Use native FTS where available
127
127
  if (this.config.provider === 'sqlite-vss') {
128
128
  // Check for virtual FTS table (convention: table_name_fts)
@@ -145,7 +145,7 @@ export class VectorIndexer {
145
145
  query = query.where('session_id', '=', sessionId);
146
146
  }
147
147
  const results = await query.limit(limit).execute();
148
- return results.map(r => this.parseMemory(r));
148
+ return results.map((r) => this.parseMemory(r));
149
149
  }
150
150
  /**
151
151
  * Reciprocal Rank Fusion (RRF)
@@ -170,7 +170,7 @@ export class VectorIndexer {
170
170
  // Sort by fused score
171
171
  return Object.values(scores)
172
172
  .sort((a, b) => b.score - a.score)
173
- .map(s => s.memory);
173
+ .map((s) => s.memory);
174
174
  }
175
175
  mergeResults(vector, keyword) {
176
176
  const seen = new Set();
@@ -201,9 +201,13 @@ export class VectorIndexer {
201
201
  id: m.id,
202
202
  sessionId: m.session_id,
203
203
  content: m.content,
204
- embedding: typeof m.embedding === 'string' ? JSON.parse(m.embedding) : (m.embedding || []),
205
- metadata: typeof m.metadata === 'string' ? JSON.parse(m.metadata) : (m.metadata || {}),
206
- createdAt: new Date(m.created_at)
204
+ embedding: typeof m.embedding === 'string'
205
+ ? JSON.parse(m.embedding)
206
+ : m.embedding || [],
207
+ metadata: typeof m.metadata === 'string'
208
+ ? JSON.parse(m.metadata)
209
+ : m.metadata || {},
210
+ createdAt: new Date(m.created_at),
207
211
  };
208
212
  }
209
213
  }
@@ -32,11 +32,11 @@ export class AblationEngine {
32
32
  // 1. Prune Knowledge (with dependency check)
33
33
  const knowledgeToPrune = await trx
34
34
  .selectFrom(this.knowledgeTable)
35
- .select('id')
35
+ .selectAll()
36
36
  .where((eb) => eb.or([
37
37
  eb('metadata', 'not like', '%"priority": "high"%'),
38
38
  eb('metadata', 'not like', '%"priority":"high"%'),
39
- eb('metadata', 'is', null)
39
+ eb('metadata', 'is', null),
40
40
  ]))
41
41
  .where('updated_at', '<', cutoff)
42
42
  // Exclude items that are linked
@@ -44,7 +44,7 @@ export class AblationEngine {
44
44
  .where('id', 'not in', (eb) => eb.selectFrom(this.linksTable).select('target_id'))
45
45
  .execute();
46
46
  if (knowledgeToPrune.length > 0) {
47
- const candidates = knowledgeToPrune.map(k => this.cortex.knowledge['parseKnowledge'](k));
47
+ const candidates = knowledgeToPrune.map((k) => this.cortex.knowledge['parseKnowledge'](k));
48
48
  const idsToDelete = [];
49
49
  for (const item of candidates) {
50
50
  const fitness = this.cortex.knowledge.calculateFitness(item);
@@ -67,7 +67,7 @@ export class AblationEngine {
67
67
  .where('created_at', '<', cutoff)
68
68
  .where((eb) => eb.or([
69
69
  eb('metadata', 'not like', '%"anchor":true%'),
70
- eb('metadata', 'is', null)
70
+ eb('metadata', 'is', null),
71
71
  ]))
72
72
  .executeTakeFirst();
73
73
  totalPruned += Number(memoriesResult.numDeletedRows || 0);
@@ -86,7 +86,7 @@ export class AblationEngine {
86
86
  const baseline = await this.cortex.metrics.getAverageMetric('success_rate');
87
87
  const stats = await this.cortex.metrics.getMetricStats('success_rate');
88
88
  // If current average is significantly lower than overall average
89
- if (stats.count > 10 && stats.avg < (baseline * 0.8)) {
89
+ if (stats.count > 10 && stats.avg < baseline * 0.8) {
90
90
  console.warn(`[AblationEngine] PERFORMANCE DEGRADATION DETECTED (Avg: ${stats.avg}, Baseline: ${baseline}). Triggering mass recovery.`);
91
91
  const ablatedItems = await this.typedDb
92
92
  .selectFrom(this.knowledgeTable)
@@ -110,16 +110,21 @@ export class AblationEngine {
110
110
  async testAblation(id) {
111
111
  console.log(`[AblationEngine] Conducting ablation test on item ${id}`);
112
112
  return await this.db.transaction().execute(async (trx) => {
113
- const item = await trx
113
+ const item = (await trx
114
114
  .selectFrom(this.knowledgeTable)
115
115
  .selectAll()
116
116
  .where('id', '=', id)
117
- .executeTakeFirst();
117
+ .executeTakeFirst());
118
118
  if (!item)
119
119
  return false;
120
- const metadata = typeof item.metadata === 'string' ? JSON.parse(item.metadata) : (item.metadata || {});
120
+ const metadata = typeof item.metadata === 'string'
121
+ ? JSON.parse(item.metadata)
122
+ : item.metadata || {};
121
123
  // 1. Record the experiment in reflections
122
- await this.cortex.reflections.reflect(item.source_session_id || 'system', 'success', `Ablation experiment initiated for item ${id}`, [`Temporary confidence reduction to evaluate reasoning impact.`, `Original confidence: ${item.confidence}`]);
124
+ await this.cortex.reflections.reflect(item.source_session_id || 'system', 'success', `Ablation experiment initiated for item ${id}`, [
125
+ `Temporary confidence reduction to evaluate reasoning impact.`,
126
+ `Original confidence: ${item.confidence}`,
127
+ ]);
123
128
  // 2. Perform the ablation
124
129
  await trx
125
130
  .updateTable(this.knowledgeTable)
@@ -128,9 +133,9 @@ export class AblationEngine {
128
133
  ...metadata,
129
134
  ablation_test: true,
130
135
  original_confidence: item.confidence,
131
- ablated_at: new Date()
136
+ ablated_at: new Date(),
132
137
  }),
133
- confidence: 0
138
+ confidence: 0,
134
139
  })
135
140
  .where('id', '=', id)
136
141
  .execute();
@@ -142,14 +147,16 @@ export class AblationEngine {
142
147
  */
143
148
  async recoverAblatedItem(id) {
144
149
  return await this.db.transaction().execute(async (trx) => {
145
- const item = await trx
150
+ const item = (await trx
146
151
  .selectFrom(this.knowledgeTable)
147
152
  .selectAll()
148
153
  .where('id', '=', id)
149
- .executeTakeFirst();
154
+ .executeTakeFirst());
150
155
  if (!item)
151
156
  return false;
152
- const metadata = typeof item.metadata === 'string' ? JSON.parse(item.metadata) : (item.metadata || {});
157
+ const metadata = typeof item.metadata === 'string'
158
+ ? JSON.parse(item.metadata)
159
+ : item.metadata || {};
153
160
  if (!metadata.ablation_test)
154
161
  return false;
155
162
  const originalConfidence = metadata.original_confidence ?? 0.5;
@@ -161,7 +168,7 @@ export class AblationEngine {
161
168
  .set({
162
169
  confidence: originalConfidence,
163
170
  metadata: JSON.stringify(metadata),
164
- updated_at: new Date()
171
+ updated_at: new Date(),
165
172
  })
166
173
  .where('id', '=', id)
167
174
  .execute();
@@ -20,13 +20,15 @@ export class ActionRefiner {
20
20
  async refineActions() {
21
21
  const recommendations = [];
22
22
  // 1. Find tools with high failure rates
23
- const failureStats = await this.db
23
+ const failureStats = (await this.db
24
24
  .selectFrom(this.actionsTable)
25
25
  .select('tool_name')
26
26
  .select((eb) => eb.fn.count('id').as('total'))
27
- .select((eb) => eb.fn.sum(eb.case().when('status', '=', 'failure').then(1).else(0).end()).as('failures'))
27
+ .select((eb) => eb.fn
28
+ .sum(eb.case().when('status', '=', 'failure').then(1).else(0).end())
29
+ .as('failures'))
28
30
  .groupBy('tool_name')
29
- .execute();
31
+ .execute());
30
32
  for (const stat of failureStats) {
31
33
  const failures = Number(stat.failures || 0);
32
34
  const total = Number(stat.total || 1);
@@ -38,7 +40,7 @@ export class ActionRefiner {
38
40
  }
39
41
  }
40
42
  // 2. Discover missing capabilities based on error patterns
41
- const missingCapabilities = await this.db
43
+ const missingCapabilities = (await this.db
42
44
  .selectFrom(this.actionsTable)
43
45
  .select('tool_name')
44
46
  .where('status', '=', 'failure')
@@ -46,10 +48,10 @@ export class ActionRefiner {
46
48
  eb('error', 'like', '%permission denied%'),
47
49
  eb('error', 'like', '%unknown tool%'),
48
50
  eb('error', 'like', '%missing capability%'),
49
- eb('error', 'like', '%not authorized%')
51
+ eb('error', 'like', '%not authorized%'),
50
52
  ]))
51
53
  .groupBy('tool_name')
52
- .execute();
54
+ .execute());
53
55
  for (const row of missingCapabilities) {
54
56
  recommendations.push(`Detected repeated access/existence failures for tool '${row.tool_name}'. Proposing capability expansion.`);
55
57
  await this.proposeCapabilityUpdate(row.tool_name);
@@ -61,14 +63,14 @@ export class ActionRefiner {
61
63
  */
62
64
  async proposeReflectionRule(toolName) {
63
65
  const existing = await this.cortex.rules.getActiveRules('agent_actions', 'insert');
64
- const hasRule = existing.some(r => r.metadata?.targetTool === toolName);
66
+ const hasRule = existing.some((r) => r.metadata?.targetTool === toolName);
65
67
  if (!hasRule) {
66
68
  console.log(`[ActionRefiner] Proposing reflection rule for tool: ${toolName}`);
67
69
  await this.cortex.rules.defineRule('agent_actions', 'insert', 'audit', {
68
70
  metadata: {
69
71
  targetTool: toolName,
70
- reason: 'High failure rate detected by ActionRefiner'
71
- }
72
+ reason: 'High failure rate detected by ActionRefiner',
73
+ },
72
74
  });
73
75
  }
74
76
  }
@@ -79,7 +81,7 @@ export class ActionRefiner {
79
81
  console.log(`[ActionRefiner] Proposing capability expansion for tool: ${toolName}`);
80
82
  await this.cortex.reflections.reflect('system', 'failure', `Architectural Gap: Missing Capability for '${toolName}'`, [
81
83
  `Identified repeated failures using tool '${toolName}'.`,
82
- `Resolution: Inspect permission sets and ensure the tool is correctly registered in the CapabilityManager.`
84
+ `Resolution: Inspect permission sets and ensure the tool is correctly registered in the CapabilityManager.`,
83
85
  ]);
84
86
  }
85
87
  }