noormme 1.2.3 → 1.2.5
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 +35 -24
- package/dist/cjs/agentic/Cortex.js +12 -13
- package/dist/cjs/agentic/EpisodicMemory.js +4 -3
- package/dist/cjs/agentic/PersonaManager.d.ts +4 -4
- package/dist/cjs/agentic/PersonaManager.js +19 -15
- package/dist/cjs/agentic/PolicyEnforcer.d.ts +4 -8
- package/dist/cjs/agentic/PolicyEnforcer.js +26 -26
- package/dist/cjs/agentic/ResourceMonitor.js +2 -1
- package/dist/cjs/agentic/SessionManager.js +7 -6
- package/dist/cjs/agentic/improvement/AblationEngine.d.ts +3 -3
- package/dist/cjs/agentic/improvement/AblationEngine.js +41 -24
- package/dist/cjs/agentic/improvement/ActionRefiner.d.ts +1 -1
- package/dist/cjs/agentic/improvement/ActionRefiner.js +21 -15
- package/dist/cjs/agentic/improvement/ConflictResolver.js +4 -3
- 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/GoalArchitect.js +10 -9
- 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 +69 -351
- 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 +27 -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 +7 -11
- package/dist/cjs/agentic/improvement/governance/RemediationEngine.js +8 -3
- 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 +57 -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/agentic/util/db-utils.d.ts +4 -0
- package/dist/cjs/agentic/util/db-utils.js +27 -0
- package/dist/cjs/cli/index.js +0 -0
- package/dist/cjs/helpers/agent-schema.js +1 -0
- package/dist/cjs/testing/test-utils.js +2 -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 +35 -24
- package/dist/esm/agentic/Cortex.js +12 -13
- package/dist/esm/agentic/EpisodicMemory.js +4 -3
- package/dist/esm/agentic/PersonaManager.d.ts +4 -4
- package/dist/esm/agentic/PersonaManager.js +19 -15
- package/dist/esm/agentic/PolicyEnforcer.d.ts +4 -8
- package/dist/esm/agentic/PolicyEnforcer.js +26 -26
- package/dist/esm/agentic/ResourceMonitor.js +2 -1
- package/dist/esm/agentic/SessionManager.js +7 -6
- package/dist/esm/agentic/improvement/AblationEngine.d.ts +3 -3
- package/dist/esm/agentic/improvement/AblationEngine.js +41 -24
- package/dist/esm/agentic/improvement/ActionRefiner.d.ts +1 -1
- package/dist/esm/agentic/improvement/ActionRefiner.js +21 -15
- package/dist/esm/agentic/improvement/ConflictResolver.js +4 -3
- 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/GoalArchitect.js +10 -9
- 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 +69 -351
- 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 +27 -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 +7 -11
- package/dist/esm/agentic/improvement/governance/RemediationEngine.js +8 -3
- 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 +54 -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/agentic/util/db-utils.d.ts +4 -0
- package/dist/esm/agentic/util/db-utils.js +25 -0
- package/dist/esm/helpers/agent-schema.js +1 -0
- package/dist/esm/testing/test-utils.js +2 -0
- package/dist/esm/types/index.d.ts +8 -0
- package/package.json +40 -44
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.StrategicPlanner = void 0;
|
|
4
|
-
const
|
|
4
|
+
const PerformanceAnalyst_js_1 = require("./strategy/PerformanceAnalyst.js");
|
|
5
|
+
const MutationEngine_js_1 = require("./strategy/MutationEngine.js");
|
|
6
|
+
const EvolutionVerificator_js_1 = require("./strategy/EvolutionVerificator.js");
|
|
5
7
|
/**
|
|
6
8
|
* StrategicPlanner proactively suggests mutation to agent personas
|
|
7
9
|
* based on performance trends observed in SovereignMetrics.
|
|
@@ -12,447 +14,92 @@ class StrategicPlanner {
|
|
|
12
14
|
config;
|
|
13
15
|
personasTable;
|
|
14
16
|
metricsTable;
|
|
17
|
+
analyst;
|
|
18
|
+
engine;
|
|
19
|
+
verificator;
|
|
15
20
|
constructor(db, cortex, config = {}) {
|
|
16
21
|
this.db = db;
|
|
17
22
|
this.cortex = cortex;
|
|
18
23
|
this.config = config;
|
|
19
24
|
this.personasTable = config.personasTable || 'agent_personas';
|
|
20
25
|
this.metricsTable = config.metricsTable || 'agent_metrics';
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
26
|
+
this.analyst = new PerformanceAnalyst_js_1.PerformanceAnalyst();
|
|
27
|
+
this.engine = new MutationEngine_js_1.MutationEngine(this.personasTable);
|
|
28
|
+
this.verificator = new EvolutionVerificator_js_1.EvolutionVerificator();
|
|
24
29
|
}
|
|
25
30
|
/**
|
|
26
31
|
* Analyze performance for all personas and apply mutations where necessary.
|
|
27
32
|
*/
|
|
28
|
-
async mutateStrategy() {
|
|
33
|
+
async mutateStrategy(trxOrDb = this.db) {
|
|
29
34
|
const mutations = [];
|
|
30
|
-
//
|
|
31
|
-
const tests = await this.cortex.tests.runAllProbes();
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
console.warn(`[StrategicPlanner] Mutation cycle aborted. System health probes failed: ${failedTests.map((t) => t.name).join(', ')}`);
|
|
35
|
+
// System Health Check
|
|
36
|
+
const tests = await this.cortex.tests.runAllProbes(trxOrDb);
|
|
37
|
+
if (tests.some((t) => !t.success)) {
|
|
38
|
+
console.warn('[StrategicPlanner] Mutation cycle aborted. System health probes failed.');
|
|
35
39
|
return [];
|
|
36
40
|
}
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
for (const p of personas) {
|
|
45
|
-
const persona = this.parsePersona(p);
|
|
41
|
+
const personaRows = await trxOrDb.selectFrom(this.personasTable).selectAll().execute();
|
|
42
|
+
const allPersonas = personaRows.map((p) => this.parsePersona(p));
|
|
43
|
+
const configStrategy = this.config.strategy || {};
|
|
44
|
+
const globalBlacklistDuration = configStrategy.globalBlacklistDuration || 3600000;
|
|
45
|
+
const localBlacklistDuration = configStrategy.localBlacklistDuration || 86400000;
|
|
46
|
+
for (const persona of allPersonas) {
|
|
47
|
+
const report = await this.analyst.analyze(trxOrDb, this.cortex, this.metricsTable, persona.id);
|
|
46
48
|
// 1. Verification Monitor
|
|
47
49
|
if (persona.metadata?.evolution_status === 'verifying') {
|
|
48
|
-
const result = await this.
|
|
50
|
+
const result = await this.verificator.verify(trxOrDb, this.cortex, this.personasTable, persona, report, allPersonas, (id, trx) => this.rollbackPersona(id, trx));
|
|
49
51
|
if (result)
|
|
50
52
|
mutations.push(result);
|
|
51
53
|
continue;
|
|
52
54
|
}
|
|
53
|
-
// 2. Failure Analysis
|
|
54
|
-
const failures = await this.analyzeFailurePatterns(persona.id);
|
|
55
|
-
|
|
56
|
-
// 3. Blacklist Check (Local & Global Phase 5)
|
|
55
|
+
// 2. Failure Analysis
|
|
56
|
+
const failures = await this.analyst.analyzeFailurePatterns(this.cortex, persona.id, trxOrDb);
|
|
57
|
+
// 3. Blacklist Check
|
|
57
58
|
const lastMutation = persona.metadata?.last_failed_mutation;
|
|
58
|
-
const isGloballyBlacklisted =
|
|
59
|
+
const isGloballyBlacklisted = allPersonas.some((mp) => {
|
|
59
60
|
return (mp.metadata?.last_failed_mutation?.type === report.recommendation &&
|
|
60
|
-
Date.now() - (mp.metadata?.last_failed_mutation?.timestamp || 0) <
|
|
61
|
-
globalBlacklistDuration);
|
|
61
|
+
Date.now() - (mp.metadata?.last_failed_mutation?.timestamp || 0) < globalBlacklistDuration);
|
|
62
62
|
});
|
|
63
|
-
if (isGloballyBlacklisted ||
|
|
64
|
-
(lastMutation &&
|
|
65
|
-
report.recommendation === lastMutation.type &&
|
|
66
|
-
Date.now() - lastMutation.timestamp < localBlacklistDuration)) {
|
|
67
|
-
console.log(`[StrategicPlanner] Skipping blacklisted mutation ${report.recommendation} for persona ${persona.id} (Global=${isGloballyBlacklisted})`);
|
|
63
|
+
if (isGloballyBlacklisted || (lastMutation && report.recommendation === lastMutation.type && Date.now() - lastMutation.timestamp < localBlacklistDuration)) {
|
|
68
64
|
continue;
|
|
69
65
|
}
|
|
70
66
|
if (report.recommendation !== 'maintain' || failures.length > 0) {
|
|
71
|
-
const result = await this.
|
|
72
|
-
if (result)
|
|
67
|
+
const result = await this.engine.applyMutation(trxOrDb, this.cortex, persona, report, failures, (r) => this.sanitizeRole(r), (p) => this.parsePersona(p));
|
|
68
|
+
if (result)
|
|
73
69
|
mutations.push(result);
|
|
74
|
-
}
|
|
75
70
|
}
|
|
76
71
|
}
|
|
77
72
|
return mutations;
|
|
78
73
|
}
|
|
79
74
|
/**
|
|
80
|
-
* Directly mutate a persona
|
|
81
|
-
* Performs a pre-flight conflict check and injects distilled lessons.
|
|
82
|
-
*/
|
|
83
|
-
async applyDirectMutation(persona, report, failures = []) {
|
|
84
|
-
return await this.db.transaction().execute(async (trx) => {
|
|
85
|
-
const reason = failures.length > 0
|
|
86
|
-
? `Failure Patterns: ${failures.join(', ')}`
|
|
87
|
-
: report.recommendation;
|
|
88
|
-
console.log(`[StrategicPlanner] Applying direct mutation to persona ${persona.id} (Reason: ${reason})`);
|
|
89
|
-
let updates = {};
|
|
90
|
-
let mutationType = 'role_update';
|
|
91
|
-
if (failures.length > 0) {
|
|
92
|
-
// Lesson-Driven Synthesis: Pull categories of lessons
|
|
93
|
-
const lessons = await this.cortex.reasoner.synthesizeLessons();
|
|
94
|
-
const relevantLessons = updates.role
|
|
95
|
-
? []
|
|
96
|
-
: (lessons['general'] || []).slice(0, 2);
|
|
97
|
-
updates = {
|
|
98
|
-
role: `${persona.role || ''} (Optimized for: ${failures.join(', ')}. Patterns: ${relevantLessons.join('; ')})`.trim(),
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
else {
|
|
102
|
-
// Evolutionary Cross-Pollination (Phase 5)
|
|
103
|
-
const allPersonas = await trx
|
|
104
|
-
.selectFrom(this.personasTable)
|
|
105
|
-
.selectAll()
|
|
106
|
-
.execute();
|
|
107
|
-
const winningMutations = allPersonas
|
|
108
|
-
.map((p) => this.parsePersona(p))
|
|
109
|
-
.filter((p) => (p.metadata?.evolution_status === 'stable' ||
|
|
110
|
-
!p.metadata?.evolution_status) &&
|
|
111
|
-
p.metadata?.mutation_reason?.includes(report.recommendation));
|
|
112
|
-
if (winningMutations.length > 0) {
|
|
113
|
-
// PRODUCTION HARDENING: Deterministic Alpha Selection
|
|
114
|
-
// Instead of Math.random(), pick the variant with the highest anchored reliability
|
|
115
|
-
const sorted = winningMutations.sort((a, b) => (b.metadata?.anchored_reliability || 0) - (a.metadata?.anchored_reliability || 0));
|
|
116
|
-
const alphaMatch = sorted[0];
|
|
117
|
-
console.log(`[StrategicPlanner] Cross-Pollinating success from Alpha Persona ${alphaMatch.id} (Reliability: ${alphaMatch.metadata?.anchored_reliability || 0})`);
|
|
118
|
-
updates = { role: this.sanitizeRole(alphaMatch.role || persona.role || 'Agent') };
|
|
119
|
-
}
|
|
120
|
-
else {
|
|
121
|
-
switch (report.recommendation) {
|
|
122
|
-
case 'optimize_accuracy':
|
|
123
|
-
updates = {
|
|
124
|
-
role: this.sanitizeRole(`${persona.role || ''} (Focus strictly on accuracy and detailed verification)`),
|
|
125
|
-
};
|
|
126
|
-
break;
|
|
127
|
-
case 'optimize_efficiency':
|
|
128
|
-
updates = {
|
|
129
|
-
policies: [
|
|
130
|
-
...(persona.policies || []),
|
|
131
|
-
'timeout_reduction',
|
|
132
|
-
'concise_output',
|
|
133
|
-
],
|
|
134
|
-
};
|
|
135
|
-
mutationType = 'policy_update';
|
|
136
|
-
break;
|
|
137
|
-
case 'critical_intervention':
|
|
138
|
-
return await this.rollbackPersona(persona.id);
|
|
139
|
-
default:
|
|
140
|
-
return null;
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
if (updates.role) {
|
|
145
|
-
updates.role = this.sanitizeRole(updates.role);
|
|
146
|
-
}
|
|
147
|
-
// 1. Predictive Conflict Detection (Pre-flight)
|
|
148
|
-
const proposedState = { ...persona, ...updates };
|
|
149
|
-
const contradictions = await this.cortex.reasoner.detectContradictions();
|
|
150
|
-
// If the new role contradicts existing goals, block mutation
|
|
151
|
-
for (const contradiction of contradictions) {
|
|
152
|
-
if (updates.role && contradiction.includes(updates.role.slice(0, 20))) {
|
|
153
|
-
console.warn(`[StrategicPlanner] Mutation blocked due to goal contradiction: ${contradiction}`);
|
|
154
|
-
return null;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
// Record mutation in history
|
|
158
|
-
const mutation = {
|
|
159
|
-
id: `mut_${Date.now()}`,
|
|
160
|
-
timestamp: Date.now(),
|
|
161
|
-
type: mutationType,
|
|
162
|
-
previousState: {
|
|
163
|
-
role: persona.role,
|
|
164
|
-
policies: persona.policies,
|
|
165
|
-
capabilities: persona.capabilities,
|
|
166
|
-
},
|
|
167
|
-
newState: { ...updates },
|
|
168
|
-
reason: `Auto-mutation triggered by ${report.recommendation}`,
|
|
169
|
-
};
|
|
170
|
-
const history = [...(persona.metadata?.mutationHistory || []), mutation];
|
|
171
|
-
if (history.length > 5)
|
|
172
|
-
history.shift();
|
|
173
|
-
const newMetadata = {
|
|
174
|
-
...persona.metadata,
|
|
175
|
-
mutationHistory: history,
|
|
176
|
-
evolution_status: 'verifying',
|
|
177
|
-
mutation_reason: report.recommendation, // Hive Signal (Phase 5)
|
|
178
|
-
verification_started_at: Date.now(),
|
|
179
|
-
verification_baseline: {
|
|
180
|
-
successRate: report.successRate,
|
|
181
|
-
averageLatency: report.averageLatency,
|
|
182
|
-
},
|
|
183
|
-
};
|
|
184
|
-
await trx
|
|
185
|
-
.updateTable(this.personasTable)
|
|
186
|
-
.set({
|
|
187
|
-
role: updates.role || persona.role,
|
|
188
|
-
policies: updates.policies
|
|
189
|
-
? JSON.stringify(updates.policies)
|
|
190
|
-
: undefined,
|
|
191
|
-
capabilities: updates.capabilities
|
|
192
|
-
? JSON.stringify(updates.capabilities)
|
|
193
|
-
: undefined,
|
|
194
|
-
metadata: JSON.stringify(newMetadata),
|
|
195
|
-
updated_at: new Date(),
|
|
196
|
-
})
|
|
197
|
-
.where('id', '=', persona.id)
|
|
198
|
-
.execute();
|
|
199
|
-
return `Persona ${persona.id} mutated and entering verification window for ${mutationType}.`;
|
|
200
|
-
});
|
|
201
|
-
}
|
|
202
|
-
/**
|
|
203
|
-
* Check if a persona in verification should be stabilized or rolled back.
|
|
204
|
-
* Uses dynamic statistical variance and adaptive meta-tuning.
|
|
205
|
-
*/
|
|
206
|
-
async verifyEvolution(persona, allPersonas = []) {
|
|
207
|
-
const report = await this.analyzePersona(persona.id);
|
|
208
|
-
// Adaptive Meta-Tuning: Increase window based on rollback history (Phase 4)
|
|
209
|
-
const rollbackHistory = persona.metadata?.rollbackHistory || [];
|
|
210
|
-
const recentRollbacks = rollbackHistory.filter((ts) => Date.now() - ts < 604800000).length;
|
|
211
|
-
// Hive-Mind Verification Speedups (Phase 5)
|
|
212
|
-
const hiveTrusted = allPersonas
|
|
213
|
-
.filter((p) => p.metadata?.evolution_status === 'stable' &&
|
|
214
|
-
p.metadata?.mutation_reason === persona.metadata?.mutation_reason).length;
|
|
215
|
-
let sampleSizeThreshold = 10 + recentRollbacks * 10;
|
|
216
|
-
// Pass 5: Adaptive Verification Windows
|
|
217
|
-
// If a mutation is performing exceptionally well early on (Z-score check), accelerate stabilization.
|
|
218
|
-
const earlyStats = await this.analyzePersona(persona.id);
|
|
219
|
-
const earlyBaseline = persona.metadata?.verification_baseline || {
|
|
220
|
-
successRate: 0.8,
|
|
221
|
-
};
|
|
222
|
-
const earlyZ = (earlyStats.successRate - earlyBaseline.successRate) / 0.1; // Use nominal stdDev for early check
|
|
223
|
-
if (earlyZ > 3.0 && earlyStats.sampleSize >= 5) {
|
|
224
|
-
console.log(`[StrategicPlanner] High Performance Detected (Z=${earlyZ.toFixed(2)}). Accelerating stabilization threshold.`);
|
|
225
|
-
sampleSizeThreshold = 5; // Accelerated Stabilization
|
|
226
|
-
}
|
|
227
|
-
if (hiveTrusted >= 3) {
|
|
228
|
-
console.log(`[StrategicPlanner] Accelerating verification for Persona ${persona.id} (Hive-Mind Trusted)`);
|
|
229
|
-
sampleSizeThreshold = Math.max(5, Math.floor(sampleSizeThreshold / 2));
|
|
230
|
-
}
|
|
231
|
-
if (report.sampleSize < sampleSizeThreshold)
|
|
232
|
-
return null;
|
|
233
|
-
const baseline = persona.metadata?.verification_baseline || {
|
|
234
|
-
successRate: 0.8,
|
|
235
|
-
averageLatency: 500,
|
|
236
|
-
};
|
|
237
|
-
// Dynamic Variance Calculation (Intelligence Refinement)
|
|
238
|
-
const recentMetrics = await this.cortex.metrics.getRecentMetrics(100);
|
|
239
|
-
const values = recentMetrics
|
|
240
|
-
.filter((m) => m.metricName === 'success_rate')
|
|
241
|
-
.map((m) => Number(m.metricValue));
|
|
242
|
-
const mean = values.reduce((a, b) => a + b, 0) / (values.length || 1);
|
|
243
|
-
const variance = values.reduce((a, b) => a + Math.pow(b - mean, 2), 0) /
|
|
244
|
-
(values.length || 1);
|
|
245
|
-
const stdDev = Math.sqrt(variance) || 0.1;
|
|
246
|
-
const zScore = (report.successRate - baseline.successRate) / (stdDev || 1);
|
|
247
|
-
console.log(`[StrategicPlanner] Verifying persona ${persona.id}: Success=${report.successRate.toFixed(2)} (Baseline=${baseline.successRate.toFixed(2)}, σ=${stdDev.toFixed(3)}, Z-Score=${zScore.toFixed(2)}, Threshold=${sampleSizeThreshold})`);
|
|
248
|
-
// 1. Early Rollback (Critical statistical drop)
|
|
249
|
-
if (zScore < -2.0) {
|
|
250
|
-
console.warn(`[StrategicPlanner] STATISTICAL DEGRADATION detected for persona ${persona.id} (Z-Score: ${zScore.toFixed(2)}). Rolling back early.`);
|
|
251
|
-
return await this.rollbackPersona(persona.id);
|
|
252
|
-
}
|
|
253
|
-
// 2. Stabilization (Proven improvement or stability)
|
|
254
|
-
if (report.sampleSize >= sampleSizeThreshold * 2 && zScore >= -0.5) {
|
|
255
|
-
console.log(`[StrategicPlanner] Evolution for persona ${persona.id} STABILIZED.`);
|
|
256
|
-
// Cognitive Rule Distillation (Phase 4)
|
|
257
|
-
if (persona.metadata?.mutation_reason?.includes('optimize_efficiency')) {
|
|
258
|
-
await this.cortex.rules.defineRule('all', 'all', 'audit', {
|
|
259
|
-
condition: 'latency > 500',
|
|
260
|
-
priority: 10,
|
|
261
|
-
metadata: {
|
|
262
|
-
reason: `Distilled from successful persona ${persona.id} optimization`,
|
|
263
|
-
},
|
|
264
|
-
});
|
|
265
|
-
}
|
|
266
|
-
await this.db
|
|
267
|
-
.updateTable(this.personasTable)
|
|
268
|
-
.set({
|
|
269
|
-
metadata: JSON.stringify({
|
|
270
|
-
...persona.metadata,
|
|
271
|
-
evolution_status: 'stable',
|
|
272
|
-
}),
|
|
273
|
-
})
|
|
274
|
-
.where('id', '=', persona.id)
|
|
275
|
-
.execute();
|
|
276
|
-
return `Evolution stabilized for persona ${persona.id}`;
|
|
277
|
-
}
|
|
278
|
-
// 3. Time-out or persistent mild degradation
|
|
279
|
-
const timeInVerification = (Date.now() - (persona.metadata?.verification_started_at || 0)) / 1000;
|
|
280
|
-
if (timeInVerification > 86400 * 3) {
|
|
281
|
-
console.warn(`[StrategicPlanner] Verification period timed out for ${persona.id}. Rolling back to safety.`);
|
|
282
|
-
return await this.rollbackPersona(persona.id);
|
|
283
|
-
}
|
|
284
|
-
return null;
|
|
285
|
-
}
|
|
286
|
-
/**
|
|
287
|
-
* Analyze recent actions for specific failure patterns.
|
|
75
|
+
* Directly mutate a persona.
|
|
288
76
|
*/
|
|
289
|
-
async
|
|
290
|
-
|
|
291
|
-
// Use ActionJournal if available to find failing tools
|
|
292
|
-
try {
|
|
293
|
-
const failureReport = await this.cortex.actions.getFailureReport();
|
|
294
|
-
// Only consider tools that failed more than once
|
|
295
|
-
const frequentFailures = failureReport.filter((f) => f.failureCount > 1);
|
|
296
|
-
for (const fail of frequentFailures) {
|
|
297
|
-
patterns.push(`tool_failure_${fail.toolName}`);
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
catch (e) {
|
|
301
|
-
// Fallback to basic metrics if ActionJournal is not reachable
|
|
302
|
-
}
|
|
303
|
-
return patterns;
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* Generate a performance report for a specific persona.
|
|
307
|
-
* Uses dynamic satisfaction thresholds based on global population stats (Phase 6).
|
|
308
|
-
*/
|
|
309
|
-
async analyzePersona(id) {
|
|
310
|
-
const recentMetrics = await this.typedDb
|
|
311
|
-
.selectFrom(this.metricsTable)
|
|
312
|
-
.selectAll()
|
|
313
|
-
.where((eb) => eb.or([
|
|
314
|
-
eb((0, sql_js_1.sql) `json_extract(metadata, '$.persona_id')`, '=', id),
|
|
315
|
-
eb((0, sql_js_1.sql) `metadata->>'persona_id'`, '=', String(id)),
|
|
316
|
-
]))
|
|
317
|
-
.orderBy('created_at', 'desc')
|
|
318
|
-
.limit(50)
|
|
319
|
-
.execute();
|
|
320
|
-
// 1. Fetch Global Baseline for Dynamic Thresholds
|
|
321
|
-
const globalMetrics = await this.cortex.metrics.getRecentMetrics(200);
|
|
322
|
-
const calcStats = (metricName) => {
|
|
323
|
-
const vals = globalMetrics
|
|
324
|
-
.filter((m) => m.metricName === metricName)
|
|
325
|
-
.map((m) => Number(m.metricValue));
|
|
326
|
-
if (vals.length < 10)
|
|
327
|
-
return { mean: metricName === 'query_latency' ? 500 : 0.9, stdDev: 0.1 };
|
|
328
|
-
const mean = vals.reduce((a, b) => a + b, 0) / vals.length;
|
|
329
|
-
const variance = vals.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / vals.length;
|
|
330
|
-
return { mean, stdDev: Math.sqrt(variance) || 0.05 };
|
|
331
|
-
};
|
|
332
|
-
const successStats = calcStats('task_success_rate');
|
|
333
|
-
const latencyStats = calcStats('query_latency');
|
|
334
|
-
if (recentMetrics.length === 0) {
|
|
335
|
-
return {
|
|
336
|
-
personaId: id,
|
|
337
|
-
successRate: successStats.mean,
|
|
338
|
-
averageLatency: latencyStats.mean,
|
|
339
|
-
sampleSize: 0,
|
|
340
|
-
recommendation: 'maintain',
|
|
341
|
-
};
|
|
342
|
-
}
|
|
343
|
-
const successMetrics = recentMetrics.filter((m) => m.metric_name === 'task_success_rate');
|
|
344
|
-
const latencyMetrics = recentMetrics.filter((m) => m.metric_name === 'query_latency');
|
|
345
|
-
const avgSuccess = successMetrics.length > 0
|
|
346
|
-
? successMetrics.reduce((sum, m) => sum + Number(m.metric_value), 0) /
|
|
347
|
-
successMetrics.length
|
|
348
|
-
: successStats.mean;
|
|
349
|
-
const avgLatency = latencyMetrics.length > 0
|
|
350
|
-
? latencyMetrics.reduce((sum, m) => sum + Number(m.metric_value), 0) /
|
|
351
|
-
latencyMetrics.length
|
|
352
|
-
: latencyStats.mean;
|
|
353
|
-
let recommendation = 'maintain';
|
|
354
|
-
// 2. Map Dynamic Thresholds to Recommendations
|
|
355
|
-
// Critical: Worse than 2.5 standard deviations from mean
|
|
356
|
-
const criticalThreshold = successStats.mean - 2.5 * successStats.stdDev;
|
|
357
|
-
// Optimize: Worse than 1.0 standard deviations from mean
|
|
358
|
-
const accuracyThreshold = successStats.mean - 1.0 * successStats.stdDev;
|
|
359
|
-
// Efficiency: Latency > 2 standard deviations above mean
|
|
360
|
-
const efficiencyThreshold = latencyStats.mean + 2.0 * latencyStats.stdDev;
|
|
361
|
-
if (avgSuccess < criticalThreshold) {
|
|
362
|
-
recommendation = 'critical_intervention';
|
|
363
|
-
}
|
|
364
|
-
else if (avgSuccess < accuracyThreshold) {
|
|
365
|
-
recommendation = 'optimize_accuracy';
|
|
366
|
-
}
|
|
367
|
-
else if (avgLatency > efficiencyThreshold) {
|
|
368
|
-
recommendation = 'optimize_efficiency';
|
|
369
|
-
}
|
|
370
|
-
console.log(`[StrategicPlanner] Analysis for ${id}: Success=${avgSuccess.toFixed(3)} (Min=${accuracyThreshold.toFixed(3)}), Latency=${avgLatency.toFixed(0)} (Max=${efficiencyThreshold.toFixed(0)})`);
|
|
371
|
-
return {
|
|
372
|
-
personaId: id,
|
|
373
|
-
successRate: avgSuccess,
|
|
374
|
-
averageLatency: avgLatency,
|
|
375
|
-
sampleSize: recentMetrics.length,
|
|
376
|
-
recommendation,
|
|
377
|
-
};
|
|
77
|
+
async evolvePersona(persona, report, trxOrDb = this.db) {
|
|
78
|
+
return this.engine.applyMutation(trxOrDb, this.cortex, persona, report, [], (r) => this.sanitizeRole(r), (p) => this.parsePersona(p));
|
|
378
79
|
}
|
|
379
80
|
/**
|
|
380
|
-
*
|
|
81
|
+
* Revert the last mutation for a persona.
|
|
381
82
|
*/
|
|
382
|
-
async
|
|
383
|
-
return
|
|
83
|
+
async rollbackPersona(id, trxOrDb = this.db) {
|
|
84
|
+
return this.engine.rollback(trxOrDb, id, (p) => this.parsePersona(p));
|
|
384
85
|
}
|
|
385
86
|
/**
|
|
386
|
-
*
|
|
87
|
+
* Analyze a persona's performance report.
|
|
387
88
|
*/
|
|
388
|
-
async
|
|
389
|
-
return
|
|
390
|
-
const current = await trx
|
|
391
|
-
.selectFrom(this.personasTable)
|
|
392
|
-
.selectAll()
|
|
393
|
-
.where('id', '=', id)
|
|
394
|
-
.executeTakeFirst();
|
|
395
|
-
if (!current)
|
|
396
|
-
throw new Error(`Persona ${id} not found`);
|
|
397
|
-
const persona = this.parsePersona(current);
|
|
398
|
-
const history = persona.metadata?.mutationHistory || [];
|
|
399
|
-
const lastMutation = history.pop();
|
|
400
|
-
if (!lastMutation) {
|
|
401
|
-
return `No mutations to rollback for persona ${id}`;
|
|
402
|
-
}
|
|
403
|
-
const previous = lastMutation.previousState;
|
|
404
|
-
const rollbackHistory = persona.metadata?.rollbackHistory || [];
|
|
405
|
-
rollbackHistory.push(Date.now());
|
|
406
|
-
const newMetadata = {
|
|
407
|
-
...persona.metadata,
|
|
408
|
-
mutationHistory: history,
|
|
409
|
-
rollbackHistory: rollbackHistory,
|
|
410
|
-
last_failed_mutation: {
|
|
411
|
-
type: lastMutation.type,
|
|
412
|
-
timestamp: Date.now(),
|
|
413
|
-
},
|
|
414
|
-
evolution_status: 'stable',
|
|
415
|
-
lastRollback: Date.now(),
|
|
416
|
-
};
|
|
417
|
-
await trx
|
|
418
|
-
.updateTable(this.personasTable)
|
|
419
|
-
.set({
|
|
420
|
-
role: previous.role,
|
|
421
|
-
policies: previous.policies
|
|
422
|
-
? JSON.stringify(previous.policies)
|
|
423
|
-
: undefined,
|
|
424
|
-
capabilities: previous.capabilities
|
|
425
|
-
? JSON.stringify(previous.capabilities)
|
|
426
|
-
: undefined,
|
|
427
|
-
metadata: JSON.stringify(newMetadata),
|
|
428
|
-
updated_at: new Date(),
|
|
429
|
-
})
|
|
430
|
-
.where('id', '=', id)
|
|
431
|
-
.execute();
|
|
432
|
-
return `Rolled back mutation ${lastMutation.id} for persona ${id}`;
|
|
433
|
-
});
|
|
89
|
+
async analyzePersona(id, trxOrDb = this.db) {
|
|
90
|
+
return this.analyst.analyze(trxOrDb, this.cortex, this.metricsTable, id);
|
|
434
91
|
}
|
|
435
92
|
sanitizeRole(role) {
|
|
436
|
-
|
|
437
|
-
// Truncate to prevent context-window exhaustion/bloat
|
|
438
|
-
const truncated = role.slice(0, 500).trim();
|
|
439
|
-
// Sanitize: remove potentially dangerous prompt-injection markers or control chars
|
|
440
|
-
return truncated.replace(/[\u0000-\u001F\u007F-\u009F]/g, '').replace(/<\|.*?\|>/g, '');
|
|
93
|
+
return role.slice(0, 500).trim().replace(/[\u0000-\u001F\u007F-\u009F]/g, '').replace(/<\|.*?\|>/g, '');
|
|
441
94
|
}
|
|
442
95
|
parsePersona(p) {
|
|
443
96
|
return {
|
|
444
97
|
id: p.id,
|
|
445
98
|
name: p.name,
|
|
446
99
|
role: p.role,
|
|
447
|
-
capabilities: typeof p.capabilities === 'string'
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
policies: typeof p.policies === 'string'
|
|
451
|
-
? JSON.parse(p.policies)
|
|
452
|
-
: p.policies || [],
|
|
453
|
-
metadata: typeof p.metadata === 'string'
|
|
454
|
-
? JSON.parse(p.metadata)
|
|
455
|
-
: p.metadata || {},
|
|
100
|
+
capabilities: typeof p.capabilities === 'string' ? JSON.parse(p.capabilities) : p.capabilities || [],
|
|
101
|
+
policies: typeof p.policies === 'string' ? JSON.parse(p.policies) : p.policies || [],
|
|
102
|
+
metadata: typeof p.metadata === 'string' ? JSON.parse(p.metadata) : p.metadata || {},
|
|
456
103
|
createdAt: new Date(p.created_at),
|
|
457
104
|
updatedAt: new Date(p.updated_at),
|
|
458
105
|
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ConflictChallenger = void 0;
|
|
4
|
+
class ConflictChallenger {
|
|
5
|
+
async challenge(trxOrDb, knowledgeTable, entity, competingFact, confidence, parseKnowledgeFn) {
|
|
6
|
+
// Semantic sanitization
|
|
7
|
+
const safeFact = competingFact.slice(0, 500).replace(/[\u0000-\u001F\u007F-\u009F]/g, '').replace(/<\|.*?\|>/g, '');
|
|
8
|
+
const existingItems = await trxOrDb
|
|
9
|
+
.selectFrom(knowledgeTable)
|
|
10
|
+
.selectAll()
|
|
11
|
+
.where('entity', '=', entity)
|
|
12
|
+
.orderBy('confidence', 'desc')
|
|
13
|
+
.execute();
|
|
14
|
+
for (const item of existingItems) {
|
|
15
|
+
const parsedItem = parseKnowledgeFn(item);
|
|
16
|
+
if (parsedItem.fact === competingFact)
|
|
17
|
+
continue;
|
|
18
|
+
// Deep Hardening: Conflict detection
|
|
19
|
+
if (confidence > 0.8) {
|
|
20
|
+
let newMeta = { ...parsedItem.metadata };
|
|
21
|
+
let penalty = 0.2;
|
|
22
|
+
let newStatus = parsedItem.status;
|
|
23
|
+
if (parsedItem.confidence > 0.7) {
|
|
24
|
+
newStatus = 'disputed';
|
|
25
|
+
newMeta = {
|
|
26
|
+
...newMeta,
|
|
27
|
+
status_reason: `Contradicted by: ${safeFact}`,
|
|
28
|
+
};
|
|
29
|
+
penalty = 0.1;
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
newStatus = 'deprecated';
|
|
33
|
+
newMeta = {
|
|
34
|
+
...newMeta,
|
|
35
|
+
status_reason: `Superseded by: ${safeFact}`,
|
|
36
|
+
};
|
|
37
|
+
penalty = 0.4;
|
|
38
|
+
}
|
|
39
|
+
const newConfidence = Math.max(0, parsedItem.confidence - penalty);
|
|
40
|
+
await trxOrDb
|
|
41
|
+
.updateTable(knowledgeTable)
|
|
42
|
+
.set({
|
|
43
|
+
confidence: newConfidence,
|
|
44
|
+
status: newStatus,
|
|
45
|
+
metadata: JSON.stringify(newMeta),
|
|
46
|
+
updated_at: new Date(),
|
|
47
|
+
})
|
|
48
|
+
.where('id', '=', parsedItem.id)
|
|
49
|
+
.execute();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
exports.ConflictChallenger = ConflictChallenger;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Kysely } from '../../../kysely.js';
|
|
2
|
+
export declare class FactDistiller {
|
|
3
|
+
/**
|
|
4
|
+
* typedDb helper (internal use)
|
|
5
|
+
*/
|
|
6
|
+
private getTypedDb;
|
|
7
|
+
distillExact(trx: any, knowledgeTable: string, entity: string, fact: string, confidence: number, sourceSessionId?: string | number, tags?: string[], metadata?: Record<string, any>, source?: 'user' | 'assistant' | 'system'): Promise<any | null>;
|
|
8
|
+
createInitial(trx: any, knowledgeTable: string, entity: string, fact: string, confidence: number, sourceSessionId?: string | number, tags?: string[], metadata?: Record<string, any>, source?: 'user' | 'assistant' | 'system'): Promise<any>;
|
|
9
|
+
verify(db: Kysely<any>, knowledgeTable: string, id: number | string, reinforcement?: number): Promise<any | null>;
|
|
10
|
+
}
|