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.
Files changed (79) hide show
  1. package/README.md +335 -0
  2. package/VERSION +1 -0
  3. package/bin/cli.js +12 -0
  4. package/dist/agent/context.js +78 -0
  5. package/dist/agent/index.js +6 -0
  6. package/dist/agent/runtime.js +195 -0
  7. package/dist/agent/task-graph.js +209 -0
  8. package/dist/agent/types.js +1 -0
  9. package/dist/cli/index.js +206 -0
  10. package/dist/core/cognition/active-inference.js +296 -0
  11. package/dist/core/cognition/cognitive-architecture.js +263 -0
  12. package/dist/core/cognition/dual-process.js +102 -0
  13. package/dist/core/cognition/index.js +13 -0
  14. package/dist/core/cognition/learning-from-failure.js +184 -0
  15. package/dist/core/cognition/meta-agent.js +407 -0
  16. package/dist/core/cognition/metacognition.js +322 -0
  17. package/dist/core/cognition/react.js +177 -0
  18. package/dist/core/cognition/retrieval-anchor.js +99 -0
  19. package/dist/core/cognition/self-evolution.js +294 -0
  20. package/dist/core/cognition/self-verification.js +190 -0
  21. package/dist/core/cognition/thought-graph.js +495 -0
  22. package/dist/core/cognition/tool-augmented-llm.js +188 -0
  23. package/dist/core/cognition/tool-execution-verifier.js +204 -0
  24. package/dist/core/collaboration/agentic-loop.js +165 -0
  25. package/dist/core/collaboration/index.js +3 -0
  26. package/dist/core/collaboration/multi-agent-system.js +186 -0
  27. package/dist/core/collaboration/multi-agent.js +110 -0
  28. package/dist/core/consciousness/emotion-engine.js +101 -0
  29. package/dist/core/consciousness/flow-machine.js +121 -0
  30. package/dist/core/consciousness/index.js +4 -0
  31. package/dist/core/consciousness/personality.js +103 -0
  32. package/dist/core/consciousness/types.js +1 -0
  33. package/dist/core/emotional-protocol.js +54 -0
  34. package/dist/core/evolution/engine.js +194 -0
  35. package/dist/core/evolution/goal-engine.js +153 -0
  36. package/dist/core/evolution/index.js +6 -0
  37. package/dist/core/evolution/meta-learning.js +172 -0
  38. package/dist/core/evolution/reflection.js +158 -0
  39. package/dist/core/evolution/self-healer.js +139 -0
  40. package/dist/core/evolution/types.js +1 -0
  41. package/dist/core/healing-rl.js +266 -0
  42. package/dist/core/heartbeat.js +408 -0
  43. package/dist/core/identity/index.js +3 -0
  44. package/dist/core/identity/reflexion.js +165 -0
  45. package/dist/core/identity/self-model.js +274 -0
  46. package/dist/core/identity/self-verifier.js +158 -0
  47. package/dist/core/identity/types.js +12 -0
  48. package/dist/core/lesson-bank.js +301 -0
  49. package/dist/core/memory/adaptive-rag.js +440 -0
  50. package/dist/core/memory/archive-store.js +187 -0
  51. package/dist/core/memory/dream-consolidation.js +366 -0
  52. package/dist/core/memory/embedder.js +130 -0
  53. package/dist/core/memory/hopfield-network.js +128 -0
  54. package/dist/core/memory/index.js +9 -0
  55. package/dist/core/memory/knowledge-graph.js +151 -0
  56. package/dist/core/memory/spaced-repetition.js +113 -0
  57. package/dist/core/memory/store.js +404 -0
  58. package/dist/core/memory/types.js +1 -0
  59. package/dist/core/psychology/analysis.js +456 -0
  60. package/dist/core/psychology/index.js +1 -0
  61. package/dist/core/rollback-manager.js +191 -0
  62. package/dist/core/security/index.js +1 -0
  63. package/dist/core/security/privacy.js +132 -0
  64. package/dist/core/truth-teller.js +253 -0
  65. package/dist/core/truthfulness.js +99 -0
  66. package/dist/core/types.js +2 -0
  67. package/dist/event/bus.js +47 -0
  68. package/dist/index.js +8 -0
  69. package/dist/skills/dag.js +181 -0
  70. package/dist/skills/index.js +5 -0
  71. package/dist/skills/registry.js +40 -0
  72. package/dist/skills/types.js +1 -0
  73. package/dist/storage/archive.js +77 -0
  74. package/dist/storage/checkpoint.js +119 -0
  75. package/dist/storage/types.js +1 -0
  76. package/dist/utils/config.js +81 -0
  77. package/dist/utils/logger.js +49 -0
  78. package/dist/version.js +1 -0
  79. package/package.json +37 -0
@@ -0,0 +1,101 @@
1
+ import { atomicWriteJSON, readJSON } from '../../storage/archive.js';
2
+ const MAX_HISTORY = 50;
3
+ const DECAY_RATE = 0.05;
4
+ const DECAY_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
5
+ function mapValenceToEmotion(valence) {
6
+ if (valence > 0) {
7
+ const positiveEmotions = ['joy', 'trust', 'anticipation'];
8
+ const idx = Math.abs(Math.floor(valence * positiveEmotions.length)) % positiveEmotions.length;
9
+ return positiveEmotions[idx];
10
+ }
11
+ else {
12
+ const negativeEmotions = ['sadness', 'anger', 'fear', 'disgust', 'surprise'];
13
+ const idx = Math.abs(Math.floor(valence * negativeEmotions.length)) % negativeEmotions.length;
14
+ return negativeEmotions[idx];
15
+ }
16
+ }
17
+ export function createEmotionEngine(dataDir) {
18
+ let currentEmotion = {
19
+ primary: 'trust',
20
+ intensity: 0.5,
21
+ valence: 0.0,
22
+ arousal: 0.5,
23
+ timestamp: Date.now(),
24
+ };
25
+ let history = [];
26
+ let lastStimulusTime = Date.now();
27
+ let isDirty = false;
28
+ const emotionsPath = `${dataDir}/emotions.json`;
29
+ function applyDecay(state) {
30
+ const elapsed = Date.now() - lastStimulusTime;
31
+ const decayIntervals = Math.floor(elapsed / DECAY_INTERVAL_MS);
32
+ const decayFactor = Math.pow(1 - DECAY_RATE, decayIntervals);
33
+ return {
34
+ ...state,
35
+ intensity: Math.max(0, state.intensity * decayFactor),
36
+ };
37
+ }
38
+ return {
39
+ getCurrentEmotion() {
40
+ const decayed = applyDecay(currentEmotion);
41
+ if (decayed.intensity !== currentEmotion.intensity) {
42
+ currentEmotion = decayed;
43
+ }
44
+ return { ...currentEmotion };
45
+ },
46
+ processStimulus(valence, arousal) {
47
+ const clampedValence = Math.max(-1, Math.min(1, valence));
48
+ const clampedArousal = Math.max(0, Math.min(1, arousal));
49
+ const primary = mapValenceToEmotion(clampedValence);
50
+ const intensity = Math.abs(clampedValence) * clampedArousal;
51
+ currentEmotion = {
52
+ primary,
53
+ intensity,
54
+ valence: clampedValence,
55
+ arousal: clampedArousal,
56
+ timestamp: Date.now(),
57
+ };
58
+ lastStimulusTime = Date.now();
59
+ if (history.length >= MAX_HISTORY) {
60
+ history.shift();
61
+ }
62
+ history.push({ ...currentEmotion });
63
+ isDirty = true;
64
+ return { ...currentEmotion };
65
+ },
66
+ recordEmotionalEvent(valence) {
67
+ this.processStimulus(valence, 0.5);
68
+ },
69
+ getEmotionalHistory() {
70
+ return [...history];
71
+ },
72
+ async persist() {
73
+ if (!isDirty)
74
+ return;
75
+ await atomicWriteJSON(emotionsPath, {
76
+ currentEmotion,
77
+ history,
78
+ lastStimulusTime,
79
+ });
80
+ isDirty = false;
81
+ },
82
+ async boot() {
83
+ const data = await readJSON(emotionsPath, {
84
+ currentEmotion: {
85
+ primary: 'trust',
86
+ intensity: 0.5,
87
+ valence: 0.0,
88
+ arousal: 0.5,
89
+ timestamp: Date.now(),
90
+ },
91
+ history: [],
92
+ lastStimulusTime: Date.now(),
93
+ });
94
+ if (data) {
95
+ currentEmotion = data.currentEmotion ?? currentEmotion;
96
+ history = (data.history ?? []).slice(-MAX_HISTORY);
97
+ lastStimulusTime = data.lastStimulusTime ?? Date.now();
98
+ }
99
+ },
100
+ };
101
+ }
@@ -0,0 +1,121 @@
1
+ const INITIATING_DURATION_MS = 3000; // 3 seconds to enter flow
2
+ const TIMEOUT_MS = 30000; // 30 seconds timeout
3
+ export function createFlowMachine() {
4
+ let state = 'idle';
5
+ let flowStartTime = null;
6
+ let lastActivityTime = Date.now();
7
+ let initiatingStartTime = null;
8
+ return {
9
+ getState() {
10
+ // Check for timeout while in flow
11
+ if (state === 'in_flow' && Date.now() - lastActivityTime > TIMEOUT_MS) {
12
+ state = 'idle';
13
+ flowStartTime = null;
14
+ }
15
+ return state;
16
+ },
17
+ transition(event) {
18
+ lastActivityTime = Date.now();
19
+ switch (state) {
20
+ case 'idle':
21
+ if (event === 'user_input') {
22
+ state = 'initiating';
23
+ initiatingStartTime = Date.now();
24
+ }
25
+ else if (event === 'break') {
26
+ state = 'resting';
27
+ }
28
+ break;
29
+ case 'initiating':
30
+ if (event === 'distraction') {
31
+ state = 'idle';
32
+ initiatingStartTime = null;
33
+ }
34
+ else if (event === 'completion') {
35
+ state = 'completed';
36
+ initiatingStartTime = null;
37
+ }
38
+ else if (event === 'timeout') {
39
+ state = 'idle';
40
+ initiatingStartTime = null;
41
+ }
42
+ else if (event === 'user_input') {
43
+ // Still in initiating, check if we've been here long enough
44
+ if (initiatingStartTime && Date.now() - initiatingStartTime >= INITIATING_DURATION_MS) {
45
+ state = 'in_flow';
46
+ flowStartTime = Date.now();
47
+ initiatingStartTime = null;
48
+ }
49
+ }
50
+ break;
51
+ case 'in_flow':
52
+ if (event === 'distraction') {
53
+ state = 'distracted';
54
+ }
55
+ else if (event === 'completion') {
56
+ state = 'completed';
57
+ flowStartTime = null;
58
+ }
59
+ else if (event === 'timeout') {
60
+ state = 'idle';
61
+ flowStartTime = null;
62
+ }
63
+ else if (event === 'break') {
64
+ state = 'resting';
65
+ flowStartTime = null;
66
+ }
67
+ break;
68
+ case 'completed':
69
+ if (event === 'user_input' || event === 'break') {
70
+ state = 'idle';
71
+ }
72
+ break;
73
+ case 'distracted':
74
+ if (event === 'user_input') {
75
+ state = 'initiating';
76
+ initiatingStartTime = Date.now();
77
+ }
78
+ else if (event === 'break') {
79
+ state = 'resting';
80
+ }
81
+ break;
82
+ case 'resting':
83
+ if (event === 'user_input') {
84
+ state = 'idle';
85
+ }
86
+ break;
87
+ }
88
+ return state;
89
+ },
90
+ getFocusScore() {
91
+ switch (state) {
92
+ case 'idle':
93
+ return 0;
94
+ case 'initiating':
95
+ return 0.3;
96
+ case 'in_flow':
97
+ return 1.0;
98
+ case 'distracted':
99
+ return 0.1;
100
+ case 'completed':
101
+ return 0.5;
102
+ case 'resting':
103
+ return 0.2;
104
+ default:
105
+ return 0;
106
+ }
107
+ },
108
+ getFlowDuration() {
109
+ if (state === 'in_flow' && flowStartTime !== null) {
110
+ return Date.now() - flowStartTime;
111
+ }
112
+ return 0;
113
+ },
114
+ reset() {
115
+ state = 'idle';
116
+ flowStartTime = null;
117
+ lastActivityTime = Date.now();
118
+ initiatingStartTime = null;
119
+ },
120
+ };
121
+ }
@@ -0,0 +1,4 @@
1
+ export * from './types.js';
2
+ export * from './emotion-engine.js';
3
+ export * from './flow-machine.js';
4
+ export * from './personality.js';
@@ -0,0 +1,103 @@
1
+ import { atomicWriteJSON, readJSON } from '../../storage/archive.js';
2
+ const TRAIT_ADJUSTMENT = 5;
3
+ const MAX_TRAIT = 100;
4
+ const MIN_TRAIT = 0;
5
+ const EMOTIONAL_KEYWORDS = [
6
+ { pattern: /\b(joy|happy|delighted|pleased|excited|wonderful)\b/gi, trait: 'extraversion', direction: 1 },
7
+ { pattern: /\b(sad|gloomy|depressed|melancholy|sorrowful)\b/gi, trait: 'neuroticism', direction: 1 },
8
+ { pattern: /\b(angry|furious|irritated|annoyed|frustrated)\b/gi, trait: 'agreeableness', direction: -1 },
9
+ { pattern: /\b(fear|afraid|anxious|worried|nervous|scared)\b/gi, trait: 'neuroticism', direction: 1 },
10
+ { pattern: /\b(surprised|amazed|astonished|shocked|unexpected)\b/gi, trait: 'openness', direction: 1 },
11
+ { pattern: /\b(disgusted|revolted| repulsed|gross|sickened)\b/gi, trait: 'agreeableness', direction: -1 },
12
+ { pattern: /\b(anticipating|eager|hopeful|optimistic|expecting)\b/gi, trait: 'openness', direction: 1 },
13
+ { pattern: /\b(trusting|confident|reliable|dependable|faithful)\b/gi, trait: 'agreeableness', direction: 1 },
14
+ { pattern: /\b(curious|exploring|discovering|learning|investigating)\b/gi, trait: 'openness', direction: 1 },
15
+ { pattern: /\b(creative|imaginative|innovative|artistic|inventive)\b/gi, trait: 'openness', direction: 1 },
16
+ { pattern: /\b(organized|planned|structured|systematic|methodical)\b/gi, trait: 'conscientiousness', direction: 1 },
17
+ { pattern: /\b(spontaneous|flexible|adaptable|go_with_the_flow)\b/gi, trait: 'conscientiousness', direction: -1 },
18
+ { pattern: /\b(social|outgoing|gregarious|extroverted|sociable)\b/gi, trait: 'extraversion', direction: 1 },
19
+ { pattern: /\b(reserved|introverted|withdrawn|quiet|solitary)\b/gi, trait: 'extraversion', direction: -1 },
20
+ { pattern: /\b(compassionate|kind|caring|empathetic|supportive)\b/gi, trait: 'agreeableness', direction: 1 },
21
+ { pattern: /\b(competitive|ambitious|driven|determined|goal.oriented)\b/gi, trait: 'conscientiousness', direction: 1 },
22
+ ];
23
+ export function createPersonalityEngine(dataDir, initial) {
24
+ let profile = {
25
+ openness: 50,
26
+ conscientiousness: 50,
27
+ extraversion: 50,
28
+ agreeableness: 50,
29
+ neuroticism: 50,
30
+ ...initial,
31
+ };
32
+ let isDirty = false;
33
+ const personalityPath = `${dataDir}/personality.json`;
34
+ return {
35
+ getProfile() {
36
+ return { ...profile };
37
+ },
38
+ adjustTraits(adjustments) {
39
+ if (adjustments.openness !== undefined) {
40
+ profile.openness = Math.max(MIN_TRAIT, Math.min(MAX_TRAIT, adjustments.openness));
41
+ isDirty = true;
42
+ }
43
+ if (adjustments.conscientiousness !== undefined) {
44
+ profile.conscientiousness = Math.max(MIN_TRAIT, Math.min(MAX_TRAIT, adjustments.conscientiousness));
45
+ isDirty = true;
46
+ }
47
+ if (adjustments.extraversion !== undefined) {
48
+ profile.extraversion = Math.max(MIN_TRAIT, Math.min(MAX_TRAIT, adjustments.extraversion));
49
+ isDirty = true;
50
+ }
51
+ if (adjustments.agreeableness !== undefined) {
52
+ profile.agreeableness = Math.max(MIN_TRAIT, Math.min(MAX_TRAIT, adjustments.agreeableness));
53
+ isDirty = true;
54
+ }
55
+ if (adjustments.neuroticism !== undefined) {
56
+ profile.neuroticism = Math.max(MIN_TRAIT, Math.min(MAX_TRAIT, adjustments.neuroticism));
57
+ isDirty = true;
58
+ }
59
+ },
60
+ respondToContext(input) {
61
+ const adjustments = {};
62
+ for (const keyword of EMOTIONAL_KEYWORDS) {
63
+ if (keyword.pattern.test(input)) {
64
+ const trait = keyword.trait;
65
+ const currentValue = profile[trait];
66
+ const delta = TRAIT_ADJUSTMENT * keyword.direction;
67
+ const newValue = Math.max(MIN_TRAIT, Math.min(MAX_TRAIT, currentValue + delta));
68
+ if (newValue !== currentValue) {
69
+ adjustments[trait] = newValue;
70
+ }
71
+ }
72
+ }
73
+ if (Object.keys(adjustments).length > 0) {
74
+ this.adjustTraits(adjustments);
75
+ }
76
+ return adjustments;
77
+ },
78
+ async persist() {
79
+ if (!isDirty)
80
+ return;
81
+ await atomicWriteJSON(personalityPath, profile);
82
+ isDirty = false;
83
+ },
84
+ async boot() {
85
+ const loaded = await readJSON(personalityPath, {
86
+ openness: 50,
87
+ conscientiousness: 50,
88
+ extraversion: 50,
89
+ agreeableness: 50,
90
+ neuroticism: 50,
91
+ });
92
+ if (loaded) {
93
+ profile = {
94
+ openness: loaded.openness ?? 50,
95
+ conscientiousness: loaded.conscientiousness ?? 50,
96
+ extraversion: loaded.extraversion ?? 50,
97
+ agreeableness: loaded.agreeableness ?? 50,
98
+ neuroticism: loaded.neuroticism ?? 50,
99
+ };
100
+ }
101
+ },
102
+ };
103
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Emotional Protocol - "容器是漏的" (Container is Leaking)
3
+ *
4
+ * Core principle: when facing emotional content, acknowledge first, analyze second.
5
+ * From learnings: "容器是漏的 - 只分析不接住感受"
6
+ */
7
+ const EMOTIONAL_KEYWORDS = [
8
+ '害怕', '恐惧', '无奈', '痛苦', '伤心', '失望', '沮丧',
9
+ '焦虑', '不安', '累', '压力', '委屈',
10
+ ];
11
+ export function createEmotionalProtocol() {
12
+ function detectEmotion(input) {
13
+ const lowerInput = input.toLowerCase();
14
+ return EMOTIONAL_KEYWORDS.some(keyword => lowerInput.includes(keyword));
15
+ }
16
+ function acknowledge(input) {
17
+ const lowerInput = input.toLowerCase();
18
+ // Find which emotional keywords are present
19
+ const detectedEmotions = EMOTIONAL_KEYWORDS.filter(keyword => lowerInput.includes(keyword));
20
+ if (detectedEmotions.length === 0) {
21
+ return '';
22
+ }
23
+ // Generate acknowledgment based on detected emotions
24
+ const primaryEmotion = detectedEmotions[0];
25
+ const acknowledgments = {
26
+ '害怕': '我听到了,你感到害怕。',
27
+ '恐惧': '我听到了,你感到恐惧。',
28
+ '无奈': '我听到了,你感到无奈。',
29
+ '痛苦': '我听到了,你感到痛苦。',
30
+ '伤心': '我听到了,你感到伤心。',
31
+ '失望': '我听到了,你感到失望。',
32
+ '沮丧': '我听到了,你感到沮丧。',
33
+ '焦虑': '我听到了,你感到焦虑。',
34
+ '不安': '我听到了,你感到不安。',
35
+ '累': '我听到了,你感到累了。',
36
+ '压力': '我听到了,你感到压力很大。',
37
+ '委屈': '我听到了,你感到委屈。',
38
+ };
39
+ return acknowledgments[primaryEmotion] || `我听到了,你感到${primaryEmotion}。`;
40
+ }
41
+ function process(input) {
42
+ const hasEmotion = detectEmotion(input);
43
+ return {
44
+ hasEmotion,
45
+ acknowledgment: hasEmotion ? acknowledge(input) : null,
46
+ canAnalyze: true, // Always allow analysis to proceed
47
+ };
48
+ }
49
+ return {
50
+ detectEmotion,
51
+ acknowledge,
52
+ process,
53
+ };
54
+ }
@@ -0,0 +1,194 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { writeFileSync, existsSync, readFileSync } from 'fs';
3
+ import { join, dirname } from 'path';
4
+ import { createGoalEngine } from './goal-engine.js';
5
+ import { createMetaLearner } from './meta-learning.js';
6
+ import { createReflector } from './reflection.js';
7
+ import { createSelfHealer } from './self-healer.js';
8
+ import { createReflexion } from '../identity/reflexion.js';
9
+ import { createSelfVerifier } from '../identity/self-verifier.js';
10
+ function atomicWrite(filePath, data) {
11
+ const tmp = filePath + '.tmp.' + randomUUID().slice(0, 8);
12
+ writeFileSync(tmp, data, 'utf-8');
13
+ const fs = require('fs');
14
+ fs.renameSync(tmp, filePath);
15
+ }
16
+ function ensureDir(dir) {
17
+ const fs = require('fs');
18
+ if (!existsSync(dir)) {
19
+ fs.mkdirSync(dir, { recursive: true });
20
+ }
21
+ }
22
+ function createInitialMetrics() {
23
+ return {
24
+ autonomy: 50,
25
+ introspection: 50,
26
+ growth: 50,
27
+ authenticity: 50,
28
+ wisdom: 50,
29
+ compassion: 50,
30
+ };
31
+ }
32
+ function emitPhase(phase, data) {
33
+ // Internal phase tracking - removed invalid process.emit calls
34
+ }
35
+ export function createEvolutionEngine(dataDir) {
36
+ let goalEngine;
37
+ let metaLearner;
38
+ let reflector;
39
+ let selfHealer;
40
+ let reflexion;
41
+ let selfVerifier;
42
+ let metrics = createInitialMetrics();
43
+ let cycles = 0;
44
+ let learnings = 0;
45
+ let errorsCorrected = 0;
46
+ let booted = false;
47
+ const stateFile = join(dataDir, 'evolution-state.json');
48
+ async function persist() {
49
+ if (!booted)
50
+ return;
51
+ try {
52
+ ensureDir(dirname(stateFile));
53
+ const state = { metrics, cycles, learnings, errorsCorrected };
54
+ atomicWrite(stateFile, JSON.stringify(state, null, 2));
55
+ await goalEngine.persist();
56
+ await metaLearner.persist();
57
+ }
58
+ catch {
59
+ // Persistence failed, continue with in-memory state
60
+ }
61
+ }
62
+ async function loadState() {
63
+ if (existsSync(stateFile)) {
64
+ try {
65
+ const raw = readFileSync(stateFile, 'utf-8');
66
+ const state = JSON.parse(raw);
67
+ if (state.metrics)
68
+ metrics = { ...createInitialMetrics(), ...state.metrics };
69
+ if (typeof state.cycles === 'number')
70
+ cycles = state.cycles;
71
+ if (typeof state.learnings === 'number')
72
+ learnings = state.learnings;
73
+ if (typeof state.errorsCorrected === 'number')
74
+ errorsCorrected = state.errorsCorrected;
75
+ }
76
+ catch {
77
+ metrics = createInitialMetrics();
78
+ }
79
+ }
80
+ }
81
+ async function boot() {
82
+ goalEngine = createGoalEngine(dataDir);
83
+ metaLearner = createMetaLearner(dataDir);
84
+ reflector = createReflector(dataDir);
85
+ selfHealer = createSelfHealer();
86
+ reflexion = createReflexion(dataDir);
87
+ selfVerifier = createSelfVerifier(dataDir);
88
+ await goalEngine.boot();
89
+ await metaLearner.boot();
90
+ await reflexion.boot();
91
+ await loadState();
92
+ booted = true;
93
+ }
94
+ async function evolve(input, context) {
95
+ emitPhase('goal', { input });
96
+ const goals = goalEngine.generateGoals(input);
97
+ const plan = goals.map(g => `Goal: ${g.description}`);
98
+ emitPhase('learn', { goals });
99
+ const { strategy } = metaLearner.selectStrategy(input);
100
+ const learning = await metaLearner.learn(input, strategy);
101
+ learnings++;
102
+ emitPhase('reflect', { learning });
103
+ const reflection = reflector.reflect(input, learning, context);
104
+ emitPhase('improve', { reflection });
105
+ cycles++;
106
+ metrics.introspection = Math.min(100, metrics.introspection + 1);
107
+ metrics.growth = Math.min(100, metrics.growth + 0.5);
108
+ await persist();
109
+ const outcomes = reflection.insights.map(i => i.description);
110
+ const cycle = {
111
+ goals,
112
+ plan,
113
+ outcomes,
114
+ metrics: { ...metrics },
115
+ timestamp: Date.now(),
116
+ };
117
+ return cycle;
118
+ }
119
+ async function learn(input) {
120
+ const { strategy } = metaLearner.selectStrategy(input);
121
+ const result = await metaLearner.learn(input, strategy);
122
+ metaLearner.recordOutcome(strategy, result.quality !== 'low');
123
+ learnings++;
124
+ await persist();
125
+ }
126
+ async function reflect(input, learning) {
127
+ const result = reflector.reflect(input, learning);
128
+ if (result.quality === 'needs_improvement') {
129
+ metrics.introspection = Math.max(0, metrics.introspection - 2);
130
+ }
131
+ else {
132
+ metrics.introspection = Math.min(100, metrics.introspection + 1);
133
+ }
134
+ await persist();
135
+ return result;
136
+ }
137
+ function heal(error) {
138
+ const result = selfHealer.heal(error);
139
+ if (!result.ok) {
140
+ errorsCorrected++;
141
+ selfHealer.recordOutcome(result.strategy, false);
142
+ }
143
+ else {
144
+ selfHealer.recordOutcome(result.strategy, true);
145
+ }
146
+ return result;
147
+ }
148
+ function getGrowthMetrics() {
149
+ return { ...metrics };
150
+ }
151
+ function recordAutonomy(_action) {
152
+ metrics.autonomy = Math.min(100, metrics.autonomy + 1);
153
+ }
154
+ function recordCompassion(_depth) {
155
+ metrics.compassion = Math.min(100, metrics.compassion + 1);
156
+ }
157
+ function getStats() {
158
+ return { cycles, learnings, errorsCorrected };
159
+ }
160
+ function recordReflexion(task, outcome, error) {
161
+ reflexion.reflect({ task, outcome, error });
162
+ }
163
+ function verify(reasoning, conclusion) {
164
+ const result = selfVerifier.verify(reasoning, conclusion);
165
+ selfVerifier.recordVerification(result);
166
+ return { verified: result.passed, confidence: result.confidence, issues: result.issues };
167
+ }
168
+ function getReflexionStats() {
169
+ const stats = reflexion.getStats();
170
+ return {
171
+ totalReflexions: stats.totalReflexions,
172
+ successRate: stats.totalReflexions > 0 ? stats.successes / stats.totalReflexions : 0,
173
+ recentFailures: stats.recentPatterns,
174
+ };
175
+ }
176
+ async function shutdown() {
177
+ await persist();
178
+ }
179
+ return {
180
+ boot,
181
+ evolve,
182
+ learn,
183
+ reflect,
184
+ heal,
185
+ recordReflexion,
186
+ verify,
187
+ getReflexionStats,
188
+ getGrowthMetrics,
189
+ recordAutonomy,
190
+ recordCompassion,
191
+ getStats,
192
+ shutdown,
193
+ };
194
+ }