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
@@ -1,5 +1,5 @@
1
1
  import type { Kysely } from '../kysely.js';
2
- import type { AgenticConfig, AgentAction } from '../types/index.js';
2
+ import type { AgentAction, AgenticConfig } from '../types/index.js';
3
3
  import type { TelemetryOrchestrator } from './telemetry/TelemetryOrchestrator.js';
4
4
  export interface ActionTable {
5
5
  id: number | string;
@@ -30,26 +30,26 @@ export declare class ActionJournal {
30
30
  /**
31
31
  * Log an action (tool call)
32
32
  */
33
- logAction(sessionId: string | number, toolName: string, args: Record<string, any>, messageId?: string | number): Promise<AgentAction>;
33
+ logAction(sessionId: string | number, toolName: string, args: Record<string, any>, messageId?: string | number, trxOrDb?: any): Promise<AgentAction>;
34
34
  /**
35
35
  * Update action with outcome
36
36
  */
37
- recordOutcome(actionId: string | number, status: AgentAction['status'], outcome: string, durationMs?: number, metadata?: Record<string, any>): Promise<AgentAction>;
37
+ recordOutcome(actionId: string | number, status: AgentAction['status'], outcome: string, durationMs?: number, metadata?: Record<string, any>, trxOrDb?: any): Promise<AgentAction>;
38
38
  /**
39
39
  * Get actions for a session with pagination
40
40
  */
41
41
  getSessionActions(sessionId: string | number, options?: {
42
42
  limit?: number;
43
43
  cursor?: string | number;
44
- }): Promise<AgentAction[]>;
44
+ }, trxOrDb?: any): Promise<AgentAction[]>;
45
45
  /**
46
46
  * Get actions by tool name across all sessions.
47
47
  */
48
- getActionsByTool(toolName: string, limit?: number): Promise<AgentAction[]>;
48
+ getActionsByTool(toolName: string, limit?: number, trxOrDb?: any): Promise<AgentAction[]>;
49
49
  /**
50
50
  * Generate a report of tool failures.
51
51
  */
52
- getFailureReport(): Promise<{
52
+ getFailureReport(trxOrDb?: any): Promise<{
53
53
  toolName: string;
54
54
  failureCount: number;
55
55
  lastFailure: string;
@@ -22,8 +22,8 @@ class ActionJournal {
22
22
  /**
23
23
  * Log an action (tool call)
24
24
  */
25
- async logAction(sessionId, toolName, args, messageId) {
26
- const action = await this.typedDb
25
+ async logAction(sessionId, toolName, args, messageId, trxOrDb = this.db) {
26
+ const action = await trxOrDb
27
27
  .insertInto(this.actionsTable)
28
28
  .values({
29
29
  session_id: sessionId,
@@ -45,8 +45,8 @@ class ActionJournal {
45
45
  /**
46
46
  * Update action with outcome
47
47
  */
48
- async recordOutcome(actionId, status, outcome, durationMs, metadata) {
49
- const action = await this.typedDb
48
+ async recordOutcome(actionId, status, outcome, durationMs, metadata, trxOrDb = this.db) {
49
+ const action = await trxOrDb
50
50
  .updateTable(this.actionsTable)
51
51
  .set({
52
52
  status,
@@ -69,9 +69,9 @@ class ActionJournal {
69
69
  /**
70
70
  * Get actions for a session with pagination
71
71
  */
72
- async getSessionActions(sessionId, options = {}) {
72
+ async getSessionActions(sessionId, options = {}, trxOrDb = this.db) {
73
73
  const { limit = 100, cursor } = options;
74
- let query = this.typedDb
74
+ let query = trxOrDb
75
75
  .selectFrom(this.actionsTable)
76
76
  .selectAll()
77
77
  .where('session_id', '=', sessionId)
@@ -86,8 +86,8 @@ class ActionJournal {
86
86
  /**
87
87
  * Get actions by tool name across all sessions.
88
88
  */
89
- async getActionsByTool(toolName, limit = 50) {
90
- const actions = await this.typedDb
89
+ async getActionsByTool(toolName, limit = 50, trxOrDb = this.db) {
90
+ const actions = await trxOrDb
91
91
  .selectFrom(this.actionsTable)
92
92
  .selectAll()
93
93
  .where('tool_name', '=', toolName)
@@ -99,10 +99,10 @@ class ActionJournal {
99
99
  /**
100
100
  * Generate a report of tool failures.
101
101
  */
102
- async getFailureReport() {
102
+ async getFailureReport(trxOrDb = this.db) {
103
103
  // Audit Phase 19: Sliding window (default 7 days) to prevent OOM/slow scans
104
104
  const windowStart = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
105
- const results = await this.typedDb
105
+ const results = await trxOrDb
106
106
  .selectFrom(this.actionsTable)
107
107
  .select([
108
108
  'tool_name',
@@ -30,24 +30,24 @@ export declare class CapabilityManager {
30
30
  /**
31
31
  * Register or update a capability (skill)
32
32
  */
33
- registerCapability(name: string, version: string, description?: string, metadata?: Record<string, any>): Promise<AgentCapability>;
33
+ registerCapability(name: string, version: string, description?: string, metadata?: Record<string, any>, trxOrDb?: any): Promise<AgentCapability>;
34
34
  /**
35
35
  * Update reliability based on action outcome using a damped moving average.
36
36
  * Manages the lifecycle of emergent skills (sandbox -> verified / blacklisted).
37
37
  */
38
- reportOutcome(name: string, success: boolean): Promise<void>;
38
+ reportOutcome(name: string, success: boolean, trxOrDb?: any): Promise<void>;
39
39
  /**
40
40
  * Get reliability score for a capability.
41
41
  */
42
- getReliability(name: string): Promise<number>;
42
+ getReliability(name: string, trxOrDb?: any): Promise<number>;
43
43
  /**
44
44
  * Get all registered capabilities, optionally filtered by status
45
45
  */
46
- getCapabilities(status?: AgentCapability['status']): Promise<AgentCapability[]>;
46
+ getCapabilities(status?: AgentCapability['status'], trxOrDb?: any): Promise<AgentCapability[]>;
47
47
  /**
48
48
  * Validate if a persona has access to a specific capability (Sandbox Enforcement).
49
49
  */
50
- validateCapabilityAccess(personaId: string | number, capabilityName: string): Promise<{
50
+ validateCapabilityAccess(personaId: string | number, capabilityName: string, trxOrDb?: any): Promise<{
51
51
  allowed: boolean;
52
52
  reason?: string;
53
53
  }>;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CapabilityManager = void 0;
4
+ const db_utils_js_1 = require("./util/db-utils.js");
4
5
  /**
5
6
  * CapabilityManager tracks the skills (tools) available to an agent
6
7
  * and their historical reliability.
@@ -30,8 +31,8 @@ class CapabilityManager {
30
31
  /**
31
32
  * Register or update a capability (skill)
32
33
  */
33
- async registerCapability(name, version, description, metadata = {}) {
34
- return await this.db.transaction().execute(async (trx) => {
34
+ async registerCapability(name, version, description, metadata = {}, trxOrDb = this.db) {
35
+ const runner = async (trx) => {
35
36
  const existing = await trx
36
37
  .selectFrom(this.capabilitiesTable)
37
38
  .selectAll()
@@ -74,24 +75,27 @@ class CapabilityManager {
74
75
  .returningAll()
75
76
  .executeTakeFirstOrThrow();
76
77
  return this.parseCapability(created);
77
- });
78
+ };
79
+ if (trxOrDb && trxOrDb !== this.db) {
80
+ return await runner(trxOrDb);
81
+ }
82
+ else {
83
+ return await this.db.transaction().execute(runner);
84
+ }
78
85
  }
79
86
  /**
80
87
  * Update reliability based on action outcome using a damped moving average.
81
88
  * Manages the lifecycle of emergent skills (sandbox -> verified / blacklisted).
82
89
  */
83
- async reportOutcome(name, success) {
84
- await this.db.transaction().execute(async (trx) => {
85
- let query = trx
90
+ async reportOutcome(name, success, trxOrDb = this.db) {
91
+ const runner = async (trx) => {
92
+ const baseQuery = trx
86
93
  .selectFrom(this.capabilitiesTable)
87
94
  .selectAll()
88
95
  .where('name', '=', name)
89
96
  .orderBy('updated_at', 'desc');
90
- // PRODUCTION HARDENING: Lock row to prevent RMW race (Skip for SQLite)
91
- if (this.db.getExecutor().adapter?.constructor.name !== 'SqliteAdapter') {
92
- query = query.forUpdate();
93
- }
94
- const capability = await query.executeTakeFirst();
97
+ const capability = await (0, db_utils_js_1.withLock)(baseQuery, trx)
98
+ .executeTakeFirst();
95
99
  if (capability) {
96
100
  const cap = capability;
97
101
  const metadata = typeof cap.metadata === 'string'
@@ -189,13 +193,19 @@ class CapabilityManager {
189
193
  .where('id', '=', cap.id)
190
194
  .execute();
191
195
  }
192
- });
196
+ };
197
+ if (trxOrDb && trxOrDb !== this.db) {
198
+ await runner(trxOrDb);
199
+ }
200
+ else {
201
+ await this.db.transaction().execute(runner);
202
+ }
193
203
  }
194
204
  /**
195
205
  * Get reliability score for a capability.
196
206
  */
197
- async getReliability(name) {
198
- const cap = await this.typedDb
207
+ async getReliability(name, trxOrDb = this.db) {
208
+ const cap = await trxOrDb
199
209
  .selectFrom(this.capabilitiesTable)
200
210
  .select('reliability')
201
211
  .where('name', '=', name)
@@ -206,8 +216,8 @@ class CapabilityManager {
206
216
  /**
207
217
  * Get all registered capabilities, optionally filtered by status
208
218
  */
209
- async getCapabilities(status) {
210
- let query = this.typedDb
219
+ async getCapabilities(status, trxOrDb = this.db) {
220
+ let query = trxOrDb
211
221
  .selectFrom(this.capabilitiesTable)
212
222
  .selectAll();
213
223
  if (status) {
@@ -223,9 +233,10 @@ class CapabilityManager {
223
233
  // Filter to latest/best variants if many versions exist
224
234
  const unique = new Map();
225
235
  for (const c of list) {
226
- const meta = typeof c.metadata === 'string' ? JSON.parse(c.metadata) : (c.metadata || {});
227
- if (!unique.has(c.name) || meta.is_alpha) {
228
- unique.set(c.name, c);
236
+ const cap = c;
237
+ const meta = typeof cap.metadata === 'string' ? JSON.parse(cap.metadata) : (cap.metadata || {});
238
+ if (!unique.has(cap.name) || meta.is_alpha) {
239
+ unique.set(cap.name, cap);
229
240
  }
230
241
  }
231
242
  return Array.from(unique.values()).map((c) => this.parseCapability(c));
@@ -233,13 +244,13 @@ class CapabilityManager {
233
244
  /**
234
245
  * Validate if a persona has access to a specific capability (Sandbox Enforcement).
235
246
  */
236
- async validateCapabilityAccess(personaId, capabilityName) {
237
- const persona = await this.cortex.personas.getPersona(String(personaId)) ||
238
- await this.typedDb.selectFrom(this.config.personasTable || 'agent_personas')
247
+ async validateCapabilityAccess(personaId, capabilityName, trxOrDb = this.db) {
248
+ const persona = await this.cortex.personas.getPersona(String(personaId), trxOrDb) ||
249
+ await trxOrDb.selectFrom(this.config.personasTable || 'agent_personas')
239
250
  .selectAll()
240
251
  .where('id', '=', personaId)
241
252
  .executeTakeFirst()
242
- .then(p => p ? this.cortex.personas.parsePersona(p) : null);
253
+ .then((p) => p ? this.cortex.personas.parsePersona(p) : null);
243
254
  if (!persona) {
244
255
  return { allowed: false, reason: `Persona ${personaId} not found.` };
245
256
  }
@@ -251,7 +262,7 @@ class CapabilityManager {
251
262
  };
252
263
  }
253
264
  // Check if capability is blacklisted globally
254
- const cap = await this.typedDb
265
+ const cap = await trxOrDb
255
266
  .selectFrom(this.capabilitiesTable)
256
267
  .select(['status', 'reliability'])
257
268
  .where('name', '=', capabilityName)
@@ -133,23 +133,22 @@ class Cortex {
133
133
  this.executionLock = true;
134
134
  console.log('[Cortex] Initiating Autonomous Soul-Searching Loop v2 (Deep Hardening Pass)...');
135
135
  try {
136
- // 1. Audit health & Run self-tests
137
- await this.#runIsolated('Audit', () => this.governor.performAudit());
138
- await this.#runIsolated('Self-Tests', () => this.tests.runAllProbes());
139
- // 2. Run background rituals (optimization, compression)
140
- await this.#runIsolated('Rituals', () => this.rituals.runPendingRituals());
141
- // 3. Learn from actions & Prune dead data
142
- await this.#runIsolated('Action Refinement', () => this.refiner.refineActions());
143
- await this.#runIsolated('Zombie Pruning', () => this.ablation.pruneZombies());
144
- await this.#runIsolated('Ablation Monitoring', () => this.ablation.monitorAblationPerformance());
145
- // 4. Mutation & Strategy
136
+ await this.db.transaction().execute(async (trx) => {
137
+ // 1. Audit health & Run self-tests
138
+ await this.#runIsolated('Audit', () => this.governor.performAudit(trx));
139
+ await this.#runIsolated('Self-Tests', () => this.tests.runAllProbes(trx));
140
+ // 2. Run background rituals (optimization, compression)
141
+ await this.#runIsolated('Rituals', () => this.rituals.runPendingRituals(trx));
142
+ // 3. Learn from actions & Prune dead data
143
+ await this.#runIsolated('Action Refinement', () => this.refiner.refineActions(trx));
144
+ await this.#runIsolated('Zombie Pruning', () => this.ablation.pruneZombies(30, trx));
145
+ await this.#runIsolated('Ablation Monitoring', () => this.ablation.monitorAblationPerformance(trx));
146
+ });
147
+ // These are often long-running or have their own internal transaction boundaries
146
148
  await this.#runIsolated('Strategy Mutation', () => this.strategy.mutateStrategy());
147
- // 5. High-Throughput Evolution Pulse
148
149
  await this.#runIsolated('Evolution Pulse', () => this.evolutionRitual.execute());
149
- // 6. Broadcast knowledge & skills
150
150
  await this.#runIsolated('Knowledge Broadcast', () => this.hive.broadcastKnowledge());
151
151
  await this.#runIsolated('Skill Synthesis', () => this.skillSynthesizer.discoverAndSynthesize());
152
- // 7. Evolutionary pulse
153
152
  await this.#runIsolated('Improvement Cycle', () => this.pilot.runSelfImprovementCycle());
154
153
  console.log('[Cortex] Soul-Searching loop completed.');
155
154
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EpisodicMemory = void 0;
4
+ const db_utils_js_1 = require("./util/db-utils.js");
4
5
  /**
5
6
  * EpisodicMemory groups interactions into semantic chunks (episodes),
6
7
  * allowing agents to recall specific scenarios and their outcomes.
@@ -39,11 +40,11 @@ class EpisodicMemory {
39
40
  */
40
41
  async completeEpisode(episodeId, summary, metadata) {
41
42
  return await this.db.transaction().execute(async (trx) => {
42
- const existing = await trx
43
+ const query = trx
43
44
  .selectFrom(this.episodesTable)
44
45
  .selectAll()
45
- .where('id', '=', episodeId)
46
- .forUpdate() // Audit Phase 12: Atomic completion lock
46
+ .where('id', '=', episodeId);
47
+ const existing = await (0, db_utils_js_1.withLock)(query, trx) // Audit Phase 12: Atomic completion lock
47
48
  .executeTakeFirst();
48
49
  if (!existing)
49
50
  throw new Error(`Episode with ID ${episodeId} not found`);
@@ -30,18 +30,18 @@ export declare class PersonaManager {
30
30
  capabilities?: string[];
31
31
  policies?: string[];
32
32
  metadata?: Record<string, any>;
33
- }): Promise<AgentPersona>;
33
+ }, trxOrDb?: any): Promise<AgentPersona>;
34
34
  /**
35
35
  * Get a persona by name
36
36
  */
37
- getPersona(name: string): Promise<AgentPersona | null>;
37
+ getPersona(name: string, trxOrDb?: any): Promise<AgentPersona | null>;
38
38
  /**
39
39
  * Delete a persona by name
40
40
  */
41
- deletePersona(name: string): Promise<boolean>;
41
+ deletePersona(name: string, trxOrDb?: any): Promise<boolean>;
42
42
  /**
43
43
  * List all personas
44
44
  */
45
- listPersonas(): Promise<AgentPersona[]>;
45
+ listPersonas(trxOrDb?: any): Promise<AgentPersona[]>;
46
46
  private parsePersona;
47
47
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PersonaManager = void 0;
4
+ const db_utils_js_1 = require("./util/db-utils.js");
4
5
  /**
5
6
  * PersonaManager handles persistent agent identities that bridge multiple sessions.
6
7
  */
@@ -19,17 +20,14 @@ class PersonaManager {
19
20
  /**
20
21
  * Create or update a persona
21
22
  */
22
- async upsertPersona(name, options = {}) {
23
- return await this.db.transaction().execute(async (trx) => {
24
- let query = trx
23
+ async upsertPersona(name, options = {}, trxOrDb = this.db) {
24
+ const runner = async (trx) => {
25
+ const baseQuery = trx
25
26
  .selectFrom(this.personasTable)
26
27
  .selectAll()
27
28
  .where('name', '=', name);
28
- // Audit Phase 13: Atomic identity lock (Skip for SQLite)
29
- if (this.db.getExecutor().adapter?.constructor.name !== 'SqliteAdapter') {
30
- query = query.forUpdate();
31
- }
32
- const existing = await query.executeTakeFirst();
29
+ const existing = await (0, db_utils_js_1.withLock)(baseQuery, trx)
30
+ .executeTakeFirst();
33
31
  const values = {
34
32
  name,
35
33
  role: options.role || null,
@@ -58,13 +56,19 @@ class PersonaManager {
58
56
  .returningAll()
59
57
  .executeTakeFirstOrThrow();
60
58
  return this.parsePersona(created);
61
- });
59
+ };
60
+ if (trxOrDb && trxOrDb !== this.db) {
61
+ return await runner(trxOrDb);
62
+ }
63
+ else {
64
+ return await this.db.transaction().execute(runner);
65
+ }
62
66
  }
63
67
  /**
64
68
  * Get a persona by name
65
69
  */
66
- async getPersona(name) {
67
- const persona = await this.typedDb
70
+ async getPersona(name, trxOrDb = this.db) {
71
+ const persona = await trxOrDb
68
72
  .selectFrom(this.personasTable)
69
73
  .selectAll()
70
74
  .where('name', '=', name)
@@ -74,8 +78,8 @@ class PersonaManager {
74
78
  /**
75
79
  * Delete a persona by name
76
80
  */
77
- async deletePersona(name) {
78
- const result = await this.typedDb
81
+ async deletePersona(name, trxOrDb = this.db) {
82
+ const result = await trxOrDb
79
83
  .deleteFrom(this.personasTable)
80
84
  .where('name', '=', name)
81
85
  .executeTakeFirst();
@@ -84,8 +88,8 @@ class PersonaManager {
84
88
  /**
85
89
  * List all personas
86
90
  */
87
- async listPersonas() {
88
- const list = await this.typedDb
91
+ async listPersonas(trxOrDb = this.db) {
92
+ const list = await trxOrDb
89
93
  .selectFrom(this.personasTable)
90
94
  .selectAll()
91
95
  .orderBy('name', 'asc')
@@ -33,30 +33,26 @@ export declare class PolicyEnforcer {
33
33
  /**
34
34
  * Define or update a policy with robust validation.
35
35
  */
36
- definePolicy(name: string, type: AgentPolicy['type'], definition: Record<string, any>, isEnabled?: boolean): Promise<AgentPolicy>;
36
+ definePolicy(name: string, type: AgentPolicy['type'], definition: Record<string, any>, isEnabled?: boolean, trxOrDb?: any): Promise<AgentPolicy>;
37
37
  /**
38
38
  * Comprehensive policy evaluation against a context value.
39
39
  * Supports thresholds, regex patterns, and cumulative budgets.
40
40
  */
41
- /**
42
- * Comprehensive policy evaluation against a context value.
43
- * Supports thresholds, regex patterns, and cumulative budgets.
44
- */
45
- checkPolicy(name: string, value: any, visited?: Set<string>): Promise<{
41
+ checkPolicy(name: string, value: any, visited?: Set<string>, trxOrDb?: any): Promise<{
46
42
  allowed: boolean;
47
43
  reason?: string;
48
44
  }>;
49
45
  /**
50
46
  * Evaluate a full context (object) against all applicable policies.
51
47
  */
52
- evaluateContext(context: Record<string, any>): Promise<{
48
+ evaluateContext(context: Record<string, any>, trxOrDb?: any): Promise<{
53
49
  allowed: boolean;
54
50
  violations: string[];
55
51
  }>;
56
52
  /**
57
53
  * Get all active policies.
58
54
  */
59
- getActivePolicies(): Promise<AgentPolicy[]>;
55
+ getActivePolicies(trxOrDb?: any): Promise<AgentPolicy[]>;
60
56
  private getCumulativeMetric;
61
57
  private parsePolicy;
62
58
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PolicyEnforcer = void 0;
4
+ const db_utils_js_1 = require("./util/db-utils.js");
4
5
  /**
5
6
  * PolicyEnforcer stores and validates agent autonomous guardrails,
6
7
  * such as budgets, safety constraints, and privacy rules.
@@ -23,17 +24,14 @@ class PolicyEnforcer {
23
24
  /**
24
25
  * Define or update a policy with robust validation.
25
26
  */
26
- async definePolicy(name, type, definition, isEnabled = true) {
27
- return await this.db.transaction().execute(async (trx) => {
28
- let query = trx
27
+ async definePolicy(name, type, definition, isEnabled = true, trxOrDb = this.db) {
28
+ const runner = async (trx) => {
29
+ const query = trx
29
30
  .selectFrom(this.policiesTable)
30
31
  .select('id')
31
32
  .where('name', '=', name);
32
- // Audit Phase 16: Exclusive lock for provisioning (Skip for SQLite)
33
- if (this.db.getExecutor().adapter?.constructor.name !== 'SqliteAdapter') {
34
- query = query.forUpdate();
35
- }
36
- const existing = await query.executeTakeFirst();
33
+ const existing = await (0, db_utils_js_1.withLock)(query, trx)
34
+ .executeTakeFirst();
37
35
  if (existing) {
38
36
  const updated = await trx
39
37
  .updateTable(this.policiesTable)
@@ -61,17 +59,19 @@ class PolicyEnforcer {
61
59
  .returningAll()
62
60
  .executeTakeFirstOrThrow();
63
61
  return this.parsePolicy(created);
64
- });
62
+ };
63
+ if (trxOrDb && trxOrDb !== this.db) {
64
+ return await runner(trxOrDb);
65
+ }
66
+ else {
67
+ return await this.db.transaction().execute(runner);
68
+ }
65
69
  }
66
70
  /**
67
71
  * Comprehensive policy evaluation against a context value.
68
72
  * Supports thresholds, regex patterns, and cumulative budgets.
69
73
  */
70
- /**
71
- * Comprehensive policy evaluation against a context value.
72
- * Supports thresholds, regex patterns, and cumulative budgets.
73
- */
74
- async checkPolicy(name, value, visited = new Set()) {
74
+ async checkPolicy(name, value, visited = new Set(), trxOrDb = this.db) {
75
75
  // Audit Pass 6: Re-entrancy / Circular Dependency Detection
76
76
  if (visited.has(name)) {
77
77
  return {
@@ -80,7 +80,7 @@ class PolicyEnforcer {
80
80
  };
81
81
  }
82
82
  visited.add(name);
83
- const policy = await this.typedDb
83
+ const policy = await trxOrDb
84
84
  .selectFrom(this.policiesTable)
85
85
  .selectAll()
86
86
  .where('name', '=', name)
@@ -111,7 +111,7 @@ class PolicyEnforcer {
111
111
  if (def.pattern.length > 500) {
112
112
  return { allowed: false, reason: `Policy '${name}' regex pattern too long (potential ReDoS risk)` };
113
113
  }
114
- const dangerousPatterns = /(\*|\+)\1|\(\.\*\)\*/;
114
+ const dangerousPatterns = /(\*|\+)\1|\(\.\*\)\*|\(\[.*\](\*|\+)\)(\*|\+)|\(.*\+\)\+/;
115
115
  if (dangerousPatterns.test(def.pattern)) {
116
116
  return { allowed: false, reason: `Policy '${name}' contains potentially dangerous ReDoS pattern` };
117
117
  }
@@ -139,7 +139,7 @@ class PolicyEnforcer {
139
139
  if (policy.type === 'budget' && def.metricName) {
140
140
  const period = def.period || 'daily';
141
141
  const limit = def.limit || 0;
142
- const total = await this.getCumulativeMetric(def.metricName, period);
142
+ const total = await this.getCumulativeMetric(def.metricName, period, trxOrDb);
143
143
  if (total + (typeof value === 'number' ? value : 0) > limit) {
144
144
  return {
145
145
  allowed: false,
@@ -151,7 +151,7 @@ class PolicyEnforcer {
151
151
  // Audit Pass 6: Moved from evaluateContext to checkPolicy for deeper nesting support
152
152
  if (def.dependsOn && Array.isArray(def.dependsOn)) {
153
153
  for (const depName of def.dependsOn) {
154
- const result = await this.checkPolicy(depName, value, new Set(visited));
154
+ const result = await this.checkPolicy(depName, value, new Set(visited), trxOrDb);
155
155
  if (!result.allowed) {
156
156
  return { allowed: false, reason: `Composite block: ${name} -> ${result.reason}` };
157
157
  }
@@ -162,19 +162,19 @@ class PolicyEnforcer {
162
162
  /**
163
163
  * Evaluate a full context (object) against all applicable policies.
164
164
  */
165
- async evaluateContext(context) {
166
- const policies = await this.getActivePolicies();
165
+ async evaluateContext(context, trxOrDb = this.db) {
166
+ const policies = await this.getActivePolicies(trxOrDb);
167
167
  const violations = [];
168
168
  for (const policy of policies) {
169
169
  // If the context has a key matching the policy name, check it
170
170
  if (context[policy.name] !== undefined) {
171
- const result = await this.checkPolicy(policy.name, context[policy.name]);
171
+ const result = await this.checkPolicy(policy.name, context[policy.name], new Set(), trxOrDb);
172
172
  if (!result.allowed)
173
173
  violations.push(result.reason);
174
174
  }
175
175
  // Check for type-specific global policies (e.g. all privacy policies)
176
176
  if (policy.type === 'privacy' && context.content) {
177
- const result = await this.checkPolicy(policy.name, context.content);
177
+ const result = await this.checkPolicy(policy.name, context.content, new Set(), trxOrDb);
178
178
  if (!result.allowed)
179
179
  violations.push(result.reason);
180
180
  }
@@ -187,15 +187,15 @@ class PolicyEnforcer {
187
187
  /**
188
188
  * Get all active policies.
189
189
  */
190
- async getActivePolicies() {
191
- const list = await this.typedDb
190
+ async getActivePolicies(trxOrDb = this.db) {
191
+ const list = await trxOrDb
192
192
  .selectFrom(this.policiesTable)
193
193
  .selectAll()
194
194
  .where('is_enabled', '=', true)
195
195
  .execute();
196
196
  return list.map((p) => this.parsePolicy(p));
197
197
  }
198
- async getCumulativeMetric(metricName, period) {
198
+ async getCumulativeMetric(metricName, period, trxOrDb = this.db) {
199
199
  const cacheKey = `${metricName}:${period}`;
200
200
  const cached = this.metricCache.get(cacheKey);
201
201
  const now = new Date();
@@ -217,7 +217,7 @@ class PolicyEnforcer {
217
217
  else if (period === 'hourly') {
218
218
  cutoff = new Date(now.getTime() - 3600000);
219
219
  }
220
- const result = await this.typedDb
220
+ const result = await trxOrDb
221
221
  .selectFrom(this.metricsTable)
222
222
  .select((eb) => eb.fn.sum('metric_value').as('total'))
223
223
  .where('metric_name', '=', metricName)
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ResourceMonitor = void 0;
4
+ const sql_js_1 = require("../raw-builder/sql.js");
4
5
  /**
5
6
  * ResourceMonitor tracks token usage and costs across sessions.
6
7
  */
@@ -100,7 +101,7 @@ class ResourceMonitor {
100
101
  .select([
101
102
  'model_name',
102
103
  (eb) => eb.fn
103
- .sum(eb('input_tokens', '+', 'output_tokens'))
104
+ .sum((0, sql_js_1.sql) `input_tokens + output_tokens`)
104
105
  .as('totalTokens'),
105
106
  (eb) => eb.fn.sum('cost').as('totalCost'),
106
107
  ])
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.SessionManager = void 0;
4
+ const db_utils_js_1 = require("./util/db-utils.js");
4
5
  /**
5
6
  * SessionManager handles the lifecycle of agentic sessions, including
6
7
  * message history, goal tracking, and memory persistence.
@@ -134,12 +135,12 @@ class SessionManager {
134
135
  async upsertGoal(sessionId, description, options = {}) {
135
136
  const { status = 'pending', priority = 0, parentId, metadata } = options;
136
137
  return await this.db.transaction().execute(async (trx) => {
137
- const existing = await trx
138
+ const query = trx
138
139
  .selectFrom(this.goalsTable)
139
140
  .selectAll()
140
141
  .where('session_id', '=', sessionId)
141
- .where('description', '=', description)
142
- .forUpdate() // Audit Phase 13: Atomic goal lock
142
+ .where('description', '=', description);
143
+ const existing = await (0, db_utils_js_1.withLock)(query, trx) // Audit Phase 13: Atomic goal lock
143
144
  .executeTakeFirst();
144
145
  if (existing) {
145
146
  const updated = await trx
@@ -210,11 +211,11 @@ class SessionManager {
210
211
  // We avoid the Read-Modify-Write race condition by letting the DB handle the merge
211
212
  // or by using a strict transaction if the DB doesn't support JSON patching natively.
212
213
  const updated = await this.db.transaction().execute(async (trx) => {
213
- const message = await trx
214
+ const query = trx
214
215
  .selectFrom(this.messagesTable)
215
216
  .select('metadata')
216
- .where('id', '=', messageId)
217
- .forUpdate() // Lock the row for the duration of the transaction
217
+ .where('id', '=', messageId);
218
+ const message = await (0, db_utils_js_1.withLock)(query, trx) // Lock the row for the duration of the transaction
218
219
  .executeTakeFirstOrThrow();
219
220
  const metadata = typeof message.metadata === 'string'
220
221
  ? JSON.parse(message.metadata)