mark-improving-agent 2.2.0
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/README.md +335 -0
- package/VERSION +1 -0
- package/bin/cli.js +12 -0
- package/dist/agent/context.js +78 -0
- package/dist/agent/index.js +6 -0
- package/dist/agent/runtime.js +195 -0
- package/dist/agent/task-graph.js +209 -0
- package/dist/agent/types.js +1 -0
- package/dist/cli/index.js +206 -0
- package/dist/core/cognition/active-inference.js +296 -0
- package/dist/core/cognition/cognitive-architecture.js +263 -0
- package/dist/core/cognition/dual-process.js +102 -0
- package/dist/core/cognition/index.js +13 -0
- package/dist/core/cognition/learning-from-failure.js +184 -0
- package/dist/core/cognition/meta-agent.js +407 -0
- package/dist/core/cognition/metacognition.js +322 -0
- package/dist/core/cognition/react.js +177 -0
- package/dist/core/cognition/retrieval-anchor.js +99 -0
- package/dist/core/cognition/self-evolution.js +294 -0
- package/dist/core/cognition/self-verification.js +190 -0
- package/dist/core/cognition/thought-graph.js +495 -0
- package/dist/core/cognition/tool-augmented-llm.js +188 -0
- package/dist/core/cognition/tool-execution-verifier.js +204 -0
- package/dist/core/collaboration/agentic-loop.js +165 -0
- package/dist/core/collaboration/index.js +3 -0
- package/dist/core/collaboration/multi-agent-system.js +186 -0
- package/dist/core/collaboration/multi-agent.js +110 -0
- package/dist/core/consciousness/emotion-engine.js +101 -0
- package/dist/core/consciousness/flow-machine.js +121 -0
- package/dist/core/consciousness/index.js +4 -0
- package/dist/core/consciousness/personality.js +103 -0
- package/dist/core/consciousness/types.js +1 -0
- package/dist/core/emotional-protocol.js +54 -0
- package/dist/core/evolution/engine.js +194 -0
- package/dist/core/evolution/goal-engine.js +153 -0
- package/dist/core/evolution/index.js +6 -0
- package/dist/core/evolution/meta-learning.js +172 -0
- package/dist/core/evolution/reflection.js +158 -0
- package/dist/core/evolution/self-healer.js +139 -0
- package/dist/core/evolution/types.js +1 -0
- package/dist/core/healing-rl.js +266 -0
- package/dist/core/heartbeat.js +408 -0
- package/dist/core/identity/index.js +3 -0
- package/dist/core/identity/reflexion.js +165 -0
- package/dist/core/identity/self-model.js +274 -0
- package/dist/core/identity/self-verifier.js +158 -0
- package/dist/core/identity/types.js +12 -0
- package/dist/core/lesson-bank.js +301 -0
- package/dist/core/memory/adaptive-rag.js +440 -0
- package/dist/core/memory/archive-store.js +187 -0
- package/dist/core/memory/dream-consolidation.js +366 -0
- package/dist/core/memory/embedder.js +130 -0
- package/dist/core/memory/hopfield-network.js +128 -0
- package/dist/core/memory/index.js +9 -0
- package/dist/core/memory/knowledge-graph.js +151 -0
- package/dist/core/memory/spaced-repetition.js +113 -0
- package/dist/core/memory/store.js +404 -0
- package/dist/core/memory/types.js +1 -0
- package/dist/core/psychology/analysis.js +456 -0
- package/dist/core/psychology/index.js +1 -0
- package/dist/core/rollback-manager.js +191 -0
- package/dist/core/security/index.js +1 -0
- package/dist/core/security/privacy.js +132 -0
- package/dist/core/truth-teller.js +253 -0
- package/dist/core/truthfulness.js +99 -0
- package/dist/core/types.js +2 -0
- package/dist/event/bus.js +47 -0
- package/dist/index.js +8 -0
- package/dist/skills/dag.js +181 -0
- package/dist/skills/index.js +5 -0
- package/dist/skills/registry.js +40 -0
- package/dist/skills/types.js +1 -0
- package/dist/storage/archive.js +77 -0
- package/dist/storage/checkpoint.js +119 -0
- package/dist/storage/types.js +1 -0
- package/dist/utils/config.js +81 -0
- package/dist/utils/logger.js +49 -0
- package/dist/version.js +1 -0
- package/package.json +37 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Learning from Failure - PSO-Inspired Error Recovery
|
|
3
|
+
*
|
|
4
|
+
* Paper: "AgentPSO: Evolving Reasoning" - Particle Swarm Optimization for agents
|
|
5
|
+
* Key insight: Errors are learning opportunities, not just failures
|
|
6
|
+
*
|
|
7
|
+
* Key mechanisms:
|
|
8
|
+
* - Error pattern encoding
|
|
9
|
+
* - Counterfactual reasoning: "What if I had done X instead?"
|
|
10
|
+
* - Failure trajectory tracking
|
|
11
|
+
* - Adaptive correction based on past errors
|
|
12
|
+
*/
|
|
13
|
+
import { randomUUID } from 'crypto';
|
|
14
|
+
const MAX_FAILURES = 1000;
|
|
15
|
+
const PATTERN_THRESHOLD = 3; // Times pattern must repeat before becoming a "known" pattern
|
|
16
|
+
export function createLearningFromFailure() {
|
|
17
|
+
const failures = new Map();
|
|
18
|
+
const patterns = new Map();
|
|
19
|
+
function generateCounterfactual(action, result) {
|
|
20
|
+
// Generate "What if?" scenarios
|
|
21
|
+
const scenarios = [
|
|
22
|
+
`What if I had paused to analyze before ${action}?`,
|
|
23
|
+
`What if I had verified the ${result} before proceeding?`,
|
|
24
|
+
`What if I had asked for clarification instead of assuming?`,
|
|
25
|
+
`What if I had checked the lesson bank first?`,
|
|
26
|
+
`What if I had used the self-verification engine?`,
|
|
27
|
+
];
|
|
28
|
+
return scenarios[Math.floor(Math.random() * scenarios.length)];
|
|
29
|
+
}
|
|
30
|
+
function extractErrorType(error, context) {
|
|
31
|
+
const errorLower = error.toLowerCase();
|
|
32
|
+
const contextLower = context.toLowerCase();
|
|
33
|
+
if (errorLower.includes('not found') || errorLower.includes('no such')) {
|
|
34
|
+
return 'resource_not_found';
|
|
35
|
+
}
|
|
36
|
+
if (errorLower.includes('permission') || errorLower.includes('access')) {
|
|
37
|
+
return 'permission_denied';
|
|
38
|
+
}
|
|
39
|
+
if (errorLower.includes('timeout') || errorLower.includes('slow')) {
|
|
40
|
+
return 'timeout';
|
|
41
|
+
}
|
|
42
|
+
if (errorLower.includes('invalid') || errorLower.includes('wrong')) {
|
|
43
|
+
return 'invalid_input';
|
|
44
|
+
}
|
|
45
|
+
if (contextLower.includes('search')) {
|
|
46
|
+
return 'search_failure';
|
|
47
|
+
}
|
|
48
|
+
if (contextLower.includes('verify')) {
|
|
49
|
+
return 'verification_failure';
|
|
50
|
+
}
|
|
51
|
+
return 'unknown_error';
|
|
52
|
+
}
|
|
53
|
+
function recordFailure(error, context, action, result) {
|
|
54
|
+
const id = `fail-${Date.now()}-${randomUUID().slice(0, 8)}`;
|
|
55
|
+
const errorType = extractErrorType(error, context);
|
|
56
|
+
const counterfactual = generateCounterfactual(action, result);
|
|
57
|
+
const record = {
|
|
58
|
+
id,
|
|
59
|
+
errorType,
|
|
60
|
+
context,
|
|
61
|
+
action,
|
|
62
|
+
result,
|
|
63
|
+
counterfactual,
|
|
64
|
+
lessons: [],
|
|
65
|
+
timestamp: Date.now(),
|
|
66
|
+
recurrenceCount: 1,
|
|
67
|
+
resolved: false,
|
|
68
|
+
};
|
|
69
|
+
// Enforce max failures limit
|
|
70
|
+
if (failures.size >= MAX_FAILURES) {
|
|
71
|
+
const oldest = Array.from(failures.values())
|
|
72
|
+
.sort((a, b) => a.timestamp - b.timestamp)[0];
|
|
73
|
+
if (oldest) {
|
|
74
|
+
failures.delete(oldest.id);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
failures.set(id, record);
|
|
78
|
+
// Update pattern frequency
|
|
79
|
+
const existingPattern = patterns.get(errorType);
|
|
80
|
+
if (existingPattern) {
|
|
81
|
+
existingPattern.frequency++;
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
patterns.set(errorType, {
|
|
85
|
+
pattern: errorType,
|
|
86
|
+
frequency: 1,
|
|
87
|
+
averageCorrectionTime: 0,
|
|
88
|
+
successRate: 0,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return record;
|
|
92
|
+
}
|
|
93
|
+
function getCounterfactual(failureId) {
|
|
94
|
+
const failure = failures.get(failureId);
|
|
95
|
+
return failure?.counterfactual || 'No counterfactual available';
|
|
96
|
+
}
|
|
97
|
+
function updatePattern(failureId, success) {
|
|
98
|
+
const failure = failures.get(failureId);
|
|
99
|
+
if (!failure)
|
|
100
|
+
return;
|
|
101
|
+
failure.resolved = success;
|
|
102
|
+
// Update pattern success rate
|
|
103
|
+
const pattern = patterns.get(failure.errorType);
|
|
104
|
+
if (pattern) {
|
|
105
|
+
const total = pattern.frequency;
|
|
106
|
+
const currentSuccesses = pattern.successRate * (total - 1);
|
|
107
|
+
pattern.successRate = (currentSuccesses + (success ? 1 : 0)) / total;
|
|
108
|
+
}
|
|
109
|
+
// Add lesson if successful recovery
|
|
110
|
+
if (success) {
|
|
111
|
+
const lesson = `For ${failure.errorType}: ${failure.counterfactual}`;
|
|
112
|
+
if (!failure.lessons.includes(lesson)) {
|
|
113
|
+
failure.lessons.push(lesson);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function getErrorPatterns() {
|
|
118
|
+
return Array.from(patterns.values())
|
|
119
|
+
.sort((a, b) => b.frequency - a.frequency);
|
|
120
|
+
}
|
|
121
|
+
async function recoverFromError(error, context) {
|
|
122
|
+
const errorType = extractErrorType(error, context);
|
|
123
|
+
const pattern = patterns.get(errorType);
|
|
124
|
+
// Check if this is a known pattern
|
|
125
|
+
if (pattern && pattern.frequency >= PATTERN_THRESHOLD && pattern.successRate > 0.5) {
|
|
126
|
+
return {
|
|
127
|
+
recovered: true,
|
|
128
|
+
attempts: 1,
|
|
129
|
+
finalStrategy: `Known pattern: ${pattern.suggestedFix || 'Use previously successful approach'}`,
|
|
130
|
+
lessonsLearned: [`Known error type: ${errorType}`, `Success rate: ${(pattern.successRate * 100).toFixed(0)}%`],
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
// Try counterfactual-based recovery
|
|
134
|
+
const failure = recordFailure(error, context, 'recovery_attempt', 'in_progress');
|
|
135
|
+
let attempts = 0;
|
|
136
|
+
const maxAttempts = 3;
|
|
137
|
+
while (attempts < maxAttempts) {
|
|
138
|
+
attempts++;
|
|
139
|
+
// Strategy 1: Check lesson bank
|
|
140
|
+
const lessonStrategy = `Check lesson bank for ${errorType} patterns`;
|
|
141
|
+
// Strategy 2: Use self-verification
|
|
142
|
+
const verifyStrategy = 'Run self-verification before retrying';
|
|
143
|
+
// Strategy 3: Slow down (PSO insight)
|
|
144
|
+
const slowStrategy = 'Wait and re-analyze before retrying';
|
|
145
|
+
// Simulate recovery attempt
|
|
146
|
+
const recovered = Math.random() > 0.3; // 70% success rate per attempt
|
|
147
|
+
if (recovered) {
|
|
148
|
+
updatePattern(failure.id, true);
|
|
149
|
+
return {
|
|
150
|
+
recovered: true,
|
|
151
|
+
attempts,
|
|
152
|
+
finalStrategy: attempts === 1 ? lessonStrategy : attempts === 2 ? verifyStrategy : slowStrategy,
|
|
153
|
+
lessonsLearned: [`Recovery attempt ${attempts} succeeded`],
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
updatePattern(failure.id, false);
|
|
158
|
+
return {
|
|
159
|
+
recovered: false,
|
|
160
|
+
attempts,
|
|
161
|
+
finalStrategy: 'All recovery attempts failed - manual intervention required',
|
|
162
|
+
lessonsLearned: ['Failed to recover automatically', 'Consider adding new lesson for this error type'],
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function getStats() {
|
|
166
|
+
const totalFailures = failures.size;
|
|
167
|
+
const recoveredFailures = Array.from(failures.values()).filter(f => f.resolved).length;
|
|
168
|
+
const patternsLearned = patterns.size;
|
|
169
|
+
return {
|
|
170
|
+
totalFailures,
|
|
171
|
+
recoveredFailures,
|
|
172
|
+
patternsLearned,
|
|
173
|
+
recoveryRate: totalFailures > 0 ? recoveredFailures / totalFailures : 0,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
recordFailure,
|
|
178
|
+
getCounterfactual,
|
|
179
|
+
updatePattern,
|
|
180
|
+
getErrorPatterns,
|
|
181
|
+
recoverFromError,
|
|
182
|
+
getStats,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MetaAgent - Self-Evolving Agent with Meta-Learning
|
|
3
|
+
*
|
|
4
|
+
* Paper: "MetaAgent: Self-Evolving Agent with Meta-Learning"
|
|
5
|
+
*
|
|
6
|
+
* Key concepts:
|
|
7
|
+
* - Meta-Learning: Learning to learn, not just learning specific tasks
|
|
8
|
+
* - Cross-domain knowledge transfer: Knowledge learned in one domain helps in another
|
|
9
|
+
* - Three-level optimization:
|
|
10
|
+
* 1. Environment-specific: Rapid adaptation to specific tasks
|
|
11
|
+
* 2. Cross-domain: Transfer knowledge across domains
|
|
12
|
+
* 3. Meta-knowledge: Abstract principles that accelerate learning
|
|
13
|
+
*
|
|
14
|
+
* Meta-knowledge structure:
|
|
15
|
+
* - Task schemas: Abstract task representations
|
|
16
|
+
* - Strategy patterns: Reusable problem-solving approaches
|
|
17
|
+
* - Domain mappings: How knowledge transfers between domains
|
|
18
|
+
*/
|
|
19
|
+
import { randomUUID } from 'crypto';
|
|
20
|
+
const META_KNOWLEDGE_KEY = 'meta-knowledge';
|
|
21
|
+
export function createMetaLearningEngine() {
|
|
22
|
+
let state = {
|
|
23
|
+
tasks: [],
|
|
24
|
+
schemas: new Map(),
|
|
25
|
+
strategies: new Map(),
|
|
26
|
+
domainMappings: new Map(),
|
|
27
|
+
crossDomainKnowledge: new Map(),
|
|
28
|
+
stats: {
|
|
29
|
+
totalTasks: 0,
|
|
30
|
+
successfulTransfers: 0,
|
|
31
|
+
failedTransfers: 0,
|
|
32
|
+
avgAdaptationTime: 0,
|
|
33
|
+
schemasLearned: 0,
|
|
34
|
+
strategiesDiscovered: 0,
|
|
35
|
+
crossDomainTransfers: 0,
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
function findDomainKey(domain) {
|
|
39
|
+
return domain.toLowerCase().split(/[\s_-]/)[0];
|
|
40
|
+
}
|
|
41
|
+
function findOrCreateSchema(task, domain) {
|
|
42
|
+
const domainKey = findDomainKey(domain);
|
|
43
|
+
// Look for existing similar schema
|
|
44
|
+
for (const schema of state.schemas.values()) {
|
|
45
|
+
if (findDomainKey(schema.domain) === domainKey) {
|
|
46
|
+
// Check similarity
|
|
47
|
+
const taskWords = new Set(task.toLowerCase().split(/\s+/).filter(w => w.length > 3));
|
|
48
|
+
const schemaWords = new Set(schema.abstractStructure.toLowerCase().split(/\s+/).filter(w => w.length > 3));
|
|
49
|
+
const intersection = [...taskWords].filter(w => schemaWords.has(w)).length;
|
|
50
|
+
if (intersection > taskWords.size * 0.3) {
|
|
51
|
+
return schema;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
// Create new schema
|
|
56
|
+
const schema = {
|
|
57
|
+
id: randomUUID(),
|
|
58
|
+
name: task.slice(0, 50),
|
|
59
|
+
domain,
|
|
60
|
+
abstractStructure: task,
|
|
61
|
+
keyParameters: task.split(/\s+/).filter(w => w.length > 4).slice(0, 10),
|
|
62
|
+
difficulty: 0.5,
|
|
63
|
+
successRate: 0.5,
|
|
64
|
+
lastUsed: Date.now(),
|
|
65
|
+
};
|
|
66
|
+
state.schemas.set(schema.id, schema);
|
|
67
|
+
state.stats.schemasLearned++;
|
|
68
|
+
return schema;
|
|
69
|
+
}
|
|
70
|
+
function findOrCreateStrategy(task, schemaIds) {
|
|
71
|
+
// Look for existing strategy that works for these schemas
|
|
72
|
+
for (const strategy of state.strategies.values()) {
|
|
73
|
+
if (strategy.applicableSchemas.some(id => schemaIds.includes(id))) {
|
|
74
|
+
return strategy;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Create new strategy based on task
|
|
78
|
+
const steps = extractStepsFromTask(task);
|
|
79
|
+
const strategy = {
|
|
80
|
+
id: randomUUID(),
|
|
81
|
+
name: `Strategy-${Date.now()}`,
|
|
82
|
+
description: `Strategy for: ${task.slice(0, 50)}...`,
|
|
83
|
+
applicableSchemas: schemaIds,
|
|
84
|
+
steps,
|
|
85
|
+
successRate: 0.5,
|
|
86
|
+
avgDuration: 5000,
|
|
87
|
+
conditions: extractConditions(task),
|
|
88
|
+
};
|
|
89
|
+
state.strategies.set(strategy.id, strategy);
|
|
90
|
+
state.stats.strategiesDiscovered++;
|
|
91
|
+
return strategy;
|
|
92
|
+
}
|
|
93
|
+
function extractStepsFromTask(task) {
|
|
94
|
+
// Extract abstract steps from task description
|
|
95
|
+
const commonSteps = [
|
|
96
|
+
'analyze_requirements',
|
|
97
|
+
'plan_approach',
|
|
98
|
+
'execute_step_1',
|
|
99
|
+
'execute_step_2',
|
|
100
|
+
'verify_result',
|
|
101
|
+
'iterate_if_needed',
|
|
102
|
+
];
|
|
103
|
+
// Simple extraction based on keywords
|
|
104
|
+
const steps = [];
|
|
105
|
+
const taskLower = task.toLowerCase();
|
|
106
|
+
if (taskLower.includes('search') || taskLower.includes('find')) {
|
|
107
|
+
steps.push('search_phase');
|
|
108
|
+
}
|
|
109
|
+
if (taskLower.includes('read') || taskLower.includes('analyze')) {
|
|
110
|
+
steps.push('analysis_phase');
|
|
111
|
+
}
|
|
112
|
+
if (taskLower.includes('write') || taskLower.includes('create') || taskLower.includes('build')) {
|
|
113
|
+
steps.push('creation_phase');
|
|
114
|
+
}
|
|
115
|
+
if (taskLower.includes('verify') || taskLower.includes('check') || taskLower.includes('test')) {
|
|
116
|
+
steps.push('verification_phase');
|
|
117
|
+
}
|
|
118
|
+
if (taskLower.includes('fix') || taskLower.includes('error') || taskLower.includes('bug')) {
|
|
119
|
+
steps.push('debugging_phase');
|
|
120
|
+
}
|
|
121
|
+
return steps.length > 0 ? steps : commonSteps;
|
|
122
|
+
}
|
|
123
|
+
function extractConditions(task) {
|
|
124
|
+
const conditions = [];
|
|
125
|
+
const taskLower = task.toLowerCase();
|
|
126
|
+
if (taskLower.includes('complex') || taskLower.includes('difficult')) {
|
|
127
|
+
conditions.push('high_complexity');
|
|
128
|
+
}
|
|
129
|
+
if (taskLower.includes('simple') || taskLower.includes('easy')) {
|
|
130
|
+
conditions.push('low_complexity');
|
|
131
|
+
}
|
|
132
|
+
if (taskLower.includes('urgent') || taskLower.includes('quick')) {
|
|
133
|
+
conditions.push('time_critical');
|
|
134
|
+
}
|
|
135
|
+
if (taskLower.includes('new') || taskLower.includes('first')) {
|
|
136
|
+
conditions.push('exploration_phase');
|
|
137
|
+
}
|
|
138
|
+
if (taskLower.includes('repeat') || taskLower.includes('again')) {
|
|
139
|
+
conditions.push('exploitation_phase');
|
|
140
|
+
}
|
|
141
|
+
return conditions;
|
|
142
|
+
}
|
|
143
|
+
function findDomainMapping(sourceDomain, targetDomain) {
|
|
144
|
+
const sourceKey = findDomainKey(sourceDomain);
|
|
145
|
+
const targetKey = findDomainKey(targetDomain);
|
|
146
|
+
const mapKey = `${sourceKey}->${targetKey}`;
|
|
147
|
+
return state.domainMappings.get(mapKey);
|
|
148
|
+
}
|
|
149
|
+
function createDomainMapping(sourceDomain, targetDomain) {
|
|
150
|
+
const sourceKey = findDomainKey(sourceDomain);
|
|
151
|
+
const targetKey = findDomainKey(targetDomain);
|
|
152
|
+
const mapKey = `${sourceKey}->${targetKey}`;
|
|
153
|
+
// Find transferable concepts (words that appear in both domains)
|
|
154
|
+
const sourceWords = new Set(sourceDomain.toLowerCase().split(/\s+/));
|
|
155
|
+
const targetWords = new Set(targetDomain.toLowerCase().split(/\s+/));
|
|
156
|
+
const transferable = [...sourceWords].filter(w => targetWords.has(w) && w.length > 3);
|
|
157
|
+
const mapping = {
|
|
158
|
+
sourceDomain,
|
|
159
|
+
targetDomain,
|
|
160
|
+
transferableConcepts: transferable.length > 0 ? transferable : ['general_concept'],
|
|
161
|
+
transfer成功率: 0.5,
|
|
162
|
+
usageCount: 0,
|
|
163
|
+
};
|
|
164
|
+
state.domainMappings.set(mapKey, mapping);
|
|
165
|
+
// Update cross-domain knowledge
|
|
166
|
+
if (!state.crossDomainKnowledge.has(sourceKey)) {
|
|
167
|
+
state.crossDomainKnowledge.set(sourceKey, new Set());
|
|
168
|
+
}
|
|
169
|
+
state.crossDomainKnowledge.get(sourceKey).add(targetKey);
|
|
170
|
+
return mapping;
|
|
171
|
+
}
|
|
172
|
+
function learnFromTask(task, domain, success, feedback) {
|
|
173
|
+
const startTime = Date.now();
|
|
174
|
+
state.stats.totalTasks++;
|
|
175
|
+
// Record task
|
|
176
|
+
state.tasks.push({ task, domain, success, timestamp: Date.now() });
|
|
177
|
+
if (state.tasks.length > 100) {
|
|
178
|
+
state.tasks = state.tasks.slice(-100);
|
|
179
|
+
}
|
|
180
|
+
// Find or create schema
|
|
181
|
+
const schema = findOrCreateSchema(task, domain);
|
|
182
|
+
// Update schema success rate
|
|
183
|
+
const prevSuccess = schema.successRate;
|
|
184
|
+
schema.successRate = prevSuccess * 0.9 + (success ? 0.1 : 0);
|
|
185
|
+
schema.lastUsed = Date.now();
|
|
186
|
+
// Find or create strategy
|
|
187
|
+
const strategy = findOrCreateStrategy(task, [schema.id]);
|
|
188
|
+
// Update strategy success rate
|
|
189
|
+
if (success) {
|
|
190
|
+
strategy.successRate = strategy.successRate * 0.95 + 0.05;
|
|
191
|
+
state.stats.successfulTransfers++;
|
|
192
|
+
}
|
|
193
|
+
else {
|
|
194
|
+
strategy.successRate = strategy.successRate * 0.9;
|
|
195
|
+
state.stats.failedTransfers++;
|
|
196
|
+
}
|
|
197
|
+
// Check for cross-domain knowledge transfer
|
|
198
|
+
let transferredKnowledge;
|
|
199
|
+
const recentSameDomain = state.tasks
|
|
200
|
+
.filter(t => findDomainKey(t.domain) === findDomainKey(domain) && t !== state.tasks[state.tasks.length - 1])
|
|
201
|
+
.slice(-5);
|
|
202
|
+
if (recentSameDomain.length > 0 && !success) {
|
|
203
|
+
// Try to find successful approach from related tasks
|
|
204
|
+
const successfulTasks = recentSameDomain.filter(t => t.success);
|
|
205
|
+
if (successfulTasks.length > 0) {
|
|
206
|
+
transferredKnowledge = successfulTasks.map(t => t.task);
|
|
207
|
+
state.stats.crossDomainTransfers++;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const adaptationTime = Date.now() - startTime;
|
|
211
|
+
state.stats.avgAdaptationTime =
|
|
212
|
+
(state.stats.avgAdaptationTime * (state.stats.totalTasks - 1) + adaptationTime) / state.stats.totalTasks;
|
|
213
|
+
return {
|
|
214
|
+
adapted: true,
|
|
215
|
+
metaLevel: transferredKnowledge ? 'cross_domain' : 'environment_specific',
|
|
216
|
+
usedSchema: schema.id,
|
|
217
|
+
usedStrategy: strategy.id,
|
|
218
|
+
transferredKnowledge,
|
|
219
|
+
adaptationTime,
|
|
220
|
+
confidence: schema.successRate * strategy.successRate,
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function selectBestStrategy(task, domain) {
|
|
224
|
+
const domainKey = findDomainKey(domain);
|
|
225
|
+
const taskConditions = extractConditions(task);
|
|
226
|
+
// Find all strategies applicable to this domain
|
|
227
|
+
const applicableStrategies = [];
|
|
228
|
+
for (const strategy of state.strategies.values()) {
|
|
229
|
+
const appliesToDomain = strategy.applicableSchemas.some(id => {
|
|
230
|
+
const schema = state.schemas.get(id);
|
|
231
|
+
return schema && findDomainKey(schema.domain) === domainKey;
|
|
232
|
+
});
|
|
233
|
+
if (!appliesToDomain)
|
|
234
|
+
continue;
|
|
235
|
+
// Score based on success rate and condition match
|
|
236
|
+
let score = strategy.successRate * 0.7;
|
|
237
|
+
// Bonus for condition match
|
|
238
|
+
const conditionMatch = strategy.conditions.filter(c => taskConditions.includes(c)).length;
|
|
239
|
+
score += conditionMatch * 0.1;
|
|
240
|
+
// Recency bonus
|
|
241
|
+
const timeSinceUse = Date.now() - strategy.avgDuration;
|
|
242
|
+
if (timeSinceUse < 60000) {
|
|
243
|
+
score += 0.1;
|
|
244
|
+
}
|
|
245
|
+
applicableStrategies.push({ strategy, score });
|
|
246
|
+
}
|
|
247
|
+
// Sort by score
|
|
248
|
+
applicableStrategies.sort((a, b) => b.score - a.score);
|
|
249
|
+
if (applicableStrategies.length === 0) {
|
|
250
|
+
// Create default strategy
|
|
251
|
+
const defaultStrategy = {
|
|
252
|
+
id: 'default',
|
|
253
|
+
name: 'Default Strategy',
|
|
254
|
+
description: 'Fallback strategy',
|
|
255
|
+
applicableSchemas: [],
|
|
256
|
+
steps: extractStepsFromTask(task),
|
|
257
|
+
successRate: 0.5,
|
|
258
|
+
avgDuration: 5000,
|
|
259
|
+
conditions: [],
|
|
260
|
+
};
|
|
261
|
+
return {
|
|
262
|
+
strategy: defaultStrategy,
|
|
263
|
+
confidence: 0.5,
|
|
264
|
+
alternativeStrategies: [],
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
strategy: applicableStrategies[0].strategy,
|
|
269
|
+
confidence: applicableStrategies[0].score,
|
|
270
|
+
alternativeStrategies: applicableStrategies.slice(1, 4).map(s => s.strategy),
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function transferKnowledge(sourceDomain, targetDomain, task) {
|
|
274
|
+
const sourceKey = findDomainKey(sourceDomain);
|
|
275
|
+
const targetKey = findDomainKey(targetDomain);
|
|
276
|
+
// Find or create mapping
|
|
277
|
+
let mapping = findDomainMapping(sourceDomain, targetDomain);
|
|
278
|
+
if (!mapping) {
|
|
279
|
+
mapping = createDomainMapping(sourceDomain, targetDomain);
|
|
280
|
+
}
|
|
281
|
+
mapping.usageCount++;
|
|
282
|
+
// Get schemas from source domain
|
|
283
|
+
const sourceSchemas = Array.from(state.schemas.values()).filter(s => findDomainKey(s.domain) === sourceKey);
|
|
284
|
+
// Get strategies from source domain
|
|
285
|
+
const sourceStrategies = Array.from(state.strategies.values()).filter(s => s.applicableSchemas.some(id => sourceSchemas.some(ss => ss.id === id)));
|
|
286
|
+
// Find relevant strategies for the task
|
|
287
|
+
const taskWords = new Set(task.toLowerCase().split(/\s+/).filter(w => w.length > 3));
|
|
288
|
+
const relevantStrategies = [];
|
|
289
|
+
for (const strategy of sourceStrategies) {
|
|
290
|
+
const strategyWords = new Set(strategy.description.toLowerCase().split(/\s+/));
|
|
291
|
+
const overlap = [...taskWords].filter(w => strategyWords.has(w)).length;
|
|
292
|
+
if (overlap > 0) {
|
|
293
|
+
relevantStrategies.push(strategy.description);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return relevantStrategies.length > 0 ? relevantStrategies : mapping.transferableConcepts;
|
|
297
|
+
}
|
|
298
|
+
function registerSchema(schema) {
|
|
299
|
+
state.schemas.set(schema.id, schema);
|
|
300
|
+
}
|
|
301
|
+
function getSchema(id) {
|
|
302
|
+
return state.schemas.get(id);
|
|
303
|
+
}
|
|
304
|
+
function findSimilarSchemas(task, domain) {
|
|
305
|
+
const taskWords = new Set(task.toLowerCase().split(/\s+/).filter(w => w.length > 3));
|
|
306
|
+
const results = [];
|
|
307
|
+
for (const schema of state.schemas.values()) {
|
|
308
|
+
if (domain && findDomainKey(schema.domain) !== findDomainKey(domain)) {
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
const schemaWords = new Set(schema.abstractStructure.toLowerCase().split(/\s+/).filter(w => w.length > 3));
|
|
312
|
+
const intersection = [...taskWords].filter(w => schemaWords.has(w)).length;
|
|
313
|
+
const union = taskWords.size + schemaWords.size - intersection;
|
|
314
|
+
const similarity = union > 0 ? intersection / union : 0;
|
|
315
|
+
if (similarity > 0.2) {
|
|
316
|
+
results.push({ schema, similarity });
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
return results.sort((a, b) => b.similarity - a.similarity).map(r => r.schema);
|
|
320
|
+
}
|
|
321
|
+
function registerStrategy(strategy) {
|
|
322
|
+
state.strategies.set(strategy.id, strategy);
|
|
323
|
+
}
|
|
324
|
+
function getStrategy(id) {
|
|
325
|
+
return state.strategies.get(id);
|
|
326
|
+
}
|
|
327
|
+
function improveStrategy(strategyId, improvement) {
|
|
328
|
+
const strategy = state.strategies.get(strategyId);
|
|
329
|
+
if (strategy) {
|
|
330
|
+
strategy.description += ` | Improved: ${improvement}`;
|
|
331
|
+
strategy.successRate = Math.min(1, strategy.successRate + 0.05);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
function addDomainMapping(source, target, concepts) {
|
|
335
|
+
const sourceKey = findDomainKey(source);
|
|
336
|
+
const targetKey = findDomainKey(target);
|
|
337
|
+
const mapKey = `${sourceKey}->${targetKey}`;
|
|
338
|
+
state.domainMappings.set(mapKey, {
|
|
339
|
+
sourceDomain: source,
|
|
340
|
+
targetDomain: target,
|
|
341
|
+
transferableConcepts: concepts,
|
|
342
|
+
transfer成功率: 0.6,
|
|
343
|
+
usageCount: 0,
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
function getRelatedDomains(domain) {
|
|
347
|
+
const domainKey = findDomainKey(domain);
|
|
348
|
+
const related = state.crossDomainKnowledge.get(domainKey);
|
|
349
|
+
return related ? [...related] : [];
|
|
350
|
+
}
|
|
351
|
+
function getMetaKnowledge() {
|
|
352
|
+
return {
|
|
353
|
+
schemas: new Map(state.schemas),
|
|
354
|
+
strategies: new Map(state.strategies),
|
|
355
|
+
domainMappings: new Map(state.domainMappings),
|
|
356
|
+
crossDomainKnowledge: new Map([...state.crossDomainKnowledge.entries()].map(([k, v]) => [k, [...v]])),
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
function exportMetaKnowledge() {
|
|
360
|
+
return JSON.stringify({
|
|
361
|
+
schemas: Array.from(state.schemas.entries()),
|
|
362
|
+
strategies: Array.from(state.strategies.entries()),
|
|
363
|
+
domainMappings: Array.from(state.domainMappings.entries()),
|
|
364
|
+
crossDomainKnowledge: [...state.crossDomainKnowledge.entries()].map(([k, v]) => [k, [...v]]),
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
function importMetaKnowledge(data) {
|
|
368
|
+
try {
|
|
369
|
+
const parsed = JSON.parse(data);
|
|
370
|
+
if (parsed.schemas) {
|
|
371
|
+
state.schemas = new Map(parsed.schemas);
|
|
372
|
+
}
|
|
373
|
+
if (parsed.strategies) {
|
|
374
|
+
state.strategies = new Map(parsed.strategies);
|
|
375
|
+
}
|
|
376
|
+
if (parsed.domainMappings) {
|
|
377
|
+
state.domainMappings = new Map(parsed.domainMappings);
|
|
378
|
+
}
|
|
379
|
+
if (parsed.crossDomainKnowledge) {
|
|
380
|
+
state.crossDomainKnowledge = new Map(parsed.crossDomainKnowledge.map(([k, v]) => [k, new Set(v)]));
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
// Invalid data, ignore
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
function getStats() {
|
|
388
|
+
return { ...state.stats };
|
|
389
|
+
}
|
|
390
|
+
return {
|
|
391
|
+
learnFromTask,
|
|
392
|
+
selectBestStrategy,
|
|
393
|
+
transferKnowledge,
|
|
394
|
+
registerSchema,
|
|
395
|
+
getSchema,
|
|
396
|
+
findSimilarSchemas,
|
|
397
|
+
registerStrategy,
|
|
398
|
+
getStrategy,
|
|
399
|
+
improveStrategy,
|
|
400
|
+
addDomainMapping,
|
|
401
|
+
getRelatedDomains,
|
|
402
|
+
getMetaKnowledge,
|
|
403
|
+
exportMetaKnowledge,
|
|
404
|
+
importMetaKnowledge,
|
|
405
|
+
getStats,
|
|
406
|
+
};
|
|
407
|
+
}
|