src — services

Module: src-services Cohesion: 0.80 Members: 0

src — services

The src/services module provides a collection of reusable, domain-specific functionalities that support the core operations of the agent. It abstracts away complex tasks such as codebase exploration, static code analysis, execution plan management, dynamic prompt construction, and unified file system interactions.

This module is designed to offer clear, focused APIs, allowing other parts of the codebase (e.g., agents, command handlers) to consume these capabilities without needing to understand their intricate internal workings.

Module Overview

The src/services module is structured into several distinct components:

Core Services

1. Code Analyzer (src/services/analysis/code-analyzer.ts)

The CodeAnalyzer service performs static analysis on individual code files to extract various metrics and detect potential issues. It's designed to provide a quick, high-level understanding of a file's characteristics without requiring a full AST parser.

Key Capabilities:

Output:

The analysis results are encapsulated in the FileAnalysis interface, defined in src/services/analysis/types.ts.

Usage Example:

import { CodeAnalyzer } from './services/analysis/code-analyzer.js';

const analyzer = new CodeAnalyzer();
const filePath = 'src/my-module.ts';
const fileContent = `
import { someUtil } from './utils';
const API_KEY = "sk-1234567890abcdefghijklmnopqrstuvwxyz"; class="hl-cmt">// Hardcoded secret
function doSomething(data: any) {
  console.log("Processing data:", data);
  if (data.length > 100) {
    class="hl-cmt">// TODO: Optimize this loop
    for (let i = 0; i < data.length; i++) {
      class="hl-cmt">// ...
    }
  }
}
export default doSomething;
`;

const analysis = analyzer.analyzeFileContent(filePath, fileContent);
console.log(`Language: ${analysis.language}`); class="hl-cmt">// typescript
console.log(`Issues:`, analysis.issues);
class="hl-cmt">// [
class="hl-cmt">//   { type: &#39;security&#39;, severity: &#39;critical&#39;, message: &#39;Problème de sécurité détecté: hardcodedSecrets&#39;, ... },
class="hl-cmt">//   { type: &#39;maintainability&#39;, severity: &#39;warning&#39;, message: &#39;TODO/FIXME non résolu&#39;, ... },
class="hl-cmt">//   { type: &#39;maintainability&#39;, severity: &#39;warning&#39;, message: &#39;console.log détecté (à supprimer en production)&#39;, ... },
class="hl-cmt">//   { type: &#39;maintainability&#39;, severity: &#39;warning&#39;, message: &#39;Type "any" utilisé&#39;, ... }
class="hl-cmt">// ]

2. Plan Analyzer (src/services/analysis/plan-analysis.ts)

The PlanAnalyzer service is responsible for performing various analytical computations on an ExecutionPlan. It enhances the plan with insights into its structure, risks, and execution characteristics.

Key Capabilities:

Connections:

This service is primarily used by the PlanGenerator to keep the plan's analysis up-to-date after modifications.

3. Codebase Explorer (src/services/codebase-explorer.ts)

The CodebaseExplorer service provides comprehensive capabilities for scanning, analyzing, and reporting on a project's file system structure and content. It's designed to give a holistic view of a codebase.

Key Classes & Interfaces:

Key Capabilities:

Helper Functions:

Usage Example:

import { exploreCodebase } from &#39;./services/codebase-explorer.js&#39;;

async function runExploration() {
  const { stats, project, tree, report } = await exploreCodebase(process.cwd(), {
    maxDepth: 5,
    excludePatterns: [&#39;node_modules&#39;, &#39;.git&#39;],
  });

  console.log(&#39;Project Info:&#39;, project);
  console.log(&#39;Codebase Stats:&#39;, stats);
  console.log(&#39;\nCodebase Tree:\n&#39;, tree);
  console.log(&#39;\nCodebase Report:\n&#39;, report);
}

runExploration();

4. Plan Generator (src/services/plan-generator.ts)

The PlanGenerator service provides a structured way to create, manage, and track the execution of complex, multi-step tasks. It implements a phased workflow, allowing for detailed planning, analysis, and progress tracking.

Key Classes & Interfaces:

Key Capabilities:

Singleton Pattern:

The plan-generator.ts module also provides getPlanGenerator() and resetPlanGenerator() functions to manage a singleton instance of the PlanGenerator, ensuring a consistent view of the active plan across the application.

Connections:

5. Prompt Builder (src/services/prompt-builder.ts)

The PromptBuilder service is a critical component responsible for dynamically constructing the comprehensive system prompt provided to the LLM agent. It aggregates information from various sources to create a rich and context-aware prompt.

Key Class:

Key Capabilities:

Connections:

The PromptBuilder has extensive outgoing calls to various managers and providers across the codebase, making it a central hub for prompt engineering and context injection. It's typically instantiated and used by the main agent loop.

6. System Prompt Override (src/services/system-prompt-override.ts)

The SystemPromptOverride service provides a mechanism to modify the system prompt using command-line interface (CLI) flags. It allows users to replace the entire prompt or append additional instructions.

Key Class:

Key Capabilities:

Connections:

This service is typically used by the agent's initialization logic to incorporate user-defined prompt modifications after the PromptBuilder has generated the initial system prompt.

7. Unified VFS Router (src/services/vfs/unified-vfs-router.ts)

The UnifiedVfsRouter acts as the central gateway for all file system operations within the application. Its purpose is to prevent "Split Brain" scenarios by ensuring a single, consistent interface for file access, and to enable the use of virtual file systems.

Key Interfaces & Classes:

Key Capabilities:

Architecture Diagram:

graph TD
    A[Agent File Operations] --> B{UnifiedVfsRouter.Instance};
    B -- "filePath.startsWith('memory://')" --> C[MemoryVfsProvider];
    B -- "Default (physical FS)" --> D[fs-extra (Physical File System)];
    C -- "Stores in .codebuddy/agent-memory" --> E[Disk];
    D -- "Accesses project files" --> E;
    B -- "Path Validation" --> F[WorkspaceIsolation];

Connections:

8. Memory VFS Provider (src/services/vfs/memory-vfs-provider.ts)

The MemoryVfsProvider is an implementation of the IVfsProvider interface, designed for ephemeral file storage with a Time-To-Live (TTL) mechanism. It stores files in a dedicated directory (.codebuddy/agent-memory/) and automatically cleans up expired entries.

Key Class:

Key Capabilities:

Connections:

9. Analysis Types (src/services/analysis/types.ts) & Plan Types (src/services/plan-types.ts)

These files define the core data structures and enumerations used by the analysis and planning services. They ensure type safety, clarity, and consistency across the module.

Key Types in analysis/types.ts:

Key Types in plan-types.ts:

Interactions and Dependencies

The src/services module is a collection of loosely coupled services, but they interact in specific ways:

Usage Patterns

Developers interacting with this module will typically:

  1. Explore a Codebase: Use CodebaseExplorer to get an overview of a project, find specific files, or generate reports.
  2. Analyze Code: Use CodeAnalyzer for static checks on individual files, often as part of a larger analysis pipeline.
  3. Manage Execution Plans: Use PlanGenerator to define, modify, track, and persist multi-step tasks, leveraging PlanAnalyzer for insights.
  4. Build Agent Prompts: The PromptBuilder is a core internal service for the agent, dynamically assembling the LLM's system prompt from many sources. Developers might extend it by adding new context providers.
  5. Interact with the File System: All file operations should ideally go through UnifiedVfsRouter.Instance to ensure consistency, security, and support for virtual file systems. This allows for flexible environments like sandboxed execution or in-memory workspaces.