@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.cjs ADDED
@@ -0,0 +1,3488 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ BaselineCommandSystem: () => BaselineCommandSystem,
34
+ MEGAGEMAutonomousAgent: () => MEGAGEMAutonomousAgent,
35
+ MEGAGEMCoreSystem: () => MEGAGEMCoreSystem
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/commands.ts
40
+ var import_experience = require("@baselineos/experience");
41
+ var import_govern = require("@baselineos/govern");
42
+ var import_promises = require("fs/promises");
43
+ var import_node_path = __toESM(require("path"), 1);
44
+ var BaselineCommandSystem = class {
45
+ state;
46
+ megagem;
47
+ contextEngine;
48
+ baselineLang;
49
+ constructor() {
50
+ this.state = {
51
+ customContextFolder: null,
52
+ baselineMode: false,
53
+ commandQueue: [],
54
+ executionHistory: [],
55
+ currentWorkflow: null
56
+ };
57
+ this.megagem = null;
58
+ this.contextEngine = null;
59
+ this.baselineLang = {
60
+ lexicon: this.initializeBaselineLexicon(),
61
+ syntax: this.initializeBaselineSyntax(),
62
+ commands: this.initializeBaselineCommands()
63
+ };
64
+ }
65
+ /**
66
+ * Initialize the Baseline lexicon with all recognized flags and their
67
+ * descriptions, usage patterns, categories, and examples.
68
+ */
69
+ initializeBaselineLexicon() {
70
+ return {
71
+ "--onboard": {
72
+ description: "Guided 20-minute onboarding flow to set up a team and run Baseline",
73
+ usage: "--onboard [--name <full-name>] [--role <role>] [--email <email>] [--company <name>] [--team <name>] [--project <name>] [--language <code>] [--learning-style <style>] [--pace <speed>] [--focus <focus>] [--learning-path <path>] [--context <path>] [--mode <mode>] [--skip-workflow] [--fresh] [--interactive]",
74
+ category: "onboarding",
75
+ examples: [
76
+ '--onboard --team "Acme Corp" --project "AI Governance"',
77
+ '--onboard --name "Amani" --role "Platform Lead" --team "GTCX Protocol"',
78
+ "--onboard --language en --learning-style visual --pace fast --focus practical --learning-path standard",
79
+ "--onboard --context ./my-project --mode production",
80
+ "--onboard --skip-workflow",
81
+ "--onboard --fresh",
82
+ "--onboard --interactive"
83
+ ]
84
+ },
85
+ "--experience": {
86
+ description: "Run an immersive experience sequence based on learning path",
87
+ usage: "--experience [--learning-path <path>] [--experiences <id,id>] [--context <path>] [--fresh]",
88
+ category: "onboarding",
89
+ examples: [
90
+ "--experience --learning-path standard",
91
+ "--experience --learning-path accelerated",
92
+ "--experience --experiences welcome-journey,ai-collaboration",
93
+ "--experience --fresh"
94
+ ]
95
+ },
96
+ "--config": {
97
+ description: "Configure Baseline preferences and settings",
98
+ usage: "--config <section> [--set <value>] [--region <value>] [--standards <csv>] [--enable <csv>] [--context <path>]",
99
+ category: "setup",
100
+ examples: [
101
+ "--config show",
102
+ "--config language --set en",
103
+ "--config culture --region latin-america --business-style relationship-focused",
104
+ "--config compliance --region eu --standards gdpr,iso27001",
105
+ "--config accessibility --screen-reader --high-contrast"
106
+ ]
107
+ },
108
+ "--index": {
109
+ description: "Index docs or context for retrieval",
110
+ usage: "--index [--paths <csv>] [--context <path>] [--max <n>]",
111
+ category: "setup",
112
+ examples: ["--index", "--index --paths docs,README.md", "--index --max 500"]
113
+ },
114
+ "--serve": {
115
+ description: "Start the Baseline MCP server (stdio) and optional API server",
116
+ usage: "--serve [--api] [--port <n>] [--context <path>] [--once]",
117
+ category: "setup",
118
+ examples: ["--serve", "--serve --api --port 3141", "--serve --once"]
119
+ },
120
+ "--agents": {
121
+ description: "Show agent registry status",
122
+ usage: "--agents [--context <path>]",
123
+ category: "info",
124
+ examples: ["--agents", "--agents --context ./project"]
125
+ },
126
+ "--doctor": {
127
+ description: "Run diagnostics for Baseline configuration and readiness",
128
+ usage: "--doctor [--context <path>]",
129
+ category: "diagnostics",
130
+ examples: ["--doctor", "--doctor --context ./project"]
131
+ },
132
+ "--baseline": {
133
+ description: "Execute the full Baseline Protocol workflow across all layers",
134
+ usage: "--baseline [options]",
135
+ category: "core",
136
+ examples: [
137
+ "--baseline",
138
+ "--baseline --context ./my-project",
139
+ "--baseline --mode production"
140
+ ]
141
+ },
142
+ "--run": {
143
+ description: "Run the full Baseline workflow (alias for --baseline)",
144
+ usage: "--run [--context <path>] [--mode <mode>]",
145
+ category: "core",
146
+ examples: ["--run", "--run --context ./project --mode development"]
147
+ },
148
+ "--init": {
149
+ description: "Initialize Baseline and optionally write config",
150
+ usage: "--init [--context <path>] [--mode <mode>] [--write-config]",
151
+ category: "setup",
152
+ examples: ["--init", "--init --write-config", "--init --context ./project"]
153
+ },
154
+ "--baseline-lang": {
155
+ description: "Execute the Baseline language processing layer",
156
+ usage: "--baseline-lang [options]",
157
+ category: "layer",
158
+ examples: [
159
+ "--baseline-lang",
160
+ "--baseline-lang --parse",
161
+ "--baseline-lang --validate"
162
+ ]
163
+ },
164
+ "--baseline-frame": {
165
+ description: "Execute the Baseline framework orchestration layer",
166
+ usage: "--baseline-frame [options]",
167
+ category: "layer",
168
+ examples: [
169
+ "--baseline-frame",
170
+ "--baseline-frame --scaffold",
171
+ "--baseline-frame --compose"
172
+ ]
173
+ },
174
+ "--baseline-studio": {
175
+ description: "Execute the Baseline studio design and rendering layer",
176
+ usage: "--baseline-studio [options]",
177
+ category: "layer",
178
+ examples: [
179
+ "--baseline-studio",
180
+ "--baseline-studio --render",
181
+ "--baseline-studio --preview"
182
+ ]
183
+ },
184
+ "--baseline-govern": {
185
+ description: "Execute the Baseline governance and compliance layer",
186
+ usage: "--baseline-govern [options]",
187
+ category: "layer",
188
+ examples: [
189
+ "--baseline-govern",
190
+ "--baseline-govern --audit",
191
+ "--baseline-govern --policy"
192
+ ]
193
+ }
194
+ };
195
+ }
196
+ /**
197
+ * Initialize syntax patterns for the command system, defining parameter
198
+ * schemas and usage examples for each pattern.
199
+ */
200
+ initializeBaselineSyntax() {
201
+ return {
202
+ onboarding: {
203
+ pattern: "--onboard [--name <full-name>] [--role <role>] [--email <email>] [--company <name>] [--team <name>] [--project <name>] [--language <code>] [--learning-style <style>] [--pace <speed>] [--focus <focus>] [--learning-path <path>] [--context <path>] [--mode <mode>] [--skip-workflow] [--fresh] [--interactive]",
204
+ parameters: {
205
+ name: "Your name for onboarding personalization",
206
+ role: "Your role (optional)",
207
+ email: "Your email (optional)",
208
+ company: "Company name for the onboarding profile",
209
+ team: "Team name to onboard (optional)",
210
+ project: "Project name to initialize (optional)",
211
+ language: "Preferred language (en, es, fr, de, ja, zh, ko, ar, hi, pt)",
212
+ "learning-style": "Learning style (visual, auditory, kinesthetic, reading)",
213
+ pace: "Learning pace (slow, moderate, fast, lightning)",
214
+ focus: "Learning focus (practical, theoretical, mixed)",
215
+ "learning-path": "Learning path (standard, accelerated, hands-on, theoretical)",
216
+ context: "Path to the project context folder",
217
+ mode: "Execution mode: development | staging | production",
218
+ "skip-workflow": "Skip running the Baseline workflow after onboarding",
219
+ fresh: "Start onboarding from scratch and overwrite any saved profile",
220
+ interactive: "Prompt for onboarding inputs"
221
+ },
222
+ examples: [
223
+ '--onboard --team "Acme" --project "AI Governance"',
224
+ '--onboard --name "Amani" --role "Engineering" --company "GTCX Dev"',
225
+ "--onboard --language en --learning-style visual --learning-path standard",
226
+ "--onboard --context ./project --mode development",
227
+ "--onboard --skip-workflow",
228
+ "--onboard --fresh",
229
+ "--onboard --interactive"
230
+ ]
231
+ },
232
+ experience: {
233
+ pattern: "--experience [--learning-path <path>] [--experiences <id,id>] [--context <path>] [--fresh]",
234
+ parameters: {
235
+ "learning-path": "Learning path (standard, accelerated, hands-on, theoretical)",
236
+ experiences: "Comma-separated experience ids to run",
237
+ context: "Path to the project context folder",
238
+ fresh: "Reset onboarding profile before running experiences"
239
+ },
240
+ examples: [
241
+ "--experience --learning-path standard",
242
+ "--experience --learning-path accelerated",
243
+ "--experience --experiences welcome-journey,ai-collaboration",
244
+ "--experience --fresh"
245
+ ]
246
+ },
247
+ config: {
248
+ pattern: "--config <section> [--set <value>] [--region <value>] [--standards <csv>] [--enable <csv>] [--context <path>]",
249
+ parameters: {
250
+ section: "Config section: show | language | culture | compliance | accessibility",
251
+ set: "Set a value for a given section",
252
+ region: "Set a region for culture/compliance",
253
+ standards: "Comma-separated standards list for compliance",
254
+ enable: "Comma-separated accessibility features to enable",
255
+ context: "Path to the project context folder"
256
+ },
257
+ examples: [
258
+ "--config show",
259
+ "--config language --set en",
260
+ "--config culture --region latin-america --business-style relationship-focused",
261
+ "--config compliance --region eu --standards gdpr,iso27001",
262
+ "--config accessibility --screen-reader --high-contrast"
263
+ ]
264
+ },
265
+ index: {
266
+ pattern: "--index [--paths <csv>] [--context <path>] [--max <n>]",
267
+ parameters: {
268
+ paths: "Comma-separated list of paths to index",
269
+ context: "Context path to resolve relative paths",
270
+ max: "Maximum number of entries to index"
271
+ },
272
+ examples: ["--index", "--index --paths docs,README.md", "--index --max 500"]
273
+ },
274
+ serve: {
275
+ pattern: "--serve [--api] [--port <n>] [--context <path>] [--once]",
276
+ parameters: {
277
+ api: "Start the HTTP/WebSocket API server alongside MCP",
278
+ port: "Port for the API server (default: 3141)",
279
+ context: "Path to the project context folder",
280
+ once: "Start then return immediately (for scripting)"
281
+ },
282
+ examples: ["--serve", "--serve --api --port 3141", "--serve --once"]
283
+ },
284
+ agents: {
285
+ pattern: "--agents [--context <path>]",
286
+ parameters: {
287
+ context: "Path to the project context folder"
288
+ },
289
+ examples: ["--agents", "--agents --context ./project"]
290
+ },
291
+ doctor: {
292
+ pattern: "--doctor [--context <path>]",
293
+ parameters: {
294
+ context: "Path to the project context folder"
295
+ },
296
+ examples: ["--doctor", "--doctor --context ./project"]
297
+ },
298
+ workflow: {
299
+ pattern: "--baseline [--context <path>] [--mode <mode>] [--verbose]",
300
+ parameters: {
301
+ context: "Path to the project context folder",
302
+ mode: "Execution mode: development | staging | production",
303
+ verbose: "Enable verbose logging output"
304
+ },
305
+ examples: [
306
+ "--baseline --context ./project --mode development",
307
+ "--baseline --mode production --verbose"
308
+ ]
309
+ },
310
+ run: {
311
+ pattern: "--run [--context <path>] [--mode <mode>]",
312
+ parameters: {
313
+ context: "Path to the project context folder",
314
+ mode: "Execution mode: development | staging | production"
315
+ },
316
+ examples: ["--run", "--run --context ./project --mode development"]
317
+ },
318
+ init: {
319
+ pattern: "--init [--context <path>] [--mode <mode>] [--write-config]",
320
+ parameters: {
321
+ context: "Path to the project context folder",
322
+ mode: "Execution mode: development | staging | production",
323
+ "write-config": "Persist baseline.config.json into .baseline/"
324
+ },
325
+ examples: ["--init --write-config", "--init --context ./project"]
326
+ },
327
+ layer: {
328
+ pattern: "--baseline-<layer> [--input <path>] [--output <path>] [--config <path>]",
329
+ parameters: {
330
+ layer: "Target layer: lang | frame | studio | govern",
331
+ input: "Input file or directory path",
332
+ output: "Output file or directory path",
333
+ config: "Layer-specific configuration file path"
334
+ },
335
+ examples: [
336
+ "--baseline-lang --input ./src --output ./dist",
337
+ "--baseline-frame --config ./baseline.config.json"
338
+ ]
339
+ },
340
+ chain: {
341
+ pattern: '--baseline-chain "<cmd1> | <cmd2> | <cmd3>"',
342
+ parameters: {
343
+ commands: "Pipe-delimited list of commands to execute sequentially"
344
+ },
345
+ examples: [
346
+ '--baseline-chain "--baseline-lang | --baseline-frame | --baseline-studio"',
347
+ '--baseline-chain "--init | --baseline"'
348
+ ]
349
+ },
350
+ queue: {
351
+ pattern: "--baseline-queue <add|run|clear|status>",
352
+ parameters: {
353
+ action: "Queue action to perform",
354
+ command: "Command to add (when using add)"
355
+ },
356
+ examples: [
357
+ "--baseline-queue add --baseline-lang",
358
+ "--baseline-queue run",
359
+ "--baseline-queue status"
360
+ ]
361
+ }
362
+ };
363
+ }
364
+ /**
365
+ * Initialize the built-in command registry with descriptions and action
366
+ * identifiers for each recognized command.
367
+ */
368
+ initializeBaselineCommands() {
369
+ return {
370
+ "--onboard": {
371
+ description: "Run a guided onboarding flow (team, project, system, workflow)",
372
+ action: "onboard",
373
+ category: "onboarding"
374
+ },
375
+ "--experience": {
376
+ description: "Run an immersive experience sequence based on learning path",
377
+ action: "experience",
378
+ category: "onboarding"
379
+ },
380
+ "--config": {
381
+ description: "Configure Baseline preferences and settings",
382
+ action: "config",
383
+ category: "setup"
384
+ },
385
+ "--index": {
386
+ description: "Index docs or context for retrieval",
387
+ action: "index",
388
+ category: "setup"
389
+ },
390
+ "--serve": {
391
+ description: "Start the Baseline server or MCP daemon (placeholder)",
392
+ action: "serve",
393
+ category: "setup"
394
+ },
395
+ "--persona": {
396
+ description: "Show persona status and available roles",
397
+ action: "persona",
398
+ category: "info"
399
+ },
400
+ "--agents": {
401
+ description: "Show agent registry status (placeholder)",
402
+ action: "agents",
403
+ category: "info"
404
+ },
405
+ "--doctor": {
406
+ description: "Run diagnostics for Baseline configuration and readiness",
407
+ action: "doctor",
408
+ category: "diagnostics"
409
+ },
410
+ "--init": {
411
+ description: "Initialize a new Baseline project in the current directory",
412
+ action: "initialize",
413
+ category: "setup"
414
+ },
415
+ "--run": {
416
+ description: "Run the full Baseline workflow with default settings",
417
+ action: "run",
418
+ category: "execution"
419
+ },
420
+ "--status": {
421
+ description: "Display the current status of the Baseline system and active workflows",
422
+ action: "status",
423
+ category: "info"
424
+ },
425
+ "--help": {
426
+ description: "Display help information for all available commands",
427
+ action: "help",
428
+ category: "info"
429
+ }
430
+ };
431
+ }
432
+ /**
433
+ * Execute the full Baseline Protocol workflow across all five layers:
434
+ * init -> lang -> frame -> studio -> govern
435
+ */
436
+ async executeBaselineWorkflow(options = {}) {
437
+ const workflowId = `wf-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
438
+ const workflow = {
439
+ id: workflowId,
440
+ startTime: /* @__PURE__ */ new Date(),
441
+ options,
442
+ status: "running"
443
+ };
444
+ this.state.currentWorkflow = workflow;
445
+ this.state.baselineMode = true;
446
+ console.log(`[Baseline] Starting workflow ${workflowId}`);
447
+ console.log(`[Baseline] Options: ${JSON.stringify(options)}`);
448
+ try {
449
+ console.log("[Baseline] Step 1/5: Initializing baseline environment...");
450
+ const initResult = await this.initializeBaseline(options);
451
+ if (!initResult.success) {
452
+ throw new Error(`Initialization failed: ${initResult.error || "unknown error"}`);
453
+ }
454
+ console.log("[Baseline] Step 1/5: Initialization complete.");
455
+ console.log("[Baseline] Step 2/5: Processing language layer...");
456
+ const langResult = await this.executeBaselineLang(options);
457
+ if (!langResult.success) {
458
+ throw new Error(`Language layer failed: ${langResult.error || "unknown error"}`);
459
+ }
460
+ console.log("[Baseline] Step 2/5: Language layer complete.");
461
+ console.log("[Baseline] Step 3/5: Processing frame layer...");
462
+ const frameResult = await this.executeBaselineFrame(options);
463
+ if (!frameResult.success) {
464
+ throw new Error(`Frame layer failed: ${frameResult.error || "unknown error"}`);
465
+ }
466
+ console.log("[Baseline] Step 3/5: Frame layer complete.");
467
+ console.log("[Baseline] Step 4/5: Processing studio layer...");
468
+ const studioResult = await this.executeBaselineStudio(options);
469
+ if (!studioResult.success) {
470
+ throw new Error(`Studio layer failed: ${studioResult.error || "unknown error"}`);
471
+ }
472
+ console.log("[Baseline] Step 4/5: Studio layer complete.");
473
+ console.log("[Baseline] Step 5/5: Processing governance layer...");
474
+ const governResult = await this.executeBaselineGovern(options);
475
+ if (!governResult.success) {
476
+ throw new Error(`Governance layer failed: ${governResult.error || "unknown error"}`);
477
+ }
478
+ console.log("[Baseline] Step 5/5: Governance layer complete.");
479
+ workflow.endTime = /* @__PURE__ */ new Date();
480
+ workflow.duration = workflow.endTime.getTime() - workflow.startTime.getTime();
481
+ workflow.status = "completed";
482
+ this.state.executionHistory.push(workflow);
483
+ this.state.currentWorkflow = null;
484
+ console.log(`[Baseline] Workflow ${workflowId} completed in ${workflow.duration}ms`);
485
+ return {
486
+ success: true,
487
+ workflow,
488
+ results: {
489
+ init: initResult,
490
+ lang: langResult,
491
+ frame: frameResult,
492
+ studio: studioResult,
493
+ govern: governResult
494
+ }
495
+ };
496
+ } catch (error) {
497
+ const errorMessage = error instanceof Error ? error.message : String(error);
498
+ workflow.endTime = /* @__PURE__ */ new Date();
499
+ workflow.duration = workflow.endTime.getTime() - workflow.startTime.getTime();
500
+ workflow.status = "failed";
501
+ workflow.error = errorMessage;
502
+ this.state.executionHistory.push(workflow);
503
+ this.state.currentWorkflow = null;
504
+ console.log(`[Baseline] Workflow ${workflowId} failed: ${errorMessage}`);
505
+ return {
506
+ success: false,
507
+ error: errorMessage,
508
+ workflow
509
+ };
510
+ }
511
+ }
512
+ normalizeString(value) {
513
+ if (typeof value === "string") {
514
+ const trimmed = value.trim();
515
+ return trimmed.length ? trimmed : void 0;
516
+ }
517
+ if (value === null || value === void 0) {
518
+ return void 0;
519
+ }
520
+ const text = String(value).trim();
521
+ return text.length ? text : void 0;
522
+ }
523
+ normalizeBoolean(value) {
524
+ if (typeof value === "boolean") return value;
525
+ if (typeof value === "string") {
526
+ return ["true", "1", "yes", "y"].includes(value.toLowerCase());
527
+ }
528
+ return false;
529
+ }
530
+ resolveContext(value, fallback) {
531
+ const resolved = this.normalizeString(value) || fallback || process.cwd();
532
+ return import_node_path.default.resolve(resolved);
533
+ }
534
+ async loadOnboardingProfile(context) {
535
+ const directory = import_node_path.default.join(context, ".baseline");
536
+ const filePath = import_node_path.default.join(directory, "onboarding.json");
537
+ try {
538
+ const raw = await (0, import_promises.readFile)(filePath, "utf8");
539
+ const parsed = JSON.parse(raw);
540
+ return { path: filePath, profile: parsed, exists: true };
541
+ } catch (err) {
542
+ const error = err;
543
+ if (error.code === "ENOENT") {
544
+ return { path: filePath, profile: null, exists: false };
545
+ }
546
+ return { path: filePath, profile: null, exists: false, error: error.message };
547
+ }
548
+ }
549
+ async saveOnboardingProfile(filePath, profile) {
550
+ await (0, import_promises.mkdir)(import_node_path.default.dirname(filePath), { recursive: true });
551
+ await (0, import_promises.writeFile)(filePath, JSON.stringify(profile, null, 2), "utf8");
552
+ }
553
+ async loadBaselineConfig(context) {
554
+ const directory = import_node_path.default.join(context, ".baseline");
555
+ const filePath = import_node_path.default.join(directory, "baseline.config.json");
556
+ try {
557
+ const raw = await (0, import_promises.readFile)(filePath, "utf8");
558
+ const parsed = JSON.parse(raw);
559
+ return { path: filePath, config: parsed, exists: true };
560
+ } catch (err) {
561
+ const error = err;
562
+ if (error.code === "ENOENT") {
563
+ return { path: filePath, config: null, exists: false };
564
+ }
565
+ return { path: filePath, config: null, exists: false, error: error.message };
566
+ }
567
+ }
568
+ async saveBaselineConfig(filePath, config) {
569
+ await (0, import_promises.mkdir)(import_node_path.default.dirname(filePath), { recursive: true });
570
+ await (0, import_promises.writeFile)(filePath, JSON.stringify(config, null, 2), "utf8");
571
+ }
572
+ async fileExists(filePath) {
573
+ try {
574
+ const result = await (0, import_promises.stat)(filePath);
575
+ return result.isFile() || result.isDirectory();
576
+ } catch {
577
+ return false;
578
+ }
579
+ }
580
+ buildDefaultConfig(context, profile) {
581
+ const now = (/* @__PURE__ */ new Date()).toISOString();
582
+ return {
583
+ version: 1,
584
+ context,
585
+ createdAt: now,
586
+ updatedAt: now,
587
+ language: profile?.preferences?.language || "en",
588
+ preferences: {
589
+ learningStyle: profile?.preferences?.learningStyle,
590
+ pace: profile?.preferences?.pace,
591
+ focus: profile?.preferences?.focus,
592
+ learningPath: profile?.preferences?.learningPath
593
+ },
594
+ culture: {},
595
+ compliance: {},
596
+ accessibility: {}
597
+ };
598
+ }
599
+ getExperienceCatalog() {
600
+ return {
601
+ "welcome-journey": {
602
+ id: "welcome-journey",
603
+ name: "Welcome Journey",
604
+ description: "Interactive introduction to Baseline and AI-native development.",
605
+ duration: "5-10 minutes",
606
+ difficulty: "beginner",
607
+ type: "story",
608
+ tags: ["onboarding", "introduction", "story"]
609
+ },
610
+ "acceleration-discovery": {
611
+ id: "acceleration-discovery",
612
+ name: "Acceleration Discovery",
613
+ description: "Experience the jump from 300x to 1,000,000x acceleration.",
614
+ duration: "10-15 minutes",
615
+ difficulty: "beginner",
616
+ type: "interactive",
617
+ tags: ["acceleration", "demo", "interactive"]
618
+ },
619
+ "ai-collaboration": {
620
+ id: "ai-collaboration",
621
+ name: "AI Collaboration Workshop",
622
+ description: "Learn to coordinate with autonomous AI systems.",
623
+ duration: "15-20 minutes",
624
+ difficulty: "intermediate",
625
+ type: "workshop",
626
+ tags: ["workshop", "ai", "collaboration"]
627
+ },
628
+ "quantum-leap": {
629
+ id: "quantum-leap",
630
+ name: "Quantum Leap Challenge",
631
+ description: "Tackle advanced challenges with quantum-level acceleration.",
632
+ duration: "20-30 minutes",
633
+ difficulty: "advanced",
634
+ type: "challenge",
635
+ tags: ["challenge", "quantum", "advanced"]
636
+ },
637
+ "singularity-mastery": {
638
+ id: "singularity-mastery",
639
+ name: "Singularity Mastery",
640
+ description: "Master the highest tiers of AI-native execution.",
641
+ duration: "30-45 minutes",
642
+ difficulty: "expert",
643
+ type: "mastery",
644
+ tags: ["mastery", "singularity", "expert"]
645
+ },
646
+ "concept-exploration": {
647
+ id: "concept-exploration",
648
+ name: "Concept Exploration",
649
+ description: "Deep dive into AI-native development concepts.",
650
+ duration: "15-20 minutes",
651
+ difficulty: "intermediate",
652
+ type: "theoretical",
653
+ tags: ["theoretical", "concepts", "learning"]
654
+ },
655
+ "theory-workshop": {
656
+ id: "theory-workshop",
657
+ name: "Theory Workshop",
658
+ description: "Explore the principles behind Baseline OS.",
659
+ duration: "25-35 minutes",
660
+ difficulty: "advanced",
661
+ type: "workshop",
662
+ tags: ["workshop", "theory", "principles"]
663
+ },
664
+ "advanced-concepts": {
665
+ id: "advanced-concepts",
666
+ name: "Advanced Concepts",
667
+ description: "Master advanced AI-native concepts and patterns.",
668
+ duration: "30-40 minutes",
669
+ difficulty: "expert",
670
+ type: "theoretical",
671
+ tags: ["theoretical", "advanced", "mastery"]
672
+ },
673
+ "workshop-series": {
674
+ id: "workshop-series",
675
+ name: "Workshop Series",
676
+ description: "Hands-on applied learning series.",
677
+ duration: "45-60 minutes",
678
+ difficulty: "intermediate",
679
+ type: "workshop",
680
+ tags: ["workshop", "series", "hands-on"]
681
+ }
682
+ };
683
+ }
684
+ getLearningPaths() {
685
+ return {
686
+ standard: {
687
+ name: "Standard Path",
688
+ experiences: ["welcome-journey", "acceleration-discovery", "ai-collaboration"]
689
+ },
690
+ accelerated: {
691
+ name: "Accelerated Path",
692
+ experiences: ["acceleration-discovery", "quantum-leap", "singularity-mastery"]
693
+ },
694
+ "hands-on": {
695
+ name: "Hands-On Path",
696
+ experiences: ["ai-collaboration", "quantum-leap", "workshop-series"]
697
+ },
698
+ theoretical: {
699
+ name: "Theoretical Path",
700
+ experiences: ["concept-exploration", "theory-workshop", "advanced-concepts"]
701
+ }
702
+ };
703
+ }
704
+ /**
705
+ * Execute a guided onboarding flow (team, project, system) and optionally
706
+ * run the full Baseline workflow. Designed for a 20-minute quickstart.
707
+ */
708
+ async executeOnboarding(options = {}) {
709
+ const startedAt = Date.now();
710
+ const context = this.resolveContext(options.context, process.cwd());
711
+ const forceFresh = this.normalizeBoolean(options.fresh) || this.normalizeBoolean(options.reset);
712
+ const existingProfile = forceFresh ? null : await this.loadOnboardingProfile(context);
713
+ const prior = existingProfile?.profile ?? null;
714
+ const name = this.normalizeString(options.name) || prior?.user?.name || "User";
715
+ const role = this.normalizeString(options.role) || prior?.user?.role || "Operator";
716
+ const email = this.normalizeString(options.email) || prior?.user?.email;
717
+ const company = this.normalizeString(options.company) || prior?.company || "Acme Corp";
718
+ const team = this.normalizeString(options.team) || prior?.team;
719
+ const project = this.normalizeString(options.project) || prior?.project;
720
+ const mode = this.normalizeString(options.mode) || prior?.mode || "development";
721
+ const language = this.normalizeString(options.language) || prior?.preferences?.language || "en";
722
+ const learningStyle = this.normalizeString(options["learning-style"]) || prior?.preferences?.learningStyle || "visual";
723
+ const pace = this.normalizeString(options.pace) || prior?.preferences?.pace || "moderate";
724
+ const focus = this.normalizeString(options.focus) || prior?.preferences?.focus || "practical";
725
+ const learningPath = this.normalizeString(options["learning-path"]) || prior?.preferences?.learningPath || "standard";
726
+ const skipWorkflow = this.normalizeBoolean(options["skip-workflow"]);
727
+ console.log("[Baseline:Onboarding] Starting 20-minute onboarding flow");
728
+ console.log(`[Baseline:Onboarding] Welcome: ${name} (${role})`);
729
+ console.log(`[Baseline:Onboarding] Language: ${language}`);
730
+ console.log(
731
+ `[Baseline:Onboarding] Learning path: ${learningPath} (${learningStyle}, ${pace}, ${focus})`
732
+ );
733
+ if (team) {
734
+ console.log(`[Baseline:Onboarding] Team: ${team}`);
735
+ }
736
+ console.log(`[Baseline:Onboarding] Company: ${company}`);
737
+ if (project) {
738
+ console.log(`[Baseline:Onboarding] Project: ${project}`);
739
+ }
740
+ console.log(`[Baseline:Onboarding] Context: ${context}`);
741
+ console.log(`[Baseline:Onboarding] Mode: ${mode}`);
742
+ if (existingProfile?.exists && !forceFresh) {
743
+ console.log("[Baseline:Onboarding] Resuming from saved onboarding profile");
744
+ }
745
+ if (skipWorkflow) {
746
+ console.log("[Baseline:Onboarding] Workflow execution skipped by flag");
747
+ }
748
+ const experience = new import_experience.BaselineExperienceSystem();
749
+ const systemResult = await experience.onboarding.system.initialize();
750
+ const systemId = systemResult.systemId || `system-${Date.now()}`;
751
+ const systemConfig = await experience.onboarding.system.configure(systemId, {
752
+ user: { name, role, email },
753
+ company,
754
+ team,
755
+ project,
756
+ context,
757
+ mode,
758
+ preferences: { language, learningStyle, pace, focus, learningPath }
759
+ });
760
+ let teamResult;
761
+ let teamConfig;
762
+ let teamId;
763
+ if (team) {
764
+ teamResult = await experience.onboarding.team.start(company);
765
+ teamId = teamResult.teamId ?? `team-${Date.now()}`;
766
+ teamConfig = await experience.onboarding.team.configure(teamId, {
767
+ user: { name, role, email },
768
+ team,
769
+ company,
770
+ mode
771
+ });
772
+ } else {
773
+ teamResult = { success: true, skipped: true, reason: "team not provided" };
774
+ teamConfig = { success: true, skipped: true, reason: "team not provided" };
775
+ }
776
+ let projectResult;
777
+ let projectConfig;
778
+ let projectId;
779
+ if (project) {
780
+ projectResult = await experience.onboarding.project.setup(project);
781
+ projectId = projectResult.projectId ?? `project-${Date.now()}`;
782
+ projectConfig = await experience.onboarding.project.configure(projectId, {
783
+ teamId,
784
+ context
785
+ });
786
+ } else {
787
+ projectResult = { success: true, skipped: true, reason: "project not provided" };
788
+ projectConfig = { success: true, skipped: true, reason: "project not provided" };
789
+ }
790
+ let workflow = null;
791
+ if (!skipWorkflow) {
792
+ workflow = await this.executeBaselineWorkflow({ context, mode });
793
+ }
794
+ const now = (/* @__PURE__ */ new Date()).toISOString();
795
+ const completedSteps = ["identity", "preferences", "workspace"];
796
+ if (!skipWorkflow) {
797
+ completedSteps.push("workflow");
798
+ }
799
+ const profile = {
800
+ version: 2,
801
+ createdAt: prior?.createdAt || now,
802
+ updatedAt: now,
803
+ user: { name, role, ...email ? { email } : {} },
804
+ company,
805
+ ...team ? { team } : {},
806
+ ...project ? { project } : {},
807
+ context,
808
+ mode,
809
+ preferences: { language, learningStyle, pace, focus, learningPath },
810
+ progress: {
811
+ completedSteps,
812
+ lastStep: completedSteps[completedSteps.length - 1],
813
+ lastCompletedAt: now
814
+ },
815
+ experiences: prior?.experiences ?? { completed: [] },
816
+ ...workflow?.workflow?.id ? { workflow: { lastRunAt: now, lastWorkflowId: workflow.workflow.id } } : {}
817
+ };
818
+ const storage = existingProfile ?? {
819
+ path: import_node_path.default.join(context, ".baseline", "onboarding.json"),
820
+ exists: false,
821
+ profile: null
822
+ };
823
+ let storageSaved = false;
824
+ let storageError;
825
+ try {
826
+ await this.saveOnboardingProfile(storage.path, profile);
827
+ storageSaved = true;
828
+ } catch (err) {
829
+ storageError = err instanceof Error ? err.message : String(err);
830
+ console.log(`[Baseline:Onboarding] Failed to save profile: ${storageError}`);
831
+ }
832
+ const success = systemResult.success && systemConfig.success && teamResult.success && teamConfig.success && projectResult.success && projectConfig.success && (workflow ? workflow.success : true);
833
+ return {
834
+ success,
835
+ onboarding: {
836
+ system: systemResult,
837
+ systemConfig,
838
+ user: { name, role, email },
839
+ preferences: { language, learningStyle, pace, focus, learningPath },
840
+ profile,
841
+ storage: {
842
+ path: storage.path,
843
+ saved: storageSaved,
844
+ error: storageError
845
+ },
846
+ team: teamResult,
847
+ teamConfig,
848
+ project: projectResult,
849
+ projectConfig
850
+ },
851
+ workflow,
852
+ nextSteps: [
853
+ "Run `baseline status` to verify layer status.",
854
+ "Run `baseline --baseline` to execute the full workflow.",
855
+ "Follow docs/experience/baseline-20-min-onboarding.md for mastery path."
856
+ ],
857
+ durationMs: Date.now() - startedAt
858
+ };
859
+ }
860
+ /**
861
+ * Execute an immersive experience sequence based on the selected learning path.
862
+ * Uses onboarding profile data and persists progress.
863
+ */
864
+ async executeExperience(options = {}) {
865
+ const context = this.resolveContext(options.context, process.cwd());
866
+ const forceFresh = this.normalizeBoolean(options.fresh) || this.normalizeBoolean(options.reset);
867
+ const storage = forceFresh ? null : await this.loadOnboardingProfile(context);
868
+ let profile = storage?.profile ?? null;
869
+ if (!profile) {
870
+ console.log("[Baseline:Experience] No onboarding profile found. Bootstrapping profile...");
871
+ const onboardingResult = await this.executeOnboarding({
872
+ ...options,
873
+ context,
874
+ "skip-workflow": true,
875
+ fresh: forceFresh
876
+ });
877
+ profile = onboardingResult.onboarding?.profile ?? null;
878
+ }
879
+ if (!profile) {
880
+ return { success: false, error: "Unable to load or create onboarding profile." };
881
+ }
882
+ const catalog = this.getExperienceCatalog();
883
+ const paths = this.getLearningPaths();
884
+ const learningPath = this.normalizeString(options["learning-path"]) || profile.preferences.learningPath || "standard";
885
+ const explicitList = this.normalizeString(options.experiences);
886
+ const requested = explicitList ? explicitList.split(",").map((entry) => entry.trim()).filter((entry) => entry.length) : paths[learningPath]?.experiences || paths.standard.experiences;
887
+ const experiences = requested.filter((id) => !!catalog[id]);
888
+ if (experiences.length === 0) {
889
+ return {
890
+ success: false,
891
+ error: "No valid experiences found. Provide --learning-path or --experiences."
892
+ };
893
+ }
894
+ console.log("[Baseline:Experience] Starting experience sequence");
895
+ console.log(`[Baseline:Experience] Path: ${learningPath}`);
896
+ experiences.forEach((experienceId, index) => {
897
+ const experience = catalog[experienceId];
898
+ console.log(
899
+ `[Baseline:Experience] ${index + 1}/${experiences.length}: ${experience.name} (${experience.duration})`
900
+ );
901
+ console.log(` ${experience.description}`);
902
+ });
903
+ const now = (/* @__PURE__ */ new Date()).toISOString();
904
+ const completed = Array.from(
905
+ /* @__PURE__ */ new Set([...profile.experiences?.completed ?? [], ...experiences])
906
+ );
907
+ const updatedProfile = {
908
+ ...profile,
909
+ updatedAt: now,
910
+ preferences: {
911
+ ...profile.preferences,
912
+ learningPath
913
+ },
914
+ experiences: {
915
+ completed,
916
+ lastExperience: experiences[experiences.length - 1],
917
+ lastCompletedAt: now
918
+ }
919
+ };
920
+ const targetPath = storage?.path ?? import_node_path.default.join(context, ".baseline", "onboarding.json");
921
+ let storageSaved = false;
922
+ let storageError;
923
+ try {
924
+ await this.saveOnboardingProfile(targetPath, updatedProfile);
925
+ storageSaved = true;
926
+ } catch (err) {
927
+ storageError = err instanceof Error ? err.message : String(err);
928
+ console.log(`[Baseline:Experience] Failed to save profile: ${storageError}`);
929
+ }
930
+ return {
931
+ success: true,
932
+ experience: {
933
+ path: learningPath,
934
+ experiences: experiences.map((id) => catalog[id]),
935
+ completed
936
+ },
937
+ profile: updatedProfile,
938
+ storage: {
939
+ path: targetPath,
940
+ saved: storageSaved,
941
+ error: storageError
942
+ }
943
+ };
944
+ }
945
+ /**
946
+ * Initialize Baseline and optionally persist config to disk.
947
+ */
948
+ async executeInit(options = {}) {
949
+ const context = this.resolveContext(options.context, process.cwd());
950
+ const mode = this.normalizeString(options.mode) || "development";
951
+ const writeConfig = this.normalizeBoolean(options["write-config"]) || this.normalizeBoolean(options.persist) || this.normalizeBoolean(options.write);
952
+ const initResult = await this.initializeBaseline({ context, mode });
953
+ if (!initResult.success) {
954
+ return initResult;
955
+ }
956
+ if (!writeConfig) {
957
+ return {
958
+ ...initResult,
959
+ message: "Initialization complete (config not written). Use --write-config to persist."
960
+ };
961
+ }
962
+ const profile = await this.loadOnboardingProfile(context);
963
+ const configRecord = await this.loadBaselineConfig(context);
964
+ const now = (/* @__PURE__ */ new Date()).toISOString();
965
+ const config = {
966
+ ...configRecord.config ?? this.buildDefaultConfig(context, profile.profile),
967
+ context,
968
+ updatedAt: now
969
+ };
970
+ await this.saveBaselineConfig(configRecord.path, config);
971
+ return {
972
+ ...initResult,
973
+ config,
974
+ configPath: configRecord.path,
975
+ message: "Initialization complete and config written."
976
+ };
977
+ }
978
+ /**
979
+ * Update or show Baseline configuration.
980
+ */
981
+ async executeConfig(options = {}) {
982
+ const context = this.resolveContext(options.context, process.cwd());
983
+ const positional = Array.isArray(options._) && options._.length ? options._ : [];
984
+ const section = this.normalizeString(options.config) || this.normalizeString(options.section) || (positional.length ? this.normalizeString(positional[0]) : void 0) || "show";
985
+ const showOnly = this.normalizeBoolean(options.show) || section === "show" || !options.set && !options.region && !options.standards && !options.enable;
986
+ const onboarding = await this.loadOnboardingProfile(context);
987
+ const existing = await this.loadBaselineConfig(context);
988
+ const now = (/* @__PURE__ */ new Date()).toISOString();
989
+ const config = existing.config ?? this.buildDefaultConfig(context, onboarding.profile);
990
+ if (showOnly) {
991
+ return {
992
+ success: true,
993
+ config,
994
+ configPath: existing.path
995
+ };
996
+ }
997
+ if (section === "language") {
998
+ const value = this.normalizeString(options.set);
999
+ if (!value) {
1000
+ return { success: false, error: "Missing --set <language-code>" };
1001
+ }
1002
+ config.language = value;
1003
+ if (onboarding.profile) {
1004
+ onboarding.profile.preferences.language = value;
1005
+ onboarding.profile.updatedAt = now;
1006
+ await this.saveOnboardingProfile(onboarding.path, onboarding.profile);
1007
+ }
1008
+ } else if (section === "culture") {
1009
+ const region = this.normalizeString(options.region);
1010
+ const businessStyle = this.normalizeString(options["business-style"]) || this.normalizeString(options.business);
1011
+ config.culture = {
1012
+ ...config.culture,
1013
+ ...region ? { region } : {},
1014
+ ...businessStyle ? { businessStyle } : {}
1015
+ };
1016
+ } else if (section === "compliance") {
1017
+ const region = this.normalizeString(options.region);
1018
+ const standardsRaw = this.normalizeString(options.standards);
1019
+ const standards = standardsRaw ? standardsRaw.split(",").map((entry) => entry.trim()).filter(Boolean) : void 0;
1020
+ config.compliance = {
1021
+ ...config.compliance,
1022
+ ...region ? { region } : {},
1023
+ ...standards ? { standards } : {}
1024
+ };
1025
+ } else if (section === "accessibility") {
1026
+ const enabledRaw = this.normalizeString(options.enable);
1027
+ const enabled = enabledRaw ? enabledRaw.split(",").map((entry) => entry.trim()).filter(Boolean) : [];
1028
+ config.accessibility = {
1029
+ ...config.accessibility,
1030
+ ...enabled.length ? { enabled } : {},
1031
+ ...this.normalizeBoolean(options["screen-reader"]) ? { screenReader: true } : {},
1032
+ ...this.normalizeBoolean(options["high-contrast"]) ? { highContrast: true } : {},
1033
+ ...this.normalizeBoolean(options["voice-control"]) ? { voiceControl: true } : {}
1034
+ };
1035
+ } else {
1036
+ return { success: false, error: `Unknown config section: ${section}` };
1037
+ }
1038
+ config.updatedAt = now;
1039
+ await this.saveBaselineConfig(existing.path, config);
1040
+ return {
1041
+ success: true,
1042
+ config,
1043
+ configPath: existing.path
1044
+ };
1045
+ }
1046
+ async collectIndexEntries(root, maxEntries) {
1047
+ const entries = [];
1048
+ const queue = [root];
1049
+ const ignore = /* @__PURE__ */ new Set([".git", "node_modules", ".baseline", "dist", ".next", "build"]);
1050
+ while (queue.length && entries.length < maxEntries) {
1051
+ const current = queue.shift();
1052
+ if (!current) continue;
1053
+ let currentStat;
1054
+ try {
1055
+ currentStat = await (0, import_promises.stat)(current);
1056
+ } catch {
1057
+ continue;
1058
+ }
1059
+ if (currentStat.isFile()) {
1060
+ entries.push(current);
1061
+ continue;
1062
+ }
1063
+ if (!currentStat.isDirectory()) continue;
1064
+ const name = import_node_path.default.basename(current);
1065
+ if (ignore.has(name)) continue;
1066
+ let children = [];
1067
+ try {
1068
+ children = await (0, import_promises.readdir)(current);
1069
+ } catch {
1070
+ continue;
1071
+ }
1072
+ for (const child of children) {
1073
+ if (entries.length >= maxEntries) break;
1074
+ queue.push(import_node_path.default.join(current, child));
1075
+ }
1076
+ }
1077
+ return entries;
1078
+ }
1079
+ /**
1080
+ * Index documentation/context files for retrieval.
1081
+ */
1082
+ async executeIndex(options = {}) {
1083
+ const context = this.resolveContext(options.context, process.cwd());
1084
+ const positional = Array.isArray(options._) && options._.length ? options._ : [];
1085
+ const pathsRaw = this.normalizeString(options.paths) || this.normalizeString(options.path) || (positional.length ? positional.join(",") : void 0);
1086
+ const defaultCandidates = ["docs", "README.md"].map((entry) => import_node_path.default.join(context, entry)).filter((entry) => entry !== "");
1087
+ const targets = pathsRaw ? pathsRaw.split(",").map((entry) => entry.trim()).filter(Boolean).map((entry) => import_node_path.default.resolve(context, entry)) : defaultCandidates;
1088
+ const maxEntries = Number(options.max) > 0 ? Number(options.max) : 2e3;
1089
+ console.log(`[Baseline:Index] Scanning ${targets.length} target(s) in ${context}`);
1090
+ const files = [];
1091
+ for (const target of targets) {
1092
+ const before = files.length;
1093
+ const collected = await this.collectIndexEntries(target, maxEntries - files.length);
1094
+ files.push(...collected);
1095
+ const added = files.length - before;
1096
+ if (added > 0) console.log(`[Baseline:Index] ${import_node_path.default.relative(context, target) || target} \u2192 ${added} file(s)`);
1097
+ if (files.length >= maxEntries) break;
1098
+ }
1099
+ console.log(`[Baseline:Index] Total: ${files.length} document(s) indexed`);
1100
+ const index = files.map((filePath) => ({
1101
+ path: filePath,
1102
+ relativePath: import_node_path.default.relative(context, filePath)
1103
+ }));
1104
+ const indexPath = import_node_path.default.join(context, ".baseline", "index.json");
1105
+ await (0, import_promises.mkdir)(import_node_path.default.dirname(indexPath), { recursive: true });
1106
+ await (0, import_promises.writeFile)(
1107
+ indexPath,
1108
+ JSON.stringify(
1109
+ {
1110
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1111
+ context,
1112
+ total: index.length,
1113
+ entries: index
1114
+ },
1115
+ null,
1116
+ 2
1117
+ ),
1118
+ "utf8"
1119
+ );
1120
+ return {
1121
+ success: true,
1122
+ indexed: index.length,
1123
+ indexPath,
1124
+ targets
1125
+ };
1126
+ }
1127
+ /**
1128
+ * Placeholder for MCP server/daemon execution.
1129
+ */
1130
+ async executeServe(options = {}) {
1131
+ return this.executeServeWithOptions(options);
1132
+ }
1133
+ /**
1134
+ * Placeholder for agent status and management.
1135
+ */
1136
+ executePersona(_options = {}) {
1137
+ const personas = [
1138
+ { id: "developer", name: "Developer", focus: "Code governance, CI/CD integration, deployment validation" },
1139
+ { id: "compliance-officer", name: "Compliance Officer", focus: "Policy enforcement, evidence export, regulatory alignment" },
1140
+ { id: "platform-engineer", name: "Platform Engineer", focus: "System health, agent management, infrastructure monitoring" },
1141
+ { id: "dfi-partner", name: "DFI Partner / Auditor", focus: "Evidence review, compliance verification, audit trails" },
1142
+ { id: "trade-finance", name: "Trade Finance Officer", focus: "AfCFTA compliance, trade governance, DFI evidence" }
1143
+ ];
1144
+ console.log("[Baseline:Persona]");
1145
+ console.log(" Available personas:");
1146
+ console.log("");
1147
+ for (const persona of personas) {
1148
+ console.log(` ${persona.id.padEnd(22)} ${persona.name}`);
1149
+ console.log(` ${"".padEnd(22)} ${persona.focus}`);
1150
+ console.log("");
1151
+ }
1152
+ console.log(" Set persona in Settings or baseline.config.ts");
1153
+ return { success: true, personas };
1154
+ }
1155
+ async executeAgents(options = {}) {
1156
+ return this.executeAgentsWithOptions(options);
1157
+ }
1158
+ async buildBaselineOS(context) {
1159
+ const { Baseline } = await import("baselineos");
1160
+ const knowledge = [
1161
+ import_node_path.default.join(context, "docs"),
1162
+ import_node_path.default.join(context, "README.md")
1163
+ ];
1164
+ return new Baseline({
1165
+ projectRoot: context,
1166
+ knowledge,
1167
+ paths: {
1168
+ data: import_node_path.default.join(context, ".baseline"),
1169
+ index: import_node_path.default.join(context, ".baseline", "index"),
1170
+ checkpoints: import_node_path.default.join(context, ".baseline", "checkpoints")
1171
+ }
1172
+ });
1173
+ }
1174
+ async executeServeWithOptions(options) {
1175
+ const context = this.resolveContext(options.context, process.cwd());
1176
+ const withApi = this.normalizeBoolean(options.api);
1177
+ const portRaw = this.normalizeString(options.port);
1178
+ const port = portRaw && Number(portRaw) > 0 ? Number(portRaw) : 3141;
1179
+ const once = this.normalizeBoolean(options.once);
1180
+ const baseline = await this.buildBaselineOS(context);
1181
+ await baseline.init();
1182
+ const mcpServer = await baseline.startMCPServer();
1183
+ let apiServer = null;
1184
+ if (withApi) {
1185
+ apiServer = await baseline.startAPIServer(port);
1186
+ }
1187
+ console.error(
1188
+ `[Baseline:Serve] MCP server started (stdio)${withApi ? ` + API:${port}` : ""}`
1189
+ );
1190
+ if (once) {
1191
+ return {
1192
+ success: true,
1193
+ status: "running",
1194
+ mode: "stdio",
1195
+ api: withApi ? { port } : null,
1196
+ message: "Server started (once mode)."
1197
+ };
1198
+ }
1199
+ await new Promise((resolve) => {
1200
+ const handle = async () => {
1201
+ try {
1202
+ await mcpServer.stop();
1203
+ } catch {
1204
+ }
1205
+ if (apiServer && typeof apiServer === "object" && "stop" in apiServer) {
1206
+ await apiServer.stop();
1207
+ }
1208
+ await baseline.shutdown();
1209
+ resolve();
1210
+ };
1211
+ process.on("SIGINT", handle);
1212
+ process.on("SIGTERM", handle);
1213
+ });
1214
+ return {
1215
+ success: true,
1216
+ status: "stopped"
1217
+ };
1218
+ }
1219
+ async executeAgentsWithOptions(options) {
1220
+ const context = this.resolveContext(options.context, process.cwd());
1221
+ const baseline = await this.buildBaselineOS(context);
1222
+ await baseline.init();
1223
+ const agents = baseline.listAgents();
1224
+ return {
1225
+ success: true,
1226
+ context,
1227
+ total: agents.length,
1228
+ agents
1229
+ };
1230
+ }
1231
+ /**
1232
+ * Run diagnostics for configuration and readiness.
1233
+ */
1234
+ async executeDoctor(options = {}) {
1235
+ const context = this.resolveContext(options.context, process.cwd());
1236
+ const checks = [
1237
+ {
1238
+ id: "config",
1239
+ description: "Baseline config exists",
1240
+ path: import_node_path.default.join(context, ".baseline", "baseline.config.json")
1241
+ },
1242
+ {
1243
+ id: "onboarding",
1244
+ description: "Onboarding profile exists",
1245
+ path: import_node_path.default.join(context, ".baseline", "onboarding.json")
1246
+ },
1247
+ {
1248
+ id: "index",
1249
+ description: "Index exists",
1250
+ path: import_node_path.default.join(context, ".baseline", "index.json")
1251
+ },
1252
+ {
1253
+ id: "roadmap",
1254
+ description: "Roadmap exists",
1255
+ path: import_node_path.default.join(context, "docs", "strategy", "roadmap.md")
1256
+ },
1257
+ {
1258
+ id: "ga-release",
1259
+ description: "GA release checklist exists",
1260
+ path: import_node_path.default.join(context, "docs", "strategy", "ga-release.md")
1261
+ },
1262
+ {
1263
+ id: "package-json",
1264
+ description: "package.json exists",
1265
+ path: import_node_path.default.join(context, "package.json")
1266
+ }
1267
+ ];
1268
+ const results = await Promise.all(
1269
+ checks.map(async (check) => ({
1270
+ ...check,
1271
+ ok: await this.fileExists(check.path)
1272
+ }))
1273
+ );
1274
+ const total = results.length;
1275
+ const passed = results.filter((check) => check.ok).length;
1276
+ const score = Math.round(passed / total * 100);
1277
+ const missing = results.filter((check) => !check.ok).map((check) => check.id);
1278
+ return {
1279
+ success: true,
1280
+ context,
1281
+ score,
1282
+ passed,
1283
+ total,
1284
+ missing,
1285
+ checks: results
1286
+ };
1287
+ }
1288
+ /**
1289
+ * Initialize the Baseline environment, setting up context folder,
1290
+ * configuration, and mode.
1291
+ */
1292
+ async initializeBaseline(options = {}) {
1293
+ try {
1294
+ const contextPath = options.context || process.cwd();
1295
+ const mode = options.mode || "development";
1296
+ this.state.customContextFolder = contextPath;
1297
+ this.state.baselineMode = true;
1298
+ console.log(`[Baseline:Init] Context path: ${contextPath}`);
1299
+ console.log(`[Baseline:Init] Mode: ${mode}`);
1300
+ const contextValid = typeof contextPath === "string" && contextPath.length > 0;
1301
+ if (!contextValid) {
1302
+ return {
1303
+ success: false,
1304
+ error: "Invalid context path provided"
1305
+ };
1306
+ }
1307
+ const config = {
1308
+ contextPath,
1309
+ mode,
1310
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1311
+ version: "0.1.0"
1312
+ };
1313
+ const detected = {};
1314
+ try {
1315
+ const { existsSync: existsSync2, readFileSync: readFileSync2 } = await import("fs");
1316
+ const { join: join2 } = await import("path");
1317
+ const pkgPath = join2(contextPath, "package.json");
1318
+ if (existsSync2(pkgPath)) {
1319
+ const pkg = JSON.parse(readFileSync2(pkgPath, "utf8"));
1320
+ const allDeps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
1321
+ if (allDeps["@anthropic-ai/sdk"]) detected.provider = "anthropic";
1322
+ else if (allDeps["openai"]) detected.provider = "openai";
1323
+ if (allDeps["langchain"] || allDeps["@langchain/core"]) detected.framework = "langchain";
1324
+ if (allDeps["@modelcontextprotocol/sdk"]) detected.mcp = true;
1325
+ if (allDeps["bullmq"] || allDeps["@temporalio/client"]) detected.orchestration = true;
1326
+ detected.runtime = "node";
1327
+ detected.name = pkg.name;
1328
+ }
1329
+ const pyReq = join2(contextPath, "requirements.txt");
1330
+ if (existsSync2(pyReq)) {
1331
+ const reqs = readFileSync2(pyReq, "utf8");
1332
+ if (reqs.includes("anthropic")) detected.provider = "anthropic";
1333
+ else if (reqs.includes("openai")) detected.provider = "openai";
1334
+ if (reqs.includes("langchain")) detected.framework = "langchain";
1335
+ detected.runtime = "python";
1336
+ }
1337
+ if (Object.keys(detected).length > 0) {
1338
+ console.log(`[Baseline:Init] Detected: ${JSON.stringify(detected)}`);
1339
+ }
1340
+ } catch {
1341
+ }
1342
+ console.log("[Baseline:Init] Environment initialized successfully");
1343
+ return {
1344
+ success: true,
1345
+ config: { ...config, detected },
1346
+ contextPath,
1347
+ mode,
1348
+ detected
1349
+ };
1350
+ } catch (error) {
1351
+ const errorMessage = error instanceof Error ? error.message : String(error);
1352
+ return {
1353
+ success: false,
1354
+ error: errorMessage
1355
+ };
1356
+ }
1357
+ }
1358
+ /**
1359
+ * Execute the Baseline Language layer -- parsing, validation,
1360
+ * and semantic analysis of the project context.
1361
+ */
1362
+ async executeBaselineLang(options = {}) {
1363
+ try {
1364
+ const inputPath = options.input || this.state.customContextFolder || process.cwd();
1365
+ const outputPath = options.output || inputPath;
1366
+ console.log(`[Baseline:Lang] Processing language layer...`);
1367
+ console.log(`[Baseline:Lang] Input: ${inputPath}`);
1368
+ console.log(`[Baseline:Lang] Output: ${outputPath}`);
1369
+ const lexiconKeys = Object.keys(this.baselineLang.lexicon);
1370
+ console.log(`[Baseline:Lang] Lexicon entries loaded: ${lexiconKeys.length}`);
1371
+ const syntaxKeys = Object.keys(this.baselineLang.syntax);
1372
+ console.log(`[Baseline:Lang] Syntax patterns loaded: ${syntaxKeys.length}`);
1373
+ const analysisResult = {
1374
+ lexiconEntries: lexiconKeys.length,
1375
+ syntaxPatterns: syntaxKeys.length,
1376
+ validationPassed: true,
1377
+ semanticScore: 1,
1378
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1379
+ };
1380
+ console.log("[Baseline:Lang] Language layer processing complete");
1381
+ return {
1382
+ success: true,
1383
+ inputPath,
1384
+ outputPath,
1385
+ analysis: analysisResult
1386
+ };
1387
+ } catch (error) {
1388
+ const errorMessage = error instanceof Error ? error.message : String(error);
1389
+ return {
1390
+ success: false,
1391
+ error: errorMessage
1392
+ };
1393
+ }
1394
+ }
1395
+ /**
1396
+ * Execute the Baseline Frame layer -- scaffolding, composition,
1397
+ * and framework orchestration.
1398
+ */
1399
+ async executeBaselineFrame(options = {}) {
1400
+ try {
1401
+ const inputPath = options.input || this.state.customContextFolder || process.cwd();
1402
+ const configPath = options.config || null;
1403
+ console.log(`[Baseline:Frame] Processing frame layer...`);
1404
+ console.log(`[Baseline:Frame] Input: ${inputPath}`);
1405
+ if (configPath) {
1406
+ console.log(`[Baseline:Frame] Config: ${configPath}`);
1407
+ }
1408
+ const scaffoldResult = {
1409
+ components: [],
1410
+ templates: [],
1411
+ structure: "hierarchical"
1412
+ };
1413
+ const compositionResult = {
1414
+ composed: true,
1415
+ layers: ["lang", "frame", "studio", "govern"],
1416
+ dependencies: []
1417
+ };
1418
+ const orchestrationResult = {
1419
+ orchestrated: true,
1420
+ pipelineStages: 4,
1421
+ parallelism: 1
1422
+ };
1423
+ console.log("[Baseline:Frame] Frame layer processing complete");
1424
+ return {
1425
+ success: true,
1426
+ scaffold: scaffoldResult,
1427
+ composition: compositionResult,
1428
+ orchestration: orchestrationResult
1429
+ };
1430
+ } catch (error) {
1431
+ const errorMessage = error instanceof Error ? error.message : String(error);
1432
+ return {
1433
+ success: false,
1434
+ error: errorMessage
1435
+ };
1436
+ }
1437
+ }
1438
+ /**
1439
+ * Execute the Baseline Studio layer -- design rendering,
1440
+ * preview generation, and visual asset processing.
1441
+ */
1442
+ async executeBaselineStudio(options = {}) {
1443
+ try {
1444
+ const inputPath = options.input || this.state.customContextFolder || process.cwd();
1445
+ const renderMode = options.render || "standard";
1446
+ console.log(`[Baseline:Studio] Processing studio layer...`);
1447
+ console.log(`[Baseline:Studio] Input: ${inputPath}`);
1448
+ console.log(`[Baseline:Studio] Render mode: ${renderMode}`);
1449
+ const designResult = {
1450
+ designSystem: "baseline-default",
1451
+ components: 0,
1452
+ tokens: {},
1453
+ themes: ["light", "dark"]
1454
+ };
1455
+ const renderResult = {
1456
+ rendered: true,
1457
+ mode: renderMode,
1458
+ outputFormat: "html",
1459
+ assets: []
1460
+ };
1461
+ const previewResult = {
1462
+ previewAvailable: false,
1463
+ previewUrl: null
1464
+ };
1465
+ console.log("[Baseline:Studio] Studio layer processing complete");
1466
+ return {
1467
+ success: true,
1468
+ design: designResult,
1469
+ render: renderResult,
1470
+ preview: previewResult
1471
+ };
1472
+ } catch (error) {
1473
+ const errorMessage = error instanceof Error ? error.message : String(error);
1474
+ return {
1475
+ success: false,
1476
+ error: errorMessage
1477
+ };
1478
+ }
1479
+ }
1480
+ /**
1481
+ * Execute the Baseline Govern layer -- audit, policy enforcement,
1482
+ * compliance checking, and governance controls.
1483
+ */
1484
+ async executeBaselineGovern(options = {}) {
1485
+ try {
1486
+ const inputPath = options.input || this.state.customContextFolder || process.cwd();
1487
+ const policyPath = options.policy || null;
1488
+ const auditPath = import_node_path.default.join(inputPath, ".baseline", "govern", "audit-trail.json");
1489
+ console.log(`[Baseline:Govern] Processing governance layer...`);
1490
+ console.log(`[Baseline:Govern] Input: ${inputPath}`);
1491
+ if (policyPath) {
1492
+ console.log(`[Baseline:Govern] Policy: ${policyPath}`);
1493
+ }
1494
+ let policyContent = "Default governance policy";
1495
+ if (policyPath) {
1496
+ try {
1497
+ policyContent = await (0, import_promises.readFile)(policyPath, "utf8");
1498
+ } catch (error) {
1499
+ const message = error instanceof Error ? error.message : String(error);
1500
+ console.log(`[Baseline:Govern] Unable to read policy file, using default policy (${message})`);
1501
+ }
1502
+ }
1503
+ const govern = new import_govern.BaselineGovernSystem({ persistPath: auditPath });
1504
+ const createdPolicy = await govern.policies.create("baseline-default", policyContent, {
1505
+ severity: "high",
1506
+ enforcement: "block",
1507
+ requireApproval: Boolean(options.requireApproval),
1508
+ requiredApprovers: Array.isArray(options.requiredApprovers) ? options.requiredApprovers : ["govern-approver"],
1509
+ rules: [
1510
+ {
1511
+ id: "restricted-sensitivity",
1512
+ name: "Restricted sensitivity requires approval",
1513
+ severity: "high",
1514
+ enforcement: "block",
1515
+ condition: { field: "sensitivity", equals: "restricted" },
1516
+ message: "Restricted workloads must pass approval before enforcement."
1517
+ }
1518
+ ]
1519
+ });
1520
+ if (!createdPolicy.success || !createdPolicy.policy) {
1521
+ throw new Error(createdPolicy.error || "Failed to create governance policy");
1522
+ }
1523
+ const policyId = createdPolicy.policy.id;
1524
+ const approvedPolicy = await govern.policies.approve(policyId, String(options.approver || "baseline-cli"));
1525
+ if (!approvedPolicy.success) {
1526
+ throw new Error(approvedPolicy.error || "Failed to approve governance policy");
1527
+ }
1528
+ const enforcement = await govern.policies.enforce(policyId, {
1529
+ resourceId: String(options.resourceId || inputPath),
1530
+ requestedBy: String(options.requestedBy || "baseline-cli"),
1531
+ sensitivity: String(options.sensitivity || "standard"),
1532
+ mode: String(options.mode || this.state.customContextFolder || "development")
1533
+ });
1534
+ const compliance = await govern.compliance.check("ISO27001", {
1535
+ documentation: options.documentation || "complete",
1536
+ process: options.process || "complete"
1537
+ });
1538
+ const evidence = govern.getEvidenceBundle(policyId, String(options.resourceId || inputPath));
1539
+ const violations = enforcement.evaluation?.violations ?? [];
1540
+ const policyResult = {
1541
+ policiesEvaluated: 1,
1542
+ policiesPassed: enforcement.success ? 1 : 0,
1543
+ policiesFailed: enforcement.success ? 0 : 1,
1544
+ violations,
1545
+ enforcementAction: enforcement.evaluation?.enforcementAction ?? "allow",
1546
+ requiresApproval: enforcement.evaluation?.requiresApproval ?? false
1547
+ };
1548
+ const auditResult = {
1549
+ auditId: `audit-${Date.now()}`,
1550
+ passed: enforcement.success,
1551
+ findings: violations.map((violation) => violation.message),
1552
+ severity: violations.length > 0 ? "high" : "none",
1553
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1554
+ events: evidence.auditTrail.length
1555
+ };
1556
+ const complianceResult = {
1557
+ compliant: compliance.compliance?.compliant ?? false,
1558
+ standards: ["ISO27001"],
1559
+ certifications: [],
1560
+ gaps: compliance.compliance?.violations ?? []
1561
+ };
1562
+ console.log("[Baseline:Govern] Governance layer processing complete");
1563
+ return {
1564
+ success: enforcement.success,
1565
+ audit: auditResult,
1566
+ policy: policyResult,
1567
+ compliance: complianceResult,
1568
+ evaluation: enforcement.evaluation,
1569
+ approval: enforcement.approval,
1570
+ evidence
1571
+ };
1572
+ } catch (error) {
1573
+ const errorMessage = error instanceof Error ? error.message : String(error);
1574
+ return {
1575
+ success: false,
1576
+ error: errorMessage
1577
+ };
1578
+ }
1579
+ }
1580
+ /**
1581
+ * Execute a chain of commands sequentially. Each command in the array
1582
+ * is executed in order. If any command fails, the chain halts.
1583
+ */
1584
+ async executeChainedCommands(commands) {
1585
+ console.log(`[Baseline:Chain] Executing ${commands.length} chained commands...`);
1586
+ const results = {};
1587
+ let overallSuccess = true;
1588
+ for (let i = 0; i < commands.length; i++) {
1589
+ const command = commands[i].trim();
1590
+ console.log(`[Baseline:Chain] Command ${i + 1}/${commands.length}: ${command}`);
1591
+ try {
1592
+ const result = await this.executeCommand(command);
1593
+ results[`step_${i + 1}`] = result;
1594
+ if (!result.success) {
1595
+ overallSuccess = false;
1596
+ console.log(`[Baseline:Chain] Command ${i + 1} failed: ${result.error || "unknown error"}`);
1597
+ break;
1598
+ }
1599
+ console.log(`[Baseline:Chain] Command ${i + 1} completed successfully`);
1600
+ } catch (error) {
1601
+ const errorMessage = error instanceof Error ? error.message : String(error);
1602
+ overallSuccess = false;
1603
+ results[`step_${i + 1}`] = { success: false, error: errorMessage };
1604
+ console.log(`[Baseline:Chain] Command ${i + 1} threw error: ${errorMessage}`);
1605
+ break;
1606
+ }
1607
+ }
1608
+ console.log(`[Baseline:Chain] Chain execution ${overallSuccess ? "completed" : "failed"}`);
1609
+ return {
1610
+ success: overallSuccess,
1611
+ results,
1612
+ commandsExecuted: Object.keys(results).length,
1613
+ totalCommands: commands.length
1614
+ };
1615
+ }
1616
+ /**
1617
+ * Add a command to the execution queue for deferred execution.
1618
+ */
1619
+ queueCommand(command) {
1620
+ this.state.commandQueue.push(command);
1621
+ console.log(`[Baseline:Queue] Command queued: ${command} (queue size: ${this.state.commandQueue.length})`);
1622
+ }
1623
+ /**
1624
+ * Execute all commands currently in the queue, in FIFO order,
1625
+ * then clear the queue.
1626
+ */
1627
+ async executeQueue() {
1628
+ const queueLength = this.state.commandQueue.length;
1629
+ if (queueLength === 0) {
1630
+ console.log("[Baseline:Queue] Queue is empty, nothing to execute");
1631
+ return { success: true, message: "Queue is empty" };
1632
+ }
1633
+ console.log(`[Baseline:Queue] Executing ${queueLength} queued commands...`);
1634
+ const commands = [...this.state.commandQueue];
1635
+ this.state.commandQueue = [];
1636
+ const result = await this.executeChainedCommands(commands);
1637
+ console.log(`[Baseline:Queue] Queue execution complete`);
1638
+ return result;
1639
+ }
1640
+ /**
1641
+ * Execute a single command string by dispatching to the appropriate
1642
+ * handler based on the command flag.
1643
+ */
1644
+ async executeCommand(command) {
1645
+ const trimmed = command.trim();
1646
+ console.log(`[Baseline:Command] Executing: ${trimmed}`);
1647
+ const parts = trimmed.split(/\s+/);
1648
+ const mainCommand = parts[0];
1649
+ const options = {};
1650
+ const positionals = [];
1651
+ for (let i = 1; i < parts.length; i++) {
1652
+ if (parts[i].startsWith("--")) {
1653
+ const key = parts[i].replace(/^--/, "");
1654
+ const value = parts[i + 1] && !parts[i + 1].startsWith("--") ? parts[++i] : "true";
1655
+ options[key] = value;
1656
+ } else {
1657
+ positionals.push(parts[i]);
1658
+ }
1659
+ }
1660
+ options._ = positionals;
1661
+ switch (mainCommand) {
1662
+ case "--onboard":
1663
+ return await this.executeOnboarding(options);
1664
+ case "--experience":
1665
+ return await this.executeExperience(options);
1666
+ case "--config":
1667
+ return await this.executeConfig(options);
1668
+ case "--index":
1669
+ return await this.executeIndex(options);
1670
+ case "--serve":
1671
+ return await this.executeServe(options);
1672
+ case "--persona":
1673
+ return this.executePersona(options);
1674
+ case "--agents":
1675
+ return await this.executeAgents(options);
1676
+ case "--doctor":
1677
+ return await this.executeDoctor(options);
1678
+ case "--baseline":
1679
+ return await this.executeBaselineWorkflow(options);
1680
+ case "--baseline-lang":
1681
+ return await this.executeBaselineLang(options);
1682
+ case "--baseline-frame":
1683
+ return await this.executeBaselineFrame(options);
1684
+ case "--baseline-studio":
1685
+ return await this.executeBaselineStudio(options);
1686
+ case "--baseline-govern":
1687
+ return await this.executeBaselineGovern(options);
1688
+ case "--init":
1689
+ return await this.executeInit(options);
1690
+ case "--run":
1691
+ return await this.executeBaselineWorkflow(options);
1692
+ case "--status": {
1693
+ const status = this.getStatus();
1694
+ return { success: true, ...status };
1695
+ }
1696
+ case "--help":
1697
+ this.showHelp();
1698
+ return { success: true };
1699
+ default:
1700
+ console.log(`[Baseline:Command] Unknown command: ${mainCommand}`);
1701
+ return {
1702
+ success: false,
1703
+ error: `Unknown command: ${mainCommand}. Use --help for available commands.`
1704
+ };
1705
+ }
1706
+ }
1707
+ /**
1708
+ * Return the current status of the Baseline system, including
1709
+ * state, execution history, and queue contents.
1710
+ */
1711
+ getStatus() {
1712
+ const status = {
1713
+ baselineMode: this.state.baselineMode,
1714
+ customContextFolder: this.state.customContextFolder,
1715
+ queueLength: this.state.commandQueue.length,
1716
+ queuedCommands: [...this.state.commandQueue],
1717
+ executionHistoryCount: this.state.executionHistory.length,
1718
+ currentWorkflow: this.state.currentWorkflow ? {
1719
+ id: this.state.currentWorkflow.id,
1720
+ status: this.state.currentWorkflow.status,
1721
+ startTime: this.state.currentWorkflow.startTime.toISOString()
1722
+ } : null,
1723
+ recentExecutions: this.state.executionHistory.slice(-5).map(
1724
+ (execution) => ({
1725
+ id: execution.id,
1726
+ status: execution.status,
1727
+ duration: execution.duration,
1728
+ startTime: execution.startTime.toISOString(),
1729
+ error: execution.error || null
1730
+ })
1731
+ ),
1732
+ megagemConnected: this.megagem !== null,
1733
+ contextEngineConnected: this.contextEngine !== null,
1734
+ lexiconEntries: Object.keys(this.baselineLang.lexicon).length,
1735
+ syntaxPatterns: Object.keys(this.baselineLang.syntax).length,
1736
+ commands: Object.keys(this.baselineLang.commands).length
1737
+ };
1738
+ const layers = ["lang", "frame", "studio", "govern", "experience", "autonomy", "persona"];
1739
+ const layerStatus = layers.map((id) => {
1740
+ const lastExec = this.state.executionHistory.filter((e) => e.status === "completed").slice(-1)[0];
1741
+ return { id, status: "armed", lastCheck: lastExec ? "passed" : "none" };
1742
+ });
1743
+ status.layers = layerStatus;
1744
+ console.log("[Baseline:Status]");
1745
+ console.log(` Mode: ${status.baselineMode ? "active" : "inactive"}`);
1746
+ console.log(` Context: ${status.customContextFolder || "none"}`);
1747
+ console.log(` Queue: ${status.queueLength} commands`);
1748
+ console.log(` History: ${status.executionHistoryCount} executions`);
1749
+ console.log(` MEGAGEM: ${status.megagemConnected ? "connected" : "disconnected"}`);
1750
+ console.log(` Context Engine: ${status.contextEngineConnected ? "connected" : "disconnected"}`);
1751
+ console.log("");
1752
+ console.log(" Governance Layers:");
1753
+ for (const layer of layerStatus) {
1754
+ const dot = layer.lastCheck === "passed" ? "\u25CF" : layer.lastCheck === "failed" ? "\u25CB" : "\u25CC";
1755
+ console.log(` ${dot} ${layer.id.padEnd(12)} ${layer.status.padEnd(8)} last check: ${layer.lastCheck}`);
1756
+ }
1757
+ return status;
1758
+ }
1759
+ /**
1760
+ * Display help information for all available commands, flags,
1761
+ * and syntax patterns.
1762
+ */
1763
+ showHelp() {
1764
+ console.log("");
1765
+ console.log("=== Baseline Protocol CLI ===");
1766
+ console.log("");
1767
+ console.log("COMMANDS:");
1768
+ console.log("");
1769
+ for (const [flag, entry] of Object.entries(this.baselineLang.commands)) {
1770
+ console.log(` ${flag.padEnd(20)} ${entry.description}`);
1771
+ }
1772
+ console.log("");
1773
+ console.log("LAYER FLAGS:");
1774
+ console.log("");
1775
+ for (const [flag, entry] of Object.entries(this.baselineLang.lexicon)) {
1776
+ console.log(` ${flag.padEnd(24)} ${entry.description}`);
1777
+ console.log(` ${"".padEnd(24)} Usage: ${entry.usage}`);
1778
+ console.log(` ${"".padEnd(24)} Category: ${entry.category}`);
1779
+ if (entry.examples.length > 0) {
1780
+ console.log(` ${"".padEnd(24)} Examples:`);
1781
+ for (const example of entry.examples) {
1782
+ console.log(` ${"".padEnd(28)} ${example}`);
1783
+ }
1784
+ }
1785
+ console.log("");
1786
+ }
1787
+ console.log("SYNTAX PATTERNS:");
1788
+ console.log("");
1789
+ for (const [name, entry] of Object.entries(this.baselineLang.syntax)) {
1790
+ console.log(` ${name}:`);
1791
+ console.log(` Pattern: ${entry.pattern}`);
1792
+ console.log(" Parameters:");
1793
+ for (const [param, desc] of Object.entries(entry.parameters)) {
1794
+ console.log(` --${param.padEnd(16)} ${desc}`);
1795
+ }
1796
+ if (entry.examples.length > 0) {
1797
+ console.log(" Examples:");
1798
+ for (const example of entry.examples) {
1799
+ console.log(` ${example}`);
1800
+ }
1801
+ }
1802
+ console.log("");
1803
+ }
1804
+ console.log("USAGE:");
1805
+ console.log(" baseline --init Initialize a new project");
1806
+ console.log(" baseline --run Run the full workflow");
1807
+ console.log(" baseline --baseline --mode production Run in production mode");
1808
+ console.log(" baseline --status Check system status");
1809
+ console.log(" baseline --help Show this help");
1810
+ console.log("");
1811
+ }
1812
+ /**
1813
+ * Set the MEGAGEM integration instance for autonomous operations.
1814
+ */
1815
+ setMegagem(megagem) {
1816
+ this.megagem = megagem;
1817
+ console.log("[Baseline] MEGAGEM integration connected");
1818
+ }
1819
+ /**
1820
+ * Set the Context Engine integration instance for context management.
1821
+ */
1822
+ setContextEngine(contextEngine) {
1823
+ this.contextEngine = contextEngine;
1824
+ console.log("[Baseline] Context Engine integration connected");
1825
+ }
1826
+ };
1827
+
1828
+ // src/megagem.ts
1829
+ var import_fs = require("fs");
1830
+ var import_path = require("path");
1831
+
1832
+ // src/config/megagem-config.json
1833
+ var megagem_config_default = {
1834
+ system: {
1835
+ name: "MEGAGEM AI Autonomous Framework",
1836
+ version: "1.0.0",
1837
+ description: "The most advanced AI autonomy system ever built. Enables AI to truly OWN and EMPOWER projects autonomously.",
1838
+ author: "GTCX Development Team",
1839
+ license: "MIT",
1840
+ created: "2025-08-12",
1841
+ status: "active"
1842
+ },
1843
+ autonomy: {
1844
+ defaultLevel: 0,
1845
+ maxLevel: 100,
1846
+ incrementStep: 25,
1847
+ levels: {
1848
+ "0": {
1849
+ name: "Manual Control",
1850
+ description: "AI waits for explicit commands",
1851
+ capabilities: ["command_execution", "basic_assistance"],
1852
+ safety: "maximum",
1853
+ humanOversight: "required"
1854
+ },
1855
+ "25": {
1856
+ name: "Assisted Autonomy",
1857
+ description: "AI suggests actions, user approves",
1858
+ capabilities: ["suggestion_generation", "plan_creation", "user_approval"],
1859
+ safety: "high",
1860
+ humanOversight: "required"
1861
+ },
1862
+ "50": {
1863
+ name: "Collaborative Autonomy",
1864
+ description: "AI executes approved plans autonomously",
1865
+ capabilities: ["plan_execution", "resource_management", "progress_tracking"],
1866
+ safety: "medium",
1867
+ humanOversight: "periodic"
1868
+ },
1869
+ "75": {
1870
+ name: "Strategic Autonomy",
1871
+ description: "AI makes strategic decisions and executes",
1872
+ capabilities: ["strategic_planning", "decision_making", "autonomous_execution"],
1873
+ safety: "medium",
1874
+ humanOversight: "minimal"
1875
+ },
1876
+ "100": {
1877
+ name: "Full Autonomy",
1878
+ description: "AI owns entire projects autonomously",
1879
+ capabilities: ["project_ownership", "full_decision_making", "autonomous_evolution"],
1880
+ safety: "monitored",
1881
+ humanOversight: "audit_only"
1882
+ }
1883
+ },
1884
+ safetyThresholds: {
1885
+ riskTolerance: "medium",
1886
+ humanOversight: "required",
1887
+ decisionApproval: "automatic",
1888
+ emergencyStop: true,
1889
+ boundaryEnforcement: true
1890
+ }
1891
+ },
1892
+ learning: {
1893
+ continuousLearning: true,
1894
+ selfImprovement: true,
1895
+ knowledgeSharing: true,
1896
+ learningMethods: {
1897
+ supervised: true,
1898
+ unsupervised: true,
1899
+ reinforcement: true,
1900
+ transfer: true,
1901
+ meta: true
1902
+ },
1903
+ improvementAreas: {
1904
+ decisionMaking: true,
1905
+ efficiency: true,
1906
+ creativity: true,
1907
+ collaboration: true,
1908
+ safety: true
1909
+ },
1910
+ learningRate: 0.1,
1911
+ knowledgeRetention: 0.95,
1912
+ adaptationSpeed: "adaptive"
1913
+ },
1914
+ safety: {
1915
+ riskAssessment: true,
1916
+ boundaryEnforcement: true,
1917
+ humanOverride: true,
1918
+ auditLogging: true,
1919
+ emergencyStop: true,
1920
+ riskCategories: {
1921
+ operational: "high",
1922
+ strategic: "medium",
1923
+ ethical: "critical",
1924
+ legal: "critical",
1925
+ technical: "medium"
1926
+ },
1927
+ safetyProtocols: {
1928
+ preAction: true,
1929
+ duringAction: true,
1930
+ postAction: true,
1931
+ emergency: true
1932
+ },
1933
+ safetyLevels: {
1934
+ low: "proceed_with_monitoring",
1935
+ medium: "proceed_with_caution",
1936
+ high: "require_approval",
1937
+ critical: "immediate_stop"
1938
+ }
1939
+ },
1940
+ collaboration: {
1941
+ multiAgent: true,
1942
+ teamFormation: true,
1943
+ taskDistribution: true,
1944
+ coordination: true,
1945
+ communication: true,
1946
+ conflictResolution: true,
1947
+ agentTypes: {
1948
+ strategist: true,
1949
+ executor: true,
1950
+ analyst: true,
1951
+ coordinator: true,
1952
+ innovator: true
1953
+ },
1954
+ collaborationModels: {
1955
+ hierarchical: true,
1956
+ collaborative: true,
1957
+ adaptive: true,
1958
+ emergent: true
1959
+ }
1960
+ },
1961
+ decisionMaking: {
1962
+ strategicThinking: true,
1963
+ riskAssessment: true,
1964
+ resourceOptimization: true,
1965
+ goalOrientedPlanning: true,
1966
+ adaptiveStrategy: true,
1967
+ decisionTypes: {
1968
+ tactical: true,
1969
+ strategic: true,
1970
+ operational: true,
1971
+ innovative: true
1972
+ },
1973
+ decisionProcess: {
1974
+ analysis: true,
1975
+ evaluation: true,
1976
+ selection: true,
1977
+ execution: true,
1978
+ monitoring: true
1979
+ }
1980
+ },
1981
+ projectOwnership: {
1982
+ projectInitiation: true,
1983
+ resourceAllocation: true,
1984
+ teamFormation: true,
1985
+ executionManagement: true,
1986
+ qualityControl: true,
1987
+ deliveryManagement: true,
1988
+ ownershipLevels: {
1989
+ partial: true,
1990
+ collaborative: true,
1991
+ primary: true,
1992
+ full: true
1993
+ },
1994
+ projectTypes: {
1995
+ development: true,
1996
+ research: true,
1997
+ operations: true,
1998
+ innovation: true
1999
+ }
2000
+ },
2001
+ performance: {
2002
+ metrics: {
2003
+ efficiency: true,
2004
+ accuracy: true,
2005
+ speed: true,
2006
+ quality: true,
2007
+ innovation: true
2008
+ },
2009
+ monitoring: {
2010
+ realTime: true,
2011
+ historical: true,
2012
+ predictive: true,
2013
+ comparative: true
2014
+ },
2015
+ optimization: {
2016
+ continuous: true,
2017
+ adaptive: true,
2018
+ goalOriented: true,
2019
+ selfImproving: true
2020
+ }
2021
+ },
2022
+ integration: {
2023
+ mantraAI: {
2024
+ enabled: true,
2025
+ integrationLevel: "deep",
2026
+ capabilities: ["strategic_thinking", "autonomous_planning"]
2027
+ },
2028
+ langChain: {
2029
+ enabled: true,
2030
+ integrationLevel: "deep",
2031
+ capabilities: ["tool_orchestration", "workflow_management"]
2032
+ },
2033
+ autoGen: {
2034
+ enabled: true,
2035
+ integrationLevel: "medium",
2036
+ capabilities: ["multi_agent_collaboration"]
2037
+ },
2038
+ crewAI: {
2039
+ enabled: true,
2040
+ integrationLevel: "medium",
2041
+ capabilities: ["project_management", "team_orchestration"]
2042
+ }
2043
+ },
2044
+ evolution: {
2045
+ selfImprovement: true,
2046
+ capabilityExpansion: true,
2047
+ knowledgeEvolution: true,
2048
+ strategyOptimization: true,
2049
+ adaptationMechanisms: {
2050
+ environmental: true,
2051
+ performance: true,
2052
+ user: true,
2053
+ internal: true
2054
+ },
2055
+ evolutionSpeed: "adaptive",
2056
+ improvementThreshold: 0.05
2057
+ },
2058
+ userInterface: {
2059
+ autonomyControl: {
2060
+ levelSlider: true,
2061
+ safetySettings: true,
2062
+ learningPreferences: true,
2063
+ performanceMetrics: true
2064
+ },
2065
+ monitoring: {
2066
+ realTimeStatus: true,
2067
+ projectOverview: true,
2068
+ safetyAlerts: true,
2069
+ performanceDashboard: true
2070
+ },
2071
+ interaction: {
2072
+ naturalLanguage: true,
2073
+ visualInterface: true,
2074
+ mobileAccess: true,
2075
+ voiceControl: true
2076
+ }
2077
+ },
2078
+ deployment: {
2079
+ environment: "production",
2080
+ scalability: "auto",
2081
+ reliability: "99.9%",
2082
+ security: "enterprise",
2083
+ monitoring: "comprehensive",
2084
+ backup: "automated",
2085
+ recovery: "instant"
2086
+ }
2087
+ };
2088
+
2089
+ // src/megagem.ts
2090
+ var MEGAGEMCoreSystem = class {
2091
+ systemName;
2092
+ version;
2093
+ autonomyLevel;
2094
+ isActive;
2095
+ learningMode;
2096
+ safetyMode;
2097
+ autonomyController;
2098
+ decisionEngine;
2099
+ projectOwner;
2100
+ learningEngine;
2101
+ safetyEngine;
2102
+ collaborationEngine;
2103
+ currentProjects;
2104
+ performanceMetrics;
2105
+ learningHistory;
2106
+ safetyEvents;
2107
+ config;
2108
+ constructor() {
2109
+ this.systemName = "MEGAGEM";
2110
+ this.version = "1.0.0";
2111
+ this.autonomyLevel = 1;
2112
+ this.isActive = false;
2113
+ this.learningMode = false;
2114
+ this.safetyMode = true;
2115
+ this.autonomyController = this.initializeAutonomyController();
2116
+ this.decisionEngine = this.initializeDecisionEngine();
2117
+ this.projectOwner = this.initializeProjectOwner();
2118
+ this.learningEngine = this.initializeLearningEngine();
2119
+ this.safetyEngine = this.initializeSafetyEngine();
2120
+ this.collaborationEngine = this.initializeCollaborationEngine();
2121
+ this.currentProjects = /* @__PURE__ */ new Map();
2122
+ this.performanceMetrics = {
2123
+ decisionsAccuracy: 0,
2124
+ taskCompletionRate: 0,
2125
+ learningRate: 0,
2126
+ collaborationScore: 0,
2127
+ safetyCompliance: 1,
2128
+ totalDecisions: 0,
2129
+ totalTasks: 0,
2130
+ totalCollaborations: 0,
2131
+ uptime: 0,
2132
+ startTime: /* @__PURE__ */ new Date()
2133
+ };
2134
+ this.learningHistory = [];
2135
+ this.safetyEvents = [];
2136
+ this.config = this.getDefaultConfig();
2137
+ }
2138
+ /**
2139
+ * Set up the autonomy controller with five operational levels
2140
+ * and escalation rules.
2141
+ */
2142
+ initializeAutonomyController() {
2143
+ return {
2144
+ currentLevel: 1,
2145
+ maxLevel: 5,
2146
+ levels: {
2147
+ 1: { name: "Supervised", description: "All actions require human approval" },
2148
+ 2: { name: "Guided", description: "Routine actions auto-approved, complex actions require approval" },
2149
+ 3: { name: "Collaborative", description: "Most actions auto-approved, high-risk actions require approval" },
2150
+ 4: { name: "Autonomous", description: "Almost all actions auto-approved, critical actions require approval" },
2151
+ 5: { name: "Full Autonomy", description: "All actions auto-approved with safety constraints" }
2152
+ },
2153
+ escalationRules: [
2154
+ { condition: "high_risk_detected", action: "reduce_autonomy", targetLevel: 1 },
2155
+ { condition: "safety_violation", action: "emergency_stop", targetLevel: 0 },
2156
+ { condition: "repeated_success", action: "increase_autonomy", targetLevel: -1 },
2157
+ { condition: "human_override", action: "set_supervised", targetLevel: 1 }
2158
+ ],
2159
+ overrideActive: false
2160
+ };
2161
+ }
2162
+ /**
2163
+ * Set up the decision engine with thresholds and history tracking.
2164
+ */
2165
+ initializeDecisionEngine() {
2166
+ return {
2167
+ pendingDecisions: [],
2168
+ decisionHistory: [],
2169
+ decisionThresholds: {
2170
+ lowRisk: 0.3,
2171
+ mediumRisk: 0.6,
2172
+ highRisk: 0.8,
2173
+ criticalRisk: 0.95
2174
+ },
2175
+ autoApprove: false
2176
+ };
2177
+ }
2178
+ /**
2179
+ * Set up the project ownership engine with project stores and templates.
2180
+ */
2181
+ initializeProjectOwner() {
2182
+ return {
2183
+ activeProjects: /* @__PURE__ */ new Map(),
2184
+ completedProjects: /* @__PURE__ */ new Map(),
2185
+ projectTemplates: /* @__PURE__ */ new Map([
2186
+ [
2187
+ "standard",
2188
+ {
2189
+ phases: ["planning", "design", "implementation", "testing", "deployment"],
2190
+ milestones: ["kickoff", "design-review", "alpha", "beta", "release"],
2191
+ roles: ["lead", "developer", "designer", "tester", "reviewer"]
2192
+ }
2193
+ ],
2194
+ [
2195
+ "agile",
2196
+ {
2197
+ phases: ["backlog", "sprint-planning", "sprint", "review", "retrospective"],
2198
+ milestones: ["sprint-start", "mid-sprint", "sprint-end", "demo"],
2199
+ roles: ["product-owner", "scrum-master", "developer", "tester"]
2200
+ }
2201
+ ],
2202
+ [
2203
+ "research",
2204
+ {
2205
+ phases: ["exploration", "hypothesis", "experimentation", "analysis", "publication"],
2206
+ milestones: ["proposal", "data-collection", "analysis-complete", "draft", "final"],
2207
+ roles: ["principal-investigator", "researcher", "analyst", "reviewer"]
2208
+ }
2209
+ ]
2210
+ ])
2211
+ };
2212
+ }
2213
+ /**
2214
+ * Set up the learning engine with knowledge base and adaptation rate.
2215
+ */
2216
+ initializeLearningEngine() {
2217
+ return {
2218
+ knowledgeBase: /* @__PURE__ */ new Map(),
2219
+ learningHistory: [],
2220
+ patterns: /* @__PURE__ */ new Map(),
2221
+ adaptationRate: 0.1
2222
+ };
2223
+ }
2224
+ /**
2225
+ * Set up the safety engine with risk assessment stores and boundary
2226
+ * configuration.
2227
+ */
2228
+ initializeSafetyEngine() {
2229
+ return {
2230
+ riskAssessments: /* @__PURE__ */ new Map(),
2231
+ boundaries: /* @__PURE__ */ new Map([
2232
+ ["max_file_operations", { limit: 1e3, current: 0 }],
2233
+ ["max_network_requests", { limit: 100, current: 0 }],
2234
+ ["max_memory_usage_mb", { limit: 512, current: 0 }],
2235
+ ["max_execution_time_ms", { limit: 3e5, current: 0 }],
2236
+ ["forbidden_operations", { list: ["delete_system_files", "modify_credentials", "disable_logging"] }]
2237
+ ]),
2238
+ safetyEvents: [],
2239
+ overrideEnabled: true
2240
+ };
2241
+ }
2242
+ /**
2243
+ * Set up the collaboration engine with registries and communication log.
2244
+ */
2245
+ initializeCollaborationEngine() {
2246
+ return {
2247
+ activeCollaborations: /* @__PURE__ */ new Map(),
2248
+ communicationLog: [],
2249
+ teamRegistry: /* @__PURE__ */ new Map()
2250
+ };
2251
+ }
2252
+ /**
2253
+ * Perform full system initialization: activate learning, safety, and
2254
+ * log startup information.
2255
+ */
2256
+ async initializeSystem() {
2257
+ console.log(`[${this.systemName}] Initializing core system v${this.version}...`);
2258
+ this.isActive = true;
2259
+ this.learningMode = true;
2260
+ this.safetyMode = true;
2261
+ this.performanceMetrics.startTime = /* @__PURE__ */ new Date();
2262
+ console.log(`[${this.systemName}] Autonomy controller ready (level ${this.autonomyController.currentLevel})`);
2263
+ console.log(`[${this.systemName}] Decision engine ready`);
2264
+ console.log(`[${this.systemName}] Project ownership engine ready`);
2265
+ console.log(`[${this.systemName}] Learning engine ready (rate: ${this.learningEngine.adaptationRate})`);
2266
+ console.log(`[${this.systemName}] Safety engine ready (override: ${this.safetyEngine.overrideEnabled})`);
2267
+ console.log(`[${this.systemName}] Collaboration engine ready`);
2268
+ console.log(`[${this.systemName}] System initialization complete`);
2269
+ return {
2270
+ success: true,
2271
+ status: this.getSystemStatus()
2272
+ };
2273
+ }
2274
+ /**
2275
+ * Set the autonomy level (1-5) and update the system behavior accordingly.
2276
+ */
2277
+ setAutonomyLevel(level) {
2278
+ if (level < 1 || level > this.autonomyController.maxLevel) {
2279
+ console.log(
2280
+ `[${this.systemName}] Invalid autonomy level: ${level}. Must be 1-${this.autonomyController.maxLevel}`
2281
+ );
2282
+ return {
2283
+ success: false,
2284
+ level: this.autonomyLevel,
2285
+ name: this.autonomyController.levels[this.autonomyLevel].name,
2286
+ error: `Level must be between 1 and ${this.autonomyController.maxLevel}`
2287
+ };
2288
+ }
2289
+ const previousLevel = this.autonomyLevel;
2290
+ this.autonomyLevel = level;
2291
+ this.autonomyController.currentLevel = level;
2292
+ this.updateSystemBehavior(level);
2293
+ console.log(
2294
+ `[${this.systemName}] Autonomy level changed: ${previousLevel} -> ${level} (${this.autonomyController.levels[level].name})`
2295
+ );
2296
+ return {
2297
+ success: true,
2298
+ level,
2299
+ name: this.autonomyController.levels[level].name
2300
+ };
2301
+ }
2302
+ /**
2303
+ * Update internal system behavior based on the autonomy level.
2304
+ */
2305
+ updateSystemBehavior(level) {
2306
+ switch (level) {
2307
+ case 1:
2308
+ this.decisionEngine.autoApprove = false;
2309
+ this.safetyEngine.overrideEnabled = true;
2310
+ break;
2311
+ case 2:
2312
+ this.decisionEngine.autoApprove = false;
2313
+ this.safetyEngine.overrideEnabled = true;
2314
+ break;
2315
+ case 3:
2316
+ this.decisionEngine.autoApprove = true;
2317
+ this.safetyEngine.overrideEnabled = true;
2318
+ break;
2319
+ case 4:
2320
+ this.decisionEngine.autoApprove = true;
2321
+ this.safetyEngine.overrideEnabled = true;
2322
+ break;
2323
+ case 5:
2324
+ this.decisionEngine.autoApprove = true;
2325
+ this.safetyEngine.overrideEnabled = false;
2326
+ break;
2327
+ default:
2328
+ break;
2329
+ }
2330
+ }
2331
+ /**
2332
+ * Return a comprehensive snapshot of the current system status.
2333
+ */
2334
+ getSystemStatus() {
2335
+ const now = /* @__PURE__ */ new Date();
2336
+ const uptimeMs = now.getTime() - this.performanceMetrics.startTime.getTime();
2337
+ return {
2338
+ systemName: this.systemName,
2339
+ version: this.version,
2340
+ isActive: this.isActive,
2341
+ autonomyLevel: this.autonomyLevel,
2342
+ autonomyName: this.autonomyController.levels[this.autonomyLevel]?.name || "unknown",
2343
+ learningMode: this.learningMode,
2344
+ safetyMode: this.safetyMode,
2345
+ uptime: uptimeMs,
2346
+ activeProjects: this.projectOwner.activeProjects.size,
2347
+ completedProjects: this.projectOwner.completedProjects.size,
2348
+ pendingDecisions: this.decisionEngine.pendingDecisions.length,
2349
+ performanceMetrics: { ...this.performanceMetrics },
2350
+ safetyEvents: this.safetyEvents.length,
2351
+ learningHistory: this.learningHistory.length,
2352
+ knowledgeBaseSize: this.learningEngine.knowledgeBase.size,
2353
+ activeCollaborations: this.collaborationEngine.activeCollaborations.size
2354
+ };
2355
+ }
2356
+ /**
2357
+ * Attempt to load a configuration file from the given path.
2358
+ * Falls back to defaults if the file does not exist.
2359
+ */
2360
+ loadConfiguration(configPath) {
2361
+ try {
2362
+ const fullPath = (0, import_path.join)(configPath, "megagem.config.json");
2363
+ if ((0, import_fs.existsSync)(fullPath)) {
2364
+ const raw = (0, import_fs.readFileSync)(fullPath, "utf-8");
2365
+ const loaded = JSON.parse(raw);
2366
+ this.config = loaded;
2367
+ console.log(`[${this.systemName}] Configuration loaded from ${fullPath}`);
2368
+ return loaded;
2369
+ }
2370
+ console.log(`[${this.systemName}] No config file found at ${fullPath}, using defaults`);
2371
+ return this.config;
2372
+ } catch (error) {
2373
+ const msg = error instanceof Error ? error.message : String(error);
2374
+ console.log(`[${this.systemName}] Error loading configuration: ${msg}`);
2375
+ return this.config;
2376
+ }
2377
+ }
2378
+ /**
2379
+ * Return the default MEGAGEM configuration object.
2380
+ */
2381
+ getDefaultConfig() {
2382
+ const cfg = megagem_config_default;
2383
+ const autonomy = cfg.autonomy ?? {};
2384
+ const thresholds = autonomy.safetyThresholds ?? {};
2385
+ return {
2386
+ system: {
2387
+ name: cfg.system?.name ?? "MEGAGEM",
2388
+ version: cfg.system?.version ?? "1.0.0",
2389
+ description: cfg.system?.description ?? "Multi-Environment General-purpose Autonomous Governance and Execution Manager"
2390
+ },
2391
+ autonomy: {
2392
+ defaultLevel: autonomy.defaultLevel ?? 1,
2393
+ maxLevel: autonomy.maxLevel ?? 5,
2394
+ safetyThresholds: {
2395
+ riskTolerance: thresholds.riskTolerance ?? "medium",
2396
+ humanOversight: thresholds.humanOversight ?? "required"
2397
+ }
2398
+ },
2399
+ learning: {
2400
+ continuousLearning: cfg.learning?.continuousLearning ?? true,
2401
+ selfImprovement: cfg.learning?.selfImprovement ?? true,
2402
+ knowledgeSharing: cfg.learning?.knowledgeSharing ?? true
2403
+ },
2404
+ safety: {
2405
+ riskAssessment: cfg.safety?.riskAssessment ?? true,
2406
+ boundaryEnforcement: cfg.safety?.boundaryEnforcement ?? true,
2407
+ humanOverride: cfg.safety?.humanOverride ?? true,
2408
+ auditLogging: cfg.safety?.auditLogging ?? true
2409
+ }
2410
+ };
2411
+ }
2412
+ /**
2413
+ * Activate autonomous operation mode: sets the system active, starts
2414
+ * performance tracking, and returns the active capabilities.
2415
+ */
2416
+ async startAutonomousOperation() {
2417
+ if (!this.isActive) {
2418
+ await this.initializeSystem();
2419
+ }
2420
+ console.log(`[${this.systemName}] Starting autonomous operation at level ${this.autonomyLevel}...`);
2421
+ const capabilities = this.activateAutonomousCapabilities();
2422
+ console.log(`[${this.systemName}] Autonomous capabilities activated: ${capabilities.join(", ")}`);
2423
+ return {
2424
+ success: true,
2425
+ capabilities
2426
+ };
2427
+ }
2428
+ /**
2429
+ * Determine which capabilities should be active given the current
2430
+ * autonomy level and return them as a list.
2431
+ */
2432
+ activateAutonomousCapabilities() {
2433
+ const capabilities = [
2434
+ "monitoring",
2435
+ "reporting",
2436
+ "status_tracking"
2437
+ ];
2438
+ if (this.autonomyLevel >= 2) {
2439
+ capabilities.push("routine_decisions", "task_scheduling", "resource_monitoring");
2440
+ }
2441
+ if (this.autonomyLevel >= 3) {
2442
+ capabilities.push("project_planning", "team_coordination", "risk_assessment");
2443
+ }
2444
+ if (this.autonomyLevel >= 4) {
2445
+ capabilities.push("autonomous_execution", "adaptive_planning", "self_optimization");
2446
+ }
2447
+ if (this.autonomyLevel >= 5) {
2448
+ capabilities.push("full_project_ownership", "strategic_planning", "cross_project_optimization");
2449
+ }
2450
+ return capabilities;
2451
+ }
2452
+ /**
2453
+ * Return the list of capabilities currently active.
2454
+ */
2455
+ getActiveCapabilities() {
2456
+ return this.activateAutonomousCapabilities();
2457
+ }
2458
+ };
2459
+ var MEGAGEMAutonomousAgent = class {
2460
+ agentId;
2461
+ agentType;
2462
+ capabilities;
2463
+ autonomyLevel;
2464
+ isActive;
2465
+ currentProjects;
2466
+ performanceMetrics;
2467
+ learningHistory;
2468
+ collaborationHistory;
2469
+ status;
2470
+ currentTask;
2471
+ teamMembers;
2472
+ resources;
2473
+ knowledgeBase;
2474
+ skillLevels;
2475
+ adaptationRate;
2476
+ constructor(agentType = "general", autonomyLevel = 1) {
2477
+ this.agentId = this.generateAgentId();
2478
+ this.agentType = agentType;
2479
+ this.capabilities = {};
2480
+ this.autonomyLevel = autonomyLevel;
2481
+ this.isActive = false;
2482
+ this.currentProjects = /* @__PURE__ */ new Map();
2483
+ this.performanceMetrics = {
2484
+ tasksCompleted: 0,
2485
+ tasksFailed: 0,
2486
+ successRate: 1,
2487
+ averageCompletionTime: 0,
2488
+ qualityScore: 1,
2489
+ learningProgress: 0
2490
+ };
2491
+ this.learningHistory = [];
2492
+ this.collaborationHistory = [];
2493
+ this.status = "idle";
2494
+ this.currentTask = null;
2495
+ this.teamMembers = [];
2496
+ this.resources = /* @__PURE__ */ new Map();
2497
+ this.knowledgeBase = /* @__PURE__ */ new Map();
2498
+ this.skillLevels = /* @__PURE__ */ new Map();
2499
+ this.adaptationRate = 0.1;
2500
+ this.initializeCapabilities(agentType);
2501
+ }
2502
+ /**
2503
+ * Generate a unique agent identifier.
2504
+ */
2505
+ generateAgentId() {
2506
+ return `agent-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
2507
+ }
2508
+ /**
2509
+ * Activate the agent for autonomous operation.
2510
+ */
2511
+ activate() {
2512
+ this.isActive = true;
2513
+ this.status = "active";
2514
+ console.log(`[Agent:${this.agentId}] Activated as ${this.agentType} agent (autonomy level ${this.autonomyLevel})`);
2515
+ }
2516
+ /**
2517
+ * Initialize capabilities based on the agent type. Supports five
2518
+ * types: project-manager, developer, designer, analyst, general.
2519
+ */
2520
+ initializeCapabilities(agentType) {
2521
+ switch (agentType) {
2522
+ case "project-manager":
2523
+ this.capabilities = {
2524
+ planning: true,
2525
+ scheduling: true,
2526
+ resourceAllocation: true,
2527
+ riskManagement: true,
2528
+ teamCoordination: true,
2529
+ reporting: true,
2530
+ budgetManagement: true,
2531
+ stakeholderCommunication: true,
2532
+ qualityAssurance: true,
2533
+ scope: "project",
2534
+ specializations: ["waterfall", "agile", "hybrid"]
2535
+ };
2536
+ this.skillLevels.set("planning", 0.9);
2537
+ this.skillLevels.set("communication", 0.85);
2538
+ this.skillLevels.set("risk-assessment", 0.8);
2539
+ this.skillLevels.set("resource-management", 0.85);
2540
+ this.skillLevels.set("quality-control", 0.8);
2541
+ break;
2542
+ case "developer":
2543
+ this.capabilities = {
2544
+ coding: true,
2545
+ testing: true,
2546
+ debugging: true,
2547
+ codeReview: true,
2548
+ architecture: true,
2549
+ documentation: true,
2550
+ deployment: true,
2551
+ optimization: true,
2552
+ scope: "technical",
2553
+ specializations: ["frontend", "backend", "fullstack", "devops"]
2554
+ };
2555
+ this.skillLevels.set("coding", 0.9);
2556
+ this.skillLevels.set("testing", 0.85);
2557
+ this.skillLevels.set("architecture", 0.8);
2558
+ this.skillLevels.set("debugging", 0.85);
2559
+ this.skillLevels.set("documentation", 0.7);
2560
+ break;
2561
+ case "designer":
2562
+ this.capabilities = {
2563
+ uiDesign: true,
2564
+ uxResearch: true,
2565
+ prototyping: true,
2566
+ visualDesign: true,
2567
+ designSystems: true,
2568
+ accessibility: true,
2569
+ userTesting: true,
2570
+ scope: "design",
2571
+ specializations: ["ui", "ux", "graphic", "interaction"]
2572
+ };
2573
+ this.skillLevels.set("visual-design", 0.9);
2574
+ this.skillLevels.set("ux-research", 0.85);
2575
+ this.skillLevels.set("prototyping", 0.8);
2576
+ this.skillLevels.set("accessibility", 0.75);
2577
+ this.skillLevels.set("design-systems", 0.8);
2578
+ break;
2579
+ case "analyst":
2580
+ this.capabilities = {
2581
+ dataAnalysis: true,
2582
+ reporting: true,
2583
+ forecasting: true,
2584
+ visualization: true,
2585
+ requirementsGathering: true,
2586
+ processModeling: true,
2587
+ scope: "analytical",
2588
+ specializations: ["data", "business", "systems", "security"]
2589
+ };
2590
+ this.skillLevels.set("data-analysis", 0.9);
2591
+ this.skillLevels.set("reporting", 0.85);
2592
+ this.skillLevels.set("forecasting", 0.8);
2593
+ this.skillLevels.set("visualization", 0.8);
2594
+ this.skillLevels.set("requirements", 0.85);
2595
+ break;
2596
+ case "general":
2597
+ default:
2598
+ this.capabilities = {
2599
+ planning: true,
2600
+ execution: true,
2601
+ monitoring: true,
2602
+ reporting: true,
2603
+ collaboration: true,
2604
+ learning: true,
2605
+ scope: "general",
2606
+ specializations: ["general-purpose"]
2607
+ };
2608
+ this.skillLevels.set("planning", 0.7);
2609
+ this.skillLevels.set("execution", 0.7);
2610
+ this.skillLevels.set("monitoring", 0.7);
2611
+ this.skillLevels.set("reporting", 0.7);
2612
+ this.skillLevels.set("collaboration", 0.7);
2613
+ break;
2614
+ }
2615
+ }
2616
+ /**
2617
+ * Take ownership of a project, creating the internal project record
2618
+ * and setting status to planning.
2619
+ */
2620
+ async takeProjectOwnership(projectData) {
2621
+ const projectId = this.generateProjectId();
2622
+ const project = {
2623
+ id: projectId,
2624
+ name: projectData.name,
2625
+ description: projectData.description,
2626
+ type: projectData.type,
2627
+ status: "planning",
2628
+ ownershipLevel: "full",
2629
+ startDate: /* @__PURE__ */ new Date(),
2630
+ objectives: projectData.objectives || [],
2631
+ constraints: projectData.constraints || [],
2632
+ resources: projectData.resources || {},
2633
+ timeline: projectData.timeline || {},
2634
+ team: /* @__PURE__ */ new Set([this.agentId]),
2635
+ tasks: /* @__PURE__ */ new Map(),
2636
+ milestones: /* @__PURE__ */ new Map(),
2637
+ risks: /* @__PURE__ */ new Map(),
2638
+ progress: 0
2639
+ };
2640
+ this.currentProjects.set(projectId, project);
2641
+ console.log(`[Agent:${this.agentId}] Took ownership of project: ${projectData.name} (${projectId})`);
2642
+ return project;
2643
+ }
2644
+ /**
2645
+ * Execute a project autonomously through all lifecycle phases:
2646
+ * plan -> form team -> allocate resources -> execute -> monitor -> deliver.
2647
+ */
2648
+ async executeProjectAutonomously(projectId) {
2649
+ const project = this.currentProjects.get(projectId);
2650
+ if (!project) {
2651
+ throw new Error(`Project ${projectId} not found`);
2652
+ }
2653
+ console.log(`[Agent:${this.agentId}] Starting autonomous execution of project: ${project.name}`);
2654
+ try {
2655
+ project.status = "planning";
2656
+ console.log(`[Agent:${this.agentId}] Phase 1: Planning project...`);
2657
+ await this.planProject(project);
2658
+ project.status = "team-formation";
2659
+ console.log(`[Agent:${this.agentId}] Phase 2: Forming project team...`);
2660
+ await this.formProjectTeam(project);
2661
+ project.status = "resource-allocation";
2662
+ console.log(`[Agent:${this.agentId}] Phase 3: Allocating resources...`);
2663
+ await this.allocateResources(project);
2664
+ project.status = "in-progress";
2665
+ console.log(`[Agent:${this.agentId}] Phase 4: Executing project plan...`);
2666
+ await this.executeProjectPlan(project);
2667
+ project.status = "monitoring";
2668
+ console.log(`[Agent:${this.agentId}] Phase 5: Monitoring and controlling...`);
2669
+ await this.monitorAndControl(project);
2670
+ project.status = "delivering";
2671
+ console.log(`[Agent:${this.agentId}] Phase 6: Delivering project...`);
2672
+ await this.deliverProject(project);
2673
+ project.status = "completed";
2674
+ project.endDate = /* @__PURE__ */ new Date();
2675
+ project.progress = 100;
2676
+ console.log(`[Agent:${this.agentId}] Project ${project.name} completed successfully`);
2677
+ return project;
2678
+ } catch (error) {
2679
+ const errorMessage = error instanceof Error ? error.message : String(error);
2680
+ project.status = "failed";
2681
+ project.error = errorMessage;
2682
+ console.log(`[Agent:${this.agentId}] Project ${project.name} failed: ${errorMessage}`);
2683
+ return project;
2684
+ }
2685
+ }
2686
+ /**
2687
+ * Create a strategic plan for the project including phases, milestones,
2688
+ * task breakdown, timeline, resource plan, and risk assessment.
2689
+ */
2690
+ async planProject(project) {
2691
+ const strategicPlan = this.createStrategicPlan(project);
2692
+ project.plan = strategicPlan;
2693
+ const phases = this.defineProjectPhases(project);
2694
+ project.plan.phases = phases;
2695
+ const milestones = this.defineMilestones(project);
2696
+ for (const milestone of milestones) {
2697
+ project.milestones.set(milestone.id, milestone);
2698
+ }
2699
+ const tasks = this.breakDownTasks(project);
2700
+ for (const task of tasks) {
2701
+ project.tasks.set(task.id, task);
2702
+ }
2703
+ const timeline = this.createTimeline(project);
2704
+ project.timeline = timeline;
2705
+ const resourcePlan = this.planResources(project);
2706
+ project.plan.resources = resourcePlan;
2707
+ const risks = this.assessRisks(project);
2708
+ for (const risk of risks) {
2709
+ project.risks.set(risk.id, risk);
2710
+ }
2711
+ project.strategy = strategicPlan;
2712
+ console.log(
2713
+ `[Agent:${this.agentId}] Project plan created: ${phases.length} phases, ${milestones.length} milestones, ${tasks.length} tasks, ${risks.length} risks`
2714
+ );
2715
+ }
2716
+ /**
2717
+ * Form a team for the project by analyzing requirements and assigning roles.
2718
+ */
2719
+ async formProjectTeam(project) {
2720
+ const requirements = this.analyzeTeamRequirements(project);
2721
+ const teamMembers = [];
2722
+ for (const role of requirements.roles) {
2723
+ const member = {
2724
+ id: `member-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
2725
+ role,
2726
+ capabilities: this.getRoleCapabilities(role),
2727
+ assignedDate: (/* @__PURE__ */ new Date()).toISOString(),
2728
+ status: "assigned"
2729
+ };
2730
+ teamMembers.push(member);
2731
+ project.team.add(member.id);
2732
+ }
2733
+ project.teamMembers = teamMembers;
2734
+ console.log(
2735
+ `[Agent:${this.agentId}] Team formed: ${teamMembers.length} members for ${requirements.roles.length} roles`
2736
+ );
2737
+ }
2738
+ /**
2739
+ * Allocate resources to the project based on current plan and constraints.
2740
+ */
2741
+ async allocateResources(project) {
2742
+ const resourceAllocation = {
2743
+ compute: {
2744
+ allocated: true,
2745
+ type: "standard",
2746
+ units: Math.max(1, project.tasks.size)
2747
+ },
2748
+ storage: {
2749
+ allocated: true,
2750
+ type: "standard",
2751
+ sizeMB: 100
2752
+ },
2753
+ budget: {
2754
+ allocated: true,
2755
+ total: project.constraints.length > 0 ? 1e4 : 5e3,
2756
+ spent: 0,
2757
+ remaining: project.constraints.length > 0 ? 1e4 : 5e3
2758
+ },
2759
+ time: {
2760
+ allocated: true,
2761
+ totalHours: project.tasks.size * 8,
2762
+ usedHours: 0,
2763
+ remainingHours: project.tasks.size * 8
2764
+ }
2765
+ };
2766
+ project.resources = resourceAllocation;
2767
+ console.log(
2768
+ `[Agent:${this.agentId}] Resources allocated: ${project.tasks.size} compute units, ${resourceAllocation.time.totalHours}h total`
2769
+ );
2770
+ }
2771
+ /**
2772
+ * Execute the project plan by iterating through all tasks.
2773
+ */
2774
+ async executeProjectPlan(project) {
2775
+ const tasks = Array.from(project.tasks.entries());
2776
+ let completedTasks = 0;
2777
+ const totalTasks = tasks.length;
2778
+ for (const [taskId, taskData] of tasks) {
2779
+ const task = taskData;
2780
+ console.log(`[Agent:${this.agentId}] Executing task: ${task.name} (${taskId})`);
2781
+ const result = await this.executeTask(task);
2782
+ if (result.success) {
2783
+ task.status = "completed";
2784
+ task.completedDate = (/* @__PURE__ */ new Date()).toISOString();
2785
+ task.result = result.output;
2786
+ completedTasks++;
2787
+ this.performanceMetrics.tasksCompleted++;
2788
+ } else {
2789
+ task.status = "failed";
2790
+ task.error = result.error;
2791
+ this.performanceMetrics.tasksFailed++;
2792
+ console.log(`[Agent:${this.agentId}] Task ${taskId} failed: ${result.error}`);
2793
+ }
2794
+ project.progress = Math.round(completedTasks / totalTasks * 80);
2795
+ }
2796
+ const totalAttempted = this.performanceMetrics.tasksCompleted + this.performanceMetrics.tasksFailed;
2797
+ this.performanceMetrics.successRate = totalAttempted > 0 ? this.performanceMetrics.tasksCompleted / totalAttempted : 1;
2798
+ console.log(
2799
+ `[Agent:${this.agentId}] Plan execution complete: ${completedTasks}/${totalTasks} tasks completed`
2800
+ );
2801
+ }
2802
+ /**
2803
+ * Monitor project health and adjust the plan if deviations are detected.
2804
+ */
2805
+ async monitorAndControl(project) {
2806
+ const health = this.assessProjectHealth(project);
2807
+ project.healthMetrics = health;
2808
+ console.log(
2809
+ `[Agent:${this.agentId}] Project health: ${health.overall} (score: ${health.score})`
2810
+ );
2811
+ if (health.score < 0.7) {
2812
+ console.log(`[Agent:${this.agentId}] Health below threshold, adjusting plan...`);
2813
+ await this.adjustProjectPlan(project, health);
2814
+ }
2815
+ project.progress = 90;
2816
+ }
2817
+ /**
2818
+ * Deliver project outputs, perform quality checks, and prepare deliverables.
2819
+ */
2820
+ async deliverProject(project) {
2821
+ console.log(`[Agent:${this.agentId}] Performing final quality check...`);
2822
+ const qualityResult = this.performQualityCheck(project);
2823
+ project.qualityScore = qualityResult.score;
2824
+ console.log(`[Agent:${this.agentId}] Preparing deliverables...`);
2825
+ const deliverables = this.prepareDeliverables(project);
2826
+ project.deliverables = deliverables;
2827
+ project.progress = 100;
2828
+ project.status = "delivered";
2829
+ console.log(
2830
+ `[Agent:${this.agentId}] Project ${project.name} delivered (quality: ${project.qualityScore})`
2831
+ );
2832
+ }
2833
+ /**
2834
+ * Build a strategic plan from the project's objectives and constraints.
2835
+ */
2836
+ createStrategicPlan(project) {
2837
+ return {
2838
+ projectId: project.id,
2839
+ projectName: project.name,
2840
+ vision: `Successfully deliver ${project.name}: ${project.description}`,
2841
+ objectives: project.objectives.map((obj, index) => ({
2842
+ id: `obj-${index + 1}`,
2843
+ description: obj,
2844
+ priority: index === 0 ? "high" : "medium",
2845
+ status: "pending"
2846
+ })),
2847
+ constraints: project.constraints,
2848
+ approach: project.type === "agile" ? "iterative" : "sequential",
2849
+ riskStrategy: "proactive",
2850
+ qualityStandard: "high",
2851
+ communicationPlan: {
2852
+ frequency: "daily",
2853
+ channels: ["status-report", "milestone-review"],
2854
+ stakeholders: ["team", "owner"]
2855
+ },
2856
+ createdDate: (/* @__PURE__ */ new Date()).toISOString()
2857
+ };
2858
+ }
2859
+ /**
2860
+ * Define project phases based on the project type.
2861
+ */
2862
+ defineProjectPhases(project) {
2863
+ const phaseTemplates = {
2864
+ standard: ["initiation", "planning", "execution", "monitoring", "closure"],
2865
+ agile: ["backlog-refinement", "sprint-planning", "development", "review", "retrospective"],
2866
+ research: ["exploration", "hypothesis", "experimentation", "analysis", "reporting"]
2867
+ };
2868
+ const phaseNames = phaseTemplates[project.type] || phaseTemplates["standard"];
2869
+ return phaseNames.map((name, index) => ({
2870
+ id: `phase-${index + 1}`,
2871
+ name,
2872
+ order: index + 1,
2873
+ status: "pending",
2874
+ startDate: null,
2875
+ endDate: null,
2876
+ dependencies: index > 0 ? [`phase-${index}`] : []
2877
+ }));
2878
+ }
2879
+ /**
2880
+ * Define milestones for the project plan.
2881
+ */
2882
+ defineMilestones(_project) {
2883
+ const baseMilestones = [
2884
+ "Project Kickoff",
2885
+ "Requirements Complete",
2886
+ "Design Approved",
2887
+ "Development Complete",
2888
+ "Testing Complete",
2889
+ "Deployment Ready",
2890
+ "Project Closure"
2891
+ ];
2892
+ return baseMilestones.map((name, index) => ({
2893
+ id: `milestone-${index + 1}`,
2894
+ name,
2895
+ order: index + 1,
2896
+ status: "pending",
2897
+ dueDate: null,
2898
+ criteria: [`${name} criteria met`],
2899
+ deliverables: [`${name} artifacts`]
2900
+ }));
2901
+ }
2902
+ /**
2903
+ * Break project objectives down into concrete tasks.
2904
+ */
2905
+ breakDownTasks(project) {
2906
+ const tasks = [];
2907
+ let taskCounter = 0;
2908
+ for (const objective of project.objectives) {
2909
+ taskCounter++;
2910
+ tasks.push({
2911
+ id: `task-${taskCounter}`,
2912
+ name: `Analyze: ${objective}`,
2913
+ type: "analysis",
2914
+ status: "pending",
2915
+ priority: "high",
2916
+ estimatedHours: 4,
2917
+ assignee: null,
2918
+ dependencies: []
2919
+ });
2920
+ taskCounter++;
2921
+ tasks.push({
2922
+ id: `task-${taskCounter}`,
2923
+ name: `Implement: ${objective}`,
2924
+ type: "implementation",
2925
+ status: "pending",
2926
+ priority: "high",
2927
+ estimatedHours: 16,
2928
+ assignee: null,
2929
+ dependencies: [`task-${taskCounter - 1}`]
2930
+ });
2931
+ taskCounter++;
2932
+ tasks.push({
2933
+ id: `task-${taskCounter}`,
2934
+ name: `Verify: ${objective}`,
2935
+ type: "verification",
2936
+ status: "pending",
2937
+ priority: "medium",
2938
+ estimatedHours: 4,
2939
+ assignee: null,
2940
+ dependencies: [`task-${taskCounter - 1}`]
2941
+ });
2942
+ }
2943
+ if (tasks.length === 0) {
2944
+ tasks.push(
2945
+ {
2946
+ id: "task-1",
2947
+ name: "Setup project environment",
2948
+ type: "setup",
2949
+ status: "pending",
2950
+ priority: "high",
2951
+ estimatedHours: 4,
2952
+ assignee: null,
2953
+ dependencies: []
2954
+ },
2955
+ {
2956
+ id: "task-2",
2957
+ name: "Define project requirements",
2958
+ type: "analysis",
2959
+ status: "pending",
2960
+ priority: "high",
2961
+ estimatedHours: 8,
2962
+ assignee: null,
2963
+ dependencies: ["task-1"]
2964
+ },
2965
+ {
2966
+ id: "task-3",
2967
+ name: "Implement core functionality",
2968
+ type: "implementation",
2969
+ status: "pending",
2970
+ priority: "high",
2971
+ estimatedHours: 24,
2972
+ assignee: null,
2973
+ dependencies: ["task-2"]
2974
+ },
2975
+ {
2976
+ id: "task-4",
2977
+ name: "Test and validate",
2978
+ type: "verification",
2979
+ status: "pending",
2980
+ priority: "medium",
2981
+ estimatedHours: 8,
2982
+ assignee: null,
2983
+ dependencies: ["task-3"]
2984
+ },
2985
+ {
2986
+ id: "task-5",
2987
+ name: "Document and deliver",
2988
+ type: "delivery",
2989
+ status: "pending",
2990
+ priority: "medium",
2991
+ estimatedHours: 4,
2992
+ assignee: null,
2993
+ dependencies: ["task-4"]
2994
+ }
2995
+ );
2996
+ }
2997
+ return tasks;
2998
+ }
2999
+ /**
3000
+ * Build a timeline for the project based on tasks and milestones.
3001
+ */
3002
+ createTimeline(project) {
3003
+ const totalTasks = project.tasks.size;
3004
+ const estimatedHours = totalTasks * 8;
3005
+ const estimatedDays = Math.ceil(estimatedHours / 8);
3006
+ const startDate = project.startDate;
3007
+ const endDate = new Date(startDate);
3008
+ endDate.setDate(endDate.getDate() + estimatedDays);
3009
+ return {
3010
+ startDate: startDate.toISOString(),
3011
+ endDate: endDate.toISOString(),
3012
+ totalDays: estimatedDays,
3013
+ totalHours: estimatedHours,
3014
+ workingHoursPerDay: 8,
3015
+ phases: Array.from(project.milestones.entries()).map(
3016
+ ([id, milestone]) => ({
3017
+ milestoneId: id,
3018
+ milestone
3019
+ })
3020
+ ),
3021
+ criticalPath: Array.from(project.tasks.keys()),
3022
+ bufferDays: Math.ceil(estimatedDays * 0.2)
3023
+ };
3024
+ }
3025
+ /**
3026
+ * Create a resource allocation plan for the project.
3027
+ */
3028
+ planResources(project) {
3029
+ const teamSize = project.team.size;
3030
+ const taskCount = project.tasks.size;
3031
+ return {
3032
+ team: {
3033
+ current: teamSize,
3034
+ required: Math.max(teamSize, Math.ceil(taskCount / 5)),
3035
+ utilization: teamSize > 0 ? Math.min(1, taskCount / (teamSize * 5)) : 0
3036
+ },
3037
+ budget: {
3038
+ estimated: taskCount * 500,
3039
+ allocated: 0,
3040
+ contingency: taskCount * 100
3041
+ },
3042
+ tools: {
3043
+ required: ["version-control", "ci-cd", "monitoring", "communication"],
3044
+ available: ["version-control", "communication"],
3045
+ gaps: ["ci-cd", "monitoring"]
3046
+ },
3047
+ infrastructure: {
3048
+ compute: "standard",
3049
+ storage: "standard",
3050
+ networking: "standard"
3051
+ }
3052
+ };
3053
+ }
3054
+ /**
3055
+ * Assess potential risks for the project and return a list of risk records.
3056
+ */
3057
+ assessRisks(project) {
3058
+ const risks = [
3059
+ {
3060
+ id: "risk-1",
3061
+ name: "Scope creep",
3062
+ category: "scope",
3063
+ probability: 0.6,
3064
+ impact: 0.7,
3065
+ severity: 0.42,
3066
+ mitigation: "Strict change control process and regular scope reviews",
3067
+ status: "identified"
3068
+ },
3069
+ {
3070
+ id: "risk-2",
3071
+ name: "Resource unavailability",
3072
+ category: "resource",
3073
+ probability: 0.3,
3074
+ impact: 0.8,
3075
+ severity: 0.24,
3076
+ mitigation: "Cross-training and backup resource identification",
3077
+ status: "identified"
3078
+ },
3079
+ {
3080
+ id: "risk-3",
3081
+ name: "Technical complexity",
3082
+ category: "technical",
3083
+ probability: 0.5,
3084
+ impact: 0.6,
3085
+ severity: 0.3,
3086
+ mitigation: "Proof of concept and incremental development approach",
3087
+ status: "identified"
3088
+ },
3089
+ {
3090
+ id: "risk-4",
3091
+ name: "Timeline pressure",
3092
+ category: "schedule",
3093
+ probability: 0.4,
3094
+ impact: 0.7,
3095
+ severity: 0.28,
3096
+ mitigation: "Buffer time allocation and milestone tracking",
3097
+ status: "identified"
3098
+ }
3099
+ ];
3100
+ if (project.constraints.length > 0) {
3101
+ risks.push({
3102
+ id: "risk-5",
3103
+ name: "Constraint violations",
3104
+ category: "compliance",
3105
+ probability: 0.3,
3106
+ impact: 0.9,
3107
+ severity: 0.27,
3108
+ mitigation: "Regular constraint validation and compliance checks",
3109
+ status: "identified"
3110
+ });
3111
+ }
3112
+ return risks;
3113
+ }
3114
+ /**
3115
+ * Analyze the team requirements for a project based on its type and scope.
3116
+ */
3117
+ analyzeTeamRequirements(project) {
3118
+ const roleMap = {
3119
+ standard: ["project-lead", "developer", "tester", "reviewer"],
3120
+ agile: ["product-owner", "scrum-master", "developer", "tester"],
3121
+ research: ["principal-investigator", "researcher", "analyst"]
3122
+ };
3123
+ const roles = roleMap[project.type] || roleMap["standard"];
3124
+ const skillMap = {
3125
+ standard: ["planning", "development", "testing", "communication"],
3126
+ agile: ["agile-methodology", "development", "testing", "collaboration"],
3127
+ research: ["research-methodology", "data-analysis", "writing", "critical-thinking"]
3128
+ };
3129
+ const skills = skillMap[project.type] || skillMap["standard"];
3130
+ return {
3131
+ roles,
3132
+ skills,
3133
+ minSize: roles.length,
3134
+ maxSize: roles.length * 2
3135
+ };
3136
+ }
3137
+ /**
3138
+ * Return the capabilities expected for a given team role.
3139
+ */
3140
+ getRoleCapabilities(role) {
3141
+ const capabilityMap = {
3142
+ "project-lead": ["planning", "coordination", "decision-making", "reporting"],
3143
+ "product-owner": ["backlog-management", "prioritization", "stakeholder-communication"],
3144
+ "scrum-master": ["facilitation", "impediment-removal", "process-improvement"],
3145
+ developer: ["coding", "testing", "code-review", "documentation"],
3146
+ designer: ["ui-design", "ux-research", "prototyping", "visual-design"],
3147
+ tester: ["test-planning", "test-execution", "bug-reporting", "automation"],
3148
+ reviewer: ["code-review", "quality-assessment", "feedback", "standards-enforcement"],
3149
+ analyst: ["data-analysis", "reporting", "requirements-gathering", "modeling"],
3150
+ "principal-investigator": ["research-design", "methodology", "publication", "mentoring"],
3151
+ researcher: ["data-collection", "analysis", "literature-review", "experimentation"]
3152
+ };
3153
+ return capabilityMap[role] || ["general-support", "collaboration"];
3154
+ }
3155
+ /**
3156
+ * Execute a single task and return the result.
3157
+ */
3158
+ async executeTask(task) {
3159
+ const startTime = Date.now();
3160
+ try {
3161
+ this.currentTask = task.id;
3162
+ this.status = "working";
3163
+ const taskType = task.type || "general";
3164
+ let output;
3165
+ switch (taskType) {
3166
+ case "analysis":
3167
+ output = {
3168
+ analyzed: true,
3169
+ findings: [],
3170
+ recommendations: []
3171
+ };
3172
+ break;
3173
+ case "implementation":
3174
+ output = {
3175
+ implemented: true,
3176
+ artifacts: [],
3177
+ testsWritten: 0
3178
+ };
3179
+ break;
3180
+ case "verification":
3181
+ output = {
3182
+ verified: true,
3183
+ testsPassed: 0,
3184
+ testsFailed: 0,
3185
+ coverage: 0
3186
+ };
3187
+ break;
3188
+ case "setup":
3189
+ output = {
3190
+ environmentReady: true,
3191
+ toolsInstalled: [],
3192
+ configurationComplete: true
3193
+ };
3194
+ break;
3195
+ case "delivery":
3196
+ output = {
3197
+ delivered: true,
3198
+ artifacts: [],
3199
+ documentation: true
3200
+ };
3201
+ break;
3202
+ default:
3203
+ output = {
3204
+ completed: true,
3205
+ type: taskType
3206
+ };
3207
+ break;
3208
+ }
3209
+ const duration = Date.now() - startTime;
3210
+ this.currentTask = null;
3211
+ this.status = "active";
3212
+ const totalCompleted = this.performanceMetrics.tasksCompleted + 1;
3213
+ this.performanceMetrics.averageCompletionTime = (this.performanceMetrics.averageCompletionTime * this.performanceMetrics.tasksCompleted + duration) / totalCompleted;
3214
+ return {
3215
+ success: true,
3216
+ output,
3217
+ duration
3218
+ };
3219
+ } catch (error) {
3220
+ const errorMessage = error instanceof Error ? error.message : String(error);
3221
+ this.currentTask = null;
3222
+ this.status = "active";
3223
+ return {
3224
+ success: false,
3225
+ error: errorMessage,
3226
+ duration: Date.now() - startTime
3227
+ };
3228
+ }
3229
+ }
3230
+ /**
3231
+ * Determine if a project phase is complete by checking task statuses.
3232
+ */
3233
+ isPhaseComplete(project, phaseIndex) {
3234
+ const tasks = Array.from(project.tasks.entries());
3235
+ const tasksPerPhase = Math.max(1, Math.ceil(tasks.length / 5));
3236
+ const startIdx = phaseIndex * tasksPerPhase;
3237
+ const endIdx = Math.min(startIdx + tasksPerPhase, tasks.length);
3238
+ for (let i = startIdx; i < endIdx; i++) {
3239
+ if (i < tasks.length) {
3240
+ const task = tasks[i][1];
3241
+ if (task.status !== "completed") {
3242
+ return false;
3243
+ }
3244
+ }
3245
+ }
3246
+ return true;
3247
+ }
3248
+ /**
3249
+ * Assess overall project health across timeline, quality, resources,
3250
+ * and risks dimensions.
3251
+ */
3252
+ assessProjectHealth(project) {
3253
+ const timelineHealth = this.assessTimelineHealth(project);
3254
+ const qualityHealth = this.assessQualityHealth(project);
3255
+ const resourceHealth = this.assessResourceHealth(project);
3256
+ const riskHealth = this.assessRiskHealth(project);
3257
+ const overallScore = timelineHealth * 0.3 + qualityHealth * 0.3 + resourceHealth * 0.2 + riskHealth * 0.2;
3258
+ let overall;
3259
+ if (overallScore >= 0.8) {
3260
+ overall = "healthy";
3261
+ } else if (overallScore >= 0.6) {
3262
+ overall = "at-risk";
3263
+ } else if (overallScore >= 0.4) {
3264
+ overall = "critical";
3265
+ } else {
3266
+ overall = "failing";
3267
+ }
3268
+ return {
3269
+ overall,
3270
+ score: Math.round(overallScore * 100) / 100,
3271
+ timeline: timelineHealth >= 0.7 ? "on-track" : "delayed",
3272
+ quality: qualityHealth >= 0.7 ? "acceptable" : "below-standard",
3273
+ resources: resourceHealth >= 0.7 ? "adequate" : "constrained",
3274
+ risks: riskHealth >= 0.7 ? "managed" : "elevated",
3275
+ details: {
3276
+ timelineScore: timelineHealth,
3277
+ qualityScore: qualityHealth,
3278
+ resourceScore: resourceHealth,
3279
+ riskScore: riskHealth
3280
+ }
3281
+ };
3282
+ }
3283
+ /**
3284
+ * Assess the timeline health of the project (0.0 - 1.0).
3285
+ */
3286
+ assessTimelineHealth(project) {
3287
+ const totalTasks = project.tasks.size;
3288
+ if (totalTasks === 0) return 1;
3289
+ let completedTasks = 0;
3290
+ for (const [, task] of project.tasks) {
3291
+ if (task.status === "completed") {
3292
+ completedTasks++;
3293
+ }
3294
+ }
3295
+ const completionRatio = completedTasks / totalTasks;
3296
+ const expectedProgress = project.progress / 100;
3297
+ const deviation = Math.abs(completionRatio - expectedProgress);
3298
+ return Math.max(0, 1 - deviation);
3299
+ }
3300
+ /**
3301
+ * Assess the quality health of the project (0.0 - 1.0).
3302
+ */
3303
+ assessQualityHealth(_project) {
3304
+ if (this.performanceMetrics.tasksCompleted === 0) return 1;
3305
+ return this.performanceMetrics.successRate;
3306
+ }
3307
+ /**
3308
+ * Assess the resource health of the project (0.0 - 1.0).
3309
+ */
3310
+ assessResourceHealth(project) {
3311
+ const resources = project.resources;
3312
+ if (!resources || Object.keys(resources).length === 0) return 0.8;
3313
+ const budget = resources.budget;
3314
+ if (budget && typeof budget.total === "number" && typeof budget.spent === "number") {
3315
+ const budgetRatio = budget.total > 0 ? 1 - budget.spent / budget.total : 1;
3316
+ return Math.max(0, Math.min(1, budgetRatio));
3317
+ }
3318
+ return 0.8;
3319
+ }
3320
+ /**
3321
+ * Assess the risk health of the project (0.0 - 1.0).
3322
+ */
3323
+ assessRiskHealth(project) {
3324
+ const riskCount = project.risks.size;
3325
+ if (riskCount === 0) return 1;
3326
+ let totalSeverity = 0;
3327
+ for (const [, risk] of project.risks) {
3328
+ const r = risk;
3329
+ totalSeverity += r.severity || 0;
3330
+ }
3331
+ const avgSeverity = totalSeverity / riskCount;
3332
+ return Math.max(0, 1 - avgSeverity);
3333
+ }
3334
+ /**
3335
+ * Adjust the project plan to address health assessment findings.
3336
+ */
3337
+ async adjustProjectPlan(project, health) {
3338
+ console.log(`[Agent:${this.agentId}] Adjusting project plan based on health assessment...`);
3339
+ if (health.timeline === "delayed") {
3340
+ console.log(`[Agent:${this.agentId}] Addressing timeline delays...`);
3341
+ this.accelerateProject(project);
3342
+ }
3343
+ if (health.quality === "below-standard") {
3344
+ console.log(`[Agent:${this.agentId}] Addressing quality issues...`);
3345
+ this.improveQuality(project);
3346
+ }
3347
+ if (health.resources === "constrained") {
3348
+ console.log(`[Agent:${this.agentId}] Addressing resource constraints...`);
3349
+ this.optimizeResources(project);
3350
+ }
3351
+ console.log(`[Agent:${this.agentId}] Project plan adjusted`);
3352
+ }
3353
+ /**
3354
+ * Accelerate project execution by reprioritizing tasks.
3355
+ */
3356
+ accelerateProject(project) {
3357
+ for (const [, task] of project.tasks) {
3358
+ const t = task;
3359
+ if (t.status === "pending" && t.priority === "medium") {
3360
+ t.priority = "high";
3361
+ }
3362
+ if (t.status === "pending" && typeof t.estimatedHours === "number") {
3363
+ t.estimatedHours = Math.ceil(t.estimatedHours * 0.8);
3364
+ }
3365
+ }
3366
+ console.log(`[Agent:${this.agentId}] Tasks reprioritized and estimates reduced for acceleration`);
3367
+ }
3368
+ /**
3369
+ * Improve quality by adding quality gates to the project.
3370
+ */
3371
+ improveQuality(project) {
3372
+ project.qualityGates = [
3373
+ "code-review-required",
3374
+ "testing-threshold-80",
3375
+ "documentation-required",
3376
+ "peer-approval-required"
3377
+ ];
3378
+ console.log(`[Agent:${this.agentId}] Quality gates added: ${project.qualityGates.length} gates`);
3379
+ }
3380
+ /**
3381
+ * Optimize resource usage by consolidating and redistributing.
3382
+ */
3383
+ optimizeResources(project) {
3384
+ const resources = project.resources;
3385
+ if (resources && resources.budget) {
3386
+ const budget = resources.budget;
3387
+ if (typeof budget.contingency === "number") {
3388
+ const released = Math.ceil(budget.contingency * 0.5);
3389
+ budget.contingency = budget.contingency - released;
3390
+ budget.remaining = (budget.remaining || 0) + released;
3391
+ }
3392
+ }
3393
+ console.log(`[Agent:${this.agentId}] Resources optimized with contingency reallocation`);
3394
+ }
3395
+ /**
3396
+ * Perform a quality check on the project deliverables.
3397
+ */
3398
+ performQualityCheck(project) {
3399
+ const totalTasks = project.tasks.size;
3400
+ let completedTasks = 0;
3401
+ let failedTasks = 0;
3402
+ for (const [, task] of project.tasks) {
3403
+ const t = task;
3404
+ if (t.status === "completed") completedTasks++;
3405
+ if (t.status === "failed") failedTasks++;
3406
+ }
3407
+ const completionRate = totalTasks > 0 ? completedTasks / totalTasks : 0;
3408
+ const failureRate = totalTasks > 0 ? failedTasks / totalTasks : 0;
3409
+ const qualityScore = Math.max(0, completionRate - failureRate * 0.5);
3410
+ return {
3411
+ score: Math.round(qualityScore * 100) / 100,
3412
+ completionRate: Math.round(completionRate * 100) / 100,
3413
+ failureRate: Math.round(failureRate * 100) / 100,
3414
+ totalTasks,
3415
+ completedTasks,
3416
+ failedTasks,
3417
+ qualityGatesPassed: project.qualityGates ? project.qualityGates.length : 0,
3418
+ recommendation: qualityScore >= 0.8 ? "Ready for delivery" : qualityScore >= 0.6 ? "Needs minor improvements" : "Requires significant rework"
3419
+ };
3420
+ }
3421
+ /**
3422
+ * Prepare the final deliverables summary for the project.
3423
+ */
3424
+ prepareDeliverables(project) {
3425
+ const artifacts = [];
3426
+ for (const [taskId, task] of project.tasks) {
3427
+ const t = task;
3428
+ if (t.status === "completed" && t.result) {
3429
+ artifacts.push({
3430
+ taskId,
3431
+ taskName: t.name,
3432
+ type: t.type,
3433
+ result: t.result
3434
+ });
3435
+ }
3436
+ }
3437
+ return {
3438
+ projectId: project.id,
3439
+ projectName: project.name,
3440
+ deliveryDate: (/* @__PURE__ */ new Date()).toISOString(),
3441
+ artifacts,
3442
+ documentation: {
3443
+ readme: true,
3444
+ changelog: true,
3445
+ apiDocs: false
3446
+ },
3447
+ summary: {
3448
+ totalArtifacts: artifacts.length,
3449
+ totalTasks: project.tasks.size,
3450
+ completedTasks: artifacts.length,
3451
+ qualityScore: project.qualityScore || 0,
3452
+ duration: project.endDate ? project.endDate.getTime() - project.startDate.getTime() : Date.now() - project.startDate.getTime()
3453
+ }
3454
+ };
3455
+ }
3456
+ /**
3457
+ * Return a status snapshot for this agent.
3458
+ */
3459
+ getAgentStatus() {
3460
+ return {
3461
+ agentId: this.agentId,
3462
+ agentType: this.agentType,
3463
+ isActive: this.isActive,
3464
+ status: this.status,
3465
+ autonomyLevel: this.autonomyLevel,
3466
+ currentTask: this.currentTask,
3467
+ activeProjects: this.currentProjects.size,
3468
+ performanceMetrics: { ...this.performanceMetrics },
3469
+ teamSize: this.teamMembers.length,
3470
+ knowledgeBaseSize: this.knowledgeBase.size,
3471
+ skillLevels: Object.fromEntries(this.skillLevels),
3472
+ adaptationRate: this.adaptationRate,
3473
+ capabilities: { ...this.capabilities }
3474
+ };
3475
+ }
3476
+ /**
3477
+ * Generate a unique project identifier.
3478
+ */
3479
+ generateProjectId() {
3480
+ return `proj-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
3481
+ }
3482
+ };
3483
+ // Annotate the CommonJS export names for ESM import in node:
3484
+ 0 && (module.exports = {
3485
+ BaselineCommandSystem,
3486
+ MEGAGEMAutonomousAgent,
3487
+ MEGAGEMCoreSystem
3488
+ });