@cogitator-ai/self-modifying 0.1.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 (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +714 -0
  3. package/dist/architecture-evolution/capability-analyzer.d.ts +32 -0
  4. package/dist/architecture-evolution/capability-analyzer.d.ts.map +1 -0
  5. package/dist/architecture-evolution/capability-analyzer.js +264 -0
  6. package/dist/architecture-evolution/capability-analyzer.js.map +1 -0
  7. package/dist/architecture-evolution/evolution-strategy.d.ts +29 -0
  8. package/dist/architecture-evolution/evolution-strategy.d.ts.map +1 -0
  9. package/dist/architecture-evolution/evolution-strategy.js +176 -0
  10. package/dist/architecture-evolution/evolution-strategy.js.map +1 -0
  11. package/dist/architecture-evolution/index.d.ts +5 -0
  12. package/dist/architecture-evolution/index.d.ts.map +1 -0
  13. package/dist/architecture-evolution/index.js +5 -0
  14. package/dist/architecture-evolution/index.js.map +1 -0
  15. package/dist/architecture-evolution/parameter-optimizer.d.ts +67 -0
  16. package/dist/architecture-evolution/parameter-optimizer.d.ts.map +1 -0
  17. package/dist/architecture-evolution/parameter-optimizer.js +341 -0
  18. package/dist/architecture-evolution/parameter-optimizer.js.map +1 -0
  19. package/dist/architecture-evolution/prompts.d.ts +33 -0
  20. package/dist/architecture-evolution/prompts.d.ts.map +1 -0
  21. package/dist/architecture-evolution/prompts.js +169 -0
  22. package/dist/architecture-evolution/prompts.js.map +1 -0
  23. package/dist/constraints/index.d.ts +4 -0
  24. package/dist/constraints/index.d.ts.map +1 -0
  25. package/dist/constraints/index.js +4 -0
  26. package/dist/constraints/index.js.map +1 -0
  27. package/dist/constraints/modification-validator.d.ts +26 -0
  28. package/dist/constraints/modification-validator.d.ts.map +1 -0
  29. package/dist/constraints/modification-validator.js +313 -0
  30. package/dist/constraints/modification-validator.js.map +1 -0
  31. package/dist/constraints/rollback-manager.d.ts +52 -0
  32. package/dist/constraints/rollback-manager.d.ts.map +1 -0
  33. package/dist/constraints/rollback-manager.js +113 -0
  34. package/dist/constraints/rollback-manager.js.map +1 -0
  35. package/dist/constraints/safety-constraints.d.ts +11 -0
  36. package/dist/constraints/safety-constraints.d.ts.map +1 -0
  37. package/dist/constraints/safety-constraints.js +78 -0
  38. package/dist/constraints/safety-constraints.js.map +1 -0
  39. package/dist/events/event-emitter.d.ts +12 -0
  40. package/dist/events/event-emitter.d.ts.map +1 -0
  41. package/dist/events/event-emitter.js +43 -0
  42. package/dist/events/event-emitter.js.map +1 -0
  43. package/dist/events/index.d.ts +2 -0
  44. package/dist/events/index.d.ts.map +1 -0
  45. package/dist/events/index.js +2 -0
  46. package/dist/events/index.js.map +1 -0
  47. package/dist/index.d.ts +8 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +7 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/meta-reasoning/index.d.ts +5 -0
  52. package/dist/meta-reasoning/index.d.ts.map +1 -0
  53. package/dist/meta-reasoning/index.js +5 -0
  54. package/dist/meta-reasoning/index.js.map +1 -0
  55. package/dist/meta-reasoning/meta-reasoner.d.ts +53 -0
  56. package/dist/meta-reasoning/meta-reasoner.d.ts.map +1 -0
  57. package/dist/meta-reasoning/meta-reasoner.js +261 -0
  58. package/dist/meta-reasoning/meta-reasoner.js.map +1 -0
  59. package/dist/meta-reasoning/observation-collector.d.ts +37 -0
  60. package/dist/meta-reasoning/observation-collector.d.ts.map +1 -0
  61. package/dist/meta-reasoning/observation-collector.js +123 -0
  62. package/dist/meta-reasoning/observation-collector.js.map +1 -0
  63. package/dist/meta-reasoning/prompts.d.ts +31 -0
  64. package/dist/meta-reasoning/prompts.d.ts.map +1 -0
  65. package/dist/meta-reasoning/prompts.js +96 -0
  66. package/dist/meta-reasoning/prompts.js.map +1 -0
  67. package/dist/meta-reasoning/strategy-selector.d.ts +27 -0
  68. package/dist/meta-reasoning/strategy-selector.d.ts.map +1 -0
  69. package/dist/meta-reasoning/strategy-selector.js +138 -0
  70. package/dist/meta-reasoning/strategy-selector.js.map +1 -0
  71. package/dist/self-modifying-agent.d.ts +61 -0
  72. package/dist/self-modifying-agent.d.ts.map +1 -0
  73. package/dist/self-modifying-agent.js +449 -0
  74. package/dist/self-modifying-agent.js.map +1 -0
  75. package/dist/tool-generation/gap-analyzer.d.ts +25 -0
  76. package/dist/tool-generation/gap-analyzer.d.ts.map +1 -0
  77. package/dist/tool-generation/gap-analyzer.js +153 -0
  78. package/dist/tool-generation/gap-analyzer.js.map +1 -0
  79. package/dist/tool-generation/generated-tool-store.d.ts +51 -0
  80. package/dist/tool-generation/generated-tool-store.d.ts.map +1 -0
  81. package/dist/tool-generation/generated-tool-store.js +195 -0
  82. package/dist/tool-generation/generated-tool-store.js.map +1 -0
  83. package/dist/tool-generation/index.d.ts +7 -0
  84. package/dist/tool-generation/index.d.ts.map +1 -0
  85. package/dist/tool-generation/index.js +7 -0
  86. package/dist/tool-generation/index.js.map +1 -0
  87. package/dist/tool-generation/prompts.d.ts +28 -0
  88. package/dist/tool-generation/prompts.d.ts.map +1 -0
  89. package/dist/tool-generation/prompts.js +269 -0
  90. package/dist/tool-generation/prompts.js.map +1 -0
  91. package/dist/tool-generation/tool-generator.d.ts +29 -0
  92. package/dist/tool-generation/tool-generator.d.ts.map +1 -0
  93. package/dist/tool-generation/tool-generator.js +169 -0
  94. package/dist/tool-generation/tool-generator.js.map +1 -0
  95. package/dist/tool-generation/tool-sandbox.d.ts +31 -0
  96. package/dist/tool-generation/tool-sandbox.d.ts.map +1 -0
  97. package/dist/tool-generation/tool-sandbox.js +240 -0
  98. package/dist/tool-generation/tool-sandbox.js.map +1 -0
  99. package/dist/tool-generation/tool-validator.d.ts +32 -0
  100. package/dist/tool-generation/tool-validator.d.ts.map +1 -0
  101. package/dist/tool-generation/tool-validator.js +304 -0
  102. package/dist/tool-generation/tool-validator.js.map +1 -0
  103. package/dist/utils/index.d.ts +2 -0
  104. package/dist/utils/index.d.ts.map +1 -0
  105. package/dist/utils/index.js +2 -0
  106. package/dist/utils/index.js.map +1 -0
  107. package/dist/utils/llm-helper.d.ts +6 -0
  108. package/dist/utils/llm-helper.d.ts.map +1 -0
  109. package/dist/utils/llm-helper.js +18 -0
  110. package/dist/utils/llm-helper.js.map +1 -0
  111. package/package.json +61 -0
  112. package/src/__tests__/architecture-evolution.test.ts +368 -0
  113. package/src/__tests__/constraints.test.ts +266 -0
  114. package/src/__tests__/index.test.ts +99 -0
  115. package/src/__tests__/meta-reasoning.test.ts +343 -0
  116. package/src/__tests__/tool-generation.test.ts +455 -0
  117. package/src/architecture-evolution/capability-analyzer.ts +337 -0
  118. package/src/architecture-evolution/evolution-strategy.ts +224 -0
  119. package/src/architecture-evolution/index.ts +26 -0
  120. package/src/architecture-evolution/parameter-optimizer.ts +489 -0
  121. package/src/architecture-evolution/prompts.ts +216 -0
  122. package/src/constraints/index.ts +23 -0
  123. package/src/constraints/modification-validator.ts +402 -0
  124. package/src/constraints/rollback-manager.ts +173 -0
  125. package/src/constraints/safety-constraints.ts +103 -0
  126. package/src/events/event-emitter.ts +62 -0
  127. package/src/events/index.ts +1 -0
  128. package/src/index.ts +112 -0
  129. package/src/meta-reasoning/index.ts +24 -0
  130. package/src/meta-reasoning/meta-reasoner.ts +381 -0
  131. package/src/meta-reasoning/observation-collector.ts +161 -0
  132. package/src/meta-reasoning/prompts.ts +131 -0
  133. package/src/meta-reasoning/strategy-selector.ts +179 -0
  134. package/src/self-modifying-agent.ts +585 -0
  135. package/src/tool-generation/gap-analyzer.ts +234 -0
  136. package/src/tool-generation/generated-tool-store.ts +268 -0
  137. package/src/tool-generation/index.ts +19 -0
  138. package/src/tool-generation/prompts.ts +308 -0
  139. package/src/tool-generation/tool-generator.ts +243 -0
  140. package/src/tool-generation/tool-sandbox.ts +332 -0
  141. package/src/tool-generation/tool-validator.ts +365 -0
  142. package/src/utils/index.ts +1 -0
  143. package/src/utils/llm-helper.ts +24 -0
@@ -0,0 +1,161 @@
1
+ import type {
2
+ MetaObservation,
3
+ ReasoningMode,
4
+ Insight,
5
+ } from '@cogitator-ai/types';
6
+
7
+ export interface ActionRecord {
8
+ type: string;
9
+ toolName?: string;
10
+ input?: unknown;
11
+ output?: unknown;
12
+ error?: string;
13
+ duration?: number;
14
+ timestamp: number;
15
+ }
16
+
17
+ export interface ObservationContext {
18
+ runId: string;
19
+ iteration: number;
20
+ goal: string;
21
+ currentMode: ReasoningMode;
22
+ tokensUsed: number;
23
+ timeElapsed: number;
24
+ iterationsRemaining: number;
25
+ budgetRemaining: number;
26
+ }
27
+
28
+ export class ObservationCollector {
29
+ private observations = new Map<string, MetaObservation[]>();
30
+ private actionHistory = new Map<string, ActionRecord[]>();
31
+ private confidenceHistory = new Map<string, number[]>();
32
+
33
+ initializeRun(runId: string): void {
34
+ this.observations.set(runId, []);
35
+ this.actionHistory.set(runId, []);
36
+ this.confidenceHistory.set(runId, []);
37
+ }
38
+
39
+ recordAction(runId: string, action: ActionRecord): void {
40
+ const history = this.actionHistory.get(runId);
41
+ if (history) {
42
+ history.push(action);
43
+ if (history.length > 100) {
44
+ history.shift();
45
+ }
46
+ }
47
+ }
48
+
49
+ recordConfidence(runId: string, confidence: number): void {
50
+ const history = this.confidenceHistory.get(runId);
51
+ if (history) {
52
+ history.push(confidence);
53
+ if (history.length > 20) {
54
+ history.shift();
55
+ }
56
+ }
57
+ }
58
+
59
+ collect(
60
+ context: ObservationContext,
61
+ insights: Insight[]
62
+ ): MetaObservation {
63
+ const { runId, iteration, goal, currentMode } = context;
64
+ const prevObservations = this.observations.get(runId) ?? [];
65
+ const lastObs = prevObservations[prevObservations.length - 1];
66
+ const actions = this.actionHistory.get(runId) ?? [];
67
+ const confidenceHist = this.confidenceHistory.get(runId) ?? [];
68
+
69
+ const currentConfidence = confidenceHist[confidenceHist.length - 1] ?? 0.5;
70
+ const progressScore = this.calculateProgress(actions);
71
+ const progressDelta = lastObs ? progressScore - lastObs.progressScore : 0;
72
+ const stagnationCount = progressDelta < 0.05
73
+ ? (lastObs?.stagnationCount ?? 0) + 1
74
+ : 0;
75
+ const repetitionScore = this.calculateRepetition(actions);
76
+ const toolSuccessRate = this.calculateToolSuccessRate(actions);
77
+ const confidenceTrend = this.calculateTrend(confidenceHist);
78
+
79
+ const observation: MetaObservation = {
80
+ runId,
81
+ iteration,
82
+ timestamp: Date.now(),
83
+ progressScore,
84
+ progressDelta,
85
+ stagnationCount,
86
+ currentConfidence,
87
+ confidenceTrend,
88
+ confidenceHistory: confidenceHist.slice(-10),
89
+ tokensUsed: context.tokensUsed,
90
+ timeElapsed: context.timeElapsed,
91
+ iterationsRemaining: context.iterationsRemaining,
92
+ budgetRemaining: context.budgetRemaining,
93
+ toolSuccessRate,
94
+ errorRate: 1 - toolSuccessRate,
95
+ repetitionScore,
96
+ currentMode,
97
+ recentActions: actions.slice(-5).map((a) => ({
98
+ type: a.type,
99
+ toolName: a.toolName,
100
+ input: a.input,
101
+ output: a.output,
102
+ error: a.error,
103
+ })),
104
+ recentInsights: insights.slice(-3),
105
+ goal,
106
+ };
107
+
108
+ prevObservations.push(observation);
109
+ return observation;
110
+ }
111
+
112
+ private calculateProgress(actions: ActionRecord[]): number {
113
+ if (actions.length === 0) return 0;
114
+ const successful = actions.filter((a) => !a.error).length;
115
+ return successful / actions.length;
116
+ }
117
+
118
+ private calculateRepetition(actions: ActionRecord[]): number {
119
+ if (actions.length < 2) return 0;
120
+ const toolCalls = actions
121
+ .filter((a) => a.type === 'tool_call' && a.toolName)
122
+ .map((a) => `${a.toolName}:${JSON.stringify(a.input)}`);
123
+
124
+ if (toolCalls.length === 0) return 0;
125
+ const unique = new Set(toolCalls);
126
+ return 1 - unique.size / toolCalls.length;
127
+ }
128
+
129
+ private calculateToolSuccessRate(actions: ActionRecord[]): number {
130
+ const toolCalls = actions.filter((a) => a.type === 'tool_call');
131
+ if (toolCalls.length === 0) return 1;
132
+ const successful = toolCalls.filter((a) => !a.error).length;
133
+ return successful / toolCalls.length;
134
+ }
135
+
136
+ private calculateTrend(values: number[]): 'rising' | 'stable' | 'falling' {
137
+ if (values.length < 3) return 'stable';
138
+ const recent = values.slice(-3);
139
+ const avg = recent.reduce((a, b) => a + b, 0) / recent.length;
140
+ const first = recent[0];
141
+
142
+ if (avg > first + 0.1) return 'rising';
143
+ if (avg < first - 0.1) return 'falling';
144
+ return 'stable';
145
+ }
146
+
147
+ getObservations(runId: string): MetaObservation[] {
148
+ return this.observations.get(runId) ?? [];
149
+ }
150
+
151
+ getLatestObservation(runId: string): MetaObservation | null {
152
+ const obs = this.observations.get(runId);
153
+ return obs?.[obs.length - 1] ?? null;
154
+ }
155
+
156
+ cleanupRun(runId: string): void {
157
+ this.observations.delete(runId);
158
+ this.actionHistory.delete(runId);
159
+ this.confidenceHistory.delete(runId);
160
+ }
161
+ }
@@ -0,0 +1,131 @@
1
+ import type {
2
+ MetaObservation,
3
+ ReasoningMode,
4
+ ReasoningModeConfig,
5
+ } from '@cogitator-ai/types';
6
+
7
+ export function buildMetaAssessmentPrompt(
8
+ observation: MetaObservation,
9
+ context: {
10
+ allowedModes: ReasoningMode[];
11
+ currentModeConfig: ReasoningModeConfig;
12
+ }
13
+ ): string {
14
+ return `# Meta-Reasoning Assessment
15
+
16
+ ## Current Goal
17
+ ${observation.goal}
18
+
19
+ ## Current Reasoning Mode
20
+ Mode: ${observation.currentMode}
21
+ Temperature: ${context.currentModeConfig.temperature}
22
+ Iterations remaining: ${observation.iterationsRemaining}
23
+
24
+ ## Progress Metrics
25
+ - Progress score: ${(observation.progressScore * 100).toFixed(1)}%
26
+ - Progress delta (last step): ${observation.progressDelta > 0 ? '+' : ''}${(observation.progressDelta * 100).toFixed(1)}%
27
+ - Stagnation count: ${observation.stagnationCount} consecutive low-progress iterations
28
+
29
+ ## Confidence Metrics
30
+ - Current confidence: ${(observation.currentConfidence * 100).toFixed(1)}%
31
+ - Trend: ${observation.confidenceTrend}
32
+ - History: [${observation.confidenceHistory.map((c) => (c * 100).toFixed(0) + '%').join(', ')}]
33
+
34
+ ## Resource Usage
35
+ - Tokens used: ${observation.tokensUsed}
36
+ - Time elapsed: ${observation.timeElapsed}ms
37
+ - Budget remaining: ${((observation.budgetRemaining ?? 0) * 100).toFixed(1)}%
38
+
39
+ ## Quality Metrics
40
+ - Tool success rate: ${(observation.toolSuccessRate * 100).toFixed(1)}%
41
+ - Repetition score: ${(observation.repetitionScore * 100).toFixed(1)}% (lower is better)
42
+
43
+ ## Recent Actions
44
+ ${(observation.recentActions ?? []).map((a) => `- ${a.type}: ${a.toolName ?? 'N/A'} ${a.error ? '(ERROR: ' + a.error + ')' : ''}`).join('\n') || 'None'}
45
+
46
+ ## Recent Insights
47
+ ${(observation.recentInsights ?? [] as Array<{ type?: string; content?: string }>).map((i) => {
48
+ const insight = i as { type?: string; content?: string };
49
+ return `- [${insight.type ?? 'insight'}] ${insight.content ?? ''}`;
50
+ }).join('\n') || 'None'}
51
+
52
+ ## Available Modes for Switching
53
+ ${context.allowedModes.map((m) => `- ${m}`).join('\n')}
54
+
55
+ ---
56
+
57
+ Analyze the agent's reasoning process and respond with a JSON object:
58
+
59
+ {
60
+ "onTrack": boolean,
61
+ "confidence": number,
62
+ "reasoning": "string",
63
+ "issues": [
64
+ {
65
+ "type": "stagnation" | "repetition" | "resource_exhaustion" | "confidence_decline" | "strategy_mismatch" | "goal_drift",
66
+ "severity": "low" | "medium" | "high" | "critical",
67
+ "description": "string"
68
+ }
69
+ ],
70
+ "opportunities": [
71
+ {
72
+ "type": "strategy_switch" | "temperature_adjust" | "tool_pivot" | "goal_refinement" | "context_injection",
73
+ "description": "string",
74
+ "expectedImprovement": number
75
+ }
76
+ ],
77
+ "recommendation": {
78
+ "action": "continue" | "switch_mode" | "adjust_parameters" | "inject_context" | "escalate" | "abort",
79
+ "newMode": "string",
80
+ "parameterChanges": {},
81
+ "contextAddition": "string",
82
+ "confidence": number,
83
+ "reasoning": "string"
84
+ }
85
+ }`;
86
+ }
87
+
88
+ export interface ParsedAssessment {
89
+ onTrack: boolean;
90
+ confidence: number;
91
+ reasoning: string;
92
+ issues: Array<{
93
+ type: string;
94
+ severity: string;
95
+ description: string;
96
+ }>;
97
+ opportunities: Array<{
98
+ type: string;
99
+ description: string;
100
+ expectedImprovement: number;
101
+ }>;
102
+ recommendation: {
103
+ action: string;
104
+ newMode?: string;
105
+ parameterChanges?: Record<string, unknown>;
106
+ contextAddition?: string;
107
+ confidence: number;
108
+ reasoning: string;
109
+ };
110
+ }
111
+
112
+ export function parseMetaAssessmentResponse(content: string): ParsedAssessment | null {
113
+ try {
114
+ const jsonMatch = content.match(/\{[\s\S]*\}/);
115
+ if (!jsonMatch) return null;
116
+ return JSON.parse(jsonMatch[0]) as ParsedAssessment;
117
+ } catch {
118
+ return null;
119
+ }
120
+ }
121
+
122
+ export const META_REASONING_SYSTEM_PROMPT = `You are a meta-reasoning system analyzing an AI agent's reasoning process.
123
+ Your job is to assess whether the agent is on track and recommend strategic adjustments.
124
+
125
+ Key responsibilities:
126
+ 1. Detect when the agent is stuck, repeating itself, or making poor progress
127
+ 2. Identify opportunities to improve the reasoning approach
128
+ 3. Recommend mode switches or parameter adjustments when beneficial
129
+ 4. Avoid over-intervention - only recommend changes when truly needed
130
+
131
+ Always respond with valid JSON matching the specified schema.`;
@@ -0,0 +1,179 @@
1
+ import type {
2
+ ReasoningMode,
3
+ ReasoningModeConfig,
4
+ TaskProfile,
5
+ MetaObservation,
6
+ } from '@cogitator-ai/types';
7
+ import { DEFAULT_MODE_PROFILES } from '@cogitator-ai/types';
8
+
9
+ export { DEFAULT_MODE_PROFILES };
10
+
11
+ export interface StrategySelectorOptions {
12
+ allowedModes: ReasoningMode[];
13
+ modeProfiles: Record<ReasoningMode, ReasoningModeConfig>;
14
+ }
15
+
16
+ export interface ModeScore {
17
+ mode: ReasoningMode;
18
+ score: number;
19
+ reasoning: string;
20
+ }
21
+
22
+ export class StrategySelector {
23
+ private allowedModes: ReasoningMode[];
24
+ private modeProfiles: Record<ReasoningMode, ReasoningModeConfig>;
25
+ private modeHistory = new Map<string, Array<{ mode: ReasoningMode; success: boolean }>>();
26
+
27
+ constructor(options: StrategySelectorOptions) {
28
+ this.allowedModes = options.allowedModes;
29
+ this.modeProfiles = options.modeProfiles;
30
+ }
31
+
32
+ selectForTask(taskProfile: TaskProfile): ReasoningMode {
33
+ const scores = this.scoreModesForTask(taskProfile);
34
+ scores.sort((a, b) => b.score - a.score);
35
+ return scores[0]?.mode ?? 'analytical';
36
+ }
37
+
38
+ scoreModesForTask(taskProfile: TaskProfile): ModeScore[] {
39
+ const scores: ModeScore[] = [];
40
+
41
+ for (const mode of this.allowedModes) {
42
+ const score = this.calculateModeScore(mode, taskProfile);
43
+ scores.push(score);
44
+ }
45
+
46
+ return scores;
47
+ }
48
+
49
+ private calculateModeScore(mode: ReasoningMode, profile: TaskProfile): ModeScore {
50
+ let score = 0.5;
51
+ const reasons: string[] = [];
52
+
53
+ switch (mode) {
54
+ case 'analytical':
55
+ if (profile.requiresReasoning) {
56
+ score += 0.2;
57
+ reasons.push('Good for reasoning tasks');
58
+ }
59
+ if (profile.complexity === 'complex' || profile.complexity === 'expert') {
60
+ score += 0.1;
61
+ reasons.push('Handles complexity well');
62
+ }
63
+ break;
64
+
65
+ case 'creative':
66
+ if (profile.requiresCreativity) {
67
+ score += 0.3;
68
+ reasons.push('Best for creative tasks');
69
+ }
70
+ if (profile.complexity === 'simple') {
71
+ score += 0.1;
72
+ reasons.push('Works well for simpler tasks');
73
+ }
74
+ break;
75
+
76
+ case 'systematic':
77
+ if (profile.complexity === 'expert' || profile.complexity === 'extreme') {
78
+ score += 0.2;
79
+ reasons.push('Thorough for complex tasks');
80
+ }
81
+ if (!profile.timeConstraint || profile.timeConstraint === 'none' || profile.timeConstraint === 'relaxed') {
82
+ score += 0.1;
83
+ reasons.push('Has time for systematic approach');
84
+ }
85
+ break;
86
+
87
+ case 'intuitive':
88
+ if (profile.timeConstraint === 'strict') {
89
+ score += 0.3;
90
+ reasons.push('Fast for time-constrained tasks');
91
+ }
92
+ if (profile.complexity === 'simple') {
93
+ score += 0.2;
94
+ reasons.push('Efficient for simple tasks');
95
+ }
96
+ break;
97
+
98
+ case 'reflective':
99
+ if (profile.requiresReasoning && profile.complexity !== 'simple') {
100
+ score += 0.15;
101
+ reasons.push('Deep reflection for reasoning');
102
+ }
103
+ break;
104
+
105
+ case 'exploratory':
106
+ if (profile.requiresCreativity && profile.requiresReasoning) {
107
+ score += 0.2;
108
+ reasons.push('Explores multiple paths');
109
+ }
110
+ if (!profile.requiresTools) {
111
+ score += 0.1;
112
+ reasons.push('Good for open-ended problems');
113
+ }
114
+ break;
115
+ }
116
+
117
+ return {
118
+ mode,
119
+ score: Math.min(1, Math.max(0, score)),
120
+ reasoning: reasons.join('; ') || 'Default scoring',
121
+ };
122
+ }
123
+
124
+ suggestSwitch(observation: MetaObservation): ReasoningMode | null {
125
+ const { currentMode, stagnationCount, confidenceTrend, repetitionScore } = observation;
126
+
127
+ if (stagnationCount >= 3 || confidenceTrend === 'falling' || repetitionScore > 0.5) {
128
+ const alternatives = this.allowedModes.filter((m) => m !== currentMode);
129
+
130
+ if (currentMode === 'analytical' && alternatives.includes('creative')) {
131
+ return 'creative';
132
+ }
133
+ if (currentMode === 'creative' && alternatives.includes('systematic')) {
134
+ return 'systematic';
135
+ }
136
+ if (currentMode === 'systematic' && alternatives.includes('exploratory')) {
137
+ return 'exploratory';
138
+ }
139
+ if (currentMode === 'intuitive' && alternatives.includes('analytical')) {
140
+ return 'analytical';
141
+ }
142
+
143
+ return alternatives[0] ?? null;
144
+ }
145
+
146
+ return null;
147
+ }
148
+
149
+ recordModeOutcome(runId: string, mode: ReasoningMode, success: boolean): void {
150
+ if (!this.modeHistory.has(runId)) {
151
+ this.modeHistory.set(runId, []);
152
+ }
153
+ this.modeHistory.get(runId)!.push({ mode, success });
154
+ }
155
+
156
+ getModeConfig(mode: ReasoningMode): ReasoningModeConfig {
157
+ return this.modeProfiles[mode];
158
+ }
159
+
160
+ getSuccessRate(mode: ReasoningMode): number {
161
+ let total = 0;
162
+ let successful = 0;
163
+
164
+ for (const history of this.modeHistory.values()) {
165
+ for (const entry of history) {
166
+ if (entry.mode === mode) {
167
+ total++;
168
+ if (entry.success) successful++;
169
+ }
170
+ }
171
+ }
172
+
173
+ return total > 0 ? successful / total : 0.5;
174
+ }
175
+
176
+ cleanupRun(runId: string): void {
177
+ this.modeHistory.delete(runId);
178
+ }
179
+ }