Merge commit 'd803bfe2b1fe7f5e219e50ac20d6801a0a58ac75' as 'vendor/ruvector'
This commit is contained in:
744
vendor/ruvector/docs/hooks/ARCHITECTURE.md
vendored
Normal file
744
vendor/ruvector/docs/hooks/ARCHITECTURE.md
vendored
Normal file
@@ -0,0 +1,744 @@
|
||||
# RuVector Hooks Architecture
|
||||
|
||||
Technical architecture documentation for the RuVector hooks system.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [System Overview](#system-overview)
|
||||
2. [Component Architecture](#component-architecture)
|
||||
3. [Intelligence Layer](#intelligence-layer)
|
||||
4. [Hook Execution Flow](#hook-execution-flow)
|
||||
5. [Data Storage](#data-storage)
|
||||
6. [Integration Points](#integration-points)
|
||||
7. [Security Model](#security-model)
|
||||
8. [Performance Optimization](#performance-optimization)
|
||||
|
||||
---
|
||||
|
||||
## System Overview
|
||||
|
||||
### High-Level Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────────┐
|
||||
│ Claude Code Runtime │
|
||||
├──────────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ PreToolUse │────►│ Tool Exec │────►│ PostToolUse │ │
|
||||
│ │ Hooks │ │ │ │ Hooks │ │
|
||||
│ └──────┬──────┘ └─────────────┘ └──────┬──────┘ │
|
||||
│ │ │ │
|
||||
│ ▼ ▼ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Hook Dispatcher │ │
|
||||
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
|
||||
│ │ │ Matcher │ │ Executor │ │ Response │ │ Timeout │ │ │
|
||||
│ │ │ Engine │ │ Engine │ │ Handler │ │ Manager │ │ │
|
||||
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ RuVector CLI Layer │ │
|
||||
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
|
||||
│ │ │ Command │ │ Template │ │ Path │ │ Config │ │ │
|
||||
│ │ │ Parser │ │ Engine │ │ Resolver │ │ Manager │ │ │
|
||||
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Intelligence Layer │ │
|
||||
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
|
||||
│ │ │Q-Learning│ │ Vector │ │ Agent │ │ Neural │ │ │
|
||||
│ │ │ Engine │ │ Memory │ │ Router │ │ Trainer │ │ │
|
||||
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌────────────────────────────────────────────────────────────┐ │
|
||||
│ │ Storage Layer │ │
|
||||
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
|
||||
│ │ │ JSON │ │ RvLite │ │ Global │ │ │
|
||||
│ │ │ Files │ │ HNSW │ │ Patterns │ │ │
|
||||
│ │ └──────────┘ └──────────┘ └──────────┘ │ │
|
||||
│ └────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└──────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Design Principles
|
||||
|
||||
1. **Portability**: No hardcoded paths; runtime resolution
|
||||
2. **Minimal Overhead**: <100ms total hook overhead
|
||||
3. **Graceful Degradation**: Hooks never block main flow
|
||||
4. **Learning by Default**: Automatic pattern improvement
|
||||
5. **Cross-Platform**: Linux, macOS, Windows support
|
||||
|
||||
---
|
||||
|
||||
## Component Architecture
|
||||
|
||||
### CLI Layer (`crates/ruvector-cli`)
|
||||
|
||||
The command-line interface for hook management.
|
||||
|
||||
```
|
||||
crates/ruvector-cli/
|
||||
├── src/
|
||||
│ ├── cli/
|
||||
│ │ ├── commands.rs # Command definitions
|
||||
│ │ ├── hooks/ # Hooks subcommands
|
||||
│ │ │ ├── mod.rs # Module exports
|
||||
│ │ │ ├── init.rs # hooks init
|
||||
│ │ │ ├── install.rs # hooks install
|
||||
│ │ │ ├── migrate.rs # hooks migrate
|
||||
│ │ │ ├── stats.rs # hooks stats
|
||||
│ │ │ ├── export.rs # hooks export
|
||||
│ │ │ └── import.rs # hooks import
|
||||
│ │ └── ...
|
||||
│ └── main.rs
|
||||
├── templates/ # Hook templates
|
||||
│ ├── hooks.json.j2 # Portable hooks template
|
||||
│ ├── config.toml.j2 # Configuration template
|
||||
│ └── gitignore.j2 # Gitignore template
|
||||
└── Cargo.toml
|
||||
```
|
||||
|
||||
### Template Engine
|
||||
|
||||
Uses Askama for type-safe template rendering:
|
||||
|
||||
```rust
|
||||
#[derive(Template)]
|
||||
#[template(path = "hooks.json.j2")]
|
||||
struct HookTemplate {
|
||||
shell: String, // Platform shell wrapper
|
||||
ruvector_cli: String, // CLI invocation method
|
||||
project_root: String, // Project root path
|
||||
}
|
||||
|
||||
fn render_hooks() -> Result<String> {
|
||||
let template = HookTemplate {
|
||||
shell: get_shell_wrapper(),
|
||||
ruvector_cli: get_cli_invocation(),
|
||||
project_root: env::current_dir()?.display().to_string(),
|
||||
};
|
||||
Ok(template.render()?)
|
||||
}
|
||||
```
|
||||
|
||||
### Path Resolution
|
||||
|
||||
Dynamic path resolution at runtime:
|
||||
|
||||
```rust
|
||||
pub fn get_ruvector_home() -> Result<PathBuf> {
|
||||
// Priority order:
|
||||
// 1. RUVECTOR_HOME environment variable
|
||||
// 2. ~/.ruvector (Unix) or %APPDATA%\ruvector (Windows)
|
||||
|
||||
if let Ok(home) = env::var("RUVECTOR_HOME") {
|
||||
return Ok(PathBuf::from(shellexpand::tilde(&home).to_string()));
|
||||
}
|
||||
|
||||
let home_dir = dirs::home_dir()
|
||||
.ok_or_else(|| anyhow!("Could not determine home directory"))?;
|
||||
|
||||
Ok(home_dir.join(".ruvector"))
|
||||
}
|
||||
|
||||
pub fn get_cli_path() -> Result<String> {
|
||||
// Priority order:
|
||||
// 1. Binary in PATH
|
||||
// 2. npx ruvector
|
||||
// 3. Current executable
|
||||
|
||||
if let Ok(path) = which::which("ruvector") {
|
||||
return Ok(path.display().to_string());
|
||||
}
|
||||
|
||||
Ok("npx ruvector".to_string())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Intelligence Layer
|
||||
|
||||
### Q-Learning Engine
|
||||
|
||||
Implements temporal difference learning for action selection:
|
||||
|
||||
```javascript
|
||||
// Q-value update equation
|
||||
// Q(s,a) ← Q(s,a) + α[r + γ max_a' Q(s',a') - Q(s,a)]
|
||||
|
||||
class QLearning {
|
||||
constructor(options = {}) {
|
||||
this.alpha = options.learningRate || 0.1; // Learning rate
|
||||
this.gamma = options.discount || 0.95; // Discount factor
|
||||
this.qTable = new Map(); // State-action values
|
||||
}
|
||||
|
||||
update(state, action, reward, nextState) {
|
||||
const currentQ = this.getQ(state, action);
|
||||
const maxNextQ = this.getMaxQ(nextState);
|
||||
const newQ = currentQ + this.alpha * (reward + this.gamma * maxNextQ - currentQ);
|
||||
this.setQ(state, action, newQ);
|
||||
}
|
||||
|
||||
selectAction(state) {
|
||||
// Epsilon-greedy exploration
|
||||
if (Math.random() < this.epsilon) {
|
||||
return this.randomAction(state);
|
||||
}
|
||||
return this.bestAction(state);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### State Representation
|
||||
|
||||
States encode file context and action type:
|
||||
|
||||
```javascript
|
||||
function encodeState(context) {
|
||||
const { file, crate, tool, previousSuccess } = context;
|
||||
|
||||
return {
|
||||
fileType: getFileExtension(file), // 'rs', 'ts', 'py'
|
||||
crateName: crate || 'unknown', // 'ruvector-core'
|
||||
toolCategory: categorize(tool), // 'edit', 'bash', 'search'
|
||||
historyHash: hashRecent(previousSuccess), // Recent success pattern
|
||||
};
|
||||
}
|
||||
|
||||
// State key for Q-table lookup
|
||||
function stateKey(state) {
|
||||
return `${state.toolCategory}_${state.fileType}_in_${state.crateName}`;
|
||||
}
|
||||
```
|
||||
|
||||
### Vector Memory
|
||||
|
||||
Semantic search using HNSW indexing:
|
||||
|
||||
```javascript
|
||||
class VectorMemory {
|
||||
constructor(dimensions = 128) {
|
||||
this.dimensions = dimensions;
|
||||
this.index = new HnswIndex({ dimensions, maxElements: 50000 });
|
||||
this.metadata = new Map();
|
||||
}
|
||||
|
||||
async store(key, text, metadata) {
|
||||
const embedding = await this.embed(text);
|
||||
const id = this.index.add(embedding);
|
||||
this.metadata.set(id, { key, ...metadata });
|
||||
return id;
|
||||
}
|
||||
|
||||
async search(query, k = 5) {
|
||||
const embedding = await this.embed(query);
|
||||
const results = this.index.search(embedding, k);
|
||||
return results.map(r => ({
|
||||
...this.metadata.get(r.id),
|
||||
distance: r.distance
|
||||
}));
|
||||
}
|
||||
|
||||
async embed(text) {
|
||||
// Simple embedding: TF-IDF + dimensionality reduction
|
||||
// Production: Use sentence-transformers or similar
|
||||
return textToEmbedding(text, this.dimensions);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Agent Router
|
||||
|
||||
Intelligent agent assignment based on context:
|
||||
|
||||
```javascript
|
||||
class AgentRouter {
|
||||
constructor(qLearning, vectorMemory) {
|
||||
this.q = qLearning;
|
||||
this.memory = vectorMemory;
|
||||
this.agentTypes = loadAgentTypes();
|
||||
}
|
||||
|
||||
async route(context) {
|
||||
const state = encodeState(context);
|
||||
|
||||
// 1. Check Q-learning suggestion
|
||||
const qSuggestion = this.q.selectAction(state);
|
||||
const qConfidence = this.q.getQ(state, qSuggestion);
|
||||
|
||||
// 2. Check similar past edits
|
||||
const similar = await this.memory.search(context.file, 3);
|
||||
const historyAgent = this.majorityVote(similar);
|
||||
|
||||
// 3. Apply file type heuristics
|
||||
const heuristicAgent = this.fileTypeHeuristic(context.file);
|
||||
|
||||
// 4. Combine signals
|
||||
return this.combine({
|
||||
q: { agent: qSuggestion, confidence: qConfidence },
|
||||
history: { agent: historyAgent, confidence: similar.length / 3 },
|
||||
heuristic: { agent: heuristicAgent, confidence: 0.5 }
|
||||
});
|
||||
}
|
||||
|
||||
fileTypeHeuristic(file) {
|
||||
const ext = path.extname(file);
|
||||
const mapping = {
|
||||
'.rs': 'rust-developer',
|
||||
'.ts': 'typescript-developer',
|
||||
'.tsx': 'react-developer',
|
||||
'.py': 'python-developer',
|
||||
'.go': 'go-developer',
|
||||
'.sql': 'database-specialist',
|
||||
};
|
||||
return mapping[ext] || 'coder';
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Hook Execution Flow
|
||||
|
||||
### PreToolUse Flow
|
||||
|
||||
```
|
||||
┌─────────────────┐
|
||||
│ Claude Code │
|
||||
│ Tool Request │
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Match Hooks │ ──► No match ──► Execute Tool
|
||||
│ (Regex/Type) │
|
||||
└────────┬────────┘
|
||||
│ Match
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Execute Hook │ timeout: 3000ms
|
||||
│ Command │
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Parse Result │
|
||||
│ (JSON/stdout) │
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌────┴────┐
|
||||
│continue?│
|
||||
└────┬────┘
|
||||
│ │
|
||||
Yes No
|
||||
│ │
|
||||
▼ ▼
|
||||
Execute Block
|
||||
Tool Tool
|
||||
```
|
||||
|
||||
### PostToolUse Flow
|
||||
|
||||
```
|
||||
┌─────────────────┐
|
||||
│ Tool Completed │
|
||||
│ (Result Ready) │
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Match Hooks │
|
||||
│ (Regex/Type) │
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Execute Hook │ (async, non-blocking)
|
||||
│ Command │
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Intelligence │
|
||||
│ Update │
|
||||
└────────┬────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────┐
|
||||
│ Q-value Train │
|
||||
│ Memory Store │
|
||||
│ Pattern Update │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
### Session Hook Flow
|
||||
|
||||
```
|
||||
Session Start Session End
|
||||
│ │
|
||||
▼ ▼
|
||||
┌──────────┐ ┌──────────┐
|
||||
│ Load │ │ Persist │
|
||||
│ Config │ │ State │
|
||||
└────┬─────┘ └────┬─────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌──────────┐ ┌──────────┐
|
||||
│ Restore │ │ Export │
|
||||
│ Memory │ │ Metrics │
|
||||
└────┬─────┘ └────┬─────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌──────────┐ ┌──────────┐
|
||||
│ Display │ │ Generate │
|
||||
│ Status │ │ Summary │
|
||||
└──────────┘ └──────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Data Storage
|
||||
|
||||
### Directory Structure
|
||||
|
||||
```
|
||||
Project Root
|
||||
├── .ruvector/ # Project-local data
|
||||
│ ├── config.toml # Configuration
|
||||
│ ├── intelligence/
|
||||
│ │ ├── memory.json # Vector memory (JSON fallback)
|
||||
│ │ ├── patterns.json # Q-learning patterns
|
||||
│ │ ├── trajectories.json # Learning history
|
||||
│ │ ├── feedback.json # User feedback
|
||||
│ │ └── memory.rvdb # RvLite vector database
|
||||
│ ├── logs/
|
||||
│ │ └── hooks-YYYY-MM-DD.log # Daily logs
|
||||
│ └── .gitignore
|
||||
│
|
||||
└── .claude/
|
||||
└── settings.json # Hook configurations
|
||||
|
||||
Global (~/.ruvector/)
|
||||
├── global/
|
||||
│ ├── patterns.json # Cross-project patterns
|
||||
│ ├── memory.rvdb # Global vector memory
|
||||
│ └── sequences.json # Common file sequences
|
||||
├── config.toml # Global configuration
|
||||
└── cache/
|
||||
└── cli-path.txt # Cached CLI location
|
||||
```
|
||||
|
||||
### Data Formats
|
||||
|
||||
#### patterns.json (Q-Learning)
|
||||
|
||||
```json
|
||||
{
|
||||
"edit_rs_in_ruvector-core": {
|
||||
"rust-developer": {
|
||||
"q_value": 0.823,
|
||||
"update_count": 47,
|
||||
"last_update": "2025-12-27T10:30:00Z"
|
||||
},
|
||||
"coder": {
|
||||
"q_value": 0.312,
|
||||
"update_count": 5,
|
||||
"last_update": "2025-12-20T14:22:00Z"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### trajectories.json (Learning History)
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": "traj_001",
|
||||
"state": "edit_rs_in_ruvector-core",
|
||||
"action": "rust-developer",
|
||||
"outcome": "success",
|
||||
"reward": 1.0,
|
||||
"timestamp": "2025-12-27T10:30:00Z",
|
||||
"ab_group": "treatment",
|
||||
"metadata": {
|
||||
"file": "crates/ruvector-core/src/lib.rs",
|
||||
"duration_ms": 1500
|
||||
}
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
#### memory.rvdb (Vector Database)
|
||||
|
||||
RvLite database with HNSW indexing:
|
||||
|
||||
```sql
|
||||
-- Schema (auto-created)
|
||||
CREATE TABLE memories (
|
||||
id TEXT PRIMARY KEY,
|
||||
embedding VECTOR(128),
|
||||
content TEXT,
|
||||
metadata JSON,
|
||||
created_at TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX memories_hnsw ON memories USING hnsw (embedding);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration Points
|
||||
|
||||
### Claude Code Integration
|
||||
|
||||
Hook configuration in `.claude/settings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "pattern", // Regex for tool name
|
||||
"hooks": [{
|
||||
"type": "command", // Shell command
|
||||
"command": "...", // Command to execute
|
||||
"timeout": 3000 // Timeout in ms
|
||||
}]
|
||||
}],
|
||||
"PostToolUse": [...],
|
||||
"SessionStart": [...],
|
||||
"Stop": [...] // Session end
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Claude-Flow Integration
|
||||
|
||||
MCP tool coordination:
|
||||
|
||||
```javascript
|
||||
// Pre-task hook with MCP
|
||||
async function preTask(description) {
|
||||
// Store in coordination memory
|
||||
await mcp__claude_flow__memory_usage({
|
||||
action: "store",
|
||||
key: "swarm/task/current",
|
||||
namespace: "coordination",
|
||||
value: JSON.stringify({ description, started: Date.now() })
|
||||
});
|
||||
|
||||
// Spawn recommended agents
|
||||
const agents = analyzeTaskNeeds(description);
|
||||
for (const agent of agents) {
|
||||
await mcp__claude_flow__agent_spawn({ type: agent });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Git Integration
|
||||
|
||||
Pre-commit hook example:
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# .git/hooks/pre-commit
|
||||
|
||||
# Run RuVector pre-edit on staged files
|
||||
FILES=$(git diff --cached --name-only --diff-filter=ACM)
|
||||
|
||||
for FILE in $FILES; do
|
||||
RESULT=$(npx ruvector hooks pre-edit --file "$FILE" --validate-syntax)
|
||||
CONTINUE=$(echo "$RESULT" | jq -r '.continue')
|
||||
|
||||
if [ "$CONTINUE" = "false" ]; then
|
||||
echo "Pre-edit hook blocked: $FILE"
|
||||
echo "$RESULT" | jq -r '.reason'
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Security Model
|
||||
|
||||
### Command Injection Prevention
|
||||
|
||||
All user inputs are escaped:
|
||||
|
||||
```rust
|
||||
use shell_escape::escape;
|
||||
|
||||
fn generate_hook_command(file_path: &str) -> String {
|
||||
let escaped = escape(file_path.into());
|
||||
format!(
|
||||
r#"/bin/bash -c 'npx ruvector hooks pre-edit --file {}'"#,
|
||||
escaped
|
||||
)
|
||||
}
|
||||
|
||||
// Prevents: "; rm -rf /" attacks
|
||||
// file_path = "test.ts; rm -rf /"
|
||||
// escaped = "'test.ts; rm -rf /'" (treated as literal string)
|
||||
```
|
||||
|
||||
### Timeout Protection
|
||||
|
||||
Hooks cannot hang indefinitely:
|
||||
|
||||
```javascript
|
||||
async function executeHookSafely(hook, timeout = 3000) {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
try {
|
||||
const result = await executeHook(hook, { signal: controller.signal });
|
||||
clearTimeout(timeoutId);
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') {
|
||||
console.warn('Hook timeout, continuing...');
|
||||
return { continue: true, reason: 'timeout' };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Graceful Failure
|
||||
|
||||
Hooks never block tool execution:
|
||||
|
||||
```javascript
|
||||
async function runPreHook(tool, context) {
|
||||
try {
|
||||
const result = await executeHookSafely(hook);
|
||||
return result.continue !== false;
|
||||
} catch (error) {
|
||||
console.warn(`Hook failed: ${error.message}`);
|
||||
return true; // Continue on error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Caching Strategy
|
||||
|
||||
```javascript
|
||||
class IntelligenceCache {
|
||||
constructor(maxAge = 300000) { // 5 minutes
|
||||
this.cache = new Map();
|
||||
this.maxAge = maxAge;
|
||||
}
|
||||
|
||||
get(key) {
|
||||
const entry = this.cache.get(key);
|
||||
if (!entry) return null;
|
||||
if (Date.now() - entry.timestamp > this.maxAge) {
|
||||
this.cache.delete(key);
|
||||
return null;
|
||||
}
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
set(key, value) {
|
||||
this.cache.set(key, { value, timestamp: Date.now() });
|
||||
}
|
||||
}
|
||||
|
||||
// Cache agent routing decisions
|
||||
const routingCache = new IntelligenceCache();
|
||||
|
||||
async function getAgent(file) {
|
||||
const cached = routingCache.get(file);
|
||||
if (cached) return cached;
|
||||
|
||||
const agent = await computeAgent(file);
|
||||
routingCache.set(file, agent);
|
||||
return agent;
|
||||
}
|
||||
```
|
||||
|
||||
### Async Operations
|
||||
|
||||
Non-blocking post-hooks:
|
||||
|
||||
```javascript
|
||||
// Fire-and-forget for training
|
||||
function postEditHook(file, success) {
|
||||
// Synchronous: quick response
|
||||
const response = { continue: true, formatted: true };
|
||||
|
||||
// Async: training (non-blocking)
|
||||
setImmediate(() => {
|
||||
trainPatterns(file, success).catch(console.warn);
|
||||
updateMemory(file).catch(console.warn);
|
||||
recordTrajectory(file, success).catch(console.warn);
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
```
|
||||
|
||||
### Batch Operations
|
||||
|
||||
Reduce I/O with batching:
|
||||
|
||||
```javascript
|
||||
class BatchWriter {
|
||||
constructor(flushInterval = 5000) {
|
||||
this.queue = [];
|
||||
this.interval = setInterval(() => this.flush(), flushInterval);
|
||||
}
|
||||
|
||||
add(item) {
|
||||
this.queue.push(item);
|
||||
}
|
||||
|
||||
async flush() {
|
||||
if (this.queue.length === 0) return;
|
||||
|
||||
const batch = this.queue.splice(0);
|
||||
await fs.appendFile(
|
||||
'trajectories.json',
|
||||
batch.map(JSON.stringify).join('\n') + '\n'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const trajectoryWriter = new BatchWriter();
|
||||
```
|
||||
|
||||
### Performance Targets
|
||||
|
||||
| Operation | Target | Typical |
|
||||
|-----------|--------|---------|
|
||||
| Pre-edit hook | <50ms | 30ms |
|
||||
| Post-edit hook | <100ms | 60ms |
|
||||
| Session start | <200ms | 150ms |
|
||||
| Memory search | <10ms | 5ms |
|
||||
| Q-value lookup | <1ms | 0.1ms |
|
||||
| Total overhead | <100ms | 70ms |
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [User Guide](USER_GUIDE.md) - Getting started
|
||||
- [CLI Reference](CLI_REFERENCE.md) - Command documentation
|
||||
- [Migration Guide](MIGRATION.md) - Upgrade from other systems
|
||||
- [Implementation Plan](IMPLEMENTATION_PLAN.md) - Development roadmap
|
||||
1081
vendor/ruvector/docs/hooks/CLI_REFERENCE.md
vendored
Normal file
1081
vendor/ruvector/docs/hooks/CLI_REFERENCE.md
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1321
vendor/ruvector/docs/hooks/IMPLEMENTATION_PLAN.md
vendored
Normal file
1321
vendor/ruvector/docs/hooks/IMPLEMENTATION_PLAN.md
vendored
Normal file
File diff suppressed because it is too large
Load Diff
581
vendor/ruvector/docs/hooks/MIGRATION.md
vendored
Normal file
581
vendor/ruvector/docs/hooks/MIGRATION.md
vendored
Normal file
@@ -0,0 +1,581 @@
|
||||
# RuVector Hooks Migration Guide
|
||||
|
||||
Guide for migrating to RuVector's portable hooks system from legacy setups or other tools.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Overview](#overview)
|
||||
2. [Migration Paths](#migration-paths)
|
||||
3. [From Legacy Intelligence](#from-legacy-intelligence)
|
||||
4. [From Claude-Flow](#from-claude-flow)
|
||||
5. [From Manual Setup](#from-manual-setup)
|
||||
6. [Data Preservation](#data-preservation)
|
||||
7. [Verification](#verification)
|
||||
8. [Rollback](#rollback)
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
### Why Migrate?
|
||||
|
||||
The new RuVector hooks system provides:
|
||||
|
||||
| Feature | Legacy | New System |
|
||||
|---------|--------|------------|
|
||||
| Portability | Hardcoded paths | Dynamic resolution |
|
||||
| CLI Management | Manual JSON editing | Full CLI support |
|
||||
| Cross-platform | Linux/macOS only | Linux, macOS, Windows |
|
||||
| Global Patterns | Not available | Supported |
|
||||
| Binary Updates | Hooks break | Survive reinstalls |
|
||||
|
||||
### Migration Safety
|
||||
|
||||
All migrations include:
|
||||
- **Automatic backup** of existing data
|
||||
- **Validation** of migrated data
|
||||
- **Atomic operations** with rollback capability
|
||||
- **Zero data loss** guarantee
|
||||
|
||||
---
|
||||
|
||||
## Migration Paths
|
||||
|
||||
### Quick Reference
|
||||
|
||||
| Source | Command | Time |
|
||||
|--------|---------|------|
|
||||
| Legacy `.claude/intelligence/` | `hooks migrate --from .claude/intelligence` | <5s |
|
||||
| Claude-flow `memory.db` | `hooks migrate --from ~/.swarm/memory.db` | <10s |
|
||||
| Exported JSON | `hooks import --input patterns.json` | <2s |
|
||||
| Fresh start | `hooks init` | <1s |
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before migrating:
|
||||
|
||||
```bash
|
||||
# 1. Backup existing data
|
||||
cp -r .claude/intelligence .claude/intelligence.backup
|
||||
cp -r ~/.swarm ~/.swarm.backup
|
||||
|
||||
# 2. Install latest RuVector CLI
|
||||
npm install -g @ruvector/cli@latest
|
||||
|
||||
# 3. Verify installation
|
||||
npx ruvector --version
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## From Legacy Intelligence
|
||||
|
||||
Migrate from the repository-specific `.claude/intelligence/` system.
|
||||
|
||||
### Current Legacy Structure
|
||||
|
||||
```
|
||||
.claude/
|
||||
├── intelligence/
|
||||
│ ├── data/
|
||||
│ │ ├── memory.json # Vector memories
|
||||
│ │ ├── trajectories.json # Learning history
|
||||
│ │ ├── patterns.json # Q-learning patterns
|
||||
│ │ └── feedback.json # User feedback
|
||||
│ ├── index.js # Intelligence layer
|
||||
│ └── cli.js # CLI commands
|
||||
└── settings.json # Hardcoded hooks
|
||||
```
|
||||
|
||||
### Migration Steps
|
||||
|
||||
#### Step 1: Initialize New System
|
||||
|
||||
```bash
|
||||
npx ruvector hooks init
|
||||
```
|
||||
|
||||
This creates:
|
||||
```
|
||||
.ruvector/
|
||||
├── config.toml
|
||||
├── intelligence/
|
||||
│ └── (empty, ready for migration)
|
||||
└── .gitignore
|
||||
```
|
||||
|
||||
#### Step 2: Migrate Data
|
||||
|
||||
```bash
|
||||
# Migrate with validation
|
||||
npx ruvector hooks migrate \
|
||||
--from .claude/intelligence \
|
||||
--validate
|
||||
|
||||
# Expected output:
|
||||
# Migrating from JSON files...
|
||||
# ✓ Imported 1,247 trajectories
|
||||
# ✓ Imported 89 Q-learning patterns
|
||||
# ✓ Converted 543 memories to vectors
|
||||
# ✓ Validation passed (100% integrity)
|
||||
# ⏱ Completed in 3.2s
|
||||
```
|
||||
|
||||
#### Step 3: Install New Hooks
|
||||
|
||||
```bash
|
||||
# Install portable hooks
|
||||
npx ruvector hooks install --force
|
||||
|
||||
# This replaces hardcoded paths with dynamic resolution
|
||||
```
|
||||
|
||||
#### Step 4: Verify Migration
|
||||
|
||||
```bash
|
||||
# Check statistics
|
||||
npx ruvector hooks stats --verbose
|
||||
|
||||
# Should show migrated data:
|
||||
# Patterns: 89
|
||||
# Memories: 543
|
||||
# Trajectories: 1,247
|
||||
```
|
||||
|
||||
#### Step 5: Clean Up (Optional)
|
||||
|
||||
After confirming migration success:
|
||||
|
||||
```bash
|
||||
# Remove legacy intelligence directory
|
||||
rm -rf .claude/intelligence
|
||||
|
||||
# Keep backup for safety
|
||||
# rm -rf .claude/intelligence.backup # Only if confident
|
||||
```
|
||||
|
||||
### Legacy Settings.json Update
|
||||
|
||||
**Before (hardcoded):**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"command": "/bin/bash -c 'cd /workspaces/ruvector/.claude/intelligence && node cli.js pre-command'"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**After (portable):**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"command": "/bin/bash -c 'RUVECTOR=$(which ruvector || echo npx ruvector); $RUVECTOR hooks pre-command \"$CMD\"'"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## From Claude-Flow
|
||||
|
||||
Migrate from Claude-Flow's SQLite memory database.
|
||||
|
||||
### Claude-Flow Structure
|
||||
|
||||
```
|
||||
~/.swarm/
|
||||
├── memory.db # SQLite database
|
||||
├── config.json # Configuration
|
||||
└── sessions/ # Session data
|
||||
```
|
||||
|
||||
### Migration Steps
|
||||
|
||||
#### Step 1: Locate Memory Database
|
||||
|
||||
```bash
|
||||
# Default location
|
||||
ls ~/.swarm/memory.db
|
||||
|
||||
# Custom location (check config)
|
||||
cat ~/.swarm/config.json | jq '.memoryPath'
|
||||
```
|
||||
|
||||
#### Step 2: Initialize RuVector
|
||||
|
||||
```bash
|
||||
cd your-project
|
||||
npx ruvector hooks init
|
||||
```
|
||||
|
||||
#### Step 3: Migrate SQLite Data
|
||||
|
||||
```bash
|
||||
# Migrate from SQLite
|
||||
npx ruvector hooks migrate \
|
||||
--from ~/.swarm/memory.db \
|
||||
--format sqlite \
|
||||
--validate
|
||||
|
||||
# Output:
|
||||
# Migrating from SQLite database...
|
||||
# ✓ Extracted 2,500 trajectories
|
||||
# ✓ Converted 150 Q-learning patterns
|
||||
# ✓ Migrated 1,200 memories to vectors
|
||||
# ✓ Validation passed
|
||||
```
|
||||
|
||||
**Note:** SQLite migration requires the `sqlite-migration` feature (v1.1+). For MVP, use JSON export:
|
||||
|
||||
```bash
|
||||
# Alternative: Export from claude-flow first
|
||||
npx claude-flow memory export --output memory-export.json
|
||||
|
||||
# Then import
|
||||
npx ruvector hooks import --input memory-export.json
|
||||
```
|
||||
|
||||
#### Step 4: Merge with Existing Data
|
||||
|
||||
If you have both legacy and claude-flow data:
|
||||
|
||||
```bash
|
||||
# Merge with existing patterns
|
||||
npx ruvector hooks migrate \
|
||||
--from ~/.swarm/memory.db \
|
||||
--merge \
|
||||
--strategy average
|
||||
```
|
||||
|
||||
#### Step 5: Install Hooks
|
||||
|
||||
```bash
|
||||
npx ruvector hooks install
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## From Manual Setup
|
||||
|
||||
Migrate from manually configured hooks.
|
||||
|
||||
### Current Manual Setup
|
||||
|
||||
**`.claude/settings.json` (manual):**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Write|Edit",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "echo 'Pre-edit hook'"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Migration Steps
|
||||
|
||||
#### Step 1: Backup Existing Settings
|
||||
|
||||
```bash
|
||||
cp .claude/settings.json .claude/settings.json.manual-backup
|
||||
```
|
||||
|
||||
#### Step 2: Initialize RuVector
|
||||
|
||||
```bash
|
||||
npx ruvector hooks init
|
||||
```
|
||||
|
||||
#### Step 3: Install with Merge
|
||||
|
||||
```bash
|
||||
# Merge RuVector hooks with existing
|
||||
npx ruvector hooks install --merge
|
||||
|
||||
# This preserves your custom hooks and adds RuVector hooks
|
||||
```
|
||||
|
||||
#### Step 4: Review Merged Settings
|
||||
|
||||
```bash
|
||||
# View the merged settings
|
||||
cat .claude/settings.json
|
||||
|
||||
# Verify your custom hooks are preserved
|
||||
```
|
||||
|
||||
### Preserving Custom Hooks
|
||||
|
||||
If you have custom hooks to preserve:
|
||||
|
||||
**Before install:**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "CustomTool",
|
||||
"hooks": [{
|
||||
"command": "my-custom-hook.sh"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**After install (merged):**
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"command": "npx ruvector hooks pre-command"
|
||||
}]
|
||||
},
|
||||
{
|
||||
"matcher": "CustomTool",
|
||||
"hooks": [{
|
||||
"command": "my-custom-hook.sh"
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Data Preservation
|
||||
|
||||
### What Gets Migrated
|
||||
|
||||
| Data Type | Source | Destination |
|
||||
|-----------|--------|-------------|
|
||||
| Q-learning patterns | `patterns.json` | `.ruvector/intelligence/patterns.json` |
|
||||
| Trajectories | `trajectories.json` | `.ruvector/intelligence/trajectories.json` |
|
||||
| Vector memories | `memory.json` | `.ruvector/intelligence/memory.rvdb` |
|
||||
| Feedback data | `feedback.json` | `.ruvector/intelligence/feedback.json` |
|
||||
| Configuration | settings.json | `.ruvector/config.toml` |
|
||||
|
||||
### Data Integrity Checks
|
||||
|
||||
The migration process includes:
|
||||
|
||||
1. **Checksum validation**: Verify data wasn't corrupted
|
||||
2. **Count verification**: Ensure all records migrated
|
||||
3. **Q-value preservation**: Maintain learned values
|
||||
4. **Vector accuracy**: Preserve embedding precision
|
||||
|
||||
### Backup Locations
|
||||
|
||||
Automatic backups are created:
|
||||
|
||||
```
|
||||
.ruvector/
|
||||
├── intelligence/
|
||||
│ └── backup-YYYYMMDD-HHMMSS/
|
||||
│ ├── patterns.json
|
||||
│ ├── trajectories.json
|
||||
│ └── memory.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verification
|
||||
|
||||
### Verify Migration Success
|
||||
|
||||
```bash
|
||||
# 1. Check statistics
|
||||
npx ruvector hooks stats --verbose
|
||||
|
||||
# 2. Compare counts
|
||||
echo "Legacy patterns: $(jq '.patterns | length' .claude/intelligence.backup/data/patterns.json 2>/dev/null || echo 0)"
|
||||
echo "Migrated patterns: $(npx ruvector hooks stats --json | jq '.patterns')"
|
||||
|
||||
# 3. Test hook execution
|
||||
npx ruvector hooks pre-edit --file test.ts
|
||||
npx ruvector hooks post-edit --file test.ts --success true
|
||||
|
||||
# 4. Verify session hooks
|
||||
npx ruvector hooks session-start --session-id "migration-test"
|
||||
npx ruvector hooks session-end --session-id "migration-test"
|
||||
```
|
||||
|
||||
### Expected Verification Output
|
||||
|
||||
```bash
|
||||
$ npx ruvector hooks stats --verbose
|
||||
|
||||
RuVector Intelligence Statistics
|
||||
================================
|
||||
|
||||
Data Migration Status: SUCCESS
|
||||
|
||||
Learning Data:
|
||||
Trajectories: 1,247 (migrated: 1,247)
|
||||
Patterns: 89 (migrated: 89)
|
||||
Memories: 543 vectors (migrated: 543)
|
||||
Integrity: 100%
|
||||
|
||||
Configuration:
|
||||
Hooks installed: Yes
|
||||
Portable paths: Yes
|
||||
Intelligence enabled: Yes
|
||||
```
|
||||
|
||||
### Test in Claude Code
|
||||
|
||||
1. Open Claude Code in your project
|
||||
2. Verify session start message appears
|
||||
3. Make an edit to a file
|
||||
4. Confirm agent assignment message
|
||||
5. Check post-edit formatting
|
||||
|
||||
---
|
||||
|
||||
## Rollback
|
||||
|
||||
### Automatic Rollback
|
||||
|
||||
If migration fails, automatic rollback occurs:
|
||||
|
||||
```bash
|
||||
$ npx ruvector hooks migrate --from .claude/intelligence
|
||||
|
||||
Migrating from JSON files...
|
||||
✓ Imported 1,247 trajectories
|
||||
✗ Error during pattern migration: Invalid Q-value format
|
||||
⟲ Rolling back migration...
|
||||
✓ Restored from backup
|
||||
Migration failed, original data preserved
|
||||
```
|
||||
|
||||
### Manual Rollback
|
||||
|
||||
To manually rollback:
|
||||
|
||||
#### Step 1: Restore Backup
|
||||
|
||||
```bash
|
||||
# Restore intelligence data
|
||||
rm -rf .ruvector/intelligence
|
||||
cp -r .ruvector/intelligence/backup-YYYYMMDD-HHMMSS/* .ruvector/intelligence/
|
||||
|
||||
# Or restore legacy location
|
||||
rm -rf .ruvector
|
||||
mv .claude/intelligence.backup .claude/intelligence
|
||||
```
|
||||
|
||||
#### Step 2: Restore Settings
|
||||
|
||||
```bash
|
||||
# Restore Claude settings
|
||||
cp .claude/settings.json.backup .claude/settings.json
|
||||
```
|
||||
|
||||
#### Step 3: Verify Restoration
|
||||
|
||||
```bash
|
||||
# For legacy
|
||||
node .claude/intelligence/cli.js stats
|
||||
|
||||
# For new system
|
||||
npx ruvector hooks stats
|
||||
```
|
||||
|
||||
### Complete Reset
|
||||
|
||||
To completely reset and start fresh:
|
||||
|
||||
```bash
|
||||
# Remove all RuVector data
|
||||
rm -rf .ruvector
|
||||
|
||||
# Remove from Claude settings
|
||||
# Edit .claude/settings.json to remove hooks section
|
||||
|
||||
# Reinitialize
|
||||
npx ruvector hooks init
|
||||
npx ruvector hooks install
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Migration FAQ
|
||||
|
||||
### Q: Will I lose my learned patterns?
|
||||
|
||||
**A:** No. All migrations include automatic backup and validation. Q-values, trajectories, and memories are preserved with 100% integrity.
|
||||
|
||||
### Q: Can I migrate incrementally?
|
||||
|
||||
**A:** Yes. Use the `--merge` flag to add new data without replacing existing:
|
||||
|
||||
```bash
|
||||
npx ruvector hooks migrate --from new-data.json --merge
|
||||
```
|
||||
|
||||
### Q: What about Windows compatibility?
|
||||
|
||||
**A:** The new system uses conditional shell detection:
|
||||
|
||||
```bash
|
||||
# Windows
|
||||
cmd /c 'npx ruvector hooks ...'
|
||||
|
||||
# Linux/macOS
|
||||
/bin/bash -c 'npx ruvector hooks ...'
|
||||
```
|
||||
|
||||
### Q: How do I migrate a team project?
|
||||
|
||||
**A:** Export and share patterns:
|
||||
|
||||
```bash
|
||||
# Team member 1: Export
|
||||
npx ruvector hooks export --output team-patterns.json
|
||||
|
||||
# Team member 2: Import and merge
|
||||
npx ruvector hooks import --input team-patterns.json --merge
|
||||
```
|
||||
|
||||
### Q: Is the migration reversible?
|
||||
|
||||
**A:** Yes. Backups are automatically created and manual rollback is always possible.
|
||||
|
||||
---
|
||||
|
||||
## Post-Migration Checklist
|
||||
|
||||
- [ ] `npx ruvector hooks stats` shows expected counts
|
||||
- [ ] Session hooks trigger on Claude Code start
|
||||
- [ ] Pre-edit hooks assign agents correctly
|
||||
- [ ] Post-edit hooks format code
|
||||
- [ ] No hardcoded paths in `.claude/settings.json`
|
||||
- [ ] Backup data stored safely
|
||||
- [ ] Team notified of migration (if applicable)
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [User Guide](USER_GUIDE.md) - Getting started
|
||||
- [CLI Reference](CLI_REFERENCE.md) - Command documentation
|
||||
- [Architecture](ARCHITECTURE.md) - Technical details
|
||||
- [Troubleshooting](TROUBLESHOOTING.md) - Common issues
|
||||
404
vendor/ruvector/docs/hooks/MVP_CHECKLIST.md
vendored
Normal file
404
vendor/ruvector/docs/hooks/MVP_CHECKLIST.md
vendored
Normal file
@@ -0,0 +1,404 @@
|
||||
# Hooks System MVP - Implementation Checklist
|
||||
|
||||
> **Related Documentation**: [README](README.md) | [Implementation Plan](IMPLEMENTATION_PLAN.md) | [Architecture](ARCHITECTURE.md)
|
||||
|
||||
**Target**: 3-4 weeks | **Status**: Ready for Development
|
||||
**Feature Branch**: `feature/portable-hooks-mvp`
|
||||
|
||||
---
|
||||
|
||||
## Week 1: Foundation & CLI Scaffolding
|
||||
|
||||
### Day 1-2: Project Setup
|
||||
- [ ] Create feature branch `feature/portable-hooks-mvp`
|
||||
- [ ] Update `crates/ruvector-cli/Cargo.toml`:
|
||||
```toml
|
||||
[dependencies]
|
||||
askama = "0.12"
|
||||
shell-escape = "0.1"
|
||||
```
|
||||
- [ ] Create directory structure:
|
||||
```
|
||||
crates/ruvector-cli/
|
||||
├── src/cli/hooks/
|
||||
│ ├── mod.rs
|
||||
│ ├── init.rs
|
||||
│ ├── install.rs
|
||||
│ ├── migrate.rs
|
||||
│ └── stats.rs
|
||||
└── templates/
|
||||
├── hooks.json.j2
|
||||
├── config.toml.j2
|
||||
└── gitignore.j2
|
||||
```
|
||||
- [ ] Write specification document (API contracts)
|
||||
- [ ] Design template schema with variable placeholders
|
||||
|
||||
### Day 3-4: CLI Command Structure
|
||||
- [ ] Add `Hooks` enum to `src/cli/commands.rs`:
|
||||
```rust
|
||||
enum Commands {
|
||||
// ... existing commands
|
||||
Hooks {
|
||||
#[command(subcommand)]
|
||||
action: HooksCommands,
|
||||
},
|
||||
}
|
||||
|
||||
enum HooksCommands {
|
||||
Init { path: Option<PathBuf> },
|
||||
Install { force: bool },
|
||||
Migrate { from: PathBuf },
|
||||
Stats { verbose: bool },
|
||||
}
|
||||
```
|
||||
- [ ] Implement command routing in `main.rs`
|
||||
- [ ] Write unit tests for command parsing
|
||||
|
||||
### Day 5: Template Engine
|
||||
- [ ] Create `HookTemplate` struct with `askama`:
|
||||
```rust
|
||||
#[derive(Template)]
|
||||
#[template(path = "hooks.json.j2")]
|
||||
struct HookTemplate {
|
||||
shell: String,
|
||||
ruvector_cli: String,
|
||||
project_root: String,
|
||||
}
|
||||
```
|
||||
- [ ] Implement platform detection:
|
||||
```rust
|
||||
fn get_shell_wrapper() -> &'static str {
|
||||
if cfg!(target_os = "windows") { "cmd /c" }
|
||||
else { "/bin/bash -c" }
|
||||
}
|
||||
```
|
||||
- [ ] Write template rendering tests
|
||||
|
||||
---
|
||||
|
||||
## Week 2: Core Commands Implementation
|
||||
|
||||
### Day 6-7: `ruvector hooks init`
|
||||
- [ ] Implement `init.rs`:
|
||||
- [ ] Create `.ruvector/` directory
|
||||
- [ ] Generate `config.toml` from template
|
||||
- [ ] Create `intelligence/` subdirectories
|
||||
- [ ] Write `.gitignore`
|
||||
- [ ] Add validation checks (prevent overwriting existing)
|
||||
- [ ] Write integration test:
|
||||
```rust
|
||||
#[test]
|
||||
fn test_init_creates_structure() {
|
||||
let temp = tempdir()?;
|
||||
run_cmd(&["ruvector", "hooks", "init"], &temp)?;
|
||||
assert!(temp.join(".ruvector/config.toml").exists());
|
||||
}
|
||||
```
|
||||
|
||||
### Day 8-9: `ruvector hooks install`
|
||||
- [ ] Implement `install.rs`:
|
||||
- [ ] Load hook template
|
||||
- [ ] Substitute variables with runtime values
|
||||
- [ ] Merge with existing `.claude/settings.json` or create new
|
||||
- [ ] Create backup (`.claude/settings.json.backup`)
|
||||
- [ ] Add `--dry-run` flag
|
||||
- [ ] Implement JSON validation
|
||||
- [ ] Write tests for template substitution
|
||||
- [ ] Write tests for merge logic
|
||||
|
||||
### Day 10: Hook Template Design
|
||||
- [ ] Create `templates/hooks.json.j2`:
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"command": "{{ shell }} 'RUVECTOR=$(which ruvector || echo npx ruvector); $RUVECTOR hooks pre-command \"$CMD\"'"
|
||||
}]
|
||||
}],
|
||||
"PostToolUse": [/* ... */],
|
||||
"SessionStart": [/* ... */]
|
||||
}
|
||||
}
|
||||
```
|
||||
- [ ] Test on Linux (bash)
|
||||
- [ ] Test on macOS (bash)
|
||||
- [ ] Test on Windows (cmd)
|
||||
|
||||
---
|
||||
|
||||
## Week 3: Intelligence Layer & Migration
|
||||
|
||||
### Day 11-12: Intelligence Layer Refactoring
|
||||
- [ ] Update `.claude/intelligence/index.js`:
|
||||
- [ ] Change `DATA_DIR` to use `process.env.RUVECTOR_DATA_DIR`
|
||||
- [ ] Add fallback chain: env → project-local → global → legacy
|
||||
```javascript
|
||||
const DATA_DIR = process.env.RUVECTOR_DATA_DIR ||
|
||||
join(process.cwd(), '.ruvector', 'intelligence') ||
|
||||
join(process.env.HOME || process.env.USERPROFILE, '.ruvector', 'global') ||
|
||||
join(__dirname, 'data'); // Legacy fallback
|
||||
```
|
||||
- [ ] Update `cli.js` with same path logic
|
||||
- [ ] Test intelligence layer works in new location
|
||||
- [ ] Verify backward compatibility (legacy paths still work)
|
||||
|
||||
### Day 13-14: JSON Migration
|
||||
- [ ] Implement `migrate.rs`:
|
||||
- [ ] Copy function with validation:
|
||||
```rust
|
||||
fn copy_with_validation(from: &Path, to: &Path) -> Result<()> {
|
||||
let data = fs::read_to_string(from)?;
|
||||
let json: serde_json::Value = serde_json::from_str(&data)?;
|
||||
let mut file = File::create(to)?;
|
||||
serde_json::to_writer_pretty(&mut file, &json)?;
|
||||
file.sync_all()?;
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
- [ ] Implement atomic migration with rollback:
|
||||
```rust
|
||||
pub fn migrate_with_safety(from: &Path, to: &Path) -> Result<MigrationStats> {
|
||||
let backup = to.with_extension("backup");
|
||||
let temp = to.with_extension("tmp");
|
||||
|
||||
// Backup → Migrate to temp → Validate → Atomic swap
|
||||
}
|
||||
```
|
||||
- [ ] Add checksum validation
|
||||
- [ ] Write migration tests with sample data
|
||||
|
||||
### Day 15: `ruvector hooks stats`
|
||||
- [ ] Implement `stats.rs`:
|
||||
- [ ] Load patterns from `.ruvector/intelligence/patterns.json`
|
||||
- [ ] Calculate statistics (count, Q-values, top patterns)
|
||||
- [ ] Format output (pretty-print or JSON)
|
||||
- [ ] Add `--verbose` and `--json` flags
|
||||
- [ ] Test with empty/populated data
|
||||
|
||||
---
|
||||
|
||||
## Week 4: Testing, Documentation & Polish
|
||||
|
||||
### Day 16-17: Cross-Platform Testing
|
||||
- [ ] Set up GitHub Actions CI:
|
||||
```yaml
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
```
|
||||
- [ ] Linux tests:
|
||||
- [ ] Fresh project init
|
||||
- [ ] Migration from `.claude/intelligence/`
|
||||
- [ ] Hooks trigger correctly
|
||||
- [ ] macOS tests (same as Linux)
|
||||
- [ ] Windows tests:
|
||||
- [ ] PowerShell environment
|
||||
- [ ] CMD environment
|
||||
- [ ] WSL environment
|
||||
- [ ] Path separator handling (`\` vs `/`)
|
||||
|
||||
### Day 18: Error Handling & Edge Cases
|
||||
- [ ] Implement graceful hook failures:
|
||||
```rust
|
||||
pub fn execute_hook_safely(hook: &HookCommand) -> Result<()> {
|
||||
match hook.execute().timeout(Duration::from_secs(3)) {
|
||||
Ok(Ok(_)) => Ok(()),
|
||||
Ok(Err(e)) => {
|
||||
eprintln!("⚠️ Hook failed: {}", e);
|
||||
Ok(()) // Non-fatal
|
||||
}
|
||||
Err(_) => {
|
||||
eprintln!("⚠️ Hook timeout");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
- [ ] Test with missing dependencies (`jq` not installed)
|
||||
- [ ] Test with corrupted JSON files
|
||||
- [ ] Test with permission errors
|
||||
|
||||
### Day 19: Documentation
|
||||
- [ ] Write `docs/hooks/USER_GUIDE.md`:
|
||||
- [ ] Quick start (5-minute setup)
|
||||
- [ ] Migration guide
|
||||
- [ ] Troubleshooting
|
||||
- [ ] Configuration reference
|
||||
- [ ] Write `docs/hooks/CLI_REFERENCE.md`:
|
||||
- [ ] Each command with examples
|
||||
- [ ] All flags documented
|
||||
- [ ] Return codes and errors
|
||||
- [ ] Update `README.md` with hooks section
|
||||
- [ ] Add examples to `examples/hooks/`
|
||||
|
||||
### Day 20: Final Polish
|
||||
- [ ] Run `cargo clippy` and fix warnings
|
||||
- [ ] Run `cargo fmt`
|
||||
- [ ] Verify test coverage >80%:
|
||||
```bash
|
||||
cargo tarpaulin --out Html
|
||||
```
|
||||
- [ ] Write release notes
|
||||
- [ ] Tag version `v0.2.0-mvp`
|
||||
|
||||
---
|
||||
|
||||
## Post-MVP: v1.1 Planning (Future)
|
||||
|
||||
### SQLite Migration (v1.1.0)
|
||||
- [ ] Add `rusqlite = { version = "0.32", optional = true }`
|
||||
- [ ] Implement format detection:
|
||||
```rust
|
||||
fn detect_embedding_format(blob: &[u8]) -> EmbeddingFormat {
|
||||
if blob.starts_with(b"\x93NUMPY") { Numpy }
|
||||
else if blob.len() % 4 == 0 { RawF32 }
|
||||
else { Unknown }
|
||||
}
|
||||
```
|
||||
- [ ] Write SQLite → rvlite converter
|
||||
- [ ] Add `--format` flag to `hooks migrate`
|
||||
|
||||
### Global Patterns System (v1.1.0)
|
||||
- [ ] Design sync protocol
|
||||
- [ ] Implement pattern merge algorithm
|
||||
- [ ] Add privacy controls (opt-in/opt-out)
|
||||
- [ ] Implement `hooks export` and `hooks import`
|
||||
|
||||
---
|
||||
|
||||
## Testing Checklist
|
||||
|
||||
### Unit Tests
|
||||
- [ ] Template rendering (all platforms)
|
||||
- [ ] Path resolution (Windows vs Unix)
|
||||
- [ ] Command parsing (clap)
|
||||
- [ ] JSON validation
|
||||
- [ ] Migration rollback logic
|
||||
|
||||
### Integration Tests
|
||||
- [ ] End-to-end: init → install → test hook triggers
|
||||
- [ ] Migration preserves data integrity
|
||||
- [ ] Hooks work after binary reinstallation
|
||||
- [ ] Backward compatibility with legacy paths
|
||||
|
||||
### Manual Testing
|
||||
- [ ] Fresh Ubuntu 22.04 VM
|
||||
- [ ] Fresh macOS 14 VM
|
||||
- [ ] Fresh Windows 11 VM (PowerShell)
|
||||
- [ ] Codespaces environment
|
||||
- [ ] GitHub Codespaces with Claude Code
|
||||
|
||||
---
|
||||
|
||||
## Definition of Done
|
||||
|
||||
### MVP Release Criteria
|
||||
- ✅ All tests pass on Linux, macOS, Windows
|
||||
- ✅ Test coverage >80%
|
||||
- ✅ Documentation complete (USER_GUIDE + CLI_REFERENCE)
|
||||
- ✅ Zero clippy warnings
|
||||
- ✅ Manual testing on 3 platforms
|
||||
- ✅ Migration tested with sample data (no data loss)
|
||||
- ✅ Hooks survive binary reinstallation
|
||||
- ✅ First-time setup completes in <5 minutes
|
||||
|
||||
### Performance Targets
|
||||
- ✅ `hooks init` completes in <1 second
|
||||
- ✅ `hooks install` completes in <2 seconds
|
||||
- ✅ `hooks migrate` processes 1000 trajectories in <5 seconds
|
||||
- ✅ Hook execution adds <50ms overhead
|
||||
|
||||
---
|
||||
|
||||
## Known Limitations (Document in Release Notes)
|
||||
|
||||
1. **SQLite migration not supported in MVP** - JSON-only migration available, SQLite coming in v1.1
|
||||
2. **Global patterns deferred to v1.1** - Project-local patterns only in MVP
|
||||
3. **Windows requires `jq` binary** - Not auto-installed, manual setup required
|
||||
4. **No `hooks export/import` in MVP** - Manual file copying as workaround
|
||||
|
||||
---
|
||||
|
||||
## Risk Mitigation Checklist
|
||||
|
||||
- [ ] ✅ Windows testing (PowerShell, CMD, WSL)
|
||||
- [ ] ✅ Atomic migration with backup/rollback
|
||||
- [ ] ✅ Command injection prevention (`shell-escape`)
|
||||
- [ ] ✅ Runtime path resolution (no hardcoded paths)
|
||||
- [ ] ✅ Graceful failure (hooks never block Claude Code)
|
||||
- [ ] ✅ Backward compatibility (legacy paths still work)
|
||||
|
||||
---
|
||||
|
||||
## Dependencies Required
|
||||
|
||||
### MVP
|
||||
```toml
|
||||
askama = "0.12" # Type-safe templates
|
||||
shell-escape = "0.1" # Security
|
||||
```
|
||||
|
||||
### Already Available
|
||||
```toml
|
||||
shellexpand = "3.1" # Path expansion ✅
|
||||
clap = { ... } # CLI framework ✅
|
||||
tokio = { ... } # Async runtime ✅
|
||||
serde_json = { ... } # JSON parsing ✅
|
||||
```
|
||||
|
||||
### v1.1
|
||||
```toml
|
||||
rusqlite = { version = "0.32", optional = true }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Success Metrics (Track During Development)
|
||||
|
||||
| Metric | Target | Actual |
|
||||
|--------|--------|--------|
|
||||
| Test coverage | >80% | ___ |
|
||||
| Platforms passing | 3/3 | ___ |
|
||||
| Migration speed (1000 traj) | <5s | ___ |
|
||||
| First-time setup | <5min | ___ |
|
||||
| Hook overhead | <50ms | ___ |
|
||||
| Data loss during migration | 0% | ___ |
|
||||
|
||||
---
|
||||
|
||||
## Quick Commands Reference
|
||||
|
||||
```bash
|
||||
# Create branch
|
||||
git checkout -b feature/portable-hooks-mvp
|
||||
|
||||
# Run tests
|
||||
cargo test --package ruvector-cli --lib hooks
|
||||
|
||||
# Run integration tests
|
||||
cargo test --package ruvector-cli --test hooks_integration
|
||||
|
||||
# Check coverage
|
||||
cargo tarpaulin --out Html --package ruvector-cli
|
||||
|
||||
# Lint
|
||||
cargo clippy --package ruvector-cli -- -D warnings
|
||||
|
||||
# Format
|
||||
cargo fmt --package ruvector-cli
|
||||
|
||||
# Build for all platforms
|
||||
cargo build --release --package ruvector-cli
|
||||
|
||||
# Test CLI commands
|
||||
cargo run --package ruvector-cli -- hooks init
|
||||
cargo run --package ruvector-cli -- hooks install --dry-run
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**Last Updated**: 2025-12-25
|
||||
**Status**: Ready for Development
|
||||
**Estimated Completion**: 3-4 weeks from start
|
||||
333
vendor/ruvector/docs/hooks/README.md
vendored
Normal file
333
vendor/ruvector/docs/hooks/README.md
vendored
Normal file
@@ -0,0 +1,333 @@
|
||||
# RuVector Hooks System Documentation
|
||||
|
||||
Intelligent hooks for Claude Code that provide automatic agent assignment, code formatting, neural pattern training, and cross-session memory persistence.
|
||||
|
||||
> **Implementation Status**: ✅ **FULLY IMPLEMENTED** - Both implementations are now functional:
|
||||
> - **Rust CLI**: `ruvector hooks <command>` (portable, high-performance)
|
||||
> - **Node.js**: `.claude/intelligence/cli.js` (legacy compatibility)
|
||||
|
||||
## Available Implementations
|
||||
|
||||
```bash
|
||||
# Rust CLI (recommended - faster, portable)
|
||||
cargo run --bin ruvector -- hooks stats
|
||||
cargo run --bin ruvector -- hooks pre-edit <file>
|
||||
cargo run --bin ruvector -- hooks post-edit <file> --success
|
||||
|
||||
# Node.js (legacy - still functional)
|
||||
node .claude/intelligence/cli.js stats
|
||||
node .claude/intelligence/cli.js pre-edit <file>
|
||||
```
|
||||
|
||||
## Quick Navigation
|
||||
|
||||
| Document | Description |
|
||||
|----------|-------------|
|
||||
| [User Guide](USER_GUIDE.md) | Getting started, setup, and basic usage |
|
||||
| [CLI Reference](CLI_REFERENCE.md) | Complete CLI command documentation |
|
||||
| [Architecture](ARCHITECTURE.md) | Technical design and system internals |
|
||||
| [Migration Guide](MIGRATION.md) | Upgrading from claude-flow or legacy systems |
|
||||
| [Troubleshooting](TROUBLESHOOTING.md) | Common issues and solutions |
|
||||
|
||||
## Developer Documents
|
||||
|
||||
| Document | Description |
|
||||
|----------|-------------|
|
||||
| [Implementation Plan](IMPLEMENTATION_PLAN.md) | SPARC-GOAP implementation roadmap |
|
||||
| [MVP Checklist](MVP_CHECKLIST.md) | Development checklist for MVP release |
|
||||
| [Review Report](REVIEW_REPORT.md) | Detailed code review and recommendations |
|
||||
| [Review Summary](REVIEW_SUMMARY.md) | Executive summary of review findings |
|
||||
|
||||
---
|
||||
|
||||
## What Are Hooks?
|
||||
|
||||
Hooks are automated actions that execute before or after Claude Code tool operations. They enable:
|
||||
|
||||
- **Intelligent Agent Assignment**: Automatically assign the best agent for each file type
|
||||
- **Code Quality**: Format, lint, and validate code automatically
|
||||
- **Memory Persistence**: Store decisions and context across sessions
|
||||
- **Neural Learning**: Continuously improve from successful patterns
|
||||
- **Swarm Coordination**: Synchronize knowledge across multi-agent workflows
|
||||
|
||||
## System Overview
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Claude Code Session │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ PreTool │───►│ Tool │───►│ PostTool │───►│ Result │ │
|
||||
│ │ Hook │ │ Execute │ │ Hook │ │ │ │
|
||||
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
|
||||
│ │ │ │
|
||||
│ ▼ ▼ │
|
||||
│ ┌─────────────────────────────────────────────────────────┐ │
|
||||
│ │ Intelligence Layer │ │
|
||||
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
|
||||
│ │ │Q-Learn │ │ Vector │ │ Pattern │ │ Agent │ │ │
|
||||
│ │ │ Table │ │ Memory │ │ Training│ │ Router │ │ │
|
||||
│ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │
|
||||
│ └─────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Initialize Hooks
|
||||
|
||||
```bash
|
||||
# Using npx (recommended)
|
||||
npx ruvector hooks init
|
||||
|
||||
# Or using claude-flow
|
||||
npx claude-flow init --hooks
|
||||
```
|
||||
|
||||
### 2. Install into Claude Code
|
||||
|
||||
```bash
|
||||
npx ruvector hooks install
|
||||
```
|
||||
|
||||
### 3. Verify Setup
|
||||
|
||||
```bash
|
||||
npx ruvector hooks stats
|
||||
```
|
||||
|
||||
## Hook Types
|
||||
|
||||
### Pre-Operation Hooks
|
||||
|
||||
Execute **before** Claude Code operations:
|
||||
|
||||
| Hook | Trigger | Purpose |
|
||||
|------|---------|---------|
|
||||
| `pre-edit` | Write, Edit, MultiEdit | Agent assignment, syntax validation |
|
||||
| `pre-bash` | Bash commands | Safety checks, resource estimation |
|
||||
| `pre-task` | Task spawning | Auto-spawn agents, load memory |
|
||||
| `pre-search` | Grep, Glob | Cache checking, query optimization |
|
||||
|
||||
### Post-Operation Hooks
|
||||
|
||||
Execute **after** Claude Code operations:
|
||||
|
||||
| Hook | Trigger | Purpose |
|
||||
|------|---------|---------|
|
||||
| `post-edit` | Write, Edit, MultiEdit | Formatting, memory storage, training |
|
||||
| `post-bash` | Bash commands | Logging, metrics, error detection |
|
||||
| `post-task` | Task completion | Performance analysis, learning export |
|
||||
| `post-search` | Grep, Glob | Caching, pattern improvement |
|
||||
|
||||
### Session Hooks
|
||||
|
||||
Manage session lifecycle:
|
||||
|
||||
| Hook | Trigger | Purpose |
|
||||
|------|---------|---------|
|
||||
| `session-start` | Session begins | Context loading, initialization |
|
||||
| `session-restore` | Manual restore | Restore previous session state |
|
||||
| `session-end` / `Stop` | Session ends | Persist state, export metrics |
|
||||
|
||||
### Compact Hooks
|
||||
|
||||
Execute during context compaction:
|
||||
|
||||
| Hook | Matcher | Purpose |
|
||||
|------|---------|---------|
|
||||
| `PreCompact` | `manual` | Display learned patterns during manual compact |
|
||||
| `PreCompact` | `auto` | Show learning stats during auto-compact |
|
||||
|
||||
## Configuration
|
||||
|
||||
Hooks are configured in `.claude/settings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"env": {
|
||||
"RUVECTOR_INTELLIGENCE_ENABLED": "true",
|
||||
"INTELLIGENCE_MODE": "treatment",
|
||||
"RUVECTOR_MEMORY_BACKEND": "rvlite"
|
||||
},
|
||||
"permissions": {
|
||||
"allow": ["Bash(cargo:*)", "Bash(git:*)", "Bash(.claude/hooks:*)"],
|
||||
"deny": ["Bash(rm -rf /)", "Bash(cargo publish:*)"]
|
||||
},
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"timeout": 3000,
|
||||
"command": "npx ruvector hooks pre-command \"$CMD\""
|
||||
}]
|
||||
},
|
||||
{
|
||||
"matcher": "Write|Edit|MultiEdit",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"timeout": 3000,
|
||||
"command": "npx ruvector hooks pre-edit \"$FILE\""
|
||||
}]
|
||||
}
|
||||
],
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "npx ruvector hooks post-command \"$CMD\" \"$SUCCESS\""
|
||||
}]
|
||||
},
|
||||
{
|
||||
"matcher": "Write|Edit|MultiEdit",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "npx ruvector hooks post-edit \"$FILE\""
|
||||
}]
|
||||
}
|
||||
],
|
||||
"PreCompact": [
|
||||
{
|
||||
"matcher": "manual",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "npx ruvector hooks compact-context --mode manual"
|
||||
}]
|
||||
},
|
||||
{
|
||||
"matcher": "auto",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "npx ruvector hooks compact-context --mode auto"
|
||||
}]
|
||||
}
|
||||
],
|
||||
"SessionStart": [
|
||||
{
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"timeout": 5000,
|
||||
"command": "npx ruvector hooks session-start"
|
||||
}]
|
||||
}
|
||||
],
|
||||
"Stop": [
|
||||
{
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "npx ruvector hooks session-end --persist-state"
|
||||
}]
|
||||
}
|
||||
]
|
||||
},
|
||||
"includeCoAuthoredBy": true,
|
||||
"enabledMcpjsonServers": ["claude-flow", "ruv-swarm"],
|
||||
"statusLine": {
|
||||
"type": "command",
|
||||
"command": ".claude/statusline-command.sh"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Configuration Sections
|
||||
|
||||
| Section | Description |
|
||||
|---------|-------------|
|
||||
| `env` | Environment variables for hooks |
|
||||
| `permissions` | Allow/deny rules for commands |
|
||||
| `hooks` | Hook definitions by event type |
|
||||
| `includeCoAuthoredBy` | Add co-author attribution |
|
||||
| `enabledMcpjsonServers` | MCP servers to enable |
|
||||
| `statusLine` | Custom status line command |
|
||||
|
||||
## Intelligence Layer
|
||||
|
||||
The hooks system includes a self-learning intelligence layer:
|
||||
|
||||
### Q-Learning Patterns
|
||||
|
||||
Learns optimal actions from experience:
|
||||
|
||||
- State-action pair tracking
|
||||
- Reward-based learning
|
||||
- Decay over time for relevance
|
||||
|
||||
### Vector Memory
|
||||
|
||||
Semantic search over past decisions:
|
||||
|
||||
- 128-dimensional embeddings
|
||||
- HNSW indexing for fast retrieval
|
||||
- Persistent storage with rvlite
|
||||
|
||||
### Agent Routing
|
||||
|
||||
Intelligent agent assignment:
|
||||
|
||||
- File type → agent type mapping
|
||||
- Confidence scoring
|
||||
- Fallback strategies
|
||||
|
||||
## Directory Structure
|
||||
|
||||
After initialization:
|
||||
|
||||
```
|
||||
.ruvector/
|
||||
├── config.toml # Project configuration
|
||||
├── intelligence/
|
||||
│ ├── memory.json # Vector memory entries
|
||||
│ ├── patterns.json # Q-learning patterns
|
||||
│ ├── trajectories.json # Learning trajectories
|
||||
│ ├── feedback.json # User feedback tracking
|
||||
│ └── memory.rvdb # RvLite vector database
|
||||
└── .gitignore
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `RUVECTOR_HOME` | `~/.ruvector` | Global patterns directory |
|
||||
| `RUVECTOR_DATA_DIR` | `./.ruvector` | Project-local data |
|
||||
| `RUVECTOR_INTELLIGENCE_ENABLED` | `true` | Enable/disable intelligence |
|
||||
| `INTELLIGENCE_MODE` | `treatment` | A/B test group |
|
||||
|
||||
## Performance
|
||||
|
||||
The hooks system is designed for minimal overhead:
|
||||
|
||||
- **Hook execution**: <50ms typical
|
||||
- **Memory lookup**: <10ms with HNSW
|
||||
- **Pattern training**: Async, non-blocking
|
||||
- **Total overhead**: <100ms per operation
|
||||
|
||||
## Integration
|
||||
|
||||
Hooks integrate with:
|
||||
|
||||
- **Claude Code**: Native tool hooks
|
||||
- **Claude Flow**: MCP swarm coordination
|
||||
- **Git**: Pre-commit and post-commit hooks
|
||||
- **RvLite**: Vector database storage
|
||||
- **Neural Training**: Pattern improvement
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. Read the [User Guide](USER_GUIDE.md) for detailed setup
|
||||
2. Explore the [CLI Reference](CLI_REFERENCE.md) for all commands
|
||||
3. Check [Architecture](ARCHITECTURE.md) for internals
|
||||
4. See [Migration Guide](MIGRATION.md) if upgrading
|
||||
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
- **Issues**: [GitHub Issues](https://github.com/ruvnet/ruvector/issues)
|
||||
- **Documentation**: This directory
|
||||
- **Examples**: `.claude/commands/hooks/`
|
||||
569
vendor/ruvector/docs/hooks/REVIEW_REPORT.md
vendored
Normal file
569
vendor/ruvector/docs/hooks/REVIEW_REPORT.md
vendored
Normal file
@@ -0,0 +1,569 @@
|
||||
# Implementation Plan Code Review Report
|
||||
|
||||
> **Related Documentation**: [README](README.md) | [Implementation Plan](IMPLEMENTATION_PLAN.md) | [MVP Checklist](MVP_CHECKLIST.md)
|
||||
|
||||
**Document**: `/home/user/ruvector/docs/hooks/IMPLEMENTATION_PLAN.md`
|
||||
**Reviewer**: Code Review Agent
|
||||
**Date**: 2025-12-25
|
||||
**Status**: ✅ APPROVED WITH REVISIONS
|
||||
|
||||
---
|
||||
|
||||
## Executive Summary
|
||||
|
||||
The implementation plan is **technically sound** and well-structured, but contains **3 critical issues** that would cause failures on Windows and during migration. After review:
|
||||
|
||||
- **Timeline optimized**: 6-8 weeks → **3-4 weeks for MVP** (50% reduction)
|
||||
- **Critical fixes added**: Windows compatibility, SQLite migration risks, command injection
|
||||
- **Scope refined**: Deferred complex features (global patterns, SQLite) to v1.1
|
||||
- **Code quality improved**: Type-safe templates, idiomatic Rust patterns, security hardening
|
||||
|
||||
**Recommendation**: Proceed with implementation using revised plan (now v2.0).
|
||||
|
||||
---
|
||||
|
||||
## 1. Critical Issues (Must Fix)
|
||||
|
||||
### Issue #1: Windows Compatibility Broken
|
||||
**Severity**: 🔴 Critical
|
||||
**Location**: Hook templates (lines 1022, 1033)
|
||||
**Impact**: Complete failure on Windows
|
||||
|
||||
**Problem**:
|
||||
```json
|
||||
{
|
||||
"command": "/bin/bash -c '...'" // ❌ /bin/bash doesn't exist on Windows
|
||||
}
|
||||
```
|
||||
|
||||
**Fix Applied** (Section 11.1):
|
||||
```rust
|
||||
fn get_shell_wrapper() -> &'static str {
|
||||
if cfg!(target_os = "windows") { "cmd /c" }
|
||||
else { "/bin/bash -c" }
|
||||
}
|
||||
```
|
||||
|
||||
**Testing Required**:
|
||||
- ✅ PowerShell environment
|
||||
- ✅ WSL environment
|
||||
- ✅ CMD.exe environment
|
||||
|
||||
---
|
||||
|
||||
### Issue #2: SQLite Migration Format Undefined
|
||||
**Severity**: 🔴 Critical
|
||||
**Location**: Milestone 4, lines 871-887
|
||||
**Impact**: Data loss during migration
|
||||
|
||||
**Problem**:
|
||||
```rust
|
||||
let embedding: Vec<u8> = row.get(3)?;
|
||||
let embedding_f32 = deserialize_embedding(&embedding)?;
|
||||
// ❌ What format? Numpy? MessagePack? Raw bytes?
|
||||
```
|
||||
|
||||
**Fix Applied**:
|
||||
- **MVP**: Defer SQLite migration to v1.1
|
||||
- **JSON-only migration** for MVP (2 days instead of 5-7 days)
|
||||
- **Future**: Add format detection before deserialization
|
||||
|
||||
**Timeline Savings**: 3-5 days
|
||||
|
||||
---
|
||||
|
||||
### Issue #3: Runtime Path Resolution Missing
|
||||
**Severity**: 🟡 High
|
||||
**Location**: Template substitution (line 288)
|
||||
**Impact**: Hooks break after binary reinstallation
|
||||
|
||||
**Problem**:
|
||||
```rust
|
||||
// Hardcodes path at install time
|
||||
output.replace("{{RUVECTOR_CLI_PATH}}", "/usr/local/bin/ruvector");
|
||||
// If user reinstalls via npm, path changes
|
||||
```
|
||||
|
||||
**Fix Applied**:
|
||||
```json
|
||||
{
|
||||
"command": "/bin/bash -c 'RUVECTOR=$(which ruvector || echo npx ruvector); $RUVECTOR hooks pre-edit'"
|
||||
}
|
||||
```
|
||||
|
||||
**Benefit**: Hooks survive binary moves/reinstalls
|
||||
|
||||
---
|
||||
|
||||
## 2. Scope Optimizations
|
||||
|
||||
### Optimization #1: Defer Global Patterns System
|
||||
**Original**: Milestone 6 (4-5 days)
|
||||
**Decision**: Move to v1.1
|
||||
|
||||
**Rationale**:
|
||||
- Adds complexity (sync conflicts, privacy controls)
|
||||
- Not required for core functionality
|
||||
- Can be added non-disruptively later
|
||||
|
||||
**Timeline Savings**: 4-5 days
|
||||
|
||||
---
|
||||
|
||||
### Optimization #2: JSON Migration First
|
||||
**Original**: SQLite + JSON migration (5-7 days)
|
||||
**Revised**: JSON-only for MVP (2 days)
|
||||
|
||||
**Rationale**:
|
||||
- Most users have existing JSON data (`.claude/intelligence/`)
|
||||
- SQLite migration is complex (format detection, embedding deserialization)
|
||||
- Lower risk to validate with JSON first
|
||||
|
||||
**Timeline Savings**: 3-5 days
|
||||
|
||||
---
|
||||
|
||||
### Optimization #3: Combine Milestones 2 & 5
|
||||
**Original**: Separate CLI (5-7 days) + Templates (3-4 days)
|
||||
**Revised**: Combined (4-5 days)
|
||||
|
||||
**Rationale**:
|
||||
- Template engine and `hooks install` are tightly coupled
|
||||
- Building together prevents context switching overhead
|
||||
|
||||
**Timeline Savings**: 4-6 days
|
||||
|
||||
---
|
||||
|
||||
## 3. Missing Elements Added
|
||||
|
||||
### 3.1 Error Handling Strategy
|
||||
**Added to**: All hook execution points
|
||||
|
||||
```rust
|
||||
pub fn execute_hook_safely(hook: &HookCommand) -> Result<()> {
|
||||
match hook.execute().timeout(Duration::from_secs(3)) {
|
||||
Ok(Ok(_)) => Ok(()),
|
||||
Ok(Err(e)) => {
|
||||
eprintln!("⚠️ Hook failed (non-fatal): {}", e);
|
||||
Ok(()) // Don't block Claude Code
|
||||
}
|
||||
Err(_) => {
|
||||
eprintln!("⚠️ Hook timeout");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Benefit**: Hooks never block Claude Code operations
|
||||
|
||||
---
|
||||
|
||||
### 3.2 Atomic Migration with Rollback
|
||||
**Added to**: Milestone 4a (Section 11.2)
|
||||
|
||||
```rust
|
||||
pub fn migrate_with_safety(from: &Path, to: &Path) -> Result<MigrationStats> {
|
||||
// 1. Backup existing data
|
||||
// 2. Migrate to temporary location
|
||||
// 3. Validate migrated data
|
||||
// 4. Atomic swap
|
||||
// On any error: restore backup
|
||||
}
|
||||
```
|
||||
|
||||
**Benefit**: Zero data loss risk
|
||||
|
||||
---
|
||||
|
||||
### 3.3 Security: Command Injection Prevention
|
||||
**Added to**: All hook templates (Section 11.3)
|
||||
|
||||
```rust
|
||||
use shell_escape::escape;
|
||||
|
||||
fn generate_hook_command(file_path: &str) -> String {
|
||||
let escaped = escape(file_path.into());
|
||||
format!(r#"ruvector hooks pre-edit {}"#, escaped)
|
||||
}
|
||||
```
|
||||
|
||||
**Prevents**: Malicious filenames like `; rm -rf /`
|
||||
|
||||
---
|
||||
|
||||
### 3.4 Windows-Specific Testing Checklist
|
||||
**Added to**: Milestone 7
|
||||
|
||||
- ✅ PowerShell compatibility
|
||||
- ✅ Path separator handling (`\` vs `/`)
|
||||
- ✅ WSL environment testing
|
||||
- ✅ Bundled `jq` binary (not in Windows PATH)
|
||||
|
||||
---
|
||||
|
||||
## 4. Code Quality Improvements
|
||||
|
||||
### 4.1 Type-Safe Templates
|
||||
**Issue**: String-based templates are error-prone (line 288)
|
||||
|
||||
**Improvement**:
|
||||
```rust
|
||||
#[derive(Template)]
|
||||
#[template(path = "hooks.json.j2")]
|
||||
struct HookTemplate {
|
||||
ruvector_cli_path: String,
|
||||
project_root: String,
|
||||
}
|
||||
|
||||
let rendered = HookTemplate { /* ... */ }.render()?;
|
||||
```
|
||||
|
||||
**Benefit**: Compile-time template validation
|
||||
|
||||
**Dependency**: `askama = "0.12"` (added to Section 12)
|
||||
|
||||
---
|
||||
|
||||
### 4.2 Idiomatic Rust Error Handling
|
||||
**Issue**: Non-idiomatic file writing (Appendix B, line 844)
|
||||
|
||||
**Before**:
|
||||
```rust
|
||||
fs::write(path, serde_json::to_string_pretty(&data)?)?;
|
||||
```
|
||||
|
||||
**After**:
|
||||
```rust
|
||||
let mut file = File::create(path)?;
|
||||
serde_json::to_writer_pretty(&mut file, &data)?;
|
||||
file.sync_all()?; // Ensure durability
|
||||
```
|
||||
|
||||
**Benefit**: Explicit error points, guaranteed disk sync
|
||||
|
||||
---
|
||||
|
||||
### 4.3 Extract Magic Numbers to Config
|
||||
**Issue**: Hardcoded values in templates (lines 1022, 1033)
|
||||
|
||||
**Before**:
|
||||
```json
|
||||
{ "timeout": 3000 } // Magic number
|
||||
```
|
||||
|
||||
**After** (add to `config.toml`):
|
||||
```toml
|
||||
[hooks]
|
||||
timeout_ms = 3000
|
||||
stderr_max_bytes = 300
|
||||
max_retries = 2
|
||||
```
|
||||
|
||||
**Benefit**: User-configurable timeouts
|
||||
|
||||
---
|
||||
|
||||
## 5. Leveraging Existing Crates
|
||||
|
||||
### 5.1 Already Available (No Work Needed)
|
||||
| Feature | Crate | Location |
|
||||
|---------|-------|----------|
|
||||
| Path expansion | `shellexpand = "3.1"` | `Cargo.toml:74` ✅ |
|
||||
| CLI framework | `clap` | `Cargo.toml:29` ✅ |
|
||||
| Vector storage | `ruvector-core` | `Cargo.toml:21` ✅ |
|
||||
| Async runtime | `tokio` | `Cargo.toml:34` ✅ |
|
||||
|
||||
**Action**: No additional dependencies needed for MVP!
|
||||
|
||||
---
|
||||
|
||||
### 5.2 Recommended Additions (v1.1)
|
||||
```toml
|
||||
[dependencies]
|
||||
rusqlite = { version = "0.32", optional = true } # SQLite migration
|
||||
askama = "0.12" # Type-safe templates
|
||||
shell-escape = "0.1" # Security
|
||||
|
||||
[features]
|
||||
sqlite-migration = ["rusqlite"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5.3 Use rvlite for Vector Storage
|
||||
**Current plan**: Generic `VectorDB`
|
||||
**Better**: Use `rvlite` (already in ruvector ecosystem)
|
||||
|
||||
```rust
|
||||
use rvlite::RvLite;
|
||||
|
||||
pub fn migrate_to_rvlite(trajectories: &[Trajectory]) -> Result<()> {
|
||||
let db = RvLite::create(".ruvector/memory.rvdb")?;
|
||||
db.sql("CREATE TABLE memories (id TEXT, embedding VECTOR(128))")?;
|
||||
// rvlite supports SQL, SPARQL, and Cypher
|
||||
}
|
||||
```
|
||||
|
||||
**Benefit**:
|
||||
- Unified storage layer
|
||||
- WASM-compatible
|
||||
- Already part of ruvector
|
||||
|
||||
---
|
||||
|
||||
## 6. MVP Definition
|
||||
|
||||
### What's Included (3-4 weeks)
|
||||
✅ **Week 1-2**: Foundation
|
||||
- `ruvector hooks init` (create `.ruvector/` structure)
|
||||
- `ruvector hooks install` (generate portable hooks)
|
||||
- Template engine with runtime path resolution
|
||||
- JSON-to-JSON migration
|
||||
|
||||
✅ **Week 3**: Intelligence Layer
|
||||
- Refactor `index.js` with `process.env.RUVECTOR_DATA_DIR`
|
||||
- Zero hardcoded paths
|
||||
- Test in fresh project
|
||||
|
||||
✅ **Week 4**: Polish
|
||||
- Cross-platform testing (Linux, macOS, Windows)
|
||||
- `ruvector hooks stats` command
|
||||
- Error handling + rollback
|
||||
- Documentation
|
||||
|
||||
---
|
||||
|
||||
### What's Deferred to v1.1 (Additional 2-3 weeks)
|
||||
❌ SQLite migration (needs format detection)
|
||||
❌ Global patterns system (sync complexity)
|
||||
❌ Export/import commands (nice-to-have)
|
||||
❌ `ruvector hooks enable/disable` (low priority)
|
||||
|
||||
---
|
||||
|
||||
## 7. Timeline Comparison
|
||||
|
||||
| Version | Original | Optimized | Savings |
|
||||
|---------|----------|-----------|---------|
|
||||
| **MVP** | N/A | **3-4 weeks** | N/A |
|
||||
| **Full v1.0** | 6-8 weeks | 3-4 weeks | **50%** |
|
||||
| **v1.1 (Full Features)** | 6-8 weeks | 5-7 weeks | ~15% |
|
||||
|
||||
**Key Changes**:
|
||||
1. Defined MVP scope (didn't exist before)
|
||||
2. Deferred complex features (SQLite, global patterns)
|
||||
3. Combined milestones (CLI + Templates)
|
||||
4. Focused on JSON migration (most common use case)
|
||||
|
||||
---
|
||||
|
||||
## 8. Risks Mitigated
|
||||
|
||||
| Risk | Original Plan | Revised Plan |
|
||||
|------|---------------|--------------|
|
||||
| Windows failure | ⚠️ Testing only | ✅ Conditional shell detection |
|
||||
| Data loss | ⚠️ Checksums only | ✅ Atomic migration + rollback |
|
||||
| Command injection | ❌ Not addressed | ✅ `shell-escape` crate |
|
||||
| SQLite format errors | ⚠️ Assumed format | ✅ Deferred to v1.1 with detection |
|
||||
| Hardcoded paths | ⚠️ Install-time subst | ✅ Runtime resolution |
|
||||
|
||||
---
|
||||
|
||||
## 9. Specific File Changes Required
|
||||
|
||||
### 9.1 Update Cargo.toml
|
||||
**File**: `/home/user/ruvector/crates/ruvector-cli/Cargo.toml`
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
# Add these lines:
|
||||
askama = "0.12" # Type-safe templates
|
||||
shell-escape = "0.1" # Security
|
||||
|
||||
# v1.1 only:
|
||||
rusqlite = { version = "0.32", optional = true }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
sqlite-migration = ["rusqlite"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 9.2 Create Hook Template
|
||||
**File**: `/home/user/ruvector/crates/ruvector-cli/templates/hooks.json.j2`
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"command": "{{ shell }} 'RUVECTOR=$(which ruvector || echo npx ruvector); $RUVECTOR hooks pre-command \"$CMD\"'"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 9.3 Refactor Intelligence Layer
|
||||
**File**: `/home/user/ruvector/.claude/intelligence/index.js`
|
||||
|
||||
**Line 20** (currently):
|
||||
```javascript
|
||||
const DATA_DIR = join(__dirname, 'data');
|
||||
```
|
||||
|
||||
**Change to**:
|
||||
```javascript
|
||||
const DATA_DIR = process.env.RUVECTOR_DATA_DIR ||
|
||||
join(process.cwd(), '.ruvector', 'intelligence') ||
|
||||
join(__dirname, 'data'); // Fallback for legacy
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. Testing Strategy
|
||||
|
||||
### 10.1 Cross-Platform Testing
|
||||
**Required Environments**:
|
||||
- ✅ Ubuntu 22.04 (GitHub Actions)
|
||||
- ✅ macOS 14 Sonoma (M1 + Intel)
|
||||
- ✅ Windows 11 (PowerShell + CMD + WSL)
|
||||
|
||||
**Test Cases**:
|
||||
1. Fresh project setup (`npx ruvector hooks init`)
|
||||
2. Migration from existing `.claude/intelligence/`
|
||||
3. Hooks trigger correctly (pre-edit, post-command)
|
||||
4. Path resolution across platforms
|
||||
5. Binary reinstallation (verify hooks still work)
|
||||
|
||||
---
|
||||
|
||||
### 10.2 Integration Tests
|
||||
**File**: `/home/user/ruvector/crates/ruvector-cli/tests/hooks_integration.rs`
|
||||
|
||||
```rust
|
||||
#[test]
|
||||
fn test_hooks_init_creates_structure() {
|
||||
let temp = tempdir()?;
|
||||
run_cmd(&["ruvector", "hooks", "init"], &temp)?;
|
||||
|
||||
assert!(temp.path().join(".ruvector/config.toml").exists());
|
||||
assert!(temp.path().join(".ruvector/intelligence").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_migration_preserves_data() {
|
||||
// Test JSON migration accuracy
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_windows_shell_compatibility() {
|
||||
// Platform-specific shell tests
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Documentation Requirements
|
||||
|
||||
### 11.1 User-Facing Docs
|
||||
**File**: `/home/user/ruvector/docs/hooks/USER_GUIDE.md`
|
||||
|
||||
**Sections**:
|
||||
1. Quick Start (5-minute setup)
|
||||
2. Migration from existing setup
|
||||
3. Troubleshooting common issues
|
||||
4. Configuration reference
|
||||
|
||||
---
|
||||
|
||||
### 11.2 API Reference
|
||||
**File**: `/home/user/ruvector/docs/hooks/CLI_REFERENCE.md`
|
||||
|
||||
**Format**:
|
||||
```markdown
|
||||
## ruvector hooks init
|
||||
|
||||
Initialize hooks system in current project.
|
||||
|
||||
**Usage**: `npx ruvector hooks init [OPTIONS]`
|
||||
|
||||
**Options**:
|
||||
- `--path <PATH>`: Custom directory (default: `./.ruvector`)
|
||||
- `--template <NAME>`: Use template (default, minimal, advanced)
|
||||
|
||||
**Example**:
|
||||
```bash
|
||||
npx ruvector hooks init
|
||||
npx ruvector hooks install
|
||||
```
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. Success Metrics
|
||||
|
||||
### MVP Success Criteria
|
||||
- ✅ Works on Linux, macOS, Windows (3/3 platforms)
|
||||
- ✅ Migration completes in <5 seconds for 1000 trajectories
|
||||
- ✅ Zero data loss in migration (validated via checksums)
|
||||
- ✅ Hooks survive binary reinstallation
|
||||
- ✅ First-time setup takes <5 minutes
|
||||
- ✅ Zero hardcoded paths in generated hooks
|
||||
|
||||
### Code Quality Metrics
|
||||
- ✅ Test coverage >80% for CLI commands
|
||||
- ✅ All commands have examples in docs
|
||||
- ✅ No clippy warnings on stable Rust
|
||||
- ✅ All integration tests pass on 3 platforms
|
||||
|
||||
---
|
||||
|
||||
## 13. Recommendations Summary
|
||||
|
||||
### Immediate Actions (Before Coding)
|
||||
1. ✅ **Approve revised plan** (v2.0 in IMPLEMENTATION_PLAN.md)
|
||||
2. ✅ **Add dependencies** to Cargo.toml (Section 12)
|
||||
3. ✅ **Create hook templates** directory structure
|
||||
4. ✅ **Set up CI testing** for Windows/macOS/Linux
|
||||
|
||||
### Implementation Order
|
||||
1. **Week 1**: Milestone 1 (Spec) + Start Milestone 2 (CLI scaffolding)
|
||||
2. **Week 2**: Finish Milestone 2+5 (CLI + Templates)
|
||||
3. **Week 3**: Milestone 3 (Intelligence Layer) + 4a (JSON Migration)
|
||||
4. **Week 4**: Milestone 7 (Testing + Docs)
|
||||
|
||||
### v1.1 Planning
|
||||
- Schedule SQLite migration for v1.1.0 (add format detection)
|
||||
- Schedule global patterns for v1.1.0 (design sync protocol first)
|
||||
- Consider team sharing features for v1.2.0
|
||||
|
||||
---
|
||||
|
||||
## 14. Final Verdict
|
||||
|
||||
**Status**: ✅ **APPROVED FOR IMPLEMENTATION** (with revisions)
|
||||
|
||||
**Confidence Level**: High (8/10)
|
||||
|
||||
**Remaining Risks**:
|
||||
- Windows testing may uncover edge cases (10% probability)
|
||||
- Intelligence layer refactor may need iteration (15% probability)
|
||||
- User adoption may surface unforeseen use cases (20% probability)
|
||||
|
||||
**Overall Assessment**: The plan is **solid, well-researched, and implementable**. The revised timeline (3-4 weeks for MVP) is **realistic and achievable**. Critical issues have been identified and fixed. Code quality improvements will prevent future maintenance burden.
|
||||
|
||||
**Next Step**: Create feature branch `feature/portable-hooks-mvp` and begin Milestone 1.
|
||||
|
||||
---
|
||||
|
||||
**Reviewed By**: Code Review Agent
|
||||
**Approved By**: [Pending]
|
||||
**Implementation Start**: [TBD]
|
||||
**Target MVP Release**: [TBD + 3-4 weeks]
|
||||
278
vendor/ruvector/docs/hooks/REVIEW_SUMMARY.md
vendored
Normal file
278
vendor/ruvector/docs/hooks/REVIEW_SUMMARY.md
vendored
Normal file
@@ -0,0 +1,278 @@
|
||||
# Hooks Implementation Plan - Code Review Summary
|
||||
|
||||
> **Related Documentation**: [README](README.md) | [Full Review](REVIEW_REPORT.md) | [Implementation Plan](IMPLEMENTATION_PLAN.md)
|
||||
|
||||
**Status**: ✅ APPROVED WITH CRITICAL FIXES
|
||||
**Timeline**: Optimized from 6-8 weeks → **3-4 weeks for MVP**
|
||||
**Risk Level**: Low-Medium (major risks mitigated)
|
||||
|
||||
---
|
||||
|
||||
## 1. Critical Issues Found (Must Fix)
|
||||
|
||||
### 🔴 Issue #1: Windows Compatibility Broken
|
||||
**Impact**: Complete failure on Windows
|
||||
**Fix**: Use conditional shell detection
|
||||
```rust
|
||||
fn get_shell_wrapper() -> &'static str {
|
||||
if cfg!(target_os = "windows") { "cmd /c" }
|
||||
else { "/bin/bash -c" }
|
||||
}
|
||||
```
|
||||
|
||||
### 🔴 Issue #2: SQLite Migration Undefined Format
|
||||
**Impact**: Data loss risk
|
||||
**Fix**: Defer SQLite to v1.1, use JSON-only migration for MVP
|
||||
|
||||
### 🔴 Issue #3: Path Resolution Breaks After Reinstall
|
||||
**Impact**: Hooks stop working after binary moves
|
||||
**Fix**: Use runtime resolution instead of install-time substitution
|
||||
```bash
|
||||
RUVECTOR=$(which ruvector || echo npx ruvector); $RUVECTOR hooks pre-edit
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Optimizations Applied
|
||||
|
||||
| Change | Time Saved | Rationale |
|
||||
|--------|------------|-----------|
|
||||
| Defer global patterns to v1.1 | 4-5 days | Adds complexity without MVP value |
|
||||
| JSON migration only (defer SQLite) | 3-5 days | Most users have JSON data |
|
||||
| Combine CLI + Templates milestones | 4-6 days | Reduce context switching |
|
||||
| **Total Savings** | **~50%** | MVP: 3-4 weeks vs 6-8 weeks |
|
||||
|
||||
---
|
||||
|
||||
## 3. Missing Elements Added
|
||||
|
||||
✅ **Error handling**: Hooks never block Claude Code operations
|
||||
✅ **Atomic migration**: Backup → Migrate → Validate → Swap with rollback
|
||||
✅ **Security**: Command injection prevention with `shell-escape`
|
||||
✅ **Windows testing**: PowerShell, CMD, WSL compatibility checklist
|
||||
|
||||
---
|
||||
|
||||
## 4. Code Quality Improvements
|
||||
|
||||
### Type-Safe Templates
|
||||
**Before**: String-based templates (error-prone)
|
||||
**After**: `askama` crate with compile-time validation
|
||||
|
||||
### Idiomatic Rust
|
||||
**Before**: `fs::write(path, json)?`
|
||||
**After**: `serde_json::to_writer_pretty()` + `file.sync_all()`
|
||||
|
||||
### Configuration
|
||||
**Before**: Magic numbers (timeout: 3000)
|
||||
**After**: Extract to `config.toml` for user customization
|
||||
|
||||
---
|
||||
|
||||
## 5. Leveraging Existing Crates
|
||||
|
||||
✅ **Already Available** (no work needed):
|
||||
- `shellexpand = "3.1"` - Path expansion
|
||||
- `clap` - CLI framework
|
||||
- `ruvector-core` - Vector storage
|
||||
- `tokio` - Async runtime
|
||||
|
||||
➕ **Add for MVP**:
|
||||
- `askama = "0.12"` - Type-safe templates
|
||||
- `shell-escape = "0.1"` - Security
|
||||
|
||||
➕ **Add for v1.1**:
|
||||
- `rusqlite = "0.32"` - SQLite migration
|
||||
|
||||
---
|
||||
|
||||
## 6. MVP Definition (3-4 Weeks)
|
||||
|
||||
### Week 1-2: Foundation
|
||||
- `ruvector hooks init` - Create `.ruvector/` structure
|
||||
- `ruvector hooks install` - Generate portable hooks
|
||||
- Template engine with runtime path resolution
|
||||
- JSON-to-JSON migration
|
||||
|
||||
### Week 3: Intelligence Layer
|
||||
- Refactor `index.js` for dynamic paths
|
||||
- Zero hardcoded paths
|
||||
- Test in fresh project
|
||||
|
||||
### Week 4: Polish
|
||||
- Cross-platform testing (Linux, macOS, Windows)
|
||||
- `ruvector hooks stats` command
|
||||
- Error handling + rollback
|
||||
- Documentation
|
||||
|
||||
### Deferred to v1.1
|
||||
❌ SQLite migration (needs format detection)
|
||||
❌ Global patterns system (sync complexity)
|
||||
❌ Export/import commands (nice-to-have)
|
||||
|
||||
---
|
||||
|
||||
## 7. Concrete Edits Made
|
||||
|
||||
### Updated IMPLEMENTATION_PLAN.md
|
||||
1. **Timeline table** (Section 8): Added MVP vs Full Release split
|
||||
2. **Risk assessment** (Section 6.1): Added 2 new risks with mitigations
|
||||
3. **Critical fixes** (NEW Section 11): Windows compatibility, rollback, security
|
||||
4. **Dependencies** (NEW Section 12): Specific Cargo.toml additions
|
||||
5. **Conclusion**: Updated with MVP achievements and timeline
|
||||
|
||||
### Created REVIEW_REPORT.md
|
||||
- 14-section detailed technical review
|
||||
- Platform-specific testing checklist
|
||||
- Integration test examples
|
||||
- Documentation requirements
|
||||
- Success metrics
|
||||
|
||||
---
|
||||
|
||||
## 8. Next Steps
|
||||
|
||||
### Immediate (Before Coding)
|
||||
1. ✅ Review and approve this document
|
||||
2. ✅ Add dependencies to `crates/ruvector-cli/Cargo.toml`
|
||||
3. ✅ Create `crates/ruvector-cli/templates/` directory
|
||||
4. ✅ Set up CI for Windows/macOS/Linux testing
|
||||
|
||||
### Week 1
|
||||
1. Create feature branch: `feature/portable-hooks-mvp`
|
||||
2. Implement Milestone 1 (Specification)
|
||||
3. Start CLI scaffolding (Milestone 2)
|
||||
|
||||
### Week 2-4
|
||||
Follow MVP implementation order (see Section 6)
|
||||
|
||||
---
|
||||
|
||||
## 9. Risks & Mitigations
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Windows edge cases | Comprehensive testing on PowerShell, CMD, WSL |
|
||||
| Data loss | Atomic migration with backup/rollback |
|
||||
| Command injection | `shell-escape` crate for all user inputs |
|
||||
| Hooks break after reinstall | Runtime path resolution via `which` |
|
||||
| SQLite format errors | Deferred to v1.1 with format detection |
|
||||
|
||||
---
|
||||
|
||||
## 10. Files Modified
|
||||
|
||||
### 1. IMPLEMENTATION_PLAN.md
|
||||
**Changes**:
|
||||
- Updated timeline (Section 8)
|
||||
- Added critical fixes (Section 11)
|
||||
- Added dependency recommendations (Section 12)
|
||||
- Updated conclusion with MVP scope
|
||||
|
||||
**Lines Modified**: ~100 lines added/changed
|
||||
|
||||
### 2. REVIEW_REPORT.md (New)
|
||||
**Purpose**: Detailed technical review with testing strategy
|
||||
|
||||
### 3. REVIEW_SUMMARY.md (This File)
|
||||
**Purpose**: Executive summary for quick review
|
||||
|
||||
---
|
||||
|
||||
## 11. Recommended File Changes
|
||||
|
||||
### Cargo.toml
|
||||
**File**: `/home/user/ruvector/crates/ruvector-cli/Cargo.toml`
|
||||
```toml
|
||||
[dependencies]
|
||||
askama = "0.12" # MVP
|
||||
shell-escape = "0.1" # MVP
|
||||
rusqlite = { version = "0.32", optional = true } # v1.1
|
||||
|
||||
[features]
|
||||
sqlite-migration = ["rusqlite"]
|
||||
```
|
||||
|
||||
### index.js
|
||||
**File**: `/home/user/ruvector/.claude/intelligence/index.js`
|
||||
**Line 20**: Change from:
|
||||
```javascript
|
||||
const DATA_DIR = join(__dirname, 'data');
|
||||
```
|
||||
To:
|
||||
```javascript
|
||||
const DATA_DIR = process.env.RUVECTOR_DATA_DIR ||
|
||||
join(process.cwd(), '.ruvector', 'intelligence') ||
|
||||
join(__dirname, 'data'); // Legacy fallback
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. Success Metrics
|
||||
|
||||
### Technical
|
||||
- ✅ Works on 3 platforms (Linux, macOS, Windows)
|
||||
- ✅ Migration <5s for 1000 trajectories
|
||||
- ✅ 100% data integrity (checksums)
|
||||
- ✅ Test coverage >80%
|
||||
|
||||
### User Experience
|
||||
- ✅ First-time setup <5 minutes
|
||||
- ✅ Zero hardcoded paths
|
||||
- ✅ Hooks survive reinstallation
|
||||
- ✅ Clear error messages
|
||||
|
||||
---
|
||||
|
||||
## 13. Final Verdict
|
||||
|
||||
**Approval**: ✅ **APPROVED FOR IMPLEMENTATION**
|
||||
|
||||
**Confidence**: 8/10
|
||||
|
||||
**Timeline**: 3-4 weeks for MVP (realistic and achievable)
|
||||
|
||||
**Remaining Risks**: Low (10-20% chance of minor delays)
|
||||
|
||||
**Overall Assessment**: Plan is solid, well-researched, and implementable. Critical issues identified and fixed. Timeline optimized by 50% while maintaining quality.
|
||||
|
||||
---
|
||||
|
||||
**Reviewed By**: Code Review Agent (ruvector)
|
||||
**Review Date**: 2025-12-25
|
||||
**Plan Version**: v2.0 (Post-Review)
|
||||
**Next Step**: Approve and begin implementation
|
||||
|
||||
---
|
||||
|
||||
## Appendix: Quick Reference
|
||||
|
||||
### Commands Being Added
|
||||
```bash
|
||||
npx ruvector hooks init # Initialize .ruvector/
|
||||
npx ruvector hooks install # Generate Claude Code hooks
|
||||
npx ruvector hooks migrate --from .claude/intelligence # Migrate data
|
||||
npx ruvector hooks stats # Show learning statistics
|
||||
```
|
||||
|
||||
### File Structure (MVP)
|
||||
```
|
||||
.ruvector/
|
||||
├── config.toml # Project settings
|
||||
├── intelligence/
|
||||
│ ├── trajectories.json # Learning data
|
||||
│ ├── patterns.json # Q-learning patterns
|
||||
│ └── memory.rvdb # Vector memory (rvlite)
|
||||
└── .gitignore
|
||||
```
|
||||
|
||||
### Dependencies Added
|
||||
- `askama` - Type-safe templates
|
||||
- `shell-escape` - Security
|
||||
- `rusqlite` (v1.1) - SQLite migration
|
||||
|
||||
### Existing Dependencies Leveraged
|
||||
- `shellexpand` - Path resolution ✅
|
||||
- `clap` - CLI framework ✅
|
||||
- `ruvector-core` - Vector storage ✅
|
||||
- `tokio` - Async runtime ✅
|
||||
733
vendor/ruvector/docs/hooks/TROUBLESHOOTING.md
vendored
Normal file
733
vendor/ruvector/docs/hooks/TROUBLESHOOTING.md
vendored
Normal file
@@ -0,0 +1,733 @@
|
||||
# RuVector Hooks Troubleshooting Guide
|
||||
|
||||
Solutions for common issues with the RuVector hooks system.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Quick Diagnostics](#quick-diagnostics)
|
||||
2. [Installation Issues](#installation-issues)
|
||||
3. [Hook Execution Issues](#hook-execution-issues)
|
||||
4. [Intelligence Layer Issues](#intelligence-layer-issues)
|
||||
5. [Performance Issues](#performance-issues)
|
||||
6. [Platform-Specific Issues](#platform-specific-issues)
|
||||
7. [Migration Issues](#migration-issues)
|
||||
8. [Debug Mode](#debug-mode)
|
||||
|
||||
---
|
||||
|
||||
## Quick Diagnostics
|
||||
|
||||
### Run Full Diagnostic
|
||||
|
||||
```bash
|
||||
# Check overall health
|
||||
npx ruvector hooks stats --verbose
|
||||
|
||||
# Validate configuration
|
||||
npx ruvector hooks validate-config
|
||||
|
||||
# Test hook execution
|
||||
npx ruvector hooks pre-edit --file test.ts
|
||||
npx ruvector hooks post-edit --file test.ts --success true
|
||||
```
|
||||
|
||||
### Common Symptoms and Solutions
|
||||
|
||||
| Symptom | Likely Cause | Solution |
|
||||
|---------|--------------|----------|
|
||||
| Hooks not running | Missing settings.json | Run `hooks install` |
|
||||
| "Command not found" | CLI not in PATH | Use `npx ruvector` |
|
||||
| No agent assignment | Intelligence disabled | Set `RUVECTOR_INTELLIGENCE_ENABLED=true` |
|
||||
| Slow hook execution | Large memory | Clean old trajectories |
|
||||
| Windows errors | Shell mismatch | Check shell wrapper |
|
||||
|
||||
---
|
||||
|
||||
## Installation Issues
|
||||
|
||||
### Problem: `hooks init` fails
|
||||
|
||||
**Symptoms:**
|
||||
```
|
||||
Error: Failed to create .ruvector directory
|
||||
Permission denied
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Check directory permissions:
|
||||
```bash
|
||||
ls -la .
|
||||
# Ensure you have write access
|
||||
```
|
||||
|
||||
2. Create directory manually:
|
||||
```bash
|
||||
mkdir -p .ruvector/intelligence
|
||||
npx ruvector hooks init
|
||||
```
|
||||
|
||||
3. Use sudo (last resort):
|
||||
```bash
|
||||
sudo npx ruvector hooks init
|
||||
sudo chown -R $USER:$USER .ruvector
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Problem: `hooks install` doesn't update settings
|
||||
|
||||
**Symptoms:**
|
||||
- `.claude/settings.json` unchanged
|
||||
- Old hooks still running
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Use `--force` flag:
|
||||
```bash
|
||||
npx ruvector hooks install --force
|
||||
```
|
||||
|
||||
2. Check backup and restore:
|
||||
```bash
|
||||
# View backup
|
||||
cat .claude/settings.json.backup
|
||||
|
||||
# If needed, restore and try again
|
||||
cp .claude/settings.json.backup .claude/settings.json
|
||||
npx ruvector hooks install --force
|
||||
```
|
||||
|
||||
3. Manually edit settings:
|
||||
```bash
|
||||
# Open and verify hook section
|
||||
code .claude/settings.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Problem: "npx ruvector" command not found
|
||||
|
||||
**Symptoms:**
|
||||
```
|
||||
npm ERR! could not determine executable to run
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Install globally:
|
||||
```bash
|
||||
npm install -g @ruvector/cli
|
||||
ruvector hooks init
|
||||
```
|
||||
|
||||
2. Check npm configuration:
|
||||
```bash
|
||||
npm config get prefix
|
||||
# Ensure this is in your PATH
|
||||
```
|
||||
|
||||
3. Use npx with package:
|
||||
```bash
|
||||
npx @ruvector/cli hooks init
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Hook Execution Issues
|
||||
|
||||
### Problem: Hooks not triggering
|
||||
|
||||
**Symptoms:**
|
||||
- No output when editing files
|
||||
- Session start message missing
|
||||
- Intelligence not active
|
||||
|
||||
**Diagnosis:**
|
||||
|
||||
```bash
|
||||
# Check settings.json has hooks
|
||||
cat .claude/settings.json | jq '.hooks'
|
||||
|
||||
# Should show PreToolUse, PostToolUse, etc.
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Reinstall hooks:
|
||||
```bash
|
||||
npx ruvector hooks install --force
|
||||
```
|
||||
|
||||
2. Check matcher patterns:
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Bash", // Case-sensitive!
|
||||
"hooks": [...]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. Verify Claude Code is loading settings:
|
||||
```bash
|
||||
# Restart Claude Code to reload settings
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Problem: Hook timeout
|
||||
|
||||
**Symptoms:**
|
||||
```
|
||||
Warning: Hook timeout after 3000ms
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Increase timeout in settings:
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"timeout": 5000, // Increase to 5 seconds
|
||||
"command": "..."
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. Check for slow operations:
|
||||
```bash
|
||||
# Time hook execution
|
||||
time npx ruvector hooks pre-edit --file test.ts
|
||||
```
|
||||
|
||||
3. Reduce hook complexity:
|
||||
- Disable neural training in pre-hooks
|
||||
- Use async for heavy operations
|
||||
- Cache repeated lookups
|
||||
|
||||
---
|
||||
|
||||
### Problem: Hook blocks tool execution
|
||||
|
||||
**Symptoms:**
|
||||
- Edit operations not completing
|
||||
- "continue: false" in output
|
||||
|
||||
**Diagnosis:**
|
||||
|
||||
```bash
|
||||
# Test hook directly
|
||||
npx ruvector hooks pre-edit --file problematic-file.ts
|
||||
|
||||
# Check response
|
||||
# { "continue": false, "reason": "..." }
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Check protected files:
|
||||
```bash
|
||||
# If file is protected, you'll see:
|
||||
# { "continue": false, "reason": "Protected file" }
|
||||
|
||||
# Add to exceptions in config.toml
|
||||
[hooks]
|
||||
protected_exceptions = [".env.local"]
|
||||
```
|
||||
|
||||
2. Disable blocking:
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Write",
|
||||
"hooks": [{
|
||||
"command": "...",
|
||||
"continueOnError": true // Never block on error
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Intelligence Layer Issues
|
||||
|
||||
### Problem: No agent suggestions
|
||||
|
||||
**Symptoms:**
|
||||
- `assignedAgent` always null
|
||||
- No intelligence guidance
|
||||
|
||||
**Diagnosis:**
|
||||
|
||||
```bash
|
||||
# Check intelligence status
|
||||
npx ruvector hooks stats
|
||||
|
||||
# Expected output:
|
||||
# Patterns: N
|
||||
# Memories: N
|
||||
# Status: Ready
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Enable intelligence:
|
||||
```bash
|
||||
export RUVECTOR_INTELLIGENCE_ENABLED=true
|
||||
```
|
||||
|
||||
2. Check data files exist:
|
||||
```bash
|
||||
ls -la .ruvector/intelligence/
|
||||
# Should show patterns.json, memory.json, etc.
|
||||
```
|
||||
|
||||
3. Initialize fresh data:
|
||||
```bash
|
||||
npx ruvector hooks init --force
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Problem: Poor agent suggestions
|
||||
|
||||
**Symptoms:**
|
||||
- Wrong agent assigned to file types
|
||||
- Low confidence scores
|
||||
|
||||
**Diagnosis:**
|
||||
|
||||
```bash
|
||||
# Check patterns
|
||||
npx ruvector hooks stats --verbose
|
||||
|
||||
# Look for:
|
||||
# Top Patterns:
|
||||
# 1. edit_rs_in_xxx → rust-developer (Q=0.82)
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Reset learning data:
|
||||
```bash
|
||||
rm .ruvector/intelligence/patterns.json
|
||||
rm .ruvector/intelligence/trajectories.json
|
||||
# Will rebuild from scratch
|
||||
```
|
||||
|
||||
2. Import team patterns:
|
||||
```bash
|
||||
npx ruvector hooks import --input team-patterns.json
|
||||
```
|
||||
|
||||
3. Wait for learning:
|
||||
- Patterns improve with use
|
||||
- 50+ edits needed for good suggestions
|
||||
|
||||
---
|
||||
|
||||
### Problem: Memory search slow or failing
|
||||
|
||||
**Symptoms:**
|
||||
- Memory search timeout
|
||||
- "Error: Failed to load memory"
|
||||
|
||||
**Diagnosis:**
|
||||
|
||||
```bash
|
||||
# Check memory size
|
||||
ls -la .ruvector/intelligence/memory.json
|
||||
|
||||
# If >10MB, consider cleanup
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Clean old memories:
|
||||
```bash
|
||||
# Backup first
|
||||
cp .ruvector/intelligence/memory.json memory-backup.json
|
||||
|
||||
# Keep only recent
|
||||
node -e "
|
||||
const fs = require('fs');
|
||||
const data = JSON.parse(fs.readFileSync('.ruvector/intelligence/memory.json'));
|
||||
const recent = data.slice(-1000); // Keep last 1000
|
||||
fs.writeFileSync('.ruvector/intelligence/memory.json', JSON.stringify(recent));
|
||||
"
|
||||
```
|
||||
|
||||
2. Rebuild HNSW index:
|
||||
```bash
|
||||
rm .ruvector/intelligence/memory.rvdb
|
||||
# Will rebuild on next use
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Issues
|
||||
|
||||
### Problem: High hook overhead
|
||||
|
||||
**Symptoms:**
|
||||
- Slow file operations
|
||||
- Noticeable delay on every edit
|
||||
|
||||
**Diagnosis:**
|
||||
|
||||
```bash
|
||||
# Time individual hooks
|
||||
time npx ruvector hooks pre-edit --file test.ts
|
||||
time npx ruvector hooks post-edit --file test.ts --success true
|
||||
|
||||
# Target: <50ms each
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Disable neural training:
|
||||
```bash
|
||||
# In config.toml
|
||||
[intelligence]
|
||||
neural_training = false
|
||||
```
|
||||
|
||||
2. Reduce memory operations:
|
||||
```toml
|
||||
[hooks]
|
||||
store_memory = false # Disable memory storage
|
||||
```
|
||||
|
||||
3. Use async post-hooks:
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [{
|
||||
"matcher": "Write",
|
||||
"hooks": [{
|
||||
"command": "...",
|
||||
"async": true // Don't wait for completion
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Problem: Large intelligence data files
|
||||
|
||||
**Symptoms:**
|
||||
- `.ruvector/intelligence/` >100MB
|
||||
- Slow startup
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Set retention limits:
|
||||
```toml
|
||||
# In config.toml
|
||||
[intelligence]
|
||||
max_trajectories = 1000
|
||||
max_memories = 10000
|
||||
```
|
||||
|
||||
2. Clean old data:
|
||||
```bash
|
||||
# Export current patterns
|
||||
npx ruvector hooks export --output patterns-backup.json --include patterns
|
||||
|
||||
# Reset
|
||||
rm -rf .ruvector/intelligence/*
|
||||
|
||||
# Re-import patterns
|
||||
npx ruvector hooks import --input patterns-backup.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Platform-Specific Issues
|
||||
|
||||
### Windows Issues
|
||||
|
||||
#### Problem: "/bin/bash not found"
|
||||
|
||||
**Symptoms:**
|
||||
```
|
||||
'/bin/bash' is not recognized as an internal or external command
|
||||
```
|
||||
|
||||
**Solution:**
|
||||
|
||||
Check that hooks use Windows-compatible shell:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"command": "cmd /c 'npx ruvector hooks pre-command'"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Or reinstall hooks (auto-detects platform):
|
||||
```bash
|
||||
npx ruvector hooks install --force
|
||||
```
|
||||
|
||||
#### Problem: Path separator issues
|
||||
|
||||
**Symptoms:**
|
||||
- File paths not recognized
|
||||
- "File not found" errors
|
||||
|
||||
**Solution:**
|
||||
|
||||
Ensure paths use forward slashes or escaped backslashes:
|
||||
|
||||
```bash
|
||||
# Good
|
||||
npx ruvector hooks pre-edit --file "src/app.ts"
|
||||
|
||||
# Bad on Windows
|
||||
npx ruvector hooks pre-edit --file "src\app.ts"
|
||||
```
|
||||
|
||||
#### Problem: jq not found
|
||||
|
||||
**Symptoms:**
|
||||
```
|
||||
'jq' is not recognized as an internal or external command
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Install jq:
|
||||
```bash
|
||||
# Using chocolatey
|
||||
choco install jq
|
||||
|
||||
# Using scoop
|
||||
scoop install jq
|
||||
```
|
||||
|
||||
2. Or use jq-free hooks:
|
||||
```bash
|
||||
npx ruvector hooks install --template minimal
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### macOS Issues
|
||||
|
||||
#### Problem: Permission denied
|
||||
|
||||
**Symptoms:**
|
||||
```
|
||||
Error: EACCES: permission denied
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Fix npm permissions:
|
||||
```bash
|
||||
sudo chown -R $(whoami) ~/.npm
|
||||
```
|
||||
|
||||
2. Use nvm:
|
||||
```bash
|
||||
# Install nvm and use it for npm
|
||||
nvm install node
|
||||
nvm use node
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Linux Issues
|
||||
|
||||
#### Problem: Node.js version too old
|
||||
|
||||
**Symptoms:**
|
||||
```
|
||||
SyntaxError: Unexpected token '.'
|
||||
```
|
||||
|
||||
**Solution:**
|
||||
|
||||
Update Node.js:
|
||||
```bash
|
||||
# Using nvm
|
||||
nvm install 18
|
||||
nvm use 18
|
||||
|
||||
# Or using package manager
|
||||
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
|
||||
sudo apt-get install -y nodejs
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Migration Issues
|
||||
|
||||
### Problem: Migration data loss
|
||||
|
||||
**Symptoms:**
|
||||
- Fewer patterns after migration
|
||||
- Missing memories
|
||||
|
||||
**Diagnosis:**
|
||||
|
||||
```bash
|
||||
# Compare counts
|
||||
echo "Before: $(jq '.length' old-patterns.json)"
|
||||
echo "After: $(npx ruvector hooks stats --json | jq '.patterns')"
|
||||
```
|
||||
|
||||
**Solutions:**
|
||||
|
||||
1. Use validation:
|
||||
```bash
|
||||
npx ruvector hooks migrate --from old-data --validate
|
||||
```
|
||||
|
||||
2. Merge instead of replace:
|
||||
```bash
|
||||
npx ruvector hooks migrate --from old-data --merge
|
||||
```
|
||||
|
||||
3. Restore from backup:
|
||||
```bash
|
||||
cp .ruvector/intelligence/backup-*/* .ruvector/intelligence/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Problem: SQLite migration format error
|
||||
|
||||
**Symptoms:**
|
||||
```
|
||||
Error: Unknown embedding format in memory.db
|
||||
```
|
||||
|
||||
**Solution:**
|
||||
|
||||
SQLite migration requires format detection. For MVP, use JSON export:
|
||||
|
||||
```bash
|
||||
# Export from source as JSON first
|
||||
npx claude-flow memory export --output memory.json
|
||||
|
||||
# Then import
|
||||
npx ruvector hooks import --input memory.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Debug Mode
|
||||
|
||||
### Enable Debug Output
|
||||
|
||||
```bash
|
||||
# Set environment variable
|
||||
export CLAUDE_FLOW_DEBUG=true
|
||||
export RUVECTOR_DEBUG=true
|
||||
|
||||
# Run with debug
|
||||
npx ruvector hooks pre-edit --file test.ts --debug
|
||||
```
|
||||
|
||||
### Debug Output Interpretation
|
||||
|
||||
```
|
||||
DEBUG: Loading config from .ruvector/config.toml
|
||||
DEBUG: Intelligence enabled: true
|
||||
DEBUG: Q-table loaded: 89 patterns
|
||||
DEBUG: Memory loaded: 543 vectors
|
||||
DEBUG: Encoding state for test.ts
|
||||
DEBUG: State key: edit_ts_in_project
|
||||
DEBUG: Q-values: { "typescript-developer": 0.82, "coder": 0.45 }
|
||||
DEBUG: Selected agent: typescript-developer (confidence: 0.82)
|
||||
```
|
||||
|
||||
### View Hook Logs
|
||||
|
||||
```bash
|
||||
# Today's logs
|
||||
cat .ruvector/logs/hooks-$(date +%Y-%m-%d).log
|
||||
|
||||
# Tail logs
|
||||
tail -f .ruvector/logs/hooks-*.log
|
||||
```
|
||||
|
||||
### Test Hooks Manually
|
||||
|
||||
```bash
|
||||
# Test pre-edit
|
||||
echo '{"tool_input":{"file_path":"test.ts"}}' | npx ruvector hooks pre-edit --stdin
|
||||
|
||||
# Test post-edit
|
||||
echo '{"tool_input":{"file_path":"test.ts"},"tool_result":{"success":true}}' | npx ruvector hooks post-edit --stdin
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Getting Help
|
||||
|
||||
### Gather Diagnostic Info
|
||||
|
||||
```bash
|
||||
# Create diagnostic report
|
||||
{
|
||||
echo "=== RuVector Version ==="
|
||||
npx ruvector --version
|
||||
|
||||
echo -e "\n=== Node Version ==="
|
||||
node --version
|
||||
|
||||
echo -e "\n=== Platform ==="
|
||||
uname -a
|
||||
|
||||
echo -e "\n=== Hooks Stats ==="
|
||||
npx ruvector hooks stats --json
|
||||
|
||||
echo -e "\n=== Config ==="
|
||||
cat .ruvector/config.toml
|
||||
|
||||
echo -e "\n=== Settings ==="
|
||||
cat .claude/settings.json | jq '.hooks'
|
||||
} > ruvector-diagnostic.txt
|
||||
|
||||
echo "Diagnostic saved to ruvector-diagnostic.txt"
|
||||
```
|
||||
|
||||
### Report Issues
|
||||
|
||||
1. Create diagnostic report (above)
|
||||
2. Open issue: https://github.com/ruvnet/ruvector/issues
|
||||
3. Include:
|
||||
- Diagnostic report
|
||||
- Steps to reproduce
|
||||
- Expected vs actual behavior
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [User Guide](USER_GUIDE.md) - Getting started
|
||||
- [CLI Reference](CLI_REFERENCE.md) - Command documentation
|
||||
- [Architecture](ARCHITECTURE.md) - Technical details
|
||||
- [Migration Guide](MIGRATION.md) - Upgrade from other systems
|
||||
629
vendor/ruvector/docs/hooks/USER_GUIDE.md
vendored
Normal file
629
vendor/ruvector/docs/hooks/USER_GUIDE.md
vendored
Normal file
@@ -0,0 +1,629 @@
|
||||
# RuVector Hooks User Guide
|
||||
|
||||
A comprehensive guide to setting up and using the RuVector hooks system for intelligent Claude Code automation.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Quick Start](#quick-start)
|
||||
2. [Prerequisites](#prerequisites)
|
||||
3. [Installation](#installation)
|
||||
4. [Basic Usage](#basic-usage)
|
||||
5. [Configuration](#configuration)
|
||||
6. [Working with Hooks](#working-with-hooks)
|
||||
7. [Intelligence Features](#intelligence-features)
|
||||
8. [Best Practices](#best-practices)
|
||||
9. [Examples](#examples)
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
Get up and running in under 5 minutes:
|
||||
|
||||
```bash
|
||||
# Step 1: Initialize hooks in your project
|
||||
npx ruvector hooks init
|
||||
|
||||
# Step 2: Install hooks into Claude Code
|
||||
npx ruvector hooks install
|
||||
|
||||
# Step 3: Verify installation
|
||||
npx ruvector hooks stats
|
||||
|
||||
# Done! Hooks are now active
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### Required
|
||||
|
||||
- **Node.js 18+**: Required for hook execution
|
||||
- **Claude Code**: The hooks integrate with Claude Code's hook system
|
||||
- **npm or pnpm**: Package manager for installation
|
||||
|
||||
### Optional
|
||||
|
||||
- **jq**: JSON processing for hook data (auto-installed on most systems)
|
||||
- **Git**: For version control integration
|
||||
- **claude-flow CLI**: For advanced swarm coordination
|
||||
|
||||
### Verify Prerequisites
|
||||
|
||||
```bash
|
||||
# Check Node.js version
|
||||
node --version # Should be 18.x or higher
|
||||
|
||||
# Check npm
|
||||
npm --version
|
||||
|
||||
# Check jq (optional)
|
||||
which jq || echo "jq not installed (optional)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
### Method 1: npx (Recommended)
|
||||
|
||||
The simplest way to install hooks:
|
||||
|
||||
```bash
|
||||
# Initialize in any project
|
||||
cd your-project
|
||||
npx ruvector hooks init
|
||||
npx ruvector hooks install
|
||||
```
|
||||
|
||||
### Method 2: Global Installation
|
||||
|
||||
For frequent use across projects:
|
||||
|
||||
```bash
|
||||
# Install globally
|
||||
npm install -g @ruvector/cli
|
||||
|
||||
# Then use directly
|
||||
ruvector hooks init
|
||||
ruvector hooks install
|
||||
```
|
||||
|
||||
### Method 3: With Claude Flow
|
||||
|
||||
If using claude-flow for swarm coordination:
|
||||
|
||||
```bash
|
||||
# Initialize with full hook support
|
||||
npx claude-flow init --hooks
|
||||
|
||||
# Hooks are automatically configured
|
||||
```
|
||||
|
||||
### Verify Installation
|
||||
|
||||
```bash
|
||||
# Check hooks are installed
|
||||
npx ruvector hooks stats
|
||||
|
||||
# Expected output:
|
||||
# RuVector Intelligence Statistics
|
||||
# --------------------------------
|
||||
# Patterns: 0 (new installation)
|
||||
# Memories: 0
|
||||
# Status: Ready
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### How Hooks Work
|
||||
|
||||
Hooks automatically execute when you use Claude Code:
|
||||
|
||||
1. **Pre-hooks** run before tool execution
|
||||
2. **Post-hooks** run after tool execution
|
||||
3. **Session hooks** run at session boundaries
|
||||
|
||||
### Automatic Behavior
|
||||
|
||||
Once installed, hooks work automatically:
|
||||
|
||||
```bash
|
||||
# When you edit a file in Claude Code:
|
||||
# 1. pre-edit hook checks file type, assigns agent
|
||||
# 2. Claude Code performs the edit
|
||||
# 3. post-edit hook formats code, stores in memory
|
||||
|
||||
# When you run a command:
|
||||
# 1. pre-bash hook validates safety
|
||||
# 2. Command executes
|
||||
# 3. post-bash hook logs result, updates metrics
|
||||
```
|
||||
|
||||
### Manual Hook Execution
|
||||
|
||||
You can also run hooks manually:
|
||||
|
||||
```bash
|
||||
# Test pre-edit hook
|
||||
npx ruvector hooks pre-edit --file "src/app.ts"
|
||||
|
||||
# Test post-edit hook
|
||||
npx ruvector hooks post-edit --file "src/app.ts" --success true
|
||||
|
||||
# Run session hooks
|
||||
npx ruvector hooks session-start
|
||||
npx ruvector hooks session-end --export-metrics
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Configuration File
|
||||
|
||||
After `hooks init`, a configuration file is created:
|
||||
|
||||
**`.ruvector/config.toml`**:
|
||||
|
||||
```toml
|
||||
[intelligence]
|
||||
enabled = true
|
||||
learning_rate = 0.1
|
||||
ab_test_group = "treatment"
|
||||
use_hyperbolic_distance = true
|
||||
curvature = 1.0
|
||||
|
||||
[memory]
|
||||
backend = "rvdb"
|
||||
max_memories = 50000
|
||||
dimensions = 128
|
||||
|
||||
[patterns]
|
||||
decay_half_life_days = 7
|
||||
min_q_value = -0.5
|
||||
max_q_value = 0.8
|
||||
|
||||
[hooks]
|
||||
pre_command_enabled = true
|
||||
post_command_enabled = true
|
||||
pre_edit_enabled = true
|
||||
post_edit_enabled = true
|
||||
session_start_enabled = true
|
||||
session_end_enabled = true
|
||||
timeout_ms = 3000
|
||||
```
|
||||
|
||||
### Claude Code Settings
|
||||
|
||||
Hooks are registered in `.claude/settings.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"timeout": 3000,
|
||||
"command": "npx ruvector hooks pre-command \"$CMD\""
|
||||
}]
|
||||
},
|
||||
{
|
||||
"matcher": "Write|Edit|MultiEdit",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"timeout": 3000,
|
||||
"command": "npx ruvector hooks pre-edit \"$FILE\""
|
||||
}]
|
||||
}
|
||||
],
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit|MultiEdit",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "npx ruvector hooks post-edit \"$FILE\" \"true\""
|
||||
}]
|
||||
}
|
||||
],
|
||||
"SessionStart": [
|
||||
{
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"timeout": 5000,
|
||||
"command": "npx ruvector hooks session-start"
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Customizing Hooks
|
||||
|
||||
#### Add Protected File Detection
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "npx ruvector hooks check-protected \"$FILE\""
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Add Auto-Testing
|
||||
|
||||
```json
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write",
|
||||
"hooks": [{
|
||||
"type": "command",
|
||||
"command": "test -f \"${FILE%.ts}.test.ts\" && npm test \"${FILE%.ts}.test.ts\"",
|
||||
"continueOnError": true
|
||||
}]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Working with Hooks
|
||||
|
||||
### Pre-Edit Hook
|
||||
|
||||
Runs before file modifications:
|
||||
|
||||
```bash
|
||||
npx ruvector hooks pre-edit --file "src/auth/login.ts"
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
- Detects file type and language
|
||||
- Assigns appropriate agent (e.g., TypeScript files → typescript-developer)
|
||||
- Checks for existing patterns
|
||||
- Validates syntax if enabled
|
||||
- Creates backup if configured
|
||||
|
||||
**Output example:**
|
||||
```json
|
||||
{
|
||||
"continue": true,
|
||||
"agent": "typescript-developer",
|
||||
"confidence": 0.85,
|
||||
"syntaxValid": true,
|
||||
"warnings": []
|
||||
}
|
||||
```
|
||||
|
||||
### Post-Edit Hook
|
||||
|
||||
Runs after file modifications:
|
||||
|
||||
```bash
|
||||
npx ruvector hooks post-edit --file "src/auth/login.ts" --success true
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
- Records successful edit in trajectory
|
||||
- Updates Q-learning patterns
|
||||
- Stores context in vector memory
|
||||
- Optionally formats code
|
||||
- Trains neural patterns
|
||||
|
||||
### Session Hooks
|
||||
|
||||
#### Starting a Session
|
||||
|
||||
```bash
|
||||
npx ruvector hooks session-start --session-id "feature-dev"
|
||||
```
|
||||
|
||||
**Output:**
|
||||
```
|
||||
RuVector Intelligence Layer Active
|
||||
|
||||
Patterns: 131 state-action pairs
|
||||
Memories: 4,247 vectors
|
||||
Status: Ready
|
||||
```
|
||||
|
||||
#### Ending a Session
|
||||
|
||||
```bash
|
||||
npx ruvector hooks session-end --export-metrics --generate-summary
|
||||
```
|
||||
|
||||
**What it does:**
|
||||
- Persists memory state
|
||||
- Exports session metrics
|
||||
- Generates work summary
|
||||
- Cleans up temporary files
|
||||
|
||||
---
|
||||
|
||||
## Intelligence Features
|
||||
|
||||
### Q-Learning
|
||||
|
||||
The hooks system learns from your actions:
|
||||
|
||||
```bash
|
||||
# View learned patterns
|
||||
npx ruvector hooks stats --verbose
|
||||
|
||||
# Output:
|
||||
# Top Patterns:
|
||||
# 1. edit_ts_in_src → typescript-developer (Q=0.82)
|
||||
# 2. edit_rs_in_crates → rust-developer (Q=0.79)
|
||||
# 3. cargo_test → success (Q=0.91)
|
||||
```
|
||||
|
||||
### Agent Routing
|
||||
|
||||
Automatically assigns the best agent for each file:
|
||||
|
||||
| File Type | Assigned Agent | Confidence |
|
||||
|-----------|---------------|------------|
|
||||
| `*.ts`, `*.tsx` | typescript-developer | 85% |
|
||||
| `*.rs` | rust-developer | 80% |
|
||||
| `*.py` | python-developer | 78% |
|
||||
| `*.go` | go-developer | 75% |
|
||||
| `*.sql` | database-specialist | 70% |
|
||||
|
||||
### Memory Persistence
|
||||
|
||||
Decisions are stored for future reference:
|
||||
|
||||
```bash
|
||||
# Check memory usage
|
||||
npx ruvector hooks stats
|
||||
|
||||
# Output:
|
||||
# Memories: 4,247 vectors
|
||||
# Dimensions: 128
|
||||
# Storage: 2.4 MB
|
||||
```
|
||||
|
||||
### A/B Testing
|
||||
|
||||
Compare learning effectiveness:
|
||||
|
||||
```bash
|
||||
# Treatment group (learning enabled)
|
||||
INTELLIGENCE_MODE=treatment npx ruvector hooks pre-edit --file "test.ts"
|
||||
|
||||
# Control group (random baseline)
|
||||
INTELLIGENCE_MODE=control npx ruvector hooks pre-edit --file "test.ts"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Initialize Early
|
||||
|
||||
Set up hooks at the start of a project:
|
||||
|
||||
```bash
|
||||
# After creating a new project
|
||||
npx ruvector hooks init
|
||||
npx ruvector hooks install
|
||||
```
|
||||
|
||||
### 2. Use Meaningful Session IDs
|
||||
|
||||
Track work with descriptive sessions:
|
||||
|
||||
```bash
|
||||
# Good: Descriptive sessions
|
||||
npx ruvector hooks session-start --session-id "feature-auth-oauth2"
|
||||
npx ruvector hooks session-start --session-id "bugfix-memory-leak-123"
|
||||
|
||||
# Avoid: Generic sessions
|
||||
npx ruvector hooks session-start --session-id "session1"
|
||||
```
|
||||
|
||||
### 3. Export Metrics Regularly
|
||||
|
||||
Capture performance data:
|
||||
|
||||
```bash
|
||||
# At end of work session
|
||||
npx ruvector hooks session-end --export-metrics --generate-summary
|
||||
```
|
||||
|
||||
### 4. Review Pattern Quality
|
||||
|
||||
Check learning effectiveness:
|
||||
|
||||
```bash
|
||||
# Weekly review
|
||||
npx ruvector hooks stats --verbose
|
||||
|
||||
# Check calibration
|
||||
# Good: 0.04-0.06 calibration error
|
||||
# Bad: >0.15 calibration error
|
||||
```
|
||||
|
||||
### 5. Keep Hooks Lightweight
|
||||
|
||||
Follow performance guidelines:
|
||||
|
||||
- Hook execution: <50ms
|
||||
- Total overhead: <100ms per operation
|
||||
- Async heavy operations
|
||||
- Cache repeated lookups
|
||||
|
||||
### 6. Use Version Control
|
||||
|
||||
Track hook configurations:
|
||||
|
||||
```bash
|
||||
# Add to git
|
||||
git add .claude/settings.json
|
||||
git add .ruvector/config.toml
|
||||
|
||||
# Ignore learning data (optional)
|
||||
echo ".ruvector/intelligence/" >> .gitignore
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Examples
|
||||
|
||||
### Example 1: Development Workflow
|
||||
|
||||
```bash
|
||||
# Start development session
|
||||
npx ruvector hooks session-start --session-id "feature-user-profile"
|
||||
|
||||
# Work on files (hooks run automatically via Claude Code)
|
||||
# - Pre-edit assigns agents
|
||||
# - Post-edit formats and stores
|
||||
|
||||
# End session
|
||||
npx ruvector hooks session-end \
|
||||
--session-id "feature-user-profile" \
|
||||
--export-metrics \
|
||||
--generate-summary
|
||||
```
|
||||
|
||||
### Example 2: Debugging Session
|
||||
|
||||
```bash
|
||||
# Start debug session
|
||||
npx ruvector hooks session-start --session-id "debug-api-timeout"
|
||||
|
||||
# Load previous context
|
||||
npx ruvector hooks session-restore --session-id "debug-api-timeout"
|
||||
|
||||
# Work on debugging...
|
||||
|
||||
# Export findings
|
||||
npx ruvector hooks session-end \
|
||||
--session-id "debug-api-timeout" \
|
||||
--store-decisions \
|
||||
--generate-report
|
||||
```
|
||||
|
||||
### Example 3: Multi-Agent Task
|
||||
|
||||
```bash
|
||||
# Pre-task with agent spawning
|
||||
npx claude-flow hook pre-task \
|
||||
--description "Implement OAuth2 authentication" \
|
||||
--auto-spawn-agents \
|
||||
--load-memory
|
||||
|
||||
# Agents work on files (hooks coordinate)
|
||||
|
||||
# Post-task analysis
|
||||
npx claude-flow hook post-task \
|
||||
--task-id "oauth2-impl" \
|
||||
--analyze-performance \
|
||||
--export-learnings
|
||||
```
|
||||
|
||||
### Example 4: Custom Rust Workflow
|
||||
|
||||
For Rust projects, specialized hooks are available:
|
||||
|
||||
```bash
|
||||
# Pre-edit for Rust files
|
||||
.claude/hooks/rust-check.sh src/lib.rs
|
||||
|
||||
# Post-edit with benchmarks
|
||||
.claude/hooks/post-rust-edit.sh src/lib.rs true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Environment Setup
|
||||
|
||||
### Required Environment Variables
|
||||
|
||||
```bash
|
||||
# Enable intelligence (default: true)
|
||||
export RUVECTOR_INTELLIGENCE_ENABLED=true
|
||||
|
||||
# Set A/B test group
|
||||
export INTELLIGENCE_MODE=treatment
|
||||
|
||||
# Optional: Custom data directory
|
||||
export RUVECTOR_DATA_DIR=.ruvector
|
||||
```
|
||||
|
||||
### Recommended Shell Configuration
|
||||
|
||||
Add to `~/.bashrc` or `~/.zshrc`:
|
||||
|
||||
```bash
|
||||
# RuVector hooks
|
||||
export RUVECTOR_INTELLIGENCE_ENABLED=true
|
||||
export INTELLIGENCE_MODE=treatment
|
||||
|
||||
# Alias for convenience
|
||||
alias rv='npx ruvector'
|
||||
alias rvhooks='npx ruvector hooks'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Getting Help
|
||||
|
||||
### Check Status
|
||||
|
||||
```bash
|
||||
npx ruvector hooks stats --verbose
|
||||
```
|
||||
|
||||
### Debug Mode
|
||||
|
||||
```bash
|
||||
# Enable debug output
|
||||
export CLAUDE_FLOW_DEBUG=true
|
||||
|
||||
# Run with debug
|
||||
npx ruvector hooks pre-edit --file "test.ts" --debug
|
||||
```
|
||||
|
||||
### View Logs
|
||||
|
||||
```bash
|
||||
# Check hook execution logs
|
||||
cat .ruvector/logs/hooks-$(date +%Y-%m-%d).log
|
||||
```
|
||||
|
||||
### Validate Configuration
|
||||
|
||||
```bash
|
||||
# Check JSON syntax
|
||||
npx ruvector hooks validate-config
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Next Steps
|
||||
|
||||
- [CLI Reference](CLI_REFERENCE.md) - Full command documentation
|
||||
- [Architecture](ARCHITECTURE.md) - Technical details
|
||||
- [Migration Guide](MIGRATION.md) - Upgrade from other systems
|
||||
- [Troubleshooting](TROUBLESHOOTING.md) - Common issues
|
||||
Reference in New Issue
Block a user