File size: 12,405 Bytes
096d5ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
 * universal-symbolics-harmonizer.ts
 * 
 * Core grammar harmonization engine for Universal Symbolics.
 * Provides bidirectional translation between all symbolic grammars.
 */

import {
  ModelVendor,
  SymbolicPrimitive,
  GrammarStyle,
  SymbolicOperation,
  VendorImplementation,
  SYMBOLIC_RUNTIME_SCHEMA
} from './universal-symbolics-runtime';

import { SymbolicsRegistry } from './universal-symbolics-registry';

/**
 * Translation options for symbolic grammar harmonization
 */
export interface HarmonizationOptions {
  preserveStructure?: boolean;        // Maintain structural elements during translation
  adaptToCapabilities?: boolean;      // Adapt operations to target vendor capabilities
  includeComments?: boolean;          // Include comments about the translation
  embedTraceability?: boolean;        // Embed source tracking in translation
  formatOutput?: boolean;             // Apply formatting to the output
  handleResidue?: boolean;            // Handle and report symbolic residue
  fallbackBehavior?: 'omit' | 'emulate' | 'comment'; // How to handle unsupported operations
}

/**
 * Result of a harmonization operation
 */
export interface HarmonizationResult {
  transformed: string;                // Transformed content
  originalVendor: ModelVendor;        // Source vendor
  targetVendor: ModelVendor;          // Target vendor
  operations: {                       // Operations that were transformed
    original: SymbolicPrimitive;
    target: SymbolicPrimitive | null;
    success: boolean;
    message?: string;
  }[];
  residue: {                          // Symbolic residue detected
    pattern: string;
    position: number;
    possiblePrimitive?: SymbolicPrimitive;
  }[];
  metrics: {                          // Metrics about the transformation
    totalOperations: number;
    successfulOperations: number;
    unsupportedOperations: number;
    adaptedOperations: number;
  };
}

/**
 * Symbolic Grammar Harmonizer
 * 
 * Provides bidirectional translation between all symbolic grammars
 * across different model vendors.
 */
export class SymbolicHarmonizer {
  private registry: SymbolicsRegistry;
  
  constructor(registry?: SymbolicsRegistry) {
    this.registry = registry || new SymbolicsRegistry();
  }
  
  /**
   * Harmonize content from source vendor to target vendor
   */
  public harmonize(
    content: string,
    sourceVendor: ModelVendor,
    targetVendor: ModelVendor,
    options: HarmonizationOptions = {}
  ): HarmonizationResult {
    // Default options
    const opts: Required<HarmonizationOptions> = {
      preserveStructure: options.preserveStructure !== undefined ? options.preserveStructure : true,
      adaptToCapabilities: options.adaptToCapabilities !== undefined ? options.adaptToCapabilities : true,
      includeComments: options.includeComments !== undefined ? options.includeComments : false,
      embedTraceability: options.embedTraceability !== undefined ? options.embedTraceability : false,
      formatOutput: options.formatOutput !== undefined ? options.formatOutput : true,
      handleResidue: options.handleResidue !== undefined ? options.handleResidue : true,
      fallbackBehavior: options.fallbackBehavior || 'emulate'
    };
    
    // Initialize result
    const result: HarmonizationResult = {
      transformed: '',
      originalVendor: sourceVendor,
      targetVendor: targetVendor,
      operations: [],
      residue: [],
      metrics: {
        totalOperations: 0,
        successfulOperations: 0,
        unsupportedOperations: 0,
        adaptedOperations: 0
      }
    };
    
    // Special case: same vendor, just return the content
    if (sourceVendor === targetVendor) {
      result.transformed = content;
      return result;
    }
    
    // Handle symbolic residue if enabled
    if (opts.handleResidue) {
      result.residue = this.registry.findSymbolicResidue(content, sourceVendor);
      
      // Only attempt repair if there is residue
      if (result.residue.length > 0) {
        content = this.registry.repairSymbolicResidue(content, sourceVendor);
      }
    }
    
    // Extract symbolic operations from source content
    const extractedOperations = this.registry.extractAllSymbolicOperations(content, sourceVendor);
    result.metrics.totalOperations = extractedOperations.length;
    
    // Build a map of operation positions to maintain structure
    const operationPositions = this.mapOperationPositions(content, sourceVendor);
    
    // Process each operation
    const operationResults: { primitive: SymbolicPrimitive, params: any, success: boolean, message?: string, transformed?: string }[] = [];
    
    for (const { primitive, params } of extractedOperations) {
      const operationResult = this.transformOperation(primitive, params, sourceVendor, targetVendor, opts);
      operationResults.push({
        primitive,
        params,
        success: operationResult.success,
        message: operationResult.message,
        transformed: operationResult.transformed
      });
      
      // Update metrics
      if (operationResult.success) {
        result.metrics.successfulOperations++;
        
        if (operationResult.adapted) {
          result.metrics.adaptedOperations++;
        }
      } else {
        result.metrics.unsupportedOperations++;
      }
      
      // Update operations log
      result.operations.push({
        original: primitive,
        target: operationResult.targetPrimitive,
        success: operationResult.success,
        message: operationResult.message
      });
    }
    
    // Generate transformed content
    result.transformed = this.generateTransformedContent(
      content,
      operationPositions,
      operationResults,
      sourceVendor,
      targetVendor,
      opts
    );
    
    // Apply formatting if enabled
    if (opts.formatOutput) {
      result.transformed = this.formatOutput(result.transformed, targetVendor);
    }
    
    return result;
  }
  
  /**
   * Transform a single symbolic operation from source to target vendor
   */
  private transformOperation(
    primitive: SymbolicPrimitive,
    params: any,
    sourceVendor: ModelVendor,
    targetVendor: ModelVendor,
    options: Required<HarmonizationOptions>
  ): {
    success: boolean;
    message?: string;
    transformed?: string;
    targetPrimitive: SymbolicPrimitive | null;
    adapted: boolean;
  } {
    // Check if target vendor supports this primitive
    const targetSupport = this.registry.vendorSupports(targetVendor, primitive);
    
    // If not supported and adaptation is enabled, try to find a similar primitive
    let targetPrimitive = primitive;
    let adapted = false;
    
    if (!targetSupport && options.adaptToCapabilities) {
      const alternativePrimitive = this.findAlternativePrimitive(primitive, targetVendor);
      
      if (alternativePrimitive) {
        targetPrimitive = alternativePrimitive;
        adapted = true;
      }
    }
    
    // Check support for the (possibly adapted) target primitive
    const finalSupport = this.registry.vendorSupports(targetVendor, targetPrimitive);
    
    if (!finalSupport) {
      // Handle based on fallback behavior
      switch (options.fallbackBehavior) {
        case 'omit':
          return {
            success: false,
            message: `Operation ${primitive} not supported by ${targetVendor} and omitted`,
            targetPrimitive: null,
            adapted: false
          };
        
        case 'comment':
          return {
            success: false,
            message: `Operation ${primitive} not supported by ${targetVendor}`,
            transformed: this.generateCommentForUnsupported(primitive, params, sourceVendor, targetVendor),
            targetPrimitive: null,
            adapted: false
          };
        
        case 'emulate':
          // Try to emulate even if not natively supported
          const emulatedTransformation = this.emulateOperation(primitive, params, sourceVendor, targetVendor);
          
          if (emulatedTransformation) {
            return {
              success: true,
              message: `Operation ${primitive} emulated for ${targetVendor}`,
              transformed: emulatedTransformation,
              targetPrimitive: targetPrimitive,
              adapted: true
            };
          }
          
          // Fall through to comment if emulation is not possible
          return {
            success: false,
            message: `Operation ${primitive} not supported by ${targetVendor} and cannot be emulated`,
            transformed: this.generateCommentForUnsupported(primitive, params, sourceVendor, targetVendor),
            targetPrimitive: null,
            adapted: false
          };
      }
    }
    
    // Transform the operation
    const implementation = this.registry.getVendorImplementation(targetPrimitive, targetVendor);
    if (!implementation) {
      return {
        success: false,
        message: `Could not find implementation for ${targetPrimitive} in ${targetVendor}`,
        targetPrimitive: null,
        adapted: false
      };
    }
    
    // If adaptation occurred, adapt the parameters
    let adaptedParams = params;
    if (adapted) {
      adaptedParams = this.adaptParameters(params, primitive, targetPrimitive);
    }
    
    // Generate the transformation
    const transformed = this.generateTransformation(targetPrimitive, adaptedParams, implementation);
    
    // Add comments or traceability if enabled
    let finalTransformed = transformed;
    
    if (options.includeComments) {
      finalTransformed = this.addComments(transformed, primitive, sourceVendor, targetPrimitive, targetVendor, adapted);
    }
    
    if (options.embedTraceability) {
      finalTransformed = this.embedTraceability(finalTransformed, primitive, sourceVendor, targetVendor);
    }
    
    return {
      success: true,
      message: adapted ? `Operation ${primitive} adapted to ${targetPrimitive} for ${targetVendor}` : undefined,
      transformed: finalTransformed,
      targetPrimitive: targetPrimitive,
      adapted: adapted
    };
  }
  
  /**
   * Map positions of operations in source content
   */
  private mapOperationPositions(content: string, vendor: ModelVendor): Map<SymbolicPrimitive, number[]> {
    const positions = new Map<SymbolicPrimitive, number[]>();
    
    // Initialize positions for all primitives
    for (const primitive of Object.values(SymbolicPrimitive)) {
      positions.set(primitive, []);
    }
    
    // Map positions based on vendor's grammar style
    switch (vendor) {
      case ModelVendor.ANTHROPIC:
        // Map XML tags
        for (const primitive of Object.values(SymbolicPrimitive)) {
          const implementation = this.registry.getVendorImplementation(primitive, vendor);
          if (!implementation || implementation.style !== GrammarStyle.XML_TAGS) continue;
          
          if (implementation.prefix && implementation.suffix) {
            const regex = new RegExp(`${escapeRegExp(implementation.prefix)}[\\s\\S]*?${escapeRegExp(implementation.suffix)}`, 'g');
            let match;
            const primitivePositions = positions.get(primitive) || [];
            
            while ((match = regex.exec(content)) !== null) {
              primitivePositions.push(match.index);
            }
            
            positions.set(primitive, primitivePositions);
          }
        }
        break;
      
      case ModelVendor.QWEN:
      case ModelVendor.OPENAI:
        // Map slash commands
        for (const primitive of Object.values(SymbolicPrimitive)) {
          const implementation = this.registry.getVendorImplementation(primitive, vendor);
          if (!implementation || implementation.style !== GrammarStyle.SLASH_COMMANDS) continue;
          
          if (implementation.prefix) {
            const regex = new RegExp(`${escapeRegExp(implementation.prefix)}\\s+[^\\n]*`, 'g');
            let match;
            const primitivePositions = positions.get(primitive) || [];
            
            while ((match = regex.exec(content)) !== null) {
              primitivePositions.push(match.index);
            }
            
            positions.set(primitive, primitivePositions);
          }
        }
        break;
      
      // Add more cases for other vendors
    }
    
    return positions;
  }