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
@@ -36,11 +36,14 @@ export class StrategicPlanner {
36
36
  .selectFrom(this.personasTable)
37
37
  .selectAll()
38
38
  .execute();
39
+ const allParsedPersonas = personas.map((p) => this.parsePersona(p));
40
+ const globalBlacklistDuration = this.config.strategy?.globalBlacklistDuration || 3600000; // 1 hour
41
+ const localBlacklistDuration = this.config.strategy?.localBlacklistDuration || 86400000; // 24 hours
39
42
  for (const p of personas) {
40
43
  const persona = this.parsePersona(p);
41
44
  // 1. Verification Monitor
42
45
  if (persona.metadata?.evolution_status === 'verifying') {
43
- const result = await this.verifyEvolution(persona);
46
+ const result = await this.verifyEvolution(persona, allParsedPersonas);
44
47
  if (result)
45
48
  mutations.push(result);
46
49
  continue;
@@ -50,20 +53,15 @@ export class StrategicPlanner {
50
53
  const report = await this.analyzePersona(persona.id);
51
54
  // 3. Blacklist Check (Local & Global Phase 5)
52
55
  const lastMutation = persona.metadata?.last_failed_mutation;
53
- const allPersonas = await this.typedDb
54
- .selectFrom(this.personasTable)
55
- .selectAll()
56
- .execute();
57
- const isGloballyBlacklisted = allPersonas.some((p) => {
58
- const mp = this.parsePersona(p);
56
+ const isGloballyBlacklisted = allParsedPersonas.some((mp) => {
59
57
  return (mp.metadata?.last_failed_mutation?.type === report.recommendation &&
60
58
  Date.now() - (mp.metadata?.last_failed_mutation?.timestamp || 0) <
61
- 3600000);
59
+ globalBlacklistDuration);
62
60
  });
63
61
  if (isGloballyBlacklisted ||
64
62
  (lastMutation &&
65
63
  report.recommendation === lastMutation.type &&
66
- Date.now() - lastMutation.timestamp < 86400000)) {
64
+ Date.now() - lastMutation.timestamp < localBlacklistDuration)) {
67
65
  console.log(`[StrategicPlanner] Skipping blacklisted mutation ${report.recommendation} for persona ${persona.id} (Global=${isGloballyBlacklisted})`);
68
66
  continue;
69
67
  }
@@ -109,15 +107,19 @@ export class StrategicPlanner {
109
107
  .filter((p) => (p.metadata?.evolution_status === 'stable' ||
110
108
  !p.metadata?.evolution_status) &&
111
109
  p.metadata?.mutation_reason?.includes(report.recommendation));
112
- if (winningMutations.length > 0 && Math.random() > 0.5) {
113
- console.log(`[StrategicPlanner] Cross-Pollinating success from Persona ${winningMutations[0].id}`);
114
- updates = { role: winningMutations[0].role || persona.role };
110
+ if (winningMutations.length > 0) {
111
+ // PRODUCTION HARDENING: Deterministic Alpha Selection
112
+ // Instead of Math.random(), pick the variant with the highest anchored reliability
113
+ const sorted = winningMutations.sort((a, b) => (b.metadata?.anchored_reliability || 0) - (a.metadata?.anchored_reliability || 0));
114
+ const alphaMatch = sorted[0];
115
+ console.log(`[StrategicPlanner] Cross-Pollinating success from Alpha Persona ${alphaMatch.id} (Reliability: ${alphaMatch.metadata?.anchored_reliability || 0})`);
116
+ updates = { role: this.sanitizeRole(alphaMatch.role || persona.role || 'Agent') };
115
117
  }
116
118
  else {
117
119
  switch (report.recommendation) {
118
120
  case 'optimize_accuracy':
119
121
  updates = {
120
- role: `${persona.role || ''} (Focus strictly on accuracy and detailed verification)`.trim(),
122
+ role: this.sanitizeRole(`${persona.role || ''} (Focus strictly on accuracy and detailed verification)`),
121
123
  };
122
124
  break;
123
125
  case 'optimize_efficiency':
@@ -137,6 +139,9 @@ export class StrategicPlanner {
137
139
  }
138
140
  }
139
141
  }
142
+ if (updates.role) {
143
+ updates.role = this.sanitizeRole(updates.role);
144
+ }
140
145
  // 1. Predictive Conflict Detection (Pre-flight)
141
146
  const proposedState = { ...persona, ...updates };
142
147
  const contradictions = await this.cortex.reasoner.detectContradictions();
@@ -196,18 +201,13 @@ export class StrategicPlanner {
196
201
  * Check if a persona in verification should be stabilized or rolled back.
197
202
  * Uses dynamic statistical variance and adaptive meta-tuning.
198
203
  */
199
- async verifyEvolution(persona) {
204
+ async verifyEvolution(persona, allPersonas = []) {
200
205
  const report = await this.analyzePersona(persona.id);
201
206
  // Adaptive Meta-Tuning: Increase window based on rollback history (Phase 4)
202
207
  const rollbackHistory = persona.metadata?.rollbackHistory || [];
203
208
  const recentRollbacks = rollbackHistory.filter((ts) => Date.now() - ts < 604800000).length;
204
209
  // Hive-Mind Verification Speedups (Phase 5)
205
- const allPersonas = await this.typedDb
206
- .selectFrom(this.personasTable)
207
- .selectAll()
208
- .execute();
209
210
  const hiveTrusted = allPersonas
210
- .map((p) => this.parsePersona(p))
211
211
  .filter((p) => p.metadata?.evolution_status === 'stable' &&
212
212
  p.metadata?.mutation_reason === persona.metadata?.mutation_reason).length;
213
213
  let sampleSizeThreshold = 10 + recentRollbacks * 10;
@@ -430,6 +430,13 @@ export class StrategicPlanner {
430
430
  return `Rolled back mutation ${lastMutation.id} for persona ${id}`;
431
431
  });
432
432
  }
433
+ sanitizeRole(role) {
434
+ // Audit Phase 7: Semantic Security
435
+ // Truncate to prevent context-window exhaustion/bloat
436
+ const truncated = role.slice(0, 500).trim();
437
+ // Sanitize: remove potentially dangerous prompt-injection markers or control chars
438
+ return truncated.replace(/[\u0000-\u001F\u007F-\u009F]/g, '').replace(/<\|.*?\|>/g, '');
439
+ }
433
440
  parsePersona(p) {
434
441
  return {
435
442
  id: p.id,
@@ -0,0 +1,17 @@
1
+ import type { Kysely } from '../../../kysely.js';
2
+ import type { AgenticConfig } from '../../../types/index.js';
3
+ import type { Cortex } from '../../Cortex.js';
4
+ export interface AuditContext {
5
+ db: Kysely<any>;
6
+ trx: Kysely<any>;
7
+ cortex: Cortex;
8
+ config: AgenticConfig;
9
+ metricsTable: string;
10
+ policiesTable: string;
11
+ personasTable: string;
12
+ skillsTable: string;
13
+ }
14
+ export interface AuditResult {
15
+ issues: string[];
16
+ metadata: Record<string, any>;
17
+ }
@@ -0,0 +1,2 @@
1
+ /// <reference types="./AuditContext.d.ts" />
2
+ export {};
@@ -0,0 +1,4 @@
1
+ import type { AuditContext, AuditResult } from './AuditContext.js';
2
+ export declare class BudgetAuditor {
3
+ audit(ctx: AuditContext): Promise<AuditResult>;
4
+ }
@@ -0,0 +1,47 @@
1
+ /// <reference types="./BudgetAuditor.d.ts" />
2
+ export class BudgetAuditor {
3
+ async audit(ctx) {
4
+ const issues = [];
5
+ // Fetch budget policies
6
+ const policies = (await ctx.trx
7
+ .selectFrom(ctx.policiesTable)
8
+ .selectAll()
9
+ .where('is_enabled', '=', true)
10
+ .where((eb) => eb.or([
11
+ eb('name', '=', 'hourly_budget'),
12
+ eb('name', '=', 'daily_budget'),
13
+ eb('type', '=', 'budget')
14
+ ]))
15
+ .execute());
16
+ const getLimit = (name) => {
17
+ const p = policies.find(p => p.name === name);
18
+ if (!p)
19
+ return 0;
20
+ const def = typeof p.definition === 'string' ? JSON.parse(p.definition) : p.definition;
21
+ return def.threshold ?? def.limit ?? 0;
22
+ };
23
+ const hourlyLimit = getLimit('hourly_budget');
24
+ const dailyLimit = getLimit('daily_budget');
25
+ const getCostInWindow = async (ms) => {
26
+ const result = await ctx.trx
27
+ .selectFrom(ctx.metricsTable)
28
+ .select((eb) => eb.fn.sum('metric_value').as('total'))
29
+ .where('metric_name', '=', 'total_cost')
30
+ .where('created_at', '>', new Date(Date.now() - ms))
31
+ .executeTakeFirst();
32
+ return Number(result?.total || 0);
33
+ };
34
+ const hCost = await getCostInWindow(3600000);
35
+ if (hCost > hourlyLimit && hourlyLimit > 0) {
36
+ issues.push(`Budget Violations: Hourly cost ($${hCost.toFixed(2)}) exceeded policy ($${hourlyLimit.toFixed(2)})`);
37
+ }
38
+ const dCost = await getCostInWindow(86400000);
39
+ if (dCost > dailyLimit && dailyLimit > 0) {
40
+ issues.push(`Budget Violations: Daily cumulative cost ($${dCost.toFixed(2)}) exceeded safety ceiling ($${dailyLimit.toFixed(2)})`);
41
+ }
42
+ return {
43
+ issues,
44
+ metadata: { hCost, hourlyLimit, dCost, dailyLimit }
45
+ };
46
+ }
47
+ }
@@ -0,0 +1,4 @@
1
+ import type { AuditContext, AuditResult } from './AuditContext.js';
2
+ export declare class EmergenceAuditor {
3
+ audit(ctx: AuditContext): Promise<AuditResult>;
4
+ }
@@ -0,0 +1,34 @@
1
+ /// <reference types="./EmergenceAuditor.d.ts" />
2
+ export class EmergenceAuditor {
3
+ async audit(ctx) {
4
+ const issues = [];
5
+ // 1. Check for rapid propagation of new skills (Potential poisoning)
6
+ const recentSkills = await ctx.trx
7
+ .selectFrom(ctx.skillsTable)
8
+ .select(['name', 'created_at'])
9
+ .where('created_at', '>', new Date(Date.now() - 3600000)) // Last hour
10
+ .execute();
11
+ if (recentSkills.length > 10) {
12
+ issues.push(`Emergent Warning: Rapid skill propagation detected (${recentSkills.length} new skills in 1hr). Potential rogue behavior.`);
13
+ }
14
+ // 2. Check for high variance in task success across swarm
15
+ const recentTaskMetrics = await ctx.trx
16
+ .selectFrom(ctx.metricsTable)
17
+ .select(['metric_value', 'metadata'])
18
+ .where('metric_name', '=', 'task_success_rate')
19
+ .where('created_at', '>', new Date(Date.now() - 1800000)) // Last 30m
20
+ .execute();
21
+ if (recentTaskMetrics.length >= 5) {
22
+ const values = recentTaskMetrics.map((m) => Number(m.metric_value));
23
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
24
+ const variance = values.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / values.length;
25
+ if (variance > 0.2) {
26
+ issues.push(`Emergent Warning: High variance in swarm success rate (${(variance * 100).toFixed(1)}%). Potential node instability.`);
27
+ }
28
+ }
29
+ return {
30
+ issues,
31
+ metadata: { recentSkillCount: recentSkills.length, successVariance: recentTaskMetrics.length >= 5 ? issues.length > 0 : null }
32
+ };
33
+ }
34
+ }
@@ -0,0 +1,4 @@
1
+ import type { AuditContext } from './AuditContext.js';
2
+ export declare class MaintenanceOracle {
3
+ suggestRepairs(ctx: AuditContext): Promise<string[]>;
4
+ }
@@ -0,0 +1,64 @@
1
+ /// <reference types="./MaintenanceOracle.d.ts" />
2
+ export class MaintenanceOracle {
3
+ async suggestRepairs(ctx) {
4
+ const repairs = [];
5
+ // Fetch maintenance policies
6
+ const policies = (await ctx.db
7
+ .selectFrom(ctx.policiesTable)
8
+ .selectAll()
9
+ .where('is_enabled', '=', true)
10
+ .execute());
11
+ const getPolicyValue = (name, fallback) => {
12
+ const p = policies.find(p => p.name === name);
13
+ if (!p)
14
+ return fallback;
15
+ const def = typeof p.definition === 'string' ? JSON.parse(p.definition) : p.definition;
16
+ return def.threshold ?? def.limit ?? def.days ?? fallback;
17
+ };
18
+ const latencyPolicy = getPolicyValue('latency_repair_threshold', 500);
19
+ const costPolicy = getPolicyValue('high_cost_threshold', 0.5);
20
+ const storagePolicy = getPolicyValue('cold_storage_threshold', 30);
21
+ // 1. Check for chronic high latency
22
+ const latencyStats = await ctx.cortex.metrics.getMetricStats('query_latency');
23
+ if (latencyStats.avg > latencyPolicy && latencyStats.count > 10) {
24
+ repairs.push(`Average latency is high (${latencyStats.avg.toFixed(2)}ms). Suggesting index audit across hit tables.`);
25
+ }
26
+ // 2. Detect specific slow tables
27
+ const recentSlowQueries = await ctx.db
28
+ .selectFrom(ctx.metricsTable)
29
+ .select('metadata')
30
+ .where('metric_name', '=', 'query_latency')
31
+ .where('metric_value', '>', latencyPolicy * 2)
32
+ .limit(20)
33
+ .execute();
34
+ const slowTables = new Set();
35
+ for (const q of recentSlowQueries) {
36
+ try {
37
+ const meta = typeof q.metadata === 'string' ? JSON.parse(q.metadata) : q.metadata || {};
38
+ if (meta.table)
39
+ slowTables.add(meta.table);
40
+ }
41
+ catch (e) { }
42
+ }
43
+ for (const table of slowTables) {
44
+ repairs.push(`Table '${table}' is experiencing periodic latency spikes. Suggesting 'CREATE INDEX' for common filters.`);
45
+ }
46
+ // 3. Check for high cost
47
+ const totalCost = await ctx.cortex.metrics.getAverageMetric('total_cost');
48
+ if (totalCost > costPolicy) {
49
+ repairs.push('Average query cost is high. Suggesting prompt compression or model switching (e.g., to a smaller model).');
50
+ }
51
+ // 4. Cold storage candidates
52
+ const oldThreshold = new Date(Date.now() - storagePolicy * 24 * 60 * 60 * 1000);
53
+ const sessionsTable = ctx.config.sessionsTable || 'agent_sessions';
54
+ const oldSessions = (await ctx.db
55
+ .selectFrom(sessionsTable)
56
+ .select((eb) => eb.fn.count('id').as('count'))
57
+ .where('created_at', '<', oldThreshold)
58
+ .executeTakeFirst());
59
+ if (Number(oldSessions?.count || 0) > 100) {
60
+ repairs.push(`[STORAGE OPTIMIZATION] Found ${oldSessions.count} sessions older than ${storagePolicy} days. Consider moving to cold storage.`);
61
+ }
62
+ return repairs;
63
+ }
64
+ }
@@ -0,0 +1,4 @@
1
+ import type { AuditContext, AuditResult } from './AuditContext.js';
2
+ export declare class PerformanceAuditor {
3
+ audit(ctx: AuditContext): Promise<AuditResult>;
4
+ }
@@ -0,0 +1,40 @@
1
+ /// <reference types="./PerformanceAuditor.d.ts" />
2
+ export class PerformanceAuditor {
3
+ async audit(ctx) {
4
+ const issues = [];
5
+ // Fetch safety policies for success rate
6
+ const policies = (await ctx.trx
7
+ .selectFrom(ctx.policiesTable)
8
+ .selectAll()
9
+ .where('is_enabled', '=', true)
10
+ .where((eb) => eb.or([
11
+ eb('name', '=', 'min_success_rate'),
12
+ eb('type', '=', 'safety')
13
+ ]))
14
+ .execute());
15
+ const getLimit = (name) => {
16
+ const p = policies.find(p => p.name === name);
17
+ if (!p)
18
+ return 0.8; // Default success floor
19
+ const def = typeof p.definition === 'string' ? JSON.parse(p.definition) : p.definition;
20
+ return def.threshold ?? def.limit ?? 0.8;
21
+ };
22
+ const minSuccess = getLimit('min_success_rate');
23
+ // Statistical Success Rate (last 100 events)
24
+ const recentSuccess = await ctx.trx
25
+ .selectFrom(ctx.metricsTable)
26
+ .select((eb) => eb.fn.avg('metric_value').as('avg'))
27
+ .where('metric_name', '=', 'success_rate')
28
+ .orderBy('created_at', 'desc')
29
+ .limit(100)
30
+ .executeTakeFirst();
31
+ const success = Number(recentSuccess?.avg || 1);
32
+ if (success < minSuccess) {
33
+ issues.push(`Performance Degradation: Rolling success rate (${Math.round(success * 100)}%) is below policy requirement (${minSuccess * 100}%)`);
34
+ }
35
+ return {
36
+ issues,
37
+ metadata: { success, minSuccess }
38
+ };
39
+ }
40
+ }
@@ -0,0 +1,6 @@
1
+ import type { AuditContext, AuditResult } from './AuditContext.js';
2
+ export declare class PersonaAuditor {
3
+ audit(ctx: AuditContext): Promise<AuditResult>;
4
+ private getActivePersona;
5
+ quarantinePersona(ctx: AuditContext, id: string | number, reason: string): Promise<void>;
6
+ }
@@ -0,0 +1,71 @@
1
+ /// <reference types="./PersonaAuditor.d.ts" />
2
+ export class PersonaAuditor {
3
+ async audit(ctx) {
4
+ const issues = [];
5
+ const activePersona = await this.getActivePersona(ctx);
6
+ if (activePersona) {
7
+ const quotaCheck = await ctx.cortex.quotas.checkQuota('persona', activePersona.id);
8
+ if (!quotaCheck.allowed) {
9
+ issues.push(`Quota Breach: ${quotaCheck.reason}`);
10
+ }
11
+ // Check for swarm-level quotas if part of a swarm
12
+ const swarmId = activePersona.metadata?.swarm_id;
13
+ if (swarmId) {
14
+ const swarmCheck = await ctx.cortex.quotas.checkQuota('swarm', swarmId);
15
+ if (!swarmCheck.allowed) {
16
+ issues.push(`Swarm Quota Breach [${swarmId}]: ${swarmCheck.reason}`);
17
+ }
18
+ }
19
+ }
20
+ return {
21
+ issues,
22
+ metadata: { activePersona }
23
+ };
24
+ }
25
+ async getActivePersona(ctx) {
26
+ const active = await ctx.trx
27
+ .selectFrom(ctx.personasTable)
28
+ .selectAll()
29
+ .where('status', '=', 'active')
30
+ .executeTakeFirst();
31
+ if (!active)
32
+ return null;
33
+ return {
34
+ ...active,
35
+ metadata: typeof active.metadata === 'string'
36
+ ? JSON.parse(active.metadata)
37
+ : active.metadata || {},
38
+ };
39
+ }
40
+ async quarantinePersona(ctx, id, reason) {
41
+ console.warn(`[PersonaAuditor] QUARANTINING Persona ${id}: ${reason}`);
42
+ let query = ctx.db
43
+ .selectFrom(ctx.personasTable)
44
+ .selectAll()
45
+ .where('id', '=', id);
46
+ // SQLite doesn't support SELECT ... FOR UPDATE easily in Kysely without specific dialect support
47
+ // But we are in a transaction usually if passed ctx.trx.
48
+ // Here we use ctx.db for the quarantine update if it's a standalone call.
49
+ const persona = await query.executeTakeFirst();
50
+ if (persona) {
51
+ const metadata = typeof persona.metadata === 'string'
52
+ ? JSON.parse(persona.metadata)
53
+ : persona.metadata || {};
54
+ await ctx.db
55
+ .updateTable(ctx.personasTable)
56
+ .set({
57
+ status: 'quarantined',
58
+ metadata: JSON.stringify({
59
+ ...metadata,
60
+ quarantine_reason: reason,
61
+ quarantined_at: new Date(),
62
+ }),
63
+ updated_at: new Date(),
64
+ })
65
+ .where('id', '=', id)
66
+ .execute();
67
+ // Rollback most recent changes via strategy engine
68
+ await ctx.cortex.strategy.rollbackPersona(id);
69
+ }
70
+ }
71
+ }
@@ -0,0 +1,5 @@
1
+ import type { AuditContext } from './AuditContext.js';
2
+ export declare class RemediationEngine {
3
+ triggerRemediation(ctx: AuditContext, issues: string[]): Promise<void>;
4
+ private remediateSkillFailure;
5
+ }
@@ -0,0 +1,40 @@
1
+ /// <reference types="./RemediationEngine.d.ts" />
2
+ export class RemediationEngine {
3
+ async triggerRemediation(ctx, issues) {
4
+ for (const issue of issues) {
5
+ if (issue.includes('Budget Violations')) {
6
+ await ctx.cortex.rituals.scheduleRitual('Budget Remediation', 'compression', 'hourly', `Automated response to: ${issue}`, { priority: 'critical', enforce_limits: true });
7
+ }
8
+ if (issue.includes('Performance Degradation')) {
9
+ await ctx.cortex.rituals.scheduleRitual('Reliability Sweep', 'pruning', 'daily', `Sanitizing high-noise memories due to: ${issue}`, { priority: 'medium', target: 'longtail' });
10
+ }
11
+ if (issue.includes('Integrity Failure')) {
12
+ await this.remediateSkillFailure(ctx, issue);
13
+ }
14
+ if (issue.includes('Quota Breach') || issue.includes('Swarm Quota Breach')) {
15
+ await ctx.cortex.rituals.scheduleRitual('Resource Throttling', 'pruning', 'hourly', `Critical resource containment: ${issue}`, { priority: 'critical', active_containment: true });
16
+ }
17
+ }
18
+ }
19
+ async remediateSkillFailure(ctx, issue) {
20
+ const skillName = issue.match(/'([^']+)'/)?.[1];
21
+ if (!skillName)
22
+ return;
23
+ console.log(`[RemediationEngine] Demoting tainted skill out of verified pool: ${skillName}`);
24
+ // Use a fresh transaction for remediation if possible, or use ctx.trx
25
+ await ctx.db.transaction().execute(async (trx) => {
26
+ const skill = await trx
27
+ .selectFrom(ctx.skillsTable)
28
+ .select('id')
29
+ .where('name', '=', skillName)
30
+ .executeTakeFirst();
31
+ if (skill) {
32
+ await trx
33
+ .updateTable(ctx.skillsTable)
34
+ .set({ status: 'experimental', updated_at: new Date() })
35
+ .where('id', '=', skill.id)
36
+ .execute();
37
+ }
38
+ });
39
+ }
40
+ }
@@ -0,0 +1,5 @@
1
+ import type { AuditContext, AuditResult } from './AuditContext.js';
2
+ export declare class SkillAuditor {
3
+ audit(ctx: AuditContext): Promise<AuditResult>;
4
+ quarantineSkill(ctx: AuditContext, name: string, reason: string): Promise<void>;
5
+ }
@@ -0,0 +1,49 @@
1
+ /// <reference types="./SkillAuditor.d.ts" />
2
+ export class SkillAuditor {
3
+ async audit(ctx) {
4
+ const issues = [];
5
+ // Fetch integrity policies for reliability floor
6
+ const policies = (await ctx.trx
7
+ .selectFrom(ctx.policiesTable)
8
+ .selectAll()
9
+ .where('is_enabled', '=', true)
10
+ .where((eb) => eb.or([
11
+ eb('name', '=', 'reliability_floor'),
12
+ eb('type', '=', 'integrity')
13
+ ]))
14
+ .execute());
15
+ const getLimit = (name) => {
16
+ const p = policies.find(p => p.name === name);
17
+ if (!p)
18
+ return 0.7; // Default reliability floor
19
+ const def = typeof p.definition === 'string' ? JSON.parse(p.definition) : p.definition;
20
+ return def.threshold ?? def.limit ?? 0.7;
21
+ };
22
+ const reliabilityLimit = getLimit('reliability_floor');
23
+ const failingVerified = await ctx.trx
24
+ .selectFrom(ctx.skillsTable)
25
+ .select(['name', 'reliability'])
26
+ .where('status', '=', 'verified')
27
+ .where('reliability', '<', reliabilityLimit)
28
+ .execute();
29
+ for (const cap of failingVerified) {
30
+ issues.push(`Integrity Failure: Verified skill '${cap.name}' reliability (${cap.reliability.toFixed(2)}) dropped below floor (${reliabilityLimit})`);
31
+ }
32
+ return {
33
+ issues,
34
+ metadata: { reliabilityLimit, failingVerifiedCount: failingVerified.length }
35
+ };
36
+ }
37
+ async quarantineSkill(ctx, name, reason) {
38
+ console.warn(`[SkillAuditor] BLACKLISTING Skill ${name}: ${reason}`);
39
+ await ctx.db
40
+ .updateTable(ctx.skillsTable)
41
+ .set({
42
+ status: 'blacklisted',
43
+ metadata: JSON.stringify({ blacklist_reason: reason, blacklisted_at: new Date() }),
44
+ updated_at: new Date()
45
+ })
46
+ .where('name', '=', name)
47
+ .execute();
48
+ }
49
+ }
@@ -22,5 +22,10 @@ export declare class CognitiveSynthesizer {
22
22
  private inferGoalFromContent;
23
23
  private detectStrategy;
24
24
  private calculateAutonomy;
25
+ /**
26
+ * Detect "Sentiment Drift" or Cognitive Friction in the input stream.
27
+ * Mirrors the agent's internal "frustration" or "flow" state.
28
+ */
29
+ private detectSentimentDrift;
25
30
  private parsePath;
26
31
  }
@@ -19,8 +19,15 @@ export class CognitiveSynthesizer {
19
19
  * Uses robust transaction logic and behavioral pathing.
20
20
  */
21
21
  async synthesize(sessionId, input, pattern) {
22
- // Production: structured goal inference logic
23
- const goalInferred = this.inferGoalFromContent(input);
22
+ // PRODUCTION HARDENING: Reasoning-Driven Synthesis
23
+ // Instead of regex heuristics, we leverage the RecursiveReasoner for high-fidelity goal extraction
24
+ const cortex = this.config.cortex;
25
+ let goalInferred = this.inferGoalFromContent(input);
26
+ if (cortex?.reasoner) {
27
+ const reasoning = await cortex.reasoner.analyzeIntent(input);
28
+ if (reasoning.goal)
29
+ goalInferred = reasoning.goal;
30
+ }
24
31
  const strategy = pattern || this.detectStrategy(input);
25
32
  try {
26
33
  await this.db.transaction().execute(async (trx) => {
@@ -31,14 +38,17 @@ export class CognitiveSynthesizer {
31
38
  .executeTakeFirst();
32
39
  if (existing) {
33
40
  const currentPath = this.parsePath(existing.evolution_path);
34
- // Only append to path if goal or strategy shifted significantly
41
+ // Only append to path if goal, strategy, or sentiment shifted significantly
42
+ const sentiment = this.detectSentimentDrift(input);
35
43
  if (existing.inferred_goal !== goalInferred ||
36
- existing.strategy !== strategy) {
44
+ existing.strategy !== strategy ||
45
+ (existing.metadata && JSON.parse(existing.metadata).lastSentiment !== sentiment)) {
37
46
  currentPath.push({
38
47
  timestamp: new Date().toISOString(),
39
48
  previousGoal: existing.inferred_goal,
40
49
  newGoal: goalInferred,
41
50
  strategyShift: strategy,
51
+ sentiment,
42
52
  });
43
53
  }
44
54
  await trx
@@ -48,6 +58,11 @@ export class CognitiveSynthesizer {
48
58
  strategy,
49
59
  evolution_path: JSON.stringify(currentPath),
50
60
  status: 'active',
61
+ metadata: JSON.stringify({
62
+ ...JSON.parse(existing.metadata || '{}'),
63
+ lastSentiment: sentiment,
64
+ pivots: currentPath.length,
65
+ }),
51
66
  autonomy_level: this.calculateAutonomy(currentPath.length, existing.autonomy_level || 1),
52
67
  updated_at: new Date(),
53
68
  })
@@ -122,9 +137,13 @@ export class CognitiveSynthesizer {
122
137
  inferGoalFromContent(content) {
123
138
  // Real-world simulation: extract the first imperative sentence or key noun phrases
124
139
  const clean = content.trim().replace(/\n/g, ' ');
140
+ // Hardened heuristic: prioritize imperative verbs and specific NOORMME intents
141
+ const imperativeMatch = clean.match(/(?:please |can you |let's )?(implement|fix|refactor|add|search|analyze|delete|evolve) .+/i);
142
+ if (imperativeMatch) {
143
+ return imperativeMatch[0].substring(0, 100) + (imperativeMatch[0].length > 100 ? '...' : '');
144
+ }
125
145
  if (clean.length < 100)
126
146
  return clean;
127
- // Simple heuristic: look for "need", "want", "please", "can you"
128
147
  const keywords = [
129
148
  'need',
130
149
  'want',
@@ -144,21 +163,44 @@ export class CognitiveSynthesizer {
144
163
  }
145
164
  detectStrategy(content) {
146
165
  const c = content.toLowerCase();
147
- if (c.includes('debug') || c.includes('fix') || c.includes('error'))
166
+ // Hardened strategy detection
167
+ if (c.includes('debug') || c.includes('fix') || c.includes('error') || c.includes('broken'))
148
168
  return 'Diagnostic Repair';
149
- if (c.includes('create') || c.includes('build') || c.includes('implement'))
169
+ if (c.includes('create') || c.includes('build') || c.includes('implement') || c.includes('new file'))
150
170
  return 'Generative Construction';
151
- if (c.includes('research') || c.includes('explain') || c.includes('how'))
171
+ if (c.includes('research') || c.includes('explain') || c.includes('how') || c.includes('investigate'))
152
172
  return 'Knowledge Acquisition';
173
+ if (c.includes('evolve') || c.includes('mutate') || c.includes('dna'))
174
+ return 'Self-Evolutionary';
153
175
  return 'Adaptive Exploration';
154
176
  }
155
177
  calculateAutonomy(pivots, currentLevel) {
156
- // Logic: frequent pivots without completion decrease autonomy.
157
- // Consistent execution increases it.
158
- if (pivots > 5)
159
- return Math.min(4, currentLevel + 1);
178
+ // Enhanced Autonomy: Lower weight on raw pivots, more on ratio
179
+ // If pivots are moderate but yield successful sub-goals, autonomy holds.
180
+ if (pivots > 10)
181
+ return Math.max(1, currentLevel - 1);
182
+ if (pivots > 5 && currentLevel > 2)
183
+ return currentLevel;
184
+ if (pivots === 0)
185
+ return Math.min(5, currentLevel + 1);
160
186
  return currentLevel;
161
187
  }
188
+ /**
189
+ * Detect "Sentiment Drift" or Cognitive Friction in the input stream.
190
+ * Mirrors the agent's internal "frustration" or "flow" state.
191
+ */
192
+ detectSentimentDrift(content) {
193
+ const c = content.toLowerCase();
194
+ const negativeTerms = ['slow', 'wrong', 'bad', 'error', 'failed', 'cannot', 'stuck'];
195
+ const postiveTerms = ['great', 'correct', 'good', 'success', 'works', 'yes'];
196
+ const negCount = negativeTerms.filter(t => c.includes(t)).length;
197
+ const posCount = postiveTerms.filter(t => c.includes(t)).length;
198
+ if (negCount > posCount + 1)
199
+ return 'frustration';
200
+ if (posCount > negCount)
201
+ return 'flow';
202
+ return 'neutral';
203
+ }
162
204
  parsePath(pathData) {
163
205
  if (!pathData)
164
206
  return [];