@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
package/README.md ADDED
@@ -0,0 +1,714 @@
1
+ # @cogitator-ai/self-modifying
2
+
3
+ Self-modifying agents for Cogitator. Agents that evolve at runtime — generating new tools, adapting reasoning strategies, and optimizing their own architecture.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @cogitator-ai/self-modifying
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { Cogitator, Agent } from '@cogitator-ai/core';
15
+ import { SelfModifyingAgent } from '@cogitator-ai/self-modifying';
16
+
17
+ const cogitator = new Cogitator({ defaultModel: 'gpt-4o' });
18
+ const agent = new Agent({
19
+ name: 'adaptive-assistant',
20
+ instructions: 'Solve problems adaptively.',
21
+ });
22
+
23
+ const selfModifying = new SelfModifyingAgent({
24
+ agent,
25
+ llm: cogitator.getDefaultBackend(),
26
+ config: {
27
+ toolGeneration: { enabled: true, autoGenerate: true },
28
+ metaReasoning: { enabled: true },
29
+ architectureEvolution: { enabled: true },
30
+ constraints: { enabled: true, autoRollback: true },
31
+ },
32
+ });
33
+
34
+ const result = await selfModifying.run('Analyze this CSV and visualize trends');
35
+
36
+ console.log('Output:', result.output);
37
+ console.log('Tools generated:', result.toolsGenerated.length);
38
+ console.log('Adaptations made:', result.adaptationsMade.length);
39
+ ```
40
+
41
+ ## Features
42
+
43
+ - **Tool Self-Generation** — Detects missing capabilities and synthesizes new tools at runtime
44
+ - **Meta-Reasoning** — Monitors reasoning process and switches between modes (analytical, creative, systematic)
45
+ - **Architecture Evolution** — Optimizes model, temperature, tool strategy using multi-armed bandits
46
+ - **Constraint Validation** — Safety checks prevent unsafe modifications
47
+ - **Rollback System** — Checkpoint before changes, auto-revert on performance decline
48
+ - **Event System** — Subscribe to all self-modification events for observability
49
+
50
+ ---
51
+
52
+ ## Tool Self-Generation
53
+
54
+ When the agent encounters a task requiring capabilities it doesn't have, it can generate new tools at runtime.
55
+
56
+ ### How It Works
57
+
58
+ 1. **Gap Analysis** — LLM compares user intent with available tools, identifies missing capabilities
59
+ 2. **Code Synthesis** — Generates safe TypeScript tool implementation
60
+ 3. **Validation** — Security scanning + correctness testing in sandbox
61
+ 4. **Registration** — Valid tools are added to the agent's toolkit
62
+
63
+ ### Configuration
64
+
65
+ ```typescript
66
+ const selfModifying = new SelfModifyingAgent({
67
+ agent,
68
+ llm,
69
+ config: {
70
+ toolGeneration: {
71
+ enabled: true,
72
+ autoGenerate: true, // Auto-create tools when gaps detected
73
+ maxToolsPerSession: 3, // Limit tools per run
74
+ minConfidenceForGeneration: 0.7, // Threshold for generating
75
+ maxIterationsPerTool: 3, // Max refinement attempts
76
+ requireLLMValidation: true, // LLM validates generated code
77
+ sandboxConfig: {
78
+ enabled: true,
79
+ maxExecutionTime: 5000, // 5s timeout
80
+ maxMemory: 50 * 1024 * 1024, // 50MB limit
81
+ allowedModules: [], // No external modules
82
+ isolationLevel: 'strict',
83
+ },
84
+ },
85
+ },
86
+ });
87
+ ```
88
+
89
+ ### Manual Tool Generation
90
+
91
+ ```typescript
92
+ import { GapAnalyzer, ToolGenerator } from '@cogitator-ai/self-modifying';
93
+
94
+ const gapAnalyzer = new GapAnalyzer({ llm, config: toolGenConfig });
95
+ const toolGenerator = new ToolGenerator({ llm, config: toolGenConfig });
96
+
97
+ // Analyze what's missing
98
+ const analysis = await gapAnalyzer.analyze(
99
+ 'Calculate compound interest over 10 years',
100
+ existingTools
101
+ );
102
+
103
+ console.log('Gaps found:', analysis.gaps.length);
104
+
105
+ // Generate tool for each gap
106
+ for (const gap of analysis.gaps) {
107
+ const result = await toolGenerator.generate(gap, existingTools);
108
+ if (result.success && result.tool) {
109
+ console.log('Generated:', result.tool.name);
110
+ }
111
+ }
112
+ ```
113
+
114
+ ### Generated Tool Store
115
+
116
+ ```typescript
117
+ import { InMemoryGeneratedToolStore } from '@cogitator-ai/self-modifying';
118
+
119
+ const store = new InMemoryGeneratedToolStore();
120
+
121
+ // Save generated tool
122
+ await store.save(generatedTool);
123
+
124
+ // Record usage for learning
125
+ await store.recordUsage({
126
+ toolId: tool.id,
127
+ timestamp: new Date(),
128
+ success: true,
129
+ executionTime: 150,
130
+ });
131
+
132
+ // List active tools
133
+ const tools = await store.list({ status: 'active' });
134
+
135
+ // Find similar tools
136
+ const similar = await store.findSimilar('calculate interest');
137
+ ```
138
+
139
+ ---
140
+
141
+ ## Meta-Reasoning
142
+
143
+ The meta-reasoning layer monitors the agent's reasoning process and makes strategic adjustments.
144
+
145
+ ### Reasoning Modes
146
+
147
+ | Mode | Temperature | Use Case |
148
+ | ------------ | ----------- | ------------------------------- |
149
+ | `analytical` | 0.3 | Logical analysis, debugging |
150
+ | `creative` | 0.9 | Brainstorming, ideation |
151
+ | `systematic` | 0.2 | Step-by-step procedures |
152
+ | `intuitive` | 0.6 | Quick decisions, heuristics |
153
+ | `reflective` | 0.4 | Self-assessment, learning |
154
+ | `exploratory`| 0.7 | Open-ended exploration |
155
+
156
+ ### Configuration
157
+
158
+ ```typescript
159
+ const selfModifying = new SelfModifyingAgent({
160
+ agent,
161
+ llm,
162
+ config: {
163
+ metaReasoning: {
164
+ enabled: true,
165
+ defaultMode: 'analytical',
166
+ allowedModes: ['analytical', 'creative', 'systematic', 'intuitive', 'reflective', 'exploratory'],
167
+ modeProfiles: {
168
+ analytical: { mode: 'analytical', temperature: 0.3, depth: 3 },
169
+ creative: { mode: 'creative', temperature: 0.9, depth: 2 },
170
+ // ... other modes
171
+ },
172
+ maxMetaAssessments: 5, // Max assessments per run
173
+ maxAdaptations: 3, // Max mode switches per run
174
+ metaAssessmentCooldown: 10000, // 10s between assessments
175
+ adaptationCooldown: 15000, // 15s between adaptations
176
+ triggers: ['on_failure', 'on_low_confidence', 'periodic'],
177
+ triggerAfterIterations: 3, // Assess every 3 iterations
178
+ triggerOnConfidenceDrop: 0.3, // Assess if confidence < 30%
179
+ triggerOnProgressStall: 2, // Assess after 2 stalled iterations
180
+ minConfidenceToAdapt: 0.6, // Min confidence to apply change
181
+ enableRollback: true,
182
+ rollbackWindow: 30000, // 30s rollback window
183
+ rollbackOnDecline: true, // Auto-rollback if metrics decline
184
+ },
185
+ },
186
+ });
187
+ ```
188
+
189
+ ### Meta-Reasoning Process
190
+
191
+ 1. **Observation** — Collect metrics (progress, confidence, tokens, time)
192
+ 2. **Assessment** — LLM analyzes if reasoning is on-track
193
+ 3. **Adaptation** — Switch mode or adjust parameters if needed
194
+ 4. **Rollback** — Revert if metrics decline after adaptation
195
+
196
+ ### Direct MetaReasoner Usage
197
+
198
+ ```typescript
199
+ import { MetaReasoner } from '@cogitator-ai/self-modifying';
200
+
201
+ const metaReasoner = new MetaReasoner({
202
+ llm,
203
+ model: 'gpt-4o',
204
+ config: metaReasoningConfig,
205
+ });
206
+
207
+ // Initialize run
208
+ const modeConfig = metaReasoner.initializeRun(runId);
209
+
210
+ // Observe current state
211
+ const observation = metaReasoner.observe(
212
+ {
213
+ runId,
214
+ iteration: 3,
215
+ goal: 'Analyze data',
216
+ currentMode: 'analytical',
217
+ tokensUsed: 1500,
218
+ timeElapsed: 5000,
219
+ iterationsRemaining: 7,
220
+ budgetRemaining: 8500,
221
+ },
222
+ insights
223
+ );
224
+
225
+ // Assess if on-track
226
+ const assessment = await metaReasoner.assess(observation);
227
+
228
+ console.log('On track:', assessment.onTrack);
229
+ console.log('Issues:', assessment.issues);
230
+ console.log('Recommendation:', assessment.recommendation);
231
+
232
+ // Apply adaptation if needed
233
+ if (assessment.requiresAdaptation) {
234
+ const adaptation = await metaReasoner.adapt(runId, assessment);
235
+ console.log('Switched to:', adaptation?.after?.mode);
236
+ }
237
+
238
+ // Rollback if needed
239
+ const rollback = metaReasoner.rollback(runId);
240
+ ```
241
+
242
+ ---
243
+
244
+ ## Architecture Evolution
245
+
246
+ Optimizes agent parameters (model, temperature, tool strategy) using multi-armed bandit algorithms.
247
+
248
+ ### Strategies
249
+
250
+ | Strategy | Description |
251
+ | ----------------- | ---------------------------------------------- |
252
+ | `ucb` | Upper Confidence Bound — balanced exploration |
253
+ | `thompson` | Thompson Sampling — probabilistic selection |
254
+ | `epsilon_greedy` | Epsilon-Greedy — random exploration with decay |
255
+
256
+ ### Configuration
257
+
258
+ ```typescript
259
+ const selfModifying = new SelfModifyingAgent({
260
+ agent,
261
+ llm,
262
+ config: {
263
+ architectureEvolution: {
264
+ enabled: true,
265
+ strategy: {
266
+ type: 'ucb',
267
+ explorationConstant: 2, // Higher = more exploration
268
+ },
269
+ // Or Thompson sampling:
270
+ // strategy: { type: 'thompson', priorAlpha: 1, priorBeta: 1 },
271
+ // Or epsilon-greedy:
272
+ // strategy: { type: 'epsilon_greedy', epsilon: 0.1, decayRate: 0.99 },
273
+
274
+ maxCandidates: 10, // Max configs to track
275
+ evaluationWindow: 10, // Runs to consider for metrics
276
+ minEvaluationsBeforeEvolution: 3, // Min runs before switching
277
+ adaptationThreshold: 0.1, // Min improvement to switch
278
+ },
279
+ },
280
+ });
281
+ ```
282
+
283
+ ### Parameter Optimizer
284
+
285
+ ```typescript
286
+ import { ParameterOptimizer } from '@cogitator-ai/self-modifying';
287
+
288
+ const optimizer = new ParameterOptimizer({
289
+ llm,
290
+ config: evolutionConfig,
291
+ baseConfig: {
292
+ model: 'gpt-4o',
293
+ temperature: 0.7,
294
+ maxTokens: 4096,
295
+ toolStrategy: 'sequential',
296
+ reflectionDepth: 1,
297
+ },
298
+ });
299
+
300
+ // Optimize for a task
301
+ const result = await optimizer.optimize('Complex reasoning task');
302
+
303
+ console.log('Should adopt:', result.shouldAdopt);
304
+ console.log('Confidence:', result.confidence);
305
+ console.log('Recommended config:', result.recommendedConfig);
306
+ console.log('Reasoning:', result.reasoning);
307
+
308
+ // Record outcome for learning
309
+ optimizer.recordOutcome(result.candidate!.id, 0.85);
310
+ ```
311
+
312
+ ### Capability Analyzer
313
+
314
+ ```typescript
315
+ import { CapabilityAnalyzer } from '@cogitator-ai/self-modifying';
316
+
317
+ const analyzer = new CapabilityAnalyzer({
318
+ llm,
319
+ enableLLMAnalysis: true,
320
+ });
321
+
322
+ const profile = await analyzer.analyze('Build a REST API with authentication');
323
+
324
+ console.log('Complexity:', profile.complexity); // 'complex'
325
+ console.log('Domain:', profile.domain); // 'coding'
326
+ console.log('Tool intensity:', profile.toolIntensity); // 'heavy'
327
+ console.log('Reasoning depth:', profile.reasoningDepth); // 'deep'
328
+ console.log('Estimated tokens:', profile.estimatedTokens);
329
+ ```
330
+
331
+ ---
332
+
333
+ ## Constraints & Safety
334
+
335
+ All self-modifications are validated against safety constraints before being applied.
336
+
337
+ ### Default Constraints
338
+
339
+ ```typescript
340
+ import {
341
+ DEFAULT_SAFETY_CONSTRAINTS,
342
+ DEFAULT_CAPABILITY_CONSTRAINTS,
343
+ DEFAULT_RESOURCE_CONSTRAINTS,
344
+ } from '@cogitator-ai/self-modifying';
345
+
346
+ // Safety: prevent dangerous operations
347
+ // - no_arbitrary_code: Sandbox execution required
348
+ // - max_tool_complexity: Lines of code < 100
349
+ // - no_self_modification_loop: Modification depth < 3
350
+
351
+ // Capability: prevent degradation
352
+ // - min_tool_count: At least 1 tool
353
+ // - max_tool_count: At most 20 tools
354
+ // - required_capabilities: Core capabilities preserved
355
+
356
+ // Resource: prevent runaway costs
357
+ // - max_tokens_per_run: Token budget
358
+ // - max_time_per_run: Time limit
359
+ // - max_cost_per_run: Cost limit
360
+ ```
361
+
362
+ ### Modification Validator
363
+
364
+ ```typescript
365
+ import { ModificationValidator } from '@cogitator-ai/self-modifying';
366
+
367
+ const validator = new ModificationValidator({
368
+ constraints: {
369
+ safety: DEFAULT_SAFETY_CONSTRAINTS,
370
+ capability: DEFAULT_CAPABILITY_CONSTRAINTS,
371
+ resource: DEFAULT_RESOURCE_CONSTRAINTS,
372
+ custom: [
373
+ {
374
+ id: 'no-external-apis',
375
+ name: 'No External APIs',
376
+ check: (mod) => !mod.changes?.usesExternalApi,
377
+ errorMessage: 'External API calls not allowed',
378
+ severity: 'error',
379
+ },
380
+ ],
381
+ },
382
+ });
383
+
384
+ const result = await validator.validate({
385
+ type: 'tool_addition',
386
+ target: 'tools',
387
+ changes: { name: 'new-tool', code: '...' },
388
+ reason: 'User requested capability',
389
+ });
390
+
391
+ console.log('Valid:', result.valid);
392
+ console.log('Warnings:', result.warnings);
393
+ console.log('Errors:', result.errors);
394
+ ```
395
+
396
+ ### Rollback Manager
397
+
398
+ ```typescript
399
+ import { RollbackManager } from '@cogitator-ai/self-modifying';
400
+
401
+ const rollbackManager = new RollbackManager({
402
+ maxCheckpoints: 10,
403
+ });
404
+
405
+ // Create checkpoint before modification
406
+ const checkpoint = await rollbackManager.createCheckpoint(
407
+ agentName,
408
+ agentConfig,
409
+ currentTools,
410
+ modifications
411
+ );
412
+
413
+ console.log('Checkpoint:', checkpoint.id);
414
+
415
+ // Rollback if something goes wrong
416
+ const restored = await rollbackManager.rollbackTo(checkpoint.id);
417
+
418
+ if (restored) {
419
+ console.log('Restored config:', restored.agentConfig);
420
+ console.log('Restored tools:', restored.tools.length);
421
+ }
422
+
423
+ // List checkpoints
424
+ const checkpoints = rollbackManager.listCheckpoints();
425
+ ```
426
+
427
+ ---
428
+
429
+ ## Events
430
+
431
+ Subscribe to self-modification events for observability.
432
+
433
+ ```typescript
434
+ const selfModifying = new SelfModifyingAgent({ agent, llm, config });
435
+
436
+ // Tool generation events
437
+ selfModifying.on('tool_generation_started', (e) => {
438
+ console.log('Generating tool for gap:', e.data.gap.suggestedToolName);
439
+ });
440
+
441
+ selfModifying.on('tool_generation_completed', (e) => {
442
+ console.log('Tool created:', e.data.name, 'success:', e.data.success);
443
+ });
444
+
445
+ // Meta-reasoning events
446
+ selfModifying.on('meta_assessment', (e) => {
447
+ console.log('Assessment:', e.data.assessment.onTrack ? 'on-track' : 'off-track');
448
+ });
449
+
450
+ selfModifying.on('strategy_changed', (e) => {
451
+ console.log(`Mode: ${e.data.previousMode} → ${e.data.newMode}`);
452
+ });
453
+
454
+ // Architecture events
455
+ selfModifying.on('architecture_evolved', (e) => {
456
+ console.log('New config:', e.data.changes);
457
+ });
458
+
459
+ // Checkpoint events
460
+ selfModifying.on('checkpoint_created', (e) => {
461
+ console.log('Checkpoint:', e.data.checkpointId);
462
+ });
463
+
464
+ selfModifying.on('rollback_performed', (e) => {
465
+ console.log('Rolled back to:', e.data.checkpointId);
466
+ });
467
+
468
+ // Run lifecycle
469
+ selfModifying.on('run_started', (e) => {
470
+ console.log('Run started:', e.runId);
471
+ });
472
+
473
+ selfModifying.on('run_completed', (e) => {
474
+ console.log('Run completed:', e.data.success);
475
+ });
476
+ ```
477
+
478
+ ### Event Types
479
+
480
+ | Event | Description |
481
+ | ---------------------------- | ------------------------------- |
482
+ | `run_started` | Self-modifying run started |
483
+ | `run_completed` | Run completed (success/failure) |
484
+ | `tool_generation_started` | Started generating a new tool |
485
+ | `tool_generation_completed` | Tool generation finished |
486
+ | `meta_assessment` | Meta-reasoning assessment made |
487
+ | `strategy_changed` | Reasoning mode switched |
488
+ | `architecture_evolved` | Architecture config changed |
489
+ | `checkpoint_created` | Rollback checkpoint created |
490
+ | `rollback_performed` | Rolled back to checkpoint |
491
+
492
+ ---
493
+
494
+ ## Checkpoints & Rollback
495
+
496
+ Create checkpoints and rollback to safe states.
497
+
498
+ ```typescript
499
+ const selfModifying = new SelfModifyingAgent({ agent, llm, config });
500
+
501
+ // Run with checkpointing
502
+ const result = await selfModifying.run('Complex task...');
503
+
504
+ // Manual checkpoint during run
505
+ selfModifying.on('strategy_changed', async () => {
506
+ const checkpoint = await selfModifying.createCheckpoint();
507
+ console.log('Saved state:', checkpoint?.id);
508
+ });
509
+
510
+ // Rollback to previous state
511
+ const success = await selfModifying.rollbackToCheckpoint(checkpointId);
512
+ console.log('Rollback success:', success);
513
+
514
+ // Get generated tools
515
+ const tools = await selfModifying.getGeneratedTools();
516
+ console.log('Active tools:', tools.length);
517
+
518
+ // Record tool usage for learning
519
+ await selfModifying.recordToolUsage(toolId, true, 150);
520
+ ```
521
+
522
+ ---
523
+
524
+ ## Type Reference
525
+
526
+ ### Core Types
527
+
528
+ ```typescript
529
+ import type {
530
+ SelfModifyingConfig,
531
+ ToolSelfGenerationConfig,
532
+ MetaReasoningConfig,
533
+ ArchitectureEvolutionConfig,
534
+ } from '@cogitator-ai/types';
535
+ ```
536
+
537
+ ### Tool Generation Types
538
+
539
+ ```typescript
540
+ import type {
541
+ CapabilityGap,
542
+ GapAnalysisResult,
543
+ GeneratedTool,
544
+ ToolValidationResult,
545
+ ToolSandboxConfig,
546
+ ToolSandboxResult,
547
+ } from '@cogitator-ai/types';
548
+ ```
549
+
550
+ ### Meta-Reasoning Types
551
+
552
+ ```typescript
553
+ import type {
554
+ ReasoningMode,
555
+ ReasoningModeConfig,
556
+ MetaObservation,
557
+ MetaAssessment,
558
+ MetaAdaptation,
559
+ MetaRecommendation,
560
+ MetaTrigger,
561
+ } from '@cogitator-ai/types';
562
+ ```
563
+
564
+ ### Architecture Evolution Types
565
+
566
+ ```typescript
567
+ import type {
568
+ TaskProfile,
569
+ ArchitectureConfig,
570
+ EvolutionCandidate,
571
+ EvolutionStrategy,
572
+ } from '@cogitator-ai/types';
573
+ ```
574
+
575
+ ### Constraint Types
576
+
577
+ ```typescript
578
+ import type {
579
+ SafetyConstraint,
580
+ CapabilityConstraint,
581
+ ResourceConstraint,
582
+ ModificationConstraints,
583
+ ModificationValidationResult,
584
+ ModificationCheckpoint,
585
+ } from '@cogitator-ai/types';
586
+ ```
587
+
588
+ ### Event Types
589
+
590
+ ```typescript
591
+ import type {
592
+ SelfModifyingEvent,
593
+ SelfModifyingEventType,
594
+ SelfModifyingEventHandler,
595
+ } from '@cogitator-ai/types';
596
+ ```
597
+
598
+ ---
599
+
600
+ ## Examples
601
+
602
+ ### Adaptive Data Analyst
603
+
604
+ ```typescript
605
+ const analyst = new Agent({
606
+ name: 'data-analyst',
607
+ instructions: 'Analyze data and create visualizations.',
608
+ tools: [readFile],
609
+ });
610
+
611
+ const selfModifying = new SelfModifyingAgent({
612
+ agent: analyst,
613
+ llm,
614
+ config: {
615
+ toolGeneration: {
616
+ enabled: true,
617
+ autoGenerate: true,
618
+ maxToolsPerSession: 5,
619
+ },
620
+ metaReasoning: {
621
+ enabled: true,
622
+ defaultMode: 'analytical',
623
+ triggers: ['on_failure', 'periodic'],
624
+ },
625
+ },
626
+ });
627
+
628
+ // Will auto-generate CSV parser, statistics calculator, chart generator as needed
629
+ const result = await selfModifying.run(
630
+ 'Load sales.csv, calculate monthly trends, and create a bar chart'
631
+ );
632
+
633
+ console.log('Generated tools:', result.toolsGenerated.map(t => t.name));
634
+ // ['csv_parser', 'trend_calculator', 'bar_chart_generator']
635
+ ```
636
+
637
+ ### Creative Problem Solver
638
+
639
+ ```typescript
640
+ const solver = new Agent({
641
+ name: 'problem-solver',
642
+ instructions: 'Find creative solutions to complex problems.',
643
+ });
644
+
645
+ const selfModifying = new SelfModifyingAgent({
646
+ agent: solver,
647
+ llm,
648
+ config: {
649
+ metaReasoning: {
650
+ enabled: true,
651
+ defaultMode: 'systematic',
652
+ allowedModes: ['systematic', 'creative', 'analytical'],
653
+ triggerOnProgressStall: 2,
654
+ },
655
+ architectureEvolution: {
656
+ enabled: true,
657
+ strategy: { type: 'thompson' },
658
+ },
659
+ },
660
+ });
661
+
662
+ // Will switch from systematic → creative if stuck
663
+ const result = await selfModifying.run(
664
+ 'Design a novel approach to reduce carbon emissions in cities'
665
+ );
666
+
667
+ console.log('Mode changes:', result.adaptationsMade.length);
668
+ console.log('Final mode:', result.finalConfig.toolStrategy);
669
+ ```
670
+
671
+ ### Safe Code Generator
672
+
673
+ ```typescript
674
+ const coder = new Agent({
675
+ name: 'code-generator',
676
+ instructions: 'Generate safe, tested code.',
677
+ });
678
+
679
+ const selfModifying = new SelfModifyingAgent({
680
+ agent: coder,
681
+ llm,
682
+ config: {
683
+ toolGeneration: {
684
+ enabled: true,
685
+ sandboxConfig: {
686
+ enabled: true,
687
+ maxExecutionTime: 3000,
688
+ isolationLevel: 'strict',
689
+ allowedModules: [],
690
+ },
691
+ },
692
+ constraints: {
693
+ enabled: true,
694
+ autoRollback: true,
695
+ maxModificationsPerRun: 5,
696
+ },
697
+ },
698
+ });
699
+
700
+ // All generated tools are sandboxed and validated
701
+ selfModifying.on('tool_generation_completed', (e) => {
702
+ if (!e.data.success) {
703
+ console.log('Tool rejected:', e.data.error);
704
+ }
705
+ });
706
+
707
+ const result = await selfModifying.run('Create a utility to parse JSON safely');
708
+ ```
709
+
710
+ ---
711
+
712
+ ## License
713
+
714
+ MIT