noormme 1.2.1 → 1.2.3

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 (44) hide show
  1. package/dist/cjs/agentic/improvement/GovernanceManager.d.ts +14 -6
  2. package/dist/cjs/agentic/improvement/GovernanceManager.js +133 -294
  3. package/dist/cjs/agentic/improvement/QuotaManager.js +1 -1
  4. package/dist/cjs/agentic/improvement/SelfEvolution.js +1 -0
  5. package/dist/cjs/agentic/improvement/governance/AuditContext.d.ts +17 -0
  6. package/dist/cjs/agentic/improvement/governance/AuditContext.js +2 -0
  7. package/dist/cjs/agentic/improvement/governance/BudgetAuditor.d.ts +4 -0
  8. package/dist/cjs/agentic/improvement/governance/BudgetAuditor.js +50 -0
  9. package/dist/cjs/agentic/improvement/governance/EmergenceAuditor.d.ts +4 -0
  10. package/dist/cjs/agentic/improvement/governance/EmergenceAuditor.js +37 -0
  11. package/dist/cjs/agentic/improvement/governance/MaintenanceOracle.d.ts +4 -0
  12. package/dist/cjs/agentic/improvement/governance/MaintenanceOracle.js +67 -0
  13. package/dist/cjs/agentic/improvement/governance/PerformanceAuditor.d.ts +4 -0
  14. package/dist/cjs/agentic/improvement/governance/PerformanceAuditor.js +43 -0
  15. package/dist/cjs/agentic/improvement/governance/PersonaAuditor.d.ts +6 -0
  16. package/dist/cjs/agentic/improvement/governance/PersonaAuditor.js +86 -0
  17. package/dist/cjs/agentic/improvement/governance/RemediationEngine.d.ts +5 -0
  18. package/dist/cjs/agentic/improvement/governance/RemediationEngine.js +43 -0
  19. package/dist/cjs/agentic/improvement/governance/SkillAuditor.d.ts +5 -0
  20. package/dist/cjs/agentic/improvement/governance/SkillAuditor.js +60 -0
  21. package/dist/cjs/cli/index.js +0 -0
  22. package/dist/cjs/helpers/agent-schema.js +14 -14
  23. package/dist/esm/agentic/improvement/GovernanceManager.d.ts +14 -6
  24. package/dist/esm/agentic/improvement/GovernanceManager.js +133 -294
  25. package/dist/esm/agentic/improvement/QuotaManager.js +1 -1
  26. package/dist/esm/agentic/improvement/SelfEvolution.js +1 -0
  27. package/dist/esm/agentic/improvement/governance/AuditContext.d.ts +17 -0
  28. package/dist/esm/agentic/improvement/governance/AuditContext.js +2 -0
  29. package/dist/esm/agentic/improvement/governance/BudgetAuditor.d.ts +4 -0
  30. package/dist/esm/agentic/improvement/governance/BudgetAuditor.js +47 -0
  31. package/dist/esm/agentic/improvement/governance/EmergenceAuditor.d.ts +4 -0
  32. package/dist/esm/agentic/improvement/governance/EmergenceAuditor.js +34 -0
  33. package/dist/esm/agentic/improvement/governance/MaintenanceOracle.d.ts +4 -0
  34. package/dist/esm/agentic/improvement/governance/MaintenanceOracle.js +64 -0
  35. package/dist/esm/agentic/improvement/governance/PerformanceAuditor.d.ts +4 -0
  36. package/dist/esm/agentic/improvement/governance/PerformanceAuditor.js +40 -0
  37. package/dist/esm/agentic/improvement/governance/PersonaAuditor.d.ts +6 -0
  38. package/dist/esm/agentic/improvement/governance/PersonaAuditor.js +83 -0
  39. package/dist/esm/agentic/improvement/governance/RemediationEngine.d.ts +5 -0
  40. package/dist/esm/agentic/improvement/governance/RemediationEngine.js +40 -0
  41. package/dist/esm/agentic/improvement/governance/SkillAuditor.d.ts +5 -0
  42. package/dist/esm/agentic/improvement/governance/SkillAuditor.js +57 -0
  43. package/dist/esm/helpers/agent-schema.js +14 -14
  44. package/package.json +44 -40
@@ -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
@@ -20,7 +30,10 @@ export declare class GovernanceManager {
20
30
  healthy: boolean;
21
31
  issues: string[];
22
32
  }>;
23
- private getActivePersona;
33
+ /**
34
+ * Suggest architectural repairs if performance is degrading
35
+ */
36
+ suggestRepairs(): Promise<string[]>;
24
37
  /**
25
38
  * Quarantine a persona that is behaving outside safety parameters.
26
39
  */
@@ -33,9 +46,4 @@ export declare class GovernanceManager {
33
46
  * Monitor cross-node behaviors and flag sudden spikes or malicious patterns.
34
47
  */
35
48
  validateEmergentBehavior(trx?: any): Promise<string[]>;
36
- private triggerRemediation;
37
- /**
38
- * Suggest architectural repairs if performance is degrading
39
- */
40
- suggestRepairs(): Promise<string[]>;
41
49
  }
@@ -1,9 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.GovernanceManager = void 0;
4
+ const BudgetAuditor_js_1 = require("./governance/BudgetAuditor.js");
5
+ const PerformanceAuditor_js_1 = require("./governance/PerformanceAuditor.js");
6
+ const PersonaAuditor_js_1 = require("./governance/PersonaAuditor.js");
7
+ const SkillAuditor_js_1 = require("./governance/SkillAuditor.js");
8
+ const EmergenceAuditor_js_1 = require("./governance/EmergenceAuditor.js");
9
+ const RemediationEngine_js_1 = require("./governance/RemediationEngine.js");
10
+ const MaintenanceOracle_js_1 = require("./governance/MaintenanceOracle.js");
4
11
  /**
5
12
  * GovernanceManager monitors agent performance and enforces high-level "sanity"
6
13
  * across the entire agentic infrastructure.
14
+ *
15
+ * Refactored to delegate specialized auditing to modular components.
7
16
  */
8
17
  class GovernanceManager {
9
18
  db;
@@ -12,6 +21,14 @@ class GovernanceManager {
12
21
  metricsTable;
13
22
  policiesTable;
14
23
  personasTable;
24
+ skillsTable;
25
+ budgetAuditor;
26
+ performanceAuditor;
27
+ personaAuditor;
28
+ skillAuditor;
29
+ emergenceAuditor;
30
+ remediationEngine;
31
+ maintenanceOracle;
15
32
  constructor(db, cortex, config = {}) {
16
33
  this.db = db;
17
34
  this.cortex = cortex;
@@ -19,326 +36,148 @@ class GovernanceManager {
19
36
  this.metricsTable = config.metricsTable || 'agent_metrics';
20
37
  this.policiesTable = config.policiesTable || 'agent_policies';
21
38
  this.personasTable = config.personasTable || 'agent_personas';
39
+ this.skillsTable = config.capabilitiesTable || 'agent_capabilities';
40
+ this.budgetAuditor = new BudgetAuditor_js_1.BudgetAuditor();
41
+ this.performanceAuditor = new PerformanceAuditor_js_1.PerformanceAuditor();
42
+ this.personaAuditor = new PersonaAuditor_js_1.PersonaAuditor();
43
+ this.skillAuditor = new SkillAuditor_js_1.SkillAuditor();
44
+ this.emergenceAuditor = new EmergenceAuditor_js_1.EmergenceAuditor();
45
+ this.remediationEngine = new RemediationEngine_js_1.RemediationEngine();
46
+ this.maintenanceOracle = new MaintenanceOracle_js_1.MaintenanceOracle();
22
47
  }
23
48
  /**
24
49
  * Perform a "Panic Check" - looking for critical failures or cost overruns
25
50
  */
26
51
  async performAudit() {
27
- const issues = [];
28
- return await this.db.transaction().execute(async (trx) => {
29
- // 0. Emergent Behavior Validation (Phase 2 Safety)
30
- const emergentIssues = await this.validateEmergentBehavior(trx);
31
- issues.push(...emergentIssues);
32
- // Fetch active policies within transaction
33
- const policies = (await trx
34
- .selectFrom(this.policiesTable)
35
- .selectAll()
36
- .where('is_enabled', '=', true)
37
- .execute());
38
- const getPolicyValue = (name, type, strict = true) => {
39
- const p = policies.find((p) => p.name === name || p.type === type);
40
- if (!p) {
41
- if (strict)
42
- throw new Error(`Governance Violation: Required policy '${name}' or type '${type}' not found.`);
43
- return null;
44
- }
45
- const def = typeof p.definition === 'string'
46
- ? JSON.parse(p.definition)
47
- : p.definition;
48
- return def.threshold ?? def.limit ?? 0;
49
- };
50
- try {
51
- // 1. Budgetary Governance: Check for cost spikes in various windows
52
- const hourlyLimit = getPolicyValue('hourly_budget', 'budget');
53
- const dailyLimit = getPolicyValue('daily_budget', 'budget');
54
- const getCostInWindow = async (ms) => {
55
- const result = await trx
56
- .selectFrom(this.metricsTable)
57
- .select((eb) => eb.fn.sum('metric_value').as('total'))
58
- .where('metric_name', '=', 'total_cost')
59
- .where('created_at', '>', new Date(Date.now() - ms))
60
- .executeTakeFirst();
61
- return Number(result?.total || 0);
62
- };
63
- const hCost = await getCostInWindow(3600000);
64
- if (hCost > hourlyLimit && hourlyLimit > 0) {
65
- issues.push(`Budget Violations: Hourly cost ($${hCost.toFixed(2)}) exceeded policy ($${hourlyLimit.toFixed(2)})`);
66
- }
67
- const dCost = await getCostInWindow(86400000);
68
- if (dCost > dailyLimit && dailyLimit > 0) {
69
- issues.push(`Budget Violations: Daily cumulative cost ($${dCost.toFixed(2)}) exceeded safety ceiling ($${dailyLimit.toFixed(2)})`);
70
- }
71
- // 2. Performance Governance: Success Rates & Success Stability
72
- const minSuccess = getPolicyValue('min_success_rate', 'safety');
73
- // Statistical Success Rate (last 100 events)
74
- const recentSuccess = await trx
75
- .selectFrom(this.metricsTable)
76
- .select((eb) => eb.fn.avg('metric_value').as('avg'))
77
- .where('metric_name', '=', 'success_rate')
78
- .orderBy('created_at', 'desc')
79
- .limit(100)
80
- .executeTakeFirst();
81
- const success = Number(recentSuccess?.avg || 1);
82
- if (success < minSuccess) {
83
- issues.push(`Performance Degradation: Rolling success rate (${Math.round(success * 100)}%) is below policy requirement (${minSuccess * 100}%)`);
84
- }
85
- // 2b. Swarm Quota Governance: Real-time quota validation
86
- const activePersona = await this.getActivePersona(trx);
87
- if (activePersona) {
88
- const quotaCheck = await this.cortex.quotas.checkQuota('persona', activePersona.id);
89
- if (!quotaCheck.allowed) {
90
- issues.push(`Quota Breach: ${quotaCheck.reason}`);
91
- }
92
- // Check for swarm-level quotas if part of a swarm
93
- const swarmId = activePersona.metadata?.swarm_id;
94
- if (swarmId) {
95
- const swarmCheck = await this.cortex.quotas.checkQuota('swarm', swarmId);
96
- if (!swarmCheck.allowed) {
97
- issues.push(`Swarm Quota Breach [${swarmId}]: ${swarmCheck.reason}`);
98
- }
99
- }
100
- }
101
- // 3. Infrastructure Integrity: Reliability of Verified Skills
102
- const reliabiltyLimit = getPolicyValue('reliability_floor', 'integrity');
103
- const failingVerified = await trx
104
- .selectFrom(this.config.capabilitiesTable || 'agent_capabilities')
105
- .select(['name', 'reliability'])
106
- .where('status', '=', 'verified')
107
- .where('reliability', '<', reliabiltyLimit)
108
- .execute();
109
- for (const cap of failingVerified) {
110
- issues.push(`Integrity Failure: Verified skill '${cap.name}' reliability (${cap.reliability.toFixed(2)}) dropped below floor (${reliabiltyLimit})`);
111
- }
112
- if (issues.length > 0) {
113
- console.warn(`[GovernanceManager] AUDIT FAILED [${new Date().toISOString()}]: ${issues.length} compliance issues detected.`);
114
- // Phase 1: Emergency Rollbacks
115
- if (activePersona && (success < 0.4 || hCost > hourlyLimit * 1.5)) {
116
- console.error(`[GovernanceManager] CRITICAL THRESHOLD BREACH. Initiating emergency containment for persona ${activePersona.id}`);
117
- await this.cortex.strategy.rollbackPersona(activePersona.id);
118
- issues.push(`Containment: Emergency rollback triggered for persona ${activePersona.id}`);
119
- }
120
- // Phase 2: Systemic Reflections
121
- await this.cortex.reflections.reflect(null, 'failure', 'Governance Compliance Audit', issues);
122
- // Phase 3: Remediation Rituals (Transactional)
123
- await this.triggerRemediation(issues, trx);
124
- }
125
- return {
126
- healthy: issues.length === 0,
127
- issues,
128
- };
52
+ const issuesList = [];
53
+ let auditMetadata = {};
54
+ // Execute core audit gathering phase
55
+ const ctx = {
56
+ db: this.db,
57
+ trx: this.db,
58
+ cortex: this.cortex,
59
+ config: this.config,
60
+ metricsTable: this.metricsTable,
61
+ policiesTable: this.policiesTable,
62
+ personasTable: this.personasTable,
63
+ skillsTable: this.skillsTable
64
+ };
65
+ // Run all auditors
66
+ const budget = await this.budgetAuditor.audit(ctx);
67
+ const performance = await this.performanceAuditor.audit(ctx);
68
+ const persona = await this.personaAuditor.audit(ctx);
69
+ const skills = await this.skillAuditor.audit(ctx);
70
+ const emergence = await this.emergenceAuditor.audit(ctx);
71
+ const pooledIssues = [
72
+ ...budget.issues,
73
+ ...performance.issues,
74
+ ...persona.issues,
75
+ ...skills.issues,
76
+ ...emergence.issues
77
+ ];
78
+ const coreAuditResult = {
79
+ issues: pooledIssues,
80
+ metadata: {
81
+ ...budget.metadata,
82
+ ...performance.metadata,
83
+ ...persona.metadata,
84
+ ...skills.metadata,
85
+ ...emergence.metadata
129
86
  }
130
- catch (e) {
131
- console.error(`[GovernanceManager] STRICT AUDIT FAILURE: ${String(e)}`);
132
- issues.push(`Strict Mode Failure: ${String(e)}`);
133
- return { healthy: false, issues };
87
+ };
88
+ issuesList.push(...coreAuditResult.issues);
89
+ if (issuesList.length > 0) {
90
+ console.warn(`[GovernanceManager] AUDIT FAILED [${new Date().toISOString()}]: ${issuesList.length} compliance issues detected.`);
91
+ const { activePersona, success, hCost, hourlyLimit } = coreAuditResult.metadata;
92
+ // Phase 1: Emergency Rollbacks
93
+ if (activePersona && (success < 0.4 || hCost > hourlyLimit * 1.5)) {
94
+ console.error(`[GovernanceManager] CRITICAL THRESHOLD BREACH. Initiating emergency containment for persona ${activePersona.id}`);
95
+ await this.personaAuditor.quarantinePersona({ db: this.db, cortex: this.cortex }, activePersona.id, 'Critical threshold breach');
96
+ issuesList.push(`Containment: Emergency rollback triggered for persona ${activePersona.id}`);
134
97
  }
135
- });
98
+ await this.cortex.reflections.reflect(null, 'failure', 'Governance Compliance Audit', issuesList);
99
+ // Phase 3: Remediation Rituals
100
+ const ctx = {
101
+ db: this.db,
102
+ trx: this.db, // Standalone remediation
103
+ cortex: this.cortex,
104
+ config: this.config,
105
+ metricsTable: this.metricsTable,
106
+ policiesTable: this.policiesTable,
107
+ personasTable: this.personasTable,
108
+ skillsTable: this.skillsTable
109
+ };
110
+ await this.remediationEngine.triggerRemediation(ctx, issuesList);
111
+ }
136
112
  return {
137
- healthy: issues.length === 0,
138
- issues,
113
+ healthy: issuesList.length === 0,
114
+ issues: issuesList,
139
115
  };
140
116
  }
141
- async getActivePersona(trx) {
142
- const db = trx || this.db;
143
- const active = await db
144
- .selectFrom(this.personasTable)
145
- .selectAll()
146
- .where('status', '=', 'active')
147
- .executeTakeFirst();
148
- if (!active)
149
- return null;
150
- return {
151
- ...active,
152
- metadata: typeof active.metadata === 'string'
153
- ? JSON.parse(active.metadata)
154
- : active.metadata || {},
117
+ /**
118
+ * Suggest architectural repairs if performance is degrading
119
+ */
120
+ async suggestRepairs() {
121
+ const ctx = {
122
+ db: this.db,
123
+ trx: this.db,
124
+ cortex: this.cortex,
125
+ config: this.config,
126
+ metricsTable: this.metricsTable,
127
+ policiesTable: this.policiesTable,
128
+ personasTable: this.personasTable,
129
+ skillsTable: this.skillsTable
155
130
  };
131
+ return this.maintenanceOracle.suggestRepairs(ctx);
156
132
  }
157
133
  /**
158
134
  * Quarantine a persona that is behaving outside safety parameters.
159
135
  */
160
136
  async quarantinePersona(id, reason) {
161
- console.warn(`[GovernanceManager] QUARANTINING Persona ${id}: ${reason}`);
162
- await this.db.transaction().execute(async (trx) => {
163
- let query = trx
164
- .selectFrom(this.personasTable)
165
- .selectAll()
166
- .where('id', '=', id);
167
- // Audit Phase 13: Atomic identity lock (Skip for SQLite)
168
- if (this.db.getExecutor().adapter?.constructor.name !== 'SqliteAdapter') {
169
- query = query.forUpdate();
170
- }
171
- const persona = await query.executeTakeFirst();
172
- if (persona) {
173
- const metadata = typeof persona.metadata === 'string'
174
- ? JSON.parse(persona.metadata)
175
- : persona.metadata || {};
176
- await trx
177
- .updateTable(this.personasTable)
178
- .set({
179
- status: 'quarantined',
180
- metadata: JSON.stringify({
181
- ...metadata,
182
- quarantine_reason: reason,
183
- quarantined_at: new Date(),
184
- }),
185
- updated_at: new Date(),
186
- })
187
- .where('id', '=', id)
188
- .execute();
189
- // Phase 3: Rollback most recent changes
190
- await this.cortex.strategy.rollbackPersona(id);
191
- }
192
- });
137
+ const ctx = {
138
+ db: this.db,
139
+ trx: this.db,
140
+ cortex: this.cortex,
141
+ config: this.config,
142
+ metricsTable: this.metricsTable,
143
+ policiesTable: this.policiesTable,
144
+ personasTable: this.personasTable,
145
+ skillsTable: this.skillsTable
146
+ };
147
+ return this.personaAuditor.quarantinePersona(ctx, id, reason);
193
148
  }
194
149
  /**
195
150
  * Blacklist a skill that is causing systemic issues.
196
151
  */
197
152
  async quarantineSkill(name, reason) {
198
- const capTable = this.config.capabilitiesTable || 'agent_capabilities';
199
- console.warn(`[GovernanceManager] BLACKLISTING Skill ${name}: ${reason}`);
200
- await this.db
201
- .updateTable(capTable)
202
- .set({
203
- status: 'blacklisted',
204
- metadata: JSON.stringify({ blacklist_reason: reason, blacklisted_at: new Date() }),
205
- updated_at: new Date()
206
- })
207
- .where('name', '=', name)
208
- .execute();
153
+ const ctx = {
154
+ db: this.db,
155
+ trx: this.db,
156
+ cortex: this.cortex,
157
+ config: this.config,
158
+ metricsTable: this.metricsTable,
159
+ policiesTable: this.policiesTable,
160
+ personasTable: this.personasTable,
161
+ skillsTable: this.skillsTable
162
+ };
163
+ return this.skillAuditor.quarantineSkill(ctx, name, reason);
209
164
  }
210
165
  /**
211
166
  * Monitor cross-node behaviors and flag sudden spikes or malicious patterns.
212
167
  */
213
168
  async validateEmergentBehavior(trx) {
214
- const issues = [];
215
- const db = trx || this.db;
216
- // 1. Check for rapid propagation of new skills (Potential poisoning)
217
- const capTable = this.config.capabilitiesTable || 'agent_capabilities';
218
- const recentSkills = await db
219
- .selectFrom(capTable)
220
- .select(['name', 'created_at'])
221
- .where('created_at', '>', new Date(Date.now() - 3600000)) // Last hour
222
- .execute();
223
- if (recentSkills.length > 10) {
224
- issues.push(`Emergent Warning: Rapid skill propagation detected (${recentSkills.length} new skills in 1hr). Potential rogue behavior.`);
225
- }
226
- // 2. Check for high variance in task success across swarm
227
- const recentTaskMetrics = await db
228
- .selectFrom(this.metricsTable)
229
- .select(['metric_value', 'metadata'])
230
- .where('metric_name', '=', 'task_success_rate')
231
- .where('created_at', '>', new Date(Date.now() - 1800000)) // Last 30m
232
- .execute();
233
- if (recentTaskMetrics.length >= 5) {
234
- const values = recentTaskMetrics.map((m) => Number(m.metric_value));
235
- const mean = values.reduce((a, b) => a + b, 0) / values.length;
236
- const variance = values.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / values.length;
237
- if (variance > 0.2) {
238
- issues.push(`Emergent Warning: High variance in swarm success rate (${(variance * 100).toFixed(1)}%). Potential node instability.`);
239
- }
240
- }
241
- return issues;
242
- }
243
- async triggerRemediation(issues, trx) {
244
- const db = trx || this.db;
245
- for (const issue of issues) {
246
- if (issue.includes('Budget Violations')) {
247
- await this.cortex.rituals.scheduleRitual('Budget Remediation', 'compression', 'hourly', `Automated response to: ${issue}`, { priority: 'critical', enforce_limits: true });
248
- }
249
- if (issue.includes('Performance Degradation')) {
250
- await this.cortex.rituals.scheduleRitual('Reliability Sweep', 'pruning', 'daily', `Sanitizing high-noise memories due to: ${issue}`, { priority: 'medium', target: 'longtail' });
251
- }
252
- if (issue.includes('Integrity Failure')) {
253
- // Audit Phase 10: Atomic demotion lock
254
- const skillName = issue.match(/'([^']+)'/)?.[1];
255
- if (skillName) {
256
- console.log(`[GovernanceManager] Demoting tainted skill out of verified pool: ${skillName}`);
257
- const remediationStep = async (t) => {
258
- const skill = await t
259
- .selectFrom(this.config.capabilitiesTable || 'agent_capabilities')
260
- .select('id')
261
- .where('name', '=', skillName)
262
- .forUpdate() // Lock the skill row
263
- .executeTakeFirst();
264
- if (skill) {
265
- await t
266
- .updateTable(this.config.capabilitiesTable || 'agent_capabilities')
267
- .set({ status: 'experimental', updated_at: new Date() })
268
- .where('id', '=', skill.id)
269
- .execute();
270
- }
271
- };
272
- if (trx) {
273
- await remediationStep(trx);
274
- }
275
- else {
276
- await this.db.transaction().execute(remediationStep);
277
- }
278
- }
279
- }
280
- if (issue.includes('Quota Breach') || issue.includes('Swarm Quota Breach')) {
281
- await this.cortex.rituals.scheduleRitual('Resource Throttling', 'pruning', 'hourly', `Critical resource containment: ${issue}`, { priority: 'critical', active_containment: true });
282
- }
283
- }
284
- }
285
- /**
286
- * Suggest architectural repairs if performance is degrading
287
- */
288
- async suggestRepairs() {
289
- const repairs = [];
290
- // 1. Check for chronic high latency
291
- const latencyStats = await this.cortex.metrics.getMetricStats('query_latency');
292
- const latencyThreshold = (await this.cortex.policies.checkPolicy('query_latency_threshold', 0)).reason ? 500 : 500; // Logic to pull from policy if possible, else 500
293
- // PRODUCTION HARDENING: Pull thresholds from explicit governance policies
294
- const policies = await this.cortex.policies.getActivePolicies();
295
- const latencyPolicy = policies.find(p => p.name === 'latency_repair_threshold')?.definition?.threshold || 500;
296
- const costPolicy = policies.find(p => p.name === 'high_cost_threshold')?.definition?.threshold || 0.5;
297
- const storagePolicy = policies.find(p => p.name === 'cold_storage_threshold')?.definition?.days || 30;
298
- if (latencyStats.avg > latencyPolicy && latencyStats.count > 10) {
299
- repairs.push(`Average latency is high (${latencyStats.avg.toFixed(2)}ms). Suggesting index audit across hit tables.`);
300
- }
301
- // 2. Detect specific slow tables from recent metrics
302
- const recentSlowQueries = await this.db
303
- .selectFrom(this.metricsTable)
304
- .select('metadata')
305
- .where('metric_name', '=', 'query_latency')
306
- .where('metric_value', '>', latencyPolicy * 2)
307
- .limit(20)
308
- .execute();
309
- const slowTables = new Set();
310
- for (const q of recentSlowQueries) {
311
- try {
312
- const meta = typeof q.metadata === 'string'
313
- ? JSON.parse(q.metadata)
314
- : q.metadata || {};
315
- if (meta.table)
316
- slowTables.add(meta.table);
317
- }
318
- catch (e) {
319
- /* ignore parse errors */
320
- }
321
- }
322
- for (const table of slowTables) {
323
- repairs.push(`Table '${table}' is experiencing periodic latency spikes. Suggesting 'CREATE INDEX' for common filters.`);
324
- }
325
- // 3. Check for high cost accumulation
326
- const totalCost = await this.cortex.metrics.getAverageMetric('total_cost');
327
- if (totalCost > costPolicy) {
328
- repairs.push('Average query cost is high. Suggesting prompt compression or model switching (e.g., to a smaller model).');
329
- }
330
- // 3. Check for cold storage candidates
331
- const sessionsTable = this.config.sessionsTable || 'agent_sessions';
332
- const oldThreshold = new Date(Date.now() - storagePolicy * 24 * 60 * 60 * 1000);
333
- const oldSessions = (await this.db
334
- .selectFrom(sessionsTable)
335
- .select((eb) => eb.fn.count('id').as('count'))
336
- .where('created_at', '<', oldThreshold)
337
- .executeTakeFirst());
338
- if (Number(oldSessions?.count || 0) > 100) {
339
- repairs.push(`[STORAGE OPTIMIZATION] Found ${oldSessions.count} sessions older than ${storagePolicy} days. Consider moving to cold storage to reduce primary database size and improve backup speed.`);
340
- }
341
- return repairs;
169
+ const ctx = {
170
+ db: this.db,
171
+ trx: trx || this.db,
172
+ cortex: this.cortex,
173
+ config: this.config,
174
+ metricsTable: this.metricsTable,
175
+ policiesTable: this.policiesTable,
176
+ personasTable: this.personasTable,
177
+ skillsTable: this.skillsTable
178
+ };
179
+ const result = await this.emergenceAuditor.audit(ctx);
180
+ return result.issues;
342
181
  }
343
182
  }
344
183
  exports.GovernanceManager = GovernanceManager;
@@ -61,7 +61,7 @@ class QuotaManager {
61
61
  targetType: targetType,
62
62
  targetId: targetId,
63
63
  metric: policy.definition.metric || 'cost',
64
- limit: policy.definition.limit || 0,
64
+ limit: policy.definition.limit ?? policy.definition.threshold ?? 0,
65
65
  period: policy.definition.period || 'hourly',
66
66
  currentUsage: 0,
67
67
  createdAt: policy.createdAt,
@@ -115,6 +115,7 @@ class SelfEvolution {
115
115
  .addColumn('evolution_path', 'text') // JSON array of pivots
116
116
  .addColumn('autonomy_level', 'integer')
117
117
  .addColumn('status', 'text') // success, abandoned, pivoted
118
+ .addColumn('metadata', 'text') // JSON - used by CognitiveSynthesizer
118
119
  .addColumn('updated_at', 'timestamp', (col) => col.defaultTo((0, sql_js_1.sql) `CURRENT_TIMESTAMP`))
119
120
  .execute();
120
121
  // 3. Research Metrics (The Alchemist's Output)
@@ -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
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -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,50 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BudgetAuditor = void 0;
4
+ class BudgetAuditor {
5
+ async audit(ctx) {
6
+ const issues = [];
7
+ // Fetch budget policies
8
+ const policies = (await ctx.trx
9
+ .selectFrom(ctx.policiesTable)
10
+ .selectAll()
11
+ .where('is_enabled', '=', true)
12
+ .where((eb) => eb.or([
13
+ eb('name', '=', 'hourly_budget'),
14
+ eb('name', '=', 'daily_budget'),
15
+ eb('type', '=', 'budget')
16
+ ]))
17
+ .execute());
18
+ const getLimit = (name) => {
19
+ const p = policies.find(p => p.name === name);
20
+ if (!p)
21
+ return 0;
22
+ const def = typeof p.definition === 'string' ? JSON.parse(p.definition) : p.definition;
23
+ return def.threshold ?? def.limit ?? 0;
24
+ };
25
+ const hourlyLimit = getLimit('hourly_budget');
26
+ const dailyLimit = getLimit('daily_budget');
27
+ const getCostInWindow = async (ms) => {
28
+ const result = await ctx.trx
29
+ .selectFrom(ctx.metricsTable)
30
+ .select((eb) => eb.fn.sum('metric_value').as('total'))
31
+ .where('metric_name', '=', 'total_cost')
32
+ .where('created_at', '>', new Date(Date.now() - ms))
33
+ .executeTakeFirst();
34
+ return Number(result?.total || 0);
35
+ };
36
+ const hCost = await getCostInWindow(3600000);
37
+ if (hCost > hourlyLimit && hourlyLimit > 0) {
38
+ issues.push(`Budget Violations: Hourly cost ($${hCost.toFixed(2)}) exceeded policy ($${hourlyLimit.toFixed(2)})`);
39
+ }
40
+ const dCost = await getCostInWindow(86400000);
41
+ if (dCost > dailyLimit && dailyLimit > 0) {
42
+ issues.push(`Budget Violations: Daily cumulative cost ($${dCost.toFixed(2)}) exceeded safety ceiling ($${dailyLimit.toFixed(2)})`);
43
+ }
44
+ return {
45
+ issues,
46
+ metadata: { hCost, hourlyLimit, dCost, dailyLimit }
47
+ };
48
+ }
49
+ }
50
+ exports.BudgetAuditor = BudgetAuditor;
@@ -0,0 +1,4 @@
1
+ import type { AuditContext, AuditResult } from './AuditContext.js';
2
+ export declare class EmergenceAuditor {
3
+ audit(ctx: AuditContext): Promise<AuditResult>;
4
+ }