noormme 1.2.2 → 1.2.4
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/ActionJournal.d.ts +6 -6
- package/dist/cjs/agentic/ActionJournal.js +10 -10
- package/dist/cjs/agentic/CapabilityManager.d.ts +5 -5
- package/dist/cjs/agentic/CapabilityManager.js +34 -19
- package/dist/cjs/agentic/Cortex.js +12 -13
- package/dist/cjs/agentic/PersonaManager.d.ts +4 -4
- package/dist/cjs/agentic/PersonaManager.js +18 -10
- package/dist/cjs/agentic/PolicyEnforcer.d.ts +4 -8
- package/dist/cjs/agentic/PolicyEnforcer.js +25 -22
- package/dist/cjs/agentic/improvement/AblationEngine.d.ts +7 -3
- package/dist/cjs/agentic/improvement/AblationEngine.js +51 -24
- package/dist/cjs/agentic/improvement/ActionRefiner.d.ts +1 -1
- package/dist/cjs/agentic/improvement/ActionRefiner.js +25 -15
- package/dist/cjs/agentic/improvement/EvolutionRitual.js +2 -1
- package/dist/cjs/agentic/improvement/EvolutionaryPilot.d.ts +1 -1
- package/dist/cjs/agentic/improvement/EvolutionaryPilot.js +17 -19
- package/dist/cjs/agentic/improvement/GovernanceManager.d.ts +5 -5
- package/dist/cjs/agentic/improvement/GovernanceManager.js +12 -22
- package/dist/cjs/agentic/improvement/HiveLink.d.ts +3 -3
- package/dist/cjs/agentic/improvement/HiveLink.js +15 -157
- package/dist/cjs/agentic/improvement/KnowledgeDistiller.d.ts +15 -29
- package/dist/cjs/agentic/improvement/KnowledgeDistiller.js +66 -349
- package/dist/cjs/agentic/improvement/QuotaManager.d.ts +1 -1
- package/dist/cjs/agentic/improvement/QuotaManager.js +11 -11
- package/dist/cjs/agentic/improvement/RecursiveReasoner.d.ts +4 -4
- package/dist/cjs/agentic/improvement/RecursiveReasoner.js +10 -10
- package/dist/cjs/agentic/improvement/ReflectionEngine.d.ts +2 -2
- package/dist/cjs/agentic/improvement/ReflectionEngine.js +2 -2
- package/dist/cjs/agentic/improvement/RitualOrchestrator.d.ts +3 -3
- package/dist/cjs/agentic/improvement/RitualOrchestrator.js +12 -9
- package/dist/cjs/agentic/improvement/SelfEvolution.d.ts +1 -1
- package/dist/cjs/agentic/improvement/SelfEvolution.js +21 -18
- package/dist/cjs/agentic/improvement/SelfTestRegistry.d.ts +1 -1
- package/dist/cjs/agentic/improvement/SelfTestRegistry.js +31 -19
- package/dist/cjs/agentic/improvement/SovereignMetrics.d.ts +6 -6
- package/dist/cjs/agentic/improvement/SovereignMetrics.js +12 -12
- package/dist/cjs/agentic/improvement/StrategicPlanner.d.ts +10 -54
- package/dist/cjs/agentic/improvement/StrategicPlanner.js +43 -396
- package/dist/cjs/agentic/improvement/distillation/ConflictChallenger.d.ts +3 -0
- package/dist/cjs/agentic/improvement/distillation/ConflictChallenger.js +54 -0
- package/dist/cjs/agentic/improvement/distillation/FactDistiller.d.ts +10 -0
- package/dist/cjs/agentic/improvement/distillation/FactDistiller.js +115 -0
- package/dist/cjs/agentic/improvement/distillation/KnowledgeConsolidator.d.ts +6 -0
- package/dist/cjs/agentic/improvement/distillation/KnowledgeConsolidator.js +63 -0
- package/dist/cjs/agentic/improvement/distillation/RelationshipArchitect.d.ts +6 -0
- package/dist/cjs/agentic/improvement/distillation/RelationshipArchitect.js +73 -0
- package/dist/cjs/agentic/improvement/governance/MaintenanceOracle.js +5 -5
- package/dist/cjs/agentic/improvement/governance/PersonaAuditor.js +41 -29
- package/dist/cjs/agentic/improvement/governance/RemediationEngine.js +8 -3
- package/dist/cjs/agentic/improvement/governance/SkillAuditor.js +17 -9
- package/dist/cjs/agentic/improvement/hive/DomainMaster.d.ts +4 -0
- package/dist/cjs/agentic/improvement/hive/DomainMaster.js +19 -0
- package/dist/cjs/agentic/improvement/hive/KnowledgePromoter.d.ts +6 -0
- package/dist/cjs/agentic/improvement/hive/KnowledgePromoter.js +56 -0
- package/dist/cjs/agentic/improvement/hive/SkillPropagator.d.ts +6 -0
- package/dist/cjs/agentic/improvement/hive/SkillPropagator.js +91 -0
- package/dist/cjs/agentic/improvement/strategy/EvolutionVerificator.d.ts +6 -0
- package/dist/cjs/agentic/improvement/strategy/EvolutionVerificator.js +48 -0
- package/dist/cjs/agentic/improvement/strategy/MutationEngine.d.ts +10 -0
- package/dist/cjs/agentic/improvement/strategy/MutationEngine.js +119 -0
- package/dist/cjs/agentic/improvement/strategy/PerformanceAnalyst.d.ts +6 -0
- package/dist/cjs/agentic/improvement/strategy/PerformanceAnalyst.js +84 -0
- package/dist/cjs/cli/index.js +0 -0
- package/dist/cjs/types/index.d.ts +8 -0
- package/dist/esm/agentic/ActionJournal.d.ts +6 -6
- package/dist/esm/agentic/ActionJournal.js +10 -10
- package/dist/esm/agentic/CapabilityManager.d.ts +5 -5
- package/dist/esm/agentic/CapabilityManager.js +34 -19
- package/dist/esm/agentic/Cortex.js +12 -13
- package/dist/esm/agentic/PersonaManager.d.ts +4 -4
- package/dist/esm/agentic/PersonaManager.js +18 -10
- package/dist/esm/agentic/PolicyEnforcer.d.ts +4 -8
- package/dist/esm/agentic/PolicyEnforcer.js +25 -22
- package/dist/esm/agentic/improvement/AblationEngine.d.ts +7 -3
- package/dist/esm/agentic/improvement/AblationEngine.js +51 -24
- package/dist/esm/agentic/improvement/ActionRefiner.d.ts +1 -1
- package/dist/esm/agentic/improvement/ActionRefiner.js +25 -15
- package/dist/esm/agentic/improvement/EvolutionRitual.js +2 -1
- package/dist/esm/agentic/improvement/EvolutionaryPilot.d.ts +1 -1
- package/dist/esm/agentic/improvement/EvolutionaryPilot.js +17 -19
- package/dist/esm/agentic/improvement/GovernanceManager.d.ts +5 -5
- package/dist/esm/agentic/improvement/GovernanceManager.js +12 -22
- package/dist/esm/agentic/improvement/HiveLink.d.ts +3 -3
- package/dist/esm/agentic/improvement/HiveLink.js +15 -157
- package/dist/esm/agentic/improvement/KnowledgeDistiller.d.ts +15 -29
- package/dist/esm/agentic/improvement/KnowledgeDistiller.js +66 -349
- package/dist/esm/agentic/improvement/QuotaManager.d.ts +1 -1
- package/dist/esm/agentic/improvement/QuotaManager.js +11 -11
- package/dist/esm/agentic/improvement/RecursiveReasoner.d.ts +4 -4
- package/dist/esm/agentic/improvement/RecursiveReasoner.js +10 -10
- package/dist/esm/agentic/improvement/ReflectionEngine.d.ts +2 -2
- package/dist/esm/agentic/improvement/ReflectionEngine.js +2 -2
- package/dist/esm/agentic/improvement/RitualOrchestrator.d.ts +3 -3
- package/dist/esm/agentic/improvement/RitualOrchestrator.js +12 -9
- package/dist/esm/agentic/improvement/SelfEvolution.d.ts +1 -1
- package/dist/esm/agentic/improvement/SelfEvolution.js +21 -18
- package/dist/esm/agentic/improvement/SelfTestRegistry.d.ts +1 -1
- package/dist/esm/agentic/improvement/SelfTestRegistry.js +31 -19
- package/dist/esm/agentic/improvement/SovereignMetrics.d.ts +6 -6
- package/dist/esm/agentic/improvement/SovereignMetrics.js +12 -12
- package/dist/esm/agentic/improvement/StrategicPlanner.d.ts +10 -54
- package/dist/esm/agentic/improvement/StrategicPlanner.js +43 -396
- package/dist/esm/agentic/improvement/distillation/ConflictChallenger.d.ts +3 -0
- package/dist/esm/agentic/improvement/distillation/ConflictChallenger.js +51 -0
- package/dist/esm/agentic/improvement/distillation/FactDistiller.d.ts +10 -0
- package/dist/esm/agentic/improvement/distillation/FactDistiller.js +112 -0
- package/dist/esm/agentic/improvement/distillation/KnowledgeConsolidator.d.ts +6 -0
- package/dist/esm/agentic/improvement/distillation/KnowledgeConsolidator.js +60 -0
- package/dist/esm/agentic/improvement/distillation/RelationshipArchitect.d.ts +6 -0
- package/dist/esm/agentic/improvement/distillation/RelationshipArchitect.js +70 -0
- package/dist/esm/agentic/improvement/governance/MaintenanceOracle.js +5 -5
- package/dist/esm/agentic/improvement/governance/PersonaAuditor.js +41 -29
- package/dist/esm/agentic/improvement/governance/RemediationEngine.js +8 -3
- package/dist/esm/agentic/improvement/governance/SkillAuditor.js +17 -9
- package/dist/esm/agentic/improvement/hive/DomainMaster.d.ts +4 -0
- package/dist/esm/agentic/improvement/hive/DomainMaster.js +16 -0
- package/dist/esm/agentic/improvement/hive/KnowledgePromoter.d.ts +6 -0
- package/dist/esm/agentic/improvement/hive/KnowledgePromoter.js +53 -0
- package/dist/esm/agentic/improvement/hive/SkillPropagator.d.ts +6 -0
- package/dist/esm/agentic/improvement/hive/SkillPropagator.js +88 -0
- package/dist/esm/agentic/improvement/strategy/EvolutionVerificator.d.ts +6 -0
- package/dist/esm/agentic/improvement/strategy/EvolutionVerificator.js +45 -0
- package/dist/esm/agentic/improvement/strategy/MutationEngine.d.ts +10 -0
- package/dist/esm/agentic/improvement/strategy/MutationEngine.js +116 -0
- package/dist/esm/agentic/improvement/strategy/PerformanceAnalyst.d.ts +6 -0
- package/dist/esm/agentic/improvement/strategy/PerformanceAnalyst.js +81 -0
- package/dist/esm/types/index.d.ts +8 -0
- package/package.json +40 -44
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EvolutionVerificator = void 0;
|
|
4
|
+
class EvolutionVerificator {
|
|
5
|
+
async verify(trxOrDb, cortex, personasTable, persona, report, allPersonas, rollbackFn) {
|
|
6
|
+
const rollbackHistory = persona.metadata?.rollbackHistory || [];
|
|
7
|
+
const recentRollbacks = rollbackHistory.filter((ts) => Date.now() - ts < 604800000).length;
|
|
8
|
+
const hiveTrusted = allPersonas.filter((p) => p.metadata?.evolution_status === 'stable' && p.metadata?.mutation_reason === persona.metadata?.mutation_reason).length;
|
|
9
|
+
let sampleSizeThreshold = 10 + recentRollbacks * 10;
|
|
10
|
+
const baseline = persona.metadata?.verification_baseline || { successRate: 0.8, averageLatency: 500 };
|
|
11
|
+
// Accelerated Stabilization
|
|
12
|
+
const earlyZ = (report.successRate - baseline.successRate) / 0.1;
|
|
13
|
+
if (earlyZ > 3.0 && report.sampleSize >= 5)
|
|
14
|
+
sampleSizeThreshold = 5;
|
|
15
|
+
if (hiveTrusted >= 3)
|
|
16
|
+
sampleSizeThreshold = Math.max(5, Math.floor(sampleSizeThreshold / 2));
|
|
17
|
+
if (report.sampleSize < sampleSizeThreshold)
|
|
18
|
+
return null;
|
|
19
|
+
// Dynamic Variance
|
|
20
|
+
const recentMetrics = await cortex.metrics.getRecentMetrics(100, trxOrDb);
|
|
21
|
+
const values = recentMetrics.filter((m) => m.metricName === 'success_rate').map((m) => Number(m.metricValue));
|
|
22
|
+
const mean = values.reduce((a, b) => a + b, 0) / (values.length || 1);
|
|
23
|
+
const variance = values.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / (values.length || 1);
|
|
24
|
+
const stdDev = Math.sqrt(variance) || 0.1;
|
|
25
|
+
const zScore = (report.successRate - baseline.successRate) / (stdDev || 1);
|
|
26
|
+
if (zScore < -2.0)
|
|
27
|
+
return await rollbackFn(persona.id, trxOrDb);
|
|
28
|
+
if (report.sampleSize >= sampleSizeThreshold * 2 && zScore >= -0.5) {
|
|
29
|
+
if (persona.metadata?.mutation_reason?.includes('optimize_efficiency')) {
|
|
30
|
+
await cortex.rules.defineRule('all', 'all', 'audit', {
|
|
31
|
+
condition: 'latency > 500',
|
|
32
|
+
priority: 10,
|
|
33
|
+
metadata: { reason: `Distilled from successful persona ${persona.id} optimization` },
|
|
34
|
+
}, trxOrDb);
|
|
35
|
+
}
|
|
36
|
+
await trxOrDb.updateTable(personasTable)
|
|
37
|
+
.set({ metadata: JSON.stringify({ ...persona.metadata, evolution_status: 'stable' }) })
|
|
38
|
+
.where('id', '=', persona.id)
|
|
39
|
+
.execute();
|
|
40
|
+
return `Evolution stabilized for persona ${persona.id}`;
|
|
41
|
+
}
|
|
42
|
+
const timeInVerification = (Date.now() - (persona.metadata?.verification_started_at || 0)) / 1000;
|
|
43
|
+
if (timeInVerification > 86400 * 3)
|
|
44
|
+
return await rollbackFn(persona.id, trxOrDb);
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
exports.EvolutionVerificator = EvolutionVerificator;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Kysely } from '../../../kysely.js';
|
|
2
|
+
import type { AgentPersona } from '../../../types/index.js';
|
|
3
|
+
import type { Cortex } from '../../Cortex.js';
|
|
4
|
+
import type { PerformanceReport } from '../StrategicPlanner.js';
|
|
5
|
+
export declare class MutationEngine {
|
|
6
|
+
private personasTable;
|
|
7
|
+
constructor(personasTable: string);
|
|
8
|
+
applyMutation(db: Kysely<any>, cortex: Cortex, persona: AgentPersona, report: PerformanceReport, failures: string[] | undefined, sanitizeRoleFn: (role: string) => string, parsePersonaFn: (p: any) => AgentPersona): Promise<string | null>;
|
|
9
|
+
rollback(db: Kysely<any>, id: string | number, parsePersonaFn: (p: any) => AgentPersona): Promise<string>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MutationEngine = void 0;
|
|
4
|
+
class MutationEngine {
|
|
5
|
+
personasTable;
|
|
6
|
+
constructor(personasTable) {
|
|
7
|
+
this.personasTable = personasTable;
|
|
8
|
+
}
|
|
9
|
+
async applyMutation(db, cortex, persona, report, failures = [], sanitizeRoleFn, parsePersonaFn) {
|
|
10
|
+
return await db.transaction().execute(async (trx) => {
|
|
11
|
+
const reason = failures.length > 0 ? `Failure Patterns: ${failures.join(', ')}` : report.recommendation;
|
|
12
|
+
let updates = {};
|
|
13
|
+
let mutationType = 'role_update';
|
|
14
|
+
if (failures.length > 0) {
|
|
15
|
+
const lessons = await cortex.reasoner.synthesizeLessons(trx);
|
|
16
|
+
const relevantLessons = (lessons['general'] || []).slice(0, 2);
|
|
17
|
+
updates = {
|
|
18
|
+
role: `${persona.role || ''} (Optimized for: ${failures.join(', ')}. Patterns: ${relevantLessons.join('; ')})`.trim(),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
const allPersonas = await trx.selectFrom(this.personasTable).selectAll().execute();
|
|
23
|
+
const winningMutations = allPersonas
|
|
24
|
+
.map((p) => parsePersonaFn(p))
|
|
25
|
+
.filter((p) => (p.metadata?.evolution_status === 'stable' || !p.metadata?.evolution_status) && p.metadata?.mutation_reason?.includes(report.recommendation));
|
|
26
|
+
if (winningMutations.length > 0) {
|
|
27
|
+
const sorted = winningMutations.sort((a, b) => (b.metadata?.anchored_reliability || 0) - (a.metadata?.anchored_reliability || 0));
|
|
28
|
+
const alphaMatch = sorted[0];
|
|
29
|
+
updates = { role: sanitizeRoleFn(alphaMatch.role || persona.role || 'Agent') };
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
switch (report.recommendation) {
|
|
33
|
+
case 'optimize_accuracy':
|
|
34
|
+
updates = { role: sanitizeRoleFn(`${persona.role || ''} (Focus strictly on accuracy and detailed verification)`) };
|
|
35
|
+
break;
|
|
36
|
+
case 'optimize_efficiency':
|
|
37
|
+
updates = { policies: [...(persona.policies || []), 'timeout_reduction', 'concise_output'] };
|
|
38
|
+
mutationType = 'policy_update';
|
|
39
|
+
break;
|
|
40
|
+
case 'critical_intervention':
|
|
41
|
+
return await this.rollback(db, persona.id, parsePersonaFn);
|
|
42
|
+
default:
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (updates.role)
|
|
48
|
+
updates.role = sanitizeRoleFn(updates.role);
|
|
49
|
+
// Conflict Detection
|
|
50
|
+
const contradictions = await cortex.reasoner.detectContradictions(trx);
|
|
51
|
+
for (const contradiction of contradictions) {
|
|
52
|
+
if (updates.role && contradiction.includes(updates.role.slice(0, 20)))
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
const mutation = {
|
|
56
|
+
id: `mut_${Date.now()}`,
|
|
57
|
+
timestamp: Date.now(),
|
|
58
|
+
type: mutationType,
|
|
59
|
+
previousState: { role: persona.role, policies: persona.policies, capabilities: persona.capabilities },
|
|
60
|
+
newState: { ...updates },
|
|
61
|
+
reason: `Auto-mutation triggered by ${report.recommendation}`,
|
|
62
|
+
};
|
|
63
|
+
const history = [...(persona.metadata?.mutationHistory || []), mutation].slice(-5);
|
|
64
|
+
const newMetadata = {
|
|
65
|
+
...persona.metadata,
|
|
66
|
+
mutationHistory: history,
|
|
67
|
+
evolution_status: 'verifying',
|
|
68
|
+
mutation_reason: report.recommendation,
|
|
69
|
+
verification_started_at: Date.now(),
|
|
70
|
+
verification_baseline: { successRate: report.successRate, averageLatency: report.averageLatency },
|
|
71
|
+
};
|
|
72
|
+
await trx.updateTable(this.personasTable)
|
|
73
|
+
.set({
|
|
74
|
+
role: updates.role || persona.role,
|
|
75
|
+
policies: updates.policies ? JSON.stringify(updates.policies) : undefined,
|
|
76
|
+
capabilities: updates.capabilities ? JSON.stringify(updates.capabilities) : undefined,
|
|
77
|
+
metadata: JSON.stringify(newMetadata),
|
|
78
|
+
updated_at: new Date(),
|
|
79
|
+
})
|
|
80
|
+
.where('id', '=', persona.id)
|
|
81
|
+
.execute();
|
|
82
|
+
return `Persona ${persona.id} mutated and entering verification window.`;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
async rollback(db, id, parsePersonaFn) {
|
|
86
|
+
return await db.transaction().execute(async (trx) => {
|
|
87
|
+
const current = await trx.selectFrom(this.personasTable).selectAll().where('id', '=', id).executeTakeFirst();
|
|
88
|
+
if (!current)
|
|
89
|
+
throw new Error(`Persona ${id} not found`);
|
|
90
|
+
const persona = parsePersonaFn(current);
|
|
91
|
+
const history = persona.metadata?.mutationHistory || [];
|
|
92
|
+
const lastMutation = history.pop();
|
|
93
|
+
if (!lastMutation)
|
|
94
|
+
return `No mutations to rollback for persona ${id}`;
|
|
95
|
+
const previous = lastMutation.previousState;
|
|
96
|
+
const rollbackHistory = [...(persona.metadata?.rollbackHistory || []), Date.now()];
|
|
97
|
+
const newMetadata = {
|
|
98
|
+
...persona.metadata,
|
|
99
|
+
mutationHistory: history,
|
|
100
|
+
rollbackHistory: rollbackHistory,
|
|
101
|
+
last_failed_mutation: { type: lastMutation.type, timestamp: Date.now() },
|
|
102
|
+
evolution_status: 'stable',
|
|
103
|
+
lastRollback: Date.now(),
|
|
104
|
+
};
|
|
105
|
+
await trx.updateTable(this.personasTable)
|
|
106
|
+
.set({
|
|
107
|
+
role: previous.role,
|
|
108
|
+
policies: previous.policies ? JSON.stringify(previous.policies) : undefined,
|
|
109
|
+
capabilities: previous.capabilities ? JSON.stringify(previous.capabilities) : undefined,
|
|
110
|
+
metadata: JSON.stringify(newMetadata),
|
|
111
|
+
updated_at: new Date(),
|
|
112
|
+
})
|
|
113
|
+
.where('id', '=', id)
|
|
114
|
+
.execute();
|
|
115
|
+
return `Rolled back mutation ${lastMutation.id} for persona ${id}`;
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
exports.MutationEngine = MutationEngine;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Cortex } from '../../Cortex.js';
|
|
2
|
+
import type { PerformanceReport } from '../StrategicPlanner.js';
|
|
3
|
+
export declare class PerformanceAnalyst {
|
|
4
|
+
analyzeFailurePatterns(cortex: Cortex, personaId: string | number, trxOrDb?: any): Promise<string[]>;
|
|
5
|
+
analyze(trxOrDb: any, cortex: Cortex, metricsTable: string, id: string | number): Promise<PerformanceReport>;
|
|
6
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PerformanceAnalyst = void 0;
|
|
4
|
+
const sql_js_1 = require("../../../raw-builder/sql.js");
|
|
5
|
+
class PerformanceAnalyst {
|
|
6
|
+
async analyzeFailurePatterns(cortex, personaId, trxOrDb = cortex.db) {
|
|
7
|
+
const patterns = [];
|
|
8
|
+
try {
|
|
9
|
+
// NOTE: cortex.actions.getFailureReport might need to be transaction-aware too
|
|
10
|
+
const failureReport = await cortex.actions.getFailureReport(trxOrDb);
|
|
11
|
+
const frequentFailures = failureReport.filter((f) => f.failureCount > 1);
|
|
12
|
+
for (const fail of frequentFailures) {
|
|
13
|
+
patterns.push(`tool_failure_${fail.toolName}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
catch (e) {
|
|
17
|
+
// Fallback handled by orchestrator
|
|
18
|
+
}
|
|
19
|
+
return patterns;
|
|
20
|
+
}
|
|
21
|
+
async analyze(trxOrDb, cortex, metricsTable, id) {
|
|
22
|
+
const recentMetrics = await trxOrDb
|
|
23
|
+
.selectFrom(metricsTable)
|
|
24
|
+
.selectAll()
|
|
25
|
+
.where((eb) => eb.or([
|
|
26
|
+
eb((0, sql_js_1.sql) `json_extract(metadata, '$.persona_id')`, '=', id),
|
|
27
|
+
eb((0, sql_js_1.sql) `metadata->>'persona_id'`, '=', String(id)),
|
|
28
|
+
]))
|
|
29
|
+
.orderBy('created_at', 'desc')
|
|
30
|
+
.limit(50)
|
|
31
|
+
.execute();
|
|
32
|
+
const globalMetrics = await cortex.metrics.getRecentMetrics(200, trxOrDb);
|
|
33
|
+
const calcStats = (metricName) => {
|
|
34
|
+
const vals = globalMetrics
|
|
35
|
+
.filter((m) => m.metricName === metricName)
|
|
36
|
+
.map((m) => Number(m.metricValue));
|
|
37
|
+
if (vals.length < 10)
|
|
38
|
+
return { mean: metricName === 'query_latency' ? 500 : 0.9, stdDev: 0.1 };
|
|
39
|
+
const mean = vals.reduce((a, b) => a + b, 0) / vals.length;
|
|
40
|
+
const variance = vals.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / vals.length;
|
|
41
|
+
return { mean, stdDev: Math.sqrt(variance) || 0.05 };
|
|
42
|
+
};
|
|
43
|
+
const successStats = calcStats('task_success_rate');
|
|
44
|
+
const latencyStats = calcStats('query_latency');
|
|
45
|
+
if (recentMetrics.length === 0) {
|
|
46
|
+
return {
|
|
47
|
+
personaId: id,
|
|
48
|
+
successRate: successStats.mean,
|
|
49
|
+
averageLatency: latencyStats.mean,
|
|
50
|
+
sampleSize: 0,
|
|
51
|
+
recommendation: 'maintain',
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const successMetrics = recentMetrics.filter((m) => m.metric_name === 'task_success_rate');
|
|
55
|
+
const latencyMetrics = recentMetrics.filter((m) => m.metric_name === 'query_latency');
|
|
56
|
+
const avgSuccess = successMetrics.length > 0
|
|
57
|
+
? successMetrics.reduce((sum, m) => sum + Number(m.metric_value), 0) / successMetrics.length
|
|
58
|
+
: successStats.mean;
|
|
59
|
+
const avgLatency = latencyMetrics.length > 0
|
|
60
|
+
? latencyMetrics.reduce((sum, m) => sum + Number(m.metric_value), 0) / latencyMetrics.length
|
|
61
|
+
: latencyStats.mean;
|
|
62
|
+
let recommendation = 'maintain';
|
|
63
|
+
const criticalThreshold = successStats.mean - 2.5 * successStats.stdDev;
|
|
64
|
+
const accuracyThreshold = successStats.mean - 1.0 * successStats.stdDev;
|
|
65
|
+
const efficiencyThreshold = latencyStats.mean + 2.0 * latencyStats.stdDev;
|
|
66
|
+
if (avgSuccess < criticalThreshold) {
|
|
67
|
+
recommendation = 'critical_intervention';
|
|
68
|
+
}
|
|
69
|
+
else if (avgSuccess < accuracyThreshold) {
|
|
70
|
+
recommendation = 'optimize_accuracy';
|
|
71
|
+
}
|
|
72
|
+
else if (avgLatency > efficiencyThreshold) {
|
|
73
|
+
recommendation = 'optimize_efficiency';
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
personaId: id,
|
|
77
|
+
successRate: avgSuccess,
|
|
78
|
+
averageLatency: avgLatency,
|
|
79
|
+
sampleSize: recentMetrics.length,
|
|
80
|
+
recommendation,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
exports.PerformanceAnalyst = PerformanceAnalyst;
|
package/dist/cjs/cli/index.js
CHANGED
|
File without changes
|
|
@@ -385,6 +385,14 @@ export interface AgentPersona {
|
|
|
385
385
|
createdAt: Date;
|
|
386
386
|
updatedAt: Date;
|
|
387
387
|
}
|
|
388
|
+
export interface PersonaMutation {
|
|
389
|
+
id: string;
|
|
390
|
+
timestamp: number;
|
|
391
|
+
type: 'role_update' | 'policy_update' | 'capability_update';
|
|
392
|
+
previousState: Partial<AgentPersona>;
|
|
393
|
+
newState: Partial<AgentPersona>;
|
|
394
|
+
reason: string;
|
|
395
|
+
}
|
|
388
396
|
export interface AgentQuota {
|
|
389
397
|
id: string | number;
|
|
390
398
|
targetType: 'persona' | 'swarm' | 'global';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Kysely } from '../kysely.js';
|
|
2
|
-
import type {
|
|
2
|
+
import type { AgentAction, AgenticConfig } from '../types/index.js';
|
|
3
3
|
import type { TelemetryOrchestrator } from './telemetry/TelemetryOrchestrator.js';
|
|
4
4
|
export interface ActionTable {
|
|
5
5
|
id: number | string;
|
|
@@ -30,26 +30,26 @@ export declare class ActionJournal {
|
|
|
30
30
|
/**
|
|
31
31
|
* Log an action (tool call)
|
|
32
32
|
*/
|
|
33
|
-
logAction(sessionId: string | number, toolName: string, args: Record<string, any>, messageId?: string | number): Promise<AgentAction>;
|
|
33
|
+
logAction(sessionId: string | number, toolName: string, args: Record<string, any>, messageId?: string | number, trxOrDb?: any): Promise<AgentAction>;
|
|
34
34
|
/**
|
|
35
35
|
* Update action with outcome
|
|
36
36
|
*/
|
|
37
|
-
recordOutcome(actionId: string | number, status: AgentAction['status'], outcome: string, durationMs?: number, metadata?: Record<string, any
|
|
37
|
+
recordOutcome(actionId: string | number, status: AgentAction['status'], outcome: string, durationMs?: number, metadata?: Record<string, any>, trxOrDb?: any): Promise<AgentAction>;
|
|
38
38
|
/**
|
|
39
39
|
* Get actions for a session with pagination
|
|
40
40
|
*/
|
|
41
41
|
getSessionActions(sessionId: string | number, options?: {
|
|
42
42
|
limit?: number;
|
|
43
43
|
cursor?: string | number;
|
|
44
|
-
}): Promise<AgentAction[]>;
|
|
44
|
+
}, trxOrDb?: any): Promise<AgentAction[]>;
|
|
45
45
|
/**
|
|
46
46
|
* Get actions by tool name across all sessions.
|
|
47
47
|
*/
|
|
48
|
-
getActionsByTool(toolName: string, limit?: number): Promise<AgentAction[]>;
|
|
48
|
+
getActionsByTool(toolName: string, limit?: number, trxOrDb?: any): Promise<AgentAction[]>;
|
|
49
49
|
/**
|
|
50
50
|
* Generate a report of tool failures.
|
|
51
51
|
*/
|
|
52
|
-
getFailureReport(): Promise<{
|
|
52
|
+
getFailureReport(trxOrDb?: any): Promise<{
|
|
53
53
|
toolName: string;
|
|
54
54
|
failureCount: number;
|
|
55
55
|
lastFailure: string;
|
|
@@ -20,8 +20,8 @@ export class ActionJournal {
|
|
|
20
20
|
/**
|
|
21
21
|
* Log an action (tool call)
|
|
22
22
|
*/
|
|
23
|
-
async logAction(sessionId, toolName, args, messageId) {
|
|
24
|
-
const action = await
|
|
23
|
+
async logAction(sessionId, toolName, args, messageId, trxOrDb = this.db) {
|
|
24
|
+
const action = await trxOrDb
|
|
25
25
|
.insertInto(this.actionsTable)
|
|
26
26
|
.values({
|
|
27
27
|
session_id: sessionId,
|
|
@@ -43,8 +43,8 @@ export class ActionJournal {
|
|
|
43
43
|
/**
|
|
44
44
|
* Update action with outcome
|
|
45
45
|
*/
|
|
46
|
-
async recordOutcome(actionId, status, outcome, durationMs, metadata) {
|
|
47
|
-
const action = await
|
|
46
|
+
async recordOutcome(actionId, status, outcome, durationMs, metadata, trxOrDb = this.db) {
|
|
47
|
+
const action = await trxOrDb
|
|
48
48
|
.updateTable(this.actionsTable)
|
|
49
49
|
.set({
|
|
50
50
|
status,
|
|
@@ -67,9 +67,9 @@ export class ActionJournal {
|
|
|
67
67
|
/**
|
|
68
68
|
* Get actions for a session with pagination
|
|
69
69
|
*/
|
|
70
|
-
async getSessionActions(sessionId, options = {}) {
|
|
70
|
+
async getSessionActions(sessionId, options = {}, trxOrDb = this.db) {
|
|
71
71
|
const { limit = 100, cursor } = options;
|
|
72
|
-
let query =
|
|
72
|
+
let query = trxOrDb
|
|
73
73
|
.selectFrom(this.actionsTable)
|
|
74
74
|
.selectAll()
|
|
75
75
|
.where('session_id', '=', sessionId)
|
|
@@ -84,8 +84,8 @@ export class ActionJournal {
|
|
|
84
84
|
/**
|
|
85
85
|
* Get actions by tool name across all sessions.
|
|
86
86
|
*/
|
|
87
|
-
async getActionsByTool(toolName, limit = 50) {
|
|
88
|
-
const actions = await
|
|
87
|
+
async getActionsByTool(toolName, limit = 50, trxOrDb = this.db) {
|
|
88
|
+
const actions = await trxOrDb
|
|
89
89
|
.selectFrom(this.actionsTable)
|
|
90
90
|
.selectAll()
|
|
91
91
|
.where('tool_name', '=', toolName)
|
|
@@ -97,10 +97,10 @@ export class ActionJournal {
|
|
|
97
97
|
/**
|
|
98
98
|
* Generate a report of tool failures.
|
|
99
99
|
*/
|
|
100
|
-
async getFailureReport() {
|
|
100
|
+
async getFailureReport(trxOrDb = this.db) {
|
|
101
101
|
// Audit Phase 19: Sliding window (default 7 days) to prevent OOM/slow scans
|
|
102
102
|
const windowStart = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
|
103
|
-
const results = await
|
|
103
|
+
const results = await trxOrDb
|
|
104
104
|
.selectFrom(this.actionsTable)
|
|
105
105
|
.select([
|
|
106
106
|
'tool_name',
|
|
@@ -30,24 +30,24 @@ export declare class CapabilityManager {
|
|
|
30
30
|
/**
|
|
31
31
|
* Register or update a capability (skill)
|
|
32
32
|
*/
|
|
33
|
-
registerCapability(name: string, version: string, description?: string, metadata?: Record<string, any
|
|
33
|
+
registerCapability(name: string, version: string, description?: string, metadata?: Record<string, any>, trxOrDb?: any): Promise<AgentCapability>;
|
|
34
34
|
/**
|
|
35
35
|
* Update reliability based on action outcome using a damped moving average.
|
|
36
36
|
* Manages the lifecycle of emergent skills (sandbox -> verified / blacklisted).
|
|
37
37
|
*/
|
|
38
|
-
reportOutcome(name: string, success: boolean): Promise<void>;
|
|
38
|
+
reportOutcome(name: string, success: boolean, trxOrDb?: any): Promise<void>;
|
|
39
39
|
/**
|
|
40
40
|
* Get reliability score for a capability.
|
|
41
41
|
*/
|
|
42
|
-
getReliability(name: string): Promise<number>;
|
|
42
|
+
getReliability(name: string, trxOrDb?: any): Promise<number>;
|
|
43
43
|
/**
|
|
44
44
|
* Get all registered capabilities, optionally filtered by status
|
|
45
45
|
*/
|
|
46
|
-
getCapabilities(status?: AgentCapability['status']): Promise<AgentCapability[]>;
|
|
46
|
+
getCapabilities(status?: AgentCapability['status'], trxOrDb?: any): Promise<AgentCapability[]>;
|
|
47
47
|
/**
|
|
48
48
|
* Validate if a persona has access to a specific capability (Sandbox Enforcement).
|
|
49
49
|
*/
|
|
50
|
-
validateCapabilityAccess(personaId: string | number, capabilityName: string): Promise<{
|
|
50
|
+
validateCapabilityAccess(personaId: string | number, capabilityName: string, trxOrDb?: any): Promise<{
|
|
51
51
|
allowed: boolean;
|
|
52
52
|
reason?: string;
|
|
53
53
|
}>;
|
|
@@ -28,8 +28,8 @@ export class CapabilityManager {
|
|
|
28
28
|
/**
|
|
29
29
|
* Register or update a capability (skill)
|
|
30
30
|
*/
|
|
31
|
-
async registerCapability(name, version, description, metadata = {}) {
|
|
32
|
-
|
|
31
|
+
async registerCapability(name, version, description, metadata = {}, trxOrDb = this.db) {
|
|
32
|
+
const runner = async (trx) => {
|
|
33
33
|
const existing = await trx
|
|
34
34
|
.selectFrom(this.capabilitiesTable)
|
|
35
35
|
.selectAll()
|
|
@@ -72,21 +72,29 @@ export class CapabilityManager {
|
|
|
72
72
|
.returningAll()
|
|
73
73
|
.executeTakeFirstOrThrow();
|
|
74
74
|
return this.parseCapability(created);
|
|
75
|
-
}
|
|
75
|
+
};
|
|
76
|
+
if (trxOrDb && trxOrDb !== this.db) {
|
|
77
|
+
return await runner(trxOrDb);
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
return await this.db.transaction().execute(runner);
|
|
81
|
+
}
|
|
76
82
|
}
|
|
77
83
|
/**
|
|
78
84
|
* Update reliability based on action outcome using a damped moving average.
|
|
79
85
|
* Manages the lifecycle of emergent skills (sandbox -> verified / blacklisted).
|
|
80
86
|
*/
|
|
81
|
-
async reportOutcome(name, success) {
|
|
82
|
-
|
|
87
|
+
async reportOutcome(name, success, trxOrDb = this.db) {
|
|
88
|
+
const runner = async (trx) => {
|
|
83
89
|
let query = trx
|
|
84
90
|
.selectFrom(this.capabilitiesTable)
|
|
85
91
|
.selectAll()
|
|
86
92
|
.where('name', '=', name)
|
|
87
93
|
.orderBy('updated_at', 'desc');
|
|
88
94
|
// PRODUCTION HARDENING: Lock row to prevent RMW race (Skip for SQLite)
|
|
89
|
-
|
|
95
|
+
const executor = trx.getExecutor();
|
|
96
|
+
const adapterName = executor?.adapter?.constructor?.name || executor?.dialect?.constructor?.name || '';
|
|
97
|
+
if (!adapterName.toLowerCase().includes('sqlite')) {
|
|
90
98
|
query = query.forUpdate();
|
|
91
99
|
}
|
|
92
100
|
const capability = await query.executeTakeFirst();
|
|
@@ -187,13 +195,19 @@ export class CapabilityManager {
|
|
|
187
195
|
.where('id', '=', cap.id)
|
|
188
196
|
.execute();
|
|
189
197
|
}
|
|
190
|
-
}
|
|
198
|
+
};
|
|
199
|
+
if (trxOrDb && trxOrDb !== this.db) {
|
|
200
|
+
await runner(trxOrDb);
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
await this.db.transaction().execute(runner);
|
|
204
|
+
}
|
|
191
205
|
}
|
|
192
206
|
/**
|
|
193
207
|
* Get reliability score for a capability.
|
|
194
208
|
*/
|
|
195
|
-
async getReliability(name) {
|
|
196
|
-
const cap = await
|
|
209
|
+
async getReliability(name, trxOrDb = this.db) {
|
|
210
|
+
const cap = await trxOrDb
|
|
197
211
|
.selectFrom(this.capabilitiesTable)
|
|
198
212
|
.select('reliability')
|
|
199
213
|
.where('name', '=', name)
|
|
@@ -204,8 +218,8 @@ export class CapabilityManager {
|
|
|
204
218
|
/**
|
|
205
219
|
* Get all registered capabilities, optionally filtered by status
|
|
206
220
|
*/
|
|
207
|
-
async getCapabilities(status) {
|
|
208
|
-
let query =
|
|
221
|
+
async getCapabilities(status, trxOrDb = this.db) {
|
|
222
|
+
let query = trxOrDb
|
|
209
223
|
.selectFrom(this.capabilitiesTable)
|
|
210
224
|
.selectAll();
|
|
211
225
|
if (status) {
|
|
@@ -221,9 +235,10 @@ export class CapabilityManager {
|
|
|
221
235
|
// Filter to latest/best variants if many versions exist
|
|
222
236
|
const unique = new Map();
|
|
223
237
|
for (const c of list) {
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
|
|
238
|
+
const cap = c;
|
|
239
|
+
const meta = typeof cap.metadata === 'string' ? JSON.parse(cap.metadata) : (cap.metadata || {});
|
|
240
|
+
if (!unique.has(cap.name) || meta.is_alpha) {
|
|
241
|
+
unique.set(cap.name, cap);
|
|
227
242
|
}
|
|
228
243
|
}
|
|
229
244
|
return Array.from(unique.values()).map((c) => this.parseCapability(c));
|
|
@@ -231,13 +246,13 @@ export class CapabilityManager {
|
|
|
231
246
|
/**
|
|
232
247
|
* Validate if a persona has access to a specific capability (Sandbox Enforcement).
|
|
233
248
|
*/
|
|
234
|
-
async validateCapabilityAccess(personaId, capabilityName) {
|
|
235
|
-
const persona = await this.cortex.personas.getPersona(String(personaId)) ||
|
|
236
|
-
await
|
|
249
|
+
async validateCapabilityAccess(personaId, capabilityName, trxOrDb = this.db) {
|
|
250
|
+
const persona = await this.cortex.personas.getPersona(String(personaId), trxOrDb) ||
|
|
251
|
+
await trxOrDb.selectFrom(this.config.personasTable || 'agent_personas')
|
|
237
252
|
.selectAll()
|
|
238
253
|
.where('id', '=', personaId)
|
|
239
254
|
.executeTakeFirst()
|
|
240
|
-
.then(p => p ? this.cortex.personas.parsePersona(p) : null);
|
|
255
|
+
.then((p) => p ? this.cortex.personas.parsePersona(p) : null);
|
|
241
256
|
if (!persona) {
|
|
242
257
|
return { allowed: false, reason: `Persona ${personaId} not found.` };
|
|
243
258
|
}
|
|
@@ -249,7 +264,7 @@ export class CapabilityManager {
|
|
|
249
264
|
};
|
|
250
265
|
}
|
|
251
266
|
// Check if capability is blacklisted globally
|
|
252
|
-
const cap = await
|
|
267
|
+
const cap = await trxOrDb
|
|
253
268
|
.selectFrom(this.capabilitiesTable)
|
|
254
269
|
.select(['status', 'reliability'])
|
|
255
270
|
.where('name', '=', capabilityName)
|
|
@@ -131,23 +131,22 @@ export class Cortex {
|
|
|
131
131
|
this.executionLock = true;
|
|
132
132
|
console.log('[Cortex] Initiating Autonomous Soul-Searching Loop v2 (Deep Hardening Pass)...');
|
|
133
133
|
try {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
134
|
+
await this.db.transaction().execute(async (trx) => {
|
|
135
|
+
// 1. Audit health & Run self-tests
|
|
136
|
+
await this.#runIsolated('Audit', () => this.governor.performAudit(trx));
|
|
137
|
+
await this.#runIsolated('Self-Tests', () => this.tests.runAllProbes(trx));
|
|
138
|
+
// 2. Run background rituals (optimization, compression)
|
|
139
|
+
await this.#runIsolated('Rituals', () => this.rituals.runPendingRituals(trx));
|
|
140
|
+
// 3. Learn from actions & Prune dead data
|
|
141
|
+
await this.#runIsolated('Action Refinement', () => this.refiner.refineActions(trx));
|
|
142
|
+
await this.#runIsolated('Zombie Pruning', () => this.ablation.pruneZombies(30, trx));
|
|
143
|
+
await this.#runIsolated('Ablation Monitoring', () => this.ablation.monitorAblationPerformance(trx));
|
|
144
|
+
});
|
|
145
|
+
// These are often long-running or have their own internal transaction boundaries
|
|
144
146
|
await this.#runIsolated('Strategy Mutation', () => this.strategy.mutateStrategy());
|
|
145
|
-
// 5. High-Throughput Evolution Pulse
|
|
146
147
|
await this.#runIsolated('Evolution Pulse', () => this.evolutionRitual.execute());
|
|
147
|
-
// 6. Broadcast knowledge & skills
|
|
148
148
|
await this.#runIsolated('Knowledge Broadcast', () => this.hive.broadcastKnowledge());
|
|
149
149
|
await this.#runIsolated('Skill Synthesis', () => this.skillSynthesizer.discoverAndSynthesize());
|
|
150
|
-
// 7. Evolutionary pulse
|
|
151
150
|
await this.#runIsolated('Improvement Cycle', () => this.pilot.runSelfImprovementCycle());
|
|
152
151
|
console.log('[Cortex] Soul-Searching loop completed.');
|
|
153
152
|
}
|
|
@@ -30,18 +30,18 @@ export declare class PersonaManager {
|
|
|
30
30
|
capabilities?: string[];
|
|
31
31
|
policies?: string[];
|
|
32
32
|
metadata?: Record<string, any>;
|
|
33
|
-
}): Promise<AgentPersona>;
|
|
33
|
+
}, trxOrDb?: any): Promise<AgentPersona>;
|
|
34
34
|
/**
|
|
35
35
|
* Get a persona by name
|
|
36
36
|
*/
|
|
37
|
-
getPersona(name: string): Promise<AgentPersona | null>;
|
|
37
|
+
getPersona(name: string, trxOrDb?: any): Promise<AgentPersona | null>;
|
|
38
38
|
/**
|
|
39
39
|
* Delete a persona by name
|
|
40
40
|
*/
|
|
41
|
-
deletePersona(name: string): Promise<boolean>;
|
|
41
|
+
deletePersona(name: string, trxOrDb?: any): Promise<boolean>;
|
|
42
42
|
/**
|
|
43
43
|
* List all personas
|
|
44
44
|
*/
|
|
45
|
-
listPersonas(): Promise<AgentPersona[]>;
|
|
45
|
+
listPersonas(trxOrDb?: any): Promise<AgentPersona[]>;
|
|
46
46
|
private parsePersona;
|
|
47
47
|
}
|