Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Developer Guide: Smart-Codebase (Refactored)

This guide provides an overview of the SKILL-centric architecture for Smart-Codebase.

## Architecture Overview

The plugin is designed to be lightweight and agent-driven.

- **`src/index.ts`**: Plugin entry point. Registers the `sc-update` command and context injector hooks.
- **`src/commands/update.ts`**: Implements the `/sc-update` command. It triggers the skill update process.
- **`src/extraction/skill-updater.ts`**: The core logic for knowledge extraction. It creates a child AI session and provides it with a specialized system prompt.
- **`src/extraction/system-prompt.ts`**: Defines the system prompt that guides the child AI agent to autonomously read, analyze, and update SKILL files.
- **`src/hooks/context-injector.ts`**: Injects a prompt into new sessions to help the AI discover the project's SKILL files.
- **`src/utils/skill-helpers.ts`**: Utility functions for managing SKILL file names and paths.

## Key Design Decisions

1. **AI-Agentic Extraction**: Instead of the plugin code trying to parse conversations and write markdown, it delegates this to a child AI session. This agent has full access to project files and conversation history, allowing it to autonomously organize knowledge.
2. **SKILL-Centric Storage**: All knowledge is stored in `.opencode/skills/<project>/` using the standard OpenCode SKILL format. This ensures that the knowledge is automatically discoverable by any OpenCode session.
3. **Single Manual Command**: We replaced multiple complex commands with a single `/sc-update` command. This gives users total control over when extraction happens and reduces background noise.
4. **Minimal Configuration**: The configuration is stripped down to 3 essential fields: `enabled`, `extractionModel`, and `extractionMaxTokens`.

## How sc-update Works

When you run `/sc-update [focus?]`:
1. The plugin retrieves the current session's message history.
2. It builds a text-based summary of the conversation.
3. It creates a child AI session (a sub-session of your current one).
4. The child AI is given a specialized system prompt and a set of tools (`read`, `write`, `edit`, `glob`, `grep`, `bash`).
5. The child AI autonomously:
- Reads existing `SKILL.md` and `reference/*.md` files.
- Browses source code to verify facts or understand context.
- Writes or updates the main `SKILL.md` (frontmatter, principles, workflows).
- Manages detailed knowledge in the `reference/` directory.
6. Once the AI completes its tasks, the child session is deleted.

## Adding Features

- **Keep it minimal**: Avoid adding background listeners or automatic triggers.
- **Agent-first**: If you need to extract new types of data, update the `system-prompt.ts` instead of writing new TypeScript logic to handle files.
- **Compatibility**: Ensure any changes to the SKILL file format remain compatible with OpenCode's auto-discovery mechanism.

## Testing

We use [Bun](https://bun.sh/) for testing.

- **`src/__tests__`**: Contains unit and integration tests.
- **Mocks**: We mock the OpenCode SDK to test command registration and child session creation without needing a live OpenCode environment.

Run tests with:
```bash
bun test
```

## Development Setup

1. **Prerequisites**: [Bun](https://bun.sh/) installed.
2. **Installation**: `bun install`
3. **Build**: `bun run build` (outputs to `dist/`)
4. **Type Check**: `bun run typecheck`
165 changes: 48 additions & 117 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,24 +18,31 @@ Every time you start a new session, AI starts from scratch. It doesn't remember:

## ✨ The Solution

smart-codebase automatically captures knowledge from your sessions and makes it available to future sessions.
Smart-Codebase gives your AI permanent memory through SKILL files. It uses an AI agent to autonomously capture knowledge from your conversations and project files.

```mermaid
graph TB
Start([Session Work])
Extractor[AI Extractor Analyzes]
SkillFile[.knowledge/SKILL.md<br/>Per Module]
ProjectSkill[.opencode/skills/project/SKILL.md<br/>OpenCode Auto-Discovery]
Init[sc-init command]
Update[sc-update command]
InitAgent[AI Scans Source Code]
UpdateAgent[AI Analyzes Session]
SkillFile[.opencode/skills/project/SKILL.md<br/>OpenCode Auto-Discovery]
RefFiles[.opencode/skills/project/reference/*.md<br/>Deep Dive Docs]
NewSession([New Session Starts])
Injector[Knowledge Injector]
Injector[Context Injector]

Start -->|idle| Extractor
Extractor -->|write| SkillFile
Extractor -->|update index| ProjectSkill
Start --> Init
Start --> Update
Init --> InitAgent
Update --> UpdateAgent
InitAgent -->|writes| SkillFile
InitAgent -->|writes| RefFiles
UpdateAgent -->|updates| SkillFile
UpdateAgent -->|updates| RefFiles

NewSession --> Injector
Injector -->|inject hint| ProjectSkill
ProjectSkill -.->|references| SkillFile
Injector -->|inject hint| SkillFile
```

---
Expand All @@ -47,29 +54,26 @@ graph TB
- [⚡ Commands](#-commands)
- [⚙️ Configuration](#️-configuration)
- [📁 File Structure](#-file-structure)
- [📊 Usage Statistics](#-usage-statistics)
- [🧹 Cleanup Command](#-cleanup-command)
- [🛠️ Development](#️-development)

---

## ⚙️ How It Works

1. **You work normally** - Edit files, debug issues, make decisions
2. **Session goes idle** - After 60 seconds of inactivity, toast notification appears
3. **You can interrupt** - Send a message to cancel extraction and continue working
4. **Extractor analyzes** - AI examines what changed and why (with progress notifications)
5. **Knowledge captured** - Stored in `.opencode/skills/<project>/modules/<module>.md`
6. **Index updated** - Global index at `.opencode/skills/<project>/SKILL.md`
7. **Next session starts** - AI reads project skill, then discovers relevant module skills
1. **You work normally** - Edit files, debug issues, and make architectural decisions.
2. **First time setup** - Run `/sc-init` once to scan your source code and generate comprehensive SKILL files.
3. **Ongoing capture** - When you reach a milestone, run `/sc-update` to extract knowledge from the current session.
4. **AI Agent analyzes** - A child AI session examines your conversation or project code to understand what changed and why.
5. **Knowledge distilled** - The agent autonomously writes or updates SKILL files in standard OpenCode format.
6. **Next session starts** - New sessions auto-discover your project SKILLs, giving the AI immediate context.

**The plugin works silently in the background. Toast notifications keep you informed without interrupting your flow.**
**Manual control means you decide exactly when to preserve knowledge. The AI agent handles the heavy lifting of writing documentation.**

---

## 📦 Installation

Navigate to `~/.config/opencode` directory:
Navigate to your `~/.config/opencode` directory:

```bash
# Using bun
Expand All @@ -93,122 +97,46 @@ Add to your `opencode.json`:

| Command | Description |
|---------|-------------|
| `/sc-status` | Show knowledge base status and usage statistics |
| `/sc-extract` | Manually trigger knowledge extraction |
| `/sc-rebuild-index` | Rebuild `.knowledge/KNOWLEDGE.md` from all SKILL.md files |
| `/sc-cleanup` | Clean up low-usage SKILL files (preview mode) |
| `/sc-cleanup --confirm` | Actually delete low-usage SKILL files |
| `/sc-init [focus?]` | Initialize project SKILL files by scanning source code. Run once before your first `/sc-update`. |
| `/sc-update [focus?]` | Trigger the AI agent to extract knowledge from the current session. |

---

## ⚙️ Configuration

No configuration required by default. To customize, create `~/.config/opencode/smart-codebase.json` (or `.jsonc`):
Create `~/.config/opencode/smart-codebase.json` (or `.jsonc`) to customize:

```jsonc
{
"enabled": true,
"debounceMs": 30000,
"autoExtract": true,
"autoInject": true,
"extractionModel": "minimax/MiniMax-M2.1",
"disabledCommands": ["sc-rebuild-index"]
"extractionModel": "openai/gpt-4o",
"extractionMaxTokens": 16000
}
```

| Option | Default | Description |
|--------|---------|-------------|
| `enabled` | `true` | Enable/disable the plugin entirely |
| `debounceMs` | `60000` | Wait time (ms) after session idle before extraction |
| `autoExtract` | `true` | Automatically extract knowledge on idle |
| `autoInject` | `true` | Inject knowledge hint at session start |
| `extractionModel` | - | Model for extraction, format: `providerID/modelID` |
| `extractionMaxTokens` | `8000` | Max token budget for extraction context |
| `disabledCommands` | `[]` | Commands to disable, e.g. `["sc-rebuild-index"]` |
| `cleanupThresholds` | See below | Thresholds for cleanup command |

#### cleanupThresholds

| Option | Default | Description |
|--------|---------|-------------|
| `cleanupThresholds.minAgeDays` | `60` | Minimum age in days for cleanup eligibility |
| `cleanupThresholds.minAccessCount` | `5` | Maximum access count for cleanup eligibility |
| `cleanupThresholds.maxInactiveDays` | `60` | Maximum days since last access for cleanup eligibility |

---

## 📁 File Structure Example

```
project/
├── .opencode/
│ └── skills/
│ └── <project-name>/
│ ├── SKILL.md # Project skill (main index)
│ └── modules/
│ ├── src-auth.md # Auth module knowledge
│ └── src-api.md # API module knowledge
├── src/
│ ├── auth/
│ │ ├── session.ts
│ │ └── jwt.ts
│ │
│ └── api/
│ └── routes.ts
```

The project skill at `.opencode/skills/<project>/SKILL.md` serves as the global index and is auto-discovered by OpenCode. Module-level knowledge is stored in `.opencode/skills/<project>/modules/<module-name>.md`.
| `enabled` | `true` | Enable or disable the plugin entirely. |
| `extractionModel` | - | Model for the AI agent (e.g., `providerID/modelID`). |
| `extractionMaxTokens` | `16000` | Token budget for the extraction context. |

---

### Usage Statistics
## 📁 File Structure

The `/sc-status` command now displays:
- Total SKILL count
- Total access count across all SKILLs
- Low-frequency SKILL count (based on cleanupThresholds)
- Usage breakdown (high/medium/low)
Knowledge is stored in your project directory using the standard OpenCode SKILL format:

Example output:
```
📊 Usage Statistics:
Total SKILLs: 15
Total accesses: 234
Low-frequency SKILLs (< 5 accesses): 3

Usage breakdown:
- High usage (≥10 accesses): 8 SKILLs
- Medium usage (5-10): 4 SKILLs
- Low usage (<5): 3 SKILLs
```

---

### Cleanup Command

Remove low-usage SKILL files based on configurable thresholds.

**Preview mode (default)**:
```bash
/sc-cleanup
```

Lists eligible SKILLs without deleting them.

**Confirm mode**:
```bash
/sc-cleanup --confirm
project/
└── .opencode/
└── skills/
└── <project-name>/
├── SKILL.md # Main project skill and index
└── reference/ # Detailed documentation files
├── architecture.md
└── api-patterns.md
```

Actually deletes files and updates the main index.

**Cleanup Criteria (AND logic)**:
A SKILL is eligible for cleanup when ALL conditions are met:
1. Age ≥ `minAgeDays` (default: 60 days)
2. Access count < `minAccessCount` (default: 5)
3. Days since last access ≥ `maxInactiveDays` (default: 60 days)

---

## 🛠️ Development
Expand All @@ -217,11 +145,14 @@ A SKILL is eligible for cleanup when ALL conditions are met:
# Install dependencies
bun install

# Build
# Build the plugin
bun run build

# Type check
# Run type checks
bun run typecheck

# Run tests
bun test
```

---
Expand Down
Loading