@baselineos/cli 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.
package/dist/index.js ADDED
@@ -0,0 +1,1664 @@
1
+ import {
2
+ BaselineCommandSystem
3
+ } from "./chunk-CCIHFLKI.js";
4
+
5
+ // src/megagem.ts
6
+ import { readFileSync, existsSync } from "fs";
7
+ import { join } from "path";
8
+
9
+ // src/config/megagem-config.json
10
+ var megagem_config_default = {
11
+ system: {
12
+ name: "MEGAGEM AI Autonomous Framework",
13
+ version: "1.0.0",
14
+ description: "The most advanced AI autonomy system ever built. Enables AI to truly OWN and EMPOWER projects autonomously.",
15
+ author: "GTCX Development Team",
16
+ license: "MIT",
17
+ created: "2025-08-12",
18
+ status: "active"
19
+ },
20
+ autonomy: {
21
+ defaultLevel: 0,
22
+ maxLevel: 100,
23
+ incrementStep: 25,
24
+ levels: {
25
+ "0": {
26
+ name: "Manual Control",
27
+ description: "AI waits for explicit commands",
28
+ capabilities: ["command_execution", "basic_assistance"],
29
+ safety: "maximum",
30
+ humanOversight: "required"
31
+ },
32
+ "25": {
33
+ name: "Assisted Autonomy",
34
+ description: "AI suggests actions, user approves",
35
+ capabilities: ["suggestion_generation", "plan_creation", "user_approval"],
36
+ safety: "high",
37
+ humanOversight: "required"
38
+ },
39
+ "50": {
40
+ name: "Collaborative Autonomy",
41
+ description: "AI executes approved plans autonomously",
42
+ capabilities: ["plan_execution", "resource_management", "progress_tracking"],
43
+ safety: "medium",
44
+ humanOversight: "periodic"
45
+ },
46
+ "75": {
47
+ name: "Strategic Autonomy",
48
+ description: "AI makes strategic decisions and executes",
49
+ capabilities: ["strategic_planning", "decision_making", "autonomous_execution"],
50
+ safety: "medium",
51
+ humanOversight: "minimal"
52
+ },
53
+ "100": {
54
+ name: "Full Autonomy",
55
+ description: "AI owns entire projects autonomously",
56
+ capabilities: ["project_ownership", "full_decision_making", "autonomous_evolution"],
57
+ safety: "monitored",
58
+ humanOversight: "audit_only"
59
+ }
60
+ },
61
+ safetyThresholds: {
62
+ riskTolerance: "medium",
63
+ humanOversight: "required",
64
+ decisionApproval: "automatic",
65
+ emergencyStop: true,
66
+ boundaryEnforcement: true
67
+ }
68
+ },
69
+ learning: {
70
+ continuousLearning: true,
71
+ selfImprovement: true,
72
+ knowledgeSharing: true,
73
+ learningMethods: {
74
+ supervised: true,
75
+ unsupervised: true,
76
+ reinforcement: true,
77
+ transfer: true,
78
+ meta: true
79
+ },
80
+ improvementAreas: {
81
+ decisionMaking: true,
82
+ efficiency: true,
83
+ creativity: true,
84
+ collaboration: true,
85
+ safety: true
86
+ },
87
+ learningRate: 0.1,
88
+ knowledgeRetention: 0.95,
89
+ adaptationSpeed: "adaptive"
90
+ },
91
+ safety: {
92
+ riskAssessment: true,
93
+ boundaryEnforcement: true,
94
+ humanOverride: true,
95
+ auditLogging: true,
96
+ emergencyStop: true,
97
+ riskCategories: {
98
+ operational: "high",
99
+ strategic: "medium",
100
+ ethical: "critical",
101
+ legal: "critical",
102
+ technical: "medium"
103
+ },
104
+ safetyProtocols: {
105
+ preAction: true,
106
+ duringAction: true,
107
+ postAction: true,
108
+ emergency: true
109
+ },
110
+ safetyLevels: {
111
+ low: "proceed_with_monitoring",
112
+ medium: "proceed_with_caution",
113
+ high: "require_approval",
114
+ critical: "immediate_stop"
115
+ }
116
+ },
117
+ collaboration: {
118
+ multiAgent: true,
119
+ teamFormation: true,
120
+ taskDistribution: true,
121
+ coordination: true,
122
+ communication: true,
123
+ conflictResolution: true,
124
+ agentTypes: {
125
+ strategist: true,
126
+ executor: true,
127
+ analyst: true,
128
+ coordinator: true,
129
+ innovator: true
130
+ },
131
+ collaborationModels: {
132
+ hierarchical: true,
133
+ collaborative: true,
134
+ adaptive: true,
135
+ emergent: true
136
+ }
137
+ },
138
+ decisionMaking: {
139
+ strategicThinking: true,
140
+ riskAssessment: true,
141
+ resourceOptimization: true,
142
+ goalOrientedPlanning: true,
143
+ adaptiveStrategy: true,
144
+ decisionTypes: {
145
+ tactical: true,
146
+ strategic: true,
147
+ operational: true,
148
+ innovative: true
149
+ },
150
+ decisionProcess: {
151
+ analysis: true,
152
+ evaluation: true,
153
+ selection: true,
154
+ execution: true,
155
+ monitoring: true
156
+ }
157
+ },
158
+ projectOwnership: {
159
+ projectInitiation: true,
160
+ resourceAllocation: true,
161
+ teamFormation: true,
162
+ executionManagement: true,
163
+ qualityControl: true,
164
+ deliveryManagement: true,
165
+ ownershipLevels: {
166
+ partial: true,
167
+ collaborative: true,
168
+ primary: true,
169
+ full: true
170
+ },
171
+ projectTypes: {
172
+ development: true,
173
+ research: true,
174
+ operations: true,
175
+ innovation: true
176
+ }
177
+ },
178
+ performance: {
179
+ metrics: {
180
+ efficiency: true,
181
+ accuracy: true,
182
+ speed: true,
183
+ quality: true,
184
+ innovation: true
185
+ },
186
+ monitoring: {
187
+ realTime: true,
188
+ historical: true,
189
+ predictive: true,
190
+ comparative: true
191
+ },
192
+ optimization: {
193
+ continuous: true,
194
+ adaptive: true,
195
+ goalOriented: true,
196
+ selfImproving: true
197
+ }
198
+ },
199
+ integration: {
200
+ mantraAI: {
201
+ enabled: true,
202
+ integrationLevel: "deep",
203
+ capabilities: ["strategic_thinking", "autonomous_planning"]
204
+ },
205
+ langChain: {
206
+ enabled: true,
207
+ integrationLevel: "deep",
208
+ capabilities: ["tool_orchestration", "workflow_management"]
209
+ },
210
+ autoGen: {
211
+ enabled: true,
212
+ integrationLevel: "medium",
213
+ capabilities: ["multi_agent_collaboration"]
214
+ },
215
+ crewAI: {
216
+ enabled: true,
217
+ integrationLevel: "medium",
218
+ capabilities: ["project_management", "team_orchestration"]
219
+ }
220
+ },
221
+ evolution: {
222
+ selfImprovement: true,
223
+ capabilityExpansion: true,
224
+ knowledgeEvolution: true,
225
+ strategyOptimization: true,
226
+ adaptationMechanisms: {
227
+ environmental: true,
228
+ performance: true,
229
+ user: true,
230
+ internal: true
231
+ },
232
+ evolutionSpeed: "adaptive",
233
+ improvementThreshold: 0.05
234
+ },
235
+ userInterface: {
236
+ autonomyControl: {
237
+ levelSlider: true,
238
+ safetySettings: true,
239
+ learningPreferences: true,
240
+ performanceMetrics: true
241
+ },
242
+ monitoring: {
243
+ realTimeStatus: true,
244
+ projectOverview: true,
245
+ safetyAlerts: true,
246
+ performanceDashboard: true
247
+ },
248
+ interaction: {
249
+ naturalLanguage: true,
250
+ visualInterface: true,
251
+ mobileAccess: true,
252
+ voiceControl: true
253
+ }
254
+ },
255
+ deployment: {
256
+ environment: "production",
257
+ scalability: "auto",
258
+ reliability: "99.9%",
259
+ security: "enterprise",
260
+ monitoring: "comprehensive",
261
+ backup: "automated",
262
+ recovery: "instant"
263
+ }
264
+ };
265
+
266
+ // src/megagem.ts
267
+ var MEGAGEMCoreSystem = class {
268
+ systemName;
269
+ version;
270
+ autonomyLevel;
271
+ isActive;
272
+ learningMode;
273
+ safetyMode;
274
+ autonomyController;
275
+ decisionEngine;
276
+ projectOwner;
277
+ learningEngine;
278
+ safetyEngine;
279
+ collaborationEngine;
280
+ currentProjects;
281
+ performanceMetrics;
282
+ learningHistory;
283
+ safetyEvents;
284
+ config;
285
+ constructor() {
286
+ this.systemName = "MEGAGEM";
287
+ this.version = "1.0.0";
288
+ this.autonomyLevel = 1;
289
+ this.isActive = false;
290
+ this.learningMode = false;
291
+ this.safetyMode = true;
292
+ this.autonomyController = this.initializeAutonomyController();
293
+ this.decisionEngine = this.initializeDecisionEngine();
294
+ this.projectOwner = this.initializeProjectOwner();
295
+ this.learningEngine = this.initializeLearningEngine();
296
+ this.safetyEngine = this.initializeSafetyEngine();
297
+ this.collaborationEngine = this.initializeCollaborationEngine();
298
+ this.currentProjects = /* @__PURE__ */ new Map();
299
+ this.performanceMetrics = {
300
+ decisionsAccuracy: 0,
301
+ taskCompletionRate: 0,
302
+ learningRate: 0,
303
+ collaborationScore: 0,
304
+ safetyCompliance: 1,
305
+ totalDecisions: 0,
306
+ totalTasks: 0,
307
+ totalCollaborations: 0,
308
+ uptime: 0,
309
+ startTime: /* @__PURE__ */ new Date()
310
+ };
311
+ this.learningHistory = [];
312
+ this.safetyEvents = [];
313
+ this.config = this.getDefaultConfig();
314
+ }
315
+ /**
316
+ * Set up the autonomy controller with five operational levels
317
+ * and escalation rules.
318
+ */
319
+ initializeAutonomyController() {
320
+ return {
321
+ currentLevel: 1,
322
+ maxLevel: 5,
323
+ levels: {
324
+ 1: { name: "Supervised", description: "All actions require human approval" },
325
+ 2: { name: "Guided", description: "Routine actions auto-approved, complex actions require approval" },
326
+ 3: { name: "Collaborative", description: "Most actions auto-approved, high-risk actions require approval" },
327
+ 4: { name: "Autonomous", description: "Almost all actions auto-approved, critical actions require approval" },
328
+ 5: { name: "Full Autonomy", description: "All actions auto-approved with safety constraints" }
329
+ },
330
+ escalationRules: [
331
+ { condition: "high_risk_detected", action: "reduce_autonomy", targetLevel: 1 },
332
+ { condition: "safety_violation", action: "emergency_stop", targetLevel: 0 },
333
+ { condition: "repeated_success", action: "increase_autonomy", targetLevel: -1 },
334
+ { condition: "human_override", action: "set_supervised", targetLevel: 1 }
335
+ ],
336
+ overrideActive: false
337
+ };
338
+ }
339
+ /**
340
+ * Set up the decision engine with thresholds and history tracking.
341
+ */
342
+ initializeDecisionEngine() {
343
+ return {
344
+ pendingDecisions: [],
345
+ decisionHistory: [],
346
+ decisionThresholds: {
347
+ lowRisk: 0.3,
348
+ mediumRisk: 0.6,
349
+ highRisk: 0.8,
350
+ criticalRisk: 0.95
351
+ },
352
+ autoApprove: false
353
+ };
354
+ }
355
+ /**
356
+ * Set up the project ownership engine with project stores and templates.
357
+ */
358
+ initializeProjectOwner() {
359
+ return {
360
+ activeProjects: /* @__PURE__ */ new Map(),
361
+ completedProjects: /* @__PURE__ */ new Map(),
362
+ projectTemplates: /* @__PURE__ */ new Map([
363
+ [
364
+ "standard",
365
+ {
366
+ phases: ["planning", "design", "implementation", "testing", "deployment"],
367
+ milestones: ["kickoff", "design-review", "alpha", "beta", "release"],
368
+ roles: ["lead", "developer", "designer", "tester", "reviewer"]
369
+ }
370
+ ],
371
+ [
372
+ "agile",
373
+ {
374
+ phases: ["backlog", "sprint-planning", "sprint", "review", "retrospective"],
375
+ milestones: ["sprint-start", "mid-sprint", "sprint-end", "demo"],
376
+ roles: ["product-owner", "scrum-master", "developer", "tester"]
377
+ }
378
+ ],
379
+ [
380
+ "research",
381
+ {
382
+ phases: ["exploration", "hypothesis", "experimentation", "analysis", "publication"],
383
+ milestones: ["proposal", "data-collection", "analysis-complete", "draft", "final"],
384
+ roles: ["principal-investigator", "researcher", "analyst", "reviewer"]
385
+ }
386
+ ]
387
+ ])
388
+ };
389
+ }
390
+ /**
391
+ * Set up the learning engine with knowledge base and adaptation rate.
392
+ */
393
+ initializeLearningEngine() {
394
+ return {
395
+ knowledgeBase: /* @__PURE__ */ new Map(),
396
+ learningHistory: [],
397
+ patterns: /* @__PURE__ */ new Map(),
398
+ adaptationRate: 0.1
399
+ };
400
+ }
401
+ /**
402
+ * Set up the safety engine with risk assessment stores and boundary
403
+ * configuration.
404
+ */
405
+ initializeSafetyEngine() {
406
+ return {
407
+ riskAssessments: /* @__PURE__ */ new Map(),
408
+ boundaries: /* @__PURE__ */ new Map([
409
+ ["max_file_operations", { limit: 1e3, current: 0 }],
410
+ ["max_network_requests", { limit: 100, current: 0 }],
411
+ ["max_memory_usage_mb", { limit: 512, current: 0 }],
412
+ ["max_execution_time_ms", { limit: 3e5, current: 0 }],
413
+ ["forbidden_operations", { list: ["delete_system_files", "modify_credentials", "disable_logging"] }]
414
+ ]),
415
+ safetyEvents: [],
416
+ overrideEnabled: true
417
+ };
418
+ }
419
+ /**
420
+ * Set up the collaboration engine with registries and communication log.
421
+ */
422
+ initializeCollaborationEngine() {
423
+ return {
424
+ activeCollaborations: /* @__PURE__ */ new Map(),
425
+ communicationLog: [],
426
+ teamRegistry: /* @__PURE__ */ new Map()
427
+ };
428
+ }
429
+ /**
430
+ * Perform full system initialization: activate learning, safety, and
431
+ * log startup information.
432
+ */
433
+ async initializeSystem() {
434
+ console.log(`[${this.systemName}] Initializing core system v${this.version}...`);
435
+ this.isActive = true;
436
+ this.learningMode = true;
437
+ this.safetyMode = true;
438
+ this.performanceMetrics.startTime = /* @__PURE__ */ new Date();
439
+ console.log(`[${this.systemName}] Autonomy controller ready (level ${this.autonomyController.currentLevel})`);
440
+ console.log(`[${this.systemName}] Decision engine ready`);
441
+ console.log(`[${this.systemName}] Project ownership engine ready`);
442
+ console.log(`[${this.systemName}] Learning engine ready (rate: ${this.learningEngine.adaptationRate})`);
443
+ console.log(`[${this.systemName}] Safety engine ready (override: ${this.safetyEngine.overrideEnabled})`);
444
+ console.log(`[${this.systemName}] Collaboration engine ready`);
445
+ console.log(`[${this.systemName}] System initialization complete`);
446
+ return {
447
+ success: true,
448
+ status: this.getSystemStatus()
449
+ };
450
+ }
451
+ /**
452
+ * Set the autonomy level (1-5) and update the system behavior accordingly.
453
+ */
454
+ setAutonomyLevel(level) {
455
+ if (level < 1 || level > this.autonomyController.maxLevel) {
456
+ console.log(
457
+ `[${this.systemName}] Invalid autonomy level: ${level}. Must be 1-${this.autonomyController.maxLevel}`
458
+ );
459
+ return {
460
+ success: false,
461
+ level: this.autonomyLevel,
462
+ name: this.autonomyController.levels[this.autonomyLevel].name,
463
+ error: `Level must be between 1 and ${this.autonomyController.maxLevel}`
464
+ };
465
+ }
466
+ const previousLevel = this.autonomyLevel;
467
+ this.autonomyLevel = level;
468
+ this.autonomyController.currentLevel = level;
469
+ this.updateSystemBehavior(level);
470
+ console.log(
471
+ `[${this.systemName}] Autonomy level changed: ${previousLevel} -> ${level} (${this.autonomyController.levels[level].name})`
472
+ );
473
+ return {
474
+ success: true,
475
+ level,
476
+ name: this.autonomyController.levels[level].name
477
+ };
478
+ }
479
+ /**
480
+ * Update internal system behavior based on the autonomy level.
481
+ */
482
+ updateSystemBehavior(level) {
483
+ switch (level) {
484
+ case 1:
485
+ this.decisionEngine.autoApprove = false;
486
+ this.safetyEngine.overrideEnabled = true;
487
+ break;
488
+ case 2:
489
+ this.decisionEngine.autoApprove = false;
490
+ this.safetyEngine.overrideEnabled = true;
491
+ break;
492
+ case 3:
493
+ this.decisionEngine.autoApprove = true;
494
+ this.safetyEngine.overrideEnabled = true;
495
+ break;
496
+ case 4:
497
+ this.decisionEngine.autoApprove = true;
498
+ this.safetyEngine.overrideEnabled = true;
499
+ break;
500
+ case 5:
501
+ this.decisionEngine.autoApprove = true;
502
+ this.safetyEngine.overrideEnabled = false;
503
+ break;
504
+ default:
505
+ break;
506
+ }
507
+ }
508
+ /**
509
+ * Return a comprehensive snapshot of the current system status.
510
+ */
511
+ getSystemStatus() {
512
+ const now = /* @__PURE__ */ new Date();
513
+ const uptimeMs = now.getTime() - this.performanceMetrics.startTime.getTime();
514
+ return {
515
+ systemName: this.systemName,
516
+ version: this.version,
517
+ isActive: this.isActive,
518
+ autonomyLevel: this.autonomyLevel,
519
+ autonomyName: this.autonomyController.levels[this.autonomyLevel]?.name || "unknown",
520
+ learningMode: this.learningMode,
521
+ safetyMode: this.safetyMode,
522
+ uptime: uptimeMs,
523
+ activeProjects: this.projectOwner.activeProjects.size,
524
+ completedProjects: this.projectOwner.completedProjects.size,
525
+ pendingDecisions: this.decisionEngine.pendingDecisions.length,
526
+ performanceMetrics: { ...this.performanceMetrics },
527
+ safetyEvents: this.safetyEvents.length,
528
+ learningHistory: this.learningHistory.length,
529
+ knowledgeBaseSize: this.learningEngine.knowledgeBase.size,
530
+ activeCollaborations: this.collaborationEngine.activeCollaborations.size
531
+ };
532
+ }
533
+ /**
534
+ * Attempt to load a configuration file from the given path.
535
+ * Falls back to defaults if the file does not exist.
536
+ */
537
+ loadConfiguration(configPath) {
538
+ try {
539
+ const fullPath = join(configPath, "megagem.config.json");
540
+ if (existsSync(fullPath)) {
541
+ const raw = readFileSync(fullPath, "utf-8");
542
+ const loaded = JSON.parse(raw);
543
+ this.config = loaded;
544
+ console.log(`[${this.systemName}] Configuration loaded from ${fullPath}`);
545
+ return loaded;
546
+ }
547
+ console.log(`[${this.systemName}] No config file found at ${fullPath}, using defaults`);
548
+ return this.config;
549
+ } catch (error) {
550
+ const msg = error instanceof Error ? error.message : String(error);
551
+ console.log(`[${this.systemName}] Error loading configuration: ${msg}`);
552
+ return this.config;
553
+ }
554
+ }
555
+ /**
556
+ * Return the default MEGAGEM configuration object.
557
+ */
558
+ getDefaultConfig() {
559
+ const cfg = megagem_config_default;
560
+ const autonomy = cfg.autonomy ?? {};
561
+ const thresholds = autonomy.safetyThresholds ?? {};
562
+ return {
563
+ system: {
564
+ name: cfg.system?.name ?? "MEGAGEM",
565
+ version: cfg.system?.version ?? "1.0.0",
566
+ description: cfg.system?.description ?? "Multi-Environment General-purpose Autonomous Governance and Execution Manager"
567
+ },
568
+ autonomy: {
569
+ defaultLevel: autonomy.defaultLevel ?? 1,
570
+ maxLevel: autonomy.maxLevel ?? 5,
571
+ safetyThresholds: {
572
+ riskTolerance: thresholds.riskTolerance ?? "medium",
573
+ humanOversight: thresholds.humanOversight ?? "required"
574
+ }
575
+ },
576
+ learning: {
577
+ continuousLearning: cfg.learning?.continuousLearning ?? true,
578
+ selfImprovement: cfg.learning?.selfImprovement ?? true,
579
+ knowledgeSharing: cfg.learning?.knowledgeSharing ?? true
580
+ },
581
+ safety: {
582
+ riskAssessment: cfg.safety?.riskAssessment ?? true,
583
+ boundaryEnforcement: cfg.safety?.boundaryEnforcement ?? true,
584
+ humanOverride: cfg.safety?.humanOverride ?? true,
585
+ auditLogging: cfg.safety?.auditLogging ?? true
586
+ }
587
+ };
588
+ }
589
+ /**
590
+ * Activate autonomous operation mode: sets the system active, starts
591
+ * performance tracking, and returns the active capabilities.
592
+ */
593
+ async startAutonomousOperation() {
594
+ if (!this.isActive) {
595
+ await this.initializeSystem();
596
+ }
597
+ console.log(`[${this.systemName}] Starting autonomous operation at level ${this.autonomyLevel}...`);
598
+ const capabilities = this.activateAutonomousCapabilities();
599
+ console.log(`[${this.systemName}] Autonomous capabilities activated: ${capabilities.join(", ")}`);
600
+ return {
601
+ success: true,
602
+ capabilities
603
+ };
604
+ }
605
+ /**
606
+ * Determine which capabilities should be active given the current
607
+ * autonomy level and return them as a list.
608
+ */
609
+ activateAutonomousCapabilities() {
610
+ const capabilities = [
611
+ "monitoring",
612
+ "reporting",
613
+ "status_tracking"
614
+ ];
615
+ if (this.autonomyLevel >= 2) {
616
+ capabilities.push("routine_decisions", "task_scheduling", "resource_monitoring");
617
+ }
618
+ if (this.autonomyLevel >= 3) {
619
+ capabilities.push("project_planning", "team_coordination", "risk_assessment");
620
+ }
621
+ if (this.autonomyLevel >= 4) {
622
+ capabilities.push("autonomous_execution", "adaptive_planning", "self_optimization");
623
+ }
624
+ if (this.autonomyLevel >= 5) {
625
+ capabilities.push("full_project_ownership", "strategic_planning", "cross_project_optimization");
626
+ }
627
+ return capabilities;
628
+ }
629
+ /**
630
+ * Return the list of capabilities currently active.
631
+ */
632
+ getActiveCapabilities() {
633
+ return this.activateAutonomousCapabilities();
634
+ }
635
+ };
636
+ var MEGAGEMAutonomousAgent = class {
637
+ agentId;
638
+ agentType;
639
+ capabilities;
640
+ autonomyLevel;
641
+ isActive;
642
+ currentProjects;
643
+ performanceMetrics;
644
+ learningHistory;
645
+ collaborationHistory;
646
+ status;
647
+ currentTask;
648
+ teamMembers;
649
+ resources;
650
+ knowledgeBase;
651
+ skillLevels;
652
+ adaptationRate;
653
+ constructor(agentType = "general", autonomyLevel = 1) {
654
+ this.agentId = this.generateAgentId();
655
+ this.agentType = agentType;
656
+ this.capabilities = {};
657
+ this.autonomyLevel = autonomyLevel;
658
+ this.isActive = false;
659
+ this.currentProjects = /* @__PURE__ */ new Map();
660
+ this.performanceMetrics = {
661
+ tasksCompleted: 0,
662
+ tasksFailed: 0,
663
+ successRate: 1,
664
+ averageCompletionTime: 0,
665
+ qualityScore: 1,
666
+ learningProgress: 0
667
+ };
668
+ this.learningHistory = [];
669
+ this.collaborationHistory = [];
670
+ this.status = "idle";
671
+ this.currentTask = null;
672
+ this.teamMembers = [];
673
+ this.resources = /* @__PURE__ */ new Map();
674
+ this.knowledgeBase = /* @__PURE__ */ new Map();
675
+ this.skillLevels = /* @__PURE__ */ new Map();
676
+ this.adaptationRate = 0.1;
677
+ this.initializeCapabilities(agentType);
678
+ }
679
+ /**
680
+ * Generate a unique agent identifier.
681
+ */
682
+ generateAgentId() {
683
+ return `agent-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
684
+ }
685
+ /**
686
+ * Activate the agent for autonomous operation.
687
+ */
688
+ activate() {
689
+ this.isActive = true;
690
+ this.status = "active";
691
+ console.log(`[Agent:${this.agentId}] Activated as ${this.agentType} agent (autonomy level ${this.autonomyLevel})`);
692
+ }
693
+ /**
694
+ * Initialize capabilities based on the agent type. Supports five
695
+ * types: project-manager, developer, designer, analyst, general.
696
+ */
697
+ initializeCapabilities(agentType) {
698
+ switch (agentType) {
699
+ case "project-manager":
700
+ this.capabilities = {
701
+ planning: true,
702
+ scheduling: true,
703
+ resourceAllocation: true,
704
+ riskManagement: true,
705
+ teamCoordination: true,
706
+ reporting: true,
707
+ budgetManagement: true,
708
+ stakeholderCommunication: true,
709
+ qualityAssurance: true,
710
+ scope: "project",
711
+ specializations: ["waterfall", "agile", "hybrid"]
712
+ };
713
+ this.skillLevels.set("planning", 0.9);
714
+ this.skillLevels.set("communication", 0.85);
715
+ this.skillLevels.set("risk-assessment", 0.8);
716
+ this.skillLevels.set("resource-management", 0.85);
717
+ this.skillLevels.set("quality-control", 0.8);
718
+ break;
719
+ case "developer":
720
+ this.capabilities = {
721
+ coding: true,
722
+ testing: true,
723
+ debugging: true,
724
+ codeReview: true,
725
+ architecture: true,
726
+ documentation: true,
727
+ deployment: true,
728
+ optimization: true,
729
+ scope: "technical",
730
+ specializations: ["frontend", "backend", "fullstack", "devops"]
731
+ };
732
+ this.skillLevels.set("coding", 0.9);
733
+ this.skillLevels.set("testing", 0.85);
734
+ this.skillLevels.set("architecture", 0.8);
735
+ this.skillLevels.set("debugging", 0.85);
736
+ this.skillLevels.set("documentation", 0.7);
737
+ break;
738
+ case "designer":
739
+ this.capabilities = {
740
+ uiDesign: true,
741
+ uxResearch: true,
742
+ prototyping: true,
743
+ visualDesign: true,
744
+ designSystems: true,
745
+ accessibility: true,
746
+ userTesting: true,
747
+ scope: "design",
748
+ specializations: ["ui", "ux", "graphic", "interaction"]
749
+ };
750
+ this.skillLevels.set("visual-design", 0.9);
751
+ this.skillLevels.set("ux-research", 0.85);
752
+ this.skillLevels.set("prototyping", 0.8);
753
+ this.skillLevels.set("accessibility", 0.75);
754
+ this.skillLevels.set("design-systems", 0.8);
755
+ break;
756
+ case "analyst":
757
+ this.capabilities = {
758
+ dataAnalysis: true,
759
+ reporting: true,
760
+ forecasting: true,
761
+ visualization: true,
762
+ requirementsGathering: true,
763
+ processModeling: true,
764
+ scope: "analytical",
765
+ specializations: ["data", "business", "systems", "security"]
766
+ };
767
+ this.skillLevels.set("data-analysis", 0.9);
768
+ this.skillLevels.set("reporting", 0.85);
769
+ this.skillLevels.set("forecasting", 0.8);
770
+ this.skillLevels.set("visualization", 0.8);
771
+ this.skillLevels.set("requirements", 0.85);
772
+ break;
773
+ case "general":
774
+ default:
775
+ this.capabilities = {
776
+ planning: true,
777
+ execution: true,
778
+ monitoring: true,
779
+ reporting: true,
780
+ collaboration: true,
781
+ learning: true,
782
+ scope: "general",
783
+ specializations: ["general-purpose"]
784
+ };
785
+ this.skillLevels.set("planning", 0.7);
786
+ this.skillLevels.set("execution", 0.7);
787
+ this.skillLevels.set("monitoring", 0.7);
788
+ this.skillLevels.set("reporting", 0.7);
789
+ this.skillLevels.set("collaboration", 0.7);
790
+ break;
791
+ }
792
+ }
793
+ /**
794
+ * Take ownership of a project, creating the internal project record
795
+ * and setting status to planning.
796
+ */
797
+ async takeProjectOwnership(projectData) {
798
+ const projectId = this.generateProjectId();
799
+ const project = {
800
+ id: projectId,
801
+ name: projectData.name,
802
+ description: projectData.description,
803
+ type: projectData.type,
804
+ status: "planning",
805
+ ownershipLevel: "full",
806
+ startDate: /* @__PURE__ */ new Date(),
807
+ objectives: projectData.objectives || [],
808
+ constraints: projectData.constraints || [],
809
+ resources: projectData.resources || {},
810
+ timeline: projectData.timeline || {},
811
+ team: /* @__PURE__ */ new Set([this.agentId]),
812
+ tasks: /* @__PURE__ */ new Map(),
813
+ milestones: /* @__PURE__ */ new Map(),
814
+ risks: /* @__PURE__ */ new Map(),
815
+ progress: 0
816
+ };
817
+ this.currentProjects.set(projectId, project);
818
+ console.log(`[Agent:${this.agentId}] Took ownership of project: ${projectData.name} (${projectId})`);
819
+ return project;
820
+ }
821
+ /**
822
+ * Execute a project autonomously through all lifecycle phases:
823
+ * plan -> form team -> allocate resources -> execute -> monitor -> deliver.
824
+ */
825
+ async executeProjectAutonomously(projectId) {
826
+ const project = this.currentProjects.get(projectId);
827
+ if (!project) {
828
+ throw new Error(`Project ${projectId} not found`);
829
+ }
830
+ console.log(`[Agent:${this.agentId}] Starting autonomous execution of project: ${project.name}`);
831
+ try {
832
+ project.status = "planning";
833
+ console.log(`[Agent:${this.agentId}] Phase 1: Planning project...`);
834
+ await this.planProject(project);
835
+ project.status = "team-formation";
836
+ console.log(`[Agent:${this.agentId}] Phase 2: Forming project team...`);
837
+ await this.formProjectTeam(project);
838
+ project.status = "resource-allocation";
839
+ console.log(`[Agent:${this.agentId}] Phase 3: Allocating resources...`);
840
+ await this.allocateResources(project);
841
+ project.status = "in-progress";
842
+ console.log(`[Agent:${this.agentId}] Phase 4: Executing project plan...`);
843
+ await this.executeProjectPlan(project);
844
+ project.status = "monitoring";
845
+ console.log(`[Agent:${this.agentId}] Phase 5: Monitoring and controlling...`);
846
+ await this.monitorAndControl(project);
847
+ project.status = "delivering";
848
+ console.log(`[Agent:${this.agentId}] Phase 6: Delivering project...`);
849
+ await this.deliverProject(project);
850
+ project.status = "completed";
851
+ project.endDate = /* @__PURE__ */ new Date();
852
+ project.progress = 100;
853
+ console.log(`[Agent:${this.agentId}] Project ${project.name} completed successfully`);
854
+ return project;
855
+ } catch (error) {
856
+ const errorMessage = error instanceof Error ? error.message : String(error);
857
+ project.status = "failed";
858
+ project.error = errorMessage;
859
+ console.log(`[Agent:${this.agentId}] Project ${project.name} failed: ${errorMessage}`);
860
+ return project;
861
+ }
862
+ }
863
+ /**
864
+ * Create a strategic plan for the project including phases, milestones,
865
+ * task breakdown, timeline, resource plan, and risk assessment.
866
+ */
867
+ async planProject(project) {
868
+ const strategicPlan = this.createStrategicPlan(project);
869
+ project.plan = strategicPlan;
870
+ const phases = this.defineProjectPhases(project);
871
+ project.plan.phases = phases;
872
+ const milestones = this.defineMilestones(project);
873
+ for (const milestone of milestones) {
874
+ project.milestones.set(milestone.id, milestone);
875
+ }
876
+ const tasks = this.breakDownTasks(project);
877
+ for (const task of tasks) {
878
+ project.tasks.set(task.id, task);
879
+ }
880
+ const timeline = this.createTimeline(project);
881
+ project.timeline = timeline;
882
+ const resourcePlan = this.planResources(project);
883
+ project.plan.resources = resourcePlan;
884
+ const risks = this.assessRisks(project);
885
+ for (const risk of risks) {
886
+ project.risks.set(risk.id, risk);
887
+ }
888
+ project.strategy = strategicPlan;
889
+ console.log(
890
+ `[Agent:${this.agentId}] Project plan created: ${phases.length} phases, ${milestones.length} milestones, ${tasks.length} tasks, ${risks.length} risks`
891
+ );
892
+ }
893
+ /**
894
+ * Form a team for the project by analyzing requirements and assigning roles.
895
+ */
896
+ async formProjectTeam(project) {
897
+ const requirements = this.analyzeTeamRequirements(project);
898
+ const teamMembers = [];
899
+ for (const role of requirements.roles) {
900
+ const member = {
901
+ id: `member-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
902
+ role,
903
+ capabilities: this.getRoleCapabilities(role),
904
+ assignedDate: (/* @__PURE__ */ new Date()).toISOString(),
905
+ status: "assigned"
906
+ };
907
+ teamMembers.push(member);
908
+ project.team.add(member.id);
909
+ }
910
+ project.teamMembers = teamMembers;
911
+ console.log(
912
+ `[Agent:${this.agentId}] Team formed: ${teamMembers.length} members for ${requirements.roles.length} roles`
913
+ );
914
+ }
915
+ /**
916
+ * Allocate resources to the project based on current plan and constraints.
917
+ */
918
+ async allocateResources(project) {
919
+ const resourceAllocation = {
920
+ compute: {
921
+ allocated: true,
922
+ type: "standard",
923
+ units: Math.max(1, project.tasks.size)
924
+ },
925
+ storage: {
926
+ allocated: true,
927
+ type: "standard",
928
+ sizeMB: 100
929
+ },
930
+ budget: {
931
+ allocated: true,
932
+ total: project.constraints.length > 0 ? 1e4 : 5e3,
933
+ spent: 0,
934
+ remaining: project.constraints.length > 0 ? 1e4 : 5e3
935
+ },
936
+ time: {
937
+ allocated: true,
938
+ totalHours: project.tasks.size * 8,
939
+ usedHours: 0,
940
+ remainingHours: project.tasks.size * 8
941
+ }
942
+ };
943
+ project.resources = resourceAllocation;
944
+ console.log(
945
+ `[Agent:${this.agentId}] Resources allocated: ${project.tasks.size} compute units, ${resourceAllocation.time.totalHours}h total`
946
+ );
947
+ }
948
+ /**
949
+ * Execute the project plan by iterating through all tasks.
950
+ */
951
+ async executeProjectPlan(project) {
952
+ const tasks = Array.from(project.tasks.entries());
953
+ let completedTasks = 0;
954
+ const totalTasks = tasks.length;
955
+ for (const [taskId, taskData] of tasks) {
956
+ const task = taskData;
957
+ console.log(`[Agent:${this.agentId}] Executing task: ${task.name} (${taskId})`);
958
+ const result = await this.executeTask(task);
959
+ if (result.success) {
960
+ task.status = "completed";
961
+ task.completedDate = (/* @__PURE__ */ new Date()).toISOString();
962
+ task.result = result.output;
963
+ completedTasks++;
964
+ this.performanceMetrics.tasksCompleted++;
965
+ } else {
966
+ task.status = "failed";
967
+ task.error = result.error;
968
+ this.performanceMetrics.tasksFailed++;
969
+ console.log(`[Agent:${this.agentId}] Task ${taskId} failed: ${result.error}`);
970
+ }
971
+ project.progress = Math.round(completedTasks / totalTasks * 80);
972
+ }
973
+ const totalAttempted = this.performanceMetrics.tasksCompleted + this.performanceMetrics.tasksFailed;
974
+ this.performanceMetrics.successRate = totalAttempted > 0 ? this.performanceMetrics.tasksCompleted / totalAttempted : 1;
975
+ console.log(
976
+ `[Agent:${this.agentId}] Plan execution complete: ${completedTasks}/${totalTasks} tasks completed`
977
+ );
978
+ }
979
+ /**
980
+ * Monitor project health and adjust the plan if deviations are detected.
981
+ */
982
+ async monitorAndControl(project) {
983
+ const health = this.assessProjectHealth(project);
984
+ project.healthMetrics = health;
985
+ console.log(
986
+ `[Agent:${this.agentId}] Project health: ${health.overall} (score: ${health.score})`
987
+ );
988
+ if (health.score < 0.7) {
989
+ console.log(`[Agent:${this.agentId}] Health below threshold, adjusting plan...`);
990
+ await this.adjustProjectPlan(project, health);
991
+ }
992
+ project.progress = 90;
993
+ }
994
+ /**
995
+ * Deliver project outputs, perform quality checks, and prepare deliverables.
996
+ */
997
+ async deliverProject(project) {
998
+ console.log(`[Agent:${this.agentId}] Performing final quality check...`);
999
+ const qualityResult = this.performQualityCheck(project);
1000
+ project.qualityScore = qualityResult.score;
1001
+ console.log(`[Agent:${this.agentId}] Preparing deliverables...`);
1002
+ const deliverables = this.prepareDeliverables(project);
1003
+ project.deliverables = deliverables;
1004
+ project.progress = 100;
1005
+ project.status = "delivered";
1006
+ console.log(
1007
+ `[Agent:${this.agentId}] Project ${project.name} delivered (quality: ${project.qualityScore})`
1008
+ );
1009
+ }
1010
+ /**
1011
+ * Build a strategic plan from the project's objectives and constraints.
1012
+ */
1013
+ createStrategicPlan(project) {
1014
+ return {
1015
+ projectId: project.id,
1016
+ projectName: project.name,
1017
+ vision: `Successfully deliver ${project.name}: ${project.description}`,
1018
+ objectives: project.objectives.map((obj, index) => ({
1019
+ id: `obj-${index + 1}`,
1020
+ description: obj,
1021
+ priority: index === 0 ? "high" : "medium",
1022
+ status: "pending"
1023
+ })),
1024
+ constraints: project.constraints,
1025
+ approach: project.type === "agile" ? "iterative" : "sequential",
1026
+ riskStrategy: "proactive",
1027
+ qualityStandard: "high",
1028
+ communicationPlan: {
1029
+ frequency: "daily",
1030
+ channels: ["status-report", "milestone-review"],
1031
+ stakeholders: ["team", "owner"]
1032
+ },
1033
+ createdDate: (/* @__PURE__ */ new Date()).toISOString()
1034
+ };
1035
+ }
1036
+ /**
1037
+ * Define project phases based on the project type.
1038
+ */
1039
+ defineProjectPhases(project) {
1040
+ const phaseTemplates = {
1041
+ standard: ["initiation", "planning", "execution", "monitoring", "closure"],
1042
+ agile: ["backlog-refinement", "sprint-planning", "development", "review", "retrospective"],
1043
+ research: ["exploration", "hypothesis", "experimentation", "analysis", "reporting"]
1044
+ };
1045
+ const phaseNames = phaseTemplates[project.type] || phaseTemplates["standard"];
1046
+ return phaseNames.map((name, index) => ({
1047
+ id: `phase-${index + 1}`,
1048
+ name,
1049
+ order: index + 1,
1050
+ status: "pending",
1051
+ startDate: null,
1052
+ endDate: null,
1053
+ dependencies: index > 0 ? [`phase-${index}`] : []
1054
+ }));
1055
+ }
1056
+ /**
1057
+ * Define milestones for the project plan.
1058
+ */
1059
+ defineMilestones(_project) {
1060
+ const baseMilestones = [
1061
+ "Project Kickoff",
1062
+ "Requirements Complete",
1063
+ "Design Approved",
1064
+ "Development Complete",
1065
+ "Testing Complete",
1066
+ "Deployment Ready",
1067
+ "Project Closure"
1068
+ ];
1069
+ return baseMilestones.map((name, index) => ({
1070
+ id: `milestone-${index + 1}`,
1071
+ name,
1072
+ order: index + 1,
1073
+ status: "pending",
1074
+ dueDate: null,
1075
+ criteria: [`${name} criteria met`],
1076
+ deliverables: [`${name} artifacts`]
1077
+ }));
1078
+ }
1079
+ /**
1080
+ * Break project objectives down into concrete tasks.
1081
+ */
1082
+ breakDownTasks(project) {
1083
+ const tasks = [];
1084
+ let taskCounter = 0;
1085
+ for (const objective of project.objectives) {
1086
+ taskCounter++;
1087
+ tasks.push({
1088
+ id: `task-${taskCounter}`,
1089
+ name: `Analyze: ${objective}`,
1090
+ type: "analysis",
1091
+ status: "pending",
1092
+ priority: "high",
1093
+ estimatedHours: 4,
1094
+ assignee: null,
1095
+ dependencies: []
1096
+ });
1097
+ taskCounter++;
1098
+ tasks.push({
1099
+ id: `task-${taskCounter}`,
1100
+ name: `Implement: ${objective}`,
1101
+ type: "implementation",
1102
+ status: "pending",
1103
+ priority: "high",
1104
+ estimatedHours: 16,
1105
+ assignee: null,
1106
+ dependencies: [`task-${taskCounter - 1}`]
1107
+ });
1108
+ taskCounter++;
1109
+ tasks.push({
1110
+ id: `task-${taskCounter}`,
1111
+ name: `Verify: ${objective}`,
1112
+ type: "verification",
1113
+ status: "pending",
1114
+ priority: "medium",
1115
+ estimatedHours: 4,
1116
+ assignee: null,
1117
+ dependencies: [`task-${taskCounter - 1}`]
1118
+ });
1119
+ }
1120
+ if (tasks.length === 0) {
1121
+ tasks.push(
1122
+ {
1123
+ id: "task-1",
1124
+ name: "Setup project environment",
1125
+ type: "setup",
1126
+ status: "pending",
1127
+ priority: "high",
1128
+ estimatedHours: 4,
1129
+ assignee: null,
1130
+ dependencies: []
1131
+ },
1132
+ {
1133
+ id: "task-2",
1134
+ name: "Define project requirements",
1135
+ type: "analysis",
1136
+ status: "pending",
1137
+ priority: "high",
1138
+ estimatedHours: 8,
1139
+ assignee: null,
1140
+ dependencies: ["task-1"]
1141
+ },
1142
+ {
1143
+ id: "task-3",
1144
+ name: "Implement core functionality",
1145
+ type: "implementation",
1146
+ status: "pending",
1147
+ priority: "high",
1148
+ estimatedHours: 24,
1149
+ assignee: null,
1150
+ dependencies: ["task-2"]
1151
+ },
1152
+ {
1153
+ id: "task-4",
1154
+ name: "Test and validate",
1155
+ type: "verification",
1156
+ status: "pending",
1157
+ priority: "medium",
1158
+ estimatedHours: 8,
1159
+ assignee: null,
1160
+ dependencies: ["task-3"]
1161
+ },
1162
+ {
1163
+ id: "task-5",
1164
+ name: "Document and deliver",
1165
+ type: "delivery",
1166
+ status: "pending",
1167
+ priority: "medium",
1168
+ estimatedHours: 4,
1169
+ assignee: null,
1170
+ dependencies: ["task-4"]
1171
+ }
1172
+ );
1173
+ }
1174
+ return tasks;
1175
+ }
1176
+ /**
1177
+ * Build a timeline for the project based on tasks and milestones.
1178
+ */
1179
+ createTimeline(project) {
1180
+ const totalTasks = project.tasks.size;
1181
+ const estimatedHours = totalTasks * 8;
1182
+ const estimatedDays = Math.ceil(estimatedHours / 8);
1183
+ const startDate = project.startDate;
1184
+ const endDate = new Date(startDate);
1185
+ endDate.setDate(endDate.getDate() + estimatedDays);
1186
+ return {
1187
+ startDate: startDate.toISOString(),
1188
+ endDate: endDate.toISOString(),
1189
+ totalDays: estimatedDays,
1190
+ totalHours: estimatedHours,
1191
+ workingHoursPerDay: 8,
1192
+ phases: Array.from(project.milestones.entries()).map(
1193
+ ([id, milestone]) => ({
1194
+ milestoneId: id,
1195
+ milestone
1196
+ })
1197
+ ),
1198
+ criticalPath: Array.from(project.tasks.keys()),
1199
+ bufferDays: Math.ceil(estimatedDays * 0.2)
1200
+ };
1201
+ }
1202
+ /**
1203
+ * Create a resource allocation plan for the project.
1204
+ */
1205
+ planResources(project) {
1206
+ const teamSize = project.team.size;
1207
+ const taskCount = project.tasks.size;
1208
+ return {
1209
+ team: {
1210
+ current: teamSize,
1211
+ required: Math.max(teamSize, Math.ceil(taskCount / 5)),
1212
+ utilization: teamSize > 0 ? Math.min(1, taskCount / (teamSize * 5)) : 0
1213
+ },
1214
+ budget: {
1215
+ estimated: taskCount * 500,
1216
+ allocated: 0,
1217
+ contingency: taskCount * 100
1218
+ },
1219
+ tools: {
1220
+ required: ["version-control", "ci-cd", "monitoring", "communication"],
1221
+ available: ["version-control", "communication"],
1222
+ gaps: ["ci-cd", "monitoring"]
1223
+ },
1224
+ infrastructure: {
1225
+ compute: "standard",
1226
+ storage: "standard",
1227
+ networking: "standard"
1228
+ }
1229
+ };
1230
+ }
1231
+ /**
1232
+ * Assess potential risks for the project and return a list of risk records.
1233
+ */
1234
+ assessRisks(project) {
1235
+ const risks = [
1236
+ {
1237
+ id: "risk-1",
1238
+ name: "Scope creep",
1239
+ category: "scope",
1240
+ probability: 0.6,
1241
+ impact: 0.7,
1242
+ severity: 0.42,
1243
+ mitigation: "Strict change control process and regular scope reviews",
1244
+ status: "identified"
1245
+ },
1246
+ {
1247
+ id: "risk-2",
1248
+ name: "Resource unavailability",
1249
+ category: "resource",
1250
+ probability: 0.3,
1251
+ impact: 0.8,
1252
+ severity: 0.24,
1253
+ mitigation: "Cross-training and backup resource identification",
1254
+ status: "identified"
1255
+ },
1256
+ {
1257
+ id: "risk-3",
1258
+ name: "Technical complexity",
1259
+ category: "technical",
1260
+ probability: 0.5,
1261
+ impact: 0.6,
1262
+ severity: 0.3,
1263
+ mitigation: "Proof of concept and incremental development approach",
1264
+ status: "identified"
1265
+ },
1266
+ {
1267
+ id: "risk-4",
1268
+ name: "Timeline pressure",
1269
+ category: "schedule",
1270
+ probability: 0.4,
1271
+ impact: 0.7,
1272
+ severity: 0.28,
1273
+ mitigation: "Buffer time allocation and milestone tracking",
1274
+ status: "identified"
1275
+ }
1276
+ ];
1277
+ if (project.constraints.length > 0) {
1278
+ risks.push({
1279
+ id: "risk-5",
1280
+ name: "Constraint violations",
1281
+ category: "compliance",
1282
+ probability: 0.3,
1283
+ impact: 0.9,
1284
+ severity: 0.27,
1285
+ mitigation: "Regular constraint validation and compliance checks",
1286
+ status: "identified"
1287
+ });
1288
+ }
1289
+ return risks;
1290
+ }
1291
+ /**
1292
+ * Analyze the team requirements for a project based on its type and scope.
1293
+ */
1294
+ analyzeTeamRequirements(project) {
1295
+ const roleMap = {
1296
+ standard: ["project-lead", "developer", "tester", "reviewer"],
1297
+ agile: ["product-owner", "scrum-master", "developer", "tester"],
1298
+ research: ["principal-investigator", "researcher", "analyst"]
1299
+ };
1300
+ const roles = roleMap[project.type] || roleMap["standard"];
1301
+ const skillMap = {
1302
+ standard: ["planning", "development", "testing", "communication"],
1303
+ agile: ["agile-methodology", "development", "testing", "collaboration"],
1304
+ research: ["research-methodology", "data-analysis", "writing", "critical-thinking"]
1305
+ };
1306
+ const skills = skillMap[project.type] || skillMap["standard"];
1307
+ return {
1308
+ roles,
1309
+ skills,
1310
+ minSize: roles.length,
1311
+ maxSize: roles.length * 2
1312
+ };
1313
+ }
1314
+ /**
1315
+ * Return the capabilities expected for a given team role.
1316
+ */
1317
+ getRoleCapabilities(role) {
1318
+ const capabilityMap = {
1319
+ "project-lead": ["planning", "coordination", "decision-making", "reporting"],
1320
+ "product-owner": ["backlog-management", "prioritization", "stakeholder-communication"],
1321
+ "scrum-master": ["facilitation", "impediment-removal", "process-improvement"],
1322
+ developer: ["coding", "testing", "code-review", "documentation"],
1323
+ designer: ["ui-design", "ux-research", "prototyping", "visual-design"],
1324
+ tester: ["test-planning", "test-execution", "bug-reporting", "automation"],
1325
+ reviewer: ["code-review", "quality-assessment", "feedback", "standards-enforcement"],
1326
+ analyst: ["data-analysis", "reporting", "requirements-gathering", "modeling"],
1327
+ "principal-investigator": ["research-design", "methodology", "publication", "mentoring"],
1328
+ researcher: ["data-collection", "analysis", "literature-review", "experimentation"]
1329
+ };
1330
+ return capabilityMap[role] || ["general-support", "collaboration"];
1331
+ }
1332
+ /**
1333
+ * Execute a single task and return the result.
1334
+ */
1335
+ async executeTask(task) {
1336
+ const startTime = Date.now();
1337
+ try {
1338
+ this.currentTask = task.id;
1339
+ this.status = "working";
1340
+ const taskType = task.type || "general";
1341
+ let output;
1342
+ switch (taskType) {
1343
+ case "analysis":
1344
+ output = {
1345
+ analyzed: true,
1346
+ findings: [],
1347
+ recommendations: []
1348
+ };
1349
+ break;
1350
+ case "implementation":
1351
+ output = {
1352
+ implemented: true,
1353
+ artifacts: [],
1354
+ testsWritten: 0
1355
+ };
1356
+ break;
1357
+ case "verification":
1358
+ output = {
1359
+ verified: true,
1360
+ testsPassed: 0,
1361
+ testsFailed: 0,
1362
+ coverage: 0
1363
+ };
1364
+ break;
1365
+ case "setup":
1366
+ output = {
1367
+ environmentReady: true,
1368
+ toolsInstalled: [],
1369
+ configurationComplete: true
1370
+ };
1371
+ break;
1372
+ case "delivery":
1373
+ output = {
1374
+ delivered: true,
1375
+ artifacts: [],
1376
+ documentation: true
1377
+ };
1378
+ break;
1379
+ default:
1380
+ output = {
1381
+ completed: true,
1382
+ type: taskType
1383
+ };
1384
+ break;
1385
+ }
1386
+ const duration = Date.now() - startTime;
1387
+ this.currentTask = null;
1388
+ this.status = "active";
1389
+ const totalCompleted = this.performanceMetrics.tasksCompleted + 1;
1390
+ this.performanceMetrics.averageCompletionTime = (this.performanceMetrics.averageCompletionTime * this.performanceMetrics.tasksCompleted + duration) / totalCompleted;
1391
+ return {
1392
+ success: true,
1393
+ output,
1394
+ duration
1395
+ };
1396
+ } catch (error) {
1397
+ const errorMessage = error instanceof Error ? error.message : String(error);
1398
+ this.currentTask = null;
1399
+ this.status = "active";
1400
+ return {
1401
+ success: false,
1402
+ error: errorMessage,
1403
+ duration: Date.now() - startTime
1404
+ };
1405
+ }
1406
+ }
1407
+ /**
1408
+ * Determine if a project phase is complete by checking task statuses.
1409
+ */
1410
+ isPhaseComplete(project, phaseIndex) {
1411
+ const tasks = Array.from(project.tasks.entries());
1412
+ const tasksPerPhase = Math.max(1, Math.ceil(tasks.length / 5));
1413
+ const startIdx = phaseIndex * tasksPerPhase;
1414
+ const endIdx = Math.min(startIdx + tasksPerPhase, tasks.length);
1415
+ for (let i = startIdx; i < endIdx; i++) {
1416
+ if (i < tasks.length) {
1417
+ const task = tasks[i][1];
1418
+ if (task.status !== "completed") {
1419
+ return false;
1420
+ }
1421
+ }
1422
+ }
1423
+ return true;
1424
+ }
1425
+ /**
1426
+ * Assess overall project health across timeline, quality, resources,
1427
+ * and risks dimensions.
1428
+ */
1429
+ assessProjectHealth(project) {
1430
+ const timelineHealth = this.assessTimelineHealth(project);
1431
+ const qualityHealth = this.assessQualityHealth(project);
1432
+ const resourceHealth = this.assessResourceHealth(project);
1433
+ const riskHealth = this.assessRiskHealth(project);
1434
+ const overallScore = timelineHealth * 0.3 + qualityHealth * 0.3 + resourceHealth * 0.2 + riskHealth * 0.2;
1435
+ let overall;
1436
+ if (overallScore >= 0.8) {
1437
+ overall = "healthy";
1438
+ } else if (overallScore >= 0.6) {
1439
+ overall = "at-risk";
1440
+ } else if (overallScore >= 0.4) {
1441
+ overall = "critical";
1442
+ } else {
1443
+ overall = "failing";
1444
+ }
1445
+ return {
1446
+ overall,
1447
+ score: Math.round(overallScore * 100) / 100,
1448
+ timeline: timelineHealth >= 0.7 ? "on-track" : "delayed",
1449
+ quality: qualityHealth >= 0.7 ? "acceptable" : "below-standard",
1450
+ resources: resourceHealth >= 0.7 ? "adequate" : "constrained",
1451
+ risks: riskHealth >= 0.7 ? "managed" : "elevated",
1452
+ details: {
1453
+ timelineScore: timelineHealth,
1454
+ qualityScore: qualityHealth,
1455
+ resourceScore: resourceHealth,
1456
+ riskScore: riskHealth
1457
+ }
1458
+ };
1459
+ }
1460
+ /**
1461
+ * Assess the timeline health of the project (0.0 - 1.0).
1462
+ */
1463
+ assessTimelineHealth(project) {
1464
+ const totalTasks = project.tasks.size;
1465
+ if (totalTasks === 0) return 1;
1466
+ let completedTasks = 0;
1467
+ for (const [, task] of project.tasks) {
1468
+ if (task.status === "completed") {
1469
+ completedTasks++;
1470
+ }
1471
+ }
1472
+ const completionRatio = completedTasks / totalTasks;
1473
+ const expectedProgress = project.progress / 100;
1474
+ const deviation = Math.abs(completionRatio - expectedProgress);
1475
+ return Math.max(0, 1 - deviation);
1476
+ }
1477
+ /**
1478
+ * Assess the quality health of the project (0.0 - 1.0).
1479
+ */
1480
+ assessQualityHealth(_project) {
1481
+ if (this.performanceMetrics.tasksCompleted === 0) return 1;
1482
+ return this.performanceMetrics.successRate;
1483
+ }
1484
+ /**
1485
+ * Assess the resource health of the project (0.0 - 1.0).
1486
+ */
1487
+ assessResourceHealth(project) {
1488
+ const resources = project.resources;
1489
+ if (!resources || Object.keys(resources).length === 0) return 0.8;
1490
+ const budget = resources.budget;
1491
+ if (budget && typeof budget.total === "number" && typeof budget.spent === "number") {
1492
+ const budgetRatio = budget.total > 0 ? 1 - budget.spent / budget.total : 1;
1493
+ return Math.max(0, Math.min(1, budgetRatio));
1494
+ }
1495
+ return 0.8;
1496
+ }
1497
+ /**
1498
+ * Assess the risk health of the project (0.0 - 1.0).
1499
+ */
1500
+ assessRiskHealth(project) {
1501
+ const riskCount = project.risks.size;
1502
+ if (riskCount === 0) return 1;
1503
+ let totalSeverity = 0;
1504
+ for (const [, risk] of project.risks) {
1505
+ const r = risk;
1506
+ totalSeverity += r.severity || 0;
1507
+ }
1508
+ const avgSeverity = totalSeverity / riskCount;
1509
+ return Math.max(0, 1 - avgSeverity);
1510
+ }
1511
+ /**
1512
+ * Adjust the project plan to address health assessment findings.
1513
+ */
1514
+ async adjustProjectPlan(project, health) {
1515
+ console.log(`[Agent:${this.agentId}] Adjusting project plan based on health assessment...`);
1516
+ if (health.timeline === "delayed") {
1517
+ console.log(`[Agent:${this.agentId}] Addressing timeline delays...`);
1518
+ this.accelerateProject(project);
1519
+ }
1520
+ if (health.quality === "below-standard") {
1521
+ console.log(`[Agent:${this.agentId}] Addressing quality issues...`);
1522
+ this.improveQuality(project);
1523
+ }
1524
+ if (health.resources === "constrained") {
1525
+ console.log(`[Agent:${this.agentId}] Addressing resource constraints...`);
1526
+ this.optimizeResources(project);
1527
+ }
1528
+ console.log(`[Agent:${this.agentId}] Project plan adjusted`);
1529
+ }
1530
+ /**
1531
+ * Accelerate project execution by reprioritizing tasks.
1532
+ */
1533
+ accelerateProject(project) {
1534
+ for (const [, task] of project.tasks) {
1535
+ const t = task;
1536
+ if (t.status === "pending" && t.priority === "medium") {
1537
+ t.priority = "high";
1538
+ }
1539
+ if (t.status === "pending" && typeof t.estimatedHours === "number") {
1540
+ t.estimatedHours = Math.ceil(t.estimatedHours * 0.8);
1541
+ }
1542
+ }
1543
+ console.log(`[Agent:${this.agentId}] Tasks reprioritized and estimates reduced for acceleration`);
1544
+ }
1545
+ /**
1546
+ * Improve quality by adding quality gates to the project.
1547
+ */
1548
+ improveQuality(project) {
1549
+ project.qualityGates = [
1550
+ "code-review-required",
1551
+ "testing-threshold-80",
1552
+ "documentation-required",
1553
+ "peer-approval-required"
1554
+ ];
1555
+ console.log(`[Agent:${this.agentId}] Quality gates added: ${project.qualityGates.length} gates`);
1556
+ }
1557
+ /**
1558
+ * Optimize resource usage by consolidating and redistributing.
1559
+ */
1560
+ optimizeResources(project) {
1561
+ const resources = project.resources;
1562
+ if (resources && resources.budget) {
1563
+ const budget = resources.budget;
1564
+ if (typeof budget.contingency === "number") {
1565
+ const released = Math.ceil(budget.contingency * 0.5);
1566
+ budget.contingency = budget.contingency - released;
1567
+ budget.remaining = (budget.remaining || 0) + released;
1568
+ }
1569
+ }
1570
+ console.log(`[Agent:${this.agentId}] Resources optimized with contingency reallocation`);
1571
+ }
1572
+ /**
1573
+ * Perform a quality check on the project deliverables.
1574
+ */
1575
+ performQualityCheck(project) {
1576
+ const totalTasks = project.tasks.size;
1577
+ let completedTasks = 0;
1578
+ let failedTasks = 0;
1579
+ for (const [, task] of project.tasks) {
1580
+ const t = task;
1581
+ if (t.status === "completed") completedTasks++;
1582
+ if (t.status === "failed") failedTasks++;
1583
+ }
1584
+ const completionRate = totalTasks > 0 ? completedTasks / totalTasks : 0;
1585
+ const failureRate = totalTasks > 0 ? failedTasks / totalTasks : 0;
1586
+ const qualityScore = Math.max(0, completionRate - failureRate * 0.5);
1587
+ return {
1588
+ score: Math.round(qualityScore * 100) / 100,
1589
+ completionRate: Math.round(completionRate * 100) / 100,
1590
+ failureRate: Math.round(failureRate * 100) / 100,
1591
+ totalTasks,
1592
+ completedTasks,
1593
+ failedTasks,
1594
+ qualityGatesPassed: project.qualityGates ? project.qualityGates.length : 0,
1595
+ recommendation: qualityScore >= 0.8 ? "Ready for delivery" : qualityScore >= 0.6 ? "Needs minor improvements" : "Requires significant rework"
1596
+ };
1597
+ }
1598
+ /**
1599
+ * Prepare the final deliverables summary for the project.
1600
+ */
1601
+ prepareDeliverables(project) {
1602
+ const artifacts = [];
1603
+ for (const [taskId, task] of project.tasks) {
1604
+ const t = task;
1605
+ if (t.status === "completed" && t.result) {
1606
+ artifacts.push({
1607
+ taskId,
1608
+ taskName: t.name,
1609
+ type: t.type,
1610
+ result: t.result
1611
+ });
1612
+ }
1613
+ }
1614
+ return {
1615
+ projectId: project.id,
1616
+ projectName: project.name,
1617
+ deliveryDate: (/* @__PURE__ */ new Date()).toISOString(),
1618
+ artifacts,
1619
+ documentation: {
1620
+ readme: true,
1621
+ changelog: true,
1622
+ apiDocs: false
1623
+ },
1624
+ summary: {
1625
+ totalArtifacts: artifacts.length,
1626
+ totalTasks: project.tasks.size,
1627
+ completedTasks: artifacts.length,
1628
+ qualityScore: project.qualityScore || 0,
1629
+ duration: project.endDate ? project.endDate.getTime() - project.startDate.getTime() : Date.now() - project.startDate.getTime()
1630
+ }
1631
+ };
1632
+ }
1633
+ /**
1634
+ * Return a status snapshot for this agent.
1635
+ */
1636
+ getAgentStatus() {
1637
+ return {
1638
+ agentId: this.agentId,
1639
+ agentType: this.agentType,
1640
+ isActive: this.isActive,
1641
+ status: this.status,
1642
+ autonomyLevel: this.autonomyLevel,
1643
+ currentTask: this.currentTask,
1644
+ activeProjects: this.currentProjects.size,
1645
+ performanceMetrics: { ...this.performanceMetrics },
1646
+ teamSize: this.teamMembers.length,
1647
+ knowledgeBaseSize: this.knowledgeBase.size,
1648
+ skillLevels: Object.fromEntries(this.skillLevels),
1649
+ adaptationRate: this.adaptationRate,
1650
+ capabilities: { ...this.capabilities }
1651
+ };
1652
+ }
1653
+ /**
1654
+ * Generate a unique project identifier.
1655
+ */
1656
+ generateProjectId() {
1657
+ return `proj-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1658
+ }
1659
+ };
1660
+ export {
1661
+ BaselineCommandSystem,
1662
+ MEGAGEMAutonomousAgent,
1663
+ MEGAGEMCoreSystem
1664
+ };