noormme 1.2.3 → 1.2.5

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 (144) hide show
  1. package/dist/cjs/agentic/ActionJournal.d.ts +6 -6
  2. package/dist/cjs/agentic/ActionJournal.js +10 -10
  3. package/dist/cjs/agentic/CapabilityManager.d.ts +5 -5
  4. package/dist/cjs/agentic/CapabilityManager.js +35 -24
  5. package/dist/cjs/agentic/Cortex.js +12 -13
  6. package/dist/cjs/agentic/EpisodicMemory.js +4 -3
  7. package/dist/cjs/agentic/PersonaManager.d.ts +4 -4
  8. package/dist/cjs/agentic/PersonaManager.js +19 -15
  9. package/dist/cjs/agentic/PolicyEnforcer.d.ts +4 -8
  10. package/dist/cjs/agentic/PolicyEnforcer.js +26 -26
  11. package/dist/cjs/agentic/ResourceMonitor.js +2 -1
  12. package/dist/cjs/agentic/SessionManager.js +7 -6
  13. package/dist/cjs/agentic/improvement/AblationEngine.d.ts +3 -3
  14. package/dist/cjs/agentic/improvement/AblationEngine.js +41 -24
  15. package/dist/cjs/agentic/improvement/ActionRefiner.d.ts +1 -1
  16. package/dist/cjs/agentic/improvement/ActionRefiner.js +21 -15
  17. package/dist/cjs/agentic/improvement/ConflictResolver.js +4 -3
  18. package/dist/cjs/agentic/improvement/EvolutionRitual.js +2 -1
  19. package/dist/cjs/agentic/improvement/EvolutionaryPilot.d.ts +1 -1
  20. package/dist/cjs/agentic/improvement/EvolutionaryPilot.js +17 -19
  21. package/dist/cjs/agentic/improvement/GoalArchitect.js +10 -9
  22. package/dist/cjs/agentic/improvement/GovernanceManager.d.ts +5 -5
  23. package/dist/cjs/agentic/improvement/GovernanceManager.js +12 -22
  24. package/dist/cjs/agentic/improvement/HiveLink.d.ts +3 -3
  25. package/dist/cjs/agentic/improvement/HiveLink.js +15 -157
  26. package/dist/cjs/agentic/improvement/KnowledgeDistiller.d.ts +15 -29
  27. package/dist/cjs/agentic/improvement/KnowledgeDistiller.js +69 -351
  28. package/dist/cjs/agentic/improvement/QuotaManager.d.ts +1 -1
  29. package/dist/cjs/agentic/improvement/QuotaManager.js +11 -11
  30. package/dist/cjs/agentic/improvement/RecursiveReasoner.d.ts +4 -4
  31. package/dist/cjs/agentic/improvement/RecursiveReasoner.js +10 -10
  32. package/dist/cjs/agentic/improvement/ReflectionEngine.d.ts +2 -2
  33. package/dist/cjs/agentic/improvement/ReflectionEngine.js +2 -2
  34. package/dist/cjs/agentic/improvement/RitualOrchestrator.d.ts +3 -3
  35. package/dist/cjs/agentic/improvement/RitualOrchestrator.js +12 -9
  36. package/dist/cjs/agentic/improvement/SelfEvolution.d.ts +1 -1
  37. package/dist/cjs/agentic/improvement/SelfEvolution.js +21 -18
  38. package/dist/cjs/agentic/improvement/SelfTestRegistry.d.ts +1 -1
  39. package/dist/cjs/agentic/improvement/SelfTestRegistry.js +27 -19
  40. package/dist/cjs/agentic/improvement/SovereignMetrics.d.ts +6 -6
  41. package/dist/cjs/agentic/improvement/SovereignMetrics.js +12 -12
  42. package/dist/cjs/agentic/improvement/StrategicPlanner.d.ts +10 -54
  43. package/dist/cjs/agentic/improvement/StrategicPlanner.js +43 -396
  44. package/dist/cjs/agentic/improvement/distillation/ConflictChallenger.d.ts +3 -0
  45. package/dist/cjs/agentic/improvement/distillation/ConflictChallenger.js +54 -0
  46. package/dist/cjs/agentic/improvement/distillation/FactDistiller.d.ts +10 -0
  47. package/dist/cjs/agentic/improvement/distillation/FactDistiller.js +115 -0
  48. package/dist/cjs/agentic/improvement/distillation/KnowledgeConsolidator.d.ts +6 -0
  49. package/dist/cjs/agentic/improvement/distillation/KnowledgeConsolidator.js +63 -0
  50. package/dist/cjs/agentic/improvement/distillation/RelationshipArchitect.d.ts +6 -0
  51. package/dist/cjs/agentic/improvement/distillation/RelationshipArchitect.js +73 -0
  52. package/dist/cjs/agentic/improvement/governance/MaintenanceOracle.js +5 -5
  53. package/dist/cjs/agentic/improvement/governance/PersonaAuditor.js +7 -11
  54. package/dist/cjs/agentic/improvement/governance/RemediationEngine.js +8 -3
  55. package/dist/cjs/agentic/improvement/hive/DomainMaster.d.ts +4 -0
  56. package/dist/cjs/agentic/improvement/hive/DomainMaster.js +19 -0
  57. package/dist/cjs/agentic/improvement/hive/KnowledgePromoter.d.ts +6 -0
  58. package/dist/cjs/agentic/improvement/hive/KnowledgePromoter.js +57 -0
  59. package/dist/cjs/agentic/improvement/hive/SkillPropagator.d.ts +6 -0
  60. package/dist/cjs/agentic/improvement/hive/SkillPropagator.js +91 -0
  61. package/dist/cjs/agentic/improvement/strategy/EvolutionVerificator.d.ts +6 -0
  62. package/dist/cjs/agentic/improvement/strategy/EvolutionVerificator.js +48 -0
  63. package/dist/cjs/agentic/improvement/strategy/MutationEngine.d.ts +10 -0
  64. package/dist/cjs/agentic/improvement/strategy/MutationEngine.js +119 -0
  65. package/dist/cjs/agentic/improvement/strategy/PerformanceAnalyst.d.ts +6 -0
  66. package/dist/cjs/agentic/improvement/strategy/PerformanceAnalyst.js +84 -0
  67. package/dist/cjs/agentic/util/db-utils.d.ts +4 -0
  68. package/dist/cjs/agentic/util/db-utils.js +27 -0
  69. package/dist/cjs/cli/index.js +0 -0
  70. package/dist/cjs/helpers/agent-schema.js +1 -0
  71. package/dist/cjs/testing/test-utils.js +2 -0
  72. package/dist/cjs/types/index.d.ts +8 -0
  73. package/dist/esm/agentic/ActionJournal.d.ts +6 -6
  74. package/dist/esm/agentic/ActionJournal.js +10 -10
  75. package/dist/esm/agentic/CapabilityManager.d.ts +5 -5
  76. package/dist/esm/agentic/CapabilityManager.js +35 -24
  77. package/dist/esm/agentic/Cortex.js +12 -13
  78. package/dist/esm/agentic/EpisodicMemory.js +4 -3
  79. package/dist/esm/agentic/PersonaManager.d.ts +4 -4
  80. package/dist/esm/agentic/PersonaManager.js +19 -15
  81. package/dist/esm/agentic/PolicyEnforcer.d.ts +4 -8
  82. package/dist/esm/agentic/PolicyEnforcer.js +26 -26
  83. package/dist/esm/agentic/ResourceMonitor.js +2 -1
  84. package/dist/esm/agentic/SessionManager.js +7 -6
  85. package/dist/esm/agentic/improvement/AblationEngine.d.ts +3 -3
  86. package/dist/esm/agentic/improvement/AblationEngine.js +41 -24
  87. package/dist/esm/agentic/improvement/ActionRefiner.d.ts +1 -1
  88. package/dist/esm/agentic/improvement/ActionRefiner.js +21 -15
  89. package/dist/esm/agentic/improvement/ConflictResolver.js +4 -3
  90. package/dist/esm/agentic/improvement/EvolutionRitual.js +2 -1
  91. package/dist/esm/agentic/improvement/EvolutionaryPilot.d.ts +1 -1
  92. package/dist/esm/agentic/improvement/EvolutionaryPilot.js +17 -19
  93. package/dist/esm/agentic/improvement/GoalArchitect.js +10 -9
  94. package/dist/esm/agentic/improvement/GovernanceManager.d.ts +5 -5
  95. package/dist/esm/agentic/improvement/GovernanceManager.js +12 -22
  96. package/dist/esm/agentic/improvement/HiveLink.d.ts +3 -3
  97. package/dist/esm/agentic/improvement/HiveLink.js +15 -157
  98. package/dist/esm/agentic/improvement/KnowledgeDistiller.d.ts +15 -29
  99. package/dist/esm/agentic/improvement/KnowledgeDistiller.js +69 -351
  100. package/dist/esm/agentic/improvement/QuotaManager.d.ts +1 -1
  101. package/dist/esm/agentic/improvement/QuotaManager.js +11 -11
  102. package/dist/esm/agentic/improvement/RecursiveReasoner.d.ts +4 -4
  103. package/dist/esm/agentic/improvement/RecursiveReasoner.js +10 -10
  104. package/dist/esm/agentic/improvement/ReflectionEngine.d.ts +2 -2
  105. package/dist/esm/agentic/improvement/ReflectionEngine.js +2 -2
  106. package/dist/esm/agentic/improvement/RitualOrchestrator.d.ts +3 -3
  107. package/dist/esm/agentic/improvement/RitualOrchestrator.js +12 -9
  108. package/dist/esm/agentic/improvement/SelfEvolution.d.ts +1 -1
  109. package/dist/esm/agentic/improvement/SelfEvolution.js +21 -18
  110. package/dist/esm/agentic/improvement/SelfTestRegistry.d.ts +1 -1
  111. package/dist/esm/agentic/improvement/SelfTestRegistry.js +27 -19
  112. package/dist/esm/agentic/improvement/SovereignMetrics.d.ts +6 -6
  113. package/dist/esm/agentic/improvement/SovereignMetrics.js +12 -12
  114. package/dist/esm/agentic/improvement/StrategicPlanner.d.ts +10 -54
  115. package/dist/esm/agentic/improvement/StrategicPlanner.js +43 -396
  116. package/dist/esm/agentic/improvement/distillation/ConflictChallenger.d.ts +3 -0
  117. package/dist/esm/agentic/improvement/distillation/ConflictChallenger.js +51 -0
  118. package/dist/esm/agentic/improvement/distillation/FactDistiller.d.ts +10 -0
  119. package/dist/esm/agentic/improvement/distillation/FactDistiller.js +112 -0
  120. package/dist/esm/agentic/improvement/distillation/KnowledgeConsolidator.d.ts +6 -0
  121. package/dist/esm/agentic/improvement/distillation/KnowledgeConsolidator.js +60 -0
  122. package/dist/esm/agentic/improvement/distillation/RelationshipArchitect.d.ts +6 -0
  123. package/dist/esm/agentic/improvement/distillation/RelationshipArchitect.js +70 -0
  124. package/dist/esm/agentic/improvement/governance/MaintenanceOracle.js +5 -5
  125. package/dist/esm/agentic/improvement/governance/PersonaAuditor.js +7 -11
  126. package/dist/esm/agentic/improvement/governance/RemediationEngine.js +8 -3
  127. package/dist/esm/agentic/improvement/hive/DomainMaster.d.ts +4 -0
  128. package/dist/esm/agentic/improvement/hive/DomainMaster.js +16 -0
  129. package/dist/esm/agentic/improvement/hive/KnowledgePromoter.d.ts +6 -0
  130. package/dist/esm/agentic/improvement/hive/KnowledgePromoter.js +54 -0
  131. package/dist/esm/agentic/improvement/hive/SkillPropagator.d.ts +6 -0
  132. package/dist/esm/agentic/improvement/hive/SkillPropagator.js +88 -0
  133. package/dist/esm/agentic/improvement/strategy/EvolutionVerificator.d.ts +6 -0
  134. package/dist/esm/agentic/improvement/strategy/EvolutionVerificator.js +45 -0
  135. package/dist/esm/agentic/improvement/strategy/MutationEngine.d.ts +10 -0
  136. package/dist/esm/agentic/improvement/strategy/MutationEngine.js +116 -0
  137. package/dist/esm/agentic/improvement/strategy/PerformanceAnalyst.d.ts +6 -0
  138. package/dist/esm/agentic/improvement/strategy/PerformanceAnalyst.js +81 -0
  139. package/dist/esm/agentic/util/db-utils.d.ts +4 -0
  140. package/dist/esm/agentic/util/db-utils.js +25 -0
  141. package/dist/esm/helpers/agent-schema.js +1 -0
  142. package/dist/esm/testing/test-utils.js +2 -0
  143. package/dist/esm/types/index.d.ts +8 -0
  144. package/package.json +40 -44
@@ -42,8 +42,8 @@ export class RecursiveReasoner {
42
42
  /**
43
43
  * Find goals matching a pattern across all sessions
44
44
  */
45
- async analyzeGlobalProgress(pattern) {
46
- const goals = (await this.typedDb
45
+ async analyzeGlobalProgress(pattern, trxOrDb = this.db) {
46
+ const goals = (await trxOrDb
47
47
  .selectFrom(this.goalsTable)
48
48
  .selectAll()
49
49
  .where('description', 'like', `%${pattern}%`)
@@ -55,10 +55,10 @@ export class RecursiveReasoner {
55
55
  * Synthesize high-level lessons and cluster similar ones using Token-Weighted significance.
56
56
  * Pass 5: High-Throughput Semantic Analysis.
57
57
  */
58
- async synthesizeLessons() {
58
+ async synthesizeLessons(trxOrDb = this.db) {
59
59
  console.log('[RecursiveReasoner] Performing high-throughput weighted token clustering...');
60
60
  const reflectionsTable = this.config.reflectionsTable || 'agent_reflections';
61
- const results = (await this.typedDb
61
+ const results = (await trxOrDb
62
62
  .selectFrom(reflectionsTable)
63
63
  .select('lessons_learned')
64
64
  .where('lessons_learned', 'is not', null)
@@ -98,12 +98,12 @@ export class RecursiveReasoner {
98
98
  * Pass 6: Goal Cross-Pollination
99
99
  * Distill successful persona mutations into global systemic goals.
100
100
  */
101
- async crossPollinateGoals() {
101
+ async crossPollinateGoals(trxOrDb = this.db) {
102
102
  console.log('[RecursiveReasoner] Cross-pollinating successful persona breakthroughs into global goals...');
103
103
  const personasTable = this.config.personasTable || 'agent_personas';
104
104
  const goalsTable = this.config.goalsTable || 'agent_goals';
105
105
  // Find personas with 'stable' evolution status (proven breakthroughs)
106
- const breakthroughs = await this.typedDb
106
+ const breakthroughs = await trxOrDb
107
107
  .selectFrom(personasTable)
108
108
  .selectAll()
109
109
  .where('metadata', 'like', '%"evolution_status":"stable"%')
@@ -118,7 +118,7 @@ export class RecursiveReasoner {
118
118
  .filter(Boolean);
119
119
  if (descriptions.length === 0)
120
120
  return 0;
121
- const existingGoals = await this.typedDb
121
+ const existingGoals = await trxOrDb
122
122
  .selectFrom(goalsTable)
123
123
  .select('description')
124
124
  .where('description', 'in', descriptions)
@@ -128,7 +128,7 @@ export class RecursiveReasoner {
128
128
  for (const desc of descriptions) {
129
129
  if (!existingSet.has(desc)) {
130
130
  console.log(`[RecursiveReasoner] Distilling breakthrough into Global Goal: ${desc.slice(0, 50)}...`);
131
- await this.typedDb
131
+ await trxOrDb
132
132
  .insertInto(goalsTable)
133
133
  .values({
134
134
  session_id: 0, // System-level goal
@@ -150,9 +150,9 @@ export class RecursiveReasoner {
150
150
  /**
151
151
  * Detect contradictions in goals (e.g., opposing objectives).
152
152
  */
153
- async detectContradictions() {
153
+ async detectContradictions(trxOrDb = this.db) {
154
154
  console.log('[RecursiveReasoner] Detecting logical contradictions in systemic goals...');
155
- const activeGoals = (await this.typedDb
155
+ const activeGoals = (await trxOrDb
156
156
  .selectFrom(this.goalsTable)
157
157
  .selectAll()
158
158
  .where('status', '=', 'active')
@@ -1,5 +1,5 @@
1
1
  import type { Kysely } from '../../kysely.js';
2
- import type { AgenticConfig, AgentReflection } from '../../types/index.js';
2
+ import type { AgentReflection, AgenticConfig } from '../../types/index.js';
3
3
  /**
4
4
  * ReflectionEngine enables agents to perform "post-mortems" on sessions,
5
5
  * storing lessons learned and evaluating outcomes to improve future performance.
@@ -12,7 +12,7 @@ export declare class ReflectionEngine {
12
12
  /**
13
13
  * Record a reflection for a session
14
14
  */
15
- reflect(sessionId: string | number, outcome: AgentReflection['outcome'], lessonsLearned: string, suggestedActions?: string[], metadata?: Record<string, any>): Promise<AgentReflection>;
15
+ reflect(sessionId: string | number, outcome: AgentReflection['outcome'], lessonsLearned: string, suggestedActions?: string[], metadata?: Record<string, any>, trxOrDb?: any): Promise<AgentReflection>;
16
16
  /**
17
17
  * Get reflections for a specific session
18
18
  */
@@ -15,8 +15,8 @@ export class ReflectionEngine {
15
15
  /**
16
16
  * Record a reflection for a session
17
17
  */
18
- async reflect(sessionId, outcome, lessonsLearned, suggestedActions, metadata) {
19
- const reflection = (await this.db
18
+ async reflect(sessionId, outcome, lessonsLearned, suggestedActions, metadata, trxOrDb = this.db) {
19
+ const reflection = (await trxOrDb
20
20
  .insertInto(this.reflectionsTable)
21
21
  .values({
22
22
  session_id: sessionId,
@@ -1,5 +1,5 @@
1
1
  import type { Kysely } from '../../kysely.js';
2
- import type { AgenticConfig, AgentRitual } from '../../types/index.js';
2
+ import type { AgentRitual, AgenticConfig } from '../../types/index.js';
3
3
  import type { Cortex } from '../Cortex.js';
4
4
  /**
5
5
  * RitualOrchestrator handles the periodic execution of background tasks
@@ -18,11 +18,11 @@ export declare class RitualOrchestrator {
18
18
  /**
19
19
  * Run all pending rituals that are due
20
20
  */
21
- runPendingRituals(): Promise<number>;
21
+ runPendingRituals(trxOrDb?: any): Promise<number>;
22
22
  /**
23
23
  * Execute a specific ritual
24
24
  */
25
- executeRitual(ritual: AgentRitual): Promise<void>;
25
+ executeRitual(ritual: AgentRitual, trxOrDb?: any): Promise<void>;
26
26
  /**
27
27
  * Calculate next run with Adaptive Backoff for failures
28
28
  */
@@ -37,10 +37,10 @@ export class RitualOrchestrator {
37
37
  /**
38
38
  * Run all pending rituals that are due
39
39
  */
40
- async runPendingRituals() {
40
+ async runPendingRituals(trxOrDb = this.db) {
41
41
  const now = new Date();
42
42
  const lockTimeout = new Date(now.getTime() + 600000); // 10 min lock by default
43
- const pending = await this.db.transaction().execute(async (trx) => {
43
+ const runner = async (trx) => {
44
44
  const due = (await trx
45
45
  .selectFrom(this.ritualsTable)
46
46
  .selectAll()
@@ -62,20 +62,23 @@ export class RitualOrchestrator {
62
62
  .execute();
63
63
  }
64
64
  return due;
65
- });
65
+ };
66
+ const pending = (trxOrDb !== this.db)
67
+ ? await runner(trxOrDb)
68
+ : await this.db.transaction().execute(runner);
66
69
  if (pending.length === 0)
67
70
  return 0;
68
71
  console.log(`[RitualOrchestrator] Found ${pending.length} pending rituals due. Locking for execution...`);
69
72
  for (const ritual of pending) {
70
- // Execute out-of-transaction to avoid long-held locks if sub-tasks are slow
71
- await this.executeRitual(ritual);
73
+ // Execute with the same trxOrDb context
74
+ await this.executeRitual(ritual, trxOrDb);
72
75
  }
73
76
  return pending.length;
74
77
  }
75
78
  /**
76
79
  * Execute a specific ritual
77
80
  */
78
- async executeRitual(ritual) {
81
+ async executeRitual(ritual, trxOrDb = this.db) {
79
82
  console.log(`[RitualOrchestrator] Executing ritual: ${ritual.name} (${ritual.type})`);
80
83
  const ritualMetadata = {
81
84
  ...ritual.metadata,
@@ -92,7 +95,7 @@ export class RitualOrchestrator {
92
95
  let offset = 0;
93
96
  const batchSize = 100; // Audit Phase 17: Paginated session processing
94
97
  while (true) {
95
- const activeSessions = await this.db
98
+ const activeSessions = await trxOrDb
96
99
  .selectFrom(sessionsTable)
97
100
  .select('id')
98
101
  .where('status', '=', 'active')
@@ -102,7 +105,7 @@ export class RitualOrchestrator {
102
105
  if (activeSessions.length === 0)
103
106
  break;
104
107
  for (const session of activeSessions) {
105
- const countResult = (await this.db
108
+ const countResult = (await trxOrDb
106
109
  .selectFrom(messagesTable)
107
110
  .select((eb) => eb.fn.countAll().as('count'))
108
111
  .where('session_id', '=', session.id)
@@ -150,7 +153,7 @@ export class RitualOrchestrator {
150
153
  // Update ritual status, unlock, and schedule next run
151
154
  const frequency = ritual.frequency || 'daily';
152
155
  const nextRun = this.calculateNextRun(frequency, success ? 0 : ritualMetadata.failureCount);
153
- await this.db
156
+ await trxOrDb
154
157
  .updateTable(this.ritualsTable)
155
158
  .set({
156
159
  status: success ? 'success' : 'failure',
@@ -25,7 +25,7 @@ export declare class SelfEvolution {
25
25
  evolve(ddl: string, options?: {
26
26
  name?: string;
27
27
  metadata?: Record<string, any>;
28
- }): Promise<void>;
28
+ }, trxOrDb?: any): Promise<void>;
29
29
  /**
30
30
  * Regenerate and write types to file if configured.
31
31
  */
@@ -26,28 +26,27 @@ export class SelfEvolution {
26
26
  * Ensure core agentic tables have telemetry columns like 'accessed_at'
27
27
  */
28
28
  async ensureTelemetryColumns() {
29
- const tables = [
29
+ const tableNames = [
30
30
  this.config.agentic?.sessionsTable || 'agent_sessions',
31
31
  this.config.agentic?.messagesTable || 'agent_messages',
32
32
  this.config.agentic?.memoriesTable || 'agent_memories',
33
33
  this.config.agentic?.goalsTable || 'agent_goals',
34
34
  this.config.agentic?.knowledgeTable || 'agent_knowledge_base',
35
35
  ];
36
- for (const table of tables) {
37
- try {
38
- const introspector = this.db.introspection;
39
- const tableInfo = await introspector
40
- .getTables()
41
- .then((ts) => ts.find((t) => t.name === table));
36
+ try {
37
+ const introspector = this.db.introspection;
38
+ const allTables = await introspector.getTables();
39
+ for (const tableName of tableNames) {
40
+ const tableInfo = allTables.find((t) => t.name === tableName);
42
41
  if (tableInfo &&
43
42
  !tableInfo.columns.some((c) => c.name === 'accessed_at')) {
44
- console.log(`[SelfEvolution] Adding 'accessed_at' column to ${table}`);
45
- await sql `ALTER TABLE ${sql.table(table)} ADD COLUMN accessed_at TIMESTAMP`.execute(this.db);
43
+ console.log(`[SelfEvolution] Adding 'accessed_at' column to ${tableName}`);
44
+ await sql `ALTER TABLE ${sql.table(tableName)} ADD COLUMN accessed_at TIMESTAMP`.execute(this.db);
46
45
  }
47
46
  }
48
- catch (e) {
49
- console.warn(`[SelfEvolution] Failed to add telemetry column to ${table}:`, e);
50
- }
47
+ }
48
+ catch (e) {
49
+ console.warn(`[SelfEvolution] Failed to add telemetry columns:`, e);
51
50
  }
52
51
  }
53
52
  /**
@@ -98,12 +97,10 @@ export class SelfEvolution {
98
97
  /**
99
98
  * Apply a schema suggestion and instantly regenerate types
100
99
  */
101
- async evolve(ddl, options = {}) {
100
+ async evolve(ddl, options = {}, trxOrDb = this.db) {
102
101
  console.log(`[SelfEvolution] Applying structural change: ${ddl}`);
103
- await this.db.transaction().execute(async (trx) => {
102
+ const runner = async (trx) => {
104
103
  // 1. Apply the DDL change
105
- // Pass transaction to evolution helper if it supports it,
106
- // otherwise use trx.execute() directly for the DDL
107
104
  await trx.execute(sql.raw(ddl));
108
105
  // 1b. Log for potential rollback
109
106
  await trx
@@ -120,7 +117,13 @@ export class SelfEvolution {
120
117
  created_at: new Date(),
121
118
  })
122
119
  .execute();
123
- });
120
+ };
121
+ if (trxOrDb && trxOrDb !== this.db) {
122
+ await runner(trxOrDb);
123
+ }
124
+ else {
125
+ await this.db.transaction().execute(runner);
126
+ }
124
127
  // 2. Regenerate types
125
128
  await this.regenerateTypes();
126
129
  console.log(`[SelfEvolution] Schema evolved successfully.`);
@@ -239,7 +242,7 @@ export class SelfEvolution {
239
242
  return `ALTER TABLE ${addColumnMatch[1]} DROP COLUMN ${addColumnMatch[2]}`;
240
243
  }
241
244
  // Match patterns like: ALTER TABLE "table_name" DROP [COLUMN] "column_name"
242
- const dropColumnMatch = d.match(/ALTER TABLE\s+([^\s]+)\s+DROP\s+(?:COLUMN\s+)?([^\s\(\)]+)/i);
245
+ const dropColumnMatch = d.match(/ALTER TABLE\s+([^\s]+)\s+DROP\s+(?:COLUMN\s+)?([^\s\(\)]+)\s+([^\s]+)/i);
243
246
  if (dropColumnMatch) {
244
247
  // Note: Data is lost, but we can restore the structure
245
248
  return `ALTER TABLE ${dropColumnMatch[1]} ADD COLUMN ${dropColumnMatch[2]} TEXT`; // Default to TEXT if unknown
@@ -17,7 +17,7 @@ export declare class SelfTestRegistry {
17
17
  /**
18
18
  * Run all registered probes
19
19
  */
20
- runAllProbes(): Promise<{
20
+ runAllProbes(trxOrDb?: any): Promise<{
21
21
  name: string;
22
22
  success: boolean;
23
23
  error?: string;
@@ -1,4 +1,5 @@
1
1
  /// <reference types="./SelfTestRegistry.d.ts" />
2
+ import { withLock } from '../util/db-utils.js';
2
3
  /**
3
4
  * SelfTestRegistry allows agents to self-register verification probes
4
5
  * that ensure autonomous changes don't violate core logic.
@@ -34,8 +35,8 @@ export class SelfTestRegistry {
34
35
  /**
35
36
  * Run all registered probes
36
37
  */
37
- async runAllProbes() {
38
- const probes = (await this.db
38
+ async runAllProbes(trxOrDb = this.db) {
39
+ const probes = (await trxOrDb
39
40
  .selectFrom('agent_logic_probes')
40
41
  .selectAll()
41
42
  .execute());
@@ -45,22 +46,21 @@ export class SelfTestRegistry {
45
46
  try {
46
47
  let success = false;
47
48
  if (probe.script.startsWith('audit:')) {
48
- success = await this.runAuditAction(probe.script.split(':')[1]);
49
+ success = await this.runAuditAction(probe.script.split(':')[1], trxOrDb);
49
50
  }
50
51
  else {
51
52
  // Master Sentinel Pass: Dynamic Probe Evaluation
52
53
  // If not a hardcoded audit, use LLM to interpret the script against DB state
53
- success = await this.dynamicEvaluation(probe);
54
+ success = await this.dynamicEvaluation(probe, trxOrDb);
54
55
  }
55
56
  results.push({ name: probe.name, success });
56
- await this.db.transaction().execute(async (trx) => {
57
+ const updateRunner = async (trx) => {
57
58
  // Audit Phase 13: Lock row before updating last_status
58
- await trx
59
+ const query = trx
59
60
  .selectFrom('agent_logic_probes')
60
61
  .select('id')
61
- .where('id', '=', probe.id)
62
- .forUpdate()
63
- .executeTakeFirst();
62
+ .where('id', '=', probe.id);
63
+ await withLock(query, trx).executeTakeFirst();
64
64
  await trx
65
65
  .updateTable('agent_logic_probes')
66
66
  .set({
@@ -69,7 +69,15 @@ export class SelfTestRegistry {
69
69
  })
70
70
  .where('id', '=', probe.id)
71
71
  .execute();
72
- });
72
+ };
73
+ if (trxOrDb && trxOrDb !== this.db) {
74
+ await updateRunner(trxOrDb);
75
+ }
76
+ else {
77
+ await this.db.transaction().execute(async (trx) => {
78
+ await updateRunner(trx);
79
+ });
80
+ }
73
81
  }
74
82
  catch (e) {
75
83
  results.push({ name: probe.name, success: false, error: String(e) });
@@ -77,7 +85,7 @@ export class SelfTestRegistry {
77
85
  }
78
86
  return results;
79
87
  }
80
- async runAuditAction(action) {
88
+ async runAuditAction(action, trxOrDb = this.db) {
81
89
  switch (action) {
82
90
  case 'check_schema_consistency':
83
91
  const tables = await this.db.introspection.getTables();
@@ -93,7 +101,7 @@ export class SelfTestRegistry {
93
101
  return missing.length === 0;
94
102
  case 'check_memory_integrity':
95
103
  const memoriesTable = this.config.memoriesTable || 'agent_memories';
96
- const invalidMemories = await this.db
104
+ const invalidMemories = await trxOrDb
97
105
  .selectFrom(memoriesTable)
98
106
  .select('id')
99
107
  .where('embedding', 'is', null)
@@ -102,7 +110,7 @@ export class SelfTestRegistry {
102
110
  case 'check_session_coherence':
103
111
  const sessionsTable = this.config.sessionsTable || 'agent_sessions';
104
112
  const messagesTable = this.config.messagesTable || 'agent_messages';
105
- const emptySessions = await this.db
113
+ const emptySessions = await trxOrDb
106
114
  .selectFrom(sessionsTable)
107
115
  .leftJoin(messagesTable, `${sessionsTable}.id`, `${messagesTable}.session_id`)
108
116
  .select(`${sessionsTable}.id as sid`)
@@ -113,7 +121,7 @@ export class SelfTestRegistry {
113
121
  const knowledgeTable = this.config.knowledgeTable || 'agent_knowledge_base';
114
122
  const actionsTable = this.config.actionsTable || 'agent_actions';
115
123
  const sessionsTbl = this.config.sessionsTable || 'agent_sessions';
116
- const orphanedKnowledge = await this.db
124
+ const orphanedKnowledge = await trxOrDb
117
125
  .selectFrom(knowledgeTable)
118
126
  .where('source_session_id', 'is not', null)
119
127
  .where((eb) => eb.not(eb.exists(eb
@@ -121,7 +129,7 @@ export class SelfTestRegistry {
121
129
  .select('id')
122
130
  .whereRef(`${knowledgeTable}.source_session_id`, '=', `${sessionsTbl}.id`))))
123
131
  .execute();
124
- const orphanedActions = await this.db
132
+ const orphanedActions = await trxOrDb
125
133
  .selectFrom(actionsTable)
126
134
  .where((eb) => eb.not(eb.exists(eb
127
135
  .selectFrom(sessionsTbl)
@@ -131,7 +139,7 @@ export class SelfTestRegistry {
131
139
  return orphanedKnowledge.length === 0 && orphanedActions.length === 0;
132
140
  case 'check_performance_drift':
133
141
  const metricsTbl = this.config.metricsTable || 'agent_metrics';
134
- const recentMetrics = (await this.db
142
+ const recentMetrics = (await trxOrDb
135
143
  .selectFrom(metricsTbl)
136
144
  .select('execution_time')
137
145
  .orderBy('created_at', 'desc')
@@ -140,7 +148,7 @@ export class SelfTestRegistry {
140
148
  if (recentMetrics.length < 5)
141
149
  return true;
142
150
  const avgRecent = recentMetrics.reduce((sum, m) => sum + (m.execution_time || 0), 0) / recentMetrics.length;
143
- const baselineMetrics = (await this.db
151
+ const baselineMetrics = (await trxOrDb
144
152
  .selectFrom(metricsTbl)
145
153
  .select('execution_time')
146
154
  .orderBy('created_at', 'desc')
@@ -158,12 +166,12 @@ export class SelfTestRegistry {
158
166
  /**
159
167
  * Interpret custom probe logic by providing the LLM with relevant database snapshots.
160
168
  */
161
- async dynamicEvaluation(probe) {
169
+ async dynamicEvaluation(probe, trxOrDb = this.db) {
162
170
  const model = this.cortex.llmFast || this.cortex.llm;
163
171
  if (!model)
164
172
  return true; // Safety fallback if no AI is available
165
173
  // Provide a small sample of metrics and actions to allow for semantic reasoning
166
- const sampleMetrics = await this.db.selectFrom(this.config.metricsTable || 'agent_metrics').limit(10).execute();
174
+ const sampleMetrics = await trxOrDb.selectFrom(this.config.metricsTable || 'agent_metrics').limit(10).execute();
167
175
  const prompt = `
168
176
  You are a Logic Verification Engine for NOORMME.
169
177
  TESTRUN: "${probe.name}"
@@ -37,30 +37,30 @@ export declare class SovereignMetrics {
37
37
  agentId?: string;
38
38
  unit?: string;
39
39
  metadata?: Record<string, any>;
40
- }): Promise<AgentMetric>;
40
+ }, trxOrDb?: any): Promise<AgentMetric>;
41
41
  /**
42
42
  * Get average value of a metric over time
43
43
  */
44
- getAverageMetric(metricName: string): Promise<number>;
44
+ getAverageMetric(metricName: string, trxOrDb?: any): Promise<number>;
45
45
  /**
46
46
  * Get comprehensive stats for a metric (min, max, avg, count).
47
47
  */
48
48
  getMetricStats(metricName: string, options?: {
49
49
  agentId?: string;
50
50
  sessionId?: string | number;
51
- }): Promise<MetricStats>;
51
+ }, trxOrDb?: any): Promise<MetricStats>;
52
52
  /**
53
53
  * Get recent metrics for analysis
54
54
  */
55
- getRecentMetrics(limit?: number): Promise<AgentMetric[]>;
55
+ getRecentMetrics(limit?: number, trxOrDb?: any): Promise<AgentMetric[]>;
56
56
  /**
57
57
  * Get metrics filtered by agent ID.
58
58
  */
59
- getMetricsByAgent(agentId: string, limit?: number): Promise<AgentMetric[]>;
59
+ getMetricsByAgent(agentId: string, limit?: number, trxOrDb?: any): Promise<AgentMetric[]>;
60
60
  /**
61
61
  * Get metrics filtered by session ID.
62
62
  */
63
- getMetricsBySession(sessionId: string | number, limit?: number): Promise<AgentMetric[]>;
63
+ getMetricsBySession(sessionId: string | number, limit?: number, trxOrDb?: any): Promise<AgentMetric[]>;
64
64
  private parseMetric;
65
65
  }
66
66
  export {};
@@ -18,8 +18,8 @@ export class SovereignMetrics {
18
18
  /**
19
19
  * Record a metric point
20
20
  */
21
- async recordMetric(metricName, metricValue, options = {}) {
22
- const metric = (await this.db
21
+ async recordMetric(metricName, metricValue, options = {}, trxOrDb = this.db) {
22
+ const metric = (await trxOrDb
23
23
  .insertInto(this.metricsTable)
24
24
  .values({
25
25
  session_id: options.sessionId ?? null,
@@ -37,8 +37,8 @@ export class SovereignMetrics {
37
37
  /**
38
38
  * Get average value of a metric over time
39
39
  */
40
- async getAverageMetric(metricName) {
41
- const result = await this.typedDb
40
+ async getAverageMetric(metricName, trxOrDb = this.db) {
41
+ const result = await trxOrDb
42
42
  .selectFrom(this.metricsTable)
43
43
  .select((eb) => eb.fn.avg('metric_value').as('avgValue'))
44
44
  .where('metric_name', '=', metricName)
@@ -48,8 +48,8 @@ export class SovereignMetrics {
48
48
  /**
49
49
  * Get comprehensive stats for a metric (min, max, avg, count).
50
50
  */
51
- async getMetricStats(metricName, options = {}) {
52
- let query = this.typedDb
51
+ async getMetricStats(metricName, options = {}, trxOrDb = this.db) {
52
+ let query = trxOrDb
53
53
  .selectFrom(this.metricsTable)
54
54
  .select((eb) => [
55
55
  eb.fn.min('metric_value').as('min'),
@@ -75,8 +75,8 @@ export class SovereignMetrics {
75
75
  /**
76
76
  * Get recent metrics for analysis
77
77
  */
78
- async getRecentMetrics(limit = 50) {
79
- const list = (await this.typedDb
78
+ async getRecentMetrics(limit = 50, trxOrDb = this.db) {
79
+ const list = (await trxOrDb
80
80
  .selectFrom(this.metricsTable)
81
81
  .selectAll()
82
82
  .orderBy('created_at', 'desc')
@@ -87,8 +87,8 @@ export class SovereignMetrics {
87
87
  /**
88
88
  * Get metrics filtered by agent ID.
89
89
  */
90
- async getMetricsByAgent(agentId, limit = 50) {
91
- const list = (await this.typedDb
90
+ async getMetricsByAgent(agentId, limit = 50, trxOrDb = this.db) {
91
+ const list = (await trxOrDb
92
92
  .selectFrom(this.metricsTable)
93
93
  .selectAll()
94
94
  .where('agent_id', '=', agentId)
@@ -100,8 +100,8 @@ export class SovereignMetrics {
100
100
  /**
101
101
  * Get metrics filtered by session ID.
102
102
  */
103
- async getMetricsBySession(sessionId, limit = 50) {
104
- const list = (await this.typedDb
103
+ async getMetricsBySession(sessionId, limit = 50, trxOrDb = this.db) {
104
+ const list = (await trxOrDb
105
105
  .selectFrom(this.metricsTable)
106
106
  .selectAll()
107
107
  .where('session_id', '=', sessionId)
@@ -1,28 +1,6 @@
1
1
  import type { Kysely } from '../../kysely.js';
2
2
  import type { AgenticConfig, AgentPersona } from '../../types/index.js';
3
3
  import type { Cortex } from '../Cortex.js';
4
- interface PersonaTable {
5
- id: number | string;
6
- name: string;
7
- role: string | null;
8
- capabilities: string | null;
9
- policies: string | null;
10
- metadata: string | null;
11
- created_at: string | Date;
12
- updated_at: string | Date;
13
- }
14
- export interface MetricTable {
15
- id: number | string;
16
- metric_name: string;
17
- metric_value: number;
18
- unit: string | null;
19
- metadata: string | null;
20
- created_at: string | Date;
21
- }
22
- export interface StrategyDatabase {
23
- agent_personas: PersonaTable;
24
- agent_metrics: MetricTable;
25
- }
26
4
  export interface PerformanceReport {
27
5
  personaId: string | number;
28
6
  successRate: number;
@@ -30,14 +8,6 @@ export interface PerformanceReport {
30
8
  sampleSize: number;
31
9
  recommendation: 'maintain' | 'optimize_efficiency' | 'optimize_accuracy' | 'critical_intervention';
32
10
  }
33
- export interface PersonaMutation {
34
- id: string;
35
- timestamp: number;
36
- type: 'role_update' | 'policy_update' | 'capability_update';
37
- previousState: Partial<AgentPersona>;
38
- newState: Partial<AgentPersona>;
39
- reason: string;
40
- }
41
11
  /**
42
12
  * StrategicPlanner proactively suggests mutation to agent personas
43
13
  * based on performance trends observed in SovereignMetrics.
@@ -48,40 +18,26 @@ export declare class StrategicPlanner {
48
18
  private config;
49
19
  private personasTable;
50
20
  private metricsTable;
21
+ private analyst;
22
+ private engine;
23
+ private verificator;
51
24
  constructor(db: Kysely<any>, cortex: Cortex, config?: AgenticConfig);
52
- private get typedDb();
53
25
  /**
54
26
  * Analyze performance for all personas and apply mutations where necessary.
55
27
  */
56
- mutateStrategy(): Promise<string[]>;
57
- /**
58
- * Directly mutate a persona and put it into 'verifying' status.
59
- * Performs a pre-flight conflict check and injects distilled lessons.
60
- */
61
- private applyDirectMutation;
28
+ mutateStrategy(trxOrDb?: any): Promise<string[]>;
62
29
  /**
63
- * Check if a persona in verification should be stabilized or rolled back.
64
- * Uses dynamic statistical variance and adaptive meta-tuning.
30
+ * Directly mutate a persona.
65
31
  */
66
- private verifyEvolution;
32
+ evolvePersona(persona: AgentPersona, report: PerformanceReport, trxOrDb?: any): Promise<string | null>;
67
33
  /**
68
- * Analyze recent actions for specific failure patterns.
69
- */
70
- private analyzeFailurePatterns;
71
- /**
72
- * Generate a performance report for a specific persona.
73
- * Uses dynamic satisfaction thresholds based on global population stats (Phase 6).
74
- */
75
- analyzePersona(id: string | number): Promise<PerformanceReport>;
76
- /**
77
- * Evolve a persona directly based on performance.
34
+ * Revert the last mutation for a persona.
78
35
  */
79
- evolvePersona(persona: AgentPersona, report: PerformanceReport): Promise<string | null>;
36
+ rollbackPersona(id: string | number, trxOrDb?: any): Promise<string>;
80
37
  /**
81
- * Revert the last mutation for a persona.
38
+ * Analyze a persona's performance report.
82
39
  */
83
- rollbackPersona(id: string | number): Promise<string>;
40
+ analyzePersona(id: string | number, trxOrDb?: any): Promise<PerformanceReport>;
84
41
  private sanitizeRole;
85
42
  private parsePersona;
86
43
  }
87
- export {};