# All files / lib/ast canonical.js

84.14% Statements 69/82
76.41% Branches 81/106
96.29% Functions 26/27
84.81% Lines 67/79

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460

    2x

    2x

    2x

    2x

    2x

    2x

    56x

    56x

    12x

    12x

    12x

    2x

    14x

    19x
    19x
    19x

    19x
    36x

    36x
    36x

    36x
    36x

    36x
    1x

    35x

    35x
    1x

    1x
    1x

    1x

    18x

    4x
    4x

    4x
    4x
    4x

    4x

    4x

    3x

    3x

    1x

    2x

    1x

    1x

    4x

    8x

    8x

    8x

    1x

    6x

    5x

    6x

    3x

    1x

    5x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

    11x

     /**
     * Canonical AST for Rosetta Configuration
     *
     * The Canonical AST represents the universal, IDE-agnostic configuration
     * that can be compiled to any IDE-specific format.
     */

    import { validateYAML, checkRequiredFields } from '../validation/schema-validator.js';
    import { diffObjects, mergeObjects, deepClone } from './utils.js';

    /**
     * Project type enumeration
     */
    export const ProjectType = {
      WEB_APP: 'web_app',
      API_SERVICE: 'api_service',
      CLI_TOOL: 'cli_tool',
      DATA_ML: 'data_ml',
      LIBRARY_SDK: 'library_sdk',
      INTERNAL_TOOLING: 'internal_tooling'
    };

    /**
     * Risk level enumeration
     */
    export const RiskLevel = {
      LOW: 'low',
      MEDIUM: 'medium',
      HIGH: 'high'
    };

    /**
     * Agent style enumeration
     */
    export const AgentStyle = {
      PAIR_PROGRAMMER: 'pair_programmer',
      AUTONOMOUS: 'autonomous',
      CONSERVATIVE: 'conservative'
    };

    /**
     * Agent scope enumeration
     */
    export const AgentScope = {
      CURRENT_FILE: 'current_file',
      MODULE: 'module',
      REPO: 'repo'
    };

    /**
     * Note category enumeration
     */
    export const NoteCategory = {
      DOMAIN_RULE: 'domain_rule',
      GOTCHA: 'gotcha',
      OPTIMIZATION: 'optimization',
      DEBUGGING: 'debugging'
    };

    /**
     * Default values for canonical configuration
     */
    const DEFAULTS = {
      schemaVersion: '1.0.0',
      project: {
        riskLevel: RiskLevel.MEDIUM
      },
      stack: {
        frontend: [],
        backend: [],
        datastores: [],
        testing: []
      },
      conventions: [],
      commands: {
        dev: [],
        test: [],
        build: []
      },
      agents: [],
      notes: [],
      ideOverrides: {},
      metadata: {}
    };

    /**
     * Canonical AST Class
     *
     * Represents the universal, IDE-agnostic configuration that can be
     * compiled to any IDE-specific format.
     */
    export class CanonicalAST {
      /**
       * Create a new Canonical AST
       * @param {Object} config - Configuration object
       */
      constructor(config = {}) {
        this._data = this._applyDefaults(config);
      }

      /**
       * Apply default values to configuration
       * @private
       */
      _applyDefaults(config) {
        return {
          schema_version: config.schema_version || DEFAULTS.schemaVersion,
          project: {
            name: config.project?.name || '',
            description: config.project?.description || '',
            type: config.project?.type || ProjectType.WEB_APP,
            risk_level: config.project?.riskLevel || config.project?.risk_level || DEFAULTS.project.riskLevel
          },
          stack: {
            language: config.stack?.language || '',
            frontend: config.stack?.frontend || [],
            backend: config.stack?.backend || [],
            datastores: config.stack?.datastores || [],
            testing: config.stack?.testing || []
          },
          conventions: config.conventions || [],
          commands: {
            dev: config.commands?.dev || [],
            test: config.commands?.test || [],
            build: config.commands?.build || []
          },
          agents: config.agents || [],
          notes: config.notes || [],
          ide_overrides: config.ideOverrides || config.ide_overrides || {},
          metadata: config.metadata || {}
        };
      }

      /**
       * Validate the AST against the schema
       * @returns {Object} Validation result with valid flag and errors
       */
      validate() {
        const quickCheck = checkRequiredFields(this._data);

        Iif (!quickCheck.valid) {
          return {
            valid: false,
            errors: [{
              path: '(root)',
              property: 'root',
              message: `Missing required fields: ${quickCheck.missing.join(', ')}`
            }]
          };
        }

        return validateYAML(this._data);
      }

      /**
       * Check if the AST is valid
       * @returns {boolean} True if valid
       */
      isValid() {
        return this.validate().valid;
      }

      /**
       * Get the raw data object
       * @returns {Object} The raw configuration data (deep clone)
       */
      toObject() {
        return deepClone(this._data);
      }

      /**
       * Get a specific value by path
       * @param {string} path - Dot-notation path with optional array indices (e.g., 'project.name', 'conventions[0].rules')
       * @returns {*} The value at the path
       */
      get(path) {
        Iif (!path) return undefined;
        const parts = path.split('.');
        let value = this._data;

        for (const part of parts) {
          Iif (!value || typeof value !== 'object') {
            return undefined;
          }

          // Parse bracket notation for array access (e.g., "arr[0]")
          const match = part.match(/^([^\[]+)(?:\[(\d+)\])?$/);
          Iif (!match) {
            return undefined;
          }

          const key = match[1];
          const index = match[2] !== undefined ? match[2] : null;

          // Access the key
          if (!(key in value)) {
            return undefined;
          }
          value = value[key];

          // If index provided, access array element
          if (index !== null) {
            Iif (!Array.isArray(value)) {
              return undefined;
            }
            const idx = parseInt(index, 10);
            Iif (idx < 0 || idx >= value.length) {
              return undefined;
            }
            value = value[idx];
          }
        }

        return value;
      }

      /**
       * Set a specific value by path
       * @param {string} path - Dot-notation path
       * @param {*} value - Value to set
       */
      set(path, value) {
        const parts = path.split('.');
        let obj = this._data;

        for (let i = 0; i < parts.length - 1; i++) {
          const part = parts[i];
          Iif (!(part in obj)) {
            obj[part] = {};
          }
          obj = obj[part];
        }

        obj[parts[parts.length - 1]] = value;
      }

      /**
       * Merge another AST into this one
       * @param {CanonicalAST} other - Another AST to merge
       * @param {string} strategy - Merge strategy: 'canonical', 'preserve', 'timestamp'
       * @returns {CanonicalAST} A new merged AST
       */
      merge(other, strategy = 'canonical') {
        const otherData = other.toObject();

        if (strategy === 'preserve') {
          // Keep existing values, only add new ones
          return new CanonicalAST(mergeObjects(this._data, otherData, 'preserve'));
        }

        if (strategy === 'timestamp') {
          // Use most recently modified
          return new CanonicalAST(mergeObjects(this._data, otherData, 'timestamp'));
        }

        // Default: canonical (prefer this AST)
        return new CanonicalAST(mergeObjects(this._data, otherData, 'canonical'));
      }

      /**
       * Diff this AST against another
       * @param {CanonicalAST} other - Another AST to compare
       * @returns {Object} Diff result
       */
      diff(other) {
        return diffObjects(this._data, other.toObject());
      }

      /**
       * Get the project name
       * @returns {string}
       */
      getProjectName() {
        return this._data.project?.name || '';
      }

      /**
       * Get the project type
       * @returns {string}
       */
      getProjectType() {
        return this._data.project?.type || ProjectType.WEB_APP;
      }

      /**
       * Get the primary language
       * @returns {string}
       */
      getLanguage() {
        return this._data.stack?.language || '';
      }

      /**
       * Get the risk level
       * @returns {string}
       */
      getRiskLevel() {
        return this._data.project?.risk_level || RiskLevel.MEDIUM;
      }

      /**
       * Get all conventions
       * @returns {Array}
       */
      getConventions() {
        return this._data.conventions || [];
      }

      /**
       * Get all agents
       * @returns {Array}
       */
      getAgents() {
        return this._data.agents || [];
      }

      /**
       * Get all notes
       * @returns {Array}
       */
      getNotes() {
        return this._data.notes || [];
      }

      /**
       * Get notes by category
       * @param {string} category - Note category
       * @returns {Array}
       */
      getNotesByCategory(category) {
        return (this._data.notes || []).filter(n => n.category === category);
      }

      /**
       * Get all commands object (dev, test, build)
       * @returns {Object} Commands object
       */
      getCommands() {
        return this._data.commands || { dev: [], test: [], build: [] };
      }

      /**
       * Get IDE overrides for a specific IDE
       * @param {string} ide - IDE identifier (claude, cursor, windsurf, etc.)
       * @returns {Object} IDE-specific overrides
       */
      getIDEOverrides(ide) {
        return this._data.ide_overrides?.[ide] || {};
      }

      /**
       * Add a note
       * @param {Object} note - Note object with title, category, content, priority
       */
      addNote(note) {
        Iif (!this._data.notes) {
          this._data.notes = [];
        }
        this._data.notes.push({
          title: note.title,
          category: note.category,
          content: note.content,
          priority: note.priority || 5
        });
      }

      /**
       * Add a convention
       * @param {Object} convention - Convention object with name and rules
       */
      addConvention(convention) {
        Iif (!this._data.conventions) {
          this._data.conventions = [];
        }
        this._data.conventions.push({
          name: convention.name,
          rules: convention.rules || [],
          examples: convention.examples || []
        });
      }

      /**
       * Add an agent
       * @param {Object} agent - Agent object with name, role, style, scope
       */
      addAgent(agent) {
        Iif (!this._data.agents) {
          this._data.agents = [];
        }
        this._data.agents.push({
          name: agent.name,
          role: agent.role,
          style: agent.style,
          scope: agent.scope,
          system_prompt: agent.systemPrompt
        });
      }

      /**
       * Set IDE overrides
       * @param {string} ide - IDE identifier
       * @param {Object} overrides - Override configuration
       */
      setIDEOverrides(ide, overrides) {
        Iif (!this._data.ide_overrides) {
          this._data.ide_overrides = {};
        }
        this._data.ide_overrides[ide] = overrides;
      }

      /**
       * Update metadata
       * @param {Object} metadata - Metadata to update
       */
      updateMetadata(metadata) {
        Iif (!this._data.metadata) {
          this._data.metadata = {};
        }
        Object.assign(this._data.metadata, metadata);
        // Always set updated_at to current timestamp
        this._data.metadata.updated_at = new Date().toISOString();
      }

      /**
       * Create a Canonical AST from a parsed YAML object
       * @param {Object} yamlObject - Parsed YAML object
       * @returns {CanonicalAST}
       */
      static fromYAML(yamlObject) {
        return new CanonicalAST(yamlObject);
      }

      /**
       * Create a minimal Canonical AST for a project type
       * @param {string} projectName - Project name
       * @param {string} projectType - Project type
       * @param {string} language - Primary language
       * @returns {CanonicalAST}
       */
      static createMinimal(projectName, projectType = ProjectType.WEB_APP, language = 'TypeScript') {
        return new CanonicalAST({
          project: {
            name: projectName,
            description: `${projectName} project`,
            type: projectType,
            riskLevel: RiskLevel.MEDIUM
          },
          stack: {
            language,
            frontend: [],
            backend: [],
            datastores: [],
            testing: []
          }
        });
      }
    }

    export default CanonicalAST;