[中文](./README.md) | English

# @easbot/codebase

Code Knowledge Graph SDK - A code indexing and querying system based on the Property Graph model

## Features

- **Property Graph Model**: Store code entities and their relationships using nodes and edges
- **Multi-language Support**: TypeScript, JavaScript, Python, Rust, Go, C/C++, C#, Java, Scala, Ruby, PHP, Zig
- **Hybrid Search**: FTS full-text search + structured queries
- **Incremental Updates**: Smart incremental indexing based on file content hashes
- **Tree-sitter Parsing**: High-performance AST parsing

## Installation

```bash
pnpm add @easbot/codebase
```

## Quick Start

```typescript
import { createCodebase } from '@easbot/codebase';

// Create graph instance
const graph = await createCodebase({
  workspaceDir: '/path/to/your/project',
});

// Index project
const result = await graph.indexDirectory();
console.log(`Indexed: ${result.filesProcessed} files, ${result.nodesCreated} nodes`);

// Search code
const results = await graph.search('UserService');
for (const r of results) {
  console.log(`${r.name} (${r.astType}) - ${r.filePath}:${r.startLine}`);
}

// Query nodes
const classes = await graph.queryNodes({ astType: 'class_declaration' });

// Query call graph
const callGraph = await graph.queryCallGraph('ts:src/service.ts:function_declaration:UserService');

// Close graph
await graph.close();
```

## API Documentation

### CodeKnowledgeGraph

Main class providing complete code knowledge graph functionality.

#### Constructor Options

```typescript
interface CodeKnowledgeGraphConfig {
  workspaceDir: string;           // Workspace directory
  database?: {
    path: string;                 // Database path
    walMode?: boolean;            // WAL mode
  };
  parser?: {
    languages?: Language[];       // Supported languages
    lazyLoad?: boolean;           // Lazy loading
  };
  indexer?: {
    batchSize: number;            // Batch size
    ignorePatterns: string[];     // Ignore patterns
    incremental: boolean;         // Incremental updates
  };
}
```

#### Main Methods

| Method | Description |
|--------|-------------|
| `initialize()` | Initialize graph |
| `indexFile(path)` | Index single file |
| `indexDirectory(dir?)` | Index directory |
| `sync()` | Incremental sync |
| `search(query, options?)` | Hybrid search |
| `queryNodes(filter)` | Query nodes |
| `queryEdges(filter)` | Query edges |
| `queryNeighbors(nodeId, options?)` | Query neighbors |
| `queryCallGraph(nodeId, depth?)` | Query call graph |
| `queryInheritance(nodeId)` | Query inheritance |
| `getStatus()` | Get status |
| `healthCheck()` | Health check |
| `close()` | Close graph |

### Search Options

```typescript
interface SearchOptions {
  maxResults?: number;            // Max results
  minScore?: number;              // Min score
  language?: Language;            // Language filter
  filePath?: string;              // File path filter
  astType?: string;               // AST type filter
  enableFts?: boolean;            // Enable FTS
  ftsWeight?: number;             // FTS weight
}
```

## Data Model

### Node

| Field | Type | Description |
|-------|------|-------------|
| id | string | Unique identifier |
| name | string | Name |
| ast_type | string | AST type |
| language | string | Language |
| file_path | string | File path |
| start_line | number | Start line |
| start_col | number | Start column |
| end_line | number | End line |
| end_col | number | End column |
| text | string | Code text |

### Edge

| Field | Type | Description |
|-------|------|-------------|
| id | string | Unique identifier |
| source | string | Source node ID |
| target | string | Target node ID |
| relation | string | Relation type |

### Relation Types

| Relation | Description |
|----------|-------------|
| CONTAINS | Parent-child AST relationship |
| CALLS | Function call relationship |
| INHERITS_FROM | Class inheritance |
| IMPLEMENTS | Interface implementation |
| IMPORTS | Module import |
| REFERENCES | Variable/identifier reference |

## Architecture

```
src/
├── types.ts              # Type definitions
├── errors.ts             # Error classes
├── index.ts              # Entry file
├── code-knowledge-graph.ts  # Main class
├── database/
│   └── database-manager.ts  # Database management
├── parser/
│   └── parser-manager.ts    # Parser management
├── extractor/
│   ├── node-extractor.ts    # Node extraction
│   └── edge-extractor.ts    # Edge extraction
├── indexer/
│   └── indexer.ts           # Indexer
└── query/
    └── query-interface.ts   # Query interface
```

## Development

```bash
# Install dependencies
pnpm install

# Build
pnpm build

# Test
pnpm test

# Type check
pnpm type-check

# Lint
pnpm lint
```

## License

MIT
