src — utils

Module: src-utils Cohesion: 0.80 Members: 0

src — utils

The src/utils module is a foundational collection of shared, reusable utilities that support various functionalities across the Code Buddy application. It encapsulates common patterns, external integrations, and core logic that would otherwise be duplicated throughout the codebase.

This document details the purpose, key components, and integration points for each utility within this module.


Module Overview

The src/utils module provides:


Utilities Reference

approval-pattern-tracker.ts

This utility implements a pattern-based learning system for user approvals. It observes repeated approvals of specific tool commands and, after a configurable threshold, can silently auto-approve them in the future. This enhances the user experience by reducing repetitive confirmation prompts for trusted actions.

Key Components:

How it Works:

  1. When recordApproval is called, normalizeArgs converts the tool's arguments into a consistent string pattern.
  2. This pattern, combined with the tool name, forms a unique key.
  3. The approvalCount for this key is incremented. If it reaches DEFAULT_THRESHOLD (default 3), the pattern is considered "learned."
  4. Patterns are saved to a JSON file in the .codebuddy directory within the current working directory.
  5. shouldAutoApprove checks if a pattern exists and its approvalCount meets the threshold, indicating it can be silently approved.

Integration:

The ApprovalPatternTracker is primarily used by the ConfirmationService to decide whether a user action can be automatically approved without explicit user input.

ascii-banner.ts

A simple utility for generating ASCII art banners, primarily used for displaying application branding or important messages in the terminal. It serves as a lightweight, MIT-licensed alternative to more complex ASCII art libraries.

Key Components:

How it Works:

For block fonts, renderBanner iterates through the input text, looking up each character in BLOCK_FONT. It then concatenates the corresponding ASCII art lines horizontally to form the complete banner. Alignment is handled by calculating padding based on terminal width. renderColorBanner splits the banner into lines and applies ANSI color codes in a gradient.

Integration:

Used at application startup to display the "GROK" banner and potentially for other significant informational messages.

autonomy-manager.ts

The AutonomyManager is a critical component for controlling the AI agent's level of autonomy and determining when user confirmation is required for operations. It supports various autonomy levels, including a "YOLO" mode with extensive guardrails.

Key Components:

How it Works:

  1. Configuration Loading: On instantiation, AutonomyManager loads its configuration from .codebuddy/autonomy.json, merging with DEFAULT_YOLO_CONFIG and DEFAULT_DANGEROUS_OPERATIONS/DEFAULT_SAFE_OPERATIONS.
  2. General Autonomy (shouldConfirm):

  1. YOLO Mode (shouldYOLOExecute):

  1. Path Validation (isPathAllowedForYOLO): Checks if a given file path matches any blockedPaths or is not within allowedPaths (if specified).

Integration:

The AutonomyManager is a core dependency of the ConfirmationService, which uses its shouldConfirm and shouldYOLOExecute methods to decide whether to prompt the user for approval or proceed automatically. It also uses logger for warnings and fs-extra for file operations.

graph TD
    A[ConfirmationService] --> B{AutonomyManager.shouldConfirm};
    B --> C{Is YOLO Enabled?};
    C -- Yes --> D{AutonomyManager.shouldYOLOExecute};
    C -- No --> E{Check AutonomyLevel};
    D -- Allowed --> F[Auto-Approve];
    D -- Blocked --> G[Require User Confirmation];
    E -- Requires Confirmation --> G;
    E -- Auto-Approved --> F;
    F --> H[Proceed with Operation];
    G --> I[Wait for User Input];
    I -- Confirmed --> H;
    I -- Rejected --> J[Cancel Operation];

    subgraph YOLO Mode Checks
        D --> D1[Is Paused?];
        D1 -- No --> D2[Is Dry-Run?];
        D2 -- No --> D3[Check Tool Rules];
        D3 --> D4[Check Deny List];
        D4 --> D5[Check Safe Mode];
        D5 --> D6[Check Session Limits];
        D6 --> D7[Check Allow List];
        D7 --> D8[Check Dangerous Operations];
    end

base-url.ts

Provides functionality to normalize and validate API base URLs, ensuring they conform to expected formats and security practices.

Key Components:

How it Works:

It leverages Node.js's built-in URL class for robust parsing and then applies a series of checks to enforce specific constraints suitable for an API base URL.

Integration:

Likely used by API client configurations or settings managers to ensure that any custom base URL provided by the user is valid before being used.

batch-review-service.ts

This service consolidates multiple file changes (creations, edits, deletions) made by an AI agent into a single batch for user review. Instead of prompting for each individual file, it presents a unified diff view, allowing the user to approve or reject changes per file or in bulk.

Key Components:

How it Works:

  1. An agent calls startBatch() at the beginning of a sequence of file modifications.
  2. For each file change, the agent calls addChange(), providing details like the file path, type of change, and a diff preview.
  3. Once all changes for a turn are collected, the UI can call formatBatchSummary() to display them to the user.
  4. The user interacts with the service via approveAll(), rejectAll(), or individual approveChange()/rejectChange()/toggleChange() calls.
  5. Finally, finalize() is called to get the results, and batchMode is deactivated.

Integration:

Tools that modify files (e.g., text-editor tools) would use this service to defer and consolidate confirmation prompts. It works in conjunction with the ConfirmationService to present a more user-friendly review experience for multi-file operations.

cache.ts

A generic, in-memory cache implementation with Time-To-Live (TTL) support. It's designed for temporary storage of computed or fetched data to improve performance.

Key Components:

How it Works:

The cache uses a JavaScript Map internally. Each entry stores the value and an expiresAt timestamp. When get is called, it checks Date.now() against expiresAt to determine if the entry is still valid. getOrCompute provides a convenient pattern for caching results of expensive operations.

Integration:

This is a general-purpose utility that can be used by any module needing to cache data, such as semantic-cache or response-cache (as seen in the call graph, though not directly in the provided source).

clipboard.ts

Provides cross-platform functionality for interacting with the system clipboard (copy and paste). It gracefully handles cases where native clipboard tools might be missing.

Key Components:

How it Works:

It uses Node.js's child_process.execSync to execute platform-specific commands:

Error handling is included to prevent crashes if a command fails or is not found.

Integration:

Any feature that needs to interact with the user's system clipboard, such as copying code snippets, command outputs, or pasting input.

codebuddy-home.ts

This module centralizes the management of the Code Buddy application's home directory (GROK_HOME), where all configuration, data, and persistent state are stored. It allows users to customize this location via an environment variable.

Key Components:

How it Works:

The module first checks process.env.GROK_HOME. If set, that path is used. Otherwise, it defaults to .codebuddy in the user's home directory (os.homedir()). All other path functions build upon this base path. fs.mkdirSync with recursive: true is used to create directories as needed.

Integration:

This is a fundamental utility used by almost every module that needs to store or retrieve persistent data, configuration files (like settings.json, user-settings.json), logs, or session information. It ensures a consistent and configurable location for all application data.

color-contrast.ts

Provides a suite of utilities for calculating color contrast ratios and ensuring accessibility according to WCAG 2.1 guidelines. It helps developers create terminal interfaces that are readable for a wider audience.

Key Components:

How it Works:

The core logic follows WCAG 2.1 specifications:

  1. Colors are converted to RGB.
  2. getRelativeLuminance calculates the perceived brightness of each color.
  3. getContrastRatio uses the luminance values to determine the contrast.
  4. getWcagLevel then categorizes this ratio against WCAG thresholds.

suggestAccessibleColor uses HSL color space and a binary search approach to find a suitable lightness value for the foreground color.

Integration:

This utility is crucial for ensuring the accessibility of the terminal UI, especially when custom themes or color schemes are applied. It can be used by theme managers or rendering components to validate color choices and provide warnings or suggestions.

config-validation/index.ts

This file serves as a barrel export for the configuration validation module, simplifying imports for other parts of the codebase.

Key Components:

Integration:

Any module needing to interact with configuration schemas or validation logic will import from this index file.

config-validation/schema.ts

This module defines the authoritative schemas and type constants for all Code Buddy configuration files. It uses Zod for robust schema definition and type inference, while also maintaining legacy JSON schemas for backward compatibility.

Key Components:

How it Works:

Zod schemas provide a declarative way to define the shape and validation rules for configuration objects. They allow for:

Integration:

This module is the single source of truth for configuration structure. The ZodConfigValidator uses these schemas to perform validation, apply defaults, and infer types.

config-validation/validators.ts

This module provides the actual validation logic for Code Buddy's configuration files. It includes both a legacy JSON schema validator and a modern, Zod-based validator, along with functions for comprehensive startup validation and command handling.

Key Components:

How it Works:

  1. Zod Validation: The ZodConfigValidator is the primary validation mechanism. It uses Zod's parse method, which automatically applies defaults and throws a ZodError on invalid input. This error is then converted into a more user-friendly ValidationError format.
  2. File Handling: validateFile handles reading JSON files, parsing them, and includes a migrateConfig step to ensure compatibility with older configurations.
  3. Startup Orchestration: validateStartupConfigWithZod is called early in the application lifecycle. It scans the project and user config directories, validates each file, and also validates environment variables. It aggregates all errors and warnings.
  4. Defaults: loadValidatedSettings and loadValidatedUserSettings ensure that even if config files are missing or invalid, the application starts with a set of sensible default values.

Integration:

config-validator.ts

This file is a simple re-export of the config-validation/index.ts module, providing an alias for easier access.

Key Components:

Integration:

Simplifies imports for other modules that need to use the configuration validation utilities.

confirmation-helper.ts

This module provides a unified and simplified interface for requesting user confirmation across various operations (file edits, bash commands, etc.). It reduces boilerplate by centralizing the logic for checking session flags and delegating to the ConfirmationService.

Key Components:

How it Works:

  1. Session Flags: checkConfirmation first consults ConfirmationService.getSessionFlags() to see if the user has globally or category-specifically opted to skip confirmation for the current session.
  2. Delegation: If not skipped, it delegates the actual prompting to ConfirmationService.requestConfirmation().
  3. Wrapping Operations: withConfirmation provides a clean way to integrate confirmation into tool logic, ensuring the operation only proceeds if approved.

Integration:

This module is widely used by tools (e.g., text-editor, docker-tool, kubernetes-tool) to standardize how they request user approval. It abstracts away the direct interaction with ConfirmationService, making tool development simpler and more consistent.

confirmation-service.ts

The ConfirmationService is the central hub for all user confirmation prompts within Code Buddy. It orchestrates the decision-making process for whether an operation requires user approval, considering autonomy levels, learned patterns, and declarative security rules.

Key Components:

How it Works:

  1. Decision Flow: When requestConfirmation is called:

  1. User Prompt: If none of the above auto-approve, the service enters a pending state, waiting for user input via the CLI. It emits events to signal the UI to display the prompt.
  2. Session Flags: Users can choose "don't ask again" for the current session, which sets flags (allOperations, fileOperations, bashCommands) to bypass future prompts.
  3. VS Code Integration: If showVSCodeOpen is true, it attempts to open the relevant file in VS Code for easier review.

Integration:

The ConfirmationService is a central orchestrator:

graph TD
    A[Tool/Agent Action] --> B[ConfirmationHelper.checkConfirmation];
    B --> C[ConfirmationService.requestConfirmation];

    C --> D{PermissionModeManager.checkPermission};
    D -- Denied --> E[Block Operation];
    D -- Allowed --> F{AutonomyManager.isYOLOEnabled};

    F -- Yes --> G{AutonomyManager.shouldYOLOExecute};
    G -- Blocked --> E;
    G -- Allowed --> H{ApprovalPatternTracker.shouldAutoApprove};

    F -- No --> I{AutonomyManager.shouldConfirm};
    I -- Requires Confirmation --> J[Prompt User];
    I -- Auto-Approved --> K[Auto-Approve];

    H -- Yes --> K;
    H -- No --> J;

    J --> L[User Input];
    L -- Confirmed --> K;
    L -- Rejected --> E;

    K --> M[Proceed with Operation];
    E --> N[Operation Cancelled];

    subgraph ConfirmationService Internal
        C --> D;
        C --> F;
        C --> I;
        C --> J;
        J --> L;
    end