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
@@ -17,19 +17,19 @@ export declare class AblationEngine {
17
17
  /**
18
18
  * Identify "Zombies": Items that have never been retrieved/hit and are old.
19
19
  */
20
- pruneZombies(thresholdDays?: number): Promise<number>;
20
+ pruneZombies(thresholdDays?: number, trxOrDb?: any): Promise<number>;
21
21
  /**
22
22
  * Monitor Performance and perform Intelligent Rollbacks.
23
23
  * Prioritizes recovery of items with highest historical hit counts.
24
24
  */
25
- monitorAblationPerformance(): Promise<{
25
+ monitorAblationPerformance(trxOrDb?: any): Promise<{
26
26
  status: 'stable' | 'degraded';
27
27
  recoveredCount: number;
28
28
  }>;
29
29
  /**
30
30
  * Conduct an "Ablation Test": Temporarily disable a knowledge item.
31
31
  */
32
- testAblation(id: string | number): Promise<boolean>;
32
+ testAblation(id: string | number, trxOrDb?: any): Promise<boolean>;
33
33
  /**
34
34
  * Restore an ablated knowledge item to its original state.
35
35
  */
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AblationEngine = void 0;
4
+ const db_utils_js_1 = require("../util/db-utils.js");
4
5
  /**
5
6
  * AblationEngine identifies and removes unused or redundant data
6
7
  * to keep the agent's context window and database lean.
@@ -26,13 +27,13 @@ class AblationEngine {
26
27
  /**
27
28
  * Identify "Zombies": Items that have never been retrieved/hit and are old.
28
29
  */
29
- async pruneZombies(thresholdDays = 30) {
30
+ async pruneZombies(thresholdDays = 30, trxOrDb = this.db) {
30
31
  const cutoff = new Date(Date.now() - thresholdDays * 24 * 3600000);
31
32
  let totalPruned = 0;
32
- return await this.db.transaction().execute(async (trx) => {
33
+ const runner = async (trx) => {
33
34
  // 1. Prune Knowledge (with dependency check and pagination)
34
35
  // Audit Phase 9: Paginated selection to prevent OOM
35
- const knowledgeToPrune = await trx
36
+ const query = trx
36
37
  .selectFrom(this.knowledgeTable)
37
38
  .selectAll()
38
39
  .where((eb) => eb.or([
@@ -43,9 +44,8 @@ class AblationEngine {
43
44
  .where('updated_at', '<', cutoff)
44
45
  .where('id', 'not in', (eb) => eb.selectFrom(this.linksTable).select('source_id'))
45
46
  .where('id', 'not in', (eb) => eb.selectFrom(this.linksTable).select('target_id'))
46
- .limit(500) // Audit Phase 9: Batch limit
47
- .forUpdate() // Audit Phase 9: Lock candidates
48
- .execute();
47
+ .limit(500); // Audit Phase 9: Batch limit
48
+ const knowledgeToPrune = await (0, db_utils_js_1.withLock)(query, trx).execute();
49
49
  if (knowledgeToPrune.length > 0) {
50
50
  const candidates = knowledgeToPrune.map((k) => this.cortex.knowledge['parseKnowledge'](k));
51
51
  const idsToDelete = [];
@@ -80,16 +80,22 @@ class AblationEngine {
80
80
  console.log(`[AblationEngine] Pruned ${totalPruned} zombie items older than ${thresholdDays} days.`);
81
81
  }
82
82
  return totalPruned;
83
- });
83
+ };
84
+ if (trxOrDb && trxOrDb !== this.db) {
85
+ return await runner(trxOrDb);
86
+ }
87
+ else {
88
+ return await this.db.transaction().execute(runner);
89
+ }
84
90
  }
85
91
  /**
86
92
  * Monitor Performance and perform Intelligent Rollbacks.
87
93
  * Prioritizes recovery of items with highest historical hit counts.
88
94
  */
89
- async monitorAblationPerformance() {
90
- return await this.db.transaction().execute(async (trx) => {
91
- const baseline = await this.cortex.metrics.getAverageMetric('success_rate');
92
- const stats = await this.cortex.metrics.getMetricStats('success_rate');
95
+ async monitorAblationPerformance(trxOrDb = this.db) {
96
+ const runner = async (trx) => {
97
+ const baseline = await this.cortex.metrics.getAverageMetric('success_rate', trx);
98
+ const stats = await this.cortex.metrics.getMetricStats('success_rate', {}, trx);
93
99
  // If current average is significantly lower than overall average
94
100
  if (stats.count > 10 && stats.avg < baseline * 0.8) {
95
101
  console.warn(`[AblationEngine] PERFORMANCE DEGRADATION DETECTED (Avg: ${stats.avg}, Baseline: ${baseline}). Triggering targeted recovery.`);
@@ -117,20 +123,25 @@ class AblationEngine {
117
123
  return { status: 'degraded', recoveredCount };
118
124
  }
119
125
  return { status: 'stable', recoveredCount: 0 };
120
- });
126
+ };
127
+ if (trxOrDb && trxOrDb !== this.db) {
128
+ return await runner(trxOrDb);
129
+ }
130
+ else {
131
+ return await this.db.transaction().execute(runner);
132
+ }
121
133
  }
122
134
  /**
123
135
  * Conduct an "Ablation Test": Temporarily disable a knowledge item.
124
136
  */
125
- async testAblation(id) {
137
+ async testAblation(id, trxOrDb = this.db) {
126
138
  console.log(`[AblationEngine] Conducting ablation test on item ${id}`);
127
- return await this.db.transaction().execute(async (trx) => {
128
- const item = (await trx
139
+ const runner = async (trx) => {
140
+ const query = trx
129
141
  .selectFrom(this.knowledgeTable)
130
142
  .selectAll()
131
- .where('id', '=', id)
132
- .forUpdate() // Audit Phase 9: Atomic lock for test initiation
133
- .executeTakeFirst());
143
+ .where('id', '=', id);
144
+ const item = (await (0, db_utils_js_1.withLock)(query, trx).executeTakeFirst());
134
145
  if (!item)
135
146
  return false;
136
147
  const metadata = typeof item.metadata === 'string'
@@ -140,7 +151,7 @@ class AblationEngine {
140
151
  `Temporary confidence reduction to evaluate reasoning impact.`,
141
152
  `Original confidence: ${item.confidence}`,
142
153
  `Historical hits: ${metadata.hit_count || 0}`
143
- ]);
154
+ ], undefined, trx);
144
155
  await trx
145
156
  .updateTable(this.knowledgeTable)
146
157
  .set({
@@ -155,19 +166,25 @@ class AblationEngine {
155
166
  .where('id', '=', id)
156
167
  .execute();
157
168
  return true;
158
- });
169
+ };
170
+ if (trxOrDb && trxOrDb !== this.db) {
171
+ await runner(trxOrDb);
172
+ }
173
+ else {
174
+ await this.db.transaction().execute(runner);
175
+ }
176
+ return true;
159
177
  }
160
178
  /**
161
179
  * Restore an ablated knowledge item to its original state.
162
180
  */
163
181
  async recoverAblatedItem(id, trx) {
164
182
  const recoveryStep = async (t) => {
165
- const item = (await t
183
+ const query = t
166
184
  .selectFrom(this.knowledgeTable)
167
185
  .selectAll()
168
- .where('id', '=', id)
169
- .forUpdate() // Audit Phase 9: Atomic lock for restoration
170
- .executeTakeFirst());
186
+ .where('id', '=', id);
187
+ const item = (await (0, db_utils_js_1.withLock)(query, t).executeTakeFirst());
171
188
  if (!item)
172
189
  return false;
173
190
  const metadata = typeof item.metadata === 'string'
@@ -14,7 +14,7 @@ export declare class ActionRefiner {
14
14
  /**
15
15
  * Analyze recent actions and propose improvements
16
16
  */
17
- refineActions(): Promise<string[]>;
17
+ refineActions(trxOrDb?: any): Promise<string[]>;
18
18
  /**
19
19
  * Propose a rule to reflect on a specific tool usage
20
20
  */
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ActionRefiner = void 0;
4
+ const db_utils_js_1 = require("../util/db-utils.js");
4
5
  /**
5
6
  * ActionRefiner analyzes the ActionJournal to find patterns in failures
6
7
  * and suggests new CognitiveRules to improve agent performance.
@@ -19,12 +20,12 @@ class ActionRefiner {
19
20
  /**
20
21
  * Analyze recent actions and propose improvements
21
22
  */
22
- async refineActions() {
23
+ async refineActions(trxOrDb = this.db) {
23
24
  const recommendations = [];
24
25
  // 1. Find tools with high failure rates (Last 24h Window)
25
26
  // Audit Phase 14: Sliding window to prevent global table scans
26
27
  const windowStart = new Date(Date.now() - 24 * 60 * 60 * 1000);
27
- const failureStats = (await this.db
28
+ const failureStats = (await trxOrDb
28
29
  .selectFrom(this.actionsTable)
29
30
  .select('tool_name')
30
31
  .select((eb) => eb.fn.count('id').as('total'))
@@ -43,11 +44,11 @@ class ActionRefiner {
43
44
  if (rate > failureRateThreshold && total > minActionBatch) {
44
45
  recommendations.push(`Tool '${stat.tool_name}' has a ${Math.round(rate * 100)}% failure rate. Suggesting automatic reflection rule.`);
45
46
  // Automatically propose a rule to reflect on this tool's usage
46
- await this.proposeReflectionRule(stat.tool_name);
47
+ await this.proposeReflectionRule(stat.tool_name, trxOrDb);
47
48
  }
48
49
  }
49
50
  // 2. Discover missing capabilities based on error patterns (Last 24h)
50
- const missingCapabilities = (await this.db
51
+ const missingCapabilities = (await trxOrDb
51
52
  .selectFrom(this.actionsTable)
52
53
  .select('tool_name')
53
54
  .where('status', '=', 'failure')
@@ -62,25 +63,24 @@ class ActionRefiner {
62
63
  .execute());
63
64
  for (const row of missingCapabilities) {
64
65
  recommendations.push(`Detected repeated access/existence failures for tool '${row.tool_name}'. Proposing capability expansion.`);
65
- await this.proposeCapabilityUpdate(row.tool_name);
66
+ await this.proposeCapabilityUpdate(row.tool_name, trxOrDb);
66
67
  }
67
68
  return recommendations;
68
69
  }
69
70
  /**
70
71
  * Propose a rule to reflect on a specific tool usage
71
72
  */
72
- async proposeReflectionRule(toolName) {
73
+ async proposeReflectionRule(toolName, trxOrDb = this.db) {
73
74
  // Audit Phase 19: Atomic rule proposal via transaction + existence check
74
- await this.db.transaction().execute(async (trx) => {
75
+ const runner = async (trx) => {
75
76
  const rulesTable = this.cortex.config.rulesTable || 'agent_rules';
76
- const existing = await trx
77
+ const query = trx
77
78
  .selectFrom(rulesTable)
78
79
  .select('id')
79
- .where('tableName', '=', 'agent_actions')
80
+ .where('table_name', '=', 'agent_actions')
80
81
  .where('operation', '=', 'insert')
81
- .where('metadata', 'like', `%\"targetTool\":\"${toolName}\"%`)
82
- .forUpdate() // Lock to prevent concurrent proposals
83
- .executeTakeFirst();
82
+ .where('metadata', 'like', `%\"targetTool\":\"${toolName}\"%`);
83
+ const existing = await (0, db_utils_js_1.withLock)(query, trx).executeTakeFirst();
84
84
  if (!existing) {
85
85
  console.log(`[ActionRefiner] Proposing reflection rule for tool: ${toolName}`);
86
86
  await this.cortex.rules.defineRule('agent_actions', 'insert', 'audit', {
@@ -90,17 +90,23 @@ class ActionRefiner {
90
90
  },
91
91
  }, trx); // Pass transaction object
92
92
  }
93
- });
93
+ };
94
+ if (trxOrDb && trxOrDb !== this.db) {
95
+ await runner(trxOrDb);
96
+ }
97
+ else {
98
+ await this.db.transaction().execute((trx) => runner(trx));
99
+ }
94
100
  }
95
101
  /**
96
102
  * Propose an update to capabilities
97
103
  */
98
- async proposeCapabilityUpdate(toolName) {
104
+ async proposeCapabilityUpdate(toolName, trxOrDb = this.db) {
99
105
  console.log(`[ActionRefiner] Proposing capability expansion for tool: ${toolName}`);
100
106
  await this.cortex.reflections.reflect('system', 'failure', `Architectural Gap: Missing Capability for '${toolName}'`, [
101
107
  `Identified repeated failures using tool '${toolName}'.`,
102
108
  `Resolution: Inspect permission sets and ensure the tool is correctly registered in the CapabilityManager.`,
103
- ]);
109
+ ], undefined, trxOrDb);
104
110
  }
105
111
  }
106
112
  exports.ActionRefiner = ActionRefiner;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ConflictResolver = void 0;
4
4
  const similarity_js_1 = require("../../util/similarity.js");
5
+ const db_utils_js_1 = require("../util/db-utils.js");
5
6
  /**
6
7
  * ConflictResolver identifies and resolves logical inconsistencies
7
8
  * in the agent's cognitive rules and behavior policies.
@@ -85,14 +86,14 @@ class ConflictResolver {
85
86
  async resolveConflict(tableName, operation) {
86
87
  console.log(`[ConflictResolver] Resolving conflict for ${tableName}:${operation}`);
87
88
  return await this.db.transaction().execute(async (trx) => {
88
- const rules = (await trx
89
+ const query = trx
89
90
  .selectFrom(this.rulesTable)
90
91
  .selectAll()
91
92
  .where('table_name', '=', tableName)
92
93
  .where('operation', '=', operation)
93
94
  .where('is_enabled', '=', true)
94
- .orderBy('created_at', 'desc')
95
- .forUpdate() // Audit Phase 10: Atomic resolution lock
95
+ .orderBy('created_at', 'desc');
96
+ const rules = (await (0, db_utils_js_1.withLock)(query, trx) // Audit Phase 10: Atomic resolution lock
96
97
  .execute());
97
98
  if (rules.length <= 1)
98
99
  return;
@@ -64,7 +64,8 @@ class EvolutionRitual {
64
64
  // Find domains that are currently "hot" (high density of recent knowledge)
65
65
  // Refactored Phase 13: Paginated scanning to handle large knowledge bursts
66
66
  const domainScores = new Map();
67
- const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000);
67
+ const lookbackHours = this.config.evolutionLookbackHours || 24;
68
+ const cutoff = new Date(Date.now() - lookbackHours * 60 * 60 * 1000);
68
69
  let offset = 0;
69
70
  const limit = 1000;
70
71
  while (true) {
@@ -13,7 +13,7 @@ export declare class EvolutionaryPilot {
13
13
  /**
14
14
  * Run a self-improvement cycle based on dynamic baselining
15
15
  */
16
- runSelfImprovementCycle(): Promise<{
16
+ runSelfImprovementCycle(trxOrDb?: any): Promise<{
17
17
  evolved: boolean;
18
18
  changes: string[];
19
19
  }>;
@@ -18,7 +18,7 @@ class EvolutionaryPilot {
18
18
  /**
19
19
  * Run a self-improvement cycle based on dynamic baselining
20
20
  */
21
- async runSelfImprovementCycle() {
21
+ async runSelfImprovementCycle(trxOrDb = this.db) {
22
22
  console.log('[EvolutionaryPilot] Initiating self-improvement cycle with full-spectrum baselining...');
23
23
  const changes = [];
24
24
  let evolved = false;
@@ -30,7 +30,7 @@ class EvolutionaryPilot {
30
30
  'trust_signal',
31
31
  ];
32
32
  const samplingCount = this.config.evolution?.samplingCount || 100;
33
- const recentMetrics = await this.cortex.metrics.getRecentMetrics(samplingCount);
33
+ const recentMetrics = await this.cortex.metrics.getRecentMetrics(samplingCount, trxOrDb);
34
34
  for (const metricName of metrics) {
35
35
  // Audit Phase 17: Bounded metric slice for scale-safe baselining
36
36
  const values = recentMetrics
@@ -43,14 +43,14 @@ class EvolutionaryPilot {
43
43
  const minSamples = this.config.evolution?.minSamples || 5;
44
44
  if (values.length < minSamples)
45
45
  continue;
46
- const policies = await this.cortex.policies.getActivePolicies();
46
+ const policies = await this.cortex.policies.getActivePolicies(trxOrDb);
47
47
  const latencyZ = policies.find(p => p.name === 'latency_drift_z')?.definition?.threshold || 2.0;
48
48
  const latencyMean = policies.find(p => p.name === 'latency_mean_ceiling')?.definition?.threshold || 1000;
49
49
  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)}`);
50
50
  // 2. Trigger Evolution based on metric-specific thresholds
51
51
  if (metricName === 'query_latency' &&
52
52
  (stats.zScore > latencyZ || stats.mean > latencyMean)) {
53
- const result = await this.optimizeLatency();
53
+ const result = await this.optimizeLatency(trxOrDb);
54
54
  if (result) {
55
55
  changes.push(...result);
56
56
  evolved = true;
@@ -61,7 +61,7 @@ class EvolutionaryPilot {
61
61
  if (metricName === 'success_rate' &&
62
62
  (stats.zScore < successZ || stats.mean < successMean)) {
63
63
  console.warn(`[EvolutionaryPilot] Success rate collapse detected (${stats.mean.toFixed(2)}). Triggering strategic mutation.`);
64
- const strategies = await this.cortex.strategy.mutateStrategy();
64
+ const strategies = await this.cortex.strategy.mutateStrategy(trxOrDb);
65
65
  changes.push(...strategies);
66
66
  evolved = true;
67
67
  }
@@ -74,13 +74,13 @@ class EvolutionaryPilot {
74
74
  }
75
75
  }
76
76
  // 3. Meta-Meta Evolution Tuning
77
- const tuned = await this.tuneEmergentSkillHyperparameters(recentMetrics);
77
+ const tuned = await this.tuneEmergentSkillHyperparameters(recentMetrics, trxOrDb);
78
78
  if (tuned) {
79
79
  changes.push('Self-tuned emergent skill hyperparameters (Meta-Meta Evolution)');
80
80
  evolved = true;
81
81
  }
82
82
  // 4. Verify: Perform an audit
83
- const audit = await this.cortex.governor.performAudit();
83
+ const audit = await this.cortex.governor.performAudit(trxOrDb);
84
84
  if (!audit.healthy) {
85
85
  console.warn('[EvolutionaryPilot] Evolution resulted in unhealthy state. Reverting may be required.');
86
86
  changes.push('WARNING: Unhealthy state detected after evolution');
@@ -91,11 +91,11 @@ class EvolutionaryPilot {
91
91
  * Meta-Meta Evolution: Adjusts the hyperparameters of the SkillSynthesizer
92
92
  * based on the systemic success or failure of recently verified skills.
93
93
  */
94
- async tuneEmergentSkillHyperparameters(recentMetrics) {
94
+ async tuneEmergentSkillHyperparameters(recentMetrics, trxOrDb = this.db) {
95
95
  console.log(`[EvolutionaryPilot] Running Meta-Meta Evolution tuning...`);
96
96
  // Count how many skills are currently blacklisted vs verified
97
- const blacklisted = await this.cortex.capabilities.getCapabilities('blacklisted');
98
- const verified = await this.cortex.capabilities.getCapabilities('verified');
97
+ const blacklisted = await this.cortex.capabilities.getCapabilities('blacklisted', trxOrDb);
98
+ const verified = await this.cortex.capabilities.getCapabilities('verified', trxOrDb);
99
99
  let tuned = false;
100
100
  const config = this.config.evolution;
101
101
  if (!config)
@@ -152,21 +152,19 @@ class EvolutionaryPilot {
152
152
  const zScore = stdDev === 0 ? 0 : (current - mean) / stdDev;
153
153
  return { mean, stdDev, current, zScore };
154
154
  }
155
- async optimizeLatency() {
155
+ async optimizeLatency(trxOrDb = this.db) {
156
156
  const changes = [];
157
157
  console.log(`[EvolutionaryPilot] Triggering latency optimization...`);
158
- const dialect = this.db.getExecutor().dialect;
159
- const isSqlite = this.db
160
- .getExecutor()
161
- .adapter.constructor.name.toLowerCase()
162
- .includes('sqlite') ||
163
- (dialect && dialect.constructor.name.toLowerCase().includes('sqlite'));
158
+ const executor = trxOrDb.getExecutor();
159
+ const adapterName = executor?.adapter?.constructor?.name || executor?.dialect?.constructor?.name || '';
160
+ const isSqlite = adapterName.toLowerCase().includes('sqlite');
164
161
  if (isSqlite) {
165
- await (0, sql_js_1.sql) `PRAGMA optimize`.execute(this.db);
162
+ await (0, sql_js_1.sql) `PRAGMA optimize`.execute(trxOrDb);
166
163
  changes.push('Applied PRAGMA optimize');
167
164
  }
168
165
  const messagesTable = this.config.messagesTable || 'agent_messages';
169
- await this.cortex.evolution.evolve(`CREATE INDEX IF NOT EXISTS idx_agent_msg_session_time ON ${messagesTable}(session_id, created_at)`);
166
+ // NOTE: cortex.evolution.evolve should be transaction-aware
167
+ await this.cortex.evolution.evolve(`CREATE INDEX IF NOT EXISTS idx_agent_msg_session_time ON ${messagesTable}(session_id, created_at)`, {}, trxOrDb);
170
168
  changes.push(`Applied composite index to ${messagesTable}`);
171
169
  return changes;
172
170
  }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GoalArchitect = void 0;
4
4
  const similarity_js_1 = require("../../util/similarity.js");
5
+ const db_utils_js_1 = require("../util/db-utils.js");
5
6
  /**
6
7
  * GoalArchitect enables agents to autonomously deconstruct complex
7
8
  * objectives into manageable sub-goals.
@@ -26,11 +27,11 @@ class GoalArchitect {
26
27
  return await this.db.transaction().execute(async (trx) => {
27
28
  // 1. Audit Phase 9: Circular Dependency Protection inside transaction
28
29
  await this.detectCircularDependency(goalId, new Set(), trx);
29
- const goal = (await trx
30
+ const query = trx
30
31
  .selectFrom(this.goalsTable)
31
32
  .selectAll()
32
- .where('id', '=', goalId)
33
- .forUpdate() // Audit Phase 9: Atomic acquisition
33
+ .where('id', '=', goalId);
34
+ const goal = (await (0, db_utils_js_1.withLock)(query, trx) // Audit Phase 9: Atomic acquisition
34
35
  .executeTakeFirst());
35
36
  if (!goal)
36
37
  throw new Error(`Goal ${goalId} not found`);
@@ -101,11 +102,11 @@ class GoalArchitect {
101
102
  const sortedIds = [...goalIds].sort((a, b) => String(a).localeCompare(String(b)));
102
103
  await this.db.transaction().execute(async (trx) => {
103
104
  // Pre-lock all rows in deterministic order
104
- await trx
105
+ const query = trx
105
106
  .selectFrom(this.goalsTable)
106
107
  .select('id')
107
- .where('id', 'in', sortedIds)
108
- .forUpdate()
108
+ .where('id', 'in', sortedIds);
109
+ await (0, db_utils_js_1.withLock)(query, trx)
109
110
  .execute();
110
111
  for (let i = 0; i < goalIds.length; i++) {
111
112
  await trx
@@ -121,11 +122,11 @@ class GoalArchitect {
121
122
  */
122
123
  async markGoalAs(goalId, status, outcome) {
123
124
  return await this.db.transaction().execute(async (trx) => {
124
- const goal = (await trx
125
+ const query = trx
125
126
  .selectFrom(this.goalsTable)
126
127
  .selectAll()
127
- .where('id', '=', goalId)
128
- .forUpdate() // Audit Phase 9: Atomic status/meta update
128
+ .where('id', '=', goalId);
129
+ const goal = (await (0, db_utils_js_1.withLock)(query, trx) // Audit Phase 9: Atomic status/meta update
129
130
  .executeTakeFirst());
130
131
  if (!goal)
131
132
  throw new Error(`Goal ${goalId} not found`);
@@ -26,24 +26,24 @@ export declare class GovernanceManager {
26
26
  /**
27
27
  * Perform a "Panic Check" - looking for critical failures or cost overruns
28
28
  */
29
- performAudit(): Promise<{
29
+ performAudit(trxOrDb?: any): Promise<{
30
30
  healthy: boolean;
31
31
  issues: string[];
32
32
  }>;
33
33
  /**
34
34
  * Suggest architectural repairs if performance is degrading
35
35
  */
36
- suggestRepairs(): Promise<string[]>;
36
+ suggestRepairs(trxOrDb?: any): Promise<string[]>;
37
37
  /**
38
38
  * Quarantine a persona that is behaving outside safety parameters.
39
39
  */
40
- quarantinePersona(id: string | number, reason: string): Promise<void>;
40
+ quarantinePersona(id: string | number, reason: string, trxOrDb?: any): Promise<void>;
41
41
  /**
42
42
  * Blacklist a skill that is causing systemic issues.
43
43
  */
44
- quarantineSkill(name: string, reason: string): Promise<void>;
44
+ quarantineSkill(name: string, reason: string, trxOrDb?: any): Promise<void>;
45
45
  /**
46
46
  * Monitor cross-node behaviors and flag sudden spikes or malicious patterns.
47
47
  */
48
- validateEmergentBehavior(trx?: any): Promise<string[]>;
48
+ validateEmergentBehavior(trxOrDb?: any): Promise<string[]>;
49
49
  }
@@ -48,13 +48,13 @@ class GovernanceManager {
48
48
  /**
49
49
  * Perform a "Panic Check" - looking for critical failures or cost overruns
50
50
  */
51
- async performAudit() {
51
+ async performAudit(trxOrDb = this.db) {
52
52
  const issuesList = [];
53
53
  let auditMetadata = {};
54
54
  // Execute core audit gathering phase
55
55
  const ctx = {
56
56
  db: this.db,
57
- trx: this.db,
57
+ trx: trxOrDb,
58
58
  cortex: this.cortex,
59
59
  config: this.config,
60
60
  metricsTable: this.metricsTable,
@@ -92,21 +92,11 @@ class GovernanceManager {
92
92
  // Phase 1: Emergency Rollbacks
93
93
  if (activePersona && (success < 0.4 || hCost > hourlyLimit * 1.5)) {
94
94
  console.error(`[GovernanceManager] CRITICAL THRESHOLD BREACH. Initiating emergency containment for persona ${activePersona.id}`);
95
- await this.personaAuditor.quarantinePersona({ db: this.db, cortex: this.cortex }, activePersona.id, 'Critical threshold breach');
95
+ await this.personaAuditor.quarantinePersona(ctx, activePersona.id, 'Critical threshold breach');
96
96
  issuesList.push(`Containment: Emergency rollback triggered for persona ${activePersona.id}`);
97
97
  }
98
- await this.cortex.reflections.reflect(null, 'failure', 'Governance Compliance Audit', issuesList);
98
+ await this.cortex.reflections.reflect('system', 'failure', 'Governance Compliance Audit', issuesList, undefined, trxOrDb);
99
99
  // Phase 3: Remediation Rituals
100
- const ctx = {
101
- db: this.db,
102
- trx: this.db, // Standalone remediation
103
- cortex: this.cortex,
104
- config: this.config,
105
- metricsTable: this.metricsTable,
106
- policiesTable: this.policiesTable,
107
- personasTable: this.personasTable,
108
- skillsTable: this.skillsTable
109
- };
110
100
  await this.remediationEngine.triggerRemediation(ctx, issuesList);
111
101
  }
112
102
  return {
@@ -117,10 +107,10 @@ class GovernanceManager {
117
107
  /**
118
108
  * Suggest architectural repairs if performance is degrading
119
109
  */
120
- async suggestRepairs() {
110
+ async suggestRepairs(trxOrDb = this.db) {
121
111
  const ctx = {
122
112
  db: this.db,
123
- trx: this.db,
113
+ trx: trxOrDb,
124
114
  cortex: this.cortex,
125
115
  config: this.config,
126
116
  metricsTable: this.metricsTable,
@@ -133,10 +123,10 @@ class GovernanceManager {
133
123
  /**
134
124
  * Quarantine a persona that is behaving outside safety parameters.
135
125
  */
136
- async quarantinePersona(id, reason) {
126
+ async quarantinePersona(id, reason, trxOrDb = this.db) {
137
127
  const ctx = {
138
128
  db: this.db,
139
- trx: this.db,
129
+ trx: trxOrDb,
140
130
  cortex: this.cortex,
141
131
  config: this.config,
142
132
  metricsTable: this.metricsTable,
@@ -149,10 +139,10 @@ class GovernanceManager {
149
139
  /**
150
140
  * Blacklist a skill that is causing systemic issues.
151
141
  */
152
- async quarantineSkill(name, reason) {
142
+ async quarantineSkill(name, reason, trxOrDb = this.db) {
153
143
  const ctx = {
154
144
  db: this.db,
155
- trx: this.db,
145
+ trx: trxOrDb,
156
146
  cortex: this.cortex,
157
147
  config: this.config,
158
148
  metricsTable: this.metricsTable,
@@ -165,10 +155,10 @@ class GovernanceManager {
165
155
  /**
166
156
  * Monitor cross-node behaviors and flag sudden spikes or malicious patterns.
167
157
  */
168
- async validateEmergentBehavior(trx) {
158
+ async validateEmergentBehavior(trxOrDb = this.db) {
169
159
  const ctx = {
170
160
  db: this.db,
171
- trx: trx || this.db,
161
+ trx: trxOrDb,
172
162
  cortex: this.cortex,
173
163
  config: this.config,
174
164
  metricsTable: this.metricsTable,
@@ -10,11 +10,13 @@ export declare class HiveLink {
10
10
  private cortex;
11
11
  private config;
12
12
  private knowledgeTable;
13
+ private promoter;
14
+ private propagator;
15
+ private domainMaster;
13
16
  constructor(db: Kysely<any>, cortex: Cortex, config?: AgenticConfig);
14
17
  private get typedDb();
15
18
  /**
16
19
  * Promote high-confidence local knowledge to global "Hive" knowledge.
17
- * This creates a new, session-agnostic entry or updates an existing global one.
18
20
  */
19
21
  broadcastKnowledge(options?: {
20
22
  minConfidence?: number;
@@ -23,12 +25,10 @@ export declare class HiveLink {
23
25
  }): Promise<number>;
24
26
  /**
25
27
  * Strengthen knowledge related to a specific domain (tag).
26
- * Increases confidence of all items with this tag, representing "domain mastery".
27
28
  */
28
29
  syncDomain(domainTag: string, boostFactor?: number): Promise<number>;
29
30
  /**
30
31
  * Propagate high-performing capabilities globally using the "Sovereign Draft" protocol.
31
- * Uses Bayesian Convergence and Shadow Promotion to avoid deadlocks.
32
32
  */
33
33
  broadcastSkills(): Promise<number>;
34
34
  /**