Skip to content

Conversation

@ammokhov
Copy link
Contributor

@ammokhov ammokhov commented Nov 8, 2025

Issue #, if available:

Description of changes:

VS Code Extension Design

Overview

The VS Code extension integrates the Resource Schema Guard Rail tool as a language diagnostic provider. The extension will execute the Python CLI tool as a subprocess, parse its output, and display validation results as inline diagnostics in the editor. The architecture follows VS Code's extension model with a focus on simplicity and performance.

Architecture

High-Level Components

┌─────────────────────────────────────────────────────┐
│              VS Code Extension Host                  │
│                                                      │
│  ┌────────────────────────────────────────────┐    │
│  │         Extension Activation               │    │
│  │  - Register diagnostic provider            │    │
│  │  - Register commands                       │    │
│  │  - Set up file watchers                    │    │
│  └────────────────────────────────────────────┘    │
│                      │                              │
│                      ▼                              │
│  ┌────────────────────────────────────────────┐    │
│  │      Diagnostic Provider                   │    │
│  │  - Trigger validation on file events       │    │
│  │  - Debounce rapid changes                  │    │
│  │  - Manage diagnostic collection            │    │
│  └────────────────────────────────────────────┘    │
│                      │                              │
│                      ▼                              │
│  ┌────────────────────────────────────────────┐    │
│  │      Guard Rail Executor                   │    │
│  │  - Execute CLI as subprocess               │    │
│  │  - Parse JSON output                       │    │
│  │  - Handle errors and timeouts              │    │
│  └────────────────────────────────────────────┘    │
│                      │                              │
│                      ▼                              │
│  ┌────────────────────────────────────────────┐    │
│  │      Diagnostic Mapper                     │    │
│  │  - Convert results to VS Code diagnostics  │    │
│  │  - Map severity levels                     │    │
│  │  - Extract line/column information         │    │
│  └────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────┘
                      │
                      ▼
         ┌────────────────────────┐
         │   Python CLI Process   │
         │   guard-rail --schema  │
         │   (stateless mode)     │
         └────────────────────────┘

Components and Interfaces

1. Extension Entry Point (extension.ts)

Responsibilities:

  • Activate extension when JSON files are opened
  • Register diagnostic collection
  • Register command palette commands
  • Set up document change listeners

Key Functions:

export function activate(context: vscode.ExtensionContext): void
export function deactivate(): void

2. Diagnostic Provider (diagnosticProvider.ts)

Responsibilities:

  • Listen for document open, save, and change events
  • Debounce validation triggers (500ms delay)
  • Clear diagnostics when files are closed
  • Update status bar with validation summary

Key Functions:

class GuardRailDiagnosticProvider {
  provideDiagnostics(document: vscode.TextDocument): Promise<void>
  clearDiagnostics(document: vscode.TextDocument): void
  updateStatusBar(errorCount: number, warningCount: number): void
}

Debouncing Strategy:

  • Use a Map<string, NodeJS.Timeout> to track pending validations per file
  • Clear existing timeout when new change occurs
  • Execute validation after 500ms of inactivity

3. Guard Rail Executor (guardRailExecutor.ts)

Responsibilities:

  • Execute the Python CLI tool as a child process
  • Handle process lifecycle (spawn, timeout, kill)
  • Parse stdout/stderr
  • Return structured results

Key Functions:

interface GuardRailResult {
  compliant: string[];
  non_compliant: Record<string, GuardRuleResult[]>;
  warning: Record<string, GuardRuleResult[]>;
  skipped: string[];
}

interface GuardRuleResult {
  check_id: string;
  message: string;
  path: string;
}

class GuardRailExecutor {
  execute(schemaPath: string): Promise<GuardRailResult[]>
  findPythonExecutable(): string
  findGuardRailCli(): string
}

Execution Details:

  • Command: python -m src.cli --schema file://<path> --format
  • Timeout: 30 seconds
  • Working directory: Workspace root (to find the guard-rail package)
  • Output format: JSON (parsed from stdout)

Python Discovery:

  • Check for python3 command first
  • Fall back to python command
  • Validate that the command exists using which or where

CLI Discovery:

  • Assume the guard-rail tool is installed in the workspace
  • Use workspace root as the working directory
  • Execute as a Python module: python -m src.cli

4. Diagnostic Mapper (diagnosticMapper.ts)

Responsibilities:

  • Convert GuardRailResult to VS Code Diagnostic objects
  • Map severity (non_compliant → Error, warning → Warning)
  • Extract line numbers from path field
  • Format diagnostic messages

Key Functions:

class DiagnosticMapper {
  mapResults(results: GuardRailResult[], document: vscode.TextDocument): vscode.Diagnostic[]
  extractLineNumber(path: string, document: vscode.TextDocument): number
  createDiagnostic(rule: string, result: GuardRuleResult, line: number): vscode.Diagnostic
}

Path Parsing Strategy:
The path field from guard rail results contains JSON paths like:

  • /properties/Tags
  • /handlers/create/permissions[0]
  • Empty string for schema-level issues

To map to line numbers:

  1. Parse the JSON path
  2. Search the document text for the property at that path
  3. Return the line number where the property is defined
  4. If path is empty or not found, default to line 0

5. Command Handler (commands.ts)

Responsibilities:

  • Implement "Validate Schema" command
  • Check if active file is a JSON schema
  • Trigger validation manually

Key Functions:

function registerCommands(context: vscode.ExtensionContext, provider: GuardRailDiagnosticProvider): void

Data Models

GuardRailResult

interface GuardRailResult {
  compliant: string[];           // Rules that passed
  non_compliant: Record<string, GuardRuleResult[]>;  // Failed rules
  warning: Record<string, GuardRuleResult[]>;        // Warning rules
  skipped: string[];             // Not applicable rules
}

GuardRuleResult

interface GuardRuleResult {
  check_id: string;    // e.g., "TAG016"
  message: string;     // Human-readable error message
  path: string;        // JSON path to the issue, e.g., "/properties/Tags"
}

VS Code Diagnostic

// Built-in VS Code type
interface Diagnostic {
  range: Range;              // Line and column range
  message: string;           // Error message to display
  severity: DiagnosticSeverity;  // Error, Warning, Info, Hint
  source: string;            // "guard-rail"
  code?: string;             // Rule name or check_id
}

Error Handling

CLI Execution Errors

  1. Python Not Found

    • Display error notification: "Python not found. Please install Python to use Guard Rail validation."
    • Do not show diagnostics
  2. Guard Rail CLI Not Found

    • Display error notification: "Guard Rail CLI not found in workspace. Please ensure the tool is installed."
    • Do not show diagnostics
  3. Execution Timeout (>30s)

    • Kill the process
    • Display warning notification: "Guard Rail validation timed out."
    • Clear existing diagnostics
  4. Non-Zero Exit Code

    • Log stderr to output channel
    • Display error notification with stderr content
    • Do not update diagnostics
  5. JSON Parse Error

    • Log raw output to output channel
    • Display error notification: "Failed to parse Guard Rail output."
    • Do not update diagnostics

File System Errors

  1. File Not Saved

    • Skip validation for unsaved files
    • Show info message: "Save the file to run validation."
  2. File Too Large (>1GB)

    • Skip validation
    • Show warning: "File too large for validation."

Testing Strategy

Unit Tests

  1. Diagnostic Mapper Tests

    • Test path parsing for various JSON path formats
    • Test line number extraction
    • Test diagnostic creation with different severities
    • Test handling of empty paths
  2. Guard Rail Executor Tests

    • Mock child process execution
    • Test timeout handling
    • Test error handling for various failure modes
    • Test JSON parsing
  3. Diagnostic Provider Tests

    • Test debouncing logic
    • Test diagnostic clearing
    • Test status bar updates

Manual Testing Checklist

  1. Open a valid schema file → No diagnostics
  2. Open an invalid schema file → Diagnostics appear
  3. Edit file to introduce error → Diagnostics update after debounce
  4. Save file → Diagnostics refresh
  5. Close file → Diagnostics clear
  6. Run "Validate Schema" command → Diagnostics appear
  7. Check status bar → Shows error/warning count

File Structure

vscode-extension/
├── package.json
├── tsconfig.json
├── src/
│   ├── extension.ts              # Entry point
│   ├── diagnosticProvider.ts     # Diagnostic provider
│   ├── guardRailExecutor.ts      # CLI executor
│   ├── diagnosticMapper.ts       # Result mapper
│   ├── commands.ts               # Command handlers
│   └── types.ts                  # Type definitions
├── test/
│   ├── suite/
│   │   ├── diagnosticMapper.test.ts
│   │   ├── guardRailExecutor.test.ts
│   │   └── diagnosticProvider.test.ts
│   └── fixtures/
│       ├── valid-schema.json
│       └── invalid-schema.json
└── out/                          # Compiled JavaScript

Development Workflow

  1. Setup

    • Install Node.js and npm
    • Run npm install to install dependencies
    • Run npm run compile to build TypeScript
  2. Development

    • Run npm run watch for continuous compilation
    • Press F5 in VS Code to launch Extension Development Host
    • Test changes in the development host
  3. Testing

    • Run unit tests with npm test
    • Manual testing in Extension Development Host
    • Test with various schema files from the workspace
  4. Packaging

    • Run vsce package to create .vsix file
    • Install locally with code --install-extension guard-rail-vscode-0.1.0.vsix

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant