@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/cli.cjs ADDED
@@ -0,0 +1,2290 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/cli.ts
32
+ var cli_exports = {};
33
+ __export(cli_exports, {
34
+ buildCommandLine: () => buildCommandLine
35
+ });
36
+ module.exports = __toCommonJS(cli_exports);
37
+ var import_lang = require("@baselineos/lang");
38
+ var import_frame = require("@baselineos/frame");
39
+ var import_studio = require("@baselineos/studio");
40
+ var import_govern2 = require("@baselineos/govern");
41
+ var import_experience2 = require("@baselineos/experience");
42
+ var import_autonomy = require("@baselineos/autonomy");
43
+ var import_persona = require("@baselineos/persona");
44
+
45
+ // src/commands.ts
46
+ var import_experience = require("@baselineos/experience");
47
+ var import_govern = require("@baselineos/govern");
48
+ var import_promises = require("fs/promises");
49
+ var import_node_path = __toESM(require("path"), 1);
50
+ var BaselineCommandSystem = class {
51
+ state;
52
+ megagem;
53
+ contextEngine;
54
+ baselineLang;
55
+ constructor() {
56
+ this.state = {
57
+ customContextFolder: null,
58
+ baselineMode: false,
59
+ commandQueue: [],
60
+ executionHistory: [],
61
+ currentWorkflow: null
62
+ };
63
+ this.megagem = null;
64
+ this.contextEngine = null;
65
+ this.baselineLang = {
66
+ lexicon: this.initializeBaselineLexicon(),
67
+ syntax: this.initializeBaselineSyntax(),
68
+ commands: this.initializeBaselineCommands()
69
+ };
70
+ }
71
+ /**
72
+ * Initialize the Baseline lexicon with all recognized flags and their
73
+ * descriptions, usage patterns, categories, and examples.
74
+ */
75
+ initializeBaselineLexicon() {
76
+ return {
77
+ "--onboard": {
78
+ description: "Guided 20-minute onboarding flow to set up a team and run Baseline",
79
+ 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]",
80
+ category: "onboarding",
81
+ examples: [
82
+ '--onboard --team "Acme Corp" --project "AI Governance"',
83
+ '--onboard --name "Amani" --role "Platform Lead" --team "GTCX Protocol"',
84
+ "--onboard --language en --learning-style visual --pace fast --focus practical --learning-path standard",
85
+ "--onboard --context ./my-project --mode production",
86
+ "--onboard --skip-workflow",
87
+ "--onboard --fresh",
88
+ "--onboard --interactive"
89
+ ]
90
+ },
91
+ "--experience": {
92
+ description: "Run an immersive experience sequence based on learning path",
93
+ usage: "--experience [--learning-path <path>] [--experiences <id,id>] [--context <path>] [--fresh]",
94
+ category: "onboarding",
95
+ examples: [
96
+ "--experience --learning-path standard",
97
+ "--experience --learning-path accelerated",
98
+ "--experience --experiences welcome-journey,ai-collaboration",
99
+ "--experience --fresh"
100
+ ]
101
+ },
102
+ "--config": {
103
+ description: "Configure Baseline preferences and settings",
104
+ usage: "--config <section> [--set <value>] [--region <value>] [--standards <csv>] [--enable <csv>] [--context <path>]",
105
+ category: "setup",
106
+ examples: [
107
+ "--config show",
108
+ "--config language --set en",
109
+ "--config culture --region latin-america --business-style relationship-focused",
110
+ "--config compliance --region eu --standards gdpr,iso27001",
111
+ "--config accessibility --screen-reader --high-contrast"
112
+ ]
113
+ },
114
+ "--index": {
115
+ description: "Index docs or context for retrieval",
116
+ usage: "--index [--paths <csv>] [--context <path>] [--max <n>]",
117
+ category: "setup",
118
+ examples: ["--index", "--index --paths docs,README.md", "--index --max 500"]
119
+ },
120
+ "--serve": {
121
+ description: "Start the Baseline MCP server (stdio) and optional API server",
122
+ usage: "--serve [--api] [--port <n>] [--context <path>] [--once]",
123
+ category: "setup",
124
+ examples: ["--serve", "--serve --api --port 3141", "--serve --once"]
125
+ },
126
+ "--agents": {
127
+ description: "Show agent registry status",
128
+ usage: "--agents [--context <path>]",
129
+ category: "info",
130
+ examples: ["--agents", "--agents --context ./project"]
131
+ },
132
+ "--doctor": {
133
+ description: "Run diagnostics for Baseline configuration and readiness",
134
+ usage: "--doctor [--context <path>]",
135
+ category: "diagnostics",
136
+ examples: ["--doctor", "--doctor --context ./project"]
137
+ },
138
+ "--baseline": {
139
+ description: "Execute the full Baseline Protocol workflow across all layers",
140
+ usage: "--baseline [options]",
141
+ category: "core",
142
+ examples: [
143
+ "--baseline",
144
+ "--baseline --context ./my-project",
145
+ "--baseline --mode production"
146
+ ]
147
+ },
148
+ "--run": {
149
+ description: "Run the full Baseline workflow (alias for --baseline)",
150
+ usage: "--run [--context <path>] [--mode <mode>]",
151
+ category: "core",
152
+ examples: ["--run", "--run --context ./project --mode development"]
153
+ },
154
+ "--init": {
155
+ description: "Initialize Baseline and optionally write config",
156
+ usage: "--init [--context <path>] [--mode <mode>] [--write-config]",
157
+ category: "setup",
158
+ examples: ["--init", "--init --write-config", "--init --context ./project"]
159
+ },
160
+ "--baseline-lang": {
161
+ description: "Execute the Baseline language processing layer",
162
+ usage: "--baseline-lang [options]",
163
+ category: "layer",
164
+ examples: [
165
+ "--baseline-lang",
166
+ "--baseline-lang --parse",
167
+ "--baseline-lang --validate"
168
+ ]
169
+ },
170
+ "--baseline-frame": {
171
+ description: "Execute the Baseline framework orchestration layer",
172
+ usage: "--baseline-frame [options]",
173
+ category: "layer",
174
+ examples: [
175
+ "--baseline-frame",
176
+ "--baseline-frame --scaffold",
177
+ "--baseline-frame --compose"
178
+ ]
179
+ },
180
+ "--baseline-studio": {
181
+ description: "Execute the Baseline studio design and rendering layer",
182
+ usage: "--baseline-studio [options]",
183
+ category: "layer",
184
+ examples: [
185
+ "--baseline-studio",
186
+ "--baseline-studio --render",
187
+ "--baseline-studio --preview"
188
+ ]
189
+ },
190
+ "--baseline-govern": {
191
+ description: "Execute the Baseline governance and compliance layer",
192
+ usage: "--baseline-govern [options]",
193
+ category: "layer",
194
+ examples: [
195
+ "--baseline-govern",
196
+ "--baseline-govern --audit",
197
+ "--baseline-govern --policy"
198
+ ]
199
+ }
200
+ };
201
+ }
202
+ /**
203
+ * Initialize syntax patterns for the command system, defining parameter
204
+ * schemas and usage examples for each pattern.
205
+ */
206
+ initializeBaselineSyntax() {
207
+ return {
208
+ onboarding: {
209
+ 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]",
210
+ parameters: {
211
+ name: "Your name for onboarding personalization",
212
+ role: "Your role (optional)",
213
+ email: "Your email (optional)",
214
+ company: "Company name for the onboarding profile",
215
+ team: "Team name to onboard (optional)",
216
+ project: "Project name to initialize (optional)",
217
+ language: "Preferred language (en, es, fr, de, ja, zh, ko, ar, hi, pt)",
218
+ "learning-style": "Learning style (visual, auditory, kinesthetic, reading)",
219
+ pace: "Learning pace (slow, moderate, fast, lightning)",
220
+ focus: "Learning focus (practical, theoretical, mixed)",
221
+ "learning-path": "Learning path (standard, accelerated, hands-on, theoretical)",
222
+ context: "Path to the project context folder",
223
+ mode: "Execution mode: development | staging | production",
224
+ "skip-workflow": "Skip running the Baseline workflow after onboarding",
225
+ fresh: "Start onboarding from scratch and overwrite any saved profile",
226
+ interactive: "Prompt for onboarding inputs"
227
+ },
228
+ examples: [
229
+ '--onboard --team "Acme" --project "AI Governance"',
230
+ '--onboard --name "Amani" --role "Engineering" --company "GTCX Dev"',
231
+ "--onboard --language en --learning-style visual --learning-path standard",
232
+ "--onboard --context ./project --mode development",
233
+ "--onboard --skip-workflow",
234
+ "--onboard --fresh",
235
+ "--onboard --interactive"
236
+ ]
237
+ },
238
+ experience: {
239
+ pattern: "--experience [--learning-path <path>] [--experiences <id,id>] [--context <path>] [--fresh]",
240
+ parameters: {
241
+ "learning-path": "Learning path (standard, accelerated, hands-on, theoretical)",
242
+ experiences: "Comma-separated experience ids to run",
243
+ context: "Path to the project context folder",
244
+ fresh: "Reset onboarding profile before running experiences"
245
+ },
246
+ examples: [
247
+ "--experience --learning-path standard",
248
+ "--experience --learning-path accelerated",
249
+ "--experience --experiences welcome-journey,ai-collaboration",
250
+ "--experience --fresh"
251
+ ]
252
+ },
253
+ config: {
254
+ pattern: "--config <section> [--set <value>] [--region <value>] [--standards <csv>] [--enable <csv>] [--context <path>]",
255
+ parameters: {
256
+ section: "Config section: show | language | culture | compliance | accessibility",
257
+ set: "Set a value for a given section",
258
+ region: "Set a region for culture/compliance",
259
+ standards: "Comma-separated standards list for compliance",
260
+ enable: "Comma-separated accessibility features to enable",
261
+ context: "Path to the project context folder"
262
+ },
263
+ examples: [
264
+ "--config show",
265
+ "--config language --set en",
266
+ "--config culture --region latin-america --business-style relationship-focused",
267
+ "--config compliance --region eu --standards gdpr,iso27001",
268
+ "--config accessibility --screen-reader --high-contrast"
269
+ ]
270
+ },
271
+ index: {
272
+ pattern: "--index [--paths <csv>] [--context <path>] [--max <n>]",
273
+ parameters: {
274
+ paths: "Comma-separated list of paths to index",
275
+ context: "Context path to resolve relative paths",
276
+ max: "Maximum number of entries to index"
277
+ },
278
+ examples: ["--index", "--index --paths docs,README.md", "--index --max 500"]
279
+ },
280
+ serve: {
281
+ pattern: "--serve [--api] [--port <n>] [--context <path>] [--once]",
282
+ parameters: {
283
+ api: "Start the HTTP/WebSocket API server alongside MCP",
284
+ port: "Port for the API server (default: 3141)",
285
+ context: "Path to the project context folder",
286
+ once: "Start then return immediately (for scripting)"
287
+ },
288
+ examples: ["--serve", "--serve --api --port 3141", "--serve --once"]
289
+ },
290
+ agents: {
291
+ pattern: "--agents [--context <path>]",
292
+ parameters: {
293
+ context: "Path to the project context folder"
294
+ },
295
+ examples: ["--agents", "--agents --context ./project"]
296
+ },
297
+ doctor: {
298
+ pattern: "--doctor [--context <path>]",
299
+ parameters: {
300
+ context: "Path to the project context folder"
301
+ },
302
+ examples: ["--doctor", "--doctor --context ./project"]
303
+ },
304
+ workflow: {
305
+ pattern: "--baseline [--context <path>] [--mode <mode>] [--verbose]",
306
+ parameters: {
307
+ context: "Path to the project context folder",
308
+ mode: "Execution mode: development | staging | production",
309
+ verbose: "Enable verbose logging output"
310
+ },
311
+ examples: [
312
+ "--baseline --context ./project --mode development",
313
+ "--baseline --mode production --verbose"
314
+ ]
315
+ },
316
+ run: {
317
+ pattern: "--run [--context <path>] [--mode <mode>]",
318
+ parameters: {
319
+ context: "Path to the project context folder",
320
+ mode: "Execution mode: development | staging | production"
321
+ },
322
+ examples: ["--run", "--run --context ./project --mode development"]
323
+ },
324
+ init: {
325
+ pattern: "--init [--context <path>] [--mode <mode>] [--write-config]",
326
+ parameters: {
327
+ context: "Path to the project context folder",
328
+ mode: "Execution mode: development | staging | production",
329
+ "write-config": "Persist baseline.config.json into .baseline/"
330
+ },
331
+ examples: ["--init --write-config", "--init --context ./project"]
332
+ },
333
+ layer: {
334
+ pattern: "--baseline-<layer> [--input <path>] [--output <path>] [--config <path>]",
335
+ parameters: {
336
+ layer: "Target layer: lang | frame | studio | govern",
337
+ input: "Input file or directory path",
338
+ output: "Output file or directory path",
339
+ config: "Layer-specific configuration file path"
340
+ },
341
+ examples: [
342
+ "--baseline-lang --input ./src --output ./dist",
343
+ "--baseline-frame --config ./baseline.config.json"
344
+ ]
345
+ },
346
+ chain: {
347
+ pattern: '--baseline-chain "<cmd1> | <cmd2> | <cmd3>"',
348
+ parameters: {
349
+ commands: "Pipe-delimited list of commands to execute sequentially"
350
+ },
351
+ examples: [
352
+ '--baseline-chain "--baseline-lang | --baseline-frame | --baseline-studio"',
353
+ '--baseline-chain "--init | --baseline"'
354
+ ]
355
+ },
356
+ queue: {
357
+ pattern: "--baseline-queue <add|run|clear|status>",
358
+ parameters: {
359
+ action: "Queue action to perform",
360
+ command: "Command to add (when using add)"
361
+ },
362
+ examples: [
363
+ "--baseline-queue add --baseline-lang",
364
+ "--baseline-queue run",
365
+ "--baseline-queue status"
366
+ ]
367
+ }
368
+ };
369
+ }
370
+ /**
371
+ * Initialize the built-in command registry with descriptions and action
372
+ * identifiers for each recognized command.
373
+ */
374
+ initializeBaselineCommands() {
375
+ return {
376
+ "--onboard": {
377
+ description: "Run a guided onboarding flow (team, project, system, workflow)",
378
+ action: "onboard",
379
+ category: "onboarding"
380
+ },
381
+ "--experience": {
382
+ description: "Run an immersive experience sequence based on learning path",
383
+ action: "experience",
384
+ category: "onboarding"
385
+ },
386
+ "--config": {
387
+ description: "Configure Baseline preferences and settings",
388
+ action: "config",
389
+ category: "setup"
390
+ },
391
+ "--index": {
392
+ description: "Index docs or context for retrieval",
393
+ action: "index",
394
+ category: "setup"
395
+ },
396
+ "--serve": {
397
+ description: "Start the Baseline server or MCP daemon (placeholder)",
398
+ action: "serve",
399
+ category: "setup"
400
+ },
401
+ "--persona": {
402
+ description: "Show persona status and available roles",
403
+ action: "persona",
404
+ category: "info"
405
+ },
406
+ "--agents": {
407
+ description: "Show agent registry status (placeholder)",
408
+ action: "agents",
409
+ category: "info"
410
+ },
411
+ "--doctor": {
412
+ description: "Run diagnostics for Baseline configuration and readiness",
413
+ action: "doctor",
414
+ category: "diagnostics"
415
+ },
416
+ "--init": {
417
+ description: "Initialize a new Baseline project in the current directory",
418
+ action: "initialize",
419
+ category: "setup"
420
+ },
421
+ "--run": {
422
+ description: "Run the full Baseline workflow with default settings",
423
+ action: "run",
424
+ category: "execution"
425
+ },
426
+ "--status": {
427
+ description: "Display the current status of the Baseline system and active workflows",
428
+ action: "status",
429
+ category: "info"
430
+ },
431
+ "--help": {
432
+ description: "Display help information for all available commands",
433
+ action: "help",
434
+ category: "info"
435
+ }
436
+ };
437
+ }
438
+ /**
439
+ * Execute the full Baseline Protocol workflow across all five layers:
440
+ * init -> lang -> frame -> studio -> govern
441
+ */
442
+ async executeBaselineWorkflow(options = {}) {
443
+ const workflowId = `wf-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
444
+ const workflow = {
445
+ id: workflowId,
446
+ startTime: /* @__PURE__ */ new Date(),
447
+ options,
448
+ status: "running"
449
+ };
450
+ this.state.currentWorkflow = workflow;
451
+ this.state.baselineMode = true;
452
+ console.log(`[Baseline] Starting workflow ${workflowId}`);
453
+ console.log(`[Baseline] Options: ${JSON.stringify(options)}`);
454
+ try {
455
+ console.log("[Baseline] Step 1/5: Initializing baseline environment...");
456
+ const initResult = await this.initializeBaseline(options);
457
+ if (!initResult.success) {
458
+ throw new Error(`Initialization failed: ${initResult.error || "unknown error"}`);
459
+ }
460
+ console.log("[Baseline] Step 1/5: Initialization complete.");
461
+ console.log("[Baseline] Step 2/5: Processing language layer...");
462
+ const langResult = await this.executeBaselineLang(options);
463
+ if (!langResult.success) {
464
+ throw new Error(`Language layer failed: ${langResult.error || "unknown error"}`);
465
+ }
466
+ console.log("[Baseline] Step 2/5: Language layer complete.");
467
+ console.log("[Baseline] Step 3/5: Processing frame layer...");
468
+ const frameResult = await this.executeBaselineFrame(options);
469
+ if (!frameResult.success) {
470
+ throw new Error(`Frame layer failed: ${frameResult.error || "unknown error"}`);
471
+ }
472
+ console.log("[Baseline] Step 3/5: Frame layer complete.");
473
+ console.log("[Baseline] Step 4/5: Processing studio layer...");
474
+ const studioResult = await this.executeBaselineStudio(options);
475
+ if (!studioResult.success) {
476
+ throw new Error(`Studio layer failed: ${studioResult.error || "unknown error"}`);
477
+ }
478
+ console.log("[Baseline] Step 4/5: Studio layer complete.");
479
+ console.log("[Baseline] Step 5/5: Processing governance layer...");
480
+ const governResult = await this.executeBaselineGovern(options);
481
+ if (!governResult.success) {
482
+ throw new Error(`Governance layer failed: ${governResult.error || "unknown error"}`);
483
+ }
484
+ console.log("[Baseline] Step 5/5: Governance layer complete.");
485
+ workflow.endTime = /* @__PURE__ */ new Date();
486
+ workflow.duration = workflow.endTime.getTime() - workflow.startTime.getTime();
487
+ workflow.status = "completed";
488
+ this.state.executionHistory.push(workflow);
489
+ this.state.currentWorkflow = null;
490
+ console.log(`[Baseline] Workflow ${workflowId} completed in ${workflow.duration}ms`);
491
+ return {
492
+ success: true,
493
+ workflow,
494
+ results: {
495
+ init: initResult,
496
+ lang: langResult,
497
+ frame: frameResult,
498
+ studio: studioResult,
499
+ govern: governResult
500
+ }
501
+ };
502
+ } catch (error) {
503
+ const errorMessage = error instanceof Error ? error.message : String(error);
504
+ workflow.endTime = /* @__PURE__ */ new Date();
505
+ workflow.duration = workflow.endTime.getTime() - workflow.startTime.getTime();
506
+ workflow.status = "failed";
507
+ workflow.error = errorMessage;
508
+ this.state.executionHistory.push(workflow);
509
+ this.state.currentWorkflow = null;
510
+ console.log(`[Baseline] Workflow ${workflowId} failed: ${errorMessage}`);
511
+ return {
512
+ success: false,
513
+ error: errorMessage,
514
+ workflow
515
+ };
516
+ }
517
+ }
518
+ normalizeString(value) {
519
+ if (typeof value === "string") {
520
+ const trimmed = value.trim();
521
+ return trimmed.length ? trimmed : void 0;
522
+ }
523
+ if (value === null || value === void 0) {
524
+ return void 0;
525
+ }
526
+ const text = String(value).trim();
527
+ return text.length ? text : void 0;
528
+ }
529
+ normalizeBoolean(value) {
530
+ if (typeof value === "boolean") return value;
531
+ if (typeof value === "string") {
532
+ return ["true", "1", "yes", "y"].includes(value.toLowerCase());
533
+ }
534
+ return false;
535
+ }
536
+ resolveContext(value, fallback) {
537
+ const resolved = this.normalizeString(value) || fallback || process.cwd();
538
+ return import_node_path.default.resolve(resolved);
539
+ }
540
+ async loadOnboardingProfile(context) {
541
+ const directory = import_node_path.default.join(context, ".baseline");
542
+ const filePath = import_node_path.default.join(directory, "onboarding.json");
543
+ try {
544
+ const raw = await (0, import_promises.readFile)(filePath, "utf8");
545
+ const parsed = JSON.parse(raw);
546
+ return { path: filePath, profile: parsed, exists: true };
547
+ } catch (err) {
548
+ const error = err;
549
+ if (error.code === "ENOENT") {
550
+ return { path: filePath, profile: null, exists: false };
551
+ }
552
+ return { path: filePath, profile: null, exists: false, error: error.message };
553
+ }
554
+ }
555
+ async saveOnboardingProfile(filePath, profile) {
556
+ await (0, import_promises.mkdir)(import_node_path.default.dirname(filePath), { recursive: true });
557
+ await (0, import_promises.writeFile)(filePath, JSON.stringify(profile, null, 2), "utf8");
558
+ }
559
+ async loadBaselineConfig(context) {
560
+ const directory = import_node_path.default.join(context, ".baseline");
561
+ const filePath = import_node_path.default.join(directory, "baseline.config.json");
562
+ try {
563
+ const raw = await (0, import_promises.readFile)(filePath, "utf8");
564
+ const parsed = JSON.parse(raw);
565
+ return { path: filePath, config: parsed, exists: true };
566
+ } catch (err) {
567
+ const error = err;
568
+ if (error.code === "ENOENT") {
569
+ return { path: filePath, config: null, exists: false };
570
+ }
571
+ return { path: filePath, config: null, exists: false, error: error.message };
572
+ }
573
+ }
574
+ async saveBaselineConfig(filePath, config) {
575
+ await (0, import_promises.mkdir)(import_node_path.default.dirname(filePath), { recursive: true });
576
+ await (0, import_promises.writeFile)(filePath, JSON.stringify(config, null, 2), "utf8");
577
+ }
578
+ async fileExists(filePath) {
579
+ try {
580
+ const result = await (0, import_promises.stat)(filePath);
581
+ return result.isFile() || result.isDirectory();
582
+ } catch {
583
+ return false;
584
+ }
585
+ }
586
+ buildDefaultConfig(context, profile) {
587
+ const now = (/* @__PURE__ */ new Date()).toISOString();
588
+ return {
589
+ version: 1,
590
+ context,
591
+ createdAt: now,
592
+ updatedAt: now,
593
+ language: profile?.preferences?.language || "en",
594
+ preferences: {
595
+ learningStyle: profile?.preferences?.learningStyle,
596
+ pace: profile?.preferences?.pace,
597
+ focus: profile?.preferences?.focus,
598
+ learningPath: profile?.preferences?.learningPath
599
+ },
600
+ culture: {},
601
+ compliance: {},
602
+ accessibility: {}
603
+ };
604
+ }
605
+ getExperienceCatalog() {
606
+ return {
607
+ "welcome-journey": {
608
+ id: "welcome-journey",
609
+ name: "Welcome Journey",
610
+ description: "Interactive introduction to Baseline and AI-native development.",
611
+ duration: "5-10 minutes",
612
+ difficulty: "beginner",
613
+ type: "story",
614
+ tags: ["onboarding", "introduction", "story"]
615
+ },
616
+ "acceleration-discovery": {
617
+ id: "acceleration-discovery",
618
+ name: "Acceleration Discovery",
619
+ description: "Experience the jump from 300x to 1,000,000x acceleration.",
620
+ duration: "10-15 minutes",
621
+ difficulty: "beginner",
622
+ type: "interactive",
623
+ tags: ["acceleration", "demo", "interactive"]
624
+ },
625
+ "ai-collaboration": {
626
+ id: "ai-collaboration",
627
+ name: "AI Collaboration Workshop",
628
+ description: "Learn to coordinate with autonomous AI systems.",
629
+ duration: "15-20 minutes",
630
+ difficulty: "intermediate",
631
+ type: "workshop",
632
+ tags: ["workshop", "ai", "collaboration"]
633
+ },
634
+ "quantum-leap": {
635
+ id: "quantum-leap",
636
+ name: "Quantum Leap Challenge",
637
+ description: "Tackle advanced challenges with quantum-level acceleration.",
638
+ duration: "20-30 minutes",
639
+ difficulty: "advanced",
640
+ type: "challenge",
641
+ tags: ["challenge", "quantum", "advanced"]
642
+ },
643
+ "singularity-mastery": {
644
+ id: "singularity-mastery",
645
+ name: "Singularity Mastery",
646
+ description: "Master the highest tiers of AI-native execution.",
647
+ duration: "30-45 minutes",
648
+ difficulty: "expert",
649
+ type: "mastery",
650
+ tags: ["mastery", "singularity", "expert"]
651
+ },
652
+ "concept-exploration": {
653
+ id: "concept-exploration",
654
+ name: "Concept Exploration",
655
+ description: "Deep dive into AI-native development concepts.",
656
+ duration: "15-20 minutes",
657
+ difficulty: "intermediate",
658
+ type: "theoretical",
659
+ tags: ["theoretical", "concepts", "learning"]
660
+ },
661
+ "theory-workshop": {
662
+ id: "theory-workshop",
663
+ name: "Theory Workshop",
664
+ description: "Explore the principles behind Baseline OS.",
665
+ duration: "25-35 minutes",
666
+ difficulty: "advanced",
667
+ type: "workshop",
668
+ tags: ["workshop", "theory", "principles"]
669
+ },
670
+ "advanced-concepts": {
671
+ id: "advanced-concepts",
672
+ name: "Advanced Concepts",
673
+ description: "Master advanced AI-native concepts and patterns.",
674
+ duration: "30-40 minutes",
675
+ difficulty: "expert",
676
+ type: "theoretical",
677
+ tags: ["theoretical", "advanced", "mastery"]
678
+ },
679
+ "workshop-series": {
680
+ id: "workshop-series",
681
+ name: "Workshop Series",
682
+ description: "Hands-on applied learning series.",
683
+ duration: "45-60 minutes",
684
+ difficulty: "intermediate",
685
+ type: "workshop",
686
+ tags: ["workshop", "series", "hands-on"]
687
+ }
688
+ };
689
+ }
690
+ getLearningPaths() {
691
+ return {
692
+ standard: {
693
+ name: "Standard Path",
694
+ experiences: ["welcome-journey", "acceleration-discovery", "ai-collaboration"]
695
+ },
696
+ accelerated: {
697
+ name: "Accelerated Path",
698
+ experiences: ["acceleration-discovery", "quantum-leap", "singularity-mastery"]
699
+ },
700
+ "hands-on": {
701
+ name: "Hands-On Path",
702
+ experiences: ["ai-collaboration", "quantum-leap", "workshop-series"]
703
+ },
704
+ theoretical: {
705
+ name: "Theoretical Path",
706
+ experiences: ["concept-exploration", "theory-workshop", "advanced-concepts"]
707
+ }
708
+ };
709
+ }
710
+ /**
711
+ * Execute a guided onboarding flow (team, project, system) and optionally
712
+ * run the full Baseline workflow. Designed for a 20-minute quickstart.
713
+ */
714
+ async executeOnboarding(options = {}) {
715
+ const startedAt = Date.now();
716
+ const context = this.resolveContext(options.context, process.cwd());
717
+ const forceFresh = this.normalizeBoolean(options.fresh) || this.normalizeBoolean(options.reset);
718
+ const existingProfile = forceFresh ? null : await this.loadOnboardingProfile(context);
719
+ const prior = existingProfile?.profile ?? null;
720
+ const name = this.normalizeString(options.name) || prior?.user?.name || "User";
721
+ const role = this.normalizeString(options.role) || prior?.user?.role || "Operator";
722
+ const email = this.normalizeString(options.email) || prior?.user?.email;
723
+ const company = this.normalizeString(options.company) || prior?.company || "Acme Corp";
724
+ const team = this.normalizeString(options.team) || prior?.team;
725
+ const project = this.normalizeString(options.project) || prior?.project;
726
+ const mode = this.normalizeString(options.mode) || prior?.mode || "development";
727
+ const language = this.normalizeString(options.language) || prior?.preferences?.language || "en";
728
+ const learningStyle = this.normalizeString(options["learning-style"]) || prior?.preferences?.learningStyle || "visual";
729
+ const pace = this.normalizeString(options.pace) || prior?.preferences?.pace || "moderate";
730
+ const focus = this.normalizeString(options.focus) || prior?.preferences?.focus || "practical";
731
+ const learningPath = this.normalizeString(options["learning-path"]) || prior?.preferences?.learningPath || "standard";
732
+ const skipWorkflow = this.normalizeBoolean(options["skip-workflow"]);
733
+ console.log("[Baseline:Onboarding] Starting 20-minute onboarding flow");
734
+ console.log(`[Baseline:Onboarding] Welcome: ${name} (${role})`);
735
+ console.log(`[Baseline:Onboarding] Language: ${language}`);
736
+ console.log(
737
+ `[Baseline:Onboarding] Learning path: ${learningPath} (${learningStyle}, ${pace}, ${focus})`
738
+ );
739
+ if (team) {
740
+ console.log(`[Baseline:Onboarding] Team: ${team}`);
741
+ }
742
+ console.log(`[Baseline:Onboarding] Company: ${company}`);
743
+ if (project) {
744
+ console.log(`[Baseline:Onboarding] Project: ${project}`);
745
+ }
746
+ console.log(`[Baseline:Onboarding] Context: ${context}`);
747
+ console.log(`[Baseline:Onboarding] Mode: ${mode}`);
748
+ if (existingProfile?.exists && !forceFresh) {
749
+ console.log("[Baseline:Onboarding] Resuming from saved onboarding profile");
750
+ }
751
+ if (skipWorkflow) {
752
+ console.log("[Baseline:Onboarding] Workflow execution skipped by flag");
753
+ }
754
+ const experience = new import_experience.BaselineExperienceSystem();
755
+ const systemResult = await experience.onboarding.system.initialize();
756
+ const systemId = systemResult.systemId || `system-${Date.now()}`;
757
+ const systemConfig = await experience.onboarding.system.configure(systemId, {
758
+ user: { name, role, email },
759
+ company,
760
+ team,
761
+ project,
762
+ context,
763
+ mode,
764
+ preferences: { language, learningStyle, pace, focus, learningPath }
765
+ });
766
+ let teamResult;
767
+ let teamConfig;
768
+ let teamId;
769
+ if (team) {
770
+ teamResult = await experience.onboarding.team.start(company);
771
+ teamId = teamResult.teamId ?? `team-${Date.now()}`;
772
+ teamConfig = await experience.onboarding.team.configure(teamId, {
773
+ user: { name, role, email },
774
+ team,
775
+ company,
776
+ mode
777
+ });
778
+ } else {
779
+ teamResult = { success: true, skipped: true, reason: "team not provided" };
780
+ teamConfig = { success: true, skipped: true, reason: "team not provided" };
781
+ }
782
+ let projectResult;
783
+ let projectConfig;
784
+ let projectId;
785
+ if (project) {
786
+ projectResult = await experience.onboarding.project.setup(project);
787
+ projectId = projectResult.projectId ?? `project-${Date.now()}`;
788
+ projectConfig = await experience.onboarding.project.configure(projectId, {
789
+ teamId,
790
+ context
791
+ });
792
+ } else {
793
+ projectResult = { success: true, skipped: true, reason: "project not provided" };
794
+ projectConfig = { success: true, skipped: true, reason: "project not provided" };
795
+ }
796
+ let workflow = null;
797
+ if (!skipWorkflow) {
798
+ workflow = await this.executeBaselineWorkflow({ context, mode });
799
+ }
800
+ const now = (/* @__PURE__ */ new Date()).toISOString();
801
+ const completedSteps = ["identity", "preferences", "workspace"];
802
+ if (!skipWorkflow) {
803
+ completedSteps.push("workflow");
804
+ }
805
+ const profile = {
806
+ version: 2,
807
+ createdAt: prior?.createdAt || now,
808
+ updatedAt: now,
809
+ user: { name, role, ...email ? { email } : {} },
810
+ company,
811
+ ...team ? { team } : {},
812
+ ...project ? { project } : {},
813
+ context,
814
+ mode,
815
+ preferences: { language, learningStyle, pace, focus, learningPath },
816
+ progress: {
817
+ completedSteps,
818
+ lastStep: completedSteps[completedSteps.length - 1],
819
+ lastCompletedAt: now
820
+ },
821
+ experiences: prior?.experiences ?? { completed: [] },
822
+ ...workflow?.workflow?.id ? { workflow: { lastRunAt: now, lastWorkflowId: workflow.workflow.id } } : {}
823
+ };
824
+ const storage = existingProfile ?? {
825
+ path: import_node_path.default.join(context, ".baseline", "onboarding.json"),
826
+ exists: false,
827
+ profile: null
828
+ };
829
+ let storageSaved = false;
830
+ let storageError;
831
+ try {
832
+ await this.saveOnboardingProfile(storage.path, profile);
833
+ storageSaved = true;
834
+ } catch (err) {
835
+ storageError = err instanceof Error ? err.message : String(err);
836
+ console.log(`[Baseline:Onboarding] Failed to save profile: ${storageError}`);
837
+ }
838
+ const success = systemResult.success && systemConfig.success && teamResult.success && teamConfig.success && projectResult.success && projectConfig.success && (workflow ? workflow.success : true);
839
+ return {
840
+ success,
841
+ onboarding: {
842
+ system: systemResult,
843
+ systemConfig,
844
+ user: { name, role, email },
845
+ preferences: { language, learningStyle, pace, focus, learningPath },
846
+ profile,
847
+ storage: {
848
+ path: storage.path,
849
+ saved: storageSaved,
850
+ error: storageError
851
+ },
852
+ team: teamResult,
853
+ teamConfig,
854
+ project: projectResult,
855
+ projectConfig
856
+ },
857
+ workflow,
858
+ nextSteps: [
859
+ "Run `baseline status` to verify layer status.",
860
+ "Run `baseline --baseline` to execute the full workflow.",
861
+ "Follow docs/experience/baseline-20-min-onboarding.md for mastery path."
862
+ ],
863
+ durationMs: Date.now() - startedAt
864
+ };
865
+ }
866
+ /**
867
+ * Execute an immersive experience sequence based on the selected learning path.
868
+ * Uses onboarding profile data and persists progress.
869
+ */
870
+ async executeExperience(options = {}) {
871
+ const context = this.resolveContext(options.context, process.cwd());
872
+ const forceFresh = this.normalizeBoolean(options.fresh) || this.normalizeBoolean(options.reset);
873
+ const storage = forceFresh ? null : await this.loadOnboardingProfile(context);
874
+ let profile = storage?.profile ?? null;
875
+ if (!profile) {
876
+ console.log("[Baseline:Experience] No onboarding profile found. Bootstrapping profile...");
877
+ const onboardingResult = await this.executeOnboarding({
878
+ ...options,
879
+ context,
880
+ "skip-workflow": true,
881
+ fresh: forceFresh
882
+ });
883
+ profile = onboardingResult.onboarding?.profile ?? null;
884
+ }
885
+ if (!profile) {
886
+ return { success: false, error: "Unable to load or create onboarding profile." };
887
+ }
888
+ const catalog = this.getExperienceCatalog();
889
+ const paths = this.getLearningPaths();
890
+ const learningPath = this.normalizeString(options["learning-path"]) || profile.preferences.learningPath || "standard";
891
+ const explicitList = this.normalizeString(options.experiences);
892
+ const requested = explicitList ? explicitList.split(",").map((entry) => entry.trim()).filter((entry) => entry.length) : paths[learningPath]?.experiences || paths.standard.experiences;
893
+ const experiences = requested.filter((id) => !!catalog[id]);
894
+ if (experiences.length === 0) {
895
+ return {
896
+ success: false,
897
+ error: "No valid experiences found. Provide --learning-path or --experiences."
898
+ };
899
+ }
900
+ console.log("[Baseline:Experience] Starting experience sequence");
901
+ console.log(`[Baseline:Experience] Path: ${learningPath}`);
902
+ experiences.forEach((experienceId, index) => {
903
+ const experience = catalog[experienceId];
904
+ console.log(
905
+ `[Baseline:Experience] ${index + 1}/${experiences.length}: ${experience.name} (${experience.duration})`
906
+ );
907
+ console.log(` ${experience.description}`);
908
+ });
909
+ const now = (/* @__PURE__ */ new Date()).toISOString();
910
+ const completed = Array.from(
911
+ /* @__PURE__ */ new Set([...profile.experiences?.completed ?? [], ...experiences])
912
+ );
913
+ const updatedProfile = {
914
+ ...profile,
915
+ updatedAt: now,
916
+ preferences: {
917
+ ...profile.preferences,
918
+ learningPath
919
+ },
920
+ experiences: {
921
+ completed,
922
+ lastExperience: experiences[experiences.length - 1],
923
+ lastCompletedAt: now
924
+ }
925
+ };
926
+ const targetPath = storage?.path ?? import_node_path.default.join(context, ".baseline", "onboarding.json");
927
+ let storageSaved = false;
928
+ let storageError;
929
+ try {
930
+ await this.saveOnboardingProfile(targetPath, updatedProfile);
931
+ storageSaved = true;
932
+ } catch (err) {
933
+ storageError = err instanceof Error ? err.message : String(err);
934
+ console.log(`[Baseline:Experience] Failed to save profile: ${storageError}`);
935
+ }
936
+ return {
937
+ success: true,
938
+ experience: {
939
+ path: learningPath,
940
+ experiences: experiences.map((id) => catalog[id]),
941
+ completed
942
+ },
943
+ profile: updatedProfile,
944
+ storage: {
945
+ path: targetPath,
946
+ saved: storageSaved,
947
+ error: storageError
948
+ }
949
+ };
950
+ }
951
+ /**
952
+ * Initialize Baseline and optionally persist config to disk.
953
+ */
954
+ async executeInit(options = {}) {
955
+ const context = this.resolveContext(options.context, process.cwd());
956
+ const mode = this.normalizeString(options.mode) || "development";
957
+ const writeConfig = this.normalizeBoolean(options["write-config"]) || this.normalizeBoolean(options.persist) || this.normalizeBoolean(options.write);
958
+ const initResult = await this.initializeBaseline({ context, mode });
959
+ if (!initResult.success) {
960
+ return initResult;
961
+ }
962
+ if (!writeConfig) {
963
+ return {
964
+ ...initResult,
965
+ message: "Initialization complete (config not written). Use --write-config to persist."
966
+ };
967
+ }
968
+ const profile = await this.loadOnboardingProfile(context);
969
+ const configRecord = await this.loadBaselineConfig(context);
970
+ const now = (/* @__PURE__ */ new Date()).toISOString();
971
+ const config = {
972
+ ...configRecord.config ?? this.buildDefaultConfig(context, profile.profile),
973
+ context,
974
+ updatedAt: now
975
+ };
976
+ await this.saveBaselineConfig(configRecord.path, config);
977
+ return {
978
+ ...initResult,
979
+ config,
980
+ configPath: configRecord.path,
981
+ message: "Initialization complete and config written."
982
+ };
983
+ }
984
+ /**
985
+ * Update or show Baseline configuration.
986
+ */
987
+ async executeConfig(options = {}) {
988
+ const context = this.resolveContext(options.context, process.cwd());
989
+ const positional = Array.isArray(options._) && options._.length ? options._ : [];
990
+ const section = this.normalizeString(options.config) || this.normalizeString(options.section) || (positional.length ? this.normalizeString(positional[0]) : void 0) || "show";
991
+ const showOnly = this.normalizeBoolean(options.show) || section === "show" || !options.set && !options.region && !options.standards && !options.enable;
992
+ const onboarding = await this.loadOnboardingProfile(context);
993
+ const existing = await this.loadBaselineConfig(context);
994
+ const now = (/* @__PURE__ */ new Date()).toISOString();
995
+ const config = existing.config ?? this.buildDefaultConfig(context, onboarding.profile);
996
+ if (showOnly) {
997
+ return {
998
+ success: true,
999
+ config,
1000
+ configPath: existing.path
1001
+ };
1002
+ }
1003
+ if (section === "language") {
1004
+ const value = this.normalizeString(options.set);
1005
+ if (!value) {
1006
+ return { success: false, error: "Missing --set <language-code>" };
1007
+ }
1008
+ config.language = value;
1009
+ if (onboarding.profile) {
1010
+ onboarding.profile.preferences.language = value;
1011
+ onboarding.profile.updatedAt = now;
1012
+ await this.saveOnboardingProfile(onboarding.path, onboarding.profile);
1013
+ }
1014
+ } else if (section === "culture") {
1015
+ const region = this.normalizeString(options.region);
1016
+ const businessStyle = this.normalizeString(options["business-style"]) || this.normalizeString(options.business);
1017
+ config.culture = {
1018
+ ...config.culture,
1019
+ ...region ? { region } : {},
1020
+ ...businessStyle ? { businessStyle } : {}
1021
+ };
1022
+ } else if (section === "compliance") {
1023
+ const region = this.normalizeString(options.region);
1024
+ const standardsRaw = this.normalizeString(options.standards);
1025
+ const standards = standardsRaw ? standardsRaw.split(",").map((entry) => entry.trim()).filter(Boolean) : void 0;
1026
+ config.compliance = {
1027
+ ...config.compliance,
1028
+ ...region ? { region } : {},
1029
+ ...standards ? { standards } : {}
1030
+ };
1031
+ } else if (section === "accessibility") {
1032
+ const enabledRaw = this.normalizeString(options.enable);
1033
+ const enabled = enabledRaw ? enabledRaw.split(",").map((entry) => entry.trim()).filter(Boolean) : [];
1034
+ config.accessibility = {
1035
+ ...config.accessibility,
1036
+ ...enabled.length ? { enabled } : {},
1037
+ ...this.normalizeBoolean(options["screen-reader"]) ? { screenReader: true } : {},
1038
+ ...this.normalizeBoolean(options["high-contrast"]) ? { highContrast: true } : {},
1039
+ ...this.normalizeBoolean(options["voice-control"]) ? { voiceControl: true } : {}
1040
+ };
1041
+ } else {
1042
+ return { success: false, error: `Unknown config section: ${section}` };
1043
+ }
1044
+ config.updatedAt = now;
1045
+ await this.saveBaselineConfig(existing.path, config);
1046
+ return {
1047
+ success: true,
1048
+ config,
1049
+ configPath: existing.path
1050
+ };
1051
+ }
1052
+ async collectIndexEntries(root, maxEntries) {
1053
+ const entries = [];
1054
+ const queue = [root];
1055
+ const ignore = /* @__PURE__ */ new Set([".git", "node_modules", ".baseline", "dist", ".next", "build"]);
1056
+ while (queue.length && entries.length < maxEntries) {
1057
+ const current = queue.shift();
1058
+ if (!current) continue;
1059
+ let currentStat;
1060
+ try {
1061
+ currentStat = await (0, import_promises.stat)(current);
1062
+ } catch {
1063
+ continue;
1064
+ }
1065
+ if (currentStat.isFile()) {
1066
+ entries.push(current);
1067
+ continue;
1068
+ }
1069
+ if (!currentStat.isDirectory()) continue;
1070
+ const name = import_node_path.default.basename(current);
1071
+ if (ignore.has(name)) continue;
1072
+ let children = [];
1073
+ try {
1074
+ children = await (0, import_promises.readdir)(current);
1075
+ } catch {
1076
+ continue;
1077
+ }
1078
+ for (const child of children) {
1079
+ if (entries.length >= maxEntries) break;
1080
+ queue.push(import_node_path.default.join(current, child));
1081
+ }
1082
+ }
1083
+ return entries;
1084
+ }
1085
+ /**
1086
+ * Index documentation/context files for retrieval.
1087
+ */
1088
+ async executeIndex(options = {}) {
1089
+ const context = this.resolveContext(options.context, process.cwd());
1090
+ const positional = Array.isArray(options._) && options._.length ? options._ : [];
1091
+ const pathsRaw = this.normalizeString(options.paths) || this.normalizeString(options.path) || (positional.length ? positional.join(",") : void 0);
1092
+ const defaultCandidates = ["docs", "README.md"].map((entry) => import_node_path.default.join(context, entry)).filter((entry) => entry !== "");
1093
+ const targets = pathsRaw ? pathsRaw.split(",").map((entry) => entry.trim()).filter(Boolean).map((entry) => import_node_path.default.resolve(context, entry)) : defaultCandidates;
1094
+ const maxEntries = Number(options.max) > 0 ? Number(options.max) : 2e3;
1095
+ console.log(`[Baseline:Index] Scanning ${targets.length} target(s) in ${context}`);
1096
+ const files = [];
1097
+ for (const target of targets) {
1098
+ const before = files.length;
1099
+ const collected = await this.collectIndexEntries(target, maxEntries - files.length);
1100
+ files.push(...collected);
1101
+ const added = files.length - before;
1102
+ if (added > 0) console.log(`[Baseline:Index] ${import_node_path.default.relative(context, target) || target} \u2192 ${added} file(s)`);
1103
+ if (files.length >= maxEntries) break;
1104
+ }
1105
+ console.log(`[Baseline:Index] Total: ${files.length} document(s) indexed`);
1106
+ const index = files.map((filePath) => ({
1107
+ path: filePath,
1108
+ relativePath: import_node_path.default.relative(context, filePath)
1109
+ }));
1110
+ const indexPath = import_node_path.default.join(context, ".baseline", "index.json");
1111
+ await (0, import_promises.mkdir)(import_node_path.default.dirname(indexPath), { recursive: true });
1112
+ await (0, import_promises.writeFile)(
1113
+ indexPath,
1114
+ JSON.stringify(
1115
+ {
1116
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1117
+ context,
1118
+ total: index.length,
1119
+ entries: index
1120
+ },
1121
+ null,
1122
+ 2
1123
+ ),
1124
+ "utf8"
1125
+ );
1126
+ return {
1127
+ success: true,
1128
+ indexed: index.length,
1129
+ indexPath,
1130
+ targets
1131
+ };
1132
+ }
1133
+ /**
1134
+ * Placeholder for MCP server/daemon execution.
1135
+ */
1136
+ async executeServe(options = {}) {
1137
+ return this.executeServeWithOptions(options);
1138
+ }
1139
+ /**
1140
+ * Placeholder for agent status and management.
1141
+ */
1142
+ executePersona(_options = {}) {
1143
+ const personas = [
1144
+ { id: "developer", name: "Developer", focus: "Code governance, CI/CD integration, deployment validation" },
1145
+ { id: "compliance-officer", name: "Compliance Officer", focus: "Policy enforcement, evidence export, regulatory alignment" },
1146
+ { id: "platform-engineer", name: "Platform Engineer", focus: "System health, agent management, infrastructure monitoring" },
1147
+ { id: "dfi-partner", name: "DFI Partner / Auditor", focus: "Evidence review, compliance verification, audit trails" },
1148
+ { id: "trade-finance", name: "Trade Finance Officer", focus: "AfCFTA compliance, trade governance, DFI evidence" }
1149
+ ];
1150
+ console.log("[Baseline:Persona]");
1151
+ console.log(" Available personas:");
1152
+ console.log("");
1153
+ for (const persona of personas) {
1154
+ console.log(` ${persona.id.padEnd(22)} ${persona.name}`);
1155
+ console.log(` ${"".padEnd(22)} ${persona.focus}`);
1156
+ console.log("");
1157
+ }
1158
+ console.log(" Set persona in Settings or baseline.config.ts");
1159
+ return { success: true, personas };
1160
+ }
1161
+ async executeAgents(options = {}) {
1162
+ return this.executeAgentsWithOptions(options);
1163
+ }
1164
+ async buildBaselineOS(context) {
1165
+ const { Baseline } = await import("baselineos");
1166
+ const knowledge = [
1167
+ import_node_path.default.join(context, "docs"),
1168
+ import_node_path.default.join(context, "README.md")
1169
+ ];
1170
+ return new Baseline({
1171
+ projectRoot: context,
1172
+ knowledge,
1173
+ paths: {
1174
+ data: import_node_path.default.join(context, ".baseline"),
1175
+ index: import_node_path.default.join(context, ".baseline", "index"),
1176
+ checkpoints: import_node_path.default.join(context, ".baseline", "checkpoints")
1177
+ }
1178
+ });
1179
+ }
1180
+ async executeServeWithOptions(options) {
1181
+ const context = this.resolveContext(options.context, process.cwd());
1182
+ const withApi = this.normalizeBoolean(options.api);
1183
+ const portRaw = this.normalizeString(options.port);
1184
+ const port = portRaw && Number(portRaw) > 0 ? Number(portRaw) : 3141;
1185
+ const once = this.normalizeBoolean(options.once);
1186
+ const baseline = await this.buildBaselineOS(context);
1187
+ await baseline.init();
1188
+ const mcpServer = await baseline.startMCPServer();
1189
+ let apiServer = null;
1190
+ if (withApi) {
1191
+ apiServer = await baseline.startAPIServer(port);
1192
+ }
1193
+ console.error(
1194
+ `[Baseline:Serve] MCP server started (stdio)${withApi ? ` + API:${port}` : ""}`
1195
+ );
1196
+ if (once) {
1197
+ return {
1198
+ success: true,
1199
+ status: "running",
1200
+ mode: "stdio",
1201
+ api: withApi ? { port } : null,
1202
+ message: "Server started (once mode)."
1203
+ };
1204
+ }
1205
+ await new Promise((resolve) => {
1206
+ const handle = async () => {
1207
+ try {
1208
+ await mcpServer.stop();
1209
+ } catch {
1210
+ }
1211
+ if (apiServer && typeof apiServer === "object" && "stop" in apiServer) {
1212
+ await apiServer.stop();
1213
+ }
1214
+ await baseline.shutdown();
1215
+ resolve();
1216
+ };
1217
+ process.on("SIGINT", handle);
1218
+ process.on("SIGTERM", handle);
1219
+ });
1220
+ return {
1221
+ success: true,
1222
+ status: "stopped"
1223
+ };
1224
+ }
1225
+ async executeAgentsWithOptions(options) {
1226
+ const context = this.resolveContext(options.context, process.cwd());
1227
+ const baseline = await this.buildBaselineOS(context);
1228
+ await baseline.init();
1229
+ const agents = baseline.listAgents();
1230
+ return {
1231
+ success: true,
1232
+ context,
1233
+ total: agents.length,
1234
+ agents
1235
+ };
1236
+ }
1237
+ /**
1238
+ * Run diagnostics for configuration and readiness.
1239
+ */
1240
+ async executeDoctor(options = {}) {
1241
+ const context = this.resolveContext(options.context, process.cwd());
1242
+ const checks = [
1243
+ {
1244
+ id: "config",
1245
+ description: "Baseline config exists",
1246
+ path: import_node_path.default.join(context, ".baseline", "baseline.config.json")
1247
+ },
1248
+ {
1249
+ id: "onboarding",
1250
+ description: "Onboarding profile exists",
1251
+ path: import_node_path.default.join(context, ".baseline", "onboarding.json")
1252
+ },
1253
+ {
1254
+ id: "index",
1255
+ description: "Index exists",
1256
+ path: import_node_path.default.join(context, ".baseline", "index.json")
1257
+ },
1258
+ {
1259
+ id: "roadmap",
1260
+ description: "Roadmap exists",
1261
+ path: import_node_path.default.join(context, "docs", "strategy", "roadmap.md")
1262
+ },
1263
+ {
1264
+ id: "ga-release",
1265
+ description: "GA release checklist exists",
1266
+ path: import_node_path.default.join(context, "docs", "strategy", "ga-release.md")
1267
+ },
1268
+ {
1269
+ id: "package-json",
1270
+ description: "package.json exists",
1271
+ path: import_node_path.default.join(context, "package.json")
1272
+ }
1273
+ ];
1274
+ const results = await Promise.all(
1275
+ checks.map(async (check) => ({
1276
+ ...check,
1277
+ ok: await this.fileExists(check.path)
1278
+ }))
1279
+ );
1280
+ const total = results.length;
1281
+ const passed = results.filter((check) => check.ok).length;
1282
+ const score = Math.round(passed / total * 100);
1283
+ const missing = results.filter((check) => !check.ok).map((check) => check.id);
1284
+ return {
1285
+ success: true,
1286
+ context,
1287
+ score,
1288
+ passed,
1289
+ total,
1290
+ missing,
1291
+ checks: results
1292
+ };
1293
+ }
1294
+ /**
1295
+ * Initialize the Baseline environment, setting up context folder,
1296
+ * configuration, and mode.
1297
+ */
1298
+ async initializeBaseline(options = {}) {
1299
+ try {
1300
+ const contextPath = options.context || process.cwd();
1301
+ const mode = options.mode || "development";
1302
+ this.state.customContextFolder = contextPath;
1303
+ this.state.baselineMode = true;
1304
+ console.log(`[Baseline:Init] Context path: ${contextPath}`);
1305
+ console.log(`[Baseline:Init] Mode: ${mode}`);
1306
+ const contextValid = typeof contextPath === "string" && contextPath.length > 0;
1307
+ if (!contextValid) {
1308
+ return {
1309
+ success: false,
1310
+ error: "Invalid context path provided"
1311
+ };
1312
+ }
1313
+ const config = {
1314
+ contextPath,
1315
+ mode,
1316
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1317
+ version: "0.1.0"
1318
+ };
1319
+ const detected = {};
1320
+ try {
1321
+ const { existsSync: existsSync2, readFileSync } = await import("fs");
1322
+ const { join } = await import("path");
1323
+ const pkgPath = join(contextPath, "package.json");
1324
+ if (existsSync2(pkgPath)) {
1325
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
1326
+ const allDeps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
1327
+ if (allDeps["@anthropic-ai/sdk"]) detected.provider = "anthropic";
1328
+ else if (allDeps["openai"]) detected.provider = "openai";
1329
+ if (allDeps["langchain"] || allDeps["@langchain/core"]) detected.framework = "langchain";
1330
+ if (allDeps["@modelcontextprotocol/sdk"]) detected.mcp = true;
1331
+ if (allDeps["bullmq"] || allDeps["@temporalio/client"]) detected.orchestration = true;
1332
+ detected.runtime = "node";
1333
+ detected.name = pkg.name;
1334
+ }
1335
+ const pyReq = join(contextPath, "requirements.txt");
1336
+ if (existsSync2(pyReq)) {
1337
+ const reqs = readFileSync(pyReq, "utf8");
1338
+ if (reqs.includes("anthropic")) detected.provider = "anthropic";
1339
+ else if (reqs.includes("openai")) detected.provider = "openai";
1340
+ if (reqs.includes("langchain")) detected.framework = "langchain";
1341
+ detected.runtime = "python";
1342
+ }
1343
+ if (Object.keys(detected).length > 0) {
1344
+ console.log(`[Baseline:Init] Detected: ${JSON.stringify(detected)}`);
1345
+ }
1346
+ } catch {
1347
+ }
1348
+ console.log("[Baseline:Init] Environment initialized successfully");
1349
+ return {
1350
+ success: true,
1351
+ config: { ...config, detected },
1352
+ contextPath,
1353
+ mode,
1354
+ detected
1355
+ };
1356
+ } catch (error) {
1357
+ const errorMessage = error instanceof Error ? error.message : String(error);
1358
+ return {
1359
+ success: false,
1360
+ error: errorMessage
1361
+ };
1362
+ }
1363
+ }
1364
+ /**
1365
+ * Execute the Baseline Language layer -- parsing, validation,
1366
+ * and semantic analysis of the project context.
1367
+ */
1368
+ async executeBaselineLang(options = {}) {
1369
+ try {
1370
+ const inputPath = options.input || this.state.customContextFolder || process.cwd();
1371
+ const outputPath = options.output || inputPath;
1372
+ console.log(`[Baseline:Lang] Processing language layer...`);
1373
+ console.log(`[Baseline:Lang] Input: ${inputPath}`);
1374
+ console.log(`[Baseline:Lang] Output: ${outputPath}`);
1375
+ const lexiconKeys = Object.keys(this.baselineLang.lexicon);
1376
+ console.log(`[Baseline:Lang] Lexicon entries loaded: ${lexiconKeys.length}`);
1377
+ const syntaxKeys = Object.keys(this.baselineLang.syntax);
1378
+ console.log(`[Baseline:Lang] Syntax patterns loaded: ${syntaxKeys.length}`);
1379
+ const analysisResult = {
1380
+ lexiconEntries: lexiconKeys.length,
1381
+ syntaxPatterns: syntaxKeys.length,
1382
+ validationPassed: true,
1383
+ semanticScore: 1,
1384
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1385
+ };
1386
+ console.log("[Baseline:Lang] Language layer processing complete");
1387
+ return {
1388
+ success: true,
1389
+ inputPath,
1390
+ outputPath,
1391
+ analysis: analysisResult
1392
+ };
1393
+ } catch (error) {
1394
+ const errorMessage = error instanceof Error ? error.message : String(error);
1395
+ return {
1396
+ success: false,
1397
+ error: errorMessage
1398
+ };
1399
+ }
1400
+ }
1401
+ /**
1402
+ * Execute the Baseline Frame layer -- scaffolding, composition,
1403
+ * and framework orchestration.
1404
+ */
1405
+ async executeBaselineFrame(options = {}) {
1406
+ try {
1407
+ const inputPath = options.input || this.state.customContextFolder || process.cwd();
1408
+ const configPath = options.config || null;
1409
+ console.log(`[Baseline:Frame] Processing frame layer...`);
1410
+ console.log(`[Baseline:Frame] Input: ${inputPath}`);
1411
+ if (configPath) {
1412
+ console.log(`[Baseline:Frame] Config: ${configPath}`);
1413
+ }
1414
+ const scaffoldResult = {
1415
+ components: [],
1416
+ templates: [],
1417
+ structure: "hierarchical"
1418
+ };
1419
+ const compositionResult = {
1420
+ composed: true,
1421
+ layers: ["lang", "frame", "studio", "govern"],
1422
+ dependencies: []
1423
+ };
1424
+ const orchestrationResult = {
1425
+ orchestrated: true,
1426
+ pipelineStages: 4,
1427
+ parallelism: 1
1428
+ };
1429
+ console.log("[Baseline:Frame] Frame layer processing complete");
1430
+ return {
1431
+ success: true,
1432
+ scaffold: scaffoldResult,
1433
+ composition: compositionResult,
1434
+ orchestration: orchestrationResult
1435
+ };
1436
+ } catch (error) {
1437
+ const errorMessage = error instanceof Error ? error.message : String(error);
1438
+ return {
1439
+ success: false,
1440
+ error: errorMessage
1441
+ };
1442
+ }
1443
+ }
1444
+ /**
1445
+ * Execute the Baseline Studio layer -- design rendering,
1446
+ * preview generation, and visual asset processing.
1447
+ */
1448
+ async executeBaselineStudio(options = {}) {
1449
+ try {
1450
+ const inputPath = options.input || this.state.customContextFolder || process.cwd();
1451
+ const renderMode = options.render || "standard";
1452
+ console.log(`[Baseline:Studio] Processing studio layer...`);
1453
+ console.log(`[Baseline:Studio] Input: ${inputPath}`);
1454
+ console.log(`[Baseline:Studio] Render mode: ${renderMode}`);
1455
+ const designResult = {
1456
+ designSystem: "baseline-default",
1457
+ components: 0,
1458
+ tokens: {},
1459
+ themes: ["light", "dark"]
1460
+ };
1461
+ const renderResult = {
1462
+ rendered: true,
1463
+ mode: renderMode,
1464
+ outputFormat: "html",
1465
+ assets: []
1466
+ };
1467
+ const previewResult = {
1468
+ previewAvailable: false,
1469
+ previewUrl: null
1470
+ };
1471
+ console.log("[Baseline:Studio] Studio layer processing complete");
1472
+ return {
1473
+ success: true,
1474
+ design: designResult,
1475
+ render: renderResult,
1476
+ preview: previewResult
1477
+ };
1478
+ } catch (error) {
1479
+ const errorMessage = error instanceof Error ? error.message : String(error);
1480
+ return {
1481
+ success: false,
1482
+ error: errorMessage
1483
+ };
1484
+ }
1485
+ }
1486
+ /**
1487
+ * Execute the Baseline Govern layer -- audit, policy enforcement,
1488
+ * compliance checking, and governance controls.
1489
+ */
1490
+ async executeBaselineGovern(options = {}) {
1491
+ try {
1492
+ const inputPath = options.input || this.state.customContextFolder || process.cwd();
1493
+ const policyPath = options.policy || null;
1494
+ const auditPath = import_node_path.default.join(inputPath, ".baseline", "govern", "audit-trail.json");
1495
+ console.log(`[Baseline:Govern] Processing governance layer...`);
1496
+ console.log(`[Baseline:Govern] Input: ${inputPath}`);
1497
+ if (policyPath) {
1498
+ console.log(`[Baseline:Govern] Policy: ${policyPath}`);
1499
+ }
1500
+ let policyContent = "Default governance policy";
1501
+ if (policyPath) {
1502
+ try {
1503
+ policyContent = await (0, import_promises.readFile)(policyPath, "utf8");
1504
+ } catch (error) {
1505
+ const message = error instanceof Error ? error.message : String(error);
1506
+ console.log(`[Baseline:Govern] Unable to read policy file, using default policy (${message})`);
1507
+ }
1508
+ }
1509
+ const govern = new import_govern.BaselineGovernSystem({ persistPath: auditPath });
1510
+ const createdPolicy = await govern.policies.create("baseline-default", policyContent, {
1511
+ severity: "high",
1512
+ enforcement: "block",
1513
+ requireApproval: Boolean(options.requireApproval),
1514
+ requiredApprovers: Array.isArray(options.requiredApprovers) ? options.requiredApprovers : ["govern-approver"],
1515
+ rules: [
1516
+ {
1517
+ id: "restricted-sensitivity",
1518
+ name: "Restricted sensitivity requires approval",
1519
+ severity: "high",
1520
+ enforcement: "block",
1521
+ condition: { field: "sensitivity", equals: "restricted" },
1522
+ message: "Restricted workloads must pass approval before enforcement."
1523
+ }
1524
+ ]
1525
+ });
1526
+ if (!createdPolicy.success || !createdPolicy.policy) {
1527
+ throw new Error(createdPolicy.error || "Failed to create governance policy");
1528
+ }
1529
+ const policyId = createdPolicy.policy.id;
1530
+ const approvedPolicy = await govern.policies.approve(policyId, String(options.approver || "baseline-cli"));
1531
+ if (!approvedPolicy.success) {
1532
+ throw new Error(approvedPolicy.error || "Failed to approve governance policy");
1533
+ }
1534
+ const enforcement = await govern.policies.enforce(policyId, {
1535
+ resourceId: String(options.resourceId || inputPath),
1536
+ requestedBy: String(options.requestedBy || "baseline-cli"),
1537
+ sensitivity: String(options.sensitivity || "standard"),
1538
+ mode: String(options.mode || this.state.customContextFolder || "development")
1539
+ });
1540
+ const compliance = await govern.compliance.check("ISO27001", {
1541
+ documentation: options.documentation || "complete",
1542
+ process: options.process || "complete"
1543
+ });
1544
+ const evidence = govern.getEvidenceBundle(policyId, String(options.resourceId || inputPath));
1545
+ const violations = enforcement.evaluation?.violations ?? [];
1546
+ const policyResult = {
1547
+ policiesEvaluated: 1,
1548
+ policiesPassed: enforcement.success ? 1 : 0,
1549
+ policiesFailed: enforcement.success ? 0 : 1,
1550
+ violations,
1551
+ enforcementAction: enforcement.evaluation?.enforcementAction ?? "allow",
1552
+ requiresApproval: enforcement.evaluation?.requiresApproval ?? false
1553
+ };
1554
+ const auditResult = {
1555
+ auditId: `audit-${Date.now()}`,
1556
+ passed: enforcement.success,
1557
+ findings: violations.map((violation) => violation.message),
1558
+ severity: violations.length > 0 ? "high" : "none",
1559
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1560
+ events: evidence.auditTrail.length
1561
+ };
1562
+ const complianceResult = {
1563
+ compliant: compliance.compliance?.compliant ?? false,
1564
+ standards: ["ISO27001"],
1565
+ certifications: [],
1566
+ gaps: compliance.compliance?.violations ?? []
1567
+ };
1568
+ console.log("[Baseline:Govern] Governance layer processing complete");
1569
+ return {
1570
+ success: enforcement.success,
1571
+ audit: auditResult,
1572
+ policy: policyResult,
1573
+ compliance: complianceResult,
1574
+ evaluation: enforcement.evaluation,
1575
+ approval: enforcement.approval,
1576
+ evidence
1577
+ };
1578
+ } catch (error) {
1579
+ const errorMessage = error instanceof Error ? error.message : String(error);
1580
+ return {
1581
+ success: false,
1582
+ error: errorMessage
1583
+ };
1584
+ }
1585
+ }
1586
+ /**
1587
+ * Execute a chain of commands sequentially. Each command in the array
1588
+ * is executed in order. If any command fails, the chain halts.
1589
+ */
1590
+ async executeChainedCommands(commands) {
1591
+ console.log(`[Baseline:Chain] Executing ${commands.length} chained commands...`);
1592
+ const results = {};
1593
+ let overallSuccess = true;
1594
+ for (let i = 0; i < commands.length; i++) {
1595
+ const command = commands[i].trim();
1596
+ console.log(`[Baseline:Chain] Command ${i + 1}/${commands.length}: ${command}`);
1597
+ try {
1598
+ const result = await this.executeCommand(command);
1599
+ results[`step_${i + 1}`] = result;
1600
+ if (!result.success) {
1601
+ overallSuccess = false;
1602
+ console.log(`[Baseline:Chain] Command ${i + 1} failed: ${result.error || "unknown error"}`);
1603
+ break;
1604
+ }
1605
+ console.log(`[Baseline:Chain] Command ${i + 1} completed successfully`);
1606
+ } catch (error) {
1607
+ const errorMessage = error instanceof Error ? error.message : String(error);
1608
+ overallSuccess = false;
1609
+ results[`step_${i + 1}`] = { success: false, error: errorMessage };
1610
+ console.log(`[Baseline:Chain] Command ${i + 1} threw error: ${errorMessage}`);
1611
+ break;
1612
+ }
1613
+ }
1614
+ console.log(`[Baseline:Chain] Chain execution ${overallSuccess ? "completed" : "failed"}`);
1615
+ return {
1616
+ success: overallSuccess,
1617
+ results,
1618
+ commandsExecuted: Object.keys(results).length,
1619
+ totalCommands: commands.length
1620
+ };
1621
+ }
1622
+ /**
1623
+ * Add a command to the execution queue for deferred execution.
1624
+ */
1625
+ queueCommand(command) {
1626
+ this.state.commandQueue.push(command);
1627
+ console.log(`[Baseline:Queue] Command queued: ${command} (queue size: ${this.state.commandQueue.length})`);
1628
+ }
1629
+ /**
1630
+ * Execute all commands currently in the queue, in FIFO order,
1631
+ * then clear the queue.
1632
+ */
1633
+ async executeQueue() {
1634
+ const queueLength = this.state.commandQueue.length;
1635
+ if (queueLength === 0) {
1636
+ console.log("[Baseline:Queue] Queue is empty, nothing to execute");
1637
+ return { success: true, message: "Queue is empty" };
1638
+ }
1639
+ console.log(`[Baseline:Queue] Executing ${queueLength} queued commands...`);
1640
+ const commands = [...this.state.commandQueue];
1641
+ this.state.commandQueue = [];
1642
+ const result = await this.executeChainedCommands(commands);
1643
+ console.log(`[Baseline:Queue] Queue execution complete`);
1644
+ return result;
1645
+ }
1646
+ /**
1647
+ * Execute a single command string by dispatching to the appropriate
1648
+ * handler based on the command flag.
1649
+ */
1650
+ async executeCommand(command) {
1651
+ const trimmed = command.trim();
1652
+ console.log(`[Baseline:Command] Executing: ${trimmed}`);
1653
+ const parts = trimmed.split(/\s+/);
1654
+ const mainCommand = parts[0];
1655
+ const options = {};
1656
+ const positionals = [];
1657
+ for (let i = 1; i < parts.length; i++) {
1658
+ if (parts[i].startsWith("--")) {
1659
+ const key = parts[i].replace(/^--/, "");
1660
+ const value = parts[i + 1] && !parts[i + 1].startsWith("--") ? parts[++i] : "true";
1661
+ options[key] = value;
1662
+ } else {
1663
+ positionals.push(parts[i]);
1664
+ }
1665
+ }
1666
+ options._ = positionals;
1667
+ switch (mainCommand) {
1668
+ case "--onboard":
1669
+ return await this.executeOnboarding(options);
1670
+ case "--experience":
1671
+ return await this.executeExperience(options);
1672
+ case "--config":
1673
+ return await this.executeConfig(options);
1674
+ case "--index":
1675
+ return await this.executeIndex(options);
1676
+ case "--serve":
1677
+ return await this.executeServe(options);
1678
+ case "--persona":
1679
+ return this.executePersona(options);
1680
+ case "--agents":
1681
+ return await this.executeAgents(options);
1682
+ case "--doctor":
1683
+ return await this.executeDoctor(options);
1684
+ case "--baseline":
1685
+ return await this.executeBaselineWorkflow(options);
1686
+ case "--baseline-lang":
1687
+ return await this.executeBaselineLang(options);
1688
+ case "--baseline-frame":
1689
+ return await this.executeBaselineFrame(options);
1690
+ case "--baseline-studio":
1691
+ return await this.executeBaselineStudio(options);
1692
+ case "--baseline-govern":
1693
+ return await this.executeBaselineGovern(options);
1694
+ case "--init":
1695
+ return await this.executeInit(options);
1696
+ case "--run":
1697
+ return await this.executeBaselineWorkflow(options);
1698
+ case "--status": {
1699
+ const status = this.getStatus();
1700
+ return { success: true, ...status };
1701
+ }
1702
+ case "--help":
1703
+ this.showHelp();
1704
+ return { success: true };
1705
+ default:
1706
+ console.log(`[Baseline:Command] Unknown command: ${mainCommand}`);
1707
+ return {
1708
+ success: false,
1709
+ error: `Unknown command: ${mainCommand}. Use --help for available commands.`
1710
+ };
1711
+ }
1712
+ }
1713
+ /**
1714
+ * Return the current status of the Baseline system, including
1715
+ * state, execution history, and queue contents.
1716
+ */
1717
+ getStatus() {
1718
+ const status = {
1719
+ baselineMode: this.state.baselineMode,
1720
+ customContextFolder: this.state.customContextFolder,
1721
+ queueLength: this.state.commandQueue.length,
1722
+ queuedCommands: [...this.state.commandQueue],
1723
+ executionHistoryCount: this.state.executionHistory.length,
1724
+ currentWorkflow: this.state.currentWorkflow ? {
1725
+ id: this.state.currentWorkflow.id,
1726
+ status: this.state.currentWorkflow.status,
1727
+ startTime: this.state.currentWorkflow.startTime.toISOString()
1728
+ } : null,
1729
+ recentExecutions: this.state.executionHistory.slice(-5).map(
1730
+ (execution) => ({
1731
+ id: execution.id,
1732
+ status: execution.status,
1733
+ duration: execution.duration,
1734
+ startTime: execution.startTime.toISOString(),
1735
+ error: execution.error || null
1736
+ })
1737
+ ),
1738
+ megagemConnected: this.megagem !== null,
1739
+ contextEngineConnected: this.contextEngine !== null,
1740
+ lexiconEntries: Object.keys(this.baselineLang.lexicon).length,
1741
+ syntaxPatterns: Object.keys(this.baselineLang.syntax).length,
1742
+ commands: Object.keys(this.baselineLang.commands).length
1743
+ };
1744
+ const layers = ["lang", "frame", "studio", "govern", "experience", "autonomy", "persona"];
1745
+ const layerStatus = layers.map((id) => {
1746
+ const lastExec = this.state.executionHistory.filter((e) => e.status === "completed").slice(-1)[0];
1747
+ return { id, status: "armed", lastCheck: lastExec ? "passed" : "none" };
1748
+ });
1749
+ status.layers = layerStatus;
1750
+ console.log("[Baseline:Status]");
1751
+ console.log(` Mode: ${status.baselineMode ? "active" : "inactive"}`);
1752
+ console.log(` Context: ${status.customContextFolder || "none"}`);
1753
+ console.log(` Queue: ${status.queueLength} commands`);
1754
+ console.log(` History: ${status.executionHistoryCount} executions`);
1755
+ console.log(` MEGAGEM: ${status.megagemConnected ? "connected" : "disconnected"}`);
1756
+ console.log(` Context Engine: ${status.contextEngineConnected ? "connected" : "disconnected"}`);
1757
+ console.log("");
1758
+ console.log(" Governance Layers:");
1759
+ for (const layer of layerStatus) {
1760
+ const dot = layer.lastCheck === "passed" ? "\u25CF" : layer.lastCheck === "failed" ? "\u25CB" : "\u25CC";
1761
+ console.log(` ${dot} ${layer.id.padEnd(12)} ${layer.status.padEnd(8)} last check: ${layer.lastCheck}`);
1762
+ }
1763
+ return status;
1764
+ }
1765
+ /**
1766
+ * Display help information for all available commands, flags,
1767
+ * and syntax patterns.
1768
+ */
1769
+ showHelp() {
1770
+ console.log("");
1771
+ console.log("=== Baseline Protocol CLI ===");
1772
+ console.log("");
1773
+ console.log("COMMANDS:");
1774
+ console.log("");
1775
+ for (const [flag, entry] of Object.entries(this.baselineLang.commands)) {
1776
+ console.log(` ${flag.padEnd(20)} ${entry.description}`);
1777
+ }
1778
+ console.log("");
1779
+ console.log("LAYER FLAGS:");
1780
+ console.log("");
1781
+ for (const [flag, entry] of Object.entries(this.baselineLang.lexicon)) {
1782
+ console.log(` ${flag.padEnd(24)} ${entry.description}`);
1783
+ console.log(` ${"".padEnd(24)} Usage: ${entry.usage}`);
1784
+ console.log(` ${"".padEnd(24)} Category: ${entry.category}`);
1785
+ if (entry.examples.length > 0) {
1786
+ console.log(` ${"".padEnd(24)} Examples:`);
1787
+ for (const example of entry.examples) {
1788
+ console.log(` ${"".padEnd(28)} ${example}`);
1789
+ }
1790
+ }
1791
+ console.log("");
1792
+ }
1793
+ console.log("SYNTAX PATTERNS:");
1794
+ console.log("");
1795
+ for (const [name, entry] of Object.entries(this.baselineLang.syntax)) {
1796
+ console.log(` ${name}:`);
1797
+ console.log(` Pattern: ${entry.pattern}`);
1798
+ console.log(" Parameters:");
1799
+ for (const [param, desc] of Object.entries(entry.parameters)) {
1800
+ console.log(` --${param.padEnd(16)} ${desc}`);
1801
+ }
1802
+ if (entry.examples.length > 0) {
1803
+ console.log(" Examples:");
1804
+ for (const example of entry.examples) {
1805
+ console.log(` ${example}`);
1806
+ }
1807
+ }
1808
+ console.log("");
1809
+ }
1810
+ console.log("USAGE:");
1811
+ console.log(" baseline --init Initialize a new project");
1812
+ console.log(" baseline --run Run the full workflow");
1813
+ console.log(" baseline --baseline --mode production Run in production mode");
1814
+ console.log(" baseline --status Check system status");
1815
+ console.log(" baseline --help Show this help");
1816
+ console.log("");
1817
+ }
1818
+ /**
1819
+ * Set the MEGAGEM integration instance for autonomous operations.
1820
+ */
1821
+ setMegagem(megagem) {
1822
+ this.megagem = megagem;
1823
+ console.log("[Baseline] MEGAGEM integration connected");
1824
+ }
1825
+ /**
1826
+ * Set the Context Engine integration instance for context management.
1827
+ */
1828
+ setContextEngine(contextEngine) {
1829
+ this.contextEngine = contextEngine;
1830
+ console.log("[Baseline] Context Engine integration connected");
1831
+ }
1832
+ };
1833
+
1834
+ // src/verify.ts
1835
+ var import_promises2 = require("fs/promises");
1836
+ var import_node_fs = require("fs");
1837
+ var import_node_crypto = require("crypto");
1838
+ async function runVerify(options) {
1839
+ const checks = [];
1840
+ if (options.evidencePath) {
1841
+ const evidenceChecks = await verifyEvidenceBundle(options.evidencePath);
1842
+ checks.push(...evidenceChecks);
1843
+ }
1844
+ if (options.policyPath) {
1845
+ const policyChecks = await verifyPolicy(options.policyPath);
1846
+ checks.push(...policyChecks);
1847
+ }
1848
+ if (options.auditTrailPath) {
1849
+ const auditChecks = await verifyAuditTrail(options.auditTrailPath);
1850
+ checks.push(...auditChecks);
1851
+ }
1852
+ if (checks.length === 0) {
1853
+ checks.push({
1854
+ name: "input",
1855
+ status: "fail",
1856
+ message: "No files provided. Use --policy, --evidence, or --audit-trail."
1857
+ });
1858
+ }
1859
+ const passed = checks.filter((c) => c.status === "pass").length;
1860
+ const failed = checks.filter((c) => c.status === "fail").length;
1861
+ const warnings = checks.filter((c) => c.status === "warn").length;
1862
+ const skipped = checks.filter((c) => c.status === "skip").length;
1863
+ const hashInput = checks.map((c) => `${c.name}:${c.status}:${c.message}`).join("|");
1864
+ const hash = (0, import_node_crypto.createHash)("sha256").update(hashInput).digest("hex").slice(0, 16);
1865
+ return {
1866
+ success: failed === 0,
1867
+ passed,
1868
+ failed,
1869
+ warnings,
1870
+ skipped,
1871
+ checks,
1872
+ hash,
1873
+ verifiedAt: (/* @__PURE__ */ new Date()).toISOString()
1874
+ };
1875
+ }
1876
+ async function verifyEvidenceBundle(filePath) {
1877
+ const checks = [];
1878
+ if (!(0, import_node_fs.existsSync)(filePath)) {
1879
+ checks.push({ name: "evidence.exists", status: "fail", message: `Evidence file not found: ${filePath}` });
1880
+ return checks;
1881
+ }
1882
+ checks.push({ name: "evidence.exists", status: "pass", message: "Evidence file found" });
1883
+ try {
1884
+ const raw = await (0, import_promises2.readFile)(filePath, "utf-8");
1885
+ const bundle = JSON.parse(raw);
1886
+ if (bundle.policy) {
1887
+ checks.push({ name: "evidence.policy", status: "pass", message: `Policy: ${bundle.policy.name ?? bundle.policy.id}` });
1888
+ } else {
1889
+ checks.push({ name: "evidence.policy", status: "warn", message: "Evidence bundle has no policy reference" });
1890
+ }
1891
+ if (Array.isArray(bundle.auditTrail)) {
1892
+ checks.push({
1893
+ name: "evidence.auditTrail",
1894
+ status: bundle.auditTrail.length > 0 ? "pass" : "warn",
1895
+ message: `Audit trail: ${bundle.auditTrail.length} events`
1896
+ });
1897
+ } else {
1898
+ checks.push({ name: "evidence.auditTrail", status: "fail", message: "Evidence bundle missing audit trail" });
1899
+ }
1900
+ if (bundle.latestEvaluation) {
1901
+ const eval_ = bundle.latestEvaluation;
1902
+ checks.push({
1903
+ name: "evidence.evaluation",
1904
+ status: eval_.passed ? "pass" : "fail",
1905
+ message: `Evaluation: ${eval_.passed ? "passed" : "failed"} (score: ${eval_.score ?? "N/A"})`
1906
+ });
1907
+ } else {
1908
+ checks.push({ name: "evidence.evaluation", status: "skip", message: "No evaluation in evidence bundle" });
1909
+ }
1910
+ if (Array.isArray(bundle.approvals)) {
1911
+ const approved = bundle.approvals.filter((a) => a.status === "approved");
1912
+ checks.push({
1913
+ name: "evidence.approvals",
1914
+ status: "pass",
1915
+ message: `Approvals: ${approved.length}/${bundle.approvals.length} approved`
1916
+ });
1917
+ }
1918
+ const contentHash = (0, import_node_crypto.createHash)("sha256").update(raw).digest("hex");
1919
+ checks.push({ name: "evidence.integrity", status: "pass", message: `SHA-256: ${contentHash.slice(0, 16)}...` });
1920
+ } catch (error) {
1921
+ checks.push({
1922
+ name: "evidence.parse",
1923
+ status: "fail",
1924
+ message: `Failed to parse evidence: ${error instanceof Error ? error.message : String(error)}`
1925
+ });
1926
+ }
1927
+ return checks;
1928
+ }
1929
+ async function verifyPolicy(filePath) {
1930
+ const checks = [];
1931
+ if (!(0, import_node_fs.existsSync)(filePath)) {
1932
+ checks.push({ name: "policy.exists", status: "fail", message: `Policy file not found: ${filePath}` });
1933
+ return checks;
1934
+ }
1935
+ checks.push({ name: "policy.exists", status: "pass", message: "Policy file found" });
1936
+ try {
1937
+ const raw = await (0, import_promises2.readFile)(filePath, "utf-8");
1938
+ const policy = JSON.parse(raw);
1939
+ if (policy.id && policy.name) {
1940
+ checks.push({ name: "policy.identity", status: "pass", message: `Policy: ${policy.name} (${policy.id})` });
1941
+ } else {
1942
+ checks.push({ name: "policy.identity", status: "fail", message: "Policy missing id or name" });
1943
+ }
1944
+ if (policy.status === "approved" || policy.status === "enforced") {
1945
+ checks.push({ name: "policy.status", status: "pass", message: `Status: ${policy.status}` });
1946
+ } else {
1947
+ checks.push({ name: "policy.status", status: "warn", message: `Policy status is ${policy.status ?? "unknown"}, not approved/enforced` });
1948
+ }
1949
+ if (policy.version) {
1950
+ checks.push({ name: "policy.version", status: "pass", message: `Version: ${policy.version}` });
1951
+ } else {
1952
+ checks.push({ name: "policy.version", status: "warn", message: "Policy has no version" });
1953
+ }
1954
+ if (Array.isArray(policy.rules) && policy.rules.length > 0) {
1955
+ checks.push({ name: "policy.rules", status: "pass", message: `${policy.rules.length} rules defined` });
1956
+ } else {
1957
+ checks.push({ name: "policy.rules", status: "warn", message: "Policy has no rules defined" });
1958
+ }
1959
+ } catch (error) {
1960
+ checks.push({
1961
+ name: "policy.parse",
1962
+ status: "fail",
1963
+ message: `Failed to parse policy: ${error instanceof Error ? error.message : String(error)}`
1964
+ });
1965
+ }
1966
+ return checks;
1967
+ }
1968
+ async function verifyAuditTrail(filePath) {
1969
+ const checks = [];
1970
+ if (!(0, import_node_fs.existsSync)(filePath)) {
1971
+ checks.push({ name: "audit.exists", status: "fail", message: `Audit trail not found: ${filePath}` });
1972
+ return checks;
1973
+ }
1974
+ checks.push({ name: "audit.exists", status: "pass", message: "Audit trail found" });
1975
+ try {
1976
+ const raw = await (0, import_promises2.readFile)(filePath, "utf-8");
1977
+ const events = JSON.parse(raw);
1978
+ if (!Array.isArray(events)) {
1979
+ checks.push({ name: "audit.format", status: "fail", message: "Audit trail is not an array" });
1980
+ return checks;
1981
+ }
1982
+ checks.push({ name: "audit.count", status: "pass", message: `${events.length} audit events` });
1983
+ let ordered = true;
1984
+ for (let i = 1; i < events.length; i++) {
1985
+ if (events[i].timestamp < events[i - 1].timestamp) {
1986
+ ordered = false;
1987
+ break;
1988
+ }
1989
+ }
1990
+ checks.push({
1991
+ name: "audit.order",
1992
+ status: ordered ? "pass" : "warn",
1993
+ message: ordered ? "Events are chronologically ordered" : "Events are NOT chronologically ordered"
1994
+ });
1995
+ const types = new Set(events.map((e) => e.type));
1996
+ checks.push({ name: "audit.types", status: "pass", message: `Event types: ${Array.from(types).join(", ")}` });
1997
+ const contentHash = (0, import_node_crypto.createHash)("sha256").update(raw).digest("hex");
1998
+ checks.push({ name: "audit.integrity", status: "pass", message: `SHA-256: ${contentHash.slice(0, 16)}...` });
1999
+ } catch (error) {
2000
+ checks.push({
2001
+ name: "audit.parse",
2002
+ status: "fail",
2003
+ message: `Failed to parse audit trail: ${error instanceof Error ? error.message : String(error)}`
2004
+ });
2005
+ }
2006
+ return checks;
2007
+ }
2008
+
2009
+ // src/cli.ts
2010
+ var import_promises3 = require("readline/promises");
2011
+ var import_node_process = require("process");
2012
+ var VERSION = "0.1.0";
2013
+ function buildCommandLine(args) {
2014
+ const raw = args.join(" ").trim();
2015
+ if (!raw) return "";
2016
+ return raw.startsWith("--") ? raw : `--${raw}`;
2017
+ }
2018
+ async function main() {
2019
+ const args = process.argv.slice(2);
2020
+ const command = args[0];
2021
+ switch (command) {
2022
+ case "--help":
2023
+ case "-h":
2024
+ case "help":
2025
+ case void 0:
2026
+ showStartScreen();
2027
+ showHelp();
2028
+ break;
2029
+ case "status":
2030
+ case "--status":
2031
+ showStatus();
2032
+ break;
2033
+ case "init": {
2034
+ const cmdSystem = new BaselineCommandSystem();
2035
+ const commandLine = buildCommandLine(["--init", ...args.slice(1), "--write-config"]);
2036
+ const result = await cmdSystem.executeCommand(commandLine);
2037
+ if (!result.success) {
2038
+ console.error(`Error: ${result.error ?? "Unknown error"}`);
2039
+ process.exit(1);
2040
+ }
2041
+ console.log(JSON.stringify(result, null, 2));
2042
+ break;
2043
+ }
2044
+ case "version":
2045
+ case "--version":
2046
+ case "-v":
2047
+ console.log(`baseline v${VERSION}`);
2048
+ break;
2049
+ case "onboard":
2050
+ case "onboarding": {
2051
+ const cmdSystem = new BaselineCommandSystem();
2052
+ const rawArgs = args.slice(1).filter((arg) => arg !== "--interactive");
2053
+ const interactive = args.length <= 1 || args.includes("--interactive");
2054
+ let result;
2055
+ if (interactive) {
2056
+ showStartScreen();
2057
+ const options = await promptOnboardingOptions();
2058
+ result = await cmdSystem.executeOnboarding(options);
2059
+ } else {
2060
+ const commandLine = buildCommandLine(["--onboard", ...rawArgs]);
2061
+ result = await cmdSystem.executeCommand(commandLine);
2062
+ }
2063
+ if (!result.success) {
2064
+ console.error(`Error: ${result.error ?? "Unknown error"}`);
2065
+ process.exit(1);
2066
+ }
2067
+ console.log(JSON.stringify(result, null, 2));
2068
+ break;
2069
+ }
2070
+ case "experience": {
2071
+ const cmdSystem = new BaselineCommandSystem();
2072
+ const rawArgs = args.slice(1);
2073
+ const commandLine = buildCommandLine(["--experience", ...rawArgs]);
2074
+ const result = await cmdSystem.executeCommand(commandLine);
2075
+ if (!result.success) {
2076
+ console.error(`Error: ${result.error ?? "Unknown error"}`);
2077
+ process.exit(1);
2078
+ }
2079
+ console.log(JSON.stringify(result, null, 2));
2080
+ break;
2081
+ }
2082
+ case "serve": {
2083
+ const cmdSystem = new BaselineCommandSystem();
2084
+ const commandLine = buildCommandLine(["--serve", ...args.slice(1)]);
2085
+ const result = await cmdSystem.executeCommand(commandLine);
2086
+ if (!result.success) {
2087
+ console.error(`Error: ${result.error ?? "Unknown error"}`);
2088
+ process.exit(1);
2089
+ }
2090
+ break;
2091
+ }
2092
+ case "verify": {
2093
+ const verifyOpts = {};
2094
+ for (let i = 1; i < args.length; i++) {
2095
+ if (args[i] === "--policy" && args[i + 1]) {
2096
+ verifyOpts.policyPath = args[++i];
2097
+ } else if (args[i] === "--evidence" && args[i + 1]) {
2098
+ verifyOpts.evidencePath = args[++i];
2099
+ } else if (args[i] === "--audit-trail" && args[i + 1]) {
2100
+ verifyOpts.auditTrailPath = args[++i];
2101
+ }
2102
+ }
2103
+ const verifyResult = await runVerify(verifyOpts);
2104
+ console.log(JSON.stringify(verifyResult, null, 2));
2105
+ if (!verifyResult.success) process.exit(1);
2106
+ break;
2107
+ }
2108
+ case "doctor": {
2109
+ const cmdSystem = new BaselineCommandSystem();
2110
+ const commandLine = buildCommandLine(["--doctor", ...args.slice(1)]);
2111
+ const result = await cmdSystem.executeCommand(commandLine);
2112
+ if (!result.success) {
2113
+ console.error(`Error: ${result.error ?? "Unknown error"}`);
2114
+ process.exit(1);
2115
+ }
2116
+ console.log(JSON.stringify(result, null, 2));
2117
+ break;
2118
+ }
2119
+ default: {
2120
+ const cmdSystem = new BaselineCommandSystem();
2121
+ const commandLine = buildCommandLine(args);
2122
+ if (!commandLine) {
2123
+ showHelp();
2124
+ return;
2125
+ }
2126
+ const result = await cmdSystem.executeCommand(commandLine);
2127
+ if (!result.success) {
2128
+ console.error(`Error: ${result.error ?? "Unknown error"}`);
2129
+ process.exit(1);
2130
+ }
2131
+ console.log(JSON.stringify(result, null, 2));
2132
+ break;
2133
+ }
2134
+ }
2135
+ }
2136
+ function showHelp() {
2137
+ console.log(`
2138
+ Baseline Protocol CLI v${VERSION}
2139
+
2140
+ Usage: baseline <command> [options]
2141
+
2142
+ Commands:
2143
+ help Show this help message
2144
+ status Show status of all protocol layers
2145
+ onboard Run the guided onboarding flow
2146
+ experience Run immersive onboarding experiences
2147
+ init Initialize Baseline and write config
2148
+ run Run the full Baseline workflow
2149
+ index Index docs or context for retrieval
2150
+ verify Verify policy compliance and evidence integrity
2151
+ serve Start the Baseline MCP server
2152
+ agents Show agent registry status
2153
+ config Configure Baseline preferences
2154
+ doctor Run diagnostics for Baseline readiness
2155
+ version Show version information
2156
+
2157
+ Layer Commands:
2158
+ --baseline Run full Baseline Protocol workflow
2159
+ --baseline-lang Run Language layer only
2160
+ --baseline-frame Run Frame layer only
2161
+ --baseline-studio Run Studio layer only
2162
+ --baseline-govern Run Governance layer only
2163
+ --init Initialize a new Baseline project
2164
+ --run Run the full workflow
2165
+ --status Show system status
2166
+ --help Show help information
2167
+ `);
2168
+ }
2169
+ function showStartScreen() {
2170
+ console.log(`
2171
+ \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
2172
+ \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D
2173
+ \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557
2174
+ \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D
2175
+ \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
2176
+ \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D
2177
+
2178
+ Baseline Protocol \u2022 Guided Onboarding
2179
+ `);
2180
+ }
2181
+ async function promptOnboardingOptions() {
2182
+ const rl = (0, import_promises3.createInterface)({ input: import_node_process.stdin, output: import_node_process.stdout });
2183
+ try {
2184
+ const nameInput = (await rl.question("Your name (default: User): ")).trim();
2185
+ const roleInput = (await rl.question("Role (default: Operator): ")).trim();
2186
+ const emailInput = (await rl.question("Email (optional): ")).trim();
2187
+ const companyInput = (await rl.question("Company name (default: Acme Corp): ")).trim();
2188
+ const languageInput = (await rl.question(
2189
+ "Preferred language (en/es/fr/de/ja/zh/ko/ar/hi/pt, default: en): "
2190
+ )).trim();
2191
+ const learningStyleInput = (await rl.question(
2192
+ "Learning style (visual/auditory/kinesthetic/reading, default: visual): "
2193
+ )).trim();
2194
+ const paceInput = (await rl.question(
2195
+ "Learning pace (slow/moderate/fast/lightning, default: moderate): "
2196
+ )).trim();
2197
+ const focusInput = (await rl.question(
2198
+ "Learning focus (practical/theoretical/mixed, default: practical): "
2199
+ )).trim();
2200
+ const learningPathInput = (await rl.question(
2201
+ "Learning path (standard/accelerated/hands-on/theoretical, default: standard): "
2202
+ )).trim();
2203
+ const teamInput = (await rl.question("Team name (optional, press enter to skip): ")).trim();
2204
+ const projectInput = (await rl.question("Project name (optional, press enter to skip): ")).trim();
2205
+ const contextInput = (await rl.question(`Context path (default: ${process.cwd()}): `)).trim();
2206
+ const modeInput = (await rl.question(
2207
+ "Mode (development/staging/production, default: development): "
2208
+ )).trim().toLowerCase();
2209
+ const runWorkflow = (await rl.question("Run full workflow now? (Y/n): ")).trim().toLowerCase();
2210
+ const skipWorkflow = runWorkflow === "n" || runWorkflow === "no";
2211
+ return {
2212
+ name: nameInput || void 0,
2213
+ role: roleInput || void 0,
2214
+ email: emailInput || void 0,
2215
+ company: companyInput || void 0,
2216
+ language: languageInput || void 0,
2217
+ "learning-style": learningStyleInput || void 0,
2218
+ pace: paceInput || void 0,
2219
+ focus: focusInput || void 0,
2220
+ "learning-path": learningPathInput || void 0,
2221
+ team: teamInput || void 0,
2222
+ project: projectInput || void 0,
2223
+ context: contextInput || void 0,
2224
+ mode: modeInput || void 0,
2225
+ "skip-workflow": skipWorkflow
2226
+ };
2227
+ } finally {
2228
+ rl.close();
2229
+ }
2230
+ }
2231
+ function showStatus() {
2232
+ console.log(`
2233
+ Baseline Protocol v${VERSION}
2234
+ `);
2235
+ console.log("Layer Status:");
2236
+ console.log("-".repeat(60));
2237
+ const safeLine = (label, fn) => {
2238
+ try {
2239
+ console.log(` ${label.padEnd(10)}: ${fn()}`);
2240
+ } catch (err) {
2241
+ const msg = err instanceof Error ? err.message : String(err);
2242
+ console.log(` ${label.padEnd(10)}: error (${msg})`);
2243
+ }
2244
+ };
2245
+ safeLine("Lang", () => {
2246
+ const lang = new import_lang.BaselineLangSystem();
2247
+ const langCommands = lang.getCommandRegistry().size;
2248
+ return `initialized (${langCommands} commands registered)`;
2249
+ });
2250
+ safeLine("Frame", () => {
2251
+ const frame = new import_frame.BaselineFrameSystem();
2252
+ const frameStatus = frame.getStatus();
2253
+ return `${frameStatus.initialized ? "initialized" : "not initialized"} (mode: ${frameStatus.currentMode?.name ?? "default"})`;
2254
+ });
2255
+ safeLine("Studio", () => {
2256
+ const studio = new import_studio.BaselineStudioSystem();
2257
+ const studioStatus = studio.getStatus();
2258
+ return `initialized (${studioStatus.system})`;
2259
+ });
2260
+ safeLine("Govern", () => {
2261
+ const govern = new import_govern2.BaselineGovernSystem();
2262
+ const governStatus = govern.getStatus();
2263
+ return `${governStatus.initialized ? "initialized" : "not initialized"} (${governStatus.policies} policies)`;
2264
+ });
2265
+ safeLine("Experience", () => {
2266
+ const experience = new import_experience2.BaselineExperienceSystem();
2267
+ const expStatus = experience.getStatus();
2268
+ return `${expStatus.initialized ? "initialized" : "not initialized"}`;
2269
+ });
2270
+ safeLine("Autonomy", () => {
2271
+ const autonomy = new import_autonomy.BaselineAutonomySystem();
2272
+ const autoStatus = autonomy.getSystemStatus();
2273
+ return `${autoStatus.status} (${autoStatus.agentCount} agents)`;
2274
+ });
2275
+ safeLine("Persona", () => {
2276
+ const persona = new import_persona.BaselinePersonaEngine();
2277
+ const personaStatus = persona.getStatus();
2278
+ return `${personaStatus.initialized ? "initialized" : "not initialized"} (${personaStatus.totalPersonas} personas)`;
2279
+ });
2280
+ console.log("");
2281
+ console.log("All systems operational.");
2282
+ }
2283
+ main().catch((err) => {
2284
+ console.error("Fatal error:", err instanceof Error ? err.message : String(err));
2285
+ process.exit(1);
2286
+ });
2287
+ // Annotate the CommonJS export names for ESM import in node:
2288
+ 0 && (module.exports = {
2289
+ buildCommandLine
2290
+ });