@baselineos/protocol-core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Baseline Lang -- Core Language Implementation
3
+ * The Language & Expression Layer of Baseline Stack
4
+ *
5
+ * @license Apache-2.0
6
+ */
7
+
8
+ import type { BaselineProgram } from '../types/index.js';
9
+ import type { BaselineParser } from '../parser/parser.js';
10
+ import type { BaselineLexicon } from '../lexicon/lexicon.js';
11
+
12
+ // ─── Result Types ───────────────────────────────────────────────────
13
+
14
+ export interface ValidationResult {
15
+ isValid: boolean;
16
+ errors: string[];
17
+ warnings: string[];
18
+ suggestions: string[];
19
+ }
20
+
21
+ export interface ExecutionResult {
22
+ success: boolean;
23
+ outputs: unknown[];
24
+ metrics: Record<string, unknown>;
25
+ timestamp: Date;
26
+ }
27
+
28
+ export interface IntermediateRepresentation {
29
+ version: string;
30
+ blocks: BaselineProgram['blocks'];
31
+ metadata: BaselineProgram['metadata'];
32
+ optimizations: unknown[];
33
+ }
34
+
35
+ export interface LanguageStats {
36
+ totalBlocks: number;
37
+ blockTypes: Record<string, number>;
38
+ lexiconSize: number;
39
+ patternCount: number;
40
+ templateCount: number;
41
+ complexity: 'low' | 'medium' | 'high' | 'complex';
42
+ }
43
+
44
+ // ─── BaselineLang ───────────────────────────────────────────────────
45
+
46
+ export class BaselineLang {
47
+ private parser: BaselineParser;
48
+ private lexicon: BaselineLexicon;
49
+
50
+ constructor(parser: BaselineParser, lexicon: BaselineLexicon) {
51
+ this.parser = parser;
52
+ this.lexicon = lexicon;
53
+ }
54
+
55
+ async initialize(): Promise<void> {
56
+ await this.initializeLanguageComponents();
57
+ await this.initializeDefaultLexicons();
58
+ await this.initializeLanguagePatterns();
59
+ }
60
+
61
+ /**
62
+ * Get the lexicon instance
63
+ */
64
+ getLexicon(): BaselineLexicon {
65
+ return this.lexicon;
66
+ }
67
+
68
+ /**
69
+ * Parse Baseline Language source code
70
+ */
71
+ async parseSource(source: string): Promise<BaselineProgram> {
72
+ try {
73
+ const program = await this.parser.parse(source);
74
+ return program;
75
+ } catch (error) {
76
+ const errorMessage = error instanceof Error ? error.message : String(error);
77
+ throw new Error(`Parsing failed: ${errorMessage}`);
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Compile Baseline Language to Intermediate Representation
83
+ */
84
+ async compileToIR(program: BaselineProgram): Promise<IntermediateRepresentation> {
85
+ try {
86
+ const ir = await this.compileProgram(program);
87
+ return ir;
88
+ } catch (error) {
89
+ const errorMessage = error instanceof Error ? error.message : String(error);
90
+ throw new Error(`Compilation failed: ${errorMessage}`);
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Execute Baseline Language program
96
+ */
97
+ async execute(program: BaselineProgram): Promise<ExecutionResult> {
98
+ try {
99
+ const ir = await this.compileToIR(program);
100
+ const result = await this.executeIR(ir);
101
+ return result;
102
+ } catch (error) {
103
+ const errorMessage = error instanceof Error ? error.message : String(error);
104
+ throw new Error(`Execution failed: ${errorMessage}`);
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Validate Baseline Language program
110
+ */
111
+ async validate(program: BaselineProgram): Promise<ValidationResult> {
112
+ try {
113
+ const validation = await this.validateProgram(program);
114
+ return validation;
115
+ } catch (error) {
116
+ const errorMessage = error instanceof Error ? error.message : String(error);
117
+ throw new Error(`Validation failed: ${errorMessage}`);
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Generate Baseline Language from template
123
+ */
124
+ async generateFromTemplate(
125
+ template: string,
126
+ variables: Record<string, unknown>,
127
+ ): Promise<string> {
128
+ try {
129
+ const generated = await this.generateLanguage(template, variables);
130
+ return generated;
131
+ } catch (error) {
132
+ const errorMessage = error instanceof Error ? error.message : String(error);
133
+ throw new Error(`Generation failed: ${errorMessage}`);
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Get language statistics and metrics
139
+ */
140
+ async getLanguageStats(): Promise<LanguageStats> {
141
+ try {
142
+ const stats = await this.calculateLanguageStats();
143
+ return stats;
144
+ } catch (error) {
145
+ const errorMessage = error instanceof Error ? error.message : String(error);
146
+ throw new Error(`Stats calculation failed: ${errorMessage}`);
147
+ }
148
+ }
149
+
150
+ // ─── Private Implementation ─────────────────────────────────────────
151
+
152
+ private async initializeLanguageComponents(): Promise<void> {
153
+ await this.initializeLexiconSystem();
154
+ await this.initializeSyntaxSystem();
155
+ await this.initializeCommandSystem();
156
+ }
157
+
158
+ private async initializeDefaultLexicons(): Promise<void> {
159
+ await this.lexicon.loadDefaultPacks();
160
+ }
161
+
162
+ private async initializeLanguagePatterns(): Promise<void> {
163
+ await this.initializePatterns();
164
+ }
165
+
166
+ private async initializeLexiconSystem(): Promise<void> {
167
+ // Initialize lexicon management system
168
+ }
169
+
170
+ private async initializeSyntaxSystem(): Promise<void> {
171
+ // Initialize syntax and grammar system
172
+ }
173
+
174
+ private async initializeCommandSystem(): Promise<void> {
175
+ // Initialize command and operation system
176
+ }
177
+
178
+ private async initializePatterns(): Promise<void> {
179
+ // Initialize language patterns
180
+ }
181
+
182
+ private async compileProgram(
183
+ program: BaselineProgram,
184
+ ): Promise<IntermediateRepresentation> {
185
+ return {
186
+ version: '1.0.0',
187
+ blocks: program.blocks,
188
+ metadata: program.metadata,
189
+ optimizations: [],
190
+ };
191
+ }
192
+
193
+ private async executeIR(_ir: IntermediateRepresentation): Promise<ExecutionResult> {
194
+ return {
195
+ success: true,
196
+ outputs: [],
197
+ metrics: {},
198
+ timestamp: new Date(),
199
+ };
200
+ }
201
+
202
+ private async validateProgram(program: BaselineProgram): Promise<ValidationResult> {
203
+ const validation: ValidationResult = {
204
+ isValid: true,
205
+ errors: [],
206
+ warnings: [],
207
+ suggestions: [],
208
+ };
209
+
210
+ if (!program.blocks || program.blocks.length === 0) {
211
+ validation.isValid = false;
212
+ validation.errors.push('Program must contain at least one block');
213
+ }
214
+
215
+ if (!program.metadata) {
216
+ validation.isValid = false;
217
+ validation.errors.push('Program must have metadata');
218
+ }
219
+
220
+ for (const block of program.blocks) {
221
+ const blockValidation = await this.validateBlock(block);
222
+ if (!blockValidation.isValid) {
223
+ validation.isValid = false;
224
+ validation.errors.push(...blockValidation.errors);
225
+ }
226
+ validation.warnings.push(...blockValidation.warnings);
227
+ validation.suggestions.push(...blockValidation.suggestions);
228
+ }
229
+
230
+ return validation;
231
+ }
232
+
233
+ private async validateBlock(
234
+ block: BaselineProgram['blocks'][number],
235
+ ): Promise<ValidationResult> {
236
+ const validation: ValidationResult = {
237
+ isValid: true,
238
+ errors: [],
239
+ warnings: [],
240
+ suggestions: [],
241
+ };
242
+
243
+ if (!block.type) {
244
+ validation.isValid = false;
245
+ validation.errors.push('Block must have a type');
246
+ }
247
+
248
+ if (!block.metadata) {
249
+ validation.isValid = false;
250
+ validation.errors.push('Block must have metadata');
251
+ }
252
+
253
+ return validation;
254
+ }
255
+
256
+ private async generateLanguage(
257
+ template: string,
258
+ variables: Record<string, unknown>,
259
+ ): Promise<string> {
260
+ let generated = template;
261
+ for (const [key, value] of Object.entries(variables)) {
262
+ const placeholder = `{{${key}}}`;
263
+ generated = generated.replace(new RegExp(placeholder, 'g'), String(value));
264
+ }
265
+ return generated;
266
+ }
267
+
268
+ private async calculateLanguageStats(): Promise<LanguageStats> {
269
+ return {
270
+ totalBlocks: 0,
271
+ blockTypes: {},
272
+ lexiconSize: 0,
273
+ patternCount: 0,
274
+ templateCount: 0,
275
+ complexity: 'low',
276
+ };
277
+ }
278
+ }
@@ -0,0 +1,414 @@
1
+ /**
2
+ * Baseline Language Lexicon Management
3
+ * Domain-specific vocabulary and template system
4
+ *
5
+ * @license Apache-2.0
6
+ */
7
+
8
+ // ─── Lexicon Types ──────────────────────────────────────────────────
9
+
10
+ export interface LexiconDomain {
11
+ name: string;
12
+ description: string;
13
+ vocabulary: string[];
14
+ patterns: string[];
15
+ examples: string[];
16
+ }
17
+
18
+ export interface LexiconTerm {
19
+ name: string;
20
+ definition: string;
21
+ synonyms: string[];
22
+ antonyms: string[];
23
+ examples: string[];
24
+ }
25
+
26
+ export interface LexiconVocabulary {
27
+ terms: LexiconTerm[];
28
+ synonyms: unknown[];
29
+ antonyms: unknown[];
30
+ definitions: LexiconDefinition[];
31
+ }
32
+
33
+ export interface LexiconDefinition {
34
+ meaning: string;
35
+ context: string;
36
+ examples: string[];
37
+ }
38
+
39
+ export interface LexiconTemplate {
40
+ name: string;
41
+ description: string;
42
+ pattern: string;
43
+ variables: LexiconVariable[];
44
+ examples: string[];
45
+ }
46
+
47
+ export interface LexiconVariable {
48
+ name: string;
49
+ type: string;
50
+ description: string;
51
+ required: boolean;
52
+ default?: string;
53
+ }
54
+
55
+ export interface LexiconPattern {
56
+ name: string;
57
+ description: string;
58
+ regex: string;
59
+ examples: string[];
60
+ usage: string[];
61
+ }
62
+
63
+ export interface SearchResult {
64
+ type: 'term' | 'definition';
65
+ domain: string;
66
+ item: LexiconTerm | LexiconDefinition;
67
+ relevance: number;
68
+ }
69
+
70
+ export interface LexiconStats {
71
+ totalDomains: number;
72
+ totalTerms: number;
73
+ totalTemplates: number;
74
+ totalPatterns: number;
75
+ domains: string[];
76
+ vocabularySizes: Record<string, number>;
77
+ }
78
+
79
+ // ─── Lexicon ────────────────────────────────────────────────────────
80
+
81
+ export class BaselineLexicon {
82
+ private domains: Map<string, LexiconDomain> = new Map();
83
+ private vocabulary: Map<string, LexiconVocabulary> = new Map();
84
+ private templates: Map<string, LexiconTemplate> = new Map();
85
+ private patterns: Map<string, LexiconPattern> = new Map();
86
+
87
+ async initialize(): Promise<void> {
88
+ await this.initializeDefaultDomains();
89
+ await this.initializeDefaultVocabulary();
90
+ await this.initializeDefaultTemplates();
91
+ await this.initializeDefaultPatterns();
92
+ }
93
+
94
+ /**
95
+ * Load default lexicon packs
96
+ */
97
+ async loadDefaultPacks(): Promise<void> {
98
+ await this.loadCoreDomainPack();
99
+ await this.loadAIMLDomainPack();
100
+ await this.loadBusinessDomainPack();
101
+ }
102
+
103
+ /**
104
+ * Add a new domain
105
+ */
106
+ addDomain(domain: LexiconDomain): void {
107
+ this.domains.set(domain.name, domain);
108
+ }
109
+
110
+ /**
111
+ * Get domain by name
112
+ */
113
+ getDomain(name: string): LexiconDomain | undefined {
114
+ return this.domains.get(name);
115
+ }
116
+
117
+ /**
118
+ * List all domains
119
+ */
120
+ listDomains(): LexiconDomain[] {
121
+ return Array.from(this.domains.values());
122
+ }
123
+
124
+ /**
125
+ * Add vocabulary set
126
+ */
127
+ addVocabulary(domain: string, vocabulary: LexiconVocabulary): void {
128
+ this.vocabulary.set(domain, vocabulary);
129
+ }
130
+
131
+ /**
132
+ * Get vocabulary for domain
133
+ */
134
+ getVocabulary(domain: string): LexiconVocabulary | undefined {
135
+ return this.vocabulary.get(domain);
136
+ }
137
+
138
+ /**
139
+ * Add template
140
+ */
141
+ addTemplate(template: LexiconTemplate): void {
142
+ this.templates.set(template.name, template);
143
+ }
144
+
145
+ /**
146
+ * Get template by name
147
+ */
148
+ getTemplate(name: string): LexiconTemplate | undefined {
149
+ return this.templates.get(name);
150
+ }
151
+
152
+ /**
153
+ * List all templates
154
+ */
155
+ listTemplates(): LexiconTemplate[] {
156
+ return Array.from(this.templates.values());
157
+ }
158
+
159
+ /**
160
+ * Add pattern
161
+ */
162
+ addPattern(pattern: LexiconPattern): void {
163
+ this.patterns.set(pattern.name, pattern);
164
+ }
165
+
166
+ /**
167
+ * Get pattern by name
168
+ */
169
+ getPattern(name: string): LexiconPattern | undefined {
170
+ return this.patterns.get(name);
171
+ }
172
+
173
+ /**
174
+ * List all patterns
175
+ */
176
+ listPatterns(): LexiconPattern[] {
177
+ return Array.from(this.patterns.values());
178
+ }
179
+
180
+ /**
181
+ * Search vocabulary across domains
182
+ */
183
+ searchVocabulary(query: string, domain?: string): SearchResult[] {
184
+ const results: SearchResult[] = [];
185
+ const searchDomains = domain ? [domain] : Array.from(this.vocabulary.keys());
186
+
187
+ for (const searchDomain of searchDomains) {
188
+ const vocab = this.vocabulary.get(searchDomain);
189
+ if (vocab) {
190
+ for (const term of vocab.terms) {
191
+ if (
192
+ this.matchesSearch(term.name, query) ||
193
+ this.matchesSearch(term.definition, query)
194
+ ) {
195
+ results.push({
196
+ type: 'term',
197
+ domain: searchDomain,
198
+ item: term,
199
+ relevance: this.calculateRelevance(term.name, query),
200
+ });
201
+ }
202
+ }
203
+
204
+ for (const definition of vocab.definitions) {
205
+ if (this.matchesSearch(definition.meaning, query)) {
206
+ results.push({
207
+ type: 'definition',
208
+ domain: searchDomain,
209
+ item: definition,
210
+ relevance: this.calculateRelevance(definition.meaning, query),
211
+ });
212
+ }
213
+ }
214
+ }
215
+ }
216
+
217
+ results.sort((a, b) => b.relevance - a.relevance);
218
+ return results;
219
+ }
220
+
221
+ /**
222
+ * Get lexicon statistics
223
+ */
224
+ getLexiconStats(): LexiconStats {
225
+ return {
226
+ totalDomains: this.domains.size,
227
+ totalTerms: Array.from(this.vocabulary.values()).reduce(
228
+ (sum, vocab) => sum + vocab.terms.length,
229
+ 0,
230
+ ),
231
+ totalTemplates: this.templates.size,
232
+ totalPatterns: this.patterns.size,
233
+ domains: Array.from(this.domains.keys()),
234
+ vocabularySizes: Object.fromEntries(
235
+ Array.from(this.vocabulary.entries()).map(([d, vocab]) => [d, vocab.terms.length]),
236
+ ),
237
+ };
238
+ }
239
+
240
+ // ─── Default Initialization ─────────────────────────────────────────
241
+
242
+ private async initializeDefaultDomains(): Promise<void> {
243
+ this.addDomain({
244
+ name: 'core',
245
+ description: 'Core Baseline Language concepts and vocabulary',
246
+ vocabulary: ['program', 'block', 'metadata', 'type', 'content'],
247
+ patterns: ['structure', 'validation', 'execution'],
248
+ examples: ['lang { ... }', 'frame { ... }', 'core { ... }'],
249
+ });
250
+
251
+ this.addDomain({
252
+ name: 'ai-ml',
253
+ description: 'Artificial Intelligence and Machine Learning concepts',
254
+ vocabulary: ['model', 'training', 'inference', 'accuracy', 'precision'],
255
+ patterns: ['supervised', 'unsupervised', 'reinforcement'],
256
+ examples: ['model { type: "llm", version: "1.0" }'],
257
+ });
258
+
259
+ this.addDomain({
260
+ name: 'business',
261
+ description: 'Business and enterprise concepts',
262
+ vocabulary: ['kpi', 'metric', 'goal', 'deliverable', 'success'],
263
+ patterns: ['measurement', 'tracking', 'reporting'],
264
+ examples: ['goal { name: "revenue", target: 1000000 }'],
265
+ });
266
+ }
267
+
268
+ private async initializeDefaultVocabulary(): Promise<void> {
269
+ this.addVocabulary('core', {
270
+ terms: [
271
+ {
272
+ name: 'program',
273
+ definition: 'A complete Baseline Language program',
274
+ synonyms: ['script', 'code', 'application'],
275
+ antonyms: [],
276
+ examples: ['Complete program structure'],
277
+ },
278
+ {
279
+ name: 'block',
280
+ definition: 'A logical section of a Baseline Language program',
281
+ synonyms: ['section', 'module', 'component'],
282
+ antonyms: [],
283
+ examples: ['lang block', 'frame block', 'core block'],
284
+ },
285
+ ],
286
+ synonyms: [],
287
+ antonyms: [],
288
+ definitions: [],
289
+ });
290
+
291
+ this.addVocabulary('ai-ml', {
292
+ terms: [
293
+ {
294
+ name: 'model',
295
+ definition: 'An AI or ML model for processing',
296
+ synonyms: ['algorithm', 'system', 'engine'],
297
+ antonyms: [],
298
+ examples: ['LLM model', 'NLP model', 'Vision model'],
299
+ },
300
+ ],
301
+ synonyms: [],
302
+ antonyms: [],
303
+ definitions: [],
304
+ });
305
+ }
306
+
307
+ private async initializeDefaultTemplates(): Promise<void> {
308
+ this.addTemplate({
309
+ name: 'basic-program',
310
+ description: 'Basic Baseline Language program structure',
311
+ pattern:
312
+ 'lang { lexicon { ... } }\nframe { intent { ... } }\ncore { fidelity { ... } }',
313
+ variables: [
314
+ {
315
+ name: 'programName',
316
+ type: 'string',
317
+ description: 'Name of the program',
318
+ required: true,
319
+ },
320
+ {
321
+ name: 'description',
322
+ type: 'string',
323
+ description: 'Program description',
324
+ required: false,
325
+ },
326
+ ],
327
+ examples: ['Basic program with lexicon, intent, and fidelity'],
328
+ });
329
+
330
+ this.addTemplate({
331
+ name: 'intent-block',
332
+ description: 'Intent block with goals and deliverables',
333
+ pattern:
334
+ 'intent {\n goal {{goalName}} {\n description: "{{goalDescription}}"\n priority: "{{priority}}"\n }\n}',
335
+ variables: [
336
+ {
337
+ name: 'goalName',
338
+ type: 'string',
339
+ description: 'Name of the goal',
340
+ required: true,
341
+ },
342
+ {
343
+ name: 'goalDescription',
344
+ type: 'string',
345
+ description: 'Description of the goal',
346
+ required: true,
347
+ },
348
+ {
349
+ name: 'priority',
350
+ type: 'string',
351
+ description: 'Priority level',
352
+ required: false,
353
+ default: 'medium',
354
+ },
355
+ ],
356
+ examples: ['Intent block with defined goal and priority'],
357
+ });
358
+ }
359
+
360
+ private async initializeDefaultPatterns(): Promise<void> {
361
+ this.addPattern({
362
+ name: 'block-structure',
363
+ description: 'Standard block structure pattern',
364
+ regex: '^[a-zA-Z_][a-zA-Z0-9_]*\\s*\\{[^}]*\\}$',
365
+ examples: ['lang { ... }', 'frame { ... }', 'core { ... }'],
366
+ usage: ['Program blocks', 'Content blocks', 'Configuration blocks'],
367
+ });
368
+
369
+ this.addPattern({
370
+ name: 'validation-rule',
371
+ description: 'Validation rule pattern',
372
+ regex: '^validation\\s+[a-zA-Z_][a-zA-Z0-9_]*\\s*\\{[^}]*\\}$',
373
+ examples: ['validation required { ... }', 'validation format { ... }'],
374
+ usage: ['Input validation', 'Data validation', 'Format validation'],
375
+ });
376
+ }
377
+
378
+ private async loadCoreDomainPack(): Promise<void> {
379
+ // Core domain pack — extensible for additional core vocabulary
380
+ }
381
+
382
+ private async loadAIMLDomainPack(): Promise<void> {
383
+ // AI/ML domain pack — extensible for ML-specific vocabulary
384
+ }
385
+
386
+ private async loadBusinessDomainPack(): Promise<void> {
387
+ // Business domain pack — extensible for business vocabulary
388
+ }
389
+
390
+ // ─── Search Utilities ─────────────────────────────────────────────
391
+
392
+ private matchesSearch(text: string, query: string): boolean {
393
+ return text.toLowerCase().includes(query.toLowerCase());
394
+ }
395
+
396
+ private calculateRelevance(text: string, query: string): number {
397
+ const textLower = text.toLowerCase();
398
+ const queryLower = query.toLowerCase();
399
+
400
+ if (textLower === queryLower) return 1.0;
401
+ if (textLower.startsWith(queryLower)) return 0.9;
402
+ if (textLower.includes(queryLower)) return 0.7;
403
+
404
+ const textWords = textLower.split(/\s+/);
405
+ const queryWords = queryLower.split(/\s+/);
406
+ let matches = 0;
407
+ for (const queryWord of queryWords) {
408
+ if (textWords.some((textWord) => textWord.includes(queryWord))) {
409
+ matches++;
410
+ }
411
+ }
412
+ return (matches / queryWords.length) * 0.5;
413
+ }
414
+ }