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,4 +1,5 @@
|
|
|
1
1
|
/// <reference types="./PersonaManager.d.ts" />
|
|
2
|
+
import { withLock } from './util/db-utils.js';
|
|
2
3
|
/**
|
|
3
4
|
* PersonaManager handles persistent agent identities that bridge multiple sessions.
|
|
4
5
|
*/
|
|
@@ -17,17 +18,14 @@ export class PersonaManager {
|
|
|
17
18
|
/**
|
|
18
19
|
* Create or update a persona
|
|
19
20
|
*/
|
|
20
|
-
async upsertPersona(name, options = {}) {
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
async upsertPersona(name, options = {}, trxOrDb = this.db) {
|
|
22
|
+
const runner = async (trx) => {
|
|
23
|
+
const baseQuery = trx
|
|
23
24
|
.selectFrom(this.personasTable)
|
|
24
25
|
.selectAll()
|
|
25
26
|
.where('name', '=', name);
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
query = query.forUpdate();
|
|
29
|
-
}
|
|
30
|
-
const existing = await query.executeTakeFirst();
|
|
27
|
+
const existing = await withLock(baseQuery, trx)
|
|
28
|
+
.executeTakeFirst();
|
|
31
29
|
const values = {
|
|
32
30
|
name,
|
|
33
31
|
role: options.role || null,
|
|
@@ -56,13 +54,19 @@ export class PersonaManager {
|
|
|
56
54
|
.returningAll()
|
|
57
55
|
.executeTakeFirstOrThrow();
|
|
58
56
|
return this.parsePersona(created);
|
|
59
|
-
}
|
|
57
|
+
};
|
|
58
|
+
if (trxOrDb && trxOrDb !== this.db) {
|
|
59
|
+
return await runner(trxOrDb);
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
return await this.db.transaction().execute(runner);
|
|
63
|
+
}
|
|
60
64
|
}
|
|
61
65
|
/**
|
|
62
66
|
* Get a persona by name
|
|
63
67
|
*/
|
|
64
|
-
async getPersona(name) {
|
|
65
|
-
const persona = await
|
|
68
|
+
async getPersona(name, trxOrDb = this.db) {
|
|
69
|
+
const persona = await trxOrDb
|
|
66
70
|
.selectFrom(this.personasTable)
|
|
67
71
|
.selectAll()
|
|
68
72
|
.where('name', '=', name)
|
|
@@ -72,8 +76,8 @@ export class PersonaManager {
|
|
|
72
76
|
/**
|
|
73
77
|
* Delete a persona by name
|
|
74
78
|
*/
|
|
75
|
-
async deletePersona(name) {
|
|
76
|
-
const result = await
|
|
79
|
+
async deletePersona(name, trxOrDb = this.db) {
|
|
80
|
+
const result = await trxOrDb
|
|
77
81
|
.deleteFrom(this.personasTable)
|
|
78
82
|
.where('name', '=', name)
|
|
79
83
|
.executeTakeFirst();
|
|
@@ -82,8 +86,8 @@ export class PersonaManager {
|
|
|
82
86
|
/**
|
|
83
87
|
* List all personas
|
|
84
88
|
*/
|
|
85
|
-
async listPersonas() {
|
|
86
|
-
const list = await
|
|
89
|
+
async listPersonas(trxOrDb = this.db) {
|
|
90
|
+
const list = await trxOrDb
|
|
87
91
|
.selectFrom(this.personasTable)
|
|
88
92
|
.selectAll()
|
|
89
93
|
.orderBy('name', 'asc')
|
|
@@ -33,30 +33,26 @@ export declare class PolicyEnforcer {
|
|
|
33
33
|
/**
|
|
34
34
|
* Define or update a policy with robust validation.
|
|
35
35
|
*/
|
|
36
|
-
definePolicy(name: string, type: AgentPolicy['type'], definition: Record<string, any>, isEnabled?: boolean): Promise<AgentPolicy>;
|
|
36
|
+
definePolicy(name: string, type: AgentPolicy['type'], definition: Record<string, any>, isEnabled?: boolean, trxOrDb?: any): Promise<AgentPolicy>;
|
|
37
37
|
/**
|
|
38
38
|
* Comprehensive policy evaluation against a context value.
|
|
39
39
|
* Supports thresholds, regex patterns, and cumulative budgets.
|
|
40
40
|
*/
|
|
41
|
-
|
|
42
|
-
* Comprehensive policy evaluation against a context value.
|
|
43
|
-
* Supports thresholds, regex patterns, and cumulative budgets.
|
|
44
|
-
*/
|
|
45
|
-
checkPolicy(name: string, value: any, visited?: Set<string>): Promise<{
|
|
41
|
+
checkPolicy(name: string, value: any, visited?: Set<string>, trxOrDb?: any): Promise<{
|
|
46
42
|
allowed: boolean;
|
|
47
43
|
reason?: string;
|
|
48
44
|
}>;
|
|
49
45
|
/**
|
|
50
46
|
* Evaluate a full context (object) against all applicable policies.
|
|
51
47
|
*/
|
|
52
|
-
evaluateContext(context: Record<string, any
|
|
48
|
+
evaluateContext(context: Record<string, any>, trxOrDb?: any): Promise<{
|
|
53
49
|
allowed: boolean;
|
|
54
50
|
violations: string[];
|
|
55
51
|
}>;
|
|
56
52
|
/**
|
|
57
53
|
* Get all active policies.
|
|
58
54
|
*/
|
|
59
|
-
getActivePolicies(): Promise<AgentPolicy[]>;
|
|
55
|
+
getActivePolicies(trxOrDb?: any): Promise<AgentPolicy[]>;
|
|
60
56
|
private getCumulativeMetric;
|
|
61
57
|
private parsePolicy;
|
|
62
58
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/// <reference types="./PolicyEnforcer.d.ts" />
|
|
2
|
+
import { withLock } from './util/db-utils.js';
|
|
2
3
|
/**
|
|
3
4
|
* PolicyEnforcer stores and validates agent autonomous guardrails,
|
|
4
5
|
* such as budgets, safety constraints, and privacy rules.
|
|
@@ -21,17 +22,14 @@ export class PolicyEnforcer {
|
|
|
21
22
|
/**
|
|
22
23
|
* Define or update a policy with robust validation.
|
|
23
24
|
*/
|
|
24
|
-
async definePolicy(name, type, definition, isEnabled = true) {
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
async definePolicy(name, type, definition, isEnabled = true, trxOrDb = this.db) {
|
|
26
|
+
const runner = async (trx) => {
|
|
27
|
+
const query = trx
|
|
27
28
|
.selectFrom(this.policiesTable)
|
|
28
29
|
.select('id')
|
|
29
30
|
.where('name', '=', name);
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
query = query.forUpdate();
|
|
33
|
-
}
|
|
34
|
-
const existing = await query.executeTakeFirst();
|
|
31
|
+
const existing = await withLock(query, trx)
|
|
32
|
+
.executeTakeFirst();
|
|
35
33
|
if (existing) {
|
|
36
34
|
const updated = await trx
|
|
37
35
|
.updateTable(this.policiesTable)
|
|
@@ -59,17 +57,19 @@ export class PolicyEnforcer {
|
|
|
59
57
|
.returningAll()
|
|
60
58
|
.executeTakeFirstOrThrow();
|
|
61
59
|
return this.parsePolicy(created);
|
|
62
|
-
}
|
|
60
|
+
};
|
|
61
|
+
if (trxOrDb && trxOrDb !== this.db) {
|
|
62
|
+
return await runner(trxOrDb);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
return await this.db.transaction().execute(runner);
|
|
66
|
+
}
|
|
63
67
|
}
|
|
64
68
|
/**
|
|
65
69
|
* Comprehensive policy evaluation against a context value.
|
|
66
70
|
* Supports thresholds, regex patterns, and cumulative budgets.
|
|
67
71
|
*/
|
|
68
|
-
|
|
69
|
-
* Comprehensive policy evaluation against a context value.
|
|
70
|
-
* Supports thresholds, regex patterns, and cumulative budgets.
|
|
71
|
-
*/
|
|
72
|
-
async checkPolicy(name, value, visited = new Set()) {
|
|
72
|
+
async checkPolicy(name, value, visited = new Set(), trxOrDb = this.db) {
|
|
73
73
|
// Audit Pass 6: Re-entrancy / Circular Dependency Detection
|
|
74
74
|
if (visited.has(name)) {
|
|
75
75
|
return {
|
|
@@ -78,7 +78,7 @@ export class PolicyEnforcer {
|
|
|
78
78
|
};
|
|
79
79
|
}
|
|
80
80
|
visited.add(name);
|
|
81
|
-
const policy = await
|
|
81
|
+
const policy = await trxOrDb
|
|
82
82
|
.selectFrom(this.policiesTable)
|
|
83
83
|
.selectAll()
|
|
84
84
|
.where('name', '=', name)
|
|
@@ -109,7 +109,7 @@ export class PolicyEnforcer {
|
|
|
109
109
|
if (def.pattern.length > 500) {
|
|
110
110
|
return { allowed: false, reason: `Policy '${name}' regex pattern too long (potential ReDoS risk)` };
|
|
111
111
|
}
|
|
112
|
-
const dangerousPatterns = /(\*|\+)\1|\(\.\*\)
|
|
112
|
+
const dangerousPatterns = /(\*|\+)\1|\(\.\*\)\*|\(\[.*\](\*|\+)\)(\*|\+)|\(.*\+\)\+/;
|
|
113
113
|
if (dangerousPatterns.test(def.pattern)) {
|
|
114
114
|
return { allowed: false, reason: `Policy '${name}' contains potentially dangerous ReDoS pattern` };
|
|
115
115
|
}
|
|
@@ -137,7 +137,7 @@ export class PolicyEnforcer {
|
|
|
137
137
|
if (policy.type === 'budget' && def.metricName) {
|
|
138
138
|
const period = def.period || 'daily';
|
|
139
139
|
const limit = def.limit || 0;
|
|
140
|
-
const total = await this.getCumulativeMetric(def.metricName, period);
|
|
140
|
+
const total = await this.getCumulativeMetric(def.metricName, period, trxOrDb);
|
|
141
141
|
if (total + (typeof value === 'number' ? value : 0) > limit) {
|
|
142
142
|
return {
|
|
143
143
|
allowed: false,
|
|
@@ -149,7 +149,7 @@ export class PolicyEnforcer {
|
|
|
149
149
|
// Audit Pass 6: Moved from evaluateContext to checkPolicy for deeper nesting support
|
|
150
150
|
if (def.dependsOn && Array.isArray(def.dependsOn)) {
|
|
151
151
|
for (const depName of def.dependsOn) {
|
|
152
|
-
const result = await this.checkPolicy(depName, value, new Set(visited));
|
|
152
|
+
const result = await this.checkPolicy(depName, value, new Set(visited), trxOrDb);
|
|
153
153
|
if (!result.allowed) {
|
|
154
154
|
return { allowed: false, reason: `Composite block: ${name} -> ${result.reason}` };
|
|
155
155
|
}
|
|
@@ -160,19 +160,19 @@ export class PolicyEnforcer {
|
|
|
160
160
|
/**
|
|
161
161
|
* Evaluate a full context (object) against all applicable policies.
|
|
162
162
|
*/
|
|
163
|
-
async evaluateContext(context) {
|
|
164
|
-
const policies = await this.getActivePolicies();
|
|
163
|
+
async evaluateContext(context, trxOrDb = this.db) {
|
|
164
|
+
const policies = await this.getActivePolicies(trxOrDb);
|
|
165
165
|
const violations = [];
|
|
166
166
|
for (const policy of policies) {
|
|
167
167
|
// If the context has a key matching the policy name, check it
|
|
168
168
|
if (context[policy.name] !== undefined) {
|
|
169
|
-
const result = await this.checkPolicy(policy.name, context[policy.name]);
|
|
169
|
+
const result = await this.checkPolicy(policy.name, context[policy.name], new Set(), trxOrDb);
|
|
170
170
|
if (!result.allowed)
|
|
171
171
|
violations.push(result.reason);
|
|
172
172
|
}
|
|
173
173
|
// Check for type-specific global policies (e.g. all privacy policies)
|
|
174
174
|
if (policy.type === 'privacy' && context.content) {
|
|
175
|
-
const result = await this.checkPolicy(policy.name, context.content);
|
|
175
|
+
const result = await this.checkPolicy(policy.name, context.content, new Set(), trxOrDb);
|
|
176
176
|
if (!result.allowed)
|
|
177
177
|
violations.push(result.reason);
|
|
178
178
|
}
|
|
@@ -185,15 +185,15 @@ export class PolicyEnforcer {
|
|
|
185
185
|
/**
|
|
186
186
|
* Get all active policies.
|
|
187
187
|
*/
|
|
188
|
-
async getActivePolicies() {
|
|
189
|
-
const list = await
|
|
188
|
+
async getActivePolicies(trxOrDb = this.db) {
|
|
189
|
+
const list = await trxOrDb
|
|
190
190
|
.selectFrom(this.policiesTable)
|
|
191
191
|
.selectAll()
|
|
192
192
|
.where('is_enabled', '=', true)
|
|
193
193
|
.execute();
|
|
194
194
|
return list.map((p) => this.parsePolicy(p));
|
|
195
195
|
}
|
|
196
|
-
async getCumulativeMetric(metricName, period) {
|
|
196
|
+
async getCumulativeMetric(metricName, period, trxOrDb = this.db) {
|
|
197
197
|
const cacheKey = `${metricName}:${period}`;
|
|
198
198
|
const cached = this.metricCache.get(cacheKey);
|
|
199
199
|
const now = new Date();
|
|
@@ -215,7 +215,7 @@ export class PolicyEnforcer {
|
|
|
215
215
|
else if (period === 'hourly') {
|
|
216
216
|
cutoff = new Date(now.getTime() - 3600000);
|
|
217
217
|
}
|
|
218
|
-
const result = await
|
|
218
|
+
const result = await trxOrDb
|
|
219
219
|
.selectFrom(this.metricsTable)
|
|
220
220
|
.select((eb) => eb.fn.sum('metric_value').as('total'))
|
|
221
221
|
.where('metric_name', '=', metricName)
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/// <reference types="./ResourceMonitor.d.ts" />
|
|
2
|
+
import { sql } from '../raw-builder/sql.js';
|
|
2
3
|
/**
|
|
3
4
|
* ResourceMonitor tracks token usage and costs across sessions.
|
|
4
5
|
*/
|
|
@@ -98,7 +99,7 @@ export class ResourceMonitor {
|
|
|
98
99
|
.select([
|
|
99
100
|
'model_name',
|
|
100
101
|
(eb) => eb.fn
|
|
101
|
-
.sum(
|
|
102
|
+
.sum(sql `input_tokens + output_tokens`)
|
|
102
103
|
.as('totalTokens'),
|
|
103
104
|
(eb) => eb.fn.sum('cost').as('totalCost'),
|
|
104
105
|
])
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/// <reference types="./SessionManager.d.ts" />
|
|
2
|
+
import { withLock } from './util/db-utils.js';
|
|
2
3
|
/**
|
|
3
4
|
* SessionManager handles the lifecycle of agentic sessions, including
|
|
4
5
|
* message history, goal tracking, and memory persistence.
|
|
@@ -132,12 +133,12 @@ export class SessionManager {
|
|
|
132
133
|
async upsertGoal(sessionId, description, options = {}) {
|
|
133
134
|
const { status = 'pending', priority = 0, parentId, metadata } = options;
|
|
134
135
|
return await this.db.transaction().execute(async (trx) => {
|
|
135
|
-
const
|
|
136
|
+
const query = trx
|
|
136
137
|
.selectFrom(this.goalsTable)
|
|
137
138
|
.selectAll()
|
|
138
139
|
.where('session_id', '=', sessionId)
|
|
139
|
-
.where('description', '=', description)
|
|
140
|
-
|
|
140
|
+
.where('description', '=', description);
|
|
141
|
+
const existing = await withLock(query, trx) // Audit Phase 13: Atomic goal lock
|
|
141
142
|
.executeTakeFirst();
|
|
142
143
|
if (existing) {
|
|
143
144
|
const updated = await trx
|
|
@@ -208,11 +209,11 @@ export class SessionManager {
|
|
|
208
209
|
// We avoid the Read-Modify-Write race condition by letting the DB handle the merge
|
|
209
210
|
// or by using a strict transaction if the DB doesn't support JSON patching natively.
|
|
210
211
|
const updated = await this.db.transaction().execute(async (trx) => {
|
|
211
|
-
const
|
|
212
|
+
const query = trx
|
|
212
213
|
.selectFrom(this.messagesTable)
|
|
213
214
|
.select('metadata')
|
|
214
|
-
.where('id', '=', messageId)
|
|
215
|
-
|
|
215
|
+
.where('id', '=', messageId);
|
|
216
|
+
const message = await withLock(query, trx) // Lock the row for the duration of the transaction
|
|
216
217
|
.executeTakeFirstOrThrow();
|
|
217
218
|
const metadata = typeof message.metadata === 'string'
|
|
218
219
|
? JSON.parse(message.metadata)
|
|
@@ -17,19 +17,19 @@ export declare class AblationEngine {
|
|
|
17
17
|
/**
|
|
18
18
|
* Identify "Zombies": Items that have never been retrieved/hit and are old.
|
|
19
19
|
*/
|
|
20
|
-
pruneZombies(thresholdDays?: number): Promise<number>;
|
|
20
|
+
pruneZombies(thresholdDays?: number, trxOrDb?: any): Promise<number>;
|
|
21
21
|
/**
|
|
22
22
|
* Monitor Performance and perform Intelligent Rollbacks.
|
|
23
23
|
* Prioritizes recovery of items with highest historical hit counts.
|
|
24
24
|
*/
|
|
25
|
-
monitorAblationPerformance(): Promise<{
|
|
25
|
+
monitorAblationPerformance(trxOrDb?: any): Promise<{
|
|
26
26
|
status: 'stable' | 'degraded';
|
|
27
27
|
recoveredCount: number;
|
|
28
28
|
}>;
|
|
29
29
|
/**
|
|
30
30
|
* Conduct an "Ablation Test": Temporarily disable a knowledge item.
|
|
31
31
|
*/
|
|
32
|
-
testAblation(id: string | number): Promise<boolean>;
|
|
32
|
+
testAblation(id: string | number, trxOrDb?: any): Promise<boolean>;
|
|
33
33
|
/**
|
|
34
34
|
* Restore an ablated knowledge item to its original state.
|
|
35
35
|
*/
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/// <reference types="./AblationEngine.d.ts" />
|
|
2
|
+
import { withLock } from '../util/db-utils.js';
|
|
2
3
|
/**
|
|
3
4
|
* AblationEngine identifies and removes unused or redundant data
|
|
4
5
|
* to keep the agent's context window and database lean.
|
|
@@ -24,13 +25,13 @@ export class AblationEngine {
|
|
|
24
25
|
/**
|
|
25
26
|
* Identify "Zombies": Items that have never been retrieved/hit and are old.
|
|
26
27
|
*/
|
|
27
|
-
async pruneZombies(thresholdDays = 30) {
|
|
28
|
+
async pruneZombies(thresholdDays = 30, trxOrDb = this.db) {
|
|
28
29
|
const cutoff = new Date(Date.now() - thresholdDays * 24 * 3600000);
|
|
29
30
|
let totalPruned = 0;
|
|
30
|
-
|
|
31
|
+
const runner = async (trx) => {
|
|
31
32
|
// 1. Prune Knowledge (with dependency check and pagination)
|
|
32
33
|
// Audit Phase 9: Paginated selection to prevent OOM
|
|
33
|
-
const
|
|
34
|
+
const query = trx
|
|
34
35
|
.selectFrom(this.knowledgeTable)
|
|
35
36
|
.selectAll()
|
|
36
37
|
.where((eb) => eb.or([
|
|
@@ -41,9 +42,8 @@ export class AblationEngine {
|
|
|
41
42
|
.where('updated_at', '<', cutoff)
|
|
42
43
|
.where('id', 'not in', (eb) => eb.selectFrom(this.linksTable).select('source_id'))
|
|
43
44
|
.where('id', 'not in', (eb) => eb.selectFrom(this.linksTable).select('target_id'))
|
|
44
|
-
.limit(500) // Audit Phase 9: Batch limit
|
|
45
|
-
|
|
46
|
-
.execute();
|
|
45
|
+
.limit(500); // Audit Phase 9: Batch limit
|
|
46
|
+
const knowledgeToPrune = await withLock(query, trx).execute();
|
|
47
47
|
if (knowledgeToPrune.length > 0) {
|
|
48
48
|
const candidates = knowledgeToPrune.map((k) => this.cortex.knowledge['parseKnowledge'](k));
|
|
49
49
|
const idsToDelete = [];
|
|
@@ -78,16 +78,22 @@ export class AblationEngine {
|
|
|
78
78
|
console.log(`[AblationEngine] Pruned ${totalPruned} zombie items older than ${thresholdDays} days.`);
|
|
79
79
|
}
|
|
80
80
|
return totalPruned;
|
|
81
|
-
}
|
|
81
|
+
};
|
|
82
|
+
if (trxOrDb && trxOrDb !== this.db) {
|
|
83
|
+
return await runner(trxOrDb);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
return await this.db.transaction().execute(runner);
|
|
87
|
+
}
|
|
82
88
|
}
|
|
83
89
|
/**
|
|
84
90
|
* Monitor Performance and perform Intelligent Rollbacks.
|
|
85
91
|
* Prioritizes recovery of items with highest historical hit counts.
|
|
86
92
|
*/
|
|
87
|
-
async monitorAblationPerformance() {
|
|
88
|
-
|
|
89
|
-
const baseline = await this.cortex.metrics.getAverageMetric('success_rate');
|
|
90
|
-
const stats = await this.cortex.metrics.getMetricStats('success_rate');
|
|
93
|
+
async monitorAblationPerformance(trxOrDb = this.db) {
|
|
94
|
+
const runner = async (trx) => {
|
|
95
|
+
const baseline = await this.cortex.metrics.getAverageMetric('success_rate', trx);
|
|
96
|
+
const stats = await this.cortex.metrics.getMetricStats('success_rate', {}, trx);
|
|
91
97
|
// If current average is significantly lower than overall average
|
|
92
98
|
if (stats.count > 10 && stats.avg < baseline * 0.8) {
|
|
93
99
|
console.warn(`[AblationEngine] PERFORMANCE DEGRADATION DETECTED (Avg: ${stats.avg}, Baseline: ${baseline}). Triggering targeted recovery.`);
|
|
@@ -115,20 +121,25 @@ export class AblationEngine {
|
|
|
115
121
|
return { status: 'degraded', recoveredCount };
|
|
116
122
|
}
|
|
117
123
|
return { status: 'stable', recoveredCount: 0 };
|
|
118
|
-
}
|
|
124
|
+
};
|
|
125
|
+
if (trxOrDb && trxOrDb !== this.db) {
|
|
126
|
+
return await runner(trxOrDb);
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
return await this.db.transaction().execute(runner);
|
|
130
|
+
}
|
|
119
131
|
}
|
|
120
132
|
/**
|
|
121
133
|
* Conduct an "Ablation Test": Temporarily disable a knowledge item.
|
|
122
134
|
*/
|
|
123
|
-
async testAblation(id) {
|
|
135
|
+
async testAblation(id, trxOrDb = this.db) {
|
|
124
136
|
console.log(`[AblationEngine] Conducting ablation test on item ${id}`);
|
|
125
|
-
|
|
126
|
-
const
|
|
137
|
+
const runner = async (trx) => {
|
|
138
|
+
const query = trx
|
|
127
139
|
.selectFrom(this.knowledgeTable)
|
|
128
140
|
.selectAll()
|
|
129
|
-
.where('id', '=', id)
|
|
130
|
-
|
|
131
|
-
.executeTakeFirst());
|
|
141
|
+
.where('id', '=', id);
|
|
142
|
+
const item = (await withLock(query, trx).executeTakeFirst());
|
|
132
143
|
if (!item)
|
|
133
144
|
return false;
|
|
134
145
|
const metadata = typeof item.metadata === 'string'
|
|
@@ -138,7 +149,7 @@ export class AblationEngine {
|
|
|
138
149
|
`Temporary confidence reduction to evaluate reasoning impact.`,
|
|
139
150
|
`Original confidence: ${item.confidence}`,
|
|
140
151
|
`Historical hits: ${metadata.hit_count || 0}`
|
|
141
|
-
]);
|
|
152
|
+
], undefined, trx);
|
|
142
153
|
await trx
|
|
143
154
|
.updateTable(this.knowledgeTable)
|
|
144
155
|
.set({
|
|
@@ -153,19 +164,25 @@ export class AblationEngine {
|
|
|
153
164
|
.where('id', '=', id)
|
|
154
165
|
.execute();
|
|
155
166
|
return true;
|
|
156
|
-
}
|
|
167
|
+
};
|
|
168
|
+
if (trxOrDb && trxOrDb !== this.db) {
|
|
169
|
+
await runner(trxOrDb);
|
|
170
|
+
}
|
|
171
|
+
else {
|
|
172
|
+
await this.db.transaction().execute(runner);
|
|
173
|
+
}
|
|
174
|
+
return true;
|
|
157
175
|
}
|
|
158
176
|
/**
|
|
159
177
|
* Restore an ablated knowledge item to its original state.
|
|
160
178
|
*/
|
|
161
179
|
async recoverAblatedItem(id, trx) {
|
|
162
180
|
const recoveryStep = async (t) => {
|
|
163
|
-
const
|
|
181
|
+
const query = t
|
|
164
182
|
.selectFrom(this.knowledgeTable)
|
|
165
183
|
.selectAll()
|
|
166
|
-
.where('id', '=', id)
|
|
167
|
-
|
|
168
|
-
.executeTakeFirst());
|
|
184
|
+
.where('id', '=', id);
|
|
185
|
+
const item = (await withLock(query, t).executeTakeFirst());
|
|
169
186
|
if (!item)
|
|
170
187
|
return false;
|
|
171
188
|
const metadata = typeof item.metadata === 'string'
|
|
@@ -14,7 +14,7 @@ export declare class ActionRefiner {
|
|
|
14
14
|
/**
|
|
15
15
|
* Analyze recent actions and propose improvements
|
|
16
16
|
*/
|
|
17
|
-
refineActions(): Promise<string[]>;
|
|
17
|
+
refineActions(trxOrDb?: any): Promise<string[]>;
|
|
18
18
|
/**
|
|
19
19
|
* Propose a rule to reflect on a specific tool usage
|
|
20
20
|
*/
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/// <reference types="./ActionRefiner.d.ts" />
|
|
2
|
+
import { withLock } from '../util/db-utils.js';
|
|
2
3
|
/**
|
|
3
4
|
* ActionRefiner analyzes the ActionJournal to find patterns in failures
|
|
4
5
|
* and suggests new CognitiveRules to improve agent performance.
|
|
@@ -17,12 +18,12 @@ export class ActionRefiner {
|
|
|
17
18
|
/**
|
|
18
19
|
* Analyze recent actions and propose improvements
|
|
19
20
|
*/
|
|
20
|
-
async refineActions() {
|
|
21
|
+
async refineActions(trxOrDb = this.db) {
|
|
21
22
|
const recommendations = [];
|
|
22
23
|
// 1. Find tools with high failure rates (Last 24h Window)
|
|
23
24
|
// Audit Phase 14: Sliding window to prevent global table scans
|
|
24
25
|
const windowStart = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
|
25
|
-
const failureStats = (await
|
|
26
|
+
const failureStats = (await trxOrDb
|
|
26
27
|
.selectFrom(this.actionsTable)
|
|
27
28
|
.select('tool_name')
|
|
28
29
|
.select((eb) => eb.fn.count('id').as('total'))
|
|
@@ -41,11 +42,11 @@ export class ActionRefiner {
|
|
|
41
42
|
if (rate > failureRateThreshold && total > minActionBatch) {
|
|
42
43
|
recommendations.push(`Tool '${stat.tool_name}' has a ${Math.round(rate * 100)}% failure rate. Suggesting automatic reflection rule.`);
|
|
43
44
|
// Automatically propose a rule to reflect on this tool's usage
|
|
44
|
-
await this.proposeReflectionRule(stat.tool_name);
|
|
45
|
+
await this.proposeReflectionRule(stat.tool_name, trxOrDb);
|
|
45
46
|
}
|
|
46
47
|
}
|
|
47
48
|
// 2. Discover missing capabilities based on error patterns (Last 24h)
|
|
48
|
-
const missingCapabilities = (await
|
|
49
|
+
const missingCapabilities = (await trxOrDb
|
|
49
50
|
.selectFrom(this.actionsTable)
|
|
50
51
|
.select('tool_name')
|
|
51
52
|
.where('status', '=', 'failure')
|
|
@@ -60,25 +61,24 @@ export class ActionRefiner {
|
|
|
60
61
|
.execute());
|
|
61
62
|
for (const row of missingCapabilities) {
|
|
62
63
|
recommendations.push(`Detected repeated access/existence failures for tool '${row.tool_name}'. Proposing capability expansion.`);
|
|
63
|
-
await this.proposeCapabilityUpdate(row.tool_name);
|
|
64
|
+
await this.proposeCapabilityUpdate(row.tool_name, trxOrDb);
|
|
64
65
|
}
|
|
65
66
|
return recommendations;
|
|
66
67
|
}
|
|
67
68
|
/**
|
|
68
69
|
* Propose a rule to reflect on a specific tool usage
|
|
69
70
|
*/
|
|
70
|
-
async proposeReflectionRule(toolName) {
|
|
71
|
+
async proposeReflectionRule(toolName, trxOrDb = this.db) {
|
|
71
72
|
// Audit Phase 19: Atomic rule proposal via transaction + existence check
|
|
72
|
-
|
|
73
|
+
const runner = async (trx) => {
|
|
73
74
|
const rulesTable = this.cortex.config.rulesTable || 'agent_rules';
|
|
74
|
-
const
|
|
75
|
+
const query = trx
|
|
75
76
|
.selectFrom(rulesTable)
|
|
76
77
|
.select('id')
|
|
77
|
-
.where('
|
|
78
|
+
.where('table_name', '=', 'agent_actions')
|
|
78
79
|
.where('operation', '=', 'insert')
|
|
79
|
-
.where('metadata', 'like', `%\"targetTool\":\"${toolName}\"%`)
|
|
80
|
-
|
|
81
|
-
.executeTakeFirst();
|
|
80
|
+
.where('metadata', 'like', `%\"targetTool\":\"${toolName}\"%`);
|
|
81
|
+
const existing = await withLock(query, trx).executeTakeFirst();
|
|
82
82
|
if (!existing) {
|
|
83
83
|
console.log(`[ActionRefiner] Proposing reflection rule for tool: ${toolName}`);
|
|
84
84
|
await this.cortex.rules.defineRule('agent_actions', 'insert', 'audit', {
|
|
@@ -88,16 +88,22 @@ export class ActionRefiner {
|
|
|
88
88
|
},
|
|
89
89
|
}, trx); // Pass transaction object
|
|
90
90
|
}
|
|
91
|
-
}
|
|
91
|
+
};
|
|
92
|
+
if (trxOrDb && trxOrDb !== this.db) {
|
|
93
|
+
await runner(trxOrDb);
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
await this.db.transaction().execute((trx) => runner(trx));
|
|
97
|
+
}
|
|
92
98
|
}
|
|
93
99
|
/**
|
|
94
100
|
* Propose an update to capabilities
|
|
95
101
|
*/
|
|
96
|
-
async proposeCapabilityUpdate(toolName) {
|
|
102
|
+
async proposeCapabilityUpdate(toolName, trxOrDb = this.db) {
|
|
97
103
|
console.log(`[ActionRefiner] Proposing capability expansion for tool: ${toolName}`);
|
|
98
104
|
await this.cortex.reflections.reflect('system', 'failure', `Architectural Gap: Missing Capability for '${toolName}'`, [
|
|
99
105
|
`Identified repeated failures using tool '${toolName}'.`,
|
|
100
106
|
`Resolution: Inspect permission sets and ensure the tool is correctly registered in the CapabilityManager.`,
|
|
101
|
-
]);
|
|
107
|
+
], undefined, trxOrDb);
|
|
102
108
|
}
|
|
103
109
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
/// <reference types="./ConflictResolver.d.ts" />
|
|
2
2
|
import { calculateSimilarity } from '../../util/similarity.js';
|
|
3
|
+
import { withLock } from '../util/db-utils.js';
|
|
3
4
|
/**
|
|
4
5
|
* ConflictResolver identifies and resolves logical inconsistencies
|
|
5
6
|
* in the agent's cognitive rules and behavior policies.
|
|
@@ -83,14 +84,14 @@ export class ConflictResolver {
|
|
|
83
84
|
async resolveConflict(tableName, operation) {
|
|
84
85
|
console.log(`[ConflictResolver] Resolving conflict for ${tableName}:${operation}`);
|
|
85
86
|
return await this.db.transaction().execute(async (trx) => {
|
|
86
|
-
const
|
|
87
|
+
const query = trx
|
|
87
88
|
.selectFrom(this.rulesTable)
|
|
88
89
|
.selectAll()
|
|
89
90
|
.where('table_name', '=', tableName)
|
|
90
91
|
.where('operation', '=', operation)
|
|
91
92
|
.where('is_enabled', '=', true)
|
|
92
|
-
.orderBy('created_at', 'desc')
|
|
93
|
-
|
|
93
|
+
.orderBy('created_at', 'desc');
|
|
94
|
+
const rules = (await withLock(query, trx) // Audit Phase 10: Atomic resolution lock
|
|
94
95
|
.execute());
|
|
95
96
|
if (rules.length <= 1)
|
|
96
97
|
return;
|
|
@@ -62,7 +62,8 @@ export class EvolutionRitual {
|
|
|
62
62
|
// Find domains that are currently "hot" (high density of recent knowledge)
|
|
63
63
|
// Refactored Phase 13: Paginated scanning to handle large knowledge bursts
|
|
64
64
|
const domainScores = new Map();
|
|
65
|
-
const
|
|
65
|
+
const lookbackHours = this.config.evolutionLookbackHours || 24;
|
|
66
|
+
const cutoff = new Date(Date.now() - lookbackHours * 60 * 60 * 1000);
|
|
66
67
|
let offset = 0;
|
|
67
68
|
const limit = 1000;
|
|
68
69
|
while (true) {
|