@baselineos/autonomy 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.
@@ -0,0 +1,600 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Types & Interfaces
5
+ // ---------------------------------------------------------------------------
6
+
7
+ export type MigrationMode = 'parallel' | 'progressive' | 'full';
8
+
9
+ export interface IntegrationPoint {
10
+ layer: string;
11
+ purpose: string;
12
+ integration: string;
13
+ status: string;
14
+ }
15
+
16
+ export interface MigrationComponentStatus {
17
+ component: string;
18
+ currentStatus: string;
19
+ targetStatus: string;
20
+ migrationProgress: number;
21
+ dependencies: string[];
22
+ estimatedCompletion: string;
23
+ }
24
+
25
+ export interface ComparisonResult {
26
+ timestamp: Date;
27
+ legacyResult: string;
28
+ newResult: string;
29
+ quality: Record<string, unknown>;
30
+ performance: Record<string, unknown>;
31
+ recommendation: string | null;
32
+ }
33
+
34
+ export interface IntegrationStatus {
35
+ migrationMode: MigrationMode;
36
+ integrationPoints: IntegrationPoint[];
37
+ migrationStatus: MigrationComponentStatus[];
38
+ comparisonHistory: ComparisonResult[];
39
+ statistics: {
40
+ totalComparisons: number;
41
+ averageQualityImprovement: number;
42
+ averagePerformanceImprovement: number;
43
+ recommendationsForNew: number;
44
+ recommendationsForLegacy: number;
45
+ };
46
+ }
47
+
48
+ export interface MigrationRecommendation {
49
+ component: string;
50
+ currentStatus: string;
51
+ recommendation: string;
52
+ priority: number;
53
+ reason: string;
54
+ }
55
+
56
+ // ---------------------------------------------------------------------------
57
+ // BaselineAutonomyIntegration
58
+ // ---------------------------------------------------------------------------
59
+
60
+ export class BaselineAutonomyIntegration extends EventEmitter {
61
+ private migrationMode: MigrationMode;
62
+ private integrationPoints: Map<string, IntegrationPoint>;
63
+ private migrationStatus: Map<string, MigrationComponentStatus>;
64
+ private comparisonHistory: ComparisonResult[];
65
+ private autonomySystem: unknown;
66
+
67
+ constructor(autonomySystem: unknown) {
68
+ super();
69
+ this.autonomySystem = autonomySystem;
70
+ this.migrationMode = 'parallel';
71
+ this.integrationPoints = new Map();
72
+ this.migrationStatus = new Map();
73
+ this.comparisonHistory = [];
74
+ }
75
+
76
+ // -----------------------------------------------------------------------
77
+ // Initialization
78
+ // -----------------------------------------------------------------------
79
+
80
+ async initialize(): Promise<void> {
81
+ console.log('[BaselineAutonomyIntegration] Initializing integration layer...');
82
+
83
+ this.initializeIntegrationPoints();
84
+ this.initializeMigrationStatus();
85
+
86
+ console.log('[BaselineAutonomyIntegration] Integration layer initialized');
87
+ console.log(`[BaselineAutonomyIntegration] Integration points: ${this.integrationPoints.size}`);
88
+ console.log(`[BaselineAutonomyIntegration] Migration components: ${this.migrationStatus.size}`);
89
+ console.log(`[BaselineAutonomyIntegration] Migration mode: ${this.migrationMode}`);
90
+
91
+ this.emit('initialized', {
92
+ integrationPoints: this.integrationPoints.size,
93
+ migrationComponents: this.migrationStatus.size,
94
+ mode: this.migrationMode,
95
+ });
96
+ }
97
+
98
+ // -----------------------------------------------------------------------
99
+ // Integration Points (6 - one per layer)
100
+ // -----------------------------------------------------------------------
101
+
102
+ private initializeIntegrationPoints(): void {
103
+ const points: IntegrationPoint[] = [
104
+ {
105
+ layer: 'protocol-core',
106
+ purpose: 'Core protocol definitions and token management',
107
+ integration: 'Mastra AI tool integration for protocol validation and token operations',
108
+ status: 'active',
109
+ },
110
+ {
111
+ layer: 'lang',
112
+ purpose: 'Natural language understanding and command parsing',
113
+ integration: 'LangChain NLP pipeline with Mastra agent orchestration',
114
+ status: 'active',
115
+ },
116
+ {
117
+ layer: 'frame',
118
+ purpose: 'UI component framework and rendering',
119
+ integration: 'AI-assisted component generation and layout optimization',
120
+ status: 'planned',
121
+ },
122
+ {
123
+ layer: 'studio',
124
+ purpose: 'Development environment and workspace management',
125
+ integration: 'Autonomous code generation and project scaffolding via Mastra agents',
126
+ status: 'active',
127
+ },
128
+ {
129
+ layer: 'govern',
130
+ purpose: 'Governance, permissions, and policy enforcement',
131
+ integration: 'AI-driven policy evaluation and compliance monitoring',
132
+ status: 'active',
133
+ },
134
+ {
135
+ layer: 'experience',
136
+ purpose: 'User experience personalization and adaptive interfaces',
137
+ integration: 'LangChain memory for user preference learning and Mastra agent personalization',
138
+ status: 'planned',
139
+ },
140
+ ];
141
+
142
+ for (const point of points) {
143
+ this.integrationPoints.set(point.layer, point);
144
+ }
145
+ }
146
+
147
+ // -----------------------------------------------------------------------
148
+ // Migration Status (4 components)
149
+ // -----------------------------------------------------------------------
150
+
151
+ private initializeMigrationStatus(): void {
152
+ const components: MigrationComponentStatus[] = [
153
+ {
154
+ component: 'nlp-pipeline',
155
+ currentStatus: 'legacy',
156
+ targetStatus: 'langchain',
157
+ migrationProgress: 35,
158
+ dependencies: ['lang', 'protocol-core'],
159
+ estimatedCompletion: '2026-Q2',
160
+ },
161
+ {
162
+ component: 'agent-orchestration',
163
+ currentStatus: 'hybrid',
164
+ targetStatus: 'mastra',
165
+ migrationProgress: 60,
166
+ dependencies: ['protocol-core', 'govern'],
167
+ estimatedCompletion: '2026-Q1',
168
+ },
169
+ {
170
+ component: 'memory-management',
171
+ currentStatus: 'legacy',
172
+ targetStatus: 'langchain-memory',
173
+ migrationProgress: 20,
174
+ dependencies: ['experience', 'lang'],
175
+ estimatedCompletion: '2026-Q3',
176
+ },
177
+ {
178
+ component: 'governance-engine',
179
+ currentStatus: 'hybrid',
180
+ targetStatus: 'mastra-governance',
181
+ migrationProgress: 45,
182
+ dependencies: ['govern', 'protocol-core'],
183
+ estimatedCompletion: '2026-Q2',
184
+ },
185
+ ];
186
+
187
+ for (const component of components) {
188
+ this.migrationStatus.set(component.component, component);
189
+ }
190
+ }
191
+
192
+ // -----------------------------------------------------------------------
193
+ // Command Execution
194
+ // -----------------------------------------------------------------------
195
+
196
+ async executeCommand(
197
+ command: string,
198
+ context: Record<string, unknown> = {}
199
+ ): Promise<Record<string, unknown>> {
200
+ console.log(`[BaselineAutonomyIntegration] Executing command: ${command} (mode: ${this.migrationMode})`);
201
+
202
+ switch (this.migrationMode) {
203
+ case 'parallel':
204
+ return this.executeParallel(command, context);
205
+ case 'progressive':
206
+ return this.executeProgressive(command, context);
207
+ case 'full':
208
+ return this.executeNew(command, context);
209
+ default:
210
+ return this.executeParallel(command, context);
211
+ }
212
+ }
213
+
214
+ // -----------------------------------------------------------------------
215
+ // Execution modes
216
+ // -----------------------------------------------------------------------
217
+
218
+ private async executeParallel(
219
+ command: string,
220
+ context: Record<string, unknown>
221
+ ): Promise<Record<string, unknown>> {
222
+ console.log('[BaselineAutonomyIntegration] [Parallel] Executing in both legacy and new systems...');
223
+
224
+ const startTimeLegacy = Date.now();
225
+ const legacyResult = await this.executeLegacy(command, context);
226
+ const legacyDuration = Date.now() - startTimeLegacy;
227
+
228
+ const startTimeNew = Date.now();
229
+ const newResult = await this.executeNew(command, context);
230
+ const newDuration = Date.now() - startTimeNew;
231
+
232
+ const comparison = this.compareResults(legacyResult, newResult, legacyDuration, newDuration);
233
+ this.comparisonHistory.push(comparison);
234
+
235
+ console.log('[BaselineAutonomyIntegration] [Parallel] Comparison complete');
236
+ console.log(`[BaselineAutonomyIntegration] Legacy duration: ${legacyDuration}ms`);
237
+ console.log(`[BaselineAutonomyIntegration] New duration: ${newDuration}ms`);
238
+ console.log(`[BaselineAutonomyIntegration] Recommendation: ${comparison.recommendation}`);
239
+
240
+ this.emit('parallel-execution', {
241
+ command,
242
+ legacyDuration,
243
+ newDuration,
244
+ comparison,
245
+ });
246
+
247
+ return {
248
+ mode: 'parallel',
249
+ legacyResult,
250
+ newResult,
251
+ comparison,
252
+ selectedResult: comparison.recommendation === 'use-new' ? newResult : legacyResult,
253
+ };
254
+ }
255
+
256
+ private async executeProgressive(
257
+ command: string,
258
+ context: Record<string, unknown>
259
+ ): Promise<Record<string, unknown>> {
260
+ console.log('[BaselineAutonomyIntegration] [Progressive] Evaluating best execution path...');
261
+
262
+ // Check migration progress for the relevant component
263
+ const relevantComponent = this.findRelevantComponent(command);
264
+ const componentStatus = relevantComponent
265
+ ? this.migrationStatus.get(relevantComponent)
266
+ : null;
267
+
268
+ if (componentStatus && componentStatus.migrationProgress >= 70) {
269
+ console.log(
270
+ `[BaselineAutonomyIntegration] [Progressive] Component ${relevantComponent} is ${componentStatus.migrationProgress}% migrated - using new system`
271
+ );
272
+ const result = await this.executeNew(command, context);
273
+ return { mode: 'progressive', system: 'new', result };
274
+ }
275
+
276
+ if (componentStatus && componentStatus.migrationProgress >= 40) {
277
+ console.log(
278
+ `[BaselineAutonomyIntegration] [Progressive] Component ${relevantComponent} is ${componentStatus.migrationProgress}% migrated - using parallel execution`
279
+ );
280
+ return this.executeParallel(command, context);
281
+ }
282
+
283
+ console.log(
284
+ '[BaselineAutonomyIntegration] [Progressive] Migration progress too low - using legacy system'
285
+ );
286
+ const result = await this.executeLegacy(command, context);
287
+ return { mode: 'progressive', system: 'legacy', result };
288
+ }
289
+
290
+ private async executeNew(
291
+ command: string,
292
+ context: Record<string, unknown>
293
+ ): Promise<Record<string, unknown>> {
294
+ console.log('[BaselineAutonomyIntegration] [New] Executing via Mastra/LangChain pipeline...');
295
+
296
+ // Simulate new system execution
297
+ await this.delay(50 + Math.random() * 100);
298
+
299
+ const result: Record<string, unknown> = {
300
+ system: 'mastra-langchain',
301
+ command,
302
+ context,
303
+ timestamp: new Date().toISOString(),
304
+ output: `Processed "${command}" via Mastra/LangChain autonomy engine`,
305
+ confidence: 0.85 + Math.random() * 0.15,
306
+ tokens: Math.floor(Math.random() * 500) + 100,
307
+ };
308
+
309
+ const validation = this.validateResult(result);
310
+ result.validation = validation;
311
+
312
+ this.emit('new-execution', { command, result });
313
+
314
+ return result;
315
+ }
316
+
317
+ private async executeLegacy(
318
+ command: string,
319
+ context: Record<string, unknown>
320
+ ): Promise<Record<string, unknown>> {
321
+ console.log('[BaselineAutonomyIntegration] [Legacy] Executing via legacy Baseline pipeline...');
322
+
323
+ // Simulate legacy system execution
324
+ await this.delay(100 + Math.random() * 200);
325
+
326
+ const result: Record<string, unknown> = {
327
+ system: 'legacy-baseline',
328
+ command,
329
+ context,
330
+ timestamp: new Date().toISOString(),
331
+ output: `Processed "${command}" via legacy Baseline pipeline`,
332
+ confidence: 0.7 + Math.random() * 0.2,
333
+ tokens: Math.floor(Math.random() * 300) + 50,
334
+ };
335
+
336
+ const validation = this.validateResult(result);
337
+ result.validation = validation;
338
+
339
+ this.emit('legacy-execution', { command, result });
340
+
341
+ return result;
342
+ }
343
+
344
+ // -----------------------------------------------------------------------
345
+ // Comparison & Quality
346
+ // -----------------------------------------------------------------------
347
+
348
+ private compareResults(
349
+ legacyResult: Record<string, unknown>,
350
+ newResult: Record<string, unknown>,
351
+ legacyDuration: number,
352
+ newDuration: number
353
+ ): ComparisonResult {
354
+ const quality = this.assessQuality(legacyResult, newResult);
355
+ const performance: Record<string, unknown> = {
356
+ legacyDuration,
357
+ newDuration,
358
+ speedImprovement: this.calculateImprovement(legacyDuration, newDuration),
359
+ fasterSystem: newDuration < legacyDuration ? 'new' : 'legacy',
360
+ };
361
+
362
+ const recommendation = this.generateRecommendation(quality, performance);
363
+
364
+ return {
365
+ timestamp: new Date(),
366
+ legacyResult: JSON.stringify(legacyResult),
367
+ newResult: JSON.stringify(newResult),
368
+ quality,
369
+ performance,
370
+ recommendation,
371
+ };
372
+ }
373
+
374
+ private assessQuality(
375
+ legacyResult: Record<string, unknown>,
376
+ newResult: Record<string, unknown>
377
+ ): Record<string, unknown> {
378
+ const legacyConfidence = (legacyResult.confidence as number) ?? 0;
379
+ const newConfidence = (newResult.confidence as number) ?? 0;
380
+
381
+ const confidenceImprovement = this.calculateImprovement(
382
+ legacyConfidence,
383
+ newConfidence
384
+ );
385
+
386
+ const legacyValid = legacyResult.validation
387
+ ? (legacyResult.validation as Record<string, unknown>).valid
388
+ : false;
389
+ const newValid = newResult.validation
390
+ ? (newResult.validation as Record<string, unknown>).valid
391
+ : false;
392
+
393
+ return {
394
+ legacyConfidence,
395
+ newConfidence,
396
+ confidenceImprovement,
397
+ legacyValid,
398
+ newValid,
399
+ qualityScore: (newConfidence + (newValid ? 0.1 : 0)) - (legacyConfidence + (legacyValid ? 0.1 : 0)),
400
+ };
401
+ }
402
+
403
+ private calculateImprovement(oldValue: number, newValue: number): number {
404
+ if (oldValue === 0) return 0;
405
+ return ((newValue - oldValue) / oldValue) * 100;
406
+ }
407
+
408
+ private generateRecommendation(
409
+ quality: Record<string, unknown>,
410
+ performance: Record<string, unknown>
411
+ ): string | null {
412
+ const qualityScore = (quality.qualityScore as number) ?? 0;
413
+ const speedImprovement = (performance.speedImprovement as number) ?? 0;
414
+ const newValid = quality.newValid as boolean;
415
+
416
+ // If the new system is both faster and higher quality, recommend it
417
+ if (qualityScore > 0 && speedImprovement > 0 && newValid) {
418
+ return 'use-new';
419
+ }
420
+
421
+ // If quality is significantly better even if slower
422
+ if (qualityScore > 0.1 && newValid) {
423
+ return 'use-new';
424
+ }
425
+
426
+ // If the new system is much faster but quality is similar
427
+ if (speedImprovement > 30 && qualityScore >= -0.05 && newValid) {
428
+ return 'use-new';
429
+ }
430
+
431
+ // If legacy is better overall
432
+ if (qualityScore < -0.1) {
433
+ return 'use-legacy';
434
+ }
435
+
436
+ // Insufficient evidence
437
+ return null;
438
+ }
439
+
440
+ private validateResult(result: Record<string, unknown>): Record<string, unknown> {
441
+ const valid =
442
+ result.output !== undefined &&
443
+ result.output !== null &&
444
+ typeof result.output === 'string' &&
445
+ (result.output as string).length > 0;
446
+
447
+ const hasConfidence =
448
+ typeof result.confidence === 'number' &&
449
+ (result.confidence as number) >= 0 &&
450
+ (result.confidence as number) <= 1;
451
+
452
+ return {
453
+ valid,
454
+ hasConfidence,
455
+ hasTimestamp: typeof result.timestamp === 'string',
456
+ hasSystem: typeof result.system === 'string',
457
+ score: (valid ? 0.4 : 0) + (hasConfidence ? 0.3 : 0) + (result.timestamp ? 0.15 : 0) + (result.system ? 0.15 : 0),
458
+ };
459
+ }
460
+
461
+ // -----------------------------------------------------------------------
462
+ // Status & Configuration
463
+ // -----------------------------------------------------------------------
464
+
465
+ getIntegrationStatus(): IntegrationStatus {
466
+ const comparisons = this.comparisonHistory;
467
+ const totalComparisons = comparisons.length;
468
+
469
+ let totalQualityImprovement = 0;
470
+ let totalPerformanceImprovement = 0;
471
+ let recommendationsForNew = 0;
472
+ let recommendationsForLegacy = 0;
473
+
474
+ for (const comparison of comparisons) {
475
+ const qualityScore = (comparison.quality.qualityScore as number) ?? 0;
476
+ totalQualityImprovement += qualityScore;
477
+
478
+ const speedImprovement = (comparison.performance.speedImprovement as number) ?? 0;
479
+ totalPerformanceImprovement += speedImprovement;
480
+
481
+ if (comparison.recommendation === 'use-new') {
482
+ recommendationsForNew += 1;
483
+ } else if (comparison.recommendation === 'use-legacy') {
484
+ recommendationsForLegacy += 1;
485
+ }
486
+ }
487
+
488
+ return {
489
+ migrationMode: this.migrationMode,
490
+ integrationPoints: Array.from(this.integrationPoints.values()),
491
+ migrationStatus: Array.from(this.migrationStatus.values()),
492
+ comparisonHistory: comparisons,
493
+ statistics: {
494
+ totalComparisons,
495
+ averageQualityImprovement: totalComparisons > 0 ? totalQualityImprovement / totalComparisons : 0,
496
+ averagePerformanceImprovement: totalComparisons > 0 ? totalPerformanceImprovement / totalComparisons : 0,
497
+ recommendationsForNew,
498
+ recommendationsForLegacy,
499
+ },
500
+ };
501
+ }
502
+
503
+ setMigrationMode(mode: MigrationMode): void {
504
+ const previousMode = this.migrationMode;
505
+ this.migrationMode = mode;
506
+
507
+ console.log(
508
+ `[BaselineAutonomyIntegration] Migration mode changed: ${previousMode} -> ${mode}`
509
+ );
510
+
511
+ this.emit('migration-mode-changed', { previousMode, newMode: mode });
512
+ }
513
+
514
+ getMigrationRecommendations(): MigrationRecommendation[] {
515
+ const recommendations: MigrationRecommendation[] = [];
516
+
517
+ for (const [, component] of this.migrationStatus) {
518
+ let recommendation: string;
519
+ let reason: string;
520
+
521
+ if (component.migrationProgress >= 80) {
522
+ recommendation = 'Complete migration to new system';
523
+ reason = `Migration is ${component.migrationProgress}% complete - finalize transition`;
524
+ } else if (component.migrationProgress >= 50) {
525
+ recommendation = 'Continue progressive migration';
526
+ reason = `Migration is ${component.migrationProgress}% complete - maintain parallel execution`;
527
+ } else if (component.migrationProgress >= 20) {
528
+ recommendation = 'Accelerate migration efforts';
529
+ reason = `Migration is only ${component.migrationProgress}% complete - increase resources`;
530
+ } else {
531
+ recommendation = 'Begin migration planning';
532
+ reason = `Migration is ${component.migrationProgress}% complete - start planning phase`;
533
+ }
534
+
535
+ const priority = this.calculatePriority(component);
536
+
537
+ recommendations.push({
538
+ component: component.component,
539
+ currentStatus: component.currentStatus,
540
+ recommendation,
541
+ priority,
542
+ reason,
543
+ });
544
+ }
545
+
546
+ // Sort by priority descending
547
+ recommendations.sort((a, b) => b.priority - a.priority);
548
+
549
+ return recommendations;
550
+ }
551
+
552
+ private calculatePriority(component: MigrationComponentStatus): number {
553
+ let priority = 0;
554
+
555
+ // Higher progress = higher priority to complete
556
+ priority += component.migrationProgress * 0.3;
557
+
558
+ // Fewer dependencies = easier to migrate = higher priority
559
+ priority += (10 - component.dependencies.length * 2) * 0.2;
560
+
561
+ // Hybrid status means already partially migrated = higher priority
562
+ if (component.currentStatus === 'hybrid') {
563
+ priority += 20;
564
+ }
565
+
566
+ // Legacy status with low progress = lower priority
567
+ if (component.currentStatus === 'legacy' && component.migrationProgress < 30) {
568
+ priority -= 10;
569
+ }
570
+
571
+ return Math.max(0, Math.min(100, priority));
572
+ }
573
+
574
+ // -----------------------------------------------------------------------
575
+ // Helpers
576
+ // -----------------------------------------------------------------------
577
+
578
+ private findRelevantComponent(command: string): string | null {
579
+ const commandLower = command.toLowerCase();
580
+
581
+ if (commandLower.includes('nlp') || commandLower.includes('parse') || commandLower.includes('language')) {
582
+ return 'nlp-pipeline';
583
+ }
584
+ if (commandLower.includes('agent') || commandLower.includes('orchestrat')) {
585
+ return 'agent-orchestration';
586
+ }
587
+ if (commandLower.includes('memory') || commandLower.includes('remember') || commandLower.includes('context')) {
588
+ return 'memory-management';
589
+ }
590
+ if (commandLower.includes('govern') || commandLower.includes('policy') || commandLower.includes('permission')) {
591
+ return 'governance-engine';
592
+ }
593
+
594
+ return null;
595
+ }
596
+
597
+ private delay(ms: number): Promise<void> {
598
+ return new Promise((resolve) => setTimeout(resolve, ms));
599
+ }
600
+ }