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