@cogitator-ai/self-modifying 0.1.0 → 1.0.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 (88) hide show
  1. package/README.md +60 -50
  2. package/dist/architecture-evolution/capability-analyzer.d.ts.map +1 -1
  3. package/dist/architecture-evolution/capability-analyzer.js +105 -19
  4. package/dist/architecture-evolution/capability-analyzer.js.map +1 -1
  5. package/dist/architecture-evolution/evolution-strategy.d.ts.map +1 -1
  6. package/dist/architecture-evolution/evolution-strategy.js +2 -6
  7. package/dist/architecture-evolution/evolution-strategy.js.map +1 -1
  8. package/dist/architecture-evolution/index.d.ts +1 -1
  9. package/dist/architecture-evolution/index.d.ts.map +1 -1
  10. package/dist/architecture-evolution/index.js +1 -1
  11. package/dist/architecture-evolution/index.js.map +1 -1
  12. package/dist/architecture-evolution/parameter-optimizer.d.ts.map +1 -1
  13. package/dist/architecture-evolution/parameter-optimizer.js.map +1 -1
  14. package/dist/architecture-evolution/prompts.d.ts.map +1 -1
  15. package/dist/architecture-evolution/prompts.js.map +1 -1
  16. package/dist/constraints/index.d.ts +1 -1
  17. package/dist/constraints/index.d.ts.map +1 -1
  18. package/dist/constraints/index.js +1 -1
  19. package/dist/constraints/index.js.map +1 -1
  20. package/dist/constraints/modification-validator.d.ts.map +1 -1
  21. package/dist/constraints/modification-validator.js +1 -2
  22. package/dist/constraints/modification-validator.js.map +1 -1
  23. package/dist/constraints/rollback-manager.d.ts.map +1 -1
  24. package/dist/constraints/rollback-manager.js.map +1 -1
  25. package/dist/constraints/safety-constraints.d.ts.map +1 -1
  26. package/dist/constraints/safety-constraints.js +1 -3
  27. package/dist/constraints/safety-constraints.js.map +1 -1
  28. package/dist/index.d.ts +2 -2
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +2 -2
  31. package/dist/index.js.map +1 -1
  32. package/dist/meta-reasoning/meta-reasoner.d.ts.map +1 -1
  33. package/dist/meta-reasoning/meta-reasoner.js +5 -10
  34. package/dist/meta-reasoning/meta-reasoner.js.map +1 -1
  35. package/dist/meta-reasoning/observation-collector.d.ts.map +1 -1
  36. package/dist/meta-reasoning/observation-collector.js +1 -3
  37. package/dist/meta-reasoning/observation-collector.js.map +1 -1
  38. package/dist/meta-reasoning/prompts.d.ts.map +1 -1
  39. package/dist/meta-reasoning/prompts.js +4 -2
  40. package/dist/meta-reasoning/prompts.js.map +1 -1
  41. package/dist/meta-reasoning/strategy-selector.d.ts.map +1 -1
  42. package/dist/meta-reasoning/strategy-selector.js +3 -1
  43. package/dist/meta-reasoning/strategy-selector.js.map +1 -1
  44. package/dist/self-modifying-agent.d.ts.map +1 -1
  45. package/dist/self-modifying-agent.js +14 -6
  46. package/dist/self-modifying-agent.js.map +1 -1
  47. package/dist/tool-generation/gap-analyzer.d.ts.map +1 -1
  48. package/dist/tool-generation/gap-analyzer.js +4 -1
  49. package/dist/tool-generation/gap-analyzer.js.map +1 -1
  50. package/dist/tool-generation/generated-tool-store.d.ts.map +1 -1
  51. package/dist/tool-generation/generated-tool-store.js.map +1 -1
  52. package/dist/tool-generation/prompts.d.ts.map +1 -1
  53. package/dist/tool-generation/prompts.js +5 -15
  54. package/dist/tool-generation/prompts.js.map +1 -1
  55. package/dist/tool-generation/tool-generator.d.ts.map +1 -1
  56. package/dist/tool-generation/tool-generator.js.map +1 -1
  57. package/dist/tool-generation/tool-sandbox.d.ts.map +1 -1
  58. package/dist/tool-generation/tool-sandbox.js +1 -3
  59. package/dist/tool-generation/tool-sandbox.js.map +1 -1
  60. package/dist/tool-generation/tool-validator.d.ts.map +1 -1
  61. package/dist/tool-generation/tool-validator.js.map +1 -1
  62. package/package.json +4 -4
  63. package/src/__tests__/architecture-evolution.test.ts +131 -30
  64. package/src/__tests__/constraints.test.ts +61 -46
  65. package/src/__tests__/index.test.ts +4 -17
  66. package/src/__tests__/meta-reasoning.test.ts +246 -155
  67. package/src/__tests__/tool-generation.test.ts +26 -7
  68. package/src/architecture-evolution/capability-analyzer.ts +113 -31
  69. package/src/architecture-evolution/evolution-strategy.ts +20 -13
  70. package/src/architecture-evolution/index.ts +1 -4
  71. package/src/architecture-evolution/parameter-optimizer.ts +42 -23
  72. package/src/architecture-evolution/prompts.ts +14 -15
  73. package/src/constraints/index.ts +1 -4
  74. package/src/constraints/modification-validator.ts +5 -18
  75. package/src/constraints/rollback-manager.ts +1 -3
  76. package/src/constraints/safety-constraints.ts +1 -3
  77. package/src/index.ts +6 -5
  78. package/src/meta-reasoning/meta-reasoner.ts +9 -16
  79. package/src/meta-reasoning/observation-collector.ts +3 -12
  80. package/src/meta-reasoning/prompts.ts +9 -9
  81. package/src/meta-reasoning/strategy-selector.ts +5 -1
  82. package/src/self-modifying-agent.ts +25 -28
  83. package/src/tool-generation/gap-analyzer.ts +18 -14
  84. package/src/tool-generation/generated-tool-store.ts +5 -8
  85. package/src/tool-generation/prompts.ts +5 -15
  86. package/src/tool-generation/tool-generator.ts +15 -11
  87. package/src/tool-generation/tool-sandbox.ts +4 -15
  88. package/src/tool-generation/tool-validator.ts +17 -13
@@ -16,28 +16,102 @@ interface DomainKeywords {
16
16
 
17
17
  const DOMAIN_KEYWORDS: DomainKeywords = {
18
18
  coding: [
19
- 'code', 'program', 'function', 'class', 'debug', 'implement', 'refactor',
20
- 'typescript', 'javascript', 'python', 'api', 'database', 'sql', 'algorithm',
21
- 'data structure', 'compile', 'syntax', 'bug', 'error', 'test', 'unit test',
19
+ 'code',
20
+ 'program',
21
+ 'function',
22
+ 'class',
23
+ 'debug',
24
+ 'implement',
25
+ 'refactor',
26
+ 'typescript',
27
+ 'javascript',
28
+ 'python',
29
+ 'api',
30
+ 'database',
31
+ 'sql',
32
+ 'algorithm',
33
+ 'data structure',
34
+ 'compile',
35
+ 'syntax',
36
+ 'bug',
37
+ 'error',
38
+ 'test',
39
+ 'unit test',
22
40
  ],
23
41
  reasoning: [
24
- 'analyze', 'reason', 'logic', 'deduce', 'infer', 'solve', 'problem',
25
- 'strategy', 'plan', 'decision', 'evaluate', 'compare', 'trade-off',
26
- 'optimize', 'proof', 'argument', 'conclusion', 'hypothesis',
42
+ 'analyze',
43
+ 'reason',
44
+ 'logic',
45
+ 'deduce',
46
+ 'infer',
47
+ 'solve',
48
+ 'problem',
49
+ 'strategy',
50
+ 'plan',
51
+ 'decision',
52
+ 'evaluate',
53
+ 'compare',
54
+ 'trade-off',
55
+ 'optimize',
56
+ 'proof',
57
+ 'argument',
58
+ 'conclusion',
59
+ 'hypothesis',
27
60
  ],
28
61
  creative: [
29
- 'create', 'imagine', 'story', 'poem', 'write', 'design', 'brainstorm',
30
- 'innovative', 'novel', 'artistic', 'compose', 'invent', 'original',
31
- 'creative', 'fiction', 'narrative', 'metaphor', 'style',
62
+ 'create',
63
+ 'imagine',
64
+ 'story',
65
+ 'poem',
66
+ 'write',
67
+ 'design',
68
+ 'brainstorm',
69
+ 'innovative',
70
+ 'novel',
71
+ 'artistic',
72
+ 'compose',
73
+ 'invent',
74
+ 'original',
75
+ 'creative',
76
+ 'fiction',
77
+ 'narrative',
78
+ 'metaphor',
79
+ 'style',
32
80
  ],
33
81
  factual: [
34
- 'what is', 'define', 'explain', 'describe', 'list', 'fact', 'information',
35
- 'history', 'science', 'data', 'statistic', 'research', 'study', 'source',
36
- 'reference', 'accurate', 'true', 'correct',
82
+ 'what is',
83
+ 'define',
84
+ 'explain',
85
+ 'describe',
86
+ 'list',
87
+ 'fact',
88
+ 'information',
89
+ 'history',
90
+ 'science',
91
+ 'data',
92
+ 'statistic',
93
+ 'research',
94
+ 'study',
95
+ 'source',
96
+ 'reference',
97
+ 'accurate',
98
+ 'true',
99
+ 'correct',
37
100
  ],
38
101
  conversational: [
39
- 'chat', 'talk', 'hello', 'hi', 'thanks', 'please', 'help', 'assist',
40
- 'question', 'answer', 'discuss', 'conversation', 'opinion',
102
+ 'chat',
103
+ 'talk',
104
+ 'hello',
105
+ 'hi',
106
+ 'thanks',
107
+ 'please',
108
+ 'help',
109
+ 'assist',
110
+ 'question',
111
+ 'answer',
112
+ 'discuss',
113
+ 'conversation',
114
+ 'opinion',
41
115
  ],
42
116
  };
43
117
 
@@ -117,7 +191,8 @@ export class CapabilityAnalyzer {
117
191
  messages: [
118
192
  {
119
193
  role: 'system',
120
- content: 'You are a task analysis expert. Analyze tasks and determine their characteristics.',
194
+ content:
195
+ 'You are a task analysis expert. Analyze tasks and determine their characteristics.',
121
196
  },
122
197
  { role: 'user', content: prompt },
123
198
  ],
@@ -128,7 +203,8 @@ export class CapabilityAnalyzer {
128
203
  messages: [
129
204
  {
130
205
  role: 'system',
131
- content: 'You are a task analysis expert. Analyze tasks and determine their characteristics.',
206
+ content:
207
+ 'You are a task analysis expert. Analyze tasks and determine their characteristics.',
132
208
  },
133
209
  { role: 'user', content: prompt },
134
210
  ],
@@ -139,17 +215,12 @@ export class CapabilityAnalyzer {
139
215
  if (parsed) {
140
216
  return parsed;
141
217
  }
142
- } catch {
143
-
144
- }
218
+ } catch {}
145
219
 
146
220
  return this.analyzeHeuristically(taskDescription, context?.availableTools);
147
221
  }
148
222
 
149
- private analyzeHeuristically(
150
- taskDescription: string,
151
- availableTools?: Tool[]
152
- ): TaskProfile {
223
+ private analyzeHeuristically(taskDescription: string, availableTools?: Tool[]): TaskProfile {
153
224
  const lowerTask = taskDescription.toLowerCase();
154
225
  const words = lowerTask.split(/\s+/);
155
226
  const wordCount = words.length;
@@ -165,7 +236,8 @@ export class CapabilityAnalyzer {
165
236
  requiresTools: toolAnalysis.requiresTools,
166
237
  toolIntensity: toolAnalysis.intensity,
167
238
  reasoningDepth: this.estimateReasoningDepth(complexity, domain),
168
- creativityLevel: domain === 'creative' ? 'high' : complexity === 'trivial' ? 'low' : 'moderate',
239
+ creativityLevel:
240
+ domain === 'creative' ? 'high' : complexity === 'trivial' ? 'low' : 'moderate',
169
241
  accuracyRequirement: this.estimateAccuracyRequirement(domain, lowerTask),
170
242
  timeConstraint: this.detectTimeConstraint(lowerTask),
171
243
  };
@@ -214,8 +286,17 @@ export class CapabilityAnalyzer {
214
286
  availableTools?: Tool[]
215
287
  ): { requiresTools: boolean; intensity: TaskProfile['toolIntensity'] } {
216
288
  const toolIndicators = [
217
- 'calculate', 'search', 'fetch', 'query', 'lookup', 'find',
218
- 'execute', 'run', 'call', 'invoke', 'use tool',
289
+ 'calculate',
290
+ 'search',
291
+ 'fetch',
292
+ 'query',
293
+ 'lookup',
294
+ 'find',
295
+ 'execute',
296
+ 'run',
297
+ 'call',
298
+ 'invoke',
299
+ 'use tool',
219
300
  ];
220
301
 
221
302
  let toolMentions = 0;
@@ -255,10 +336,7 @@ export class CapabilityAnalyzer {
255
336
  expert: 15,
256
337
  };
257
338
 
258
- return Math.min(
259
- wordCount * baseMultiplier[complexity] + 200,
260
- 32000
261
- );
339
+ return Math.min(wordCount * baseMultiplier[complexity] + 200, 32000);
262
340
  }
263
341
 
264
342
  private estimateReasoningDepth(
@@ -266,7 +344,11 @@ export class CapabilityAnalyzer {
266
344
  domain: TaskProfile['domain']
267
345
  ): TaskProfile['reasoningDepth'] {
268
346
  if (domain === 'reasoning') {
269
- return complexity === 'trivial' ? 'moderate' : complexity === 'simple' ? 'deep' : 'exhaustive';
347
+ return complexity === 'trivial'
348
+ ? 'moderate'
349
+ : complexity === 'simple'
350
+ ? 'deep'
351
+ : 'exhaustive';
270
352
  }
271
353
 
272
354
  switch (complexity) {
@@ -1,4 +1,7 @@
1
- import type { EvolutionCandidate, EvolutionStrategy as IEvolutionStrategy } from '@cogitator-ai/types';
1
+ import type {
2
+ EvolutionCandidate,
3
+ EvolutionStrategy as IEvolutionStrategy,
4
+ } from '@cogitator-ai/types';
2
5
 
3
6
  export interface EvolutionStrategyOptions {
4
7
  strategy: IEvolutionStrategy;
@@ -93,7 +96,8 @@ export class EvolutionStrategy {
93
96
  }
94
97
 
95
98
  const exploitation = candidate.score;
96
- const exploration = c * Math.sqrt(Math.log(this.totalSelections + 1) / candidate.evaluationCount);
99
+ const exploration =
100
+ c * Math.sqrt(Math.log(this.totalSelections + 1) / candidate.evaluationCount);
97
101
  const ucb = exploitation + exploration;
98
102
 
99
103
  return { candidate, ucb, isExploration: exploration > exploitation };
@@ -105,20 +109,19 @@ export class EvolutionStrategy {
105
109
  candidate: best.candidate,
106
110
  score: best.ucb === Infinity ? 0 : best.ucb,
107
111
  isExploration: best.isExploration,
108
- reasoning: best.ucb === Infinity
109
- ? `UCB: selected unexplored candidate ${best.candidate.id}`
110
- : `UCB: selected ${best.candidate.id} with UCB score ${best.ucb.toFixed(3)} (base: ${best.candidate.score.toFixed(3)}, exploration bonus)`,
112
+ reasoning:
113
+ best.ucb === Infinity
114
+ ? `UCB: selected unexplored candidate ${best.candidate.id}`
115
+ : `UCB: selected ${best.candidate.id} with UCB score ${best.ucb.toFixed(3)} (base: ${best.candidate.score.toFixed(3)}, exploration bonus)`,
111
116
  };
112
117
  }
113
118
 
114
119
  private thompsonSampling(candidates: EvolutionCandidate[]): SelectionResult {
115
120
  const samples = candidates.map((candidate) => {
116
- const alpha = candidate.evaluationCount > 0
117
- ? candidate.score * candidate.evaluationCount + 1
118
- : 1;
119
- const beta = candidate.evaluationCount > 0
120
- ? (1 - candidate.score) * candidate.evaluationCount + 1
121
- : 1;
121
+ const alpha =
122
+ candidate.evaluationCount > 0 ? candidate.score * candidate.evaluationCount + 1 : 1;
123
+ const beta =
124
+ candidate.evaluationCount > 0 ? (1 - candidate.score) * candidate.evaluationCount + 1 : 1;
122
125
 
123
126
  const sample = this.sampleBeta(alpha, beta);
124
127
 
@@ -193,7 +196,10 @@ export class EvolutionStrategy {
193
196
  case 'epsilon_greedy':
194
197
  return this.strategy.epsilon ?? 0.1;
195
198
  case 'ucb':
196
- return Math.min(1, (this.strategy.explorationConstant ?? 2) / Math.sqrt(this.totalSelections));
199
+ return Math.min(
200
+ 1,
201
+ (this.strategy.explorationConstant ?? 2) / Math.sqrt(this.totalSelections)
202
+ );
197
203
  case 'thompson_sampling':
198
204
  return 0.5;
199
205
  default:
@@ -205,7 +211,8 @@ export class EvolutionStrategy {
205
211
  const unexploredCount = candidates.filter((c) => c.evaluationCount === 0).length;
206
212
  if (unexploredCount > 0) return true;
207
213
 
208
- const avgEvaluations = candidates.reduce((sum, c) => sum + c.evaluationCount, 0) / candidates.length;
214
+ const avgEvaluations =
215
+ candidates.reduce((sum, c) => sum + c.evaluationCount, 0) / candidates.length;
209
216
  if (avgEvaluations < 5) return true;
210
217
 
211
218
  const scores = candidates.map((c) => c.score);
@@ -1,7 +1,4 @@
1
- export {
2
- CapabilityAnalyzer,
3
- type CapabilityAnalyzerOptions,
4
- } from './capability-analyzer';
1
+ export { CapabilityAnalyzer, type CapabilityAnalyzerOptions } from './capability-analyzer';
5
2
 
6
3
  export {
7
4
  EvolutionStrategy,
@@ -133,13 +133,16 @@ export class ParameterOptimizer {
133
133
  );
134
134
 
135
135
  try {
136
- const response = await this.callLLM([
137
- {
138
- role: 'system',
139
- content: 'You are an AI architecture optimizer. Generate candidate configurations.',
140
- },
141
- { role: 'user', content: prompt },
142
- ], 0.5);
136
+ const response = await this.callLLM(
137
+ [
138
+ {
139
+ role: 'system',
140
+ content: 'You are an AI architecture optimizer. Generate candidate configurations.',
141
+ },
142
+ { role: 'user', content: prompt },
143
+ ],
144
+ 0.5
145
+ );
143
146
 
144
147
  const generated = parseCandidateGenerationResponse(response.content);
145
148
 
@@ -239,7 +242,10 @@ export class ParameterOptimizer {
239
242
  const mutationRate = 0.3;
240
243
 
241
244
  if (Math.random() < mutationRate && mutated.temperature !== undefined) {
242
- mutated.temperature = Math.max(0, Math.min(2, mutated.temperature + (Math.random() - 0.5) * 0.3));
245
+ mutated.temperature = Math.max(
246
+ 0,
247
+ Math.min(2, mutated.temperature + (Math.random() - 0.5) * 0.3)
248
+ );
243
249
  }
244
250
 
245
251
  if (Math.random() < mutationRate && mutated.maxTokens !== undefined) {
@@ -248,7 +254,10 @@ export class ParameterOptimizer {
248
254
  }
249
255
 
250
256
  if (Math.random() < mutationRate && mutated.reflectionDepth !== undefined) {
251
- mutated.reflectionDepth = Math.max(0, Math.min(5, mutated.reflectionDepth + Math.round(Math.random() * 2 - 1)));
257
+ mutated.reflectionDepth = Math.max(
258
+ 0,
259
+ Math.min(5, mutated.reflectionDepth + Math.round(Math.random() * 2 - 1))
260
+ );
252
261
  }
253
262
 
254
263
  return mutated;
@@ -324,7 +333,10 @@ export class ParameterOptimizer {
324
333
 
325
334
  private getRelevantHistory(profile: TaskProfile): HistoricalRecord[] {
326
335
  return this.history
327
- .filter((h) => h.taskProfile.domain === profile.domain || h.taskProfile.complexity === profile.complexity)
336
+ .filter(
337
+ (h) =>
338
+ h.taskProfile.domain === profile.domain || h.taskProfile.complexity === profile.complexity
339
+ )
328
340
  .slice(-10);
329
341
  }
330
342
 
@@ -435,15 +447,19 @@ export class ParameterOptimizer {
435
447
  if (evaluatedCandidates.length === 0) return null;
436
448
 
437
449
  const results = evaluatedCandidates.map((c) => {
438
- const records = this.history.filter((h) => JSON.stringify(h.config) === JSON.stringify(c.config));
439
- const avgMetrics = records.length > 0
440
- ? {
441
- successRate: records.reduce((s, r) => s + r.metrics.successRate, 0) / records.length,
442
- avgLatency: records.reduce((s, r) => s + r.metrics.latency, 0) / records.length,
443
- avgTokens: records.reduce((s, r) => s + r.metrics.tokenUsage, 0) / records.length,
444
- qualityScore: records.reduce((s, r) => s + r.metrics.qualityScore, 0) / records.length,
445
- }
446
- : { successRate: 0, avgLatency: 0, avgTokens: 0, qualityScore: 0 };
450
+ const records = this.history.filter(
451
+ (h) => JSON.stringify(h.config) === JSON.stringify(c.config)
452
+ );
453
+ const avgMetrics =
454
+ records.length > 0
455
+ ? {
456
+ successRate: records.reduce((s, r) => s + r.metrics.successRate, 0) / records.length,
457
+ avgLatency: records.reduce((s, r) => s + r.metrics.latency, 0) / records.length,
458
+ avgTokens: records.reduce((s, r) => s + r.metrics.tokenUsage, 0) / records.length,
459
+ qualityScore:
460
+ records.reduce((s, r) => s + r.metrics.qualityScore, 0) / records.length,
461
+ }
462
+ : { successRate: 0, avgLatency: 0, avgTokens: 0, qualityScore: 0 };
447
463
 
448
464
  return { candidateId: c.id, metrics: avgMetrics };
449
465
  });
@@ -451,10 +467,13 @@ export class ParameterOptimizer {
451
467
  const prompt = buildPerformanceAnalysisPrompt(evaluatedCandidates, results);
452
468
 
453
469
  try {
454
- const response = await this.callLLM([
455
- { role: 'system', content: 'You are an AI performance analyst.' },
456
- { role: 'user', content: prompt },
457
- ], 0.2);
470
+ const response = await this.callLLM(
471
+ [
472
+ { role: 'system', content: 'You are an AI performance analyst.' },
473
+ { role: 'user', content: prompt },
474
+ ],
475
+ 0.2
476
+ );
458
477
 
459
478
  return parsePerformanceAnalysisResponse(response.content);
460
479
  } catch {
@@ -63,12 +63,12 @@ export function buildCandidateGenerationPrompt(
63
63
  ? `
64
64
  HISTORICAL PERFORMANCE:
65
65
  ${historicalPerformance
66
- .slice(-5)
67
- .map(
68
- (h, i) =>
69
- `${i + 1}. Config: ${JSON.stringify(h.config)} → Score: ${h.score.toFixed(2)}, Metrics: ${JSON.stringify(h.metrics)}`
70
- )
71
- .join('\n')}`
66
+ .slice(-5)
67
+ .map(
68
+ (h, i) =>
69
+ `${i + 1}. Config: ${JSON.stringify(h.config)} → Score: ${h.score.toFixed(2)}, Metrics: ${JSON.stringify(h.metrics)}`
70
+ )
71
+ .join('\n')}`
72
72
  : '';
73
73
 
74
74
  return `Generate candidate configurations for architecture evolution.
@@ -118,15 +118,15 @@ export function buildPerformanceAnalysisPrompt(
118
118
 
119
119
  CANDIDATES AND RESULTS:
120
120
  ${candidates
121
- .map((c) => {
122
- const result = results.find((r) => r.candidateId === c.id);
123
- return `
121
+ .map((c) => {
122
+ const result = results.find((r) => r.candidateId === c.id);
123
+ return `
124
124
  ${c.id}:
125
125
  Config: ${JSON.stringify(c.config)}
126
126
  Reasoning: ${c.reasoning}
127
127
  ${result ? `Results: ${JSON.stringify(result.metrics)}` : 'Not yet tested'}`;
128
- })
129
- .join('\n')}
128
+ })
129
+ .join('\n')}
130
130
 
131
131
  Respond with:
132
132
  {
@@ -162,9 +162,7 @@ export function parseTaskProfileResponse(response: string): TaskProfile | null {
162
162
  }
163
163
  }
164
164
 
165
- export function parseCandidateGenerationResponse(
166
- response: string
167
- ): EvolutionCandidate[] {
165
+ export function parseCandidateGenerationResponse(response: string): EvolutionCandidate[] {
168
166
  const jsonMatch = response.match(/\[[\s\S]*\]/);
169
167
  if (!jsonMatch) return [];
170
168
 
@@ -178,7 +176,8 @@ export function parseCandidateGenerationResponse(
178
176
  id: String(c.id || `candidate_${idx}`),
179
177
  config: c.config as Partial<ArchitectureConfig>,
180
178
  reasoning: String(c.reasoning || ''),
181
- expectedImprovement: typeof c.expectedImprovement === 'number' ? c.expectedImprovement : 0.5,
179
+ expectedImprovement:
180
+ typeof c.expectedImprovement === 'number' ? c.expectedImprovement : 0.5,
182
181
  risk: (['low', 'medium', 'high'].includes(String(c.risk)) ? c.risk : 'medium') as
183
182
  | 'low'
184
183
  | 'medium'
@@ -17,7 +17,4 @@ export {
17
17
  type CheckpointDiff,
18
18
  } from './rollback-manager';
19
19
 
20
- export {
21
- ModificationValidator,
22
- type ModificationValidatorOptions,
23
- } from './modification-validator';
20
+ export { ModificationValidator, type ModificationValidatorOptions } from './modification-validator';
@@ -21,10 +21,7 @@ export class ModificationValidator {
21
21
  private strictMode: boolean;
22
22
 
23
23
  constructor(options: ModificationValidatorOptions = {}) {
24
- this.constraints = mergeConstraints(
25
- createDefaultConstraints(),
26
- options.constraints ?? {}
27
- );
24
+ this.constraints = mergeConstraints(createDefaultConstraints(), options.constraints ?? {});
28
25
  this.strictMode = options.strictMode ?? false;
29
26
  }
30
27
 
@@ -55,12 +52,8 @@ export class ModificationValidator {
55
52
  }
56
53
  }
57
54
 
58
- const hasCriticalViolation = results.some(
59
- (r) => !r.satisfied && r.severity === 'critical'
60
- );
61
- const hasErrorViolation = results.some(
62
- (r) => !r.satisfied && r.severity === 'error'
63
- );
55
+ const hasCriticalViolation = results.some((r) => !r.satisfied && r.severity === 'critical');
56
+ const hasErrorViolation = results.some((r) => !r.satisfied && r.severity === 'error');
64
57
 
65
58
  const valid = this.strictMode
66
59
  ? results.every((r) => r.satisfied)
@@ -146,10 +139,7 @@ export class ModificationValidator {
146
139
  return result;
147
140
  }
148
141
 
149
- private evaluateSimpleCondition(
150
- condition: string,
151
- context: Record<string, unknown>
152
- ): boolean {
142
+ private evaluateSimpleCondition(condition: string, context: Record<string, unknown>): boolean {
153
143
  const operators = ['<=', '>=', '<', '>', '!=', '='];
154
144
  for (const op of operators) {
155
145
  const idx = condition.indexOf(op);
@@ -216,10 +206,7 @@ export class ModificationValidator {
216
206
  if (constraint.forbidden?.includes(payload.category)) {
217
207
  satisfied = false;
218
208
  message = `Category '${payload.category}' is forbidden`;
219
- } else if (
220
- constraint.allowed?.length &&
221
- !constraint.allowed.includes(payload.category)
222
- ) {
209
+ } else if (constraint.allowed?.length && !constraint.allowed.includes(payload.category)) {
223
210
  satisfied = false;
224
211
  message = `Category '${payload.category}' is not in allowed list`;
225
212
  }
@@ -156,9 +156,7 @@ export class RollbackManager {
156
156
  const toolsRemoved = [...toolsA].filter((t) => !toolsB.has(t));
157
157
 
158
158
  const modsBefore = new Set(checkpointA.modifications.map((m) => m.id));
159
- const modificationsApplied = checkpointB.modifications.filter(
160
- (m) => !modsBefore.has(m.id)
161
- );
159
+ const modificationsApplied = checkpointB.modifications.filter((m) => !modsBefore.has(m.id));
162
160
 
163
161
  return { configChanges, toolsAdded, toolsRemoved, modificationsApplied };
164
162
  }
@@ -89,9 +89,7 @@ export function mergeConstraints(
89
89
  additions: Partial<ModificationConstraints>
90
90
  ): ModificationConstraints {
91
91
  return {
92
- safety: additions.safety
93
- ? mergeSafetyConstraints(base.safety, additions.safety)
94
- : base.safety,
92
+ safety: additions.safety ? mergeSafetyConstraints(base.safety, additions.safety) : base.safety,
95
93
  capability: additions.capability
96
94
  ? mergeCapabilityConstraints(base.capability, additions.capability)
97
95
  : base.capability,
package/src/index.ts CHANGED
@@ -1,4 +1,8 @@
1
- export { SelfModifyingAgent, type SelfModifyingAgentOptions, type RunContext } from './self-modifying-agent';
1
+ export {
2
+ SelfModifyingAgent,
3
+ type SelfModifyingAgentOptions,
4
+ type RunContext,
5
+ } from './self-modifying-agent';
2
6
 
3
7
  export {
4
8
  GapAnalyzer,
@@ -69,10 +73,7 @@ export {
69
73
  type CheckpointDiff,
70
74
  } from './constraints';
71
75
 
72
- export {
73
- SelfModifyingEventEmitter,
74
- type SelfModifyingEventHandler,
75
- } from './events';
76
+ export { SelfModifyingEventEmitter, type SelfModifyingEventHandler } from './events';
76
77
 
77
78
  export type {
78
79
  SelfModifyingConfig,
@@ -14,7 +14,11 @@ import type {
14
14
  MetaOpportunity,
15
15
  } from '@cogitator-ai/types';
16
16
  import { DEFAULT_META_REASONING_CONFIG } from '@cogitator-ai/types';
17
- import { ObservationCollector, type ActionRecord, type ObservationContext } from './observation-collector';
17
+ import {
18
+ ObservationCollector,
19
+ type ActionRecord,
20
+ type ObservationContext,
21
+ } from './observation-collector';
18
22
  import { StrategySelector } from './strategy-selector';
19
23
  import {
20
24
  buildMetaAssessmentPrompt,
@@ -98,8 +102,7 @@ export class MetaReasoner {
98
102
  switch (trigger) {
99
103
  case 'iteration_complete':
100
104
  return (
101
- context.iteration > 0 &&
102
- context.iteration % this.config.triggerAfterIterations === 0
105
+ context.iteration > 0 && context.iteration % this.config.triggerAfterIterations === 0
103
106
  );
104
107
 
105
108
  case 'confidence_drop':
@@ -235,10 +238,7 @@ export class MetaReasoner {
235
238
 
236
239
  switch (recommendation.action) {
237
240
  case 'switch_mode':
238
- if (
239
- recommendation.newMode &&
240
- this.config.allowedModes.includes(recommendation.newMode)
241
- ) {
241
+ if (recommendation.newMode && this.config.allowedModes.includes(recommendation.newMode)) {
242
242
  newConfig = this.getModeConfig(recommendation.newMode);
243
243
  adaptationType = 'mode_switch';
244
244
  this.currentMode.set(runId, recommendation.newMode);
@@ -290,10 +290,7 @@ export class MetaReasoner {
290
290
  return null;
291
291
  }
292
292
 
293
- if (
294
- lastAdaptation.rollbackDeadline &&
295
- Date.now() > lastAdaptation.rollbackDeadline
296
- ) {
293
+ if (lastAdaptation.rollbackDeadline && Date.now() > lastAdaptation.rollbackDeadline) {
297
294
  return null;
298
295
  }
299
296
 
@@ -328,11 +325,7 @@ export class MetaReasoner {
328
325
  if (adaptation) {
329
326
  adaptation.outcome = outcome;
330
327
 
331
- if (
332
- this.config.rollbackOnDecline &&
333
- !outcome.improved &&
334
- adaptation.rollbackable
335
- ) {
328
+ if (this.config.rollbackOnDecline && !outcome.improved && adaptation.rollbackable) {
336
329
  this.rollback(runId);
337
330
  }
338
331
  }
@@ -1,8 +1,4 @@
1
- import type {
2
- MetaObservation,
3
- ReasoningMode,
4
- Insight,
5
- } from '@cogitator-ai/types';
1
+ import type { MetaObservation, ReasoningMode, Insight } from '@cogitator-ai/types';
6
2
 
7
3
  export interface ActionRecord {
8
4
  type: string;
@@ -56,10 +52,7 @@ export class ObservationCollector {
56
52
  }
57
53
  }
58
54
 
59
- collect(
60
- context: ObservationContext,
61
- insights: Insight[]
62
- ): MetaObservation {
55
+ collect(context: ObservationContext, insights: Insight[]): MetaObservation {
63
56
  const { runId, iteration, goal, currentMode } = context;
64
57
  const prevObservations = this.observations.get(runId) ?? [];
65
58
  const lastObs = prevObservations[prevObservations.length - 1];
@@ -69,9 +62,7 @@ export class ObservationCollector {
69
62
  const currentConfidence = confidenceHist[confidenceHist.length - 1] ?? 0.5;
70
63
  const progressScore = this.calculateProgress(actions);
71
64
  const progressDelta = lastObs ? progressScore - lastObs.progressScore : 0;
72
- const stagnationCount = progressDelta < 0.05
73
- ? (lastObs?.stagnationCount ?? 0) + 1
74
- : 0;
65
+ const stagnationCount = progressDelta < 0.05 ? (lastObs?.stagnationCount ?? 0) + 1 : 0;
75
66
  const repetitionScore = this.calculateRepetition(actions);
76
67
  const toolSuccessRate = this.calculateToolSuccessRate(actions);
77
68
  const confidenceTrend = this.calculateTrend(confidenceHist);