noormme 1.2.0 → 1.2.2

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 (165) hide show
  1. package/README.md +60 -6
  2. package/dist/cjs/agentic/ActionJournal.d.ts +5 -2
  3. package/dist/cjs/agentic/ActionJournal.js +13 -5
  4. package/dist/cjs/agentic/CapabilityManager.d.ts +7 -0
  5. package/dist/cjs/agentic/CapabilityManager.js +84 -7
  6. package/dist/cjs/agentic/CognitiveRepository.js +3 -6
  7. package/dist/cjs/agentic/Cortex.d.ts +4 -0
  8. package/dist/cjs/agentic/Cortex.js +38 -17
  9. package/dist/cjs/agentic/EpisodicMemory.d.ts +5 -1
  10. package/dist/cjs/agentic/EpisodicMemory.js +11 -4
  11. package/dist/cjs/agentic/PersonaManager.js +37 -31
  12. package/dist/cjs/agentic/PolicyEnforcer.d.ts +6 -1
  13. package/dist/cjs/agentic/PolicyEnforcer.js +74 -17
  14. package/dist/cjs/agentic/ResourceMonitor.d.ts +9 -0
  15. package/dist/cjs/agentic/ResourceMonitor.js +36 -2
  16. package/dist/cjs/agentic/SessionManager.js +24 -17
  17. package/dist/cjs/agentic/VectorIndexer.d.ts +1 -0
  18. package/dist/cjs/agentic/VectorIndexer.js +26 -17
  19. package/dist/cjs/agentic/improvement/AblationEngine.d.ts +4 -6
  20. package/dist/cjs/agentic/improvement/AblationEngine.js +57 -37
  21. package/dist/cjs/agentic/improvement/ActionRefiner.js +30 -14
  22. package/dist/cjs/agentic/improvement/ConflictResolver.d.ts +3 -1
  23. package/dist/cjs/agentic/improvement/ConflictResolver.js +59 -47
  24. package/dist/cjs/agentic/improvement/CortexJanitor.js +11 -0
  25. package/dist/cjs/agentic/improvement/CuriosityEngine.d.ts +1 -1
  26. package/dist/cjs/agentic/improvement/CuriosityEngine.js +48 -21
  27. package/dist/cjs/agentic/improvement/EvolutionRitual.js +26 -14
  28. package/dist/cjs/agentic/improvement/EvolutionaryPilot.js +16 -4
  29. package/dist/cjs/agentic/improvement/GoalArchitect.d.ts +6 -2
  30. package/dist/cjs/agentic/improvement/GoalArchitect.js +72 -34
  31. package/dist/cjs/agentic/improvement/GovernanceManager.d.ts +20 -6
  32. package/dist/cjs/agentic/improvement/GovernanceManager.js +134 -155
  33. package/dist/cjs/agentic/improvement/HiveLink.d.ts +7 -3
  34. package/dist/cjs/agentic/improvement/HiveLink.js +135 -113
  35. package/dist/cjs/agentic/improvement/KnowledgeDistiller.js +43 -35
  36. package/dist/cjs/agentic/improvement/QuotaManager.d.ts +41 -0
  37. package/dist/cjs/agentic/improvement/QuotaManager.js +185 -0
  38. package/dist/cjs/agentic/improvement/RecursiveReasoner.js +50 -25
  39. package/dist/cjs/agentic/improvement/ReflectionEngine.d.ts +4 -1
  40. package/dist/cjs/agentic/improvement/ReflectionEngine.js +3 -1
  41. package/dist/cjs/agentic/improvement/RitualOrchestrator.js +27 -16
  42. package/dist/cjs/agentic/improvement/RuleEngine.d.ts +1 -1
  43. package/dist/cjs/agentic/improvement/RuleEngine.js +10 -4
  44. package/dist/cjs/agentic/improvement/SelfEvolution.js +22 -17
  45. package/dist/cjs/agentic/improvement/SelfTestRegistry.d.ts +5 -0
  46. package/dist/cjs/agentic/improvement/SelfTestRegistry.js +129 -109
  47. package/dist/cjs/agentic/improvement/SkillSynthesizer.d.ts +1 -0
  48. package/dist/cjs/agentic/improvement/SkillSynthesizer.js +22 -13
  49. package/dist/cjs/agentic/improvement/StrategicPlanner.d.ts +1 -0
  50. package/dist/cjs/agentic/improvement/StrategicPlanner.js +26 -19
  51. package/dist/cjs/agentic/improvement/governance/AuditContext.d.ts +17 -0
  52. package/dist/cjs/agentic/improvement/governance/AuditContext.js +2 -0
  53. package/dist/cjs/agentic/improvement/governance/BudgetAuditor.d.ts +4 -0
  54. package/dist/cjs/agentic/improvement/governance/BudgetAuditor.js +50 -0
  55. package/dist/cjs/agentic/improvement/governance/EmergenceAuditor.d.ts +4 -0
  56. package/dist/cjs/agentic/improvement/governance/EmergenceAuditor.js +37 -0
  57. package/dist/cjs/agentic/improvement/governance/MaintenanceOracle.d.ts +4 -0
  58. package/dist/cjs/agentic/improvement/governance/MaintenanceOracle.js +67 -0
  59. package/dist/cjs/agentic/improvement/governance/PerformanceAuditor.d.ts +4 -0
  60. package/dist/cjs/agentic/improvement/governance/PerformanceAuditor.js +43 -0
  61. package/dist/cjs/agentic/improvement/governance/PersonaAuditor.d.ts +6 -0
  62. package/dist/cjs/agentic/improvement/governance/PersonaAuditor.js +74 -0
  63. package/dist/cjs/agentic/improvement/governance/RemediationEngine.d.ts +5 -0
  64. package/dist/cjs/agentic/improvement/governance/RemediationEngine.js +43 -0
  65. package/dist/cjs/agentic/improvement/governance/SkillAuditor.d.ts +5 -0
  66. package/dist/cjs/agentic/improvement/governance/SkillAuditor.js +52 -0
  67. package/dist/cjs/agentic/telemetry/CognitiveSynthesizer.d.ts +5 -0
  68. package/dist/cjs/agentic/telemetry/CognitiveSynthesizer.js +54 -12
  69. package/dist/cjs/agentic/telemetry/EventHarvester.d.ts +1 -1
  70. package/dist/cjs/agentic/telemetry/EventHarvester.js +10 -3
  71. package/dist/cjs/agentic/telemetry/ResearchAlchemist.d.ts +7 -2
  72. package/dist/cjs/agentic/telemetry/ResearchAlchemist.js +49 -8
  73. package/dist/cjs/agentic/telemetry/TelemetryOrchestrator.d.ts +4 -1
  74. package/dist/cjs/agentic/telemetry/TelemetryOrchestrator.js +38 -11
  75. package/dist/cjs/cli/commands/inspect.js +40 -1
  76. package/dist/cjs/cli/commands/watch.js +31 -25
  77. package/dist/cjs/cli/index.js +0 -0
  78. package/dist/cjs/dialect/sqlite/sqlite-introspector.js +15 -5
  79. package/dist/cjs/helpers/agent-schema.js +15 -14
  80. package/dist/cjs/migration/data_migrator.js +4 -4
  81. package/dist/cjs/migration/schema_differ.js +37 -15
  82. package/dist/cjs/types/index.d.ts +12 -0
  83. package/dist/cjs/util/safe-sql-helpers.js +7 -10
  84. package/dist/esm/agentic/ActionJournal.d.ts +5 -2
  85. package/dist/esm/agentic/ActionJournal.js +13 -5
  86. package/dist/esm/agentic/CapabilityManager.d.ts +7 -0
  87. package/dist/esm/agentic/CapabilityManager.js +84 -7
  88. package/dist/esm/agentic/CognitiveRepository.js +3 -6
  89. package/dist/esm/agentic/Cortex.d.ts +4 -0
  90. package/dist/esm/agentic/Cortex.js +38 -17
  91. package/dist/esm/agentic/EpisodicMemory.d.ts +5 -1
  92. package/dist/esm/agentic/EpisodicMemory.js +11 -4
  93. package/dist/esm/agentic/PersonaManager.js +37 -31
  94. package/dist/esm/agentic/PolicyEnforcer.d.ts +6 -1
  95. package/dist/esm/agentic/PolicyEnforcer.js +74 -17
  96. package/dist/esm/agentic/ResourceMonitor.d.ts +9 -0
  97. package/dist/esm/agentic/ResourceMonitor.js +36 -2
  98. package/dist/esm/agentic/SessionManager.js +24 -17
  99. package/dist/esm/agentic/VectorIndexer.d.ts +1 -0
  100. package/dist/esm/agentic/VectorIndexer.js +26 -17
  101. package/dist/esm/agentic/improvement/AblationEngine.d.ts +4 -6
  102. package/dist/esm/agentic/improvement/AblationEngine.js +57 -37
  103. package/dist/esm/agentic/improvement/ActionRefiner.js +30 -14
  104. package/dist/esm/agentic/improvement/ConflictResolver.d.ts +3 -1
  105. package/dist/esm/agentic/improvement/ConflictResolver.js +59 -47
  106. package/dist/esm/agentic/improvement/CortexJanitor.js +11 -0
  107. package/dist/esm/agentic/improvement/CuriosityEngine.d.ts +1 -1
  108. package/dist/esm/agentic/improvement/CuriosityEngine.js +48 -21
  109. package/dist/esm/agentic/improvement/EvolutionRitual.js +26 -14
  110. package/dist/esm/agentic/improvement/EvolutionaryPilot.js +16 -4
  111. package/dist/esm/agentic/improvement/GoalArchitect.d.ts +6 -2
  112. package/dist/esm/agentic/improvement/GoalArchitect.js +72 -34
  113. package/dist/esm/agentic/improvement/GovernanceManager.d.ts +20 -6
  114. package/dist/esm/agentic/improvement/GovernanceManager.js +134 -155
  115. package/dist/esm/agentic/improvement/HiveLink.d.ts +7 -3
  116. package/dist/esm/agentic/improvement/HiveLink.js +135 -113
  117. package/dist/esm/agentic/improvement/KnowledgeDistiller.js +43 -35
  118. package/dist/esm/agentic/improvement/QuotaManager.d.ts +41 -0
  119. package/dist/esm/agentic/improvement/QuotaManager.js +182 -0
  120. package/dist/esm/agentic/improvement/RecursiveReasoner.js +50 -25
  121. package/dist/esm/agentic/improvement/ReflectionEngine.d.ts +4 -1
  122. package/dist/esm/agentic/improvement/ReflectionEngine.js +3 -1
  123. package/dist/esm/agentic/improvement/RitualOrchestrator.js +27 -16
  124. package/dist/esm/agentic/improvement/RuleEngine.d.ts +1 -1
  125. package/dist/esm/agentic/improvement/RuleEngine.js +10 -4
  126. package/dist/esm/agentic/improvement/SelfEvolution.js +22 -17
  127. package/dist/esm/agentic/improvement/SelfTestRegistry.d.ts +5 -0
  128. package/dist/esm/agentic/improvement/SelfTestRegistry.js +129 -109
  129. package/dist/esm/agentic/improvement/SkillSynthesizer.d.ts +1 -0
  130. package/dist/esm/agentic/improvement/SkillSynthesizer.js +22 -13
  131. package/dist/esm/agentic/improvement/StrategicPlanner.d.ts +1 -0
  132. package/dist/esm/agentic/improvement/StrategicPlanner.js +26 -19
  133. package/dist/esm/agentic/improvement/governance/AuditContext.d.ts +17 -0
  134. package/dist/esm/agentic/improvement/governance/AuditContext.js +2 -0
  135. package/dist/esm/agentic/improvement/governance/BudgetAuditor.d.ts +4 -0
  136. package/dist/esm/agentic/improvement/governance/BudgetAuditor.js +47 -0
  137. package/dist/esm/agentic/improvement/governance/EmergenceAuditor.d.ts +4 -0
  138. package/dist/esm/agentic/improvement/governance/EmergenceAuditor.js +34 -0
  139. package/dist/esm/agentic/improvement/governance/MaintenanceOracle.d.ts +4 -0
  140. package/dist/esm/agentic/improvement/governance/MaintenanceOracle.js +64 -0
  141. package/dist/esm/agentic/improvement/governance/PerformanceAuditor.d.ts +4 -0
  142. package/dist/esm/agentic/improvement/governance/PerformanceAuditor.js +40 -0
  143. package/dist/esm/agentic/improvement/governance/PersonaAuditor.d.ts +6 -0
  144. package/dist/esm/agentic/improvement/governance/PersonaAuditor.js +71 -0
  145. package/dist/esm/agentic/improvement/governance/RemediationEngine.d.ts +5 -0
  146. package/dist/esm/agentic/improvement/governance/RemediationEngine.js +40 -0
  147. package/dist/esm/agentic/improvement/governance/SkillAuditor.d.ts +5 -0
  148. package/dist/esm/agentic/improvement/governance/SkillAuditor.js +49 -0
  149. package/dist/esm/agentic/telemetry/CognitiveSynthesizer.d.ts +5 -0
  150. package/dist/esm/agentic/telemetry/CognitiveSynthesizer.js +54 -12
  151. package/dist/esm/agentic/telemetry/EventHarvester.d.ts +1 -1
  152. package/dist/esm/agentic/telemetry/EventHarvester.js +10 -3
  153. package/dist/esm/agentic/telemetry/ResearchAlchemist.d.ts +7 -2
  154. package/dist/esm/agentic/telemetry/ResearchAlchemist.js +49 -8
  155. package/dist/esm/agentic/telemetry/TelemetryOrchestrator.d.ts +4 -1
  156. package/dist/esm/agentic/telemetry/TelemetryOrchestrator.js +38 -11
  157. package/dist/esm/cli/commands/inspect.js +40 -1
  158. package/dist/esm/cli/commands/watch.js +31 -25
  159. package/dist/esm/dialect/sqlite/sqlite-introspector.js +15 -5
  160. package/dist/esm/helpers/agent-schema.js +15 -14
  161. package/dist/esm/migration/data_migrator.js +4 -4
  162. package/dist/esm/migration/schema_differ.js +37 -15
  163. package/dist/esm/types/index.d.ts +12 -0
  164. package/dist/esm/util/safe-sql-helpers.js +7 -10
  165. package/package.json +44 -40
@@ -18,41 +18,50 @@ class ConflictResolver {
18
18
  /**
19
19
  * Audit rules for direct conflicts and semantic overlaps.
20
20
  */
21
- async auditRuleConflicts() {
22
- console.log('[ConflictResolver] Auditing cognitive rules for conflicts and overlaps...');
23
- const rules = (await this.db
24
- .selectFrom(this.rulesTable)
25
- .selectAll()
26
- .where('is_enabled', '=', true)
27
- .execute());
21
+ async auditRuleConflicts(options = {}) {
22
+ const batchSize = options.batchSize ?? 500;
28
23
  const conflicts = [];
29
- // 1. Direct Conflicts: Same Table + Same Operation
30
- const seen = new Map();
31
- for (const rule of rules) {
32
- const key = `${rule.tableName}:${rule.operation}`;
33
- if (seen.has(key)) {
34
- const existing = seen.get(key);
35
- // If they have different actions but same triggers, it's a conflict
36
- if (existing.action !== rule.action) {
37
- conflicts.push(`Direct Conflict: Multiple actions for '${key}' ('${existing.action}' vs '${rule.action}')`);
24
+ let offset = 0;
25
+ console.log(`[ConflictResolver] Auditing cognitive rules (batchSize=${batchSize})...`);
26
+ const seenDirect = new Map();
27
+ const tableRules = new Map();
28
+ while (true) {
29
+ const rules = (await this.db
30
+ .selectFrom(this.rulesTable)
31
+ .selectAll()
32
+ .where('is_enabled', '=', true)
33
+ .limit(batchSize)
34
+ .offset(offset)
35
+ .execute());
36
+ if (rules.length === 0)
37
+ break;
38
+ for (const rule of rules) {
39
+ // 1. Direct Conflicts: Same Table + Same Operation
40
+ const directKey = `${rule.tableName}:${rule.operation}`;
41
+ if (seenDirect.has(directKey)) {
42
+ const existing = seenDirect.get(directKey);
43
+ if (existing.action !== rule.action) {
44
+ conflicts.push(`Direct Conflict: Multiple actions for '${directKey}' ('${existing.action}' vs '${rule.action}')`);
45
+ }
46
+ else if (existing.condition === rule.condition) {
47
+ conflicts.push(`Redundant Rules: Duplicate rule detected for '${directKey}' with same condition.`);
48
+ }
38
49
  }
39
- else if (existing.condition === rule.condition) {
40
- conflicts.push(`Redundant Rules: Duplicate rule detected for '${key}' with same condition.`);
50
+ seenDirect.set(directKey, rule);
51
+ // Group for semantic check
52
+ const list = tableRules.get(rule.tableName) || [];
53
+ if (list.length < 100) { // Audit Phase 16: Quadratic Guard per table
54
+ list.push(rule);
55
+ tableRules.set(rule.tableName, list);
41
56
  }
42
57
  }
43
- seen.set(key, rule);
44
- }
45
- // 2. Semantic Overlaps: Multiple rules targeting same table with potentially overlapping conditions
46
- // This is a rudimentary check for similar keywords in conditions
47
- const tableRules = new Map();
48
- for (const rule of rules) {
49
- const list = tableRules.get(rule.tableName) || [];
50
- list.push(rule);
51
- tableRules.set(rule.tableName, list);
58
+ if (rules.length < batchSize)
59
+ break;
60
+ offset += batchSize;
52
61
  }
62
+ // 2. Semantic Overlaps: Quadratic check with hard limits
53
63
  for (const [table, list] of tableRules.entries()) {
54
64
  if (list.length > 1) {
55
- // Check for overlapping conditions (e.g., both check 'status' or both check 'priority')
56
65
  for (let i = 0; i < list.length; i++) {
57
66
  for (let j = i + 1; j < list.length; j++) {
58
67
  const r1 = list[i];
@@ -60,7 +69,7 @@ class ConflictResolver {
60
69
  if (r1.condition && r2.condition) {
61
70
  const similarity = (0, similarity_js_1.calculateSimilarity)(r1.condition, r2.condition);
62
71
  if (similarity > 0.6) {
63
- conflicts.push(`Potential Semantic Overlap on '${table}': Rules ${r1.id} and ${r2.id} have high condition similarity (${(similarity * 100).toFixed(1)}%)`);
72
+ conflicts.push(`Potential Semantic Overlap on '${table}': Rules ${r1.id} and ${r2.id} have high similarity (${(similarity * 100).toFixed(1)}%)`);
64
73
  }
65
74
  }
66
75
  }
@@ -75,24 +84,27 @@ class ConflictResolver {
75
84
  */
76
85
  async resolveConflict(tableName, operation) {
77
86
  console.log(`[ConflictResolver] Resolving conflict for ${tableName}:${operation}`);
78
- const rules = (await this.db
79
- .selectFrom(this.rulesTable)
80
- .selectAll()
81
- .where('table_name', '=', tableName)
82
- .where('operation', '=', operation)
83
- .where('is_enabled', '=', true)
84
- .orderBy('created_at', 'desc')
85
- .execute());
86
- if (rules.length <= 1)
87
- return;
88
- // Keep the first (newest) one, disable the rest
89
- const toDisable = rules.slice(1).map((r) => r.id);
90
- await this.db
91
- .updateTable(this.rulesTable)
92
- .set({ is_enabled: false })
93
- .where('id', 'in', toDisable)
94
- .execute();
95
- console.log(`[ConflictResolver] Disabled ${toDisable.length} redundant rules for ${tableName}:${operation}`);
87
+ return await this.db.transaction().execute(async (trx) => {
88
+ const rules = (await trx
89
+ .selectFrom(this.rulesTable)
90
+ .selectAll()
91
+ .where('table_name', '=', tableName)
92
+ .where('operation', '=', operation)
93
+ .where('is_enabled', '=', true)
94
+ .orderBy('created_at', 'desc')
95
+ .forUpdate() // Audit Phase 10: Atomic resolution lock
96
+ .execute());
97
+ if (rules.length <= 1)
98
+ return;
99
+ // Keep the first (newest) one, disable the rest
100
+ const toDisable = rules.slice(1).map((r) => r.id);
101
+ await trx
102
+ .updateTable(this.rulesTable)
103
+ .set({ is_enabled: false })
104
+ .where('id', 'in', toDisable)
105
+ .execute();
106
+ console.log(`[ConflictResolver] Disabled ${toDisable.length} redundant rules for ${tableName}:${operation}`);
107
+ });
96
108
  }
97
109
  }
98
110
  exports.ConflictResolver = ConflictResolver;
@@ -174,6 +174,17 @@ class CortexJanitor {
174
174
  }
175
175
  async logRitual(type, status, metadata) {
176
176
  try {
177
+ // Audit Phase 18: Prevent log-spam in concurrent swarms
178
+ const windowStart = new Date(Date.now() - 10 * 60 * 1000); // 10 min window
179
+ const existing = await this.db
180
+ .selectFrom(this.ritualsTable)
181
+ .select('id')
182
+ .where('name', '=', `Automated ${type}`)
183
+ .where('type', '=', type)
184
+ .where('last_run', '>', windowStart)
185
+ .executeTakeFirst();
186
+ if (existing)
187
+ return;
177
188
  await this.db
178
189
  .insertInto(this.ritualsTable)
179
190
  .values({
@@ -36,7 +36,7 @@ export declare class CuriosityEngine {
36
36
  suggestQuestions(entity: string): Promise<string[]>;
37
37
  /**
38
38
  * Generate "Relationship Hypotheses" between high-confidence entities.
39
- * Suggests that entities with multi-tag overlaps might be related.
39
+ * Refactored Phase 11: Linear O(N) relationship discovery via tag-to-entity mapping.
40
40
  */
41
41
  generateHypotheses(): Promise<string[]>;
42
42
  /**
@@ -55,11 +55,13 @@ class CuriosityEngine {
55
55
  .having((eb) => eb.fn.count('id'), '>', 1)
56
56
  .execute();
57
57
  for (const row of entities) {
58
+ // Audit Phase 11: Paginated fact retrieval to prevent OOM on dense entities
58
59
  const items = (await this.typedDb
59
60
  .selectFrom(this.knowledgeTable)
60
61
  .selectAll()
61
62
  .where('entity', '=', row.entity)
62
63
  .where('confidence', '>', 0.5)
64
+ .limit(200) // Prevent OOM on massive entity fact lists
63
65
  .execute());
64
66
  if (items.length > 1) {
65
67
  for (let i = 0; i < items.length; i++) {
@@ -169,44 +171,69 @@ class CuriosityEngine {
169
171
  }
170
172
  /**
171
173
  * Generate "Relationship Hypotheses" between high-confidence entities.
172
- * Suggests that entities with multi-tag overlaps might be related.
174
+ * Refactored Phase 11: Linear O(N) relationship discovery via tag-to-entity mapping.
173
175
  */
174
176
  async generateHypotheses() {
175
177
  console.log('[CuriosityEngine] Generating relationship hypotheses...');
176
- // 1. Get high-confidence entities
178
+ // 1. Get high-confidence entities (Paginated to handle scale)
177
179
  const entities = (await this.typedDb
178
180
  .selectFrom(this.knowledgeTable)
179
181
  .select(['entity', 'tags'])
180
182
  .where('confidence', '>', 0.7)
181
183
  .where('tags', 'is not', null)
184
+ .limit(2000)
182
185
  .execute());
183
186
  const hypotheses = [];
184
- const entityTagsMap = new Map();
187
+ const tagToEntities = new Map();
188
+ // Audit Phase 11: Build inverted index O(N)
185
189
  for (const row of entities) {
186
190
  const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags || [];
187
- if (tags.length > 0) {
188
- entityTagsMap.set(row.entity, new Set(tags));
191
+ for (const tag of tags) {
192
+ const list = tagToEntities.get(tag) || [];
193
+ list.push(row.entity);
194
+ tagToEntities.set(tag, list);
189
195
  }
190
196
  }
191
- const entityNames = Array.from(entityTagsMap.keys());
192
- // 2. Identify entities sharing multiple matching tags (Density check)
193
- for (let i = 0; i < entityNames.length; i++) {
194
- for (let j = i + 1; j < entityNames.length; j++) {
195
- const tagsI = entityTagsMap.get(entityNames[i]);
196
- const tagsJ = entityTagsMap.get(entityNames[j]);
197
- // intersection
198
- const commonTags = [...tagsI].filter((t) => tagsJ.has(t));
199
- if (commonTags.length >= 2) {
200
- hypotheses.push(`[HYPOTHESIS] "${entityNames[i]}" and "${entityNames[j]}" share a dense tag set (${commonTags.join(', ')}). Is there a structural coupling?`);
201
- }
202
- else if (commonTags.length === 1 &&
203
- (tagsI.size === 1 || tagsJ.size === 1)) {
204
- // Specific probe for shared lone-tags
205
- hypotheses.push(`[HYPOTHESIS] Both "${entityNames[i]}" and "${entityNames[j]}" are uniquely identified by "${commonTags[0]}". Might be aliases or sub-components.`);
197
+ // 2. Identify dense tag overlaps via index lookup
198
+ const pairCouplings = new Map(); // Key: "entity1|entity2", Value: [commonTags]
199
+ let totalPairs = 0;
200
+ const MAX_PAIRS = 5000; // Audit Phase 15: Runaway coupling guard
201
+ for (const [tag, entityList] of tagToEntities.entries()) {
202
+ if (entityList.length < 2)
203
+ continue;
204
+ if (totalPairs >= MAX_PAIRS)
205
+ break;
206
+ // Limit inner pairing to prevent explosion on ubiquitous tags
207
+ const limitedList = entityList.slice(0, 50);
208
+ for (let i = 0; i < limitedList.length; i++) {
209
+ if (totalPairs >= MAX_PAIRS)
210
+ break;
211
+ for (let j = i + 1; j < limitedList.length; j++) {
212
+ const pairKey = [limitedList[i], limitedList[j]].sort().join('|');
213
+ const common = pairCouplings.get(pairKey) || [];
214
+ if (common.length === 0)
215
+ totalPairs++;
216
+ common.push(tag);
217
+ pairCouplings.set(pairKey, common);
218
+ if (totalPairs >= MAX_PAIRS)
219
+ break;
206
220
  }
207
221
  }
208
222
  }
209
- return hypotheses.slice(0, 10); // Limit to top 10
223
+ // 3. Synthesize hypotheses from dense coupling
224
+ for (const [pair, common] of pairCouplings.entries()) {
225
+ const [e1, e2] = pair.split('|');
226
+ if (common.length >= 2) {
227
+ hypotheses.push(`[HYPOTHESIS] "${e1}" and "${e2}" share a dense tag set (${common.join(', ')}). Is there a structural coupling?`);
228
+ }
229
+ else if (common.length === 1) {
230
+ // Only flag shared lone tags if they were rare or specific
231
+ hypotheses.push(`[HYPOTHESIS] Both "${e1}" and "${e2}" are identified by "${common[0]}". Might be aliases or sub-components.`);
232
+ }
233
+ if (hypotheses.length >= 20)
234
+ break;
235
+ }
236
+ return hypotheses.slice(0, 10);
210
237
  }
211
238
  /**
212
239
  * Propose a research ritual based on identified gaps, hotspots, and hypotheses.
@@ -62,22 +62,34 @@ class EvolutionRitual {
62
62
  async identifyActiveDomains() {
63
63
  // Production Hardening: Entropy-Based Discovery
64
64
  // Find domains that are currently "hot" (high density of recent knowledge)
65
- // This represents areas where the agent is learning fast and needs stabilization.
66
- const result = await this.db
67
- .selectFrom(this.config.knowledgeTable || 'agent_knowledge_base')
68
- .select(['tags', 'confidence'])
69
- .where('updated_at', '>', new Date(Date.now() - 24 * 60 * 60 * 1000)) // Last 24h
70
- .execute();
65
+ // Refactored Phase 13: Paginated scanning to handle large knowledge bursts
71
66
  const domainScores = new Map();
72
- for (const row of result) {
73
- const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags || [];
74
- for (const t of tags) {
75
- if (t === 'hive_mind')
76
- continue;
77
- // Score based on confidence density: a mix of volume and high-quality signals
78
- const current = domainScores.get(t) || 0;
79
- domainScores.set(t, current + (row.confidence || 0));
67
+ const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000);
68
+ let offset = 0;
69
+ const limit = 1000;
70
+ while (true) {
71
+ const result = await this.db
72
+ .selectFrom(this.config.knowledgeTable || 'agent_knowledge_base')
73
+ .select(['tags', 'confidence'])
74
+ .where('updated_at', '>', cutoff)
75
+ .orderBy('updated_at', 'asc')
76
+ .limit(limit)
77
+ .offset(offset)
78
+ .execute();
79
+ if (result.length === 0)
80
+ break;
81
+ for (const row of result) {
82
+ const tags = typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags || [];
83
+ for (const t of tags) {
84
+ if (t === 'hive_mind')
85
+ continue;
86
+ const current = domainScores.get(t) || 0;
87
+ domainScores.set(t, current + (row.confidence || 0));
88
+ }
80
89
  }
90
+ if (result.length < limit)
91
+ break;
92
+ offset += limit;
81
93
  }
82
94
  // Sort by total confidence density (Entropy/Activity proxy)
83
95
  // Production Hardening: Only boost domains with significant activity (Threshold: 1.0)
@@ -29,32 +29,44 @@ class EvolutionaryPilot {
29
29
  'total_cost',
30
30
  'trust_signal',
31
31
  ];
32
- const recentMetrics = await this.cortex.metrics.getRecentMetrics(100);
32
+ const samplingCount = this.config.evolution?.samplingCount || 100;
33
+ const recentMetrics = await this.cortex.metrics.getRecentMetrics(samplingCount);
33
34
  for (const metricName of metrics) {
35
+ // Audit Phase 17: Bounded metric slice for scale-safe baselining
34
36
  const values = recentMetrics
35
37
  .filter((m) => m.metricName === metricName)
38
+ .slice(0, 500) // Hard boundary for statistical window
36
39
  .map((m) => Number(m.metricValue));
37
40
  if (values.length < 5)
38
41
  continue;
39
42
  const stats = this.calculateZScore(values);
43
+ const minSamples = this.config.evolution?.minSamples || 5;
44
+ if (values.length < minSamples)
45
+ continue;
46
+ const policies = await this.cortex.policies.getActivePolicies();
47
+ const latencyZ = policies.find(p => p.name === 'latency_drift_z')?.definition?.threshold || 2.0;
48
+ const latencyMean = policies.find(p => p.name === 'latency_mean_ceiling')?.definition?.threshold || 1000;
40
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)}`);
41
50
  // 2. Trigger Evolution based on metric-specific thresholds
42
51
  if (metricName === 'query_latency' &&
43
- (stats.zScore > 2.0 || stats.mean > 1000)) {
52
+ (stats.zScore > latencyZ || stats.mean > latencyMean)) {
44
53
  const result = await this.optimizeLatency();
45
54
  if (result) {
46
55
  changes.push(...result);
47
56
  evolved = true;
48
57
  }
49
58
  }
59
+ const successZ = policies.find(p => p.name === 'success_rate_z')?.definition?.threshold || -1.5;
60
+ const successMean = policies.find(p => p.name === 'min_success_rate')?.definition?.threshold || 0.7;
50
61
  if (metricName === 'success_rate' &&
51
- (stats.zScore < -1.5 || stats.mean < 0.7)) {
62
+ (stats.zScore < successZ || stats.mean < successMean)) {
52
63
  console.warn(`[EvolutionaryPilot] Success rate collapse detected (${stats.mean.toFixed(2)}). Triggering strategic mutation.`);
53
64
  const strategies = await this.cortex.strategy.mutateStrategy();
54
65
  changes.push(...strategies);
55
66
  evolved = true;
56
67
  }
57
- if (metricName === 'total_cost' && stats.zScore > 2.5) {
68
+ const costZThreshold = policies.find(p => p.name === 'cost_spike_z')?.definition?.threshold || 2.5;
69
+ if (metricName === 'total_cost' && stats.zScore > costZThreshold) {
58
70
  console.warn(`[EvolutionaryPilot] Cost spike detected. Triggering emergency compression.`);
59
71
  await this.cortex.rituals.scheduleRitual('Emergency Compression', 'compression', 'hourly', 'High cost spike detected via Z-score analysis.');
60
72
  changes.push('Scheduled emergency compression due to cost spike');
@@ -26,11 +26,16 @@ export declare class GoalArchitect {
26
26
  private get typedDb();
27
27
  /**
28
28
  * Deconstruct a goal into multiple sub-goals transactionally.
29
+ * Includes circular dependency and terminal duplicate protection.
29
30
  */
30
31
  deconstructGoal(goalId: string | number, subGoals: string[]): Promise<AgentGoal[]>;
32
+ /**
33
+ * Recursive check for circular dependencies in the goal tree.
34
+ * Prevents infinite loops caused by autonomous decomposition.
35
+ */
36
+ private detectCircularDependency;
31
37
  /**
32
38
  * Reorder goals by updating their priorities in batch.
33
- * Lower number = higher priority.
34
39
  */
35
40
  reorderGoals(goalIds: (string | number)[]): Promise<void>;
36
41
  /**
@@ -39,7 +44,6 @@ export declare class GoalArchitect {
39
44
  markGoalAs(goalId: string | number, status: AgentGoal['status'], outcome?: string): Promise<AgentGoal>;
40
45
  /**
41
46
  * Check if a goal is blocked by uncompleted sub-goals.
42
- * Returns true if all sub-goals are completed, false otherwise.
43
47
  */
44
48
  checkGoalDependencies(goalId: string | number): Promise<{
45
49
  canComplete: boolean;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GoalArchitect = void 0;
4
+ const similarity_js_1 = require("../../util/similarity.js");
4
5
  /**
5
6
  * GoalArchitect enables agents to autonomously deconstruct complex
6
7
  * objectives into manageable sub-goals.
@@ -19,22 +20,35 @@ class GoalArchitect {
19
20
  }
20
21
  /**
21
22
  * Deconstruct a goal into multiple sub-goals transactionally.
23
+ * Includes circular dependency and terminal duplicate protection.
22
24
  */
23
25
  async deconstructGoal(goalId, subGoals) {
24
26
  return await this.db.transaction().execute(async (trx) => {
27
+ // 1. Audit Phase 9: Circular Dependency Protection inside transaction
28
+ await this.detectCircularDependency(goalId, new Set(), trx);
25
29
  const goal = (await trx
26
30
  .selectFrom(this.goalsTable)
27
31
  .selectAll()
28
32
  .where('id', '=', goalId)
33
+ .forUpdate() // Audit Phase 9: Atomic acquisition
29
34
  .executeTakeFirst());
30
35
  if (!goal)
31
36
  throw new Error(`Goal ${goalId} not found`);
32
- console.log(`[GoalArchitect] Deconstructing goal ${goalId}: "${goal.description}" into ${subGoals.length} steps.`);
37
+ // 2. Production Hardening: Semantic Duplicate Detection
38
+ const existingSubGoals = await trx
39
+ .selectFrom(this.goalsTable)
40
+ .select('description')
41
+ .where('parent_id', '=', goalId)
42
+ .execute();
33
43
  const created = [];
34
- // Calculate base priority for sub-goals (higher than parent)
35
44
  const basePriority = (goal.priority || 0) + 1;
36
45
  for (let i = 0; i < subGoals.length; i++) {
37
46
  const desc = subGoals[i];
47
+ const isDuplicate = existingSubGoals.some(ex => (0, similarity_js_1.calculateSimilarity)(ex.description, desc) > 0.9);
48
+ if (isDuplicate) {
49
+ console.log(`[GoalArchitect] Skipping duplicate sub-goal: "${desc}"`);
50
+ continue;
51
+ }
38
52
  const subGoal = (await trx
39
53
  .insertInto(this.goalsTable)
40
54
  .values({
@@ -42,7 +56,7 @@ class GoalArchitect {
42
56
  parent_id: goalId,
43
57
  description: desc,
44
58
  status: 'pending',
45
- priority: basePriority + i, // Sequential priority
59
+ priority: basePriority + i,
46
60
  created_at: new Date(),
47
61
  updated_at: new Date(),
48
62
  })
@@ -50,7 +64,6 @@ class GoalArchitect {
50
64
  .executeTakeFirstOrThrow());
51
65
  created.push(this.parseGoal(subGoal));
52
66
  }
53
- // Update parent status to in_progress if it was pending
54
67
  if (goal.status === 'pending') {
55
68
  await trx
56
69
  .updateTable(this.goalsTable)
@@ -61,12 +74,39 @@ class GoalArchitect {
61
74
  return created;
62
75
  });
63
76
  }
77
+ /**
78
+ * Recursive check for circular dependencies in the goal tree.
79
+ * Prevents infinite loops caused by autonomous decomposition.
80
+ */
81
+ async detectCircularDependency(startId, visited = new Set(), trx) {
82
+ if (visited.has(startId)) {
83
+ throw new Error(`Circular dependency detected in goal hierarchy at ID: ${startId}`);
84
+ }
85
+ visited.add(startId);
86
+ const db = trx || this.db;
87
+ const goal = await db
88
+ .selectFrom(this.goalsTable)
89
+ .select('parent_id')
90
+ .where('id', '=', startId)
91
+ .executeTakeFirst();
92
+ if (goal?.parent_id) {
93
+ await this.detectCircularDependency(goal.parent_id, visited, trx);
94
+ }
95
+ }
64
96
  /**
65
97
  * Reorder goals by updating their priorities in batch.
66
- * Lower number = higher priority.
67
98
  */
68
99
  async reorderGoals(goalIds) {
100
+ // Audit Phase 9: Sort IDs to prevent deadlocks during batch acquisition
101
+ const sortedIds = [...goalIds].sort((a, b) => String(a).localeCompare(String(b)));
69
102
  await this.db.transaction().execute(async (trx) => {
103
+ // Pre-lock all rows in deterministic order
104
+ await trx
105
+ .selectFrom(this.goalsTable)
106
+ .select('id')
107
+ .where('id', 'in', sortedIds)
108
+ .forUpdate()
109
+ .execute();
70
110
  for (let i = 0; i < goalIds.length; i++) {
71
111
  await trx
72
112
  .updateTable(this.goalsTable)
@@ -80,34 +120,36 @@ class GoalArchitect {
80
120
  * Update a goal's status and optionally log outcome/reason in metadata.
81
121
  */
82
122
  async markGoalAs(goalId, status, outcome) {
83
- const goal = await this.typedDb
84
- .selectFrom(this.goalsTable)
85
- .selectAll()
86
- .where('id', '=', goalId)
87
- .executeTakeFirst();
88
- if (!goal)
89
- throw new Error(`Goal ${goalId} not found`);
90
- const currentMeta = goal.metadata ? JSON.parse(goal.metadata) : {};
91
- const newMeta = {
92
- ...currentMeta,
93
- lastStatusChange: Date.now(),
94
- outcome: outcome || currentMeta.outcome,
95
- };
96
- const updated = (await this.db
97
- .updateTable(this.goalsTable)
98
- .set({
99
- status,
100
- metadata: JSON.stringify(newMeta),
101
- updated_at: new Date(),
102
- })
103
- .where('id', '=', goalId)
104
- .returningAll()
105
- .executeTakeFirstOrThrow());
106
- return this.parseGoal(updated);
123
+ return await this.db.transaction().execute(async (trx) => {
124
+ const goal = (await trx
125
+ .selectFrom(this.goalsTable)
126
+ .selectAll()
127
+ .where('id', '=', goalId)
128
+ .forUpdate() // Audit Phase 9: Atomic status/meta update
129
+ .executeTakeFirst());
130
+ if (!goal)
131
+ throw new Error(`Goal ${goalId} not found`);
132
+ const currentMeta = goal.metadata ? JSON.parse(goal.metadata) : {};
133
+ const newMeta = {
134
+ ...currentMeta,
135
+ lastStatusChange: Date.now(),
136
+ outcome: outcome || currentMeta.outcome,
137
+ };
138
+ const updated = (await trx
139
+ .updateTable(this.goalsTable)
140
+ .set({
141
+ status,
142
+ metadata: JSON.stringify(newMeta),
143
+ updated_at: new Date(),
144
+ })
145
+ .where('id', '=', goalId)
146
+ .returningAll()
147
+ .executeTakeFirstOrThrow());
148
+ return this.parseGoal(updated);
149
+ });
107
150
  }
108
151
  /**
109
152
  * Check if a goal is blocked by uncompleted sub-goals.
110
- * Returns true if all sub-goals are completed, false otherwise.
111
153
  */
112
154
  async checkGoalDependencies(goalId) {
113
155
  const subGoals = await this.typedDb
@@ -128,7 +170,6 @@ class GoalArchitect {
128
170
  * Identify goals that have "stalled" (no status changes in > 7 days)
129
171
  */
130
172
  async trackStalledGoals(daysThreshold = 7) {
131
- console.log('[GoalArchitect] Identifying stalled objectives...');
132
173
  const thresholdDate = new Date(Date.now() - daysThreshold * 24 * 3600000);
133
174
  const stalled = (await this.typedDb
134
175
  .selectFrom(this.goalsTable)
@@ -136,9 +177,6 @@ class GoalArchitect {
136
177
  .where('status', 'in', ['pending', 'in_progress'])
137
178
  .where('updated_at', '<', thresholdDate)
138
179
  .execute());
139
- if (stalled.length > 0) {
140
- console.log(`[GoalArchitect] Identified ${stalled.length} stalled goals.`);
141
- }
142
180
  return stalled.map((g) => this.parseGoal(g));
143
181
  }
144
182
  parseGoal(g) {
@@ -4,6 +4,8 @@ import type { Cortex } from '../Cortex.js';
4
4
  /**
5
5
  * GovernanceManager monitors agent performance and enforces high-level "sanity"
6
6
  * across the entire agentic infrastructure.
7
+ *
8
+ * Refactored to delegate specialized auditing to modular components.
7
9
  */
8
10
  export declare class GovernanceManager {
9
11
  private db;
@@ -12,6 +14,14 @@ export declare class GovernanceManager {
12
14
  private metricsTable;
13
15
  private policiesTable;
14
16
  private personasTable;
17
+ private skillsTable;
18
+ private budgetAuditor;
19
+ private performanceAuditor;
20
+ private personaAuditor;
21
+ private skillAuditor;
22
+ private emergenceAuditor;
23
+ private remediationEngine;
24
+ private maintenanceOracle;
15
25
  constructor(db: Kysely<any>, cortex: Cortex, config?: AgenticConfig);
16
26
  /**
17
27
  * Perform a "Panic Check" - looking for critical failures or cost overruns
@@ -21,15 +31,19 @@ export declare class GovernanceManager {
21
31
  issues: string[];
22
32
  }>;
23
33
  /**
24
- * Retrieves the currently active persona.
34
+ * Suggest architectural repairs if performance is degrading
25
35
  */
26
- private getActivePersona;
36
+ suggestRepairs(): Promise<string[]>;
27
37
  /**
28
- * Trigger autonomous remediation steps based on specific failure modes
38
+ * Quarantine a persona that is behaving outside safety parameters.
29
39
  */
30
- private triggerRemediation;
40
+ quarantinePersona(id: string | number, reason: string): Promise<void>;
31
41
  /**
32
- * Suggest architectural repairs if performance is degrading
42
+ * Blacklist a skill that is causing systemic issues.
33
43
  */
34
- suggestRepairs(): Promise<string[]>;
44
+ quarantineSkill(name: string, reason: string): Promise<void>;
45
+ /**
46
+ * Monitor cross-node behaviors and flag sudden spikes or malicious patterns.
47
+ */
48
+ validateEmergentBehavior(trx?: any): Promise<string[]>;
35
49
  }