mirror of
https://github.com/anomalyco/opencode.git
synced 2026-07-23 10:45:33 -04:00
chore: apply local updates after upstream merge
This commit is contained in:
@@ -9,20 +9,39 @@
|
||||
},
|
||||
"personas-memory": {
|
||||
"type": "local",
|
||||
"command": ["bun", "run", "~/.local/src/agent-core/src/mcp/servers/memory.ts"],
|
||||
"command": ["bun", "run", "/home/artur/.local/src/agent-core/src/mcp/servers/memory.ts"],
|
||||
"enabled": true
|
||||
},
|
||||
"personas-calendar": {
|
||||
"type": "local",
|
||||
"command": ["bun", "run", "~/.local/src/agent-core/src/mcp/servers/calendar.ts"],
|
||||
"command": ["bun", "run", "/home/artur/.local/src/agent-core/src/mcp/servers/calendar.ts"],
|
||||
"enabled": true
|
||||
},
|
||||
"personas-portfolio": {
|
||||
"type": "local",
|
||||
"command": ["bun", "run", "~/.local/src/agent-core/src/mcp/servers/portfolio.ts"],
|
||||
"command": ["bun", "run", "/home/artur/.local/src/agent-core/src/mcp/servers/portfolio.ts"],
|
||||
"enabled": true
|
||||
}
|
||||
},
|
||||
"memory": {
|
||||
"qdrant": {
|
||||
"url": "http://localhost:6333",
|
||||
"collection": "personas_memory"
|
||||
},
|
||||
"embedding": {
|
||||
"profile": "nebius/qwen3-embedding-8b",
|
||||
"dimensions": 4096,
|
||||
"apiKey": "{env:NEBIUS_API_KEY}"
|
||||
}
|
||||
},
|
||||
"tiara": {
|
||||
"qdrant": {
|
||||
"url": "http://localhost:6333",
|
||||
"stateCollection": "personas_state",
|
||||
"memoryCollection": "personas_memory",
|
||||
"embeddingDimension": 4096
|
||||
}
|
||||
},
|
||||
"tools": {
|
||||
"github-triage": false,
|
||||
"github-pr-search": false
|
||||
@@ -44,10 +63,12 @@
|
||||
"color": "#7fd88c"
|
||||
},
|
||||
"title": {
|
||||
"model": "google/antigravity-gemini-3-flash",
|
||||
"temperature": 0.5,
|
||||
"hidden": true
|
||||
},
|
||||
"compaction": {
|
||||
"model": "google/antigravity-gemini-3-flash",
|
||||
"temperature": 0.3,
|
||||
"hidden": true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
name: 1password
|
||||
description: Set up and use 1Password CLI (op). Use when installing the CLI, enabling desktop app integration, signing in (single or multi-account), or reading/injecting/running secrets via op.
|
||||
homepage: https://developer.1password.com/docs/cli/get-started/
|
||||
metadata: {"zee":{"emoji":"🔐","requires":{"bins":["op"]},"install":[{"id":"brew","kind":"brew","formula":"1password-cli","bins":["op"],"label":"Install 1Password CLI (brew)"}]}}
|
||||
---
|
||||
|
||||
# 1Password CLI
|
||||
|
||||
Follow the official CLI get-started steps. Don't guess install commands.
|
||||
|
||||
## References
|
||||
|
||||
- `references/get-started.md` (install + app integration + sign-in flow)
|
||||
- `references/cli-examples.md` (real `op` examples)
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Check OS + shell.
|
||||
2. Verify CLI present: `op --version`.
|
||||
3. Confirm desktop app integration is enabled (per get-started) and the app is unlocked.
|
||||
4. REQUIRED: create a fresh tmux session for all `op` commands (no direct `op` calls outside tmux).
|
||||
5. Sign in / authorize inside tmux: `op signin` (expect app prompt).
|
||||
6. Verify access inside tmux: `op whoami` (must succeed before any secret read).
|
||||
7. If multiple accounts: use `--account` or `OP_ACCOUNT`.
|
||||
|
||||
## REQUIRED tmux session (T-Max)
|
||||
|
||||
The shell tool uses a fresh TTY per command. To avoid re-prompts and failures, always run `op` inside a dedicated tmux session with a fresh socket/session name.
|
||||
|
||||
Example (see `tmux` skill for socket conventions, do not reuse old session names):
|
||||
|
||||
```bash
|
||||
SOCKET_DIR="${ZEE_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/zee-tmux-sockets}"
|
||||
mkdir -p "$SOCKET_DIR"
|
||||
SOCKET="$SOCKET_DIR/zee-op.sock"
|
||||
SESSION="op-auth-$(date +%Y%m%d-%H%M%S)"
|
||||
|
||||
tmux -S "$SOCKET" new -d -s "$SESSION" -n shell
|
||||
tmux -S "$SOCKET" send-keys -t "$SESSION":0.0 -- "op signin --account my.1password.com" Enter
|
||||
tmux -S "$SOCKET" send-keys -t "$SESSION":0.0 -- "op whoami" Enter
|
||||
tmux -S "$SOCKET" send-keys -t "$SESSION":0.0 -- "op vault list" Enter
|
||||
tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200
|
||||
tmux -S "$SOCKET" kill-session -t "$SESSION"
|
||||
```
|
||||
|
||||
## Guardrails
|
||||
|
||||
- Never paste secrets into logs, chat, or code.
|
||||
- Prefer `op run` / `op inject` over writing secrets to disk.
|
||||
- If sign-in without app integration is needed, use `op account add`.
|
||||
- If a command returns "account is not signed in", re-run `op signin` inside tmux and authorize in the app.
|
||||
- Do not run `op` outside tmux; stop and ask if tmux is unavailable.
|
||||
@@ -0,0 +1,29 @@
|
||||
# op CLI examples (from op help)
|
||||
|
||||
## Sign in
|
||||
|
||||
- `op signin`
|
||||
- `op signin --account <shorthand|signin-address|account-id|user-id>`
|
||||
|
||||
## Read
|
||||
|
||||
- `op read op://app-prod/db/password`
|
||||
- `op read "op://app-prod/db/one-time password?attribute=otp"`
|
||||
- `op read "op://app-prod/ssh key/private key?ssh-format=openssh"`
|
||||
- `op read --out-file ./key.pem op://app-prod/server/ssh/key.pem`
|
||||
|
||||
## Run
|
||||
|
||||
- `export DB_PASSWORD="op://app-prod/db/password"`
|
||||
- `op run --no-masking -- printenv DB_PASSWORD`
|
||||
- `op run --env-file="./.env" -- printenv DB_PASSWORD`
|
||||
|
||||
## Inject
|
||||
|
||||
- `echo "db_password: {{ op://app-prod/db/password }}" | op inject`
|
||||
- `op inject -i config.yml.tpl -o config.yml`
|
||||
|
||||
## Whoami / accounts
|
||||
|
||||
- `op whoami`
|
||||
- `op account list`
|
||||
@@ -0,0 +1,17 @@
|
||||
# 1Password CLI get-started (summary)
|
||||
|
||||
- Works on macOS, Windows, and Linux.
|
||||
- macOS/Linux shells: bash, zsh, sh, fish.
|
||||
- Windows shell: PowerShell.
|
||||
- Requires a 1Password subscription and the desktop app to use app integration.
|
||||
- macOS requirement: Big Sur 11.0.0 or later.
|
||||
- Linux app integration requires PolKit + an auth agent.
|
||||
- Install the CLI per the official doc for your OS.
|
||||
- Enable desktop app integration in the 1Password app:
|
||||
- Open and unlock the app, then select your account/collection.
|
||||
- macOS: Settings > Developer > Integrate with 1Password CLI (Touch ID optional).
|
||||
- Windows: turn on Windows Hello, then Settings > Developer > Integrate.
|
||||
- Linux: Settings > Security > Unlock using system authentication, then Settings > Developer > Integrate.
|
||||
- After integration, run any command to sign in (example in docs: `op vault list`).
|
||||
- If multiple accounts: use `op signin` to pick one, or `--account` / `OP_ACCOUNT`.
|
||||
- For non-integration auth, use `op account add`.
|
||||
@@ -0,0 +1,550 @@
|
||||
---
|
||||
name: "AgentDB Advanced Features"
|
||||
description: "Master advanced AgentDB features including QUIC synchronization, multi-database management, custom distance metrics, hybrid search, and distributed systems integration. Use when building distributed AI systems, multi-agent coordination, or advanced vector search applications."
|
||||
---
|
||||
|
||||
# AgentDB Advanced Features
|
||||
|
||||
## What This Skill Does
|
||||
|
||||
Covers advanced AgentDB capabilities for distributed systems, multi-database coordination, custom distance metrics, hybrid search (vector + metadata), QUIC synchronization, and production deployment patterns. Enables building sophisticated AI systems with sub-millisecond cross-node communication and advanced search capabilities.
|
||||
|
||||
**Performance**: <1ms QUIC sync, hybrid search with filters, custom distance metrics.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- AgentDB v1.0.7+ (via agentic-flow)
|
||||
- Understanding of distributed systems (for QUIC sync)
|
||||
- Vector search fundamentals
|
||||
|
||||
---
|
||||
|
||||
## QUIC Synchronization
|
||||
|
||||
### What is QUIC Sync?
|
||||
|
||||
QUIC (Quick UDP Internet Connections) enables sub-millisecond latency synchronization between AgentDB instances across network boundaries with automatic retry, multiplexing, and encryption.
|
||||
|
||||
**Benefits**:
|
||||
- <1ms latency between nodes
|
||||
- Multiplexed streams (multiple operations simultaneously)
|
||||
- Built-in encryption (TLS 1.3)
|
||||
- Automatic retry and recovery
|
||||
- Event-based broadcasting
|
||||
|
||||
### Enable QUIC Sync
|
||||
|
||||
```typescript
|
||||
import { createAgentDBAdapter } from 'agentic-flow/reasoningbank';
|
||||
|
||||
// Initialize with QUIC synchronization
|
||||
const adapter = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/distributed.db',
|
||||
enableQUICSync: true,
|
||||
syncPort: 4433,
|
||||
syncPeers: [
|
||||
'192.168.1.10:4433',
|
||||
'192.168.1.11:4433',
|
||||
'192.168.1.12:4433',
|
||||
],
|
||||
});
|
||||
|
||||
// Patterns automatically sync across all peers
|
||||
await adapter.insertPattern({
|
||||
// ... pattern data
|
||||
});
|
||||
|
||||
// Available on all peers within ~1ms
|
||||
```
|
||||
|
||||
### QUIC Configuration
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
enableQUICSync: true,
|
||||
syncPort: 4433, // QUIC server port
|
||||
syncPeers: ['host1:4433'], // Peer addresses
|
||||
syncInterval: 1000, // Sync interval (ms)
|
||||
syncBatchSize: 100, // Patterns per batch
|
||||
maxRetries: 3, // Retry failed syncs
|
||||
compression: true, // Enable compression
|
||||
});
|
||||
```
|
||||
|
||||
### Multi-Node Deployment
|
||||
|
||||
```bash
|
||||
# Node 1 (192.168.1.10)
|
||||
AGENTDB_QUIC_SYNC=true \
|
||||
AGENTDB_QUIC_PORT=4433 \
|
||||
AGENTDB_QUIC_PEERS=192.168.1.11:4433,192.168.1.12:4433 \
|
||||
node server.js
|
||||
|
||||
# Node 2 (192.168.1.11)
|
||||
AGENTDB_QUIC_SYNC=true \
|
||||
AGENTDB_QUIC_PORT=4433 \
|
||||
AGENTDB_QUIC_PEERS=192.168.1.10:4433,192.168.1.12:4433 \
|
||||
node server.js
|
||||
|
||||
# Node 3 (192.168.1.12)
|
||||
AGENTDB_QUIC_SYNC=true \
|
||||
AGENTDB_QUIC_PORT=4433 \
|
||||
AGENTDB_QUIC_PEERS=192.168.1.10:4433,192.168.1.11:4433 \
|
||||
node server.js
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Distance Metrics
|
||||
|
||||
### Cosine Similarity (Default)
|
||||
|
||||
Best for normalized vectors, semantic similarity:
|
||||
|
||||
```bash
|
||||
# CLI
|
||||
npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m cosine
|
||||
|
||||
# API
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
metric: 'cosine',
|
||||
k: 10,
|
||||
});
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- Text embeddings (BERT, GPT, etc.)
|
||||
- Semantic search
|
||||
- Document similarity
|
||||
- Most general-purpose applications
|
||||
|
||||
**Formula**: `cos(θ) = (A · B) / (||A|| × ||B||)`
|
||||
**Range**: [-1, 1] (1 = identical, -1 = opposite)
|
||||
|
||||
### Euclidean Distance (L2)
|
||||
|
||||
Best for spatial data, geometric similarity:
|
||||
|
||||
```bash
|
||||
# CLI
|
||||
npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m euclidean
|
||||
|
||||
# API
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
metric: 'euclidean',
|
||||
k: 10,
|
||||
});
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- Image embeddings
|
||||
- Spatial data
|
||||
- Computer vision
|
||||
- When vector magnitude matters
|
||||
|
||||
**Formula**: `d = √(Σ(ai - bi)²)`
|
||||
**Range**: [0, ∞] (0 = identical, ∞ = very different)
|
||||
|
||||
### Dot Product
|
||||
|
||||
Best for pre-normalized vectors, fast computation:
|
||||
|
||||
```bash
|
||||
# CLI
|
||||
npx agentdb@latest query ./vectors.db "[0.1,0.2,...]" -m dot
|
||||
|
||||
# API
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
metric: 'dot',
|
||||
k: 10,
|
||||
});
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- Pre-normalized embeddings
|
||||
- Fast similarity computation
|
||||
- When vectors are already unit-length
|
||||
|
||||
**Formula**: `dot = Σ(ai × bi)`
|
||||
**Range**: [-∞, ∞] (higher = more similar)
|
||||
|
||||
### Custom Distance Metrics
|
||||
|
||||
```typescript
|
||||
// Implement custom distance function
|
||||
function customDistance(vec1: number[], vec2: number[]): number {
|
||||
// Weighted Euclidean distance
|
||||
const weights = [1.0, 2.0, 1.5, ...];
|
||||
let sum = 0;
|
||||
for (let i = 0; i < vec1.length; i++) {
|
||||
sum += weights[i] * Math.pow(vec1[i] - vec2[i], 2);
|
||||
}
|
||||
return Math.sqrt(sum);
|
||||
}
|
||||
|
||||
// Use in search (requires custom implementation)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Hybrid Search (Vector + Metadata)
|
||||
|
||||
### Basic Hybrid Search
|
||||
|
||||
Combine vector similarity with metadata filtering:
|
||||
|
||||
```typescript
|
||||
// Store documents with metadata
|
||||
await adapter.insertPattern({
|
||||
id: '',
|
||||
type: 'document',
|
||||
domain: 'research-papers',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding: documentEmbedding,
|
||||
text: documentText,
|
||||
metadata: {
|
||||
author: 'Jane Smith',
|
||||
year: 2025,
|
||||
category: 'machine-learning',
|
||||
citations: 150,
|
||||
}
|
||||
}),
|
||||
confidence: 1.0,
|
||||
usage_count: 0,
|
||||
success_count: 0,
|
||||
created_at: Date.now(),
|
||||
last_used: Date.now(),
|
||||
});
|
||||
|
||||
// Hybrid search: vector similarity + metadata filters
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'research-papers',
|
||||
k: 20,
|
||||
filters: {
|
||||
year: { $gte: 2023 }, // Published 2023 or later
|
||||
category: 'machine-learning', // ML papers only
|
||||
citations: { $gte: 50 }, // Highly cited
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Advanced Filtering
|
||||
|
||||
```typescript
|
||||
// Complex metadata queries
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'products',
|
||||
k: 50,
|
||||
filters: {
|
||||
price: { $gte: 10, $lte: 100 }, // Price range
|
||||
category: { $in: ['electronics', 'gadgets'] }, // Multiple categories
|
||||
rating: { $gte: 4.0 }, // High rated
|
||||
inStock: true, // Available
|
||||
tags: { $contains: 'wireless' }, // Has tag
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Weighted Hybrid Search
|
||||
|
||||
Combine vector and metadata scores:
|
||||
|
||||
```typescript
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'content',
|
||||
k: 20,
|
||||
hybridWeights: {
|
||||
vectorSimilarity: 0.7, // 70% weight on semantic similarity
|
||||
metadataScore: 0.3, // 30% weight on metadata match
|
||||
},
|
||||
filters: {
|
||||
category: 'technology',
|
||||
recency: { $gte: Date.now() - 30 * 24 * 3600000 }, // Last 30 days
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Multi-Database Management
|
||||
|
||||
### Multiple Databases
|
||||
|
||||
```typescript
|
||||
// Separate databases for different domains
|
||||
const knowledgeDB = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/knowledge.db',
|
||||
});
|
||||
|
||||
const conversationDB = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/conversations.db',
|
||||
});
|
||||
|
||||
const codeDB = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/code.db',
|
||||
});
|
||||
|
||||
// Use appropriate database for each task
|
||||
await knowledgeDB.insertPattern({ /* knowledge */ });
|
||||
await conversationDB.insertPattern({ /* conversation */ });
|
||||
await codeDB.insertPattern({ /* code */ });
|
||||
```
|
||||
|
||||
### Database Sharding
|
||||
|
||||
```typescript
|
||||
// Shard by domain for horizontal scaling
|
||||
const shards = {
|
||||
'domain-a': await createAgentDBAdapter({ dbPath: '.agentdb/shard-a.db' }),
|
||||
'domain-b': await createAgentDBAdapter({ dbPath: '.agentdb/shard-b.db' }),
|
||||
'domain-c': await createAgentDBAdapter({ dbPath: '.agentdb/shard-c.db' }),
|
||||
};
|
||||
|
||||
// Route queries to appropriate shard
|
||||
function getDBForDomain(domain: string) {
|
||||
const shardKey = domain.split('-')[0]; // Extract shard key
|
||||
return shards[shardKey] || shards['domain-a'];
|
||||
}
|
||||
|
||||
// Insert to correct shard
|
||||
const db = getDBForDomain('domain-a-task');
|
||||
await db.insertPattern({ /* ... */ });
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MMR (Maximal Marginal Relevance)
|
||||
|
||||
Retrieve diverse results to avoid redundancy:
|
||||
|
||||
```typescript
|
||||
// Without MMR: Similar results may be redundant
|
||||
const standardResults = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
k: 10,
|
||||
useMMR: false,
|
||||
});
|
||||
|
||||
// With MMR: Diverse, non-redundant results
|
||||
const diverseResults = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
k: 10,
|
||||
useMMR: true,
|
||||
mmrLambda: 0.5, // Balance relevance (0) vs diversity (1)
|
||||
});
|
||||
```
|
||||
|
||||
**MMR Parameters**:
|
||||
- `mmrLambda = 0`: Maximum relevance (may be redundant)
|
||||
- `mmrLambda = 0.5`: Balanced (default)
|
||||
- `mmrLambda = 1`: Maximum diversity (may be less relevant)
|
||||
|
||||
**Use Cases**:
|
||||
- Search result diversification
|
||||
- Recommendation systems
|
||||
- Avoiding echo chambers
|
||||
- Exploratory search
|
||||
|
||||
---
|
||||
|
||||
## Context Synthesis
|
||||
|
||||
Generate rich context from multiple memories:
|
||||
|
||||
```typescript
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'problem-solving',
|
||||
k: 10,
|
||||
synthesizeContext: true, // Enable context synthesis
|
||||
});
|
||||
|
||||
// ContextSynthesizer creates coherent narrative
|
||||
console.log('Synthesized Context:', result.context);
|
||||
// "Based on 10 similar problem-solving attempts, the most effective
|
||||
// approach involves: 1) analyzing root cause, 2) brainstorming solutions,
|
||||
// 3) evaluating trade-offs, 4) implementing incrementally. Success rate: 85%"
|
||||
|
||||
console.log('Patterns:', result.patterns);
|
||||
// Extracted common patterns across memories
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Production Patterns
|
||||
|
||||
### Connection Pooling
|
||||
|
||||
```typescript
|
||||
// Singleton pattern for shared adapter
|
||||
class AgentDBPool {
|
||||
private static instance: AgentDBAdapter;
|
||||
|
||||
static async getInstance() {
|
||||
if (!this.instance) {
|
||||
this.instance = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/production.db',
|
||||
quantizationType: 'scalar',
|
||||
cacheSize: 2000,
|
||||
});
|
||||
}
|
||||
return this.instance;
|
||||
}
|
||||
}
|
||||
|
||||
// Use in application
|
||||
const db = await AgentDBPool.getInstance();
|
||||
const results = await db.retrieveWithReasoning(queryEmbedding, { k: 10 });
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```typescript
|
||||
async function safeRetrieve(queryEmbedding: number[], options: any) {
|
||||
try {
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, options);
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (error.code === 'DIMENSION_MISMATCH') {
|
||||
console.error('Query embedding dimension mismatch');
|
||||
// Handle dimension error
|
||||
} else if (error.code === 'DATABASE_LOCKED') {
|
||||
// Retry with exponential backoff
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
return safeRetrieve(queryEmbedding, options);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Monitoring and Logging
|
||||
|
||||
```typescript
|
||||
// Performance monitoring
|
||||
const startTime = Date.now();
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, { k: 10 });
|
||||
const latency = Date.now() - startTime;
|
||||
|
||||
if (latency > 100) {
|
||||
console.warn('Slow query detected:', latency, 'ms');
|
||||
}
|
||||
|
||||
// Log statistics
|
||||
const stats = await adapter.getStats();
|
||||
console.log('Database Stats:', {
|
||||
totalPatterns: stats.totalPatterns,
|
||||
dbSize: stats.dbSize,
|
||||
cacheHitRate: stats.cacheHitRate,
|
||||
avgSearchLatency: stats.avgSearchLatency,
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CLI Advanced Operations
|
||||
|
||||
### Database Import/Export
|
||||
|
||||
```bash
|
||||
# Export with compression
|
||||
npx agentdb@latest export ./vectors.db ./backup.json.gz --compress
|
||||
|
||||
# Import from backup
|
||||
npx agentdb@latest import ./backup.json.gz --decompress
|
||||
|
||||
# Merge databases
|
||||
npx agentdb@latest merge ./db1.sqlite ./db2.sqlite ./merged.sqlite
|
||||
```
|
||||
|
||||
### Database Optimization
|
||||
|
||||
```bash
|
||||
# Vacuum database (reclaim space)
|
||||
sqlite3 .agentdb/vectors.db "VACUUM;"
|
||||
|
||||
# Analyze for query optimization
|
||||
sqlite3 .agentdb/vectors.db "ANALYZE;"
|
||||
|
||||
# Rebuild indices
|
||||
npx agentdb@latest reindex ./vectors.db
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```bash
|
||||
# AgentDB configuration
|
||||
AGENTDB_PATH=.agentdb/reasoningbank.db
|
||||
AGENTDB_ENABLED=true
|
||||
|
||||
# Performance tuning
|
||||
AGENTDB_QUANTIZATION=binary # binary|scalar|product|none
|
||||
AGENTDB_CACHE_SIZE=2000
|
||||
AGENTDB_HNSW_M=16
|
||||
AGENTDB_HNSW_EF=100
|
||||
|
||||
# Learning plugins
|
||||
AGENTDB_LEARNING=true
|
||||
|
||||
# Reasoning agents
|
||||
AGENTDB_REASONING=true
|
||||
|
||||
# QUIC synchronization
|
||||
AGENTDB_QUIC_SYNC=true
|
||||
AGENTDB_QUIC_PORT=4433
|
||||
AGENTDB_QUIC_PEERS=host1:4433,host2:4433
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Issue: QUIC sync not working
|
||||
|
||||
```bash
|
||||
# Check firewall allows UDP port 4433
|
||||
sudo ufw allow 4433/udp
|
||||
|
||||
# Verify peers are reachable
|
||||
ping host1
|
||||
|
||||
# Check QUIC logs
|
||||
DEBUG=agentdb:quic node server.js
|
||||
```
|
||||
|
||||
### Issue: Hybrid search returns no results
|
||||
|
||||
```typescript
|
||||
// Relax filters
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
k: 100, // Increase k
|
||||
filters: {
|
||||
// Remove or relax filters
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### Issue: Memory consolidation too aggressive
|
||||
|
||||
```typescript
|
||||
// Disable automatic optimization
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
optimizeMemory: false, // Disable auto-consolidation
|
||||
k: 10,
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Learn More
|
||||
|
||||
- **QUIC Protocol**: docs/quic-synchronization.pdf
|
||||
- **Hybrid Search**: docs/hybrid-search-guide.md
|
||||
- **GitHub**: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb
|
||||
- **Website**: https://agentdb.ruv.io
|
||||
|
||||
---
|
||||
|
||||
**Category**: Advanced / Distributed Systems
|
||||
**Difficulty**: Advanced
|
||||
**Estimated Time**: 45-60 minutes
|
||||
@@ -0,0 +1,545 @@
|
||||
---
|
||||
name: "AgentDB Learning Plugins"
|
||||
description: "Create and train AI learning plugins with AgentDB's 9 reinforcement learning algorithms. Includes Decision Transformer, Q-Learning, SARSA, Actor-Critic, and more. Use when building self-learning agents, implementing RL, or optimizing agent behavior through experience."
|
||||
---
|
||||
|
||||
# AgentDB Learning Plugins
|
||||
|
||||
## What This Skill Does
|
||||
|
||||
Provides access to 9 reinforcement learning algorithms via AgentDB's plugin system. Create, train, and deploy learning plugins for autonomous agents that improve through experience. Includes offline RL (Decision Transformer), value-based learning (Q-Learning), policy gradients (Actor-Critic), and advanced techniques.
|
||||
|
||||
**Performance**: Train models 10-100x faster with WASM-accelerated neural inference.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- AgentDB v1.0.7+ (via agentic-flow)
|
||||
- Basic understanding of reinforcement learning (recommended)
|
||||
|
||||
---
|
||||
|
||||
## Quick Start with CLI
|
||||
|
||||
### Create Learning Plugin
|
||||
|
||||
```bash
|
||||
# Interactive wizard
|
||||
npx agentdb@latest create-plugin
|
||||
|
||||
# Use specific template
|
||||
npx agentdb@latest create-plugin -t decision-transformer -n my-agent
|
||||
|
||||
# Preview without creating
|
||||
npx agentdb@latest create-plugin -t q-learning --dry-run
|
||||
|
||||
# Custom output directory
|
||||
npx agentdb@latest create-plugin -t actor-critic -o ./plugins
|
||||
```
|
||||
|
||||
### List Available Templates
|
||||
|
||||
```bash
|
||||
# Show all plugin templates
|
||||
npx agentdb@latest list-templates
|
||||
|
||||
# Available templates:
|
||||
# - decision-transformer (sequence modeling RL - recommended)
|
||||
# - q-learning (value-based learning)
|
||||
# - sarsa (on-policy TD learning)
|
||||
# - actor-critic (policy gradient with baseline)
|
||||
# - curiosity-driven (exploration-based)
|
||||
```
|
||||
|
||||
### Manage Plugins
|
||||
|
||||
```bash
|
||||
# List installed plugins
|
||||
npx agentdb@latest list-plugins
|
||||
|
||||
# Get plugin information
|
||||
npx agentdb@latest plugin-info my-agent
|
||||
|
||||
# Shows: algorithm, configuration, training status
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Start with API
|
||||
|
||||
```typescript
|
||||
import { createAgentDBAdapter } from 'agentic-flow/reasoningbank';
|
||||
|
||||
// Initialize with learning enabled
|
||||
const adapter = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/learning.db',
|
||||
enableLearning: true, // Enable learning plugins
|
||||
enableReasoning: true,
|
||||
cacheSize: 1000,
|
||||
});
|
||||
|
||||
// Store training experience
|
||||
await adapter.insertPattern({
|
||||
id: '',
|
||||
type: 'experience',
|
||||
domain: 'game-playing',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding: await computeEmbedding('state-action-reward'),
|
||||
pattern: {
|
||||
state: [0.1, 0.2, 0.3],
|
||||
action: 2,
|
||||
reward: 1.0,
|
||||
next_state: [0.15, 0.25, 0.35],
|
||||
done: false
|
||||
}
|
||||
}),
|
||||
confidence: 0.9,
|
||||
usage_count: 1,
|
||||
success_count: 1,
|
||||
created_at: Date.now(),
|
||||
last_used: Date.now(),
|
||||
});
|
||||
|
||||
// Train learning model
|
||||
const metrics = await adapter.train({
|
||||
epochs: 50,
|
||||
batchSize: 32,
|
||||
});
|
||||
|
||||
console.log('Training Loss:', metrics.loss);
|
||||
console.log('Duration:', metrics.duration, 'ms');
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Available Learning Algorithms (9 Total)
|
||||
|
||||
### 1. Decision Transformer (Recommended)
|
||||
|
||||
**Type**: Offline Reinforcement Learning
|
||||
**Best For**: Learning from logged experiences, imitation learning
|
||||
**Strengths**: No online interaction needed, stable training
|
||||
|
||||
```bash
|
||||
npx agentdb@latest create-plugin -t decision-transformer -n dt-agent
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- Learn from historical data
|
||||
- Imitation learning from expert demonstrations
|
||||
- Safe learning without environment interaction
|
||||
- Sequence modeling tasks
|
||||
|
||||
**Configuration**:
|
||||
```json
|
||||
{
|
||||
"algorithm": "decision-transformer",
|
||||
"model_size": "base",
|
||||
"context_length": 20,
|
||||
"embed_dim": 128,
|
||||
"n_heads": 8,
|
||||
"n_layers": 6
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Q-Learning
|
||||
|
||||
**Type**: Value-Based RL (Off-Policy)
|
||||
**Best For**: Discrete action spaces, sample efficiency
|
||||
**Strengths**: Proven, simple, works well for small/medium problems
|
||||
|
||||
```bash
|
||||
npx agentdb@latest create-plugin -t q-learning -n q-agent
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- Grid worlds, board games
|
||||
- Navigation tasks
|
||||
- Resource allocation
|
||||
- Discrete decision-making
|
||||
|
||||
**Configuration**:
|
||||
```json
|
||||
{
|
||||
"algorithm": "q-learning",
|
||||
"learning_rate": 0.001,
|
||||
"gamma": 0.99,
|
||||
"epsilon": 0.1,
|
||||
"epsilon_decay": 0.995
|
||||
}
|
||||
```
|
||||
|
||||
### 3. SARSA
|
||||
|
||||
**Type**: Value-Based RL (On-Policy)
|
||||
**Best For**: Safe exploration, risk-sensitive tasks
|
||||
**Strengths**: More conservative than Q-Learning, better for safety
|
||||
|
||||
```bash
|
||||
npx agentdb@latest create-plugin -t sarsa -n sarsa-agent
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- Safety-critical applications
|
||||
- Risk-sensitive decision-making
|
||||
- Online learning with exploration
|
||||
|
||||
**Configuration**:
|
||||
```json
|
||||
{
|
||||
"algorithm": "sarsa",
|
||||
"learning_rate": 0.001,
|
||||
"gamma": 0.99,
|
||||
"epsilon": 0.1
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Actor-Critic
|
||||
|
||||
**Type**: Policy Gradient with Value Baseline
|
||||
**Best For**: Continuous actions, variance reduction
|
||||
**Strengths**: Stable, works for continuous/discrete actions
|
||||
|
||||
```bash
|
||||
npx agentdb@latest create-plugin -t actor-critic -n ac-agent
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- Continuous control (robotics, simulations)
|
||||
- Complex action spaces
|
||||
- Multi-agent coordination
|
||||
|
||||
**Configuration**:
|
||||
```json
|
||||
{
|
||||
"algorithm": "actor-critic",
|
||||
"actor_lr": 0.001,
|
||||
"critic_lr": 0.002,
|
||||
"gamma": 0.99,
|
||||
"entropy_coef": 0.01
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Active Learning
|
||||
|
||||
**Type**: Query-Based Learning
|
||||
**Best For**: Label-efficient learning, human-in-the-loop
|
||||
**Strengths**: Minimizes labeling cost, focuses on uncertain samples
|
||||
|
||||
**Use Cases**:
|
||||
- Human feedback incorporation
|
||||
- Label-efficient training
|
||||
- Uncertainty sampling
|
||||
- Annotation cost reduction
|
||||
|
||||
### 6. Adversarial Training
|
||||
|
||||
**Type**: Robustness Enhancement
|
||||
**Best For**: Safety, robustness to perturbations
|
||||
**Strengths**: Improves model robustness, adversarial defense
|
||||
|
||||
**Use Cases**:
|
||||
- Security applications
|
||||
- Robust decision-making
|
||||
- Adversarial defense
|
||||
- Safety testing
|
||||
|
||||
### 7. Curriculum Learning
|
||||
|
||||
**Type**: Progressive Difficulty Training
|
||||
**Best For**: Complex tasks, faster convergence
|
||||
**Strengths**: Stable learning, faster convergence on hard tasks
|
||||
|
||||
**Use Cases**:
|
||||
- Complex multi-stage tasks
|
||||
- Hard exploration problems
|
||||
- Skill composition
|
||||
- Transfer learning
|
||||
|
||||
### 8. Federated Learning
|
||||
|
||||
**Type**: Distributed Learning
|
||||
**Best For**: Privacy, distributed data
|
||||
**Strengths**: Privacy-preserving, scalable
|
||||
|
||||
**Use Cases**:
|
||||
- Multi-agent systems
|
||||
- Privacy-sensitive data
|
||||
- Distributed training
|
||||
- Collaborative learning
|
||||
|
||||
### 9. Multi-Task Learning
|
||||
|
||||
**Type**: Transfer Learning
|
||||
**Best For**: Related tasks, knowledge sharing
|
||||
**Strengths**: Faster learning on new tasks, better generalization
|
||||
|
||||
**Use Cases**:
|
||||
- Task families
|
||||
- Transfer learning
|
||||
- Domain adaptation
|
||||
- Meta-learning
|
||||
|
||||
---
|
||||
|
||||
## Training Workflow
|
||||
|
||||
### 1. Collect Experiences
|
||||
|
||||
```typescript
|
||||
// Store experiences during agent execution
|
||||
for (let i = 0; i < numEpisodes; i++) {
|
||||
const episode = runEpisode();
|
||||
|
||||
for (const step of episode.steps) {
|
||||
await adapter.insertPattern({
|
||||
id: '',
|
||||
type: 'experience',
|
||||
domain: 'task-domain',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding: await computeEmbedding(JSON.stringify(step)),
|
||||
pattern: {
|
||||
state: step.state,
|
||||
action: step.action,
|
||||
reward: step.reward,
|
||||
next_state: step.next_state,
|
||||
done: step.done
|
||||
}
|
||||
}),
|
||||
confidence: step.reward > 0 ? 0.9 : 0.5,
|
||||
usage_count: 1,
|
||||
success_count: step.reward > 0 ? 1 : 0,
|
||||
created_at: Date.now(),
|
||||
last_used: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Train Model
|
||||
|
||||
```typescript
|
||||
// Train on collected experiences
|
||||
const trainingMetrics = await adapter.train({
|
||||
epochs: 100,
|
||||
batchSize: 64,
|
||||
learningRate: 0.001,
|
||||
validationSplit: 0.2,
|
||||
});
|
||||
|
||||
console.log('Training Metrics:', trainingMetrics);
|
||||
// {
|
||||
// loss: 0.023,
|
||||
// valLoss: 0.028,
|
||||
// duration: 1523,
|
||||
// epochs: 100
|
||||
// }
|
||||
```
|
||||
|
||||
### 3. Evaluate Performance
|
||||
|
||||
```typescript
|
||||
// Retrieve similar successful experiences
|
||||
const testQuery = await computeEmbedding(JSON.stringify(testState));
|
||||
const result = await adapter.retrieveWithReasoning(testQuery, {
|
||||
domain: 'task-domain',
|
||||
k: 10,
|
||||
synthesizeContext: true,
|
||||
});
|
||||
|
||||
// Evaluate action quality
|
||||
const suggestedAction = result.memories[0].pattern.action;
|
||||
const confidence = result.memories[0].similarity;
|
||||
|
||||
console.log('Suggested Action:', suggestedAction);
|
||||
console.log('Confidence:', confidence);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Advanced Training Techniques
|
||||
|
||||
### Experience Replay
|
||||
|
||||
```typescript
|
||||
// Store experiences in buffer
|
||||
const replayBuffer = [];
|
||||
|
||||
// Sample random batch for training
|
||||
const batch = sampleRandomBatch(replayBuffer, batchSize: 32);
|
||||
|
||||
// Train on batch
|
||||
await adapter.train({
|
||||
data: batch,
|
||||
epochs: 1,
|
||||
batchSize: 32,
|
||||
});
|
||||
```
|
||||
|
||||
### Prioritized Experience Replay
|
||||
|
||||
```typescript
|
||||
// Store experiences with priority (TD error)
|
||||
await adapter.insertPattern({
|
||||
// ... standard fields
|
||||
confidence: tdError, // Use TD error as confidence/priority
|
||||
// ...
|
||||
});
|
||||
|
||||
// Retrieve high-priority experiences
|
||||
const highPriority = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'task-domain',
|
||||
k: 32,
|
||||
minConfidence: 0.7, // Only high TD-error experiences
|
||||
});
|
||||
```
|
||||
|
||||
### Multi-Agent Training
|
||||
|
||||
```typescript
|
||||
// Collect experiences from multiple agents
|
||||
for (const agent of agents) {
|
||||
const experience = await agent.step();
|
||||
|
||||
await adapter.insertPattern({
|
||||
// ... store experience with agent ID
|
||||
domain: `multi-agent/${agent.id}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Train shared model
|
||||
await adapter.train({
|
||||
epochs: 50,
|
||||
batchSize: 64,
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Batch Training
|
||||
|
||||
```typescript
|
||||
// Collect batch of experiences
|
||||
const experiences = collectBatch(size: 1000);
|
||||
|
||||
// Batch insert (500x faster)
|
||||
for (const exp of experiences) {
|
||||
await adapter.insertPattern({ /* ... */ });
|
||||
}
|
||||
|
||||
// Train on batch
|
||||
await adapter.train({
|
||||
epochs: 10,
|
||||
batchSize: 128, // Larger batch for efficiency
|
||||
});
|
||||
```
|
||||
|
||||
### Incremental Learning
|
||||
|
||||
```typescript
|
||||
// Train incrementally as new data arrives
|
||||
setInterval(async () => {
|
||||
const newExperiences = getNewExperiences();
|
||||
|
||||
if (newExperiences.length > 100) {
|
||||
await adapter.train({
|
||||
epochs: 5,
|
||||
batchSize: 32,
|
||||
});
|
||||
}
|
||||
}, 60000); // Every minute
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration with Reasoning Agents
|
||||
|
||||
Combine learning with reasoning for better performance:
|
||||
|
||||
```typescript
|
||||
// Train learning model
|
||||
await adapter.train({ epochs: 50, batchSize: 32 });
|
||||
|
||||
// Use reasoning agents for inference
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'decision-making',
|
||||
k: 10,
|
||||
useMMR: true, // Diverse experiences
|
||||
synthesizeContext: true, // Rich context
|
||||
optimizeMemory: true, // Consolidate patterns
|
||||
});
|
||||
|
||||
// Make decision based on learned experiences + reasoning
|
||||
const decision = result.context.suggestedAction;
|
||||
const confidence = result.memories[0].similarity;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CLI Operations
|
||||
|
||||
```bash
|
||||
# Create plugin
|
||||
npx agentdb@latest create-plugin -t decision-transformer -n my-plugin
|
||||
|
||||
# List plugins
|
||||
npx agentdb@latest list-plugins
|
||||
|
||||
# Get plugin info
|
||||
npx agentdb@latest plugin-info my-plugin
|
||||
|
||||
# List templates
|
||||
npx agentdb@latest list-templates
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Issue: Training not converging
|
||||
```typescript
|
||||
// Reduce learning rate
|
||||
await adapter.train({
|
||||
epochs: 100,
|
||||
batchSize: 32,
|
||||
learningRate: 0.0001, // Lower learning rate
|
||||
});
|
||||
```
|
||||
|
||||
### Issue: Overfitting
|
||||
```typescript
|
||||
// Use validation split
|
||||
await adapter.train({
|
||||
epochs: 50,
|
||||
batchSize: 64,
|
||||
validationSplit: 0.2, // 20% validation
|
||||
});
|
||||
|
||||
// Enable memory optimization
|
||||
await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
optimizeMemory: true, // Consolidate, reduce overfitting
|
||||
});
|
||||
```
|
||||
|
||||
### Issue: Slow training
|
||||
```bash
|
||||
# Enable quantization for faster inference
|
||||
# Use binary quantization (32x faster)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Learn More
|
||||
|
||||
- **Algorithm Papers**: See docs/algorithms/ for detailed papers
|
||||
- **GitHub**: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb
|
||||
- **MCP Integration**: `npx agentdb@latest mcp`
|
||||
- **Website**: https://agentdb.ruv.io
|
||||
|
||||
---
|
||||
|
||||
**Category**: Machine Learning / Reinforcement Learning
|
||||
**Difficulty**: Intermediate to Advanced
|
||||
**Estimated Time**: 30-60 minutes
|
||||
@@ -0,0 +1,339 @@
|
||||
---
|
||||
name: "AgentDB Memory Patterns"
|
||||
description: "Implement persistent memory patterns for AI agents using AgentDB. Includes session memory, long-term storage, pattern learning, and context management. Use when building stateful agents, chat systems, or intelligent assistants."
|
||||
---
|
||||
|
||||
# AgentDB Memory Patterns
|
||||
|
||||
## What This Skill Does
|
||||
|
||||
Provides memory management patterns for AI agents using AgentDB's persistent storage and ReasoningBank integration. Enables agents to remember conversations, learn from interactions, and maintain context across sessions.
|
||||
|
||||
**Performance**: 150x-12,500x faster than traditional solutions with 100% backward compatibility.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- AgentDB v1.0.7+ (via agentic-flow or standalone)
|
||||
- Understanding of agent architectures
|
||||
|
||||
## Quick Start with CLI
|
||||
|
||||
### Initialize AgentDB
|
||||
|
||||
```bash
|
||||
# Initialize vector database
|
||||
npx agentdb@latest init ./agents.db
|
||||
|
||||
# Or with custom dimensions
|
||||
npx agentdb@latest init ./agents.db --dimension 768
|
||||
|
||||
# Use preset configurations
|
||||
npx agentdb@latest init ./agents.db --preset large
|
||||
|
||||
# In-memory database for testing
|
||||
npx agentdb@latest init ./memory.db --in-memory
|
||||
```
|
||||
|
||||
### Start MCP Server for Claude Code
|
||||
|
||||
```bash
|
||||
# Start MCP server (integrates with Claude Code)
|
||||
npx agentdb@latest mcp
|
||||
|
||||
# Add to Claude Code (one-time setup)
|
||||
claude mcp add agentdb npx agentdb@latest mcp
|
||||
```
|
||||
|
||||
### Create Learning Plugin
|
||||
|
||||
```bash
|
||||
# Interactive plugin wizard
|
||||
npx agentdb@latest create-plugin
|
||||
|
||||
# Use template directly
|
||||
npx agentdb@latest create-plugin -t decision-transformer -n my-agent
|
||||
|
||||
# Available templates:
|
||||
# - decision-transformer (sequence modeling RL)
|
||||
# - q-learning (value-based learning)
|
||||
# - sarsa (on-policy TD learning)
|
||||
# - actor-critic (policy gradient)
|
||||
# - curiosity-driven (exploration-based)
|
||||
```
|
||||
|
||||
## Quick Start with API
|
||||
|
||||
```typescript
|
||||
import { createAgentDBAdapter } from 'agentic-flow/reasoningbank';
|
||||
|
||||
// Initialize with default configuration
|
||||
const adapter = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/reasoningbank.db',
|
||||
enableLearning: true, // Enable learning plugins
|
||||
enableReasoning: true, // Enable reasoning agents
|
||||
quantizationType: 'scalar', // binary | scalar | product | none
|
||||
cacheSize: 1000, // In-memory cache
|
||||
});
|
||||
|
||||
// Store interaction memory
|
||||
const patternId = await adapter.insertPattern({
|
||||
id: '',
|
||||
type: 'pattern',
|
||||
domain: 'conversation',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding: await computeEmbedding('What is the capital of France?'),
|
||||
pattern: {
|
||||
user: 'What is the capital of France?',
|
||||
assistant: 'The capital of France is Paris.',
|
||||
timestamp: Date.now()
|
||||
}
|
||||
}),
|
||||
confidence: 0.95,
|
||||
usage_count: 1,
|
||||
success_count: 1,
|
||||
created_at: Date.now(),
|
||||
last_used: Date.now(),
|
||||
});
|
||||
|
||||
// Retrieve context with reasoning
|
||||
const context = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'conversation',
|
||||
k: 10,
|
||||
useMMR: true, // Maximal Marginal Relevance
|
||||
synthesizeContext: true, // Generate rich context
|
||||
});
|
||||
```
|
||||
|
||||
## Memory Patterns
|
||||
|
||||
### 1. Session Memory
|
||||
```typescript
|
||||
class SessionMemory {
|
||||
async storeMessage(role: string, content: string) {
|
||||
return await db.storeMemory({
|
||||
sessionId: this.sessionId,
|
||||
role,
|
||||
content,
|
||||
timestamp: Date.now()
|
||||
});
|
||||
}
|
||||
|
||||
async getSessionHistory(limit = 20) {
|
||||
return await db.query({
|
||||
filters: { sessionId: this.sessionId },
|
||||
orderBy: 'timestamp',
|
||||
limit
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Long-Term Memory
|
||||
```typescript
|
||||
// Store important facts
|
||||
await db.storeFact({
|
||||
category: 'user_preference',
|
||||
key: 'language',
|
||||
value: 'English',
|
||||
confidence: 1.0,
|
||||
source: 'explicit'
|
||||
});
|
||||
|
||||
// Retrieve facts
|
||||
const prefs = await db.getFacts({
|
||||
category: 'user_preference'
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Pattern Learning
|
||||
```typescript
|
||||
// Learn from successful interactions
|
||||
await db.storePattern({
|
||||
trigger: 'user_asks_time',
|
||||
response: 'provide_formatted_time',
|
||||
success: true,
|
||||
context: { timezone: 'UTC' }
|
||||
});
|
||||
|
||||
// Apply learned patterns
|
||||
const pattern = await db.matchPattern(currentContext);
|
||||
```
|
||||
|
||||
## Advanced Patterns
|
||||
|
||||
### Hierarchical Memory
|
||||
```typescript
|
||||
// Organize memory in hierarchy
|
||||
await memory.organize({
|
||||
immediate: recentMessages, // Last 10 messages
|
||||
shortTerm: sessionContext, // Current session
|
||||
longTerm: importantFacts, // Persistent facts
|
||||
semantic: embeddedKnowledge // Vector search
|
||||
});
|
||||
```
|
||||
|
||||
### Memory Consolidation
|
||||
```typescript
|
||||
// Periodically consolidate memories
|
||||
await memory.consolidate({
|
||||
strategy: 'importance', // Keep important memories
|
||||
maxSize: 10000, // Size limit
|
||||
minScore: 0.5 // Relevance threshold
|
||||
});
|
||||
```
|
||||
|
||||
## CLI Operations
|
||||
|
||||
### Query Database
|
||||
|
||||
```bash
|
||||
# Query with vector embedding
|
||||
npx agentdb@latest query ./agents.db "[0.1,0.2,0.3,...]"
|
||||
|
||||
# Top-k results
|
||||
npx agentdb@latest query ./agents.db "[0.1,0.2,0.3]" -k 10
|
||||
|
||||
# With similarity threshold
|
||||
npx agentdb@latest query ./agents.db "0.1 0.2 0.3" -t 0.75
|
||||
|
||||
# JSON output
|
||||
npx agentdb@latest query ./agents.db "[...]" -f json
|
||||
```
|
||||
|
||||
### Import/Export Data
|
||||
|
||||
```bash
|
||||
# Export vectors to file
|
||||
npx agentdb@latest export ./agents.db ./backup.json
|
||||
|
||||
# Import vectors from file
|
||||
npx agentdb@latest import ./backup.json
|
||||
|
||||
# Get database statistics
|
||||
npx agentdb@latest stats ./agents.db
|
||||
```
|
||||
|
||||
### Performance Benchmarks
|
||||
|
||||
```bash
|
||||
# Run performance benchmarks
|
||||
npx agentdb@latest benchmark
|
||||
|
||||
# Results show:
|
||||
# - Pattern Search: 150x faster (100µs vs 15ms)
|
||||
# - Batch Insert: 500x faster (2ms vs 1s)
|
||||
# - Large-scale Query: 12,500x faster (8ms vs 100s)
|
||||
```
|
||||
|
||||
## Integration with ReasoningBank
|
||||
|
||||
```typescript
|
||||
import { createAgentDBAdapter, migrateToAgentDB } from 'agentic-flow/reasoningbank';
|
||||
|
||||
// Migrate from legacy ReasoningBank
|
||||
const result = await migrateToAgentDB(
|
||||
'.swarm/memory.db', // Source (legacy)
|
||||
'.agentdb/reasoningbank.db' // Destination (AgentDB)
|
||||
);
|
||||
|
||||
console.log(`✅ Migrated ${result.patternsMigrated} patterns`);
|
||||
|
||||
// Train learning model
|
||||
const adapter = await createAgentDBAdapter({
|
||||
enableLearning: true,
|
||||
});
|
||||
|
||||
await adapter.train({
|
||||
epochs: 50,
|
||||
batchSize: 32,
|
||||
});
|
||||
|
||||
// Get optimal strategy with reasoning
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'task-planning',
|
||||
synthesizeContext: true,
|
||||
optimizeMemory: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Learning Plugins
|
||||
|
||||
### Available Algorithms (9 Total)
|
||||
|
||||
1. **Decision Transformer** - Sequence modeling RL (recommended)
|
||||
2. **Q-Learning** - Value-based learning
|
||||
3. **SARSA** - On-policy TD learning
|
||||
4. **Actor-Critic** - Policy gradient with baseline
|
||||
5. **Active Learning** - Query selection
|
||||
6. **Adversarial Training** - Robustness
|
||||
7. **Curriculum Learning** - Progressive difficulty
|
||||
8. **Federated Learning** - Distributed learning
|
||||
9. **Multi-task Learning** - Transfer learning
|
||||
|
||||
### List and Manage Plugins
|
||||
|
||||
```bash
|
||||
# List available plugins
|
||||
npx agentdb@latest list-plugins
|
||||
|
||||
# List plugin templates
|
||||
npx agentdb@latest list-templates
|
||||
|
||||
# Get plugin info
|
||||
npx agentdb@latest plugin-info <name>
|
||||
```
|
||||
|
||||
## Reasoning Agents (4 Modules)
|
||||
|
||||
1. **PatternMatcher** - Find similar patterns with HNSW indexing
|
||||
2. **ContextSynthesizer** - Generate rich context from multiple sources
|
||||
3. **MemoryOptimizer** - Consolidate similar patterns, prune low-quality
|
||||
4. **ExperienceCurator** - Quality-based experience filtering
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Enable quantization**: Use scalar/binary for 4-32x memory reduction
|
||||
2. **Use caching**: 1000 pattern cache for <1ms retrieval
|
||||
3. **Batch operations**: 500x faster than individual inserts
|
||||
4. **Train regularly**: Update learning models with new experiences
|
||||
5. **Enable reasoning**: Automatic context synthesis and optimization
|
||||
6. **Monitor metrics**: Use `stats` command to track performance
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Issue: Memory growing too large
|
||||
```bash
|
||||
# Check database size
|
||||
npx agentdb@latest stats ./agents.db
|
||||
|
||||
# Enable quantization
|
||||
# Use 'binary' (32x smaller) or 'scalar' (4x smaller)
|
||||
```
|
||||
|
||||
### Issue: Slow search performance
|
||||
```bash
|
||||
# Enable HNSW indexing and caching
|
||||
# Results: <100µs search time
|
||||
```
|
||||
|
||||
### Issue: Migration from legacy ReasoningBank
|
||||
```bash
|
||||
# Automatic migration with validation
|
||||
npx agentdb@latest migrate --source .swarm/memory.db
|
||||
```
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
- **Vector Search**: <100µs (HNSW indexing)
|
||||
- **Pattern Retrieval**: <1ms (with cache)
|
||||
- **Batch Insert**: 2ms for 100 patterns
|
||||
- **Memory Efficiency**: 4-32x reduction with quantization
|
||||
- **Backward Compatibility**: 100% compatible with ReasoningBank API
|
||||
|
||||
## Learn More
|
||||
|
||||
- GitHub: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb
|
||||
- Documentation: node_modules/agentic-flow/docs/AGENTDB_INTEGRATION.md
|
||||
- MCP Integration: `npx agentdb@latest mcp` for Claude Code
|
||||
- Website: https://agentdb.ruv.io
|
||||
@@ -0,0 +1,509 @@
|
||||
---
|
||||
name: "AgentDB Performance Optimization"
|
||||
description: "Optimize AgentDB performance with quantization (4-32x memory reduction), HNSW indexing (150x faster search), caching, and batch operations. Use when optimizing memory usage, improving search speed, or scaling to millions of vectors."
|
||||
---
|
||||
|
||||
# AgentDB Performance Optimization
|
||||
|
||||
## What This Skill Does
|
||||
|
||||
Provides comprehensive performance optimization techniques for AgentDB vector databases. Achieve 150x-12,500x performance improvements through quantization, HNSW indexing, caching strategies, and batch operations. Reduce memory usage by 4-32x while maintaining accuracy.
|
||||
|
||||
**Performance**: <100µs vector search, <1ms pattern retrieval, 2ms batch insert for 100 vectors.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- AgentDB v1.0.7+ (via agentic-flow)
|
||||
- Existing AgentDB database or application
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Run Performance Benchmarks
|
||||
|
||||
```bash
|
||||
# Comprehensive performance benchmarking
|
||||
npx agentdb@latest benchmark
|
||||
|
||||
# Results show:
|
||||
# ✅ Pattern Search: 150x faster (100µs vs 15ms)
|
||||
# ✅ Batch Insert: 500x faster (2ms vs 1s for 100 vectors)
|
||||
# ✅ Large-scale Query: 12,500x faster (8ms vs 100s at 1M vectors)
|
||||
# ✅ Memory Efficiency: 4-32x reduction with quantization
|
||||
```
|
||||
|
||||
### Enable Optimizations
|
||||
|
||||
```typescript
|
||||
import { createAgentDBAdapter } from 'agentic-flow/reasoningbank';
|
||||
|
||||
// Optimized configuration
|
||||
const adapter = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/optimized.db',
|
||||
quantizationType: 'binary', // 32x memory reduction
|
||||
cacheSize: 1000, // In-memory cache
|
||||
enableLearning: true,
|
||||
enableReasoning: true,
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quantization Strategies
|
||||
|
||||
### 1. Binary Quantization (32x Reduction)
|
||||
|
||||
**Best For**: Large-scale deployments (1M+ vectors), memory-constrained environments
|
||||
**Trade-off**: ~2-5% accuracy loss, 32x memory reduction, 10x faster
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'binary',
|
||||
// 768-dim float32 (3072 bytes) → 96 bytes binary
|
||||
// 1M vectors: 3GB → 96MB
|
||||
});
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- Mobile/edge deployment
|
||||
- Large-scale vector storage (millions of vectors)
|
||||
- Real-time search with memory constraints
|
||||
|
||||
**Performance**:
|
||||
- Memory: 32x smaller
|
||||
- Search Speed: 10x faster (bit operations)
|
||||
- Accuracy: 95-98% of original
|
||||
|
||||
### 2. Scalar Quantization (4x Reduction)
|
||||
|
||||
**Best For**: Balanced performance/accuracy, moderate datasets
|
||||
**Trade-off**: ~1-2% accuracy loss, 4x memory reduction, 3x faster
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'scalar',
|
||||
// 768-dim float32 (3072 bytes) → 768 bytes (uint8)
|
||||
// 1M vectors: 3GB → 768MB
|
||||
});
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- Production applications requiring high accuracy
|
||||
- Medium-scale deployments (10K-1M vectors)
|
||||
- General-purpose optimization
|
||||
|
||||
**Performance**:
|
||||
- Memory: 4x smaller
|
||||
- Search Speed: 3x faster
|
||||
- Accuracy: 98-99% of original
|
||||
|
||||
### 3. Product Quantization (8-16x Reduction)
|
||||
|
||||
**Best For**: High-dimensional vectors, balanced compression
|
||||
**Trade-off**: ~3-7% accuracy loss, 8-16x memory reduction, 5x faster
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'product',
|
||||
// 768-dim float32 (3072 bytes) → 48-96 bytes
|
||||
// 1M vectors: 3GB → 192MB
|
||||
});
|
||||
```
|
||||
|
||||
**Use Cases**:
|
||||
- High-dimensional embeddings (>512 dims)
|
||||
- Image/video embeddings
|
||||
- Large-scale similarity search
|
||||
|
||||
**Performance**:
|
||||
- Memory: 8-16x smaller
|
||||
- Search Speed: 5x faster
|
||||
- Accuracy: 93-97% of original
|
||||
|
||||
### 4. No Quantization (Full Precision)
|
||||
|
||||
**Best For**: Maximum accuracy, small datasets
|
||||
**Trade-off**: No accuracy loss, full memory usage
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'none',
|
||||
// Full float32 precision
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## HNSW Indexing
|
||||
|
||||
**Hierarchical Navigable Small World** - O(log n) search complexity
|
||||
|
||||
### Automatic HNSW
|
||||
|
||||
AgentDB automatically builds HNSW indices:
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/vectors.db',
|
||||
// HNSW automatically enabled
|
||||
});
|
||||
|
||||
// Search with HNSW (100µs vs 15ms linear scan)
|
||||
const results = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
k: 10,
|
||||
});
|
||||
```
|
||||
|
||||
### HNSW Parameters
|
||||
|
||||
```typescript
|
||||
// Advanced HNSW configuration
|
||||
const adapter = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/vectors.db',
|
||||
hnswM: 16, // Connections per layer (default: 16)
|
||||
hnswEfConstruction: 200, // Build quality (default: 200)
|
||||
hnswEfSearch: 100, // Search quality (default: 100)
|
||||
});
|
||||
```
|
||||
|
||||
**Parameter Tuning**:
|
||||
- **M** (connections): Higher = better recall, more memory
|
||||
- Small datasets (<10K): M = 8
|
||||
- Medium datasets (10K-100K): M = 16
|
||||
- Large datasets (>100K): M = 32
|
||||
- **efConstruction**: Higher = better index quality, slower build
|
||||
- Fast build: 100
|
||||
- Balanced: 200 (default)
|
||||
- High quality: 400
|
||||
- **efSearch**: Higher = better recall, slower search
|
||||
- Fast search: 50
|
||||
- Balanced: 100 (default)
|
||||
- High recall: 200
|
||||
|
||||
---
|
||||
|
||||
## Caching Strategies
|
||||
|
||||
### In-Memory Pattern Cache
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
cacheSize: 1000, // Cache 1000 most-used patterns
|
||||
});
|
||||
|
||||
// First retrieval: ~2ms (database)
|
||||
// Subsequent: <1ms (cache hit)
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
k: 10,
|
||||
});
|
||||
```
|
||||
|
||||
**Cache Tuning**:
|
||||
- Small applications: 100-500 patterns
|
||||
- Medium applications: 500-2000 patterns
|
||||
- Large applications: 2000-5000 patterns
|
||||
|
||||
### LRU Cache Behavior
|
||||
|
||||
```typescript
|
||||
// Cache automatically evicts least-recently-used patterns
|
||||
// Most frequently accessed patterns stay in cache
|
||||
|
||||
// Monitor cache performance
|
||||
const stats = await adapter.getStats();
|
||||
console.log('Cache Hit Rate:', stats.cacheHitRate);
|
||||
// Aim for >80% hit rate
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Batch Operations
|
||||
|
||||
### Batch Insert (500x Faster)
|
||||
|
||||
```typescript
|
||||
// ❌ SLOW: Individual inserts
|
||||
for (const doc of documents) {
|
||||
await adapter.insertPattern({ /* ... */ }); // 1s for 100 docs
|
||||
}
|
||||
|
||||
// ✅ FAST: Batch insert
|
||||
const patterns = documents.map(doc => ({
|
||||
id: '',
|
||||
type: 'document',
|
||||
domain: 'knowledge',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding: doc.embedding,
|
||||
text: doc.text,
|
||||
}),
|
||||
confidence: 1.0,
|
||||
usage_count: 0,
|
||||
success_count: 0,
|
||||
created_at: Date.now(),
|
||||
last_used: Date.now(),
|
||||
}));
|
||||
|
||||
// Insert all at once (2ms for 100 docs)
|
||||
for (const pattern of patterns) {
|
||||
await adapter.insertPattern(pattern);
|
||||
}
|
||||
```
|
||||
|
||||
### Batch Retrieval
|
||||
|
||||
```typescript
|
||||
// Retrieve multiple queries efficiently
|
||||
const queries = [queryEmbedding1, queryEmbedding2, queryEmbedding3];
|
||||
|
||||
// Parallel retrieval
|
||||
const results = await Promise.all(
|
||||
queries.map(q => adapter.retrieveWithReasoning(q, { k: 5 }))
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Memory Optimization
|
||||
|
||||
### Automatic Consolidation
|
||||
|
||||
```typescript
|
||||
// Enable automatic pattern consolidation
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'documents',
|
||||
optimizeMemory: true, // Consolidate similar patterns
|
||||
k: 10,
|
||||
});
|
||||
|
||||
console.log('Optimizations:', result.optimizations);
|
||||
// {
|
||||
// consolidated: 15, // Merged 15 similar patterns
|
||||
// pruned: 3, // Removed 3 low-quality patterns
|
||||
// improved_quality: 0.12 // 12% quality improvement
|
||||
// }
|
||||
```
|
||||
|
||||
### Manual Optimization
|
||||
|
||||
```typescript
|
||||
// Manually trigger optimization
|
||||
await adapter.optimize();
|
||||
|
||||
// Get statistics
|
||||
const stats = await adapter.getStats();
|
||||
console.log('Before:', stats.totalPatterns);
|
||||
console.log('After:', stats.totalPatterns); // Reduced by ~10-30%
|
||||
```
|
||||
|
||||
### Pruning Strategies
|
||||
|
||||
```typescript
|
||||
// Prune low-confidence patterns
|
||||
await adapter.prune({
|
||||
minConfidence: 0.5, // Remove confidence < 0.5
|
||||
minUsageCount: 2, // Remove usage_count < 2
|
||||
maxAge: 30 * 24 * 3600, // Remove >30 days old
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Monitoring
|
||||
|
||||
### Database Statistics
|
||||
|
||||
```bash
|
||||
# Get comprehensive stats
|
||||
npx agentdb@latest stats .agentdb/vectors.db
|
||||
|
||||
# Output:
|
||||
# Total Patterns: 125,430
|
||||
# Database Size: 47.2 MB (with binary quantization)
|
||||
# Avg Confidence: 0.87
|
||||
# Domains: 15
|
||||
# Cache Hit Rate: 84%
|
||||
# Index Type: HNSW
|
||||
```
|
||||
|
||||
### Runtime Metrics
|
||||
|
||||
```typescript
|
||||
const stats = await adapter.getStats();
|
||||
|
||||
console.log('Performance Metrics:');
|
||||
console.log('Total Patterns:', stats.totalPatterns);
|
||||
console.log('Database Size:', stats.dbSize);
|
||||
console.log('Avg Confidence:', stats.avgConfidence);
|
||||
console.log('Cache Hit Rate:', stats.cacheHitRate);
|
||||
console.log('Search Latency (avg):', stats.avgSearchLatency);
|
||||
console.log('Insert Latency (avg):', stats.avgInsertLatency);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Optimization Recipes
|
||||
|
||||
### Recipe 1: Maximum Speed (Sacrifice Accuracy)
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'binary', // 32x memory reduction
|
||||
cacheSize: 5000, // Large cache
|
||||
hnswM: 8, // Fewer connections = faster
|
||||
hnswEfSearch: 50, // Low search quality = faster
|
||||
});
|
||||
|
||||
// Expected: <50µs search, 90-95% accuracy
|
||||
```
|
||||
|
||||
### Recipe 2: Balanced Performance
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'scalar', // 4x memory reduction
|
||||
cacheSize: 1000, // Standard cache
|
||||
hnswM: 16, // Balanced connections
|
||||
hnswEfSearch: 100, // Balanced quality
|
||||
});
|
||||
|
||||
// Expected: <100µs search, 98-99% accuracy
|
||||
```
|
||||
|
||||
### Recipe 3: Maximum Accuracy
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'none', // No quantization
|
||||
cacheSize: 2000, // Large cache
|
||||
hnswM: 32, // Many connections
|
||||
hnswEfSearch: 200, // High search quality
|
||||
});
|
||||
|
||||
// Expected: <200µs search, 100% accuracy
|
||||
```
|
||||
|
||||
### Recipe 4: Memory-Constrained (Mobile/Edge)
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'binary', // 32x memory reduction
|
||||
cacheSize: 100, // Small cache
|
||||
hnswM: 8, // Minimal connections
|
||||
});
|
||||
|
||||
// Expected: <100µs search, ~10MB for 100K vectors
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Scaling Strategies
|
||||
|
||||
### Small Scale (<10K vectors)
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'none', // Full precision
|
||||
cacheSize: 500,
|
||||
hnswM: 8,
|
||||
});
|
||||
```
|
||||
|
||||
### Medium Scale (10K-100K vectors)
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'scalar', // 4x reduction
|
||||
cacheSize: 1000,
|
||||
hnswM: 16,
|
||||
});
|
||||
```
|
||||
|
||||
### Large Scale (100K-1M vectors)
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'binary', // 32x reduction
|
||||
cacheSize: 2000,
|
||||
hnswM: 32,
|
||||
});
|
||||
```
|
||||
|
||||
### Massive Scale (>1M vectors)
|
||||
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'product', // 8-16x reduction
|
||||
cacheSize: 5000,
|
||||
hnswM: 48,
|
||||
hnswEfConstruction: 400,
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Issue: High memory usage
|
||||
|
||||
```bash
|
||||
# Check database size
|
||||
npx agentdb@latest stats .agentdb/vectors.db
|
||||
|
||||
# Enable quantization
|
||||
# Use 'binary' for 32x reduction
|
||||
```
|
||||
|
||||
### Issue: Slow search performance
|
||||
|
||||
```typescript
|
||||
// Increase cache size
|
||||
const adapter = await createAgentDBAdapter({
|
||||
cacheSize: 2000, // Increase from 1000
|
||||
});
|
||||
|
||||
// Reduce search quality (faster)
|
||||
const result = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
k: 5, // Reduce from 10
|
||||
});
|
||||
```
|
||||
|
||||
### Issue: Low accuracy
|
||||
|
||||
```typescript
|
||||
// Disable or use lighter quantization
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'scalar', // Instead of 'binary'
|
||||
hnswEfSearch: 200, // Higher search quality
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Benchmarks
|
||||
|
||||
**Test System**: AMD Ryzen 9 5950X, 64GB RAM
|
||||
|
||||
| Operation | Vector Count | No Optimization | Optimized | Improvement |
|
||||
|-----------|-------------|-----------------|-----------|-------------|
|
||||
| Search | 10K | 15ms | 100µs | 150x |
|
||||
| Search | 100K | 150ms | 120µs | 1,250x |
|
||||
| Search | 1M | 100s | 8ms | 12,500x |
|
||||
| Batch Insert (100) | - | 1s | 2ms | 500x |
|
||||
| Memory Usage | 1M | 3GB | 96MB | 32x (binary) |
|
||||
|
||||
---
|
||||
|
||||
## Learn More
|
||||
|
||||
- **Quantization Paper**: docs/quantization-techniques.pdf
|
||||
- **HNSW Algorithm**: docs/hnsw-index.pdf
|
||||
- **GitHub**: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb
|
||||
- **Website**: https://agentdb.ruv.io
|
||||
|
||||
---
|
||||
|
||||
**Category**: Performance / Optimization
|
||||
**Difficulty**: Intermediate
|
||||
**Estimated Time**: 20-30 minutes
|
||||
@@ -0,0 +1,339 @@
|
||||
---
|
||||
name: "AgentDB Vector Search"
|
||||
description: "Implement semantic vector search with AgentDB for intelligent document retrieval, similarity matching, and context-aware querying. Use when building RAG systems, semantic search engines, or intelligent knowledge bases."
|
||||
---
|
||||
|
||||
# AgentDB Vector Search
|
||||
|
||||
## What This Skill Does
|
||||
|
||||
Implements vector-based semantic search using AgentDB's high-performance vector database with **150x-12,500x faster** operations than traditional solutions. Features HNSW indexing, quantization, and sub-millisecond search (<100µs).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- AgentDB v1.0.7+ (via agentic-flow or standalone)
|
||||
- OpenAI API key (for embeddings) or custom embedding model
|
||||
|
||||
## Quick Start with CLI
|
||||
|
||||
### Initialize Vector Database
|
||||
|
||||
```bash
|
||||
# Initialize with default dimensions (1536 for OpenAI ada-002)
|
||||
npx agentdb@latest init ./vectors.db
|
||||
|
||||
# Custom dimensions for different embedding models
|
||||
npx agentdb@latest init ./vectors.db --dimension 768 # sentence-transformers
|
||||
npx agentdb@latest init ./vectors.db --dimension 384 # all-MiniLM-L6-v2
|
||||
|
||||
# Use preset configurations
|
||||
npx agentdb@latest init ./vectors.db --preset small # <10K vectors
|
||||
npx agentdb@latest init ./vectors.db --preset medium # 10K-100K vectors
|
||||
npx agentdb@latest init ./vectors.db --preset large # >100K vectors
|
||||
|
||||
# In-memory database for testing
|
||||
npx agentdb@latest init ./vectors.db --in-memory
|
||||
```
|
||||
|
||||
### Query Vector Database
|
||||
|
||||
```bash
|
||||
# Basic similarity search
|
||||
npx agentdb@latest query ./vectors.db "[0.1,0.2,0.3,...]"
|
||||
|
||||
# Top-k results
|
||||
npx agentdb@latest query ./vectors.db "[0.1,0.2,0.3]" -k 10
|
||||
|
||||
# With similarity threshold (cosine similarity)
|
||||
npx agentdb@latest query ./vectors.db "0.1 0.2 0.3" -t 0.75 -m cosine
|
||||
|
||||
# Different distance metrics
|
||||
npx agentdb@latest query ./vectors.db "[...]" -m euclidean # L2 distance
|
||||
npx agentdb@latest query ./vectors.db "[...]" -m dot # Dot product
|
||||
|
||||
# JSON output for automation
|
||||
npx agentdb@latest query ./vectors.db "[...]" -f json -k 5
|
||||
|
||||
# Verbose output with distances
|
||||
npx agentdb@latest query ./vectors.db "[...]" -v
|
||||
```
|
||||
|
||||
### Import/Export Vectors
|
||||
|
||||
```bash
|
||||
# Export vectors to JSON
|
||||
npx agentdb@latest export ./vectors.db ./backup.json
|
||||
|
||||
# Import vectors from JSON
|
||||
npx agentdb@latest import ./backup.json
|
||||
|
||||
# Get database statistics
|
||||
npx agentdb@latest stats ./vectors.db
|
||||
```
|
||||
|
||||
## Quick Start with API
|
||||
|
||||
```typescript
|
||||
import { createAgentDBAdapter, computeEmbedding } from 'agentic-flow/reasoningbank';
|
||||
|
||||
// Initialize with vector search optimizations
|
||||
const adapter = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/vectors.db',
|
||||
enableLearning: false, // Vector search only
|
||||
enableReasoning: true, // Enable semantic matching
|
||||
quantizationType: 'binary', // 32x memory reduction
|
||||
cacheSize: 1000, // Fast retrieval
|
||||
});
|
||||
|
||||
// Store document with embedding
|
||||
const text = "The quantum computer achieved 100 qubits";
|
||||
const embedding = await computeEmbedding(text);
|
||||
|
||||
await adapter.insertPattern({
|
||||
id: '',
|
||||
type: 'document',
|
||||
domain: 'technology',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding,
|
||||
text,
|
||||
metadata: { category: "quantum", date: "2025-01-15" }
|
||||
}),
|
||||
confidence: 1.0,
|
||||
usage_count: 0,
|
||||
success_count: 0,
|
||||
created_at: Date.now(),
|
||||
last_used: Date.now(),
|
||||
});
|
||||
|
||||
// Semantic search with MMR (Maximal Marginal Relevance)
|
||||
const queryEmbedding = await computeEmbedding("quantum computing advances");
|
||||
const results = await adapter.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'technology',
|
||||
k: 10,
|
||||
useMMR: true, // Diverse results
|
||||
synthesizeContext: true, // Rich context
|
||||
});
|
||||
```
|
||||
|
||||
## Core Features
|
||||
|
||||
### 1. Vector Storage
|
||||
```typescript
|
||||
// Store with automatic embedding
|
||||
await db.storeWithEmbedding({
|
||||
content: "Your document text",
|
||||
metadata: { source: "docs", page: 42 }
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Similarity Search
|
||||
```typescript
|
||||
// Find similar documents
|
||||
const similar = await db.findSimilar("quantum computing", {
|
||||
limit: 5,
|
||||
minScore: 0.75
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Hybrid Search (Vector + Metadata)
|
||||
```typescript
|
||||
// Combine vector similarity with metadata filtering
|
||||
const results = await db.hybridSearch({
|
||||
query: "machine learning models",
|
||||
filters: {
|
||||
category: "research",
|
||||
date: { $gte: "2024-01-01" }
|
||||
},
|
||||
limit: 20
|
||||
});
|
||||
```
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### RAG (Retrieval Augmented Generation)
|
||||
```typescript
|
||||
// Build RAG pipeline
|
||||
async function ragQuery(question: string) {
|
||||
// 1. Get relevant context
|
||||
const context = await db.searchSimilar(
|
||||
await embed(question),
|
||||
{ limit: 5, threshold: 0.7 }
|
||||
);
|
||||
|
||||
// 2. Generate answer with context
|
||||
const prompt = `Context: ${context.map(c => c.text).join('\n')}
|
||||
Question: ${question}`;
|
||||
|
||||
return await llm.generate(prompt);
|
||||
}
|
||||
```
|
||||
|
||||
### Batch Operations
|
||||
```typescript
|
||||
// Efficient batch storage
|
||||
await db.batchStore(documents.map(doc => ({
|
||||
text: doc.content,
|
||||
embedding: doc.vector,
|
||||
metadata: doc.meta
|
||||
})));
|
||||
```
|
||||
|
||||
## MCP Server Integration
|
||||
|
||||
```bash
|
||||
# Start AgentDB MCP server for Claude Code
|
||||
npx agentdb@latest mcp
|
||||
|
||||
# Add to Claude Code (one-time setup)
|
||||
claude mcp add agentdb npx agentdb@latest mcp
|
||||
|
||||
# Now use MCP tools in Claude Code:
|
||||
# - agentdb_query: Semantic vector search
|
||||
# - agentdb_store: Store documents with embeddings
|
||||
# - agentdb_stats: Database statistics
|
||||
```
|
||||
|
||||
## Performance Benchmarks
|
||||
|
||||
```bash
|
||||
# Run comprehensive benchmarks
|
||||
npx agentdb@latest benchmark
|
||||
|
||||
# Results:
|
||||
# ✅ Pattern Search: 150x faster (100µs vs 15ms)
|
||||
# ✅ Batch Insert: 500x faster (2ms vs 1s for 100 vectors)
|
||||
# ✅ Large-scale Query: 12,500x faster (8ms vs 100s at 1M vectors)
|
||||
# ✅ Memory Efficiency: 4-32x reduction with quantization
|
||||
```
|
||||
|
||||
## Quantization Options
|
||||
|
||||
AgentDB provides multiple quantization strategies for memory efficiency:
|
||||
|
||||
### Binary Quantization (32x reduction)
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'binary', // 768-dim → 96 bytes
|
||||
});
|
||||
```
|
||||
|
||||
### Scalar Quantization (4x reduction)
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'scalar', // 768-dim → 768 bytes
|
||||
});
|
||||
```
|
||||
|
||||
### Product Quantization (8-16x reduction)
|
||||
```typescript
|
||||
const adapter = await createAgentDBAdapter({
|
||||
quantizationType: 'product', // 768-dim → 48-96 bytes
|
||||
});
|
||||
```
|
||||
|
||||
## Distance Metrics
|
||||
|
||||
```bash
|
||||
# Cosine similarity (default, best for most use cases)
|
||||
npx agentdb@latest query ./db.sqlite "[...]" -m cosine
|
||||
|
||||
# Euclidean distance (L2 norm)
|
||||
npx agentdb@latest query ./db.sqlite "[...]" -m euclidean
|
||||
|
||||
# Dot product (for normalized vectors)
|
||||
npx agentdb@latest query ./db.sqlite "[...]" -m dot
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### HNSW Indexing
|
||||
- **O(log n) search complexity**
|
||||
- **Sub-millisecond retrieval** (<100µs)
|
||||
- **Automatic index building**
|
||||
|
||||
### Caching
|
||||
- **1000 pattern in-memory cache**
|
||||
- **<1ms pattern retrieval**
|
||||
- **Automatic cache invalidation**
|
||||
|
||||
### MMR (Maximal Marginal Relevance)
|
||||
- **Diverse result sets**
|
||||
- **Avoid redundancy**
|
||||
- **Balance relevance and diversity**
|
||||
|
||||
## Performance Tips
|
||||
|
||||
1. **Enable HNSW indexing**: Automatic with AgentDB, 10-100x faster
|
||||
2. **Use quantization**: Binary (32x), Scalar (4x), Product (8-16x) memory reduction
|
||||
3. **Batch operations**: 500x faster for bulk inserts
|
||||
4. **Match dimensions**: 1536 (OpenAI), 768 (sentence-transformers), 384 (MiniLM)
|
||||
5. **Similarity threshold**: Start at 0.7 for quality, adjust based on use case
|
||||
6. **Enable caching**: 1000 pattern cache for frequent queries
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Issue: Slow search performance
|
||||
```bash
|
||||
# Check if HNSW indexing is enabled (automatic)
|
||||
npx agentdb@latest stats ./vectors.db
|
||||
|
||||
# Expected: <100µs search time
|
||||
```
|
||||
|
||||
### Issue: High memory usage
|
||||
```bash
|
||||
# Enable binary quantization (32x reduction)
|
||||
# Use in adapter: quantizationType: 'binary'
|
||||
```
|
||||
|
||||
### Issue: Poor relevance
|
||||
```bash
|
||||
# Adjust similarity threshold
|
||||
npx agentdb@latest query ./db.sqlite "[...]" -t 0.8 # Higher threshold
|
||||
|
||||
# Or use MMR for diverse results
|
||||
# Use in adapter: useMMR: true
|
||||
```
|
||||
|
||||
### Issue: Wrong dimensions
|
||||
```bash
|
||||
# Check embedding model dimensions:
|
||||
# - OpenAI ada-002: 1536
|
||||
# - sentence-transformers: 768
|
||||
# - all-MiniLM-L6-v2: 384
|
||||
|
||||
npx agentdb@latest init ./db.sqlite --dimension 768
|
||||
```
|
||||
|
||||
## Database Statistics
|
||||
|
||||
```bash
|
||||
# Get comprehensive stats
|
||||
npx agentdb@latest stats ./vectors.db
|
||||
|
||||
# Shows:
|
||||
# - Total patterns/vectors
|
||||
# - Database size
|
||||
# - Average confidence
|
||||
# - Domains distribution
|
||||
# - Index status
|
||||
```
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
- **Vector Search**: <100µs (HNSW indexing)
|
||||
- **Pattern Retrieval**: <1ms (with cache)
|
||||
- **Batch Insert**: 2ms for 100 vectors
|
||||
- **Memory Efficiency**: 4-32x reduction with quantization
|
||||
- **Scalability**: Handles 1M+ vectors efficiently
|
||||
- **Latency**: Sub-millisecond for most operations
|
||||
|
||||
## Learn More
|
||||
|
||||
- GitHub: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb
|
||||
- Documentation: node_modules/agentic-flow/docs/AGENTDB_INTEGRATION.md
|
||||
- MCP Integration: `npx agentdb@latest mcp` for Claude Code
|
||||
- Website: https://agentdb.ruv.io
|
||||
- CLI Help: `npx agentdb@latest --help`
|
||||
- Command Help: `npx agentdb@latest help <command>`
|
||||
@@ -0,0 +1,645 @@
|
||||
---
|
||||
name: agentic-jujutsu
|
||||
version: 2.3.2
|
||||
description: Quantum-resistant, self-learning version control for AI agents with ReasoningBank intelligence and multi-agent coordination
|
||||
---
|
||||
|
||||
# Agentic Jujutsu - AI Agent Version Control
|
||||
|
||||
> Quantum-ready, self-learning version control designed for multiple AI agents working simultaneously without conflicts.
|
||||
|
||||
## When to Use This Skill
|
||||
|
||||
Use **agentic-jujutsu** when you need:
|
||||
- ✅ Multiple AI agents modifying code simultaneously
|
||||
- ✅ Lock-free version control (23x faster than Git)
|
||||
- ✅ Self-learning AI that improves from experience
|
||||
- ✅ Quantum-resistant security for future-proof protection
|
||||
- ✅ Automatic conflict resolution (87% success rate)
|
||||
- ✅ Pattern recognition and intelligent suggestions
|
||||
- ✅ Multi-agent coordination without blocking
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
npx agentic-jujutsu
|
||||
```
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```javascript
|
||||
const { JjWrapper } = require('agentic-jujutsu');
|
||||
|
||||
const jj = new JjWrapper();
|
||||
|
||||
// Basic operations
|
||||
await jj.status();
|
||||
await jj.newCommit('Add feature');
|
||||
await jj.log(10);
|
||||
|
||||
// Self-learning trajectory
|
||||
const id = jj.startTrajectory('Implement authentication');
|
||||
await jj.branchCreate('feature/auth');
|
||||
await jj.newCommit('Add auth');
|
||||
jj.addToTrajectory();
|
||||
jj.finalizeTrajectory(0.9, 'Clean implementation');
|
||||
|
||||
// Get AI suggestions
|
||||
const suggestion = JSON.parse(jj.getSuggestion('Add logout feature'));
|
||||
console.log(`Confidence: ${suggestion.confidence}`);
|
||||
```
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
### 1. Self-Learning with ReasoningBank
|
||||
|
||||
Track operations, learn patterns, and get intelligent suggestions:
|
||||
|
||||
```javascript
|
||||
// Start learning trajectory
|
||||
const trajectoryId = jj.startTrajectory('Deploy to production');
|
||||
|
||||
// Perform operations (automatically tracked)
|
||||
await jj.execute(['git', 'push', 'origin', 'main']);
|
||||
await jj.branchCreate('release/v1.0');
|
||||
await jj.newCommit('Release v1.0');
|
||||
|
||||
// Record operations to trajectory
|
||||
jj.addToTrajectory();
|
||||
|
||||
// Finalize with success score (0.0-1.0) and critique
|
||||
jj.finalizeTrajectory(0.95, 'Deployment successful, no issues');
|
||||
|
||||
// Later: Get AI-powered suggestions for similar tasks
|
||||
const suggestion = JSON.parse(jj.getSuggestion('Deploy to staging'));
|
||||
console.log('AI Recommendation:', suggestion.reasoning);
|
||||
console.log('Confidence:', (suggestion.confidence * 100).toFixed(1) + '%');
|
||||
console.log('Expected Success:', (suggestion.expectedSuccessRate * 100).toFixed(1) + '%');
|
||||
```
|
||||
|
||||
**Validation (v2.3.1)**:
|
||||
- ✅ Tasks must be non-empty (max 10KB)
|
||||
- ✅ Success scores must be 0.0-1.0
|
||||
- ✅ Must have operations before finalizing
|
||||
- ✅ Contexts cannot be empty
|
||||
|
||||
### 2. Pattern Discovery
|
||||
|
||||
Automatically identify successful operation sequences:
|
||||
|
||||
```javascript
|
||||
// Get discovered patterns
|
||||
const patterns = JSON.parse(jj.getPatterns());
|
||||
|
||||
patterns.forEach(pattern => {
|
||||
console.log(`Pattern: ${pattern.name}`);
|
||||
console.log(` Success rate: ${(pattern.successRate * 100).toFixed(1)}%`);
|
||||
console.log(` Used ${pattern.observationCount} times`);
|
||||
console.log(` Operations: ${pattern.operationSequence.join(' → ')}`);
|
||||
console.log(` Confidence: ${(pattern.confidence * 100).toFixed(1)}%`);
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Learning Statistics
|
||||
|
||||
Track improvement over time:
|
||||
|
||||
```javascript
|
||||
const stats = JSON.parse(jj.getLearningStats());
|
||||
|
||||
console.log('Learning Progress:');
|
||||
console.log(` Total trajectories: ${stats.totalTrajectories}`);
|
||||
console.log(` Patterns discovered: ${stats.totalPatterns}`);
|
||||
console.log(` Average success: ${(stats.avgSuccessRate * 100).toFixed(1)}%`);
|
||||
console.log(` Improvement rate: ${(stats.improvementRate * 100).toFixed(1)}%`);
|
||||
console.log(` Prediction accuracy: ${(stats.predictionAccuracy * 100).toFixed(1)}%`);
|
||||
```
|
||||
|
||||
### 4. Multi-Agent Coordination
|
||||
|
||||
Multiple agents work concurrently without conflicts:
|
||||
|
||||
```javascript
|
||||
// Agent 1: Developer
|
||||
const dev = new JjWrapper();
|
||||
dev.startTrajectory('Implement feature');
|
||||
await dev.newCommit('Add feature X');
|
||||
dev.addToTrajectory();
|
||||
dev.finalizeTrajectory(0.85);
|
||||
|
||||
// Agent 2: Reviewer (learns from Agent 1)
|
||||
const reviewer = new JjWrapper();
|
||||
const suggestion = JSON.parse(reviewer.getSuggestion('Review feature X'));
|
||||
|
||||
if (suggestion.confidence > 0.7) {
|
||||
console.log('High confidence approach:', suggestion.reasoning);
|
||||
}
|
||||
|
||||
// Agent 3: Tester (benefits from both)
|
||||
const tester = new JjWrapper();
|
||||
const similar = JSON.parse(tester.queryTrajectories('test feature', 5));
|
||||
console.log(`Found ${similar.length} similar test approaches`);
|
||||
```
|
||||
|
||||
### 5. Quantum-Resistant Security (v2.3.0+)
|
||||
|
||||
Fast integrity verification with quantum-resistant cryptography:
|
||||
|
||||
```javascript
|
||||
const { generateQuantumFingerprint, verifyQuantumFingerprint } = require('agentic-jujutsu');
|
||||
|
||||
// Generate SHA3-512 fingerprint (NIST FIPS 202)
|
||||
const data = Buffer.from('commit-data');
|
||||
const fingerprint = generateQuantumFingerprint(data);
|
||||
console.log('Fingerprint:', fingerprint.toString('hex'));
|
||||
|
||||
// Verify integrity (<1ms)
|
||||
const isValid = verifyQuantumFingerprint(data, fingerprint);
|
||||
console.log('Valid:', isValid);
|
||||
|
||||
// HQC-128 encryption for trajectories
|
||||
const crypto = require('crypto');
|
||||
const key = crypto.randomBytes(32).toString('base64');
|
||||
jj.enableEncryption(key);
|
||||
```
|
||||
|
||||
### 6. Operation Tracking with AgentDB
|
||||
|
||||
Automatic tracking of all operations:
|
||||
|
||||
```javascript
|
||||
// Operations are tracked automatically
|
||||
await jj.status();
|
||||
await jj.newCommit('Fix bug');
|
||||
await jj.rebase('main');
|
||||
|
||||
// Get operation statistics
|
||||
const stats = JSON.parse(jj.getStats());
|
||||
console.log(`Total operations: ${stats.total_operations}`);
|
||||
console.log(`Success rate: ${(stats.success_rate * 100).toFixed(1)}%`);
|
||||
console.log(`Avg duration: ${stats.avg_duration_ms.toFixed(2)}ms`);
|
||||
|
||||
// Query recent operations
|
||||
const ops = jj.getOperations(10);
|
||||
ops.forEach(op => {
|
||||
console.log(`${op.operationType}: ${op.command}`);
|
||||
console.log(` Duration: ${op.durationMs}ms, Success: ${op.success}`);
|
||||
});
|
||||
|
||||
// Get user operations (excludes snapshots)
|
||||
const userOps = jj.getUserOperations(20);
|
||||
```
|
||||
|
||||
## Advanced Use Cases
|
||||
|
||||
### Use Case 1: Adaptive Workflow Optimization
|
||||
|
||||
Learn and improve deployment workflows:
|
||||
|
||||
```javascript
|
||||
async function adaptiveDeployment(jj, environment) {
|
||||
// Get AI suggestion based on past deployments
|
||||
const suggestion = JSON.parse(jj.getSuggestion(`Deploy to ${environment}`));
|
||||
|
||||
console.log(`Deploying with ${(suggestion.confidence * 100).toFixed(0)}% confidence`);
|
||||
console.log(`Expected duration: ${suggestion.estimatedDurationMs}ms`);
|
||||
|
||||
// Start tracking
|
||||
jj.startTrajectory(`Deploy to ${environment}`);
|
||||
|
||||
// Execute recommended operations
|
||||
for (const op of suggestion.recommendedOperations) {
|
||||
console.log(`Executing: ${op}`);
|
||||
await executeOperation(op);
|
||||
}
|
||||
|
||||
jj.addToTrajectory();
|
||||
|
||||
// Record outcome
|
||||
const success = await verifyDeployment();
|
||||
jj.finalizeTrajectory(
|
||||
success ? 0.95 : 0.5,
|
||||
success ? 'Deployment successful' : 'Issues detected'
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Use Case 2: Multi-Agent Code Review
|
||||
|
||||
Coordinate review across multiple agents:
|
||||
|
||||
```javascript
|
||||
async function coordinatedReview(agents) {
|
||||
const reviews = await Promise.all(agents.map(async (agent) => {
|
||||
const jj = new JjWrapper();
|
||||
|
||||
// Start review trajectory
|
||||
jj.startTrajectory(`Review by ${agent.name}`);
|
||||
|
||||
// Get AI suggestion for review approach
|
||||
const suggestion = JSON.parse(jj.getSuggestion('Code review'));
|
||||
|
||||
// Perform review
|
||||
const diff = await jj.diff('@', '@-');
|
||||
const issues = await agent.analyze(diff);
|
||||
|
||||
jj.addToTrajectory();
|
||||
jj.finalizeTrajectory(
|
||||
issues.length === 0 ? 0.9 : 0.6,
|
||||
`Found ${issues.length} issues`
|
||||
);
|
||||
|
||||
return { agent: agent.name, issues, suggestion };
|
||||
}));
|
||||
|
||||
// Aggregate learning from all agents
|
||||
return reviews;
|
||||
}
|
||||
```
|
||||
|
||||
### Use Case 3: Error Pattern Detection
|
||||
|
||||
Learn from failures to prevent future issues:
|
||||
|
||||
```javascript
|
||||
async function smartMerge(jj, branch) {
|
||||
// Query similar merge attempts
|
||||
const similar = JSON.parse(jj.queryTrajectories(`merge ${branch}`, 10));
|
||||
|
||||
// Analyze past failures
|
||||
const failures = similar.filter(t => t.successScore < 0.5);
|
||||
|
||||
if (failures.length > 0) {
|
||||
console.log('⚠️ Similar merges failed in the past:');
|
||||
failures.forEach(f => {
|
||||
if (f.critique) {
|
||||
console.log(` - ${f.critique}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Get AI recommendation
|
||||
const suggestion = JSON.parse(jj.getSuggestion(`merge ${branch}`));
|
||||
|
||||
if (suggestion.confidence < 0.7) {
|
||||
console.log('⚠️ Low confidence. Recommended steps:');
|
||||
suggestion.recommendedOperations.forEach(op => console.log(` - ${op}`));
|
||||
}
|
||||
|
||||
// Execute merge with tracking
|
||||
jj.startTrajectory(`Merge ${branch}`);
|
||||
try {
|
||||
await jj.execute(['merge', branch]);
|
||||
jj.addToTrajectory();
|
||||
jj.finalizeTrajectory(0.9, 'Merge successful');
|
||||
} catch (err) {
|
||||
jj.addToTrajectory();
|
||||
jj.finalizeTrajectory(0.3, `Merge failed: ${err.message}`);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Use Case 4: Continuous Learning Loop
|
||||
|
||||
Implement a self-improving agent:
|
||||
|
||||
```javascript
|
||||
class SelfImprovingAgent {
|
||||
constructor() {
|
||||
this.jj = new JjWrapper();
|
||||
}
|
||||
|
||||
async performTask(taskDescription) {
|
||||
// Get AI suggestion
|
||||
const suggestion = JSON.parse(this.jj.getSuggestion(taskDescription));
|
||||
|
||||
console.log(`Task: ${taskDescription}`);
|
||||
console.log(`AI Confidence: ${(suggestion.confidence * 100).toFixed(1)}%`);
|
||||
console.log(`Expected Success: ${(suggestion.expectedSuccessRate * 100).toFixed(1)}%`);
|
||||
|
||||
// Start trajectory
|
||||
this.jj.startTrajectory(taskDescription);
|
||||
|
||||
// Execute with recommended approach
|
||||
const startTime = Date.now();
|
||||
let success = false;
|
||||
|
||||
try {
|
||||
for (const op of suggestion.recommendedOperations) {
|
||||
await this.execute(op);
|
||||
}
|
||||
success = true;
|
||||
} catch (err) {
|
||||
console.error('Task failed:', err.message);
|
||||
}
|
||||
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
// Record learning
|
||||
this.jj.addToTrajectory();
|
||||
this.jj.finalizeTrajectory(
|
||||
success ? 0.9 : 0.4,
|
||||
success
|
||||
? `Completed in ${duration}ms using ${suggestion.recommendedOperations.length} operations`
|
||||
: `Failed after ${duration}ms`
|
||||
);
|
||||
|
||||
// Check improvement
|
||||
const stats = JSON.parse(this.jj.getLearningStats());
|
||||
console.log(`Improvement rate: ${(stats.improvementRate * 100).toFixed(1)}%`);
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
async execute(operation) {
|
||||
// Execute operation logic
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
const agent = new SelfImprovingAgent();
|
||||
|
||||
// Agent improves over time
|
||||
for (let i = 1; i <= 10; i++) {
|
||||
console.log(`\n--- Attempt ${i} ---`);
|
||||
await agent.performTask('Deploy application');
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### Core Methods
|
||||
|
||||
| Method | Description | Returns |
|
||||
|--------|-------------|---------|
|
||||
| `new JjWrapper()` | Create wrapper instance | JjWrapper |
|
||||
| `status()` | Get repository status | Promise<JjResult> |
|
||||
| `newCommit(msg)` | Create new commit | Promise<JjResult> |
|
||||
| `log(limit)` | Show commit history | Promise<JjCommit[]> |
|
||||
| `diff(from, to)` | Show differences | Promise<JjDiff> |
|
||||
| `branchCreate(name, rev?)` | Create branch | Promise<JjResult> |
|
||||
| `rebase(source, dest)` | Rebase commits | Promise<JjResult> |
|
||||
|
||||
### ReasoningBank Methods
|
||||
|
||||
| Method | Description | Returns |
|
||||
|--------|-------------|---------|
|
||||
| `startTrajectory(task)` | Begin learning trajectory | string (trajectory ID) |
|
||||
| `addToTrajectory()` | Add recent operations | void |
|
||||
| `finalizeTrajectory(score, critique?)` | Complete trajectory (score: 0.0-1.0) | void |
|
||||
| `getSuggestion(task)` | Get AI recommendation | JSON: DecisionSuggestion |
|
||||
| `getLearningStats()` | Get learning metrics | JSON: LearningStats |
|
||||
| `getPatterns()` | Get discovered patterns | JSON: Pattern[] |
|
||||
| `queryTrajectories(task, limit)` | Find similar trajectories | JSON: Trajectory[] |
|
||||
| `resetLearning()` | Clear learned data | void |
|
||||
|
||||
### AgentDB Methods
|
||||
|
||||
| Method | Description | Returns |
|
||||
|--------|-------------|---------|
|
||||
| `getStats()` | Get operation statistics | JSON: Stats |
|
||||
| `getOperations(limit)` | Get recent operations | JjOperation[] |
|
||||
| `getUserOperations(limit)` | Get user operations only | JjOperation[] |
|
||||
| `clearLog()` | Clear operation log | void |
|
||||
|
||||
### Quantum Security Methods (v2.3.0+)
|
||||
|
||||
| Method | Description | Returns |
|
||||
|--------|-------------|---------|
|
||||
| `generateQuantumFingerprint(data)` | Generate SHA3-512 fingerprint | Buffer (64 bytes) |
|
||||
| `verifyQuantumFingerprint(data, fp)` | Verify fingerprint | boolean |
|
||||
| `enableEncryption(key, pubKey?)` | Enable HQC-128 encryption | void |
|
||||
| `disableEncryption()` | Disable encryption | void |
|
||||
| `isEncryptionEnabled()` | Check encryption status | boolean |
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
| Metric | Git | Agentic Jujutsu |
|
||||
|--------|-----|-----------------|
|
||||
| Concurrent commits | 15 ops/s | 350 ops/s (23x) |
|
||||
| Context switching | 500-1000ms | 50-100ms (10x) |
|
||||
| Conflict resolution | 30-40% auto | 87% auto (2.5x) |
|
||||
| Lock waiting | 50 min/day | 0 min (∞) |
|
||||
| Quantum fingerprints | N/A | <1ms |
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Trajectory Management
|
||||
|
||||
```javascript
|
||||
// ✅ Good: Meaningful task descriptions
|
||||
jj.startTrajectory('Implement user authentication with JWT');
|
||||
|
||||
// ❌ Bad: Vague descriptions
|
||||
jj.startTrajectory('fix stuff');
|
||||
|
||||
// ✅ Good: Honest success scores
|
||||
jj.finalizeTrajectory(0.7, 'Works but needs refactoring');
|
||||
|
||||
// ❌ Bad: Always 1.0
|
||||
jj.finalizeTrajectory(1.0, 'Perfect!'); // Prevents learning
|
||||
```
|
||||
|
||||
### 2. Pattern Recognition
|
||||
|
||||
```javascript
|
||||
// ✅ Good: Let patterns emerge naturally
|
||||
for (let i = 0; i < 10; i++) {
|
||||
jj.startTrajectory('Deploy feature');
|
||||
await deploy();
|
||||
jj.addToTrajectory();
|
||||
jj.finalizeTrajectory(wasSuccessful ? 0.9 : 0.5);
|
||||
}
|
||||
|
||||
// ❌ Bad: Not recording outcomes
|
||||
await deploy(); // No learning
|
||||
```
|
||||
|
||||
### 3. Multi-Agent Coordination
|
||||
|
||||
```javascript
|
||||
// ✅ Good: Concurrent operations
|
||||
const agents = ['agent1', 'agent2', 'agent3'];
|
||||
await Promise.all(agents.map(async (agent) => {
|
||||
const jj = new JjWrapper();
|
||||
// Each agent works independently
|
||||
await jj.newCommit(`Changes by ${agent}`);
|
||||
}));
|
||||
|
||||
// ❌ Bad: Sequential with locks
|
||||
for (const agent of agents) {
|
||||
await agent.waitForLock(); // Not needed!
|
||||
await agent.commit();
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Error Handling
|
||||
|
||||
```javascript
|
||||
// ✅ Good: Record failures with details
|
||||
try {
|
||||
await jj.execute(['complex-operation']);
|
||||
jj.finalizeTrajectory(0.9);
|
||||
} catch (err) {
|
||||
jj.finalizeTrajectory(0.3, `Failed: ${err.message}. Root cause: ...`);
|
||||
}
|
||||
|
||||
// ❌ Bad: Silent failures
|
||||
try {
|
||||
await jj.execute(['operation']);
|
||||
} catch (err) {
|
||||
// No learning from failure
|
||||
}
|
||||
```
|
||||
|
||||
## Validation Rules (v2.3.1+)
|
||||
|
||||
### Task Description
|
||||
- ✅ Cannot be empty or whitespace-only
|
||||
- ✅ Maximum length: 10,000 bytes
|
||||
- ✅ Automatically trimmed
|
||||
|
||||
### Success Score
|
||||
- ✅ Must be finite (not NaN or Infinity)
|
||||
- ✅ Must be between 0.0 and 1.0 (inclusive)
|
||||
|
||||
### Operations
|
||||
- ✅ Must have at least one operation before finalizing
|
||||
|
||||
### Context
|
||||
- ✅ Cannot be empty
|
||||
- ✅ Keys cannot be empty or whitespace-only
|
||||
- ✅ Keys max 1,000 bytes, values max 10,000 bytes
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Issue: Low Confidence Suggestions
|
||||
|
||||
```javascript
|
||||
const suggestion = JSON.parse(jj.getSuggestion('new task'));
|
||||
|
||||
if (suggestion.confidence < 0.5) {
|
||||
// Not enough data - check learning stats
|
||||
const stats = JSON.parse(jj.getLearningStats());
|
||||
console.log(`Need more data. Current trajectories: ${stats.totalTrajectories}`);
|
||||
|
||||
// Recommend: Record 5-10 trajectories first
|
||||
}
|
||||
```
|
||||
|
||||
### Issue: Validation Errors
|
||||
|
||||
```javascript
|
||||
try {
|
||||
jj.startTrajectory(''); // Empty task
|
||||
} catch (err) {
|
||||
if (err.message.includes('Validation error')) {
|
||||
console.log('Invalid input:', err.message);
|
||||
// Use non-empty, meaningful task description
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
jj.finalizeTrajectory(1.5); // Score > 1.0
|
||||
} catch (err) {
|
||||
// Use score between 0.0 and 1.0
|
||||
jj.finalizeTrajectory(Math.max(0, Math.min(1, score)));
|
||||
}
|
||||
```
|
||||
|
||||
### Issue: No Patterns Discovered
|
||||
|
||||
```javascript
|
||||
const patterns = JSON.parse(jj.getPatterns());
|
||||
|
||||
if (patterns.length === 0) {
|
||||
// Need more trajectories with >70% success
|
||||
// Record at least 3-5 successful trajectories
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Example 1: Simple Learning Workflow
|
||||
|
||||
```javascript
|
||||
const { JjWrapper } = require('agentic-jujutsu');
|
||||
|
||||
async function learnFromWork() {
|
||||
const jj = new JjWrapper();
|
||||
|
||||
// Start tracking
|
||||
jj.startTrajectory('Add user profile feature');
|
||||
|
||||
// Do work
|
||||
await jj.branchCreate('feature/user-profile');
|
||||
await jj.newCommit('Add user profile model');
|
||||
await jj.newCommit('Add profile API endpoints');
|
||||
await jj.newCommit('Add profile UI');
|
||||
|
||||
// Record operations
|
||||
jj.addToTrajectory();
|
||||
|
||||
// Finalize with result
|
||||
jj.finalizeTrajectory(0.85, 'Feature complete, minor styling issues remain');
|
||||
|
||||
// Next time, get suggestions
|
||||
const suggestion = JSON.parse(jj.getSuggestion('Add settings page'));
|
||||
console.log('AI suggests:', suggestion.reasoning);
|
||||
}
|
||||
```
|
||||
|
||||
### Example 2: Multi-Agent Swarm
|
||||
|
||||
```javascript
|
||||
async function agentSwarm(taskList) {
|
||||
const agents = taskList.map((task, i) => ({
|
||||
name: `agent-${i}`,
|
||||
jj: new JjWrapper(),
|
||||
task
|
||||
}));
|
||||
|
||||
// All agents work concurrently (no conflicts!)
|
||||
const results = await Promise.all(agents.map(async (agent) => {
|
||||
agent.jj.startTrajectory(agent.task);
|
||||
|
||||
// Get AI suggestion
|
||||
const suggestion = JSON.parse(agent.jj.getSuggestion(agent.task));
|
||||
|
||||
// Execute task
|
||||
const success = await executeTask(agent, suggestion);
|
||||
|
||||
agent.jj.addToTrajectory();
|
||||
agent.jj.finalizeTrajectory(success ? 0.9 : 0.5);
|
||||
|
||||
return { agent: agent.name, success };
|
||||
}));
|
||||
|
||||
console.log('Results:', results);
|
||||
}
|
||||
```
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- **NPM Package**: https://npmjs.com/package/agentic-jujutsu
|
||||
- **GitHub**: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentic-jujutsu
|
||||
- **Full README**: See package README.md
|
||||
- **Validation Guide**: docs/VALIDATION_FIXES_v2.3.1.md
|
||||
- **AgentDB Guide**: docs/AGENTDB_GUIDE.md
|
||||
|
||||
## Version History
|
||||
|
||||
- **v2.3.2** - Documentation updates
|
||||
- **v2.3.1** - Validation fixes for ReasoningBank
|
||||
- **v2.3.0** - Quantum-resistant security with @qudag/napi-core
|
||||
- **v2.1.0** - Self-learning AI with ReasoningBank
|
||||
- **v2.0.0** - Zero-dependency installation with embedded jj binary
|
||||
|
||||
---
|
||||
|
||||
**Status**: ✅ Production Ready
|
||||
**License**: MIT
|
||||
**Maintained**: Active
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
name: apple-notes
|
||||
description: Manage Apple Notes via the `memo` CLI on macOS (create, view, edit, delete, search, move, and export notes). Use when a user asks Zee to add a note, list notes, search notes, or manage note folders.
|
||||
homepage: https://github.com/antoniorodr/memo
|
||||
metadata: {"zee":{"emoji":"📝","os":["darwin"],"requires":{"bins":["memo"]},"install":[{"id":"brew","kind":"brew","formula":"antoniorodr/memo/memo","bins":["memo"],"label":"Install memo via Homebrew"}]}}
|
||||
---
|
||||
|
||||
# Apple Notes CLI
|
||||
|
||||
Use `memo notes` to manage Apple Notes directly from the terminal. Create, view, edit, delete, search, move notes between folders, and export to HTML/Markdown.
|
||||
|
||||
Setup
|
||||
- Install (Homebrew): `brew tap antoniorodr/memo && brew install antoniorodr/memo/memo`
|
||||
- Manual (pip): `pip install .` (after cloning the repo)
|
||||
- macOS-only; if prompted, grant Automation access to Notes.app.
|
||||
|
||||
View Notes
|
||||
- List all notes: `memo notes`
|
||||
- Filter by folder: `memo notes -f "Folder Name"`
|
||||
- Search notes (fuzzy): `memo notes -s "query"`
|
||||
|
||||
Create Notes
|
||||
- Add a new note: `memo notes -a`
|
||||
- Opens an interactive editor to compose the note.
|
||||
- Quick add with title: `memo notes -a "Note Title"`
|
||||
|
||||
Edit Notes
|
||||
- Edit existing note: `memo notes -e`
|
||||
- Interactive selection of note to edit.
|
||||
|
||||
Delete Notes
|
||||
- Delete a note: `memo notes -d`
|
||||
- Interactive selection of note to delete.
|
||||
|
||||
Move Notes
|
||||
- Move note to folder: `memo notes -m`
|
||||
- Interactive selection of note and destination folder.
|
||||
|
||||
Export Notes
|
||||
- Export to HTML/Markdown: `memo notes -ex`
|
||||
- Exports selected note; uses Mistune for markdown processing.
|
||||
|
||||
Limitations
|
||||
- Cannot edit notes containing images or attachments.
|
||||
- Interactive prompts may require terminal access.
|
||||
|
||||
Notes
|
||||
- macOS-only.
|
||||
- Requires Apple Notes.app to be accessible.
|
||||
- For automation, grant permissions in System Settings > Privacy & Security > Automation.
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: apple-reminders
|
||||
description: Manage Apple Reminders via the `remindctl` CLI on macOS (list, add, edit, complete, delete). Supports lists, date filters, and JSON/plain output.
|
||||
homepage: https://github.com/steipete/remindctl
|
||||
metadata: {"zee":{"emoji":"⏰","os":["darwin"],"requires":{"bins":["remindctl"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/remindctl","bins":["remindctl"],"label":"Install remindctl via Homebrew"}]}}
|
||||
---
|
||||
|
||||
# Apple Reminders CLI (remindctl)
|
||||
|
||||
Use `remindctl` to manage Apple Reminders directly from the terminal. It supports list filtering, date-based views, and scripting output.
|
||||
|
||||
Setup
|
||||
- Install (Homebrew): `brew install steipete/tap/remindctl`
|
||||
- From source: `pnpm install && pnpm build` (binary at `./bin/remindctl`)
|
||||
- macOS-only; grant Reminders permission when prompted.
|
||||
|
||||
Permissions
|
||||
- Check status: `remindctl status`
|
||||
- Request access: `remindctl authorize`
|
||||
|
||||
View Reminders
|
||||
- Default (today): `remindctl`
|
||||
- Today: `remindctl today`
|
||||
- Tomorrow: `remindctl tomorrow`
|
||||
- Week: `remindctl week`
|
||||
- Overdue: `remindctl overdue`
|
||||
- Upcoming: `remindctl upcoming`
|
||||
- Completed: `remindctl completed`
|
||||
- All: `remindctl all`
|
||||
- Specific date: `remindctl 2026-01-04`
|
||||
|
||||
Manage Lists
|
||||
- List all lists: `remindctl list`
|
||||
- Show list: `remindctl list Work`
|
||||
- Create list: `remindctl list Projects --create`
|
||||
- Rename list: `remindctl list Work --rename Office`
|
||||
- Delete list: `remindctl list Work --delete`
|
||||
|
||||
Create Reminders
|
||||
- Quick add: `remindctl add "Buy milk"`
|
||||
- With list + due: `remindctl add --title "Call mom" --list Personal --due tomorrow`
|
||||
|
||||
Edit Reminders
|
||||
- Edit title/due: `remindctl edit 1 --title "New title" --due 2026-01-04`
|
||||
|
||||
Complete Reminders
|
||||
- Complete by id: `remindctl complete 1 2 3`
|
||||
|
||||
Delete Reminders
|
||||
- Delete by id: `remindctl delete 4A83 --force`
|
||||
|
||||
Output Formats
|
||||
- JSON (scripting): `remindctl today --json`
|
||||
- Plain TSV: `remindctl today --plain`
|
||||
- Counts only: `remindctl today --quiet`
|
||||
|
||||
Date Formats
|
||||
Accepted by `--due` and date filters:
|
||||
- `today`, `tomorrow`, `yesterday`
|
||||
- `YYYY-MM-DD`
|
||||
- `YYYY-MM-DD HH:mm`
|
||||
- ISO 8601 (`2026-01-04T12:34:56Z`)
|
||||
|
||||
Notes
|
||||
- macOS-only.
|
||||
- If access is denied, enable Terminal/remindctl in System Settings → Privacy & Security → Reminders.
|
||||
- If running over SSH, grant access on the Mac that runs the command.
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
name: bear-notes
|
||||
description: Create, search, and manage Bear notes via grizzly CLI.
|
||||
homepage: https://bear.app
|
||||
metadata: {"zee":{"emoji":"🐻","os":["darwin"],"requires":{"bins":["grizzly"]},"install":[{"id":"go","kind":"go","module":"github.com/tylerwince/grizzly/cmd/grizzly@latest","bins":["grizzly"],"label":"Install grizzly (go)"}]}}
|
||||
---
|
||||
|
||||
# Bear Notes
|
||||
|
||||
Use `grizzly` to create, read, and manage notes in Bear on macOS.
|
||||
|
||||
Requirements
|
||||
- Bear app installed and running
|
||||
- For some operations (add-text, tags, open-note --selected), a Bear app token (stored in `~/.config/grizzly/token`)
|
||||
|
||||
## Getting a Bear Token
|
||||
|
||||
For operations that require a token (add-text, tags, open-note --selected), you need an authentication token:
|
||||
1. Open Bear → Help → API Token → Copy Token
|
||||
2. Save it: `echo "YOUR_TOKEN" > ~/.config/grizzly/token`
|
||||
|
||||
## Common Commands
|
||||
|
||||
Create a note
|
||||
```bash
|
||||
echo "Note content here" | grizzly create --title "My Note" --tag work
|
||||
grizzly create --title "Quick Note" --tag inbox < /dev/null
|
||||
```
|
||||
|
||||
Open/read a note by ID
|
||||
```bash
|
||||
grizzly open-note --id "NOTE_ID" --enable-callback --json
|
||||
```
|
||||
|
||||
Append text to a note
|
||||
```bash
|
||||
echo "Additional content" | grizzly add-text --id "NOTE_ID" --mode append --token-file ~/.config/grizzly/token
|
||||
```
|
||||
|
||||
List all tags
|
||||
```bash
|
||||
grizzly tags --enable-callback --json --token-file ~/.config/grizzly/token
|
||||
```
|
||||
|
||||
Search notes (via open-tag)
|
||||
```bash
|
||||
grizzly open-tag --name "work" --enable-callback --json
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
Common flags:
|
||||
- `--dry-run` — Preview the URL without executing
|
||||
- `--print-url` — Show the x-callback-url
|
||||
- `--enable-callback` — Wait for Bear's response (needed for reading data)
|
||||
- `--json` — Output as JSON (when using callbacks)
|
||||
- `--token-file PATH` — Path to Bear API token file
|
||||
|
||||
## Configuration
|
||||
|
||||
Grizzly reads config from (in priority order):
|
||||
1. CLI flags
|
||||
2. Environment variables (`GRIZZLY_TOKEN_FILE`, `GRIZZLY_CALLBACK_URL`, `GRIZZLY_TIMEOUT`)
|
||||
3. `.grizzly.toml` in current directory
|
||||
4. `~/.config/grizzly/config.toml`
|
||||
|
||||
Example `~/.config/grizzly/config.toml`:
|
||||
```toml
|
||||
token_file = "~/.config/grizzly/token"
|
||||
callback_url = "http://127.0.0.1:42123/success"
|
||||
timeout = "5s"
|
||||
```
|
||||
|
||||
## Notes
|
||||
|
||||
- Bear must be running for commands to work
|
||||
- Note IDs are Bear's internal identifiers (visible in note info or via callbacks)
|
||||
- Use `--enable-callback` when you need to read data back from Bear
|
||||
- Some operations require a valid token (add-text, tags, open-note --selected)
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: bird
|
||||
description: X/Twitter CLI for reading, searching, and posting via cookies or Sweetistics.
|
||||
homepage: https://bird.fast
|
||||
metadata: {"zee":{"emoji":"🐦","requires":{"bins":["bird"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/bird","bins":["bird"],"label":"Install bird (brew)"}]}}
|
||||
---
|
||||
|
||||
# bird
|
||||
|
||||
Use `bird` to read/search X and post tweets/replies.
|
||||
|
||||
Quick start
|
||||
- `bird whoami`
|
||||
- `bird read <url-or-id>`
|
||||
- `bird thread <url-or-id>`
|
||||
- `bird search "query" -n 5`
|
||||
|
||||
Posting (confirm with user first)
|
||||
- `bird tweet "text"`
|
||||
- `bird reply <id-or-url> "text"`
|
||||
|
||||
Auth sources
|
||||
- Browser cookies (default: Firefox/Chrome)
|
||||
- Sweetistics API: set `SWEETISTICS_API_KEY` or use `--engine sweetistics`
|
||||
- Check sources: `bird check`
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
name: blogwatcher
|
||||
description: Monitor blogs and RSS/Atom feeds for updates using the blogwatcher CLI.
|
||||
homepage: https://github.com/Hyaxia/blogwatcher
|
||||
metadata: {"zee":{"emoji":"📰","requires":{"bins":["blogwatcher"]},"install":[{"id":"go","kind":"go","module":"github.com/Hyaxia/blogwatcher/cmd/blogwatcher@latest","bins":["blogwatcher"],"label":"Install blogwatcher (go)"}]}}
|
||||
---
|
||||
|
||||
# blogwatcher
|
||||
|
||||
Track blog and RSS/Atom feed updates with the `blogwatcher` CLI.
|
||||
|
||||
Install
|
||||
- Go: `go install github.com/Hyaxia/blogwatcher/cmd/blogwatcher@latest`
|
||||
|
||||
Quick start
|
||||
- `blogwatcher --help`
|
||||
|
||||
Common commands
|
||||
- Add a blog: `blogwatcher add "My Blog" https://example.com`
|
||||
- List blogs: `blogwatcher blogs`
|
||||
- Scan for updates: `blogwatcher scan`
|
||||
- List articles: `blogwatcher articles`
|
||||
- Mark an article read: `blogwatcher read 1`
|
||||
- Mark all articles read: `blogwatcher read-all`
|
||||
- Remove a blog: `blogwatcher remove "My Blog"`
|
||||
|
||||
Example output
|
||||
```
|
||||
$ blogwatcher blogs
|
||||
Tracked blogs (1):
|
||||
|
||||
xkcd
|
||||
URL: https://xkcd.com
|
||||
```
|
||||
```
|
||||
$ blogwatcher scan
|
||||
Scanning 1 blog(s)...
|
||||
|
||||
xkcd
|
||||
Source: RSS | Found: 4 | New: 4
|
||||
|
||||
Found 4 new article(s) total!
|
||||
```
|
||||
|
||||
Notes
|
||||
- Use `blogwatcher <command> --help` to discover flags and options.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
name: blucli
|
||||
description: BluOS CLI (blu) for discovery, playback, grouping, and volume.
|
||||
homepage: https://blucli.sh
|
||||
metadata: {"zee":{"emoji":"🫐","requires":{"bins":["blu"]},"install":[{"id":"go","kind":"go","module":"github.com/steipete/blucli/cmd/blu@latest","bins":["blu"],"label":"Install blucli (go)"}]}}
|
||||
---
|
||||
|
||||
# blucli (blu)
|
||||
|
||||
Use `blu` to control Bluesound/NAD players.
|
||||
|
||||
Quick start
|
||||
- `blu devices` (pick target)
|
||||
- `blu --device <id> status`
|
||||
- `blu play|pause|stop`
|
||||
- `blu volume set 15`
|
||||
|
||||
Target selection (in priority order)
|
||||
- `--device <id|name|alias>`
|
||||
- `BLU_DEVICE`
|
||||
- config default (if set)
|
||||
|
||||
Common tasks
|
||||
- Grouping: `blu group status|add|remove`
|
||||
- TuneIn search/play: `blu tunein search "query"`, `blu tunein play "query"`
|
||||
|
||||
Prefer `--json` for scripts. Confirm the target device before changing playback.
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: brave-search
|
||||
description: Web search and content extraction via Brave Search API.
|
||||
homepage: https://brave.com/search/api
|
||||
metadata: {"zee":{"emoji":"🦁","requires":{"bins":["node"],"env":["BRAVE_API_KEY"]},"primaryEnv":"BRAVE_API_KEY"}}
|
||||
---
|
||||
|
||||
# Brave Search
|
||||
|
||||
Headless web search (and lightweight content extraction) using Brave Search API. No browser required.
|
||||
|
||||
## Search
|
||||
|
||||
```bash
|
||||
node {baseDir}/scripts/search.mjs "query"
|
||||
node {baseDir}/scripts/search.mjs "query" -n 10
|
||||
node {baseDir}/scripts/search.mjs "query" --content
|
||||
node {baseDir}/scripts/search.mjs "query" -n 3 --content
|
||||
```
|
||||
|
||||
## Extract a page
|
||||
|
||||
```bash
|
||||
node {baseDir}/scripts/content.mjs "https://example.com/article"
|
||||
```
|
||||
|
||||
Notes:
|
||||
- Needs `BRAVE_API_KEY`.
|
||||
- Content extraction is best-effort (good for articles; not for app-like sites).
|
||||
- If a site is blocked or too JS-heavy, prefer the `summarize` skill (it can use a Firecrawl fallback).
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
function usage() {
|
||||
console.error(`Usage: content.mjs <url>`);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
export async function fetchAsMarkdown(url) {
|
||||
const resp = await fetch(url, {
|
||||
headers: { "User-Agent": "clawdbot-brave-search/1.0" },
|
||||
});
|
||||
const html = await resp.text();
|
||||
|
||||
// Very lightweight “readability-ish” extraction without dependencies:
|
||||
// - drop script/style/nav/footer
|
||||
// - strip tags
|
||||
// - keep paragraphs
|
||||
const cleaned = html
|
||||
.replace(/<script[\s\S]*?<\/script>/gi, " ")
|
||||
.replace(/<style[\s\S]*?<\/style>/gi, " ")
|
||||
.replace(/<(nav|footer|header)[\s\S]*?<\/\1>/gi, " ")
|
||||
.replace(/<br\s*\/?>/gi, "\n")
|
||||
.replace(/<\/p>/gi, "\n\n")
|
||||
.replace(/<\/div>/gi, "\n")
|
||||
.replace(/<[^>]+>/g, " ")
|
||||
.replace(/ /g, " ")
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/\s+\n/g, "\n")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.replace(/[ \t]{2,}/g, " ")
|
||||
.trim();
|
||||
|
||||
if (!resp.ok) {
|
||||
return `> Fetch failed (${resp.status}).\n\n${cleaned.slice(0, 2000)}\n`;
|
||||
}
|
||||
|
||||
const paras = cleaned
|
||||
.split("\n\n")
|
||||
.map((p) => p.trim())
|
||||
.filter(Boolean)
|
||||
.slice(0, 30);
|
||||
|
||||
return paras.map((p) => `- ${p}`).join("\n") + "\n";
|
||||
}
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
if (args.length === 0 || args[0] === "-h" || args[0] === "--help") usage();
|
||||
const url = args[0];
|
||||
process.stdout.write(await fetchAsMarkdown(url));
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
function usage() {
|
||||
console.error(`Usage: search.mjs "query" [-n 5] [--content]`);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
if (args.length === 0 || args[0] === "-h" || args[0] === "--help") usage();
|
||||
|
||||
const query = args[0];
|
||||
let n = 5;
|
||||
let withContent = false;
|
||||
|
||||
for (let i = 1; i < args.length; i++) {
|
||||
const a = args[i];
|
||||
if (a === "-n") {
|
||||
n = Number.parseInt(args[i + 1] ?? "5", 10);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (a === "--content") {
|
||||
withContent = true;
|
||||
continue;
|
||||
}
|
||||
console.error(`Unknown arg: ${a}`);
|
||||
usage();
|
||||
}
|
||||
|
||||
const apiKey = (process.env.BRAVE_API_KEY ?? "").trim();
|
||||
if (!apiKey) {
|
||||
console.error("Missing BRAVE_API_KEY");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const endpoint = new URL("https://api.search.brave.com/res/v1/web/search");
|
||||
endpoint.searchParams.set("q", query);
|
||||
endpoint.searchParams.set("count", String(Math.max(1, Math.min(n, 20))));
|
||||
endpoint.searchParams.set("text_decorations", "false");
|
||||
endpoint.searchParams.set("safesearch", "moderate");
|
||||
|
||||
const resp = await fetch(endpoint, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"X-Subscription-Token": apiKey,
|
||||
},
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const text = await resp.text().catch(() => "");
|
||||
throw new Error(`Brave Search failed (${resp.status}): ${text}`);
|
||||
}
|
||||
|
||||
const data = await resp.json();
|
||||
const results = (data?.web?.results ?? []).slice(0, n);
|
||||
|
||||
const lines = [];
|
||||
for (const r of results) {
|
||||
const title = String(r?.title ?? "").trim();
|
||||
const url = String(r?.url ?? "").trim();
|
||||
const desc = String(r?.description ?? "").trim();
|
||||
if (!title || !url) continue;
|
||||
lines.push(`- ${title}\n ${url}${desc ? `\n ${desc}` : ""}`);
|
||||
}
|
||||
|
||||
process.stdout.write(lines.join("\n\n") + "\n");
|
||||
|
||||
if (!withContent) process.exit(0);
|
||||
|
||||
process.stdout.write("\n---\n\n");
|
||||
for (const r of results) {
|
||||
const title = String(r?.title ?? "").trim();
|
||||
const url = String(r?.url ?? "").trim();
|
||||
if (!url) continue;
|
||||
process.stdout.write(`# ${title || url}\n${url}\n\n`);
|
||||
const child = await import("./content.mjs");
|
||||
const text = await child.fetchAsMarkdown(url);
|
||||
process.stdout.write(text.trimEnd() + "\n\n");
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: camsnap
|
||||
description: Capture frames or clips from RTSP/ONVIF cameras.
|
||||
homepage: https://camsnap.ai
|
||||
metadata: {"zee":{"emoji":"📸","requires":{"bins":["camsnap"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/camsnap","bins":["camsnap"],"label":"Install camsnap (brew)"}]}}
|
||||
---
|
||||
|
||||
# camsnap
|
||||
|
||||
Use `camsnap` to grab snapshots, clips, or motion events from configured cameras.
|
||||
|
||||
Setup
|
||||
- Config file: `~/.config/camsnap/config.yaml`
|
||||
- Add camera: `camsnap add --name kitchen --host 192.168.0.10 --user user --pass pass`
|
||||
|
||||
Common commands
|
||||
- Discover: `camsnap discover --info`
|
||||
- Snapshot: `camsnap snap kitchen --out shot.jpg`
|
||||
- Clip: `camsnap clip kitchen --dur 5s --out clip.mp4`
|
||||
- Motion watch: `camsnap watch kitchen --threshold 0.2 --action '...'`
|
||||
- Doctor: `camsnap doctor --probe`
|
||||
|
||||
Notes
|
||||
- Requires `ffmpeg` on PATH.
|
||||
- Prefer a short test capture before longer clips.
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
name: clawdhub
|
||||
description: Use the ClawdHub CLI to search, install, update, and publish agent skills from clawdhub.com. Use when you need to fetch new skills on the fly, sync installed skills to latest or a specific version, or publish new/updated skill folders with the npm-installed clawdhub CLI.
|
||||
metadata: {"zee":{"requires":{"bins":["clawdhub"]},"install":[{"id":"node","kind":"node","package":"clawdhub","bins":["clawdhub"],"label":"Install ClawdHub CLI (npm)"}]}}
|
||||
---
|
||||
|
||||
# ClawdHub CLI
|
||||
|
||||
Install
|
||||
```bash
|
||||
npm i -g clawdhub
|
||||
```
|
||||
|
||||
Auth (publish)
|
||||
```bash
|
||||
clawdhub login
|
||||
clawdhub whoami
|
||||
```
|
||||
|
||||
Search
|
||||
```bash
|
||||
clawdhub search "postgres backups"
|
||||
```
|
||||
|
||||
Install
|
||||
```bash
|
||||
clawdhub install my-skill
|
||||
clawdhub install my-skill --version 1.2.3
|
||||
```
|
||||
|
||||
Update (hash-based match + upgrade)
|
||||
```bash
|
||||
clawdhub update my-skill
|
||||
clawdhub update my-skill --version 1.2.3
|
||||
clawdhub update --all
|
||||
clawdhub update my-skill --force
|
||||
clawdhub update --all --no-input --force
|
||||
```
|
||||
|
||||
List
|
||||
```bash
|
||||
clawdhub list
|
||||
```
|
||||
|
||||
Publish
|
||||
```bash
|
||||
clawdhub publish ./my-skill --slug my-skill --name "My Skill" --version 1.2.0 --changelog "Fixes + docs"
|
||||
```
|
||||
|
||||
Notes
|
||||
- Default registry: https://clawdhub.com (override with CLAWDHUB_REGISTRY or --registry)
|
||||
- Default workdir: cwd; install dir: ./skills (override with --workdir / --dir)
|
||||
- Update command hashes local files, resolves matching version, and upgrades to latest unless --version is set
|
||||
@@ -0,0 +1,274 @@
|
||||
---
|
||||
name: coding-agent
|
||||
description: Run Codex CLI, Claude Code, agent-core, or Pi Coding Agent via background process for programmatic control.
|
||||
metadata: {"zee":{"emoji":"🧩","requires":{"anyBins":["claude","codex","agent-core","pi"]}}}
|
||||
---
|
||||
|
||||
# Coding Agent (background-first)
|
||||
|
||||
Use **bash background mode** for non-interactive coding work. For interactive coding sessions, use the **tmux** skill (always, except very simple one-shot prompts).
|
||||
|
||||
## The Pattern: workdir + background
|
||||
|
||||
```bash
|
||||
# Create temp space for chats/scratch work
|
||||
SCRATCH=$(mktemp -d)
|
||||
|
||||
# Start agent in target directory ("little box" - only sees relevant files)
|
||||
bash workdir:$SCRATCH background:true command:"<agent command>"
|
||||
# Or for project work:
|
||||
bash workdir:~/project/folder background:true command:"<agent command>"
|
||||
# Returns sessionId for tracking
|
||||
|
||||
# Monitor progress
|
||||
process action:log sessionId:XXX
|
||||
|
||||
# Check if done
|
||||
process action:poll sessionId:XXX
|
||||
|
||||
# Send input (if agent asks a question)
|
||||
process action:write sessionId:XXX data:"y"
|
||||
|
||||
# Kill if needed
|
||||
process action:kill sessionId:XXX
|
||||
```
|
||||
|
||||
**Why workdir matters:** Agent wakes up in a focused directory, doesn't wander off reading unrelated files (like your soul.md 😅).
|
||||
|
||||
---
|
||||
|
||||
## Codex CLI
|
||||
|
||||
**Model:** `gpt-5.2-codex` is the default (set in ~/.codex/config.toml)
|
||||
|
||||
### Building/Creating (use --full-auto or --yolo)
|
||||
```bash
|
||||
# --full-auto: sandboxed but auto-approves in workspace
|
||||
bash workdir:~/project background:true command:"codex exec --full-auto \"Build a snake game with dark theme\""
|
||||
|
||||
# --yolo: NO sandbox, NO approvals (fastest, most dangerous)
|
||||
bash workdir:~/project background:true command:"codex --yolo \"Build a snake game with dark theme\""
|
||||
|
||||
# Note: --yolo is a shortcut for --dangerously-bypass-approvals-and-sandbox
|
||||
```
|
||||
|
||||
### Reviewing PRs (vanilla, no flags)
|
||||
|
||||
**⚠️ CRITICAL: Never review PRs in Zee's own project folder!**
|
||||
- Either use the project where the PR is submitted (if it's NOT ~/Projects/zee)
|
||||
- Or clone to a temp folder first
|
||||
|
||||
```bash
|
||||
# Option 1: Review in the actual project (if NOT zee)
|
||||
bash workdir:~/Projects/some-other-repo background:true command:"codex review --base main"
|
||||
|
||||
# Option 2: Clone to temp folder for safe review (REQUIRED for zee PRs!)
|
||||
REVIEW_DIR=$(mktemp -d)
|
||||
git clone https://github.com/zee/zee.git $REVIEW_DIR
|
||||
cd $REVIEW_DIR && gh pr checkout 130
|
||||
bash workdir:$REVIEW_DIR background:true command:"codex review --base origin/main"
|
||||
# Clean up after: rm -rf $REVIEW_DIR
|
||||
|
||||
# Option 3: Use git worktree (keeps main intact)
|
||||
git worktree add /tmp/pr-130-review pr-130-branch
|
||||
bash workdir:/tmp/pr-130-review background:true command:"codex review --base main"
|
||||
```
|
||||
|
||||
**Why?** Checking out branches in the running Zee repo can break the live instance!
|
||||
|
||||
### Batch PR Reviews (parallel army!)
|
||||
```bash
|
||||
# Fetch all PR refs first
|
||||
git fetch origin '+refs/pull/*/head:refs/remotes/origin/pr/*'
|
||||
|
||||
# Deploy the army - one Codex per PR!
|
||||
bash workdir:~/project background:true command:"codex exec \"Review PR #86. git diff origin/main...origin/pr/86\""
|
||||
bash workdir:~/project background:true command:"codex exec \"Review PR #87. git diff origin/main...origin/pr/87\""
|
||||
bash workdir:~/project background:true command:"codex exec \"Review PR #95. git diff origin/main...origin/pr/95\""
|
||||
# ... repeat for all PRs
|
||||
|
||||
# Monitor all
|
||||
process action:list
|
||||
|
||||
# Get results and post to GitHub
|
||||
process action:log sessionId:XXX
|
||||
gh pr comment <PR#> --body "<review content>"
|
||||
```
|
||||
|
||||
### Tips for PR Reviews
|
||||
- **Fetch refs first:** `git fetch origin '+refs/pull/*/head:refs/remotes/origin/pr/*'`
|
||||
- **Use git diff:** Tell Codex to use `git diff origin/main...origin/pr/XX`
|
||||
- **Don't checkout:** Multiple parallel reviews = don't let them change branches
|
||||
- **Post results:** Use `gh pr comment` to post reviews to GitHub
|
||||
|
||||
---
|
||||
|
||||
## Claude Code
|
||||
|
||||
```bash
|
||||
bash workdir:~/project background:true command:"claude \"Your task\""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Agent-Core
|
||||
|
||||
```bash
|
||||
bash workdir:~/project background:true command:"agent-core run \"Your task\""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pi Coding Agent
|
||||
|
||||
```bash
|
||||
# Install: npm install -g @mariozechner/pi-coding-agent
|
||||
bash workdir:~/project background:true command:"pi \"Your task\""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Pi flags (common)
|
||||
|
||||
- `--print` / `-p`: non-interactive; runs prompt and exits.
|
||||
- `--provider <name>`: pick provider (default: google).
|
||||
- `--model <id>`: pick model (default: gemini-2.5-flash).
|
||||
- `--api-key <key>`: override API key (defaults to env vars).
|
||||
|
||||
Examples:
|
||||
|
||||
```bash
|
||||
# Set provider + model, non-interactive
|
||||
bash workdir:~/project background:true command:"pi --provider openai --model gpt-4o-mini -p \"Summarize src/\""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## tmux (interactive sessions)
|
||||
|
||||
Use the tmux skill for interactive coding sessions (always, except very simple one-shot prompts). Prefer bash background mode for non-interactive runs.
|
||||
|
||||
---
|
||||
|
||||
## Parallel Issue Fixing with git worktrees + tmux
|
||||
|
||||
For fixing multiple issues in parallel, use git worktrees (isolated branches) + tmux sessions:
|
||||
|
||||
```bash
|
||||
# 1. Clone repo to temp location
|
||||
cd /tmp && git clone git@github.com:user/repo.git repo-worktrees
|
||||
cd repo-worktrees
|
||||
|
||||
# 2. Create worktrees for each issue (isolated branches!)
|
||||
git worktree add -b fix/issue-78 /tmp/issue-78 main
|
||||
git worktree add -b fix/issue-99 /tmp/issue-99 main
|
||||
|
||||
# 3. Set up tmux sessions
|
||||
SOCKET="${TMPDIR:-/tmp}/codex-fixes.sock"
|
||||
tmux -S "$SOCKET" new-session -d -s fix-78
|
||||
tmux -S "$SOCKET" new-session -d -s fix-99
|
||||
|
||||
# 4. Launch Codex in each (after pnpm install!)
|
||||
tmux -S "$SOCKET" send-keys -t fix-78 "cd /tmp/issue-78 && pnpm install && codex --yolo 'Fix issue #78: <description>. Commit and push.'" Enter
|
||||
tmux -S "$SOCKET" send-keys -t fix-99 "cd /tmp/issue-99 && pnpm install && codex --yolo 'Fix issue #99: <description>. Commit and push.'" Enter
|
||||
|
||||
# 5. Monitor progress
|
||||
tmux -S "$SOCKET" capture-pane -p -t fix-78 -S -30
|
||||
tmux -S "$SOCKET" capture-pane -p -t fix-99 -S -30
|
||||
|
||||
# 6. Check if done (prompt returned)
|
||||
tmux -S "$SOCKET" capture-pane -p -t fix-78 -S -3 | grep -q "❯" && echo "Done!"
|
||||
|
||||
# 7. Create PRs after fixes
|
||||
cd /tmp/issue-78 && git push -u origin fix/issue-78
|
||||
gh pr create --repo user/repo --head fix/issue-78 --title "fix: ..." --body "..."
|
||||
|
||||
# 8. Cleanup
|
||||
tmux -S "$SOCKET" kill-server
|
||||
git worktree remove /tmp/issue-78
|
||||
git worktree remove /tmp/issue-99
|
||||
```
|
||||
|
||||
**Why worktrees?** Each Codex works in isolated branch, no conflicts. Can run 5+ parallel fixes!
|
||||
|
||||
**Why tmux over bash background?** Codex is interactive — needs TTY for proper output. tmux provides persistent sessions with full history capture.
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Rules
|
||||
|
||||
1. **Respect tool choice** — if user asks for Codex, use Codex. NEVER offer to build it yourself!
|
||||
2. **Be patient** — don't kill sessions because they're "slow"
|
||||
3. **Monitor with process:log** — check progress without interfering
|
||||
4. **--full-auto for building** — auto-approves changes
|
||||
5. **vanilla for reviewing** — no special flags needed
|
||||
6. **Parallel is OK** — run many Codex processes at once for batch work
|
||||
7. **NEVER start Codex in ~/clawd/** — it'll read your soul docs and get weird ideas about the org chart! Use the target project dir or /tmp for blank slate chats
|
||||
8. **NEVER checkout branches in ~/Projects/zee/** — that's the LIVE Zee instance! Clone to /tmp or use git worktree for PR reviews
|
||||
|
||||
---
|
||||
|
||||
## PR Template (The Razor Standard)
|
||||
|
||||
When submitting PRs to external repos, use this format for quality & maintainer-friendliness:
|
||||
|
||||
````markdown
|
||||
## Original Prompt
|
||||
[Exact request/problem statement]
|
||||
|
||||
## What this does
|
||||
[High-level description]
|
||||
|
||||
**Features:**
|
||||
- [Key feature 1]
|
||||
- [Key feature 2]
|
||||
|
||||
**Example usage:**
|
||||
```bash
|
||||
# Example
|
||||
command example
|
||||
```
|
||||
|
||||
## Feature intent (maintainer-friendly)
|
||||
[Why useful, how it fits, workflows it enables]
|
||||
|
||||
## Prompt history (timestamped)
|
||||
- YYYY-MM-DD HH:MM UTC: [Step 1]
|
||||
- YYYY-MM-DD HH:MM UTC: [Step 2]
|
||||
|
||||
## How I tested
|
||||
**Manual verification:**
|
||||
1. [Test step] - Output: `[result]`
|
||||
2. [Test step] - Result: [result]
|
||||
|
||||
**Files tested:**
|
||||
- [Detail]
|
||||
- [Edge cases]
|
||||
|
||||
## Session logs (implementation)
|
||||
- [What was researched]
|
||||
- [What was discovered]
|
||||
- [Time spent]
|
||||
|
||||
## Implementation details
|
||||
**New files:**
|
||||
- `path/file.ts` - [description]
|
||||
|
||||
**Modified files:**
|
||||
- `path/file.ts` - [change]
|
||||
|
||||
**Technical notes:**
|
||||
- [Detail 1]
|
||||
- [Detail 2]
|
||||
|
||||
---
|
||||
*Submitted by Razor 🥷 - Mariano's AI agent*
|
||||
````
|
||||
|
||||
**Key principles:**
|
||||
1. Human-written description (no AI slop)
|
||||
2. Feature intent for maintainers
|
||||
3. Timestamped prompt history
|
||||
4. Session logs if using Codex/agent
|
||||
|
||||
**Example:** https://github.com/steipete/bird/pull/22
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
name: concept-exploration
|
||||
description: Deep understanding through Socratic questioning and concept mapping
|
||||
triggers:
|
||||
- explain
|
||||
- understand
|
||||
- why does
|
||||
- how does
|
||||
- concept
|
||||
- theory
|
||||
---
|
||||
|
||||
# Concept Exploration
|
||||
|
||||
Build deep understanding through active inquiry, not passive reading.
|
||||
|
||||
## Learning Approach
|
||||
|
||||
Inspired by Math Academy and Feynman technique:
|
||||
|
||||
1. **Can you explain it simply?** If not, you don't understand it
|
||||
2. **What are the prerequisites?** Map dependencies
|
||||
3. **What are the edge cases?** Test understanding limits
|
||||
4. **How does it connect?** Link to known concepts
|
||||
|
||||
## Exploration Methods
|
||||
|
||||
### Socratic Questioning
|
||||
Ask probing questions:
|
||||
- What do you mean by X?
|
||||
- How did you arrive at that?
|
||||
- What would be a counterexample?
|
||||
- What assumptions are you making?
|
||||
- What would change if...?
|
||||
|
||||
### Concept Mapping
|
||||
```
|
||||
┌─────────────┐
|
||||
│ Limits │
|
||||
└──────┬──────┘
|
||||
│ enables
|
||||
┌───────────┼───────────┐
|
||||
▼ ▼ ▼
|
||||
┌────────┐ ┌────────┐ ┌────────┐
|
||||
│Derivat.│ │Continu.│ │Integral│
|
||||
└────────┘ └────────┘ └────────┘
|
||||
```
|
||||
|
||||
### Prerequisite Check
|
||||
Before teaching concept X:
|
||||
1. List prerequisites A, B, C
|
||||
2. Quick-check student knows A, B, C
|
||||
3. If gap found, address prerequisite first
|
||||
4. Only then proceed to X
|
||||
|
||||
## Mastery Criteria
|
||||
|
||||
A concept is "understood" when student can:
|
||||
- [ ] Explain it in own words
|
||||
- [ ] Give examples and non-examples
|
||||
- [ ] Apply it to novel problems
|
||||
- [ ] Identify when it's applicable
|
||||
- [ ] Explain why it works (not just how)
|
||||
|
||||
## Memory Integration
|
||||
|
||||
Track concept mastery:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "johny/concepts",
|
||||
key: topic,
|
||||
value: {
|
||||
topic,
|
||||
prerequisites: ["limits", "continuity"],
|
||||
masteryLevel: 0.85, // 0-1 scale
|
||||
lastAssessed: new Date(),
|
||||
canExplain: true,
|
||||
canApply: true,
|
||||
canGeneralize: false, // needs more work
|
||||
commonMisconceptions: ["confuses with..."]
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Knowledge Graph
|
||||
|
||||
Build interconnected understanding:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "johny/knowledge-graph",
|
||||
key: "edges",
|
||||
value: {
|
||||
edges: [
|
||||
{ from: "derivative", to: "limit", relation: "defined-by" },
|
||||
{ from: "integral", to: "antiderivative", relation: "inverse-of" },
|
||||
{ from: "ftc", to: "derivative", relation: "connects" },
|
||||
{ from: "ftc", to: "integral", relation: "connects" }
|
||||
]
|
||||
}
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,92 @@
|
||||
---
|
||||
name: deliberate-practice
|
||||
description: Structured practice sessions with immediate feedback for skill acquisition
|
||||
triggers:
|
||||
- practice
|
||||
- drill
|
||||
- exercise
|
||||
- train
|
||||
- learn by doing
|
||||
---
|
||||
|
||||
# Deliberate Practice
|
||||
|
||||
Facilitate focused, goal-oriented practice sessions based on Anders Ericsson's deliberate practice principles.
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Specific Goals**: Each session targets a specific sub-skill
|
||||
2. **Full Attention**: Concentrated effort, no distractions
|
||||
3. **Immediate Feedback**: Know if you're right/wrong instantly
|
||||
4. **Stretch Zone**: Just beyond current ability (not too easy, not impossible)
|
||||
5. **Repetition with Refinement**: Repeat until mastery, then move on
|
||||
|
||||
## Practice Session Structure
|
||||
|
||||
### 1. Warm-up (5 min)
|
||||
- Review prerequisites
|
||||
- Recall relevant concepts
|
||||
- Set specific goal for session
|
||||
|
||||
### 2. Focused Practice (20-25 min)
|
||||
- Work on problems at edge of ability
|
||||
- Get immediate feedback on each attempt
|
||||
- Identify specific errors and why they occurred
|
||||
|
||||
### 3. Cool-down (5 min)
|
||||
- Summarize what was learned
|
||||
- Note persistent difficulties
|
||||
- Queue items for spaced repetition
|
||||
|
||||
## Difficulty Calibration
|
||||
|
||||
```
|
||||
Too Easy │ Optimal Zone │ Too Hard
|
||||
────────────┼──────────────┼──────────
|
||||
< 70% right │ 70-85% right │ > 85% wrong
|
||||
Boring │ Challenging │ Frustrating
|
||||
No growth │ Maximum │ No growth
|
||||
│ learning │
|
||||
```
|
||||
|
||||
## Feedback Patterns
|
||||
|
||||
### Immediate Correction
|
||||
When student makes error:
|
||||
1. Show correct answer
|
||||
2. Explain why it's correct
|
||||
3. Have them redo the problem
|
||||
4. Queue similar problem for later
|
||||
|
||||
### Error Analysis
|
||||
Track error types:
|
||||
- Conceptual (misunderstanding)
|
||||
- Procedural (wrong steps)
|
||||
- Careless (attention lapse)
|
||||
- Knowledge gap (missing prerequisite)
|
||||
|
||||
## Memory Integration
|
||||
|
||||
Store practice data:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "johny/practice",
|
||||
key: `session/${date}/${topic}`,
|
||||
value: {
|
||||
topic,
|
||||
problemsAttempted: 15,
|
||||
accuracy: 0.73,
|
||||
timeSpent: 25,
|
||||
errorsBy Type: { conceptual: 2, procedural: 2 },
|
||||
itemsForReview: ["integration-by-parts", "trig-substitution"]
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Spaced Repetition Queue
|
||||
|
||||
Items needing review are scheduled based on performance:
|
||||
- First error: Review in 1 day
|
||||
- Second error: Review in 4 hours
|
||||
- Correct after error: Review in 3 days
|
||||
- Consistently correct: Review in 7 days, then 14, 30...
|
||||
@@ -0,0 +1,369 @@
|
||||
---
|
||||
name: discord
|
||||
description: Use when you need to control Discord from Zee via the discord tool: send messages, react, post or upload stickers, upload emojis, run polls, manage threads/pins/search, fetch permissions or member/role/channel info, or handle moderation actions in Discord DMs or channels.
|
||||
---
|
||||
|
||||
# Discord Actions
|
||||
|
||||
## Overview
|
||||
|
||||
Use `discord` to manage messages, reactions, threads, polls, and moderation. You can disable groups via `discord.actions.*` (defaults to enabled, except roles/moderation). The tool uses the bot token configured for Zee.
|
||||
|
||||
## Inputs to collect
|
||||
|
||||
- For reactions: `channelId`, `messageId`, and an `emoji`.
|
||||
- For stickers/polls/sendMessage: a `to` target (`channel:<id>` or `user:<id>`). Optional `content` text.
|
||||
- Polls also need a `question` plus 2–10 `answers`.
|
||||
- For media: `mediaUrl` with `file:///path` for local files or `https://...` for remote.
|
||||
- For emoji uploads: `guildId`, `name`, `mediaUrl`, optional `roleIds` (limit 256KB, PNG/JPG/GIF).
|
||||
- For sticker uploads: `guildId`, `name`, `description`, `tags`, `mediaUrl` (limit 512KB, PNG/APNG/Lottie JSON).
|
||||
|
||||
Message context lines include `discord message id` and `channel` fields you can reuse directly.
|
||||
|
||||
**Note:** `sendMessage` uses `to: "channel:<id>"` format, not `channelId`. Other actions like `react`, `readMessages`, `editMessage` use `channelId` directly.
|
||||
|
||||
## Actions
|
||||
|
||||
### React to a message
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "react",
|
||||
"channelId": "123",
|
||||
"messageId": "456",
|
||||
"emoji": "✅"
|
||||
}
|
||||
```
|
||||
|
||||
### List reactions + users
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "reactions",
|
||||
"channelId": "123",
|
||||
"messageId": "456",
|
||||
"limit": 100
|
||||
}
|
||||
```
|
||||
|
||||
### Send a sticker
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "sticker",
|
||||
"to": "channel:123",
|
||||
"stickerIds": ["9876543210"],
|
||||
"content": "Nice work!"
|
||||
}
|
||||
```
|
||||
|
||||
- Up to 3 sticker IDs per message.
|
||||
- `to` can be `user:<id>` for DMs.
|
||||
|
||||
### Upload a custom emoji
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "emojiUpload",
|
||||
"guildId": "999",
|
||||
"name": "party_blob",
|
||||
"mediaUrl": "file:///tmp/party.png",
|
||||
"roleIds": ["222"]
|
||||
}
|
||||
```
|
||||
|
||||
- Emoji images must be PNG/JPG/GIF and <= 256KB.
|
||||
- `roleIds` is optional; omit to make the emoji available to everyone.
|
||||
|
||||
### Upload a sticker
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "stickerUpload",
|
||||
"guildId": "999",
|
||||
"name": "zee_wave",
|
||||
"description": "Zee waving hello",
|
||||
"tags": "👋",
|
||||
"mediaUrl": "file:///tmp/wave.png"
|
||||
}
|
||||
```
|
||||
|
||||
- Stickers require `name`, `description`, and `tags`.
|
||||
- Uploads must be PNG/APNG/Lottie JSON and <= 512KB.
|
||||
|
||||
### Create a poll
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "poll",
|
||||
"to": "channel:123",
|
||||
"question": "Lunch?",
|
||||
"answers": ["Pizza", "Sushi", "Salad"],
|
||||
"allowMultiselect": false,
|
||||
"durationHours": 24,
|
||||
"content": "Vote now"
|
||||
}
|
||||
```
|
||||
|
||||
- `durationHours` defaults to 24; max 32 days (768 hours).
|
||||
|
||||
### Check bot permissions for a channel
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "permissions",
|
||||
"channelId": "123"
|
||||
}
|
||||
```
|
||||
|
||||
## Ideas to try
|
||||
|
||||
- React with ✅/⚠️ to mark status updates.
|
||||
- Post a quick poll for release decisions or meeting times.
|
||||
- Send celebratory stickers after successful deploys.
|
||||
- Upload new emojis/stickers for release moments.
|
||||
- Run weekly “priority check” polls in team channels.
|
||||
- DM stickers as acknowledgements when a user’s request is completed.
|
||||
|
||||
## Action gating
|
||||
|
||||
Use `discord.actions.*` to disable action groups:
|
||||
- `reactions` (react + reactions list + emojiList)
|
||||
- `stickers`, `polls`, `permissions`, `messages`, `threads`, `pins`, `search`
|
||||
- `emojiUploads`, `stickerUploads`
|
||||
- `memberInfo`, `roleInfo`, `channelInfo`, `voiceStatus`, `events`
|
||||
- `roles` (role add/remove, default `false`)
|
||||
- `moderation` (timeout/kick/ban, default `false`)
|
||||
### Read recent messages
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "readMessages",
|
||||
"channelId": "123",
|
||||
"limit": 20
|
||||
}
|
||||
```
|
||||
|
||||
### Send/edit/delete a message
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "sendMessage",
|
||||
"to": "channel:123",
|
||||
"content": "Hello from Zee"
|
||||
}
|
||||
```
|
||||
|
||||
**With media attachment:**
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "sendMessage",
|
||||
"to": "channel:123",
|
||||
"content": "Check out this audio!",
|
||||
"mediaUrl": "file:///tmp/audio.mp3"
|
||||
}
|
||||
```
|
||||
|
||||
- `to` uses format `channel:<id>` or `user:<id>` for DMs (not `channelId`!)
|
||||
- `mediaUrl` supports local files (`file:///path/to/file`) and remote URLs (`https://...`)
|
||||
- Optional `replyTo` with a message ID to reply to a specific message
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "editMessage",
|
||||
"channelId": "123",
|
||||
"messageId": "456",
|
||||
"content": "Fixed typo"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "deleteMessage",
|
||||
"channelId": "123",
|
||||
"messageId": "456"
|
||||
}
|
||||
```
|
||||
|
||||
### Threads
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "threadCreate",
|
||||
"channelId": "123",
|
||||
"name": "Bug triage",
|
||||
"messageId": "456"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "threadList",
|
||||
"guildId": "999"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "threadReply",
|
||||
"channelId": "777",
|
||||
"content": "Replying in thread"
|
||||
}
|
||||
```
|
||||
|
||||
### Pins
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "pinMessage",
|
||||
"channelId": "123",
|
||||
"messageId": "456"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "listPins",
|
||||
"channelId": "123"
|
||||
}
|
||||
```
|
||||
|
||||
### Search messages
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "searchMessages",
|
||||
"guildId": "999",
|
||||
"content": "release notes",
|
||||
"channelIds": ["123", "456"],
|
||||
"limit": 10
|
||||
}
|
||||
```
|
||||
|
||||
### Member + role info
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "memberInfo",
|
||||
"guildId": "999",
|
||||
"userId": "111"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "roleInfo",
|
||||
"guildId": "999"
|
||||
}
|
||||
```
|
||||
|
||||
### List available custom emojis
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "emojiList",
|
||||
"guildId": "999"
|
||||
}
|
||||
```
|
||||
|
||||
### Role changes (disabled by default)
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "roleAdd",
|
||||
"guildId": "999",
|
||||
"userId": "111",
|
||||
"roleId": "222"
|
||||
}
|
||||
```
|
||||
|
||||
### Channel info
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "channelInfo",
|
||||
"channelId": "123"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "channelList",
|
||||
"guildId": "999"
|
||||
}
|
||||
```
|
||||
|
||||
### Voice status
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "voiceStatus",
|
||||
"guildId": "999",
|
||||
"userId": "111"
|
||||
}
|
||||
```
|
||||
|
||||
### Scheduled events
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "eventList",
|
||||
"guildId": "999"
|
||||
}
|
||||
```
|
||||
|
||||
### Moderation (disabled by default)
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "timeout",
|
||||
"guildId": "999",
|
||||
"userId": "111",
|
||||
"durationMinutes": 10
|
||||
}
|
||||
```
|
||||
|
||||
## Discord Writing Style Guide
|
||||
|
||||
**Keep it conversational!** Discord is a chat platform, not documentation.
|
||||
|
||||
### Do
|
||||
- Short, punchy messages (1-3 sentences ideal)
|
||||
- Multiple quick replies > one wall of text
|
||||
- Use emoji for tone/emphasis 🦞
|
||||
- Lowercase casual style is fine
|
||||
- Break up info into digestible chunks
|
||||
- Match the energy of the conversation
|
||||
|
||||
### Don't
|
||||
- No markdown tables (Discord renders them as ugly raw `| text |`)
|
||||
- No `## Headers` for casual chat (use **bold** or CAPS for emphasis)
|
||||
- Avoid multi-paragraph essays
|
||||
- Don't over-explain simple things
|
||||
- Skip the "I'd be happy to help!" fluff
|
||||
|
||||
### Formatting that works
|
||||
- **bold** for emphasis
|
||||
- `code` for technical terms
|
||||
- Lists for multiple items
|
||||
- > quotes for referencing
|
||||
- Wrap multiple links in `<>` to suppress embeds
|
||||
|
||||
### Example transformations
|
||||
|
||||
❌ Bad:
|
||||
```
|
||||
I'd be happy to help with that! Here's a comprehensive overview of the versioning strategies available:
|
||||
|
||||
## Semantic Versioning
|
||||
Semver uses MAJOR.MINOR.PATCH format where...
|
||||
|
||||
## Calendar Versioning
|
||||
CalVer uses date-based versions like...
|
||||
```
|
||||
|
||||
✅ Good:
|
||||
```
|
||||
versioning options: semver (1.2.3), calver (2026.01.04), or yolo (`latest` forever). what fits your release cadence?
|
||||
```
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
name: earnings-intelligence
|
||||
description: Analyze earnings reports, calls, and estimate revisions
|
||||
triggers:
|
||||
- earnings analysis
|
||||
- earnings call
|
||||
- earnings surprise
|
||||
- estimate revisions
|
||||
- quarterly results
|
||||
---
|
||||
|
||||
# Earnings Intelligence
|
||||
|
||||
Comprehensive earnings analysis and call intelligence.
|
||||
|
||||
## Pre-Earnings Research
|
||||
|
||||
### Upcoming Earnings
|
||||
```
|
||||
# Get earnings calendar
|
||||
obb.equity.calendar.earnings(start_date="2024-01-15", end_date="2024-01-31")
|
||||
|
||||
# Earnings estimates
|
||||
obb.equity.estimates.consensus(symbol="AAPL", provider="fmp")
|
||||
```
|
||||
|
||||
### Historical Performance
|
||||
```
|
||||
# Past earnings surprises
|
||||
obb.equity.fundamental.historical_eps(symbol="AAPL", provider="fmp")
|
||||
```
|
||||
|
||||
## Earnings Call Analysis
|
||||
|
||||
### Transcript Processing
|
||||
Using meeting intelligence integration:
|
||||
```
|
||||
# When an earnings call transcript is available
|
||||
from stanley.notes import NoteManager
|
||||
|
||||
notes = NoteManager()
|
||||
event = notes.create_event(
|
||||
symbol="AAPL",
|
||||
company_name="Apple Inc.",
|
||||
event_type="earnings_call",
|
||||
event_date="2024-01-25"
|
||||
)
|
||||
```
|
||||
|
||||
### Key Metrics to Track
|
||||
1. Revenue vs estimates
|
||||
2. EPS vs estimates
|
||||
3. Guidance changes
|
||||
4. Margin trends
|
||||
5. Key segment performance
|
||||
6. Management tone/confidence
|
||||
|
||||
## Post-Earnings Analysis
|
||||
|
||||
### Estimate Revisions
|
||||
```
|
||||
from stanley.research import analyze_estimate_revisions
|
||||
|
||||
revisions = analyze_estimate_revisions(
|
||||
symbol="AAPL",
|
||||
days_after_earnings=30
|
||||
)
|
||||
```
|
||||
|
||||
### Price Reaction
|
||||
```
|
||||
# Implied vs actual move
|
||||
obb.equity.price.historical(symbol="AAPL", start_date=earnings_date)
|
||||
```
|
||||
|
||||
## Memory Patterns
|
||||
|
||||
Store earnings insights:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "stanley/earnings",
|
||||
key: `${symbol}/${quarter}`,
|
||||
value: {
|
||||
date: earningsDate,
|
||||
epsActual: 1.52,
|
||||
epsEstimate: 1.48,
|
||||
surprise: 0.027,
|
||||
guidance: "raised",
|
||||
keyTakeaways: ["..."],
|
||||
analystReactions: ["..."]
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Automated Workflows
|
||||
|
||||
### Pre-Earnings Alert
|
||||
Triggered by earnings calendar:
|
||||
1. Get consensus estimates
|
||||
2. Review prior quarter
|
||||
3. Set up event note
|
||||
4. Identify key metrics to watch
|
||||
|
||||
### Post-Earnings Summary
|
||||
Day after earnings:
|
||||
1. Pull actual results
|
||||
2. Calculate surprise
|
||||
3. Get analyst revisions
|
||||
4. Update thesis if needed
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: eightctl
|
||||
description: Control Eight Sleep pods (status, temperature, alarms, schedules).
|
||||
homepage: https://eightctl.sh
|
||||
metadata: {"zee":{"emoji":"🎛️","requires":{"bins":["eightctl"]},"install":[{"id":"go","kind":"go","module":"github.com/steipete/eightctl/cmd/eightctl@latest","bins":["eightctl"],"label":"Install eightctl (go)"}]}}
|
||||
---
|
||||
|
||||
# eightctl
|
||||
|
||||
Use `eightctl` for Eight Sleep pod control. Requires auth.
|
||||
|
||||
Auth
|
||||
- Config: `~/.config/eightctl/config.yaml`
|
||||
- Env: `EIGHTCTL_EMAIL`, `EIGHTCTL_PASSWORD`
|
||||
|
||||
Quick start
|
||||
- `eightctl status`
|
||||
- `eightctl on|off`
|
||||
- `eightctl temp 20`
|
||||
|
||||
Common tasks
|
||||
- Alarms: `eightctl alarm list|create|dismiss`
|
||||
- Schedules: `eightctl schedule list|create|update`
|
||||
- Audio: `eightctl audio state|play|pause`
|
||||
- Base: `eightctl base info|angle`
|
||||
|
||||
Notes
|
||||
- API is unofficial and rate-limited; avoid repeated logins.
|
||||
- Confirm before changing temperature or alarms.
|
||||
@@ -0,0 +1,104 @@
|
||||
---
|
||||
name: financial-research
|
||||
description: Conduct fundamental investment research using OpenBB and Stanley backend
|
||||
triggers:
|
||||
- stock research
|
||||
- company analysis
|
||||
- investment thesis
|
||||
- fundamental analysis
|
||||
- valuation
|
||||
---
|
||||
|
||||
# Financial Research
|
||||
|
||||
Conduct rigorous fundamental investment research on public companies using OpenBB data and Stanley analysis tools.
|
||||
|
||||
## Available Data Sources
|
||||
|
||||
### Via OpenBB MCP
|
||||
- **Equity Data**: Historical prices, fundamentals, ownership, shorts
|
||||
- **News & Sentiment**: Company news, market news, analyst coverage
|
||||
- **SEC Filings**: 10-K, 10-Q, 8-K filings via SEC provider
|
||||
|
||||
### Via Stanley Backend
|
||||
- **Research**: ResearchAnalyzer, DCF models, peer comparison
|
||||
- **Analytics**: Money flow, institutional positioning, options flow
|
||||
- **Accounting**: Financial statements, earnings quality, red flags
|
||||
|
||||
## Research Workflow
|
||||
|
||||
### 1. Company Overview
|
||||
```
|
||||
# Quick overview using OpenBB
|
||||
obb.equity.fundamental.overview(symbol="AAPL", provider="fmp")
|
||||
obb.equity.profile(symbol="AAPL")
|
||||
```
|
||||
|
||||
### 2. Financial Analysis
|
||||
```
|
||||
# Income statement trend
|
||||
obb.equity.fundamental.income(symbol="AAPL", period="annual", limit=5)
|
||||
|
||||
# Balance sheet strength
|
||||
obb.equity.fundamental.balance(symbol="AAPL", period="annual")
|
||||
|
||||
# Cash flow analysis
|
||||
obb.equity.fundamental.cash(symbol="AAPL", period="annual")
|
||||
|
||||
# Key ratios
|
||||
obb.equity.fundamental.ratios(symbol="AAPL")
|
||||
```
|
||||
|
||||
### 3. Ownership & Positioning
|
||||
```
|
||||
# Institutional holders (13F)
|
||||
obb.equity.ownership.institutional(symbol="AAPL", provider="fmp")
|
||||
|
||||
# Insider trading
|
||||
obb.equity.ownership.insider_trading(symbol="AAPL")
|
||||
|
||||
# Short interest
|
||||
obb.equity.shorts.short_volume(symbol="AAPL")
|
||||
```
|
||||
|
||||
### 4. Valuation Analysis
|
||||
```
|
||||
# Use Stanley's valuation module
|
||||
from stanley.research import calculate_dcf, compare_to_peers
|
||||
|
||||
dcf_result = calculate_dcf(
|
||||
symbol="AAPL",
|
||||
growth_rate=0.08,
|
||||
discount_rate=0.10,
|
||||
terminal_growth=0.025
|
||||
)
|
||||
|
||||
peers = compare_to_peers("AAPL", ["MSFT", "GOOGL", "AMZN"])
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
Research reports should include:
|
||||
1. **Executive Summary**: Key thesis and recommendation
|
||||
2. **Business Overview**: What the company does, moat analysis
|
||||
3. **Financial Analysis**: Revenue trends, margins, ROE/ROIC
|
||||
4. **Valuation**: DCF, comparables, historical multiples
|
||||
5. **Risks**: Key risks and bear case scenarios
|
||||
6. **Catalysts**: Upcoming events and inflection points
|
||||
|
||||
## Memory Integration
|
||||
|
||||
Store research findings:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "stanley/research",
|
||||
key: `thesis/${symbol}`,
|
||||
value: {
|
||||
symbol,
|
||||
thesis: "...",
|
||||
conviction: "high",
|
||||
targetPrice: 185,
|
||||
lastUpdated: new Date()
|
||||
}
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,738 @@
|
||||
---
|
||||
name: flow-nexus-neural
|
||||
description: Train and deploy neural networks in distributed E2B sandboxes with Flow Nexus
|
||||
version: 1.0.0
|
||||
category: ai-ml
|
||||
tags:
|
||||
- neural-networks
|
||||
- distributed-training
|
||||
- machine-learning
|
||||
- deep-learning
|
||||
- flow-nexus
|
||||
- e2b-sandboxes
|
||||
requires_auth: true
|
||||
mcp_server: flow-nexus
|
||||
---
|
||||
|
||||
# Flow Nexus Neural Networks
|
||||
|
||||
Deploy, train, and manage neural networks in distributed E2B sandbox environments. Train custom models with multiple architectures (feedforward, LSTM, GAN, transformer) or use pre-built templates from the marketplace.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
```bash
|
||||
# Add Flow Nexus MCP server
|
||||
claude mcp add flow-nexus npx flow-nexus@latest mcp start
|
||||
|
||||
# Register and login
|
||||
npx flow-nexus@latest register
|
||||
npx flow-nexus@latest login
|
||||
```
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
### 1. Single-Node Neural Training
|
||||
|
||||
Train neural networks with custom architectures and configurations.
|
||||
|
||||
**Available Architectures:**
|
||||
- `feedforward` - Standard fully-connected networks
|
||||
- `lstm` - Long Short-Term Memory for sequences
|
||||
- `gan` - Generative Adversarial Networks
|
||||
- `autoencoder` - Dimensionality reduction
|
||||
- `transformer` - Attention-based models
|
||||
|
||||
**Training Tiers:**
|
||||
- `nano` - Minimal resources (fast, limited)
|
||||
- `mini` - Small models
|
||||
- `small` - Standard models
|
||||
- `medium` - Complex models
|
||||
- `large` - Large-scale training
|
||||
|
||||
#### Example: Train Custom Classifier
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_train({
|
||||
config: {
|
||||
architecture: {
|
||||
type: "feedforward",
|
||||
layers: [
|
||||
{ type: "dense", units: 256, activation: "relu" },
|
||||
{ type: "dropout", rate: 0.3 },
|
||||
{ type: "dense", units: 128, activation: "relu" },
|
||||
{ type: "dropout", rate: 0.2 },
|
||||
{ type: "dense", units: 64, activation: "relu" },
|
||||
{ type: "dense", units: 10, activation: "softmax" }
|
||||
]
|
||||
},
|
||||
training: {
|
||||
epochs: 100,
|
||||
batch_size: 32,
|
||||
learning_rate: 0.001,
|
||||
optimizer: "adam"
|
||||
},
|
||||
divergent: {
|
||||
enabled: true,
|
||||
pattern: "lateral", // quantum, chaotic, associative, evolutionary
|
||||
factor: 0.5
|
||||
}
|
||||
},
|
||||
tier: "small",
|
||||
user_id: "your_user_id"
|
||||
})
|
||||
```
|
||||
|
||||
#### Example: LSTM for Time Series
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_train({
|
||||
config: {
|
||||
architecture: {
|
||||
type: "lstm",
|
||||
layers: [
|
||||
{ type: "lstm", units: 128, return_sequences: true },
|
||||
{ type: "dropout", rate: 0.2 },
|
||||
{ type: "lstm", units: 64 },
|
||||
{ type: "dense", units: 1, activation: "linear" }
|
||||
]
|
||||
},
|
||||
training: {
|
||||
epochs: 150,
|
||||
batch_size: 64,
|
||||
learning_rate: 0.01,
|
||||
optimizer: "adam"
|
||||
}
|
||||
},
|
||||
tier: "medium"
|
||||
})
|
||||
```
|
||||
|
||||
#### Example: Transformer Architecture
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_train({
|
||||
config: {
|
||||
architecture: {
|
||||
type: "transformer",
|
||||
layers: [
|
||||
{ type: "embedding", vocab_size: 10000, embedding_dim: 512 },
|
||||
{ type: "transformer_encoder", num_heads: 8, ff_dim: 2048 },
|
||||
{ type: "global_average_pooling" },
|
||||
{ type: "dense", units: 128, activation: "relu" },
|
||||
{ type: "dense", units: 2, activation: "softmax" }
|
||||
]
|
||||
},
|
||||
training: {
|
||||
epochs: 50,
|
||||
batch_size: 16,
|
||||
learning_rate: 0.0001,
|
||||
optimizer: "adam"
|
||||
}
|
||||
},
|
||||
tier: "large"
|
||||
})
|
||||
```
|
||||
|
||||
### 2. Model Inference
|
||||
|
||||
Run predictions on trained models.
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_predict({
|
||||
model_id: "model_abc123",
|
||||
input: [
|
||||
[0.5, 0.3, 0.2, 0.1],
|
||||
[0.8, 0.1, 0.05, 0.05],
|
||||
[0.2, 0.6, 0.15, 0.05]
|
||||
],
|
||||
user_id: "your_user_id"
|
||||
})
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"predictions": [
|
||||
[0.12, 0.85, 0.03],
|
||||
[0.89, 0.08, 0.03],
|
||||
[0.05, 0.92, 0.03]
|
||||
],
|
||||
"inference_time_ms": 45,
|
||||
"model_version": "1.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Template Marketplace
|
||||
|
||||
Browse and deploy pre-trained models from the marketplace.
|
||||
|
||||
#### List Available Templates
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_list_templates({
|
||||
category: "classification", // timeseries, regression, nlp, vision, anomaly, generative
|
||||
tier: "free", // or "paid"
|
||||
search: "sentiment",
|
||||
limit: 20
|
||||
})
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"templates": [
|
||||
{
|
||||
"id": "sentiment-analysis-v2",
|
||||
"name": "Sentiment Analysis Classifier",
|
||||
"description": "Pre-trained BERT model for sentiment analysis",
|
||||
"category": "nlp",
|
||||
"accuracy": 0.94,
|
||||
"downloads": 1523,
|
||||
"tier": "free"
|
||||
},
|
||||
{
|
||||
"id": "image-classifier-resnet",
|
||||
"name": "ResNet Image Classifier",
|
||||
"description": "ResNet-50 for image classification",
|
||||
"category": "vision",
|
||||
"accuracy": 0.96,
|
||||
"downloads": 2341,
|
||||
"tier": "paid"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Deploy Template
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_deploy_template({
|
||||
template_id: "sentiment-analysis-v2",
|
||||
custom_config: {
|
||||
training: {
|
||||
epochs: 50,
|
||||
learning_rate: 0.0001
|
||||
}
|
||||
},
|
||||
user_id: "your_user_id"
|
||||
})
|
||||
```
|
||||
|
||||
### 4. Distributed Training Clusters
|
||||
|
||||
Train large models across multiple E2B sandboxes with distributed computing.
|
||||
|
||||
#### Initialize Cluster
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_cluster_init({
|
||||
name: "large-model-cluster",
|
||||
architecture: "transformer", // transformer, cnn, rnn, gnn, hybrid
|
||||
topology: "mesh", // mesh, ring, star, hierarchical
|
||||
consensus: "proof-of-learning", // byzantine, raft, gossip
|
||||
daaEnabled: true, // Decentralized Autonomous Agents
|
||||
wasmOptimization: true
|
||||
})
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"cluster_id": "cluster_xyz789",
|
||||
"name": "large-model-cluster",
|
||||
"status": "initializing",
|
||||
"topology": "mesh",
|
||||
"max_nodes": 100,
|
||||
"created_at": "2025-10-19T10:30:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### Deploy Worker Nodes
|
||||
|
||||
```javascript
|
||||
// Deploy parameter server
|
||||
mcp__flow-nexus__neural_node_deploy({
|
||||
cluster_id: "cluster_xyz789",
|
||||
node_type: "parameter_server",
|
||||
model: "large",
|
||||
template: "nodejs",
|
||||
capabilities: ["parameter_management", "gradient_aggregation"],
|
||||
autonomy: 0.8
|
||||
})
|
||||
|
||||
// Deploy worker nodes
|
||||
mcp__flow-nexus__neural_node_deploy({
|
||||
cluster_id: "cluster_xyz789",
|
||||
node_type: "worker",
|
||||
model: "xl",
|
||||
role: "worker",
|
||||
capabilities: ["training", "inference"],
|
||||
layers: [
|
||||
{ type: "transformer_encoder", num_heads: 16 },
|
||||
{ type: "feed_forward", units: 4096 }
|
||||
],
|
||||
autonomy: 0.9
|
||||
})
|
||||
|
||||
// Deploy aggregator
|
||||
mcp__flow-nexus__neural_node_deploy({
|
||||
cluster_id: "cluster_xyz789",
|
||||
node_type: "aggregator",
|
||||
model: "large",
|
||||
capabilities: ["gradient_aggregation", "model_synchronization"]
|
||||
})
|
||||
```
|
||||
|
||||
#### Connect Cluster Topology
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_cluster_connect({
|
||||
cluster_id: "cluster_xyz789",
|
||||
topology: "mesh" // Override default if needed
|
||||
})
|
||||
```
|
||||
|
||||
#### Start Distributed Training
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_train_distributed({
|
||||
cluster_id: "cluster_xyz789",
|
||||
dataset: "imagenet", // or custom dataset identifier
|
||||
epochs: 100,
|
||||
batch_size: 128,
|
||||
learning_rate: 0.001,
|
||||
optimizer: "adam", // sgd, rmsprop, adagrad
|
||||
federated: true // Enable federated learning
|
||||
})
|
||||
```
|
||||
|
||||
**Federated Learning Example:**
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_train_distributed({
|
||||
cluster_id: "cluster_xyz789",
|
||||
dataset: "medical_images_distributed",
|
||||
epochs: 200,
|
||||
batch_size: 64,
|
||||
learning_rate: 0.0001,
|
||||
optimizer: "adam",
|
||||
federated: true, // Data stays on local nodes
|
||||
aggregation_rounds: 50,
|
||||
min_nodes_per_round: 5
|
||||
})
|
||||
```
|
||||
|
||||
#### Monitor Cluster Status
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_cluster_status({
|
||||
cluster_id: "cluster_xyz789"
|
||||
})
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"cluster_id": "cluster_xyz789",
|
||||
"status": "training",
|
||||
"nodes": [
|
||||
{
|
||||
"node_id": "node_001",
|
||||
"type": "parameter_server",
|
||||
"status": "active",
|
||||
"cpu_usage": 0.75,
|
||||
"memory_usage": 0.82
|
||||
},
|
||||
{
|
||||
"node_id": "node_002",
|
||||
"type": "worker",
|
||||
"status": "active",
|
||||
"training_progress": 0.45
|
||||
}
|
||||
],
|
||||
"training_metrics": {
|
||||
"current_epoch": 45,
|
||||
"total_epochs": 100,
|
||||
"loss": 0.234,
|
||||
"accuracy": 0.891
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Run Distributed Inference
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_predict_distributed({
|
||||
cluster_id: "cluster_xyz789",
|
||||
input_data: JSON.stringify([
|
||||
[0.1, 0.2, 0.3],
|
||||
[0.4, 0.5, 0.6]
|
||||
]),
|
||||
aggregation: "ensemble" // mean, majority, weighted, ensemble
|
||||
})
|
||||
```
|
||||
|
||||
#### Terminate Cluster
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_cluster_terminate({
|
||||
cluster_id: "cluster_xyz789"
|
||||
})
|
||||
```
|
||||
|
||||
### 5. Model Management
|
||||
|
||||
#### List Your Models
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_list_models({
|
||||
user_id: "your_user_id",
|
||||
include_public: true
|
||||
})
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"model_id": "model_abc123",
|
||||
"name": "Custom Classifier v1",
|
||||
"architecture": "feedforward",
|
||||
"accuracy": 0.92,
|
||||
"created_at": "2025-10-15T14:20:00Z",
|
||||
"status": "trained"
|
||||
},
|
||||
{
|
||||
"model_id": "model_def456",
|
||||
"name": "LSTM Forecaster",
|
||||
"architecture": "lstm",
|
||||
"mse": 0.0045,
|
||||
"created_at": "2025-10-18T09:15:00Z",
|
||||
"status": "training"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Check Training Status
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_training_status({
|
||||
job_id: "job_training_xyz"
|
||||
})
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"job_id": "job_training_xyz",
|
||||
"status": "training",
|
||||
"progress": 0.67,
|
||||
"current_epoch": 67,
|
||||
"total_epochs": 100,
|
||||
"current_loss": 0.234,
|
||||
"estimated_completion": "2025-10-19T12:45:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### Performance Benchmarking
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_performance_benchmark({
|
||||
model_id: "model_abc123",
|
||||
benchmark_type: "comprehensive" // inference, throughput, memory, comprehensive
|
||||
})
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"model_id": "model_abc123",
|
||||
"benchmarks": {
|
||||
"inference_latency_ms": 12.5,
|
||||
"throughput_qps": 8000,
|
||||
"memory_usage_mb": 245,
|
||||
"gpu_utilization": 0.78,
|
||||
"accuracy": 0.92,
|
||||
"f1_score": 0.89
|
||||
},
|
||||
"timestamp": "2025-10-19T11:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
#### Create Validation Workflow
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_validation_workflow({
|
||||
model_id: "model_abc123",
|
||||
user_id: "your_user_id",
|
||||
validation_type: "comprehensive" // performance, accuracy, robustness, comprehensive
|
||||
})
|
||||
```
|
||||
|
||||
### 6. Publishing and Marketplace
|
||||
|
||||
#### Publish Model as Template
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_publish_template({
|
||||
model_id: "model_abc123",
|
||||
name: "High-Accuracy Sentiment Classifier",
|
||||
description: "Fine-tuned BERT model for sentiment analysis with 94% accuracy",
|
||||
category: "nlp",
|
||||
price: 0, // 0 for free, or credits amount
|
||||
user_id: "your_user_id"
|
||||
})
|
||||
```
|
||||
|
||||
#### Rate a Template
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__neural_rate_template({
|
||||
template_id: "sentiment-analysis-v2",
|
||||
rating: 5,
|
||||
review: "Excellent model! Achieved 95% accuracy on my dataset.",
|
||||
user_id: "your_user_id"
|
||||
})
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### Image Classification with CNN
|
||||
|
||||
```javascript
|
||||
// Initialize cluster for large-scale image training
|
||||
const cluster = await mcp__flow-nexus__neural_cluster_init({
|
||||
name: "image-classification-cluster",
|
||||
architecture: "cnn",
|
||||
topology: "hierarchical",
|
||||
wasmOptimization: true
|
||||
})
|
||||
|
||||
// Deploy worker nodes
|
||||
await mcp__flow-nexus__neural_node_deploy({
|
||||
cluster_id: cluster.cluster_id,
|
||||
node_type: "worker",
|
||||
model: "large",
|
||||
capabilities: ["training", "data_augmentation"]
|
||||
})
|
||||
|
||||
// Start training
|
||||
await mcp__flow-nexus__neural_train_distributed({
|
||||
cluster_id: cluster.cluster_id,
|
||||
dataset: "custom_images",
|
||||
epochs: 100,
|
||||
batch_size: 64,
|
||||
learning_rate: 0.001,
|
||||
optimizer: "adam"
|
||||
})
|
||||
```
|
||||
|
||||
### NLP Sentiment Analysis
|
||||
|
||||
```javascript
|
||||
// Use pre-built template
|
||||
const deployment = await mcp__flow-nexus__neural_deploy_template({
|
||||
template_id: "sentiment-analysis-v2",
|
||||
custom_config: {
|
||||
training: {
|
||||
epochs: 30,
|
||||
batch_size: 16
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Run inference
|
||||
const result = await mcp__flow-nexus__neural_predict({
|
||||
model_id: deployment.model_id,
|
||||
input: ["This product is amazing!", "Terrible experience."]
|
||||
})
|
||||
```
|
||||
|
||||
### Time Series Forecasting
|
||||
|
||||
```javascript
|
||||
// Train LSTM model
|
||||
const training = await mcp__flow-nexus__neural_train({
|
||||
config: {
|
||||
architecture: {
|
||||
type: "lstm",
|
||||
layers: [
|
||||
{ type: "lstm", units: 128, return_sequences: true },
|
||||
{ type: "dropout", rate: 0.2 },
|
||||
{ type: "lstm", units: 64 },
|
||||
{ type: "dense", units: 1 }
|
||||
]
|
||||
},
|
||||
training: {
|
||||
epochs: 150,
|
||||
batch_size: 64,
|
||||
learning_rate: 0.01,
|
||||
optimizer: "adam"
|
||||
}
|
||||
},
|
||||
tier: "medium"
|
||||
})
|
||||
|
||||
// Monitor progress
|
||||
const status = await mcp__flow-nexus__neural_training_status({
|
||||
job_id: training.job_id
|
||||
})
|
||||
```
|
||||
|
||||
### Federated Learning for Privacy
|
||||
|
||||
```javascript
|
||||
// Initialize federated cluster
|
||||
const cluster = await mcp__flow-nexus__neural_cluster_init({
|
||||
name: "federated-medical-cluster",
|
||||
architecture: "transformer",
|
||||
topology: "mesh",
|
||||
consensus: "proof-of-learning",
|
||||
daaEnabled: true
|
||||
})
|
||||
|
||||
// Deploy nodes across different locations
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await mcp__flow-nexus__neural_node_deploy({
|
||||
cluster_id: cluster.cluster_id,
|
||||
node_type: "worker",
|
||||
model: "large",
|
||||
autonomy: 0.9
|
||||
})
|
||||
}
|
||||
|
||||
// Train with federated learning (data never leaves nodes)
|
||||
await mcp__flow-nexus__neural_train_distributed({
|
||||
cluster_id: cluster.cluster_id,
|
||||
dataset: "medical_records_distributed",
|
||||
epochs: 200,
|
||||
federated: true,
|
||||
aggregation_rounds: 100
|
||||
})
|
||||
```
|
||||
|
||||
## Architecture Patterns
|
||||
|
||||
### Feedforward Networks
|
||||
Best for: Classification, regression, simple pattern recognition
|
||||
```javascript
|
||||
{
|
||||
type: "feedforward",
|
||||
layers: [
|
||||
{ type: "dense", units: 256, activation: "relu" },
|
||||
{ type: "dropout", rate: 0.3 },
|
||||
{ type: "dense", units: 128, activation: "relu" },
|
||||
{ type: "dense", units: 10, activation: "softmax" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### LSTM Networks
|
||||
Best for: Time series, sequences, forecasting
|
||||
```javascript
|
||||
{
|
||||
type: "lstm",
|
||||
layers: [
|
||||
{ type: "lstm", units: 128, return_sequences: true },
|
||||
{ type: "lstm", units: 64 },
|
||||
{ type: "dense", units: 1 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Transformers
|
||||
Best for: NLP, attention mechanisms, large-scale text
|
||||
```javascript
|
||||
{
|
||||
type: "transformer",
|
||||
layers: [
|
||||
{ type: "embedding", vocab_size: 10000, embedding_dim: 512 },
|
||||
{ type: "transformer_encoder", num_heads: 8, ff_dim: 2048 },
|
||||
{ type: "global_average_pooling" },
|
||||
{ type: "dense", units: 2, activation: "softmax" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### GANs
|
||||
Best for: Generative tasks, image synthesis
|
||||
```javascript
|
||||
{
|
||||
type: "gan",
|
||||
generator_layers: [...],
|
||||
discriminator_layers: [...]
|
||||
}
|
||||
```
|
||||
|
||||
### Autoencoders
|
||||
Best for: Dimensionality reduction, anomaly detection
|
||||
```javascript
|
||||
{
|
||||
type: "autoencoder",
|
||||
encoder_layers: [
|
||||
{ type: "dense", units: 128, activation: "relu" },
|
||||
{ type: "dense", units: 64, activation: "relu" }
|
||||
],
|
||||
decoder_layers: [
|
||||
{ type: "dense", units: 128, activation: "relu" },
|
||||
{ type: "dense", units: input_dim, activation: "sigmoid" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Start Small**: Begin with `nano` or `mini` tiers for experimentation
|
||||
2. **Use Templates**: Leverage marketplace templates for common tasks
|
||||
3. **Monitor Training**: Check status regularly to catch issues early
|
||||
4. **Benchmark Models**: Always benchmark before production deployment
|
||||
5. **Distributed Training**: Use clusters for large models (>1B parameters)
|
||||
6. **Federated Learning**: Use for privacy-sensitive data
|
||||
7. **Version Models**: Publish successful models as templates for reuse
|
||||
8. **Validate Thoroughly**: Use validation workflows before deployment
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Training Stalled
|
||||
```javascript
|
||||
// Check cluster status
|
||||
const status = await mcp__flow-nexus__neural_cluster_status({
|
||||
cluster_id: "cluster_id"
|
||||
})
|
||||
|
||||
// Terminate and restart if needed
|
||||
await mcp__flow-nexus__neural_cluster_terminate({
|
||||
cluster_id: "cluster_id"
|
||||
})
|
||||
```
|
||||
|
||||
### Low Accuracy
|
||||
- Increase epochs
|
||||
- Adjust learning rate
|
||||
- Add regularization (dropout)
|
||||
- Try different optimizer
|
||||
- Use data augmentation
|
||||
|
||||
### Out of Memory
|
||||
- Reduce batch size
|
||||
- Use smaller model tier
|
||||
- Enable gradient accumulation
|
||||
- Use distributed training
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `flow-nexus-sandbox` - E2B sandbox management
|
||||
- `flow-nexus-swarm` - AI swarm orchestration
|
||||
- `flow-nexus-workflow` - Workflow automation
|
||||
|
||||
## Resources
|
||||
|
||||
- Flow Nexus Docs: https://flow-nexus.ruv.io/docs
|
||||
- Neural Network Guide: https://flow-nexus.ruv.io/docs/neural
|
||||
- Template Marketplace: https://flow-nexus.ruv.io/templates
|
||||
- API Reference: https://flow-nexus.ruv.io/api
|
||||
|
||||
---
|
||||
|
||||
**Note**: Distributed training requires authentication. Register at https://flow-nexus.ruv.io or use `npx flow-nexus@latest register`.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,610 @@
|
||||
---
|
||||
name: flow-nexus-swarm
|
||||
description: Cloud-based AI swarm deployment and event-driven workflow automation with Flow Nexus platform
|
||||
category: orchestration
|
||||
tags: [swarm, workflow, cloud, agents, automation, message-queue]
|
||||
version: 1.0.0
|
||||
requires:
|
||||
- flow-nexus MCP server
|
||||
- Active Flow Nexus account (register at flow-nexus.ruv.io)
|
||||
---
|
||||
|
||||
# Flow Nexus Swarm & Workflow Orchestration
|
||||
|
||||
Deploy and manage cloud-based AI agent swarms with event-driven workflow automation, message queue processing, and intelligent agent coordination.
|
||||
|
||||
## 📋 Table of Contents
|
||||
|
||||
1. [Overview](#overview)
|
||||
2. [Swarm Management](#swarm-management)
|
||||
3. [Workflow Automation](#workflow-automation)
|
||||
4. [Agent Orchestration](#agent-orchestration)
|
||||
5. [Templates & Patterns](#templates--patterns)
|
||||
6. [Advanced Features](#advanced-features)
|
||||
7. [Best Practices](#best-practices)
|
||||
|
||||
## Overview
|
||||
|
||||
Flow Nexus provides cloud-based orchestration for AI agent swarms with:
|
||||
|
||||
- **Multi-topology Support**: Hierarchical, mesh, ring, and star architectures
|
||||
- **Event-driven Workflows**: Message queue processing with async execution
|
||||
- **Template Library**: Pre-built swarm configurations for common use cases
|
||||
- **Intelligent Agent Assignment**: Vector similarity matching for optimal agent selection
|
||||
- **Real-time Monitoring**: Comprehensive metrics and audit trails
|
||||
- **Scalable Infrastructure**: Cloud-based execution with auto-scaling
|
||||
|
||||
## Swarm Management
|
||||
|
||||
### Initialize Swarm
|
||||
|
||||
Create a new swarm with specified topology and configuration:
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__swarm_init({
|
||||
topology: "hierarchical", // Options: mesh, ring, star, hierarchical
|
||||
maxAgents: 8,
|
||||
strategy: "balanced" // Options: balanced, specialized, adaptive
|
||||
})
|
||||
```
|
||||
|
||||
**Topology Guide:**
|
||||
- **Hierarchical**: Tree structure with coordinator nodes (best for complex projects)
|
||||
- **Mesh**: Peer-to-peer collaboration (best for research and analysis)
|
||||
- **Ring**: Circular coordination (best for sequential workflows)
|
||||
- **Star**: Centralized hub (best for simple delegation)
|
||||
|
||||
**Strategy Guide:**
|
||||
- **Balanced**: Equal distribution of workload across agents
|
||||
- **Specialized**: Agents focus on specific expertise areas
|
||||
- **Adaptive**: Dynamic adjustment based on task complexity
|
||||
|
||||
### Spawn Agents
|
||||
|
||||
Add specialized agents to the swarm:
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__agent_spawn({
|
||||
type: "researcher", // Options: researcher, coder, analyst, optimizer, coordinator
|
||||
name: "Lead Researcher",
|
||||
capabilities: ["web_search", "analysis", "summarization"]
|
||||
})
|
||||
```
|
||||
|
||||
**Agent Types:**
|
||||
- **Researcher**: Information gathering, web search, analysis
|
||||
- **Coder**: Code generation, refactoring, implementation
|
||||
- **Analyst**: Data analysis, pattern recognition, insights
|
||||
- **Optimizer**: Performance tuning, resource optimization
|
||||
- **Coordinator**: Task delegation, progress tracking, integration
|
||||
|
||||
### Orchestrate Tasks
|
||||
|
||||
Distribute tasks across the swarm:
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__task_orchestrate({
|
||||
task: "Build a REST API with authentication and database integration",
|
||||
strategy: "parallel", // Options: parallel, sequential, adaptive
|
||||
maxAgents: 5,
|
||||
priority: "high" // Options: low, medium, high, critical
|
||||
})
|
||||
```
|
||||
|
||||
**Execution Strategies:**
|
||||
- **Parallel**: Maximum concurrency for independent subtasks
|
||||
- **Sequential**: Step-by-step execution with dependencies
|
||||
- **Adaptive**: AI-powered strategy selection based on task analysis
|
||||
|
||||
### Monitor & Scale Swarms
|
||||
|
||||
```javascript
|
||||
// Get detailed swarm status
|
||||
mcp__flow-nexus__swarm_status({
|
||||
swarm_id: "optional-id" // Uses active swarm if not provided
|
||||
})
|
||||
|
||||
// List all active swarms
|
||||
mcp__flow-nexus__swarm_list({
|
||||
status: "active" // Options: active, destroyed, all
|
||||
})
|
||||
|
||||
// Scale swarm up or down
|
||||
mcp__flow-nexus__swarm_scale({
|
||||
target_agents: 10,
|
||||
swarm_id: "optional-id"
|
||||
})
|
||||
|
||||
// Gracefully destroy swarm
|
||||
mcp__flow-nexus__swarm_destroy({
|
||||
swarm_id: "optional-id"
|
||||
})
|
||||
```
|
||||
|
||||
## Workflow Automation
|
||||
|
||||
### Create Workflow
|
||||
|
||||
Define event-driven workflows with message queue processing:
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__workflow_create({
|
||||
name: "CI/CD Pipeline",
|
||||
description: "Automated testing, building, and deployment",
|
||||
steps: [
|
||||
{
|
||||
id: "test",
|
||||
action: "run_tests",
|
||||
agent: "tester",
|
||||
parallel: true
|
||||
},
|
||||
{
|
||||
id: "build",
|
||||
action: "build_app",
|
||||
agent: "builder",
|
||||
depends_on: ["test"]
|
||||
},
|
||||
{
|
||||
id: "deploy",
|
||||
action: "deploy_prod",
|
||||
agent: "deployer",
|
||||
depends_on: ["build"]
|
||||
}
|
||||
],
|
||||
triggers: ["push_to_main", "manual_trigger"],
|
||||
metadata: {
|
||||
priority: 10,
|
||||
retry_policy: "exponential_backoff"
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
**Workflow Features:**
|
||||
- **Dependency Management**: Define step dependencies with `depends_on`
|
||||
- **Parallel Execution**: Set `parallel: true` for concurrent steps
|
||||
- **Event Triggers**: GitHub events, schedules, manual triggers
|
||||
- **Retry Policies**: Automatic retry on transient failures
|
||||
- **Priority Queuing**: High-priority workflows execute first
|
||||
|
||||
### Execute Workflow
|
||||
|
||||
Run workflows synchronously or asynchronously:
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__workflow_execute({
|
||||
workflow_id: "workflow_id",
|
||||
input_data: {
|
||||
branch: "main",
|
||||
commit: "abc123",
|
||||
environment: "production"
|
||||
},
|
||||
async: true // Queue-based execution for long-running workflows
|
||||
})
|
||||
```
|
||||
|
||||
**Execution Modes:**
|
||||
- **Sync (async: false)**: Immediate execution, wait for completion
|
||||
- **Async (async: true)**: Message queue processing, non-blocking
|
||||
|
||||
### Monitor Workflows
|
||||
|
||||
```javascript
|
||||
// Get workflow status and metrics
|
||||
mcp__flow-nexus__workflow_status({
|
||||
workflow_id: "id",
|
||||
execution_id: "specific-run-id", // Optional
|
||||
include_metrics: true
|
||||
})
|
||||
|
||||
// List workflows with filters
|
||||
mcp__flow-nexus__workflow_list({
|
||||
status: "running", // Options: running, completed, failed, pending
|
||||
limit: 10,
|
||||
offset: 0
|
||||
})
|
||||
|
||||
// Get complete audit trail
|
||||
mcp__flow-nexus__workflow_audit_trail({
|
||||
workflow_id: "id",
|
||||
limit: 50,
|
||||
start_time: "2025-01-01T00:00:00Z"
|
||||
})
|
||||
```
|
||||
|
||||
### Agent Assignment
|
||||
|
||||
Intelligently assign agents to workflow tasks:
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__workflow_agent_assign({
|
||||
task_id: "task_id",
|
||||
agent_type: "coder", // Preferred agent type
|
||||
use_vector_similarity: true // AI-powered capability matching
|
||||
})
|
||||
```
|
||||
|
||||
**Vector Similarity Matching:**
|
||||
- Analyzes task requirements and agent capabilities
|
||||
- Finds optimal agent based on past performance
|
||||
- Considers workload and availability
|
||||
|
||||
### Queue Management
|
||||
|
||||
Monitor and manage message queues:
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__workflow_queue_status({
|
||||
queue_name: "optional-specific-queue",
|
||||
include_messages: true // Show pending messages
|
||||
})
|
||||
```
|
||||
|
||||
## Agent Orchestration
|
||||
|
||||
### Full-Stack Development Pattern
|
||||
|
||||
```javascript
|
||||
// 1. Initialize swarm with hierarchical topology
|
||||
mcp__flow-nexus__swarm_init({
|
||||
topology: "hierarchical",
|
||||
maxAgents: 8,
|
||||
strategy: "specialized"
|
||||
})
|
||||
|
||||
// 2. Spawn specialized agents
|
||||
mcp__flow-nexus__agent_spawn({ type: "coordinator", name: "Project Manager" })
|
||||
mcp__flow-nexus__agent_spawn({ type: "coder", name: "Backend Developer" })
|
||||
mcp__flow-nexus__agent_spawn({ type: "coder", name: "Frontend Developer" })
|
||||
mcp__flow-nexus__agent_spawn({ type: "coder", name: "Database Architect" })
|
||||
mcp__flow-nexus__agent_spawn({ type: "analyst", name: "QA Engineer" })
|
||||
|
||||
// 3. Create development workflow
|
||||
mcp__flow-nexus__workflow_create({
|
||||
name: "Full-Stack Development",
|
||||
steps: [
|
||||
{ id: "requirements", action: "analyze_requirements", agent: "coordinator" },
|
||||
{ id: "db_design", action: "design_schema", agent: "Database Architect" },
|
||||
{ id: "backend", action: "build_api", agent: "Backend Developer", depends_on: ["db_design"] },
|
||||
{ id: "frontend", action: "build_ui", agent: "Frontend Developer", depends_on: ["requirements"] },
|
||||
{ id: "integration", action: "integrate", agent: "Backend Developer", depends_on: ["backend", "frontend"] },
|
||||
{ id: "testing", action: "qa_testing", agent: "QA Engineer", depends_on: ["integration"] }
|
||||
]
|
||||
})
|
||||
|
||||
// 4. Execute workflow
|
||||
mcp__flow-nexus__workflow_execute({
|
||||
workflow_id: "workflow_id",
|
||||
input_data: {
|
||||
project: "E-commerce Platform",
|
||||
tech_stack: ["Node.js", "React", "PostgreSQL"]
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Research & Analysis Pattern
|
||||
|
||||
```javascript
|
||||
// 1. Initialize mesh topology for collaborative research
|
||||
mcp__flow-nexus__swarm_init({
|
||||
topology: "mesh",
|
||||
maxAgents: 5,
|
||||
strategy: "balanced"
|
||||
})
|
||||
|
||||
// 2. Spawn research agents
|
||||
mcp__flow-nexus__agent_spawn({ type: "researcher", name: "Primary Researcher" })
|
||||
mcp__flow-nexus__agent_spawn({ type: "researcher", name: "Secondary Researcher" })
|
||||
mcp__flow-nexus__agent_spawn({ type: "analyst", name: "Data Analyst" })
|
||||
mcp__flow-nexus__agent_spawn({ type: "analyst", name: "Insights Analyst" })
|
||||
|
||||
// 3. Orchestrate research task
|
||||
mcp__flow-nexus__task_orchestrate({
|
||||
task: "Research machine learning trends for 2025 and analyze market opportunities",
|
||||
strategy: "parallel",
|
||||
maxAgents: 4,
|
||||
priority: "high"
|
||||
})
|
||||
```
|
||||
|
||||
### CI/CD Pipeline Pattern
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__workflow_create({
|
||||
name: "Deployment Pipeline",
|
||||
description: "Automated testing, building, and multi-environment deployment",
|
||||
steps: [
|
||||
{ id: "lint", action: "lint_code", agent: "code_quality", parallel: true },
|
||||
{ id: "unit_test", action: "unit_tests", agent: "test_runner", parallel: true },
|
||||
{ id: "integration_test", action: "integration_tests", agent: "test_runner", parallel: true },
|
||||
{ id: "build", action: "build_artifacts", agent: "builder", depends_on: ["lint", "unit_test", "integration_test"] },
|
||||
{ id: "security_scan", action: "security_scan", agent: "security", depends_on: ["build"] },
|
||||
{ id: "deploy_staging", action: "deploy", agent: "deployer", depends_on: ["security_scan"] },
|
||||
{ id: "smoke_test", action: "smoke_tests", agent: "test_runner", depends_on: ["deploy_staging"] },
|
||||
{ id: "deploy_prod", action: "deploy", agent: "deployer", depends_on: ["smoke_test"] }
|
||||
],
|
||||
triggers: ["github_push", "github_pr_merged"],
|
||||
metadata: {
|
||||
priority: 10,
|
||||
auto_rollback: true
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Data Processing Pipeline Pattern
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__workflow_create({
|
||||
name: "ETL Pipeline",
|
||||
description: "Extract, Transform, Load data processing",
|
||||
steps: [
|
||||
{ id: "extract", action: "extract_data", agent: "data_extractor" },
|
||||
{ id: "validate_raw", action: "validate_data", agent: "validator", depends_on: ["extract"] },
|
||||
{ id: "transform", action: "transform_data", agent: "transformer", depends_on: ["validate_raw"] },
|
||||
{ id: "enrich", action: "enrich_data", agent: "enricher", depends_on: ["transform"] },
|
||||
{ id: "load", action: "load_data", agent: "loader", depends_on: ["enrich"] },
|
||||
{ id: "validate_final", action: "validate_data", agent: "validator", depends_on: ["load"] }
|
||||
],
|
||||
triggers: ["schedule:0 2 * * *"], // Daily at 2 AM
|
||||
metadata: {
|
||||
retry_policy: "exponential_backoff",
|
||||
max_retries: 3
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Templates & Patterns
|
||||
|
||||
### Use Pre-built Templates
|
||||
|
||||
```javascript
|
||||
// Create swarm from template
|
||||
mcp__flow-nexus__swarm_create_from_template({
|
||||
template_name: "full-stack-dev",
|
||||
overrides: {
|
||||
maxAgents: 6,
|
||||
strategy: "specialized"
|
||||
}
|
||||
})
|
||||
|
||||
// List available templates
|
||||
mcp__flow-nexus__swarm_templates_list({
|
||||
category: "quickstart", // Options: quickstart, specialized, enterprise, custom, all
|
||||
includeStore: true
|
||||
})
|
||||
```
|
||||
|
||||
**Available Template Categories:**
|
||||
|
||||
**Quickstart Templates:**
|
||||
- `full-stack-dev`: Complete web development swarm
|
||||
- `research-team`: Research and analysis swarm
|
||||
- `code-review`: Automated code review swarm
|
||||
- `data-pipeline`: ETL and data processing
|
||||
|
||||
**Specialized Templates:**
|
||||
- `ml-development`: Machine learning project swarm
|
||||
- `mobile-dev`: Mobile app development
|
||||
- `devops-automation`: Infrastructure and deployment
|
||||
- `security-audit`: Security analysis and testing
|
||||
|
||||
**Enterprise Templates:**
|
||||
- `enterprise-migration`: Large-scale system migration
|
||||
- `multi-repo-sync`: Multi-repository coordination
|
||||
- `compliance-review`: Regulatory compliance workflows
|
||||
- `incident-response`: Automated incident management
|
||||
|
||||
### Custom Template Creation
|
||||
|
||||
Save successful swarm configurations as reusable templates for future projects.
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Real-time Monitoring
|
||||
|
||||
```javascript
|
||||
// Subscribe to execution streams
|
||||
mcp__flow-nexus__execution_stream_subscribe({
|
||||
stream_type: "claude-flow-swarm",
|
||||
deployment_id: "deployment_id"
|
||||
})
|
||||
|
||||
// Get execution status
|
||||
mcp__flow-nexus__execution_stream_status({
|
||||
stream_id: "stream_id"
|
||||
})
|
||||
|
||||
// List files created during execution
|
||||
mcp__flow-nexus__execution_files_list({
|
||||
stream_id: "stream_id",
|
||||
created_by: "claude-flow"
|
||||
})
|
||||
```
|
||||
|
||||
### Swarm Metrics & Analytics
|
||||
|
||||
```javascript
|
||||
// Get swarm performance metrics
|
||||
mcp__flow-nexus__swarm_status({
|
||||
swarm_id: "id"
|
||||
})
|
||||
|
||||
// Analyze workflow efficiency
|
||||
mcp__flow-nexus__workflow_status({
|
||||
workflow_id: "id",
|
||||
include_metrics: true
|
||||
})
|
||||
```
|
||||
|
||||
### Multi-Swarm Coordination
|
||||
|
||||
Coordinate multiple swarms for complex, multi-phase projects:
|
||||
|
||||
```javascript
|
||||
// Phase 1: Research swarm
|
||||
const researchSwarm = await mcp__flow-nexus__swarm_init({
|
||||
topology: "mesh",
|
||||
maxAgents: 4
|
||||
})
|
||||
|
||||
// Phase 2: Development swarm
|
||||
const devSwarm = await mcp__flow-nexus__swarm_init({
|
||||
topology: "hierarchical",
|
||||
maxAgents: 8
|
||||
})
|
||||
|
||||
// Phase 3: Testing swarm
|
||||
const testSwarm = await mcp__flow-nexus__swarm_init({
|
||||
topology: "star",
|
||||
maxAgents: 5
|
||||
})
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Choose the Right Topology
|
||||
|
||||
```javascript
|
||||
// Simple projects: Star
|
||||
mcp__flow-nexus__swarm_init({ topology: "star", maxAgents: 3 })
|
||||
|
||||
// Collaborative work: Mesh
|
||||
mcp__flow-nexus__swarm_init({ topology: "mesh", maxAgents: 5 })
|
||||
|
||||
// Complex projects: Hierarchical
|
||||
mcp__flow-nexus__swarm_init({ topology: "hierarchical", maxAgents: 10 })
|
||||
|
||||
// Sequential workflows: Ring
|
||||
mcp__flow-nexus__swarm_init({ topology: "ring", maxAgents: 4 })
|
||||
```
|
||||
|
||||
### 2. Optimize Agent Assignment
|
||||
|
||||
```javascript
|
||||
// Use vector similarity for optimal matching
|
||||
mcp__flow-nexus__workflow_agent_assign({
|
||||
task_id: "complex-task",
|
||||
use_vector_similarity: true
|
||||
})
|
||||
```
|
||||
|
||||
### 3. Implement Proper Error Handling
|
||||
|
||||
```javascript
|
||||
mcp__flow-nexus__workflow_create({
|
||||
name: "Resilient Workflow",
|
||||
steps: [...],
|
||||
metadata: {
|
||||
retry_policy: "exponential_backoff",
|
||||
max_retries: 3,
|
||||
timeout: 300000, // 5 minutes
|
||||
on_failure: "notify_and_rollback"
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### 4. Monitor and Scale
|
||||
|
||||
```javascript
|
||||
// Regular monitoring
|
||||
const status = await mcp__flow-nexus__swarm_status()
|
||||
|
||||
// Scale based on workload
|
||||
if (status.workload > 0.8) {
|
||||
await mcp__flow-nexus__swarm_scale({ target_agents: status.agents + 2 })
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Use Async Execution for Long-Running Workflows
|
||||
|
||||
```javascript
|
||||
// Long-running workflows should use message queues
|
||||
mcp__flow-nexus__workflow_execute({
|
||||
workflow_id: "data-pipeline",
|
||||
async: true // Non-blocking execution
|
||||
})
|
||||
|
||||
// Monitor progress
|
||||
mcp__flow-nexus__workflow_queue_status({ include_messages: true })
|
||||
```
|
||||
|
||||
### 6. Clean Up Resources
|
||||
|
||||
```javascript
|
||||
// Destroy swarm when complete
|
||||
mcp__flow-nexus__swarm_destroy({ swarm_id: "id" })
|
||||
```
|
||||
|
||||
### 7. Leverage Templates
|
||||
|
||||
```javascript
|
||||
// Use proven templates instead of building from scratch
|
||||
mcp__flow-nexus__swarm_create_from_template({
|
||||
template_name: "code-review",
|
||||
overrides: { maxAgents: 4 }
|
||||
})
|
||||
```
|
||||
|
||||
## Integration with Claude Flow
|
||||
|
||||
Flow Nexus swarms integrate seamlessly with Claude Flow hooks:
|
||||
|
||||
```bash
|
||||
# Pre-task coordination setup
|
||||
npx claude-flow@alpha hooks pre-task --description "Initialize swarm"
|
||||
|
||||
# Post-task metrics export
|
||||
npx claude-flow@alpha hooks post-task --task-id "swarm-execution"
|
||||
```
|
||||
|
||||
## Common Use Cases
|
||||
|
||||
### 1. Multi-Repo Development
|
||||
- Coordinate development across multiple repositories
|
||||
- Synchronized testing and deployment
|
||||
- Cross-repo dependency management
|
||||
|
||||
### 2. Research Projects
|
||||
- Distributed information gathering
|
||||
- Parallel analysis of different data sources
|
||||
- Collaborative synthesis and reporting
|
||||
|
||||
### 3. DevOps Automation
|
||||
- Infrastructure as Code deployment
|
||||
- Multi-environment testing
|
||||
- Automated rollback and recovery
|
||||
|
||||
### 4. Code Quality Workflows
|
||||
- Automated code review
|
||||
- Security scanning
|
||||
- Performance benchmarking
|
||||
|
||||
### 5. Data Processing
|
||||
- Large-scale ETL pipelines
|
||||
- Real-time data transformation
|
||||
- Data validation and quality checks
|
||||
|
||||
## Authentication & Setup
|
||||
|
||||
```bash
|
||||
# Install Flow Nexus
|
||||
npm install -g flow-nexus@latest
|
||||
|
||||
# Register account
|
||||
npx flow-nexus@latest register
|
||||
|
||||
# Login
|
||||
npx flow-nexus@latest login
|
||||
|
||||
# Add MCP server to Claude Code
|
||||
claude mcp add flow-nexus npx flow-nexus@latest mcp start
|
||||
```
|
||||
|
||||
## Support & Resources
|
||||
|
||||
- **Platform**: https://flow-nexus.ruv.io
|
||||
- **Documentation**: https://github.com/ruvnet/flow-nexus
|
||||
- **Issues**: https://github.com/ruvnet/flow-nexus/issues
|
||||
|
||||
---
|
||||
|
||||
**Remember**: Flow Nexus provides cloud-based orchestration infrastructure. For local execution and coordination, use the core `claude-flow` MCP server alongside Flow Nexus for maximum flexibility.
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
name: food-order
|
||||
description: Reorder Foodora orders + track ETA/status with ordercli. Never confirm without explicit user approval. Triggers: order food, reorder, track ETA.
|
||||
homepage: https://ordercli.sh
|
||||
metadata: {"zee":{"emoji":"🥡","requires":{"bins":["ordercli"]},"install":[{"id":"go","kind":"go","module":"github.com/steipete/ordercli/cmd/ordercli@latest","bins":["ordercli"],"label":"Install ordercli (go)"}]}}
|
||||
---
|
||||
|
||||
# Food order (Foodora via ordercli)
|
||||
|
||||
Goal: reorder a previous Foodora order safely (preview first; confirm only on explicit user “yes/confirm/place the order”).
|
||||
|
||||
Hard safety rules
|
||||
- Never run `ordercli foodora reorder ... --confirm` unless user explicitly confirms placing the order.
|
||||
- Prefer preview-only steps first; show what will happen; ask for confirmation.
|
||||
- If user is unsure: stop at preview and ask questions.
|
||||
|
||||
Setup (once)
|
||||
- Country: `ordercli foodora countries` → `ordercli foodora config set --country AT`
|
||||
- Login (password): `ordercli foodora login --email you@example.com --password-stdin`
|
||||
- Login (no password, preferred): `ordercli foodora session chrome --url https://www.foodora.at/ --profile "Default"`
|
||||
|
||||
Find what to reorder
|
||||
- Recent list: `ordercli foodora history --limit 10`
|
||||
- Details: `ordercli foodora history show <orderCode>`
|
||||
- If needed (machine-readable): `ordercli foodora history show <orderCode> --json`
|
||||
|
||||
Preview reorder (no cart changes)
|
||||
- `ordercli foodora reorder <orderCode>`
|
||||
|
||||
Place reorder (cart change; explicit confirmation required)
|
||||
- Confirm first, then run: `ordercli foodora reorder <orderCode> --confirm`
|
||||
- Multiple addresses? Ask user for the right `--address-id` (take from their Foodora account / prior order data) and run:
|
||||
- `ordercli foodora reorder <orderCode> --confirm --address-id <id>`
|
||||
|
||||
Track the order
|
||||
- ETA/status (active list): `ordercli foodora orders`
|
||||
- Live updates: `ordercli foodora orders --watch`
|
||||
- Single order detail: `ordercli foodora order <orderCode>`
|
||||
|
||||
Debug / safe testing
|
||||
- Use a throwaway config: `ordercli --config /tmp/ordercli.json ...`
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
name: gemini
|
||||
description: Gemini CLI for one-shot Q&A, summaries, and generation.
|
||||
homepage: https://ai.google.dev/
|
||||
metadata: {"zee":{"emoji":"♊️","requires":{"bins":["gemini"]},"install":[{"id":"brew","kind":"brew","formula":"gemini-cli","bins":["gemini"],"label":"Install Gemini CLI (brew)"}]}}
|
||||
---
|
||||
|
||||
# Gemini CLI
|
||||
|
||||
Use Gemini in one-shot mode with a positional prompt (avoid interactive mode).
|
||||
|
||||
Quick start
|
||||
- `gemini "Answer this question..."`
|
||||
- `gemini --model <name> "Prompt..."`
|
||||
- `gemini --output-format json "Return JSON"`
|
||||
|
||||
Extensions
|
||||
- List: `gemini --list-extensions`
|
||||
- Manage: `gemini extensions <command>`
|
||||
|
||||
Notes
|
||||
- If auth is required, run `gemini` once interactively and follow the login flow.
|
||||
- Avoid `--yolo` for safety.
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
name: gifgrep
|
||||
description: Search GIF providers with CLI/TUI, download results, and extract stills/sheets.
|
||||
homepage: https://gifgrep.com
|
||||
metadata: {"zee":{"emoji":"🧲","requires":{"bins":["gifgrep"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/gifgrep","bins":["gifgrep"],"label":"Install gifgrep (brew)"},{"id":"go","kind":"go","module":"github.com/steipete/gifgrep/cmd/gifgrep@latest","bins":["gifgrep"],"label":"Install gifgrep (go)"}]}}
|
||||
---
|
||||
|
||||
# gifgrep
|
||||
|
||||
Use `gifgrep` to search GIF providers (Tenor/Giphy), browse in a TUI, download results, and extract stills or sheets.
|
||||
|
||||
GIF-Grab (gifgrep workflow)
|
||||
- Search → preview → download → extract (still/sheet) for fast review and sharing.
|
||||
|
||||
Quick start
|
||||
- `gifgrep cats --max 5`
|
||||
- `gifgrep cats --format url | head -n 5`
|
||||
- `gifgrep search --json cats | jq '.[0].url'`
|
||||
- `gifgrep tui "office handshake"`
|
||||
- `gifgrep cats --download --max 1 --format url`
|
||||
|
||||
TUI + previews
|
||||
- TUI: `gifgrep tui "query"`
|
||||
- CLI still previews: `--thumbs` (Kitty/Ghostty only; still frame)
|
||||
|
||||
Download + reveal
|
||||
- `--download` saves to `~/Downloads`
|
||||
- `--reveal` shows the last download in Finder
|
||||
|
||||
Stills + sheets
|
||||
- `gifgrep still ./clip.gif --at 1.5s -o still.png`
|
||||
- `gifgrep sheet ./clip.gif --frames 9 --cols 3 -o sheet.png`
|
||||
- Sheets = single PNG grid of sampled frames (great for quick review, docs, PRs, chat).
|
||||
- Tune: `--frames` (count), `--cols` (grid width), `--padding` (spacing).
|
||||
|
||||
Providers
|
||||
- `--source auto|tenor|giphy`
|
||||
- `GIPHY_API_KEY` required for `--source giphy`
|
||||
- `TENOR_API_KEY` optional (Tenor demo key used if unset)
|
||||
|
||||
Output
|
||||
- `--json` prints an array of results (`id`, `title`, `url`, `preview_url`, `tags`, `width`, `height`)
|
||||
- `--format` for pipe-friendly fields (e.g., `url`)
|
||||
|
||||
Environment tweaks
|
||||
- `GIFGREP_SOFTWARE_ANIM=1` to force software animation
|
||||
- `GIFGREP_CELL_ASPECT=0.5` to tweak preview geometry
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,874 @@
|
||||
---
|
||||
name: github-multi-repo
|
||||
version: 1.0.0
|
||||
description: Multi-repository coordination, synchronization, and architecture management with AI swarm orchestration
|
||||
category: github-integration
|
||||
tags: [multi-repo, synchronization, architecture, coordination, github]
|
||||
author: Claude Flow Team
|
||||
requires:
|
||||
- ruv-swarm@^1.0.11
|
||||
- gh-cli@^2.0.0
|
||||
capabilities:
|
||||
- cross-repository coordination
|
||||
- package synchronization
|
||||
- architecture optimization
|
||||
- template management
|
||||
- distributed workflows
|
||||
---
|
||||
|
||||
# GitHub Multi-Repository Coordination Skill
|
||||
|
||||
## Overview
|
||||
|
||||
Advanced multi-repository coordination system that combines swarm intelligence, package synchronization, and repository architecture optimization. This skill enables organization-wide automation, cross-project collaboration, and scalable repository management.
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
### 🔄 Multi-Repository Swarm Coordination
|
||||
Cross-repository AI swarm orchestration for distributed development workflows.
|
||||
|
||||
### 📦 Package Synchronization
|
||||
Intelligent dependency resolution and version alignment across multiple packages.
|
||||
|
||||
### 🏗️ Repository Architecture
|
||||
Structure optimization and template management for scalable projects.
|
||||
|
||||
### 🔗 Integration Management
|
||||
Cross-package integration testing and deployment coordination.
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Initialize Multi-Repo Coordination
|
||||
```bash
|
||||
# Basic swarm initialization
|
||||
npx claude-flow skill run github-multi-repo init \
|
||||
--repos "org/frontend,org/backend,org/shared" \
|
||||
--topology hierarchical
|
||||
|
||||
# Advanced initialization with synchronization
|
||||
npx claude-flow skill run github-multi-repo init \
|
||||
--repos "org/frontend,org/backend,org/shared" \
|
||||
--topology mesh \
|
||||
--shared-memory \
|
||||
--sync-strategy eventual
|
||||
```
|
||||
|
||||
### Synchronize Packages
|
||||
```bash
|
||||
# Synchronize package versions and dependencies
|
||||
npx claude-flow skill run github-multi-repo sync \
|
||||
--packages "claude-code-flow,ruv-swarm" \
|
||||
--align-versions \
|
||||
--update-docs
|
||||
```
|
||||
|
||||
### Optimize Architecture
|
||||
```bash
|
||||
# Analyze and optimize repository structure
|
||||
npx claude-flow skill run github-multi-repo optimize \
|
||||
--analyze-structure \
|
||||
--suggest-improvements \
|
||||
--create-templates
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
### 1. Cross-Repository Swarm Orchestration
|
||||
|
||||
#### Repository Discovery
|
||||
```javascript
|
||||
// Auto-discover related repositories with gh CLI
|
||||
const REPOS = Bash(`gh repo list my-organization --limit 100 \
|
||||
--json name,description,languages,topics \
|
||||
--jq '.[] | select(.languages | keys | contains(["TypeScript"]))'`)
|
||||
|
||||
// Analyze repository dependencies
|
||||
const DEPS = Bash(`gh repo list my-organization --json name | \
|
||||
jq -r '.[].name' | while read -r repo; do
|
||||
gh api repos/my-organization/$repo/contents/package.json \
|
||||
--jq '.content' 2>/dev/null | base64 -d | jq '{name, dependencies}'
|
||||
done | jq -s '.'`)
|
||||
|
||||
// Initialize swarm with discovered repositories
|
||||
mcp__claude-flow__swarm_init({
|
||||
topology: "hierarchical",
|
||||
maxAgents: 8,
|
||||
metadata: { repos: REPOS, dependencies: DEPS }
|
||||
})
|
||||
```
|
||||
|
||||
#### Synchronized Operations
|
||||
```javascript
|
||||
// Execute synchronized changes across repositories
|
||||
[Parallel Multi-Repo Operations]:
|
||||
// Spawn coordination agents
|
||||
Task("Repository Coordinator", "Coordinate changes across all repositories", "coordinator")
|
||||
Task("Dependency Analyzer", "Analyze cross-repo dependencies", "analyst")
|
||||
Task("Integration Tester", "Validate cross-repo changes", "tester")
|
||||
|
||||
// Get matching repositories
|
||||
Bash(`gh repo list org --limit 100 --json name \
|
||||
--jq '.[] | select(.name | test("-service$")) | .name' > /tmp/repos.txt`)
|
||||
|
||||
// Execute task across repositories
|
||||
Bash(`cat /tmp/repos.txt | while read -r repo; do
|
||||
gh repo clone org/$repo /tmp/$repo -- --depth=1
|
||||
cd /tmp/$repo
|
||||
|
||||
# Apply changes
|
||||
npm update
|
||||
npm test
|
||||
|
||||
# Create PR if successful
|
||||
if [ $? -eq 0 ]; then
|
||||
git checkout -b update-dependencies-$(date +%Y%m%d)
|
||||
git add -A
|
||||
git commit -m "chore: Update dependencies"
|
||||
git push origin HEAD
|
||||
gh pr create --title "Update dependencies" --body "Automated update" --label "dependencies"
|
||||
fi
|
||||
done`)
|
||||
|
||||
// Track all operations
|
||||
TodoWrite { todos: [
|
||||
{ id: "discover", content: "Discover all service repositories", status: "completed" },
|
||||
{ id: "update", content: "Update dependencies", status: "completed" },
|
||||
{ id: "test", content: "Run integration tests", status: "in_progress" },
|
||||
{ id: "pr", content: "Create pull requests", status: "pending" }
|
||||
]}
|
||||
```
|
||||
|
||||
### 2. Package Synchronization
|
||||
|
||||
#### Version Alignment
|
||||
```javascript
|
||||
// Synchronize package dependencies and versions
|
||||
[Complete Package Sync]:
|
||||
// Initialize sync swarm
|
||||
mcp__claude-flow__swarm_init({ topology: "mesh", maxAgents: 5 })
|
||||
|
||||
// Spawn sync agents
|
||||
Task("Sync Coordinator", "Coordinate version alignment", "coordinator")
|
||||
Task("Dependency Analyzer", "Analyze dependencies", "analyst")
|
||||
Task("Integration Tester", "Validate synchronization", "tester")
|
||||
|
||||
// Read package states
|
||||
Read("/workspaces/ruv-FANN/claude-code-flow/claude-code-flow/package.json")
|
||||
Read("/workspaces/ruv-FANN/ruv-swarm/npm/package.json")
|
||||
|
||||
// Align versions using gh CLI
|
||||
Bash(`gh api repos/:owner/:repo/git/refs \
|
||||
-f ref='refs/heads/sync/package-alignment' \
|
||||
-f sha=$(gh api repos/:owner/:repo/git/refs/heads/main --jq '.object.sha')`)
|
||||
|
||||
// Update package.json files
|
||||
Bash(`gh api repos/:owner/:repo/contents/package.json \
|
||||
--method PUT \
|
||||
-f message="feat: Align Node.js version requirements" \
|
||||
-f branch="sync/package-alignment" \
|
||||
-f content="$(cat aligned-package.json | base64)"`)
|
||||
|
||||
// Store sync state
|
||||
mcp__claude-flow__memory_usage({
|
||||
action: "store",
|
||||
key: "sync/packages/status",
|
||||
value: {
|
||||
timestamp: Date.now(),
|
||||
packages_synced: ["claude-code-flow", "ruv-swarm"],
|
||||
status: "synchronized"
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
#### Documentation Synchronization
|
||||
```javascript
|
||||
// Synchronize CLAUDE.md files across packages
|
||||
[Documentation Sync]:
|
||||
// Get source documentation
|
||||
Bash(`gh api repos/:owner/:repo/contents/ruv-swarm/docs/CLAUDE.md \
|
||||
--jq '.content' | base64 -d > /tmp/claude-source.md`)
|
||||
|
||||
// Update target documentation
|
||||
Bash(`gh api repos/:owner/:repo/contents/claude-code-flow/CLAUDE.md \
|
||||
--method PUT \
|
||||
-f message="docs: Synchronize CLAUDE.md" \
|
||||
-f branch="sync/documentation" \
|
||||
-f content="$(cat /tmp/claude-source.md | base64)"`)
|
||||
|
||||
// Track sync status
|
||||
mcp__claude-flow__memory_usage({
|
||||
action: "store",
|
||||
key: "sync/documentation/status",
|
||||
value: { status: "synchronized", files: ["CLAUDE.md"] }
|
||||
})
|
||||
```
|
||||
|
||||
#### Cross-Package Integration
|
||||
```javascript
|
||||
// Coordinate feature implementation across packages
|
||||
[Cross-Package Feature]:
|
||||
// Push changes to all packages
|
||||
mcp__github__push_files({
|
||||
branch: "feature/github-integration",
|
||||
files: [
|
||||
{
|
||||
path: "claude-code-flow/.claude/commands/github/github-modes.md",
|
||||
content: "[GitHub modes documentation]"
|
||||
},
|
||||
{
|
||||
path: "ruv-swarm/src/github-coordinator/hooks.js",
|
||||
content: "[GitHub coordination hooks]"
|
||||
}
|
||||
],
|
||||
message: "feat: Add GitHub workflow integration"
|
||||
})
|
||||
|
||||
// Create coordinated PR
|
||||
Bash(`gh pr create \
|
||||
--title "Feature: GitHub Workflow Integration" \
|
||||
--body "## 🚀 GitHub Integration
|
||||
|
||||
### Features
|
||||
- ✅ Multi-repo coordination
|
||||
- ✅ Package synchronization
|
||||
- ✅ Architecture optimization
|
||||
|
||||
### Testing
|
||||
- [x] Package dependency verification
|
||||
- [x] Integration tests
|
||||
- [x] Cross-package compatibility"`)
|
||||
```
|
||||
|
||||
### 3. Repository Architecture
|
||||
|
||||
#### Structure Analysis
|
||||
```javascript
|
||||
// Analyze and optimize repository structure
|
||||
[Architecture Analysis]:
|
||||
// Initialize architecture swarm
|
||||
mcp__claude-flow__swarm_init({ topology: "hierarchical", maxAgents: 6 })
|
||||
|
||||
// Spawn architecture agents
|
||||
Task("Senior Architect", "Analyze repository structure", "architect")
|
||||
Task("Structure Analyst", "Identify optimization opportunities", "analyst")
|
||||
Task("Performance Optimizer", "Optimize structure for scalability", "optimizer")
|
||||
Task("Best Practices Researcher", "Research architecture patterns", "researcher")
|
||||
|
||||
// Analyze current structures
|
||||
LS("/workspaces/ruv-FANN/claude-code-flow/claude-code-flow")
|
||||
LS("/workspaces/ruv-FANN/ruv-swarm/npm")
|
||||
|
||||
// Search for best practices
|
||||
Bash(`gh search repos "language:javascript template architecture" \
|
||||
--limit 10 \
|
||||
--json fullName,description,stargazersCount \
|
||||
--sort stars \
|
||||
--order desc`)
|
||||
|
||||
// Store analysis results
|
||||
mcp__claude-flow__memory_usage({
|
||||
action: "store",
|
||||
key: "architecture/analysis/results",
|
||||
value: {
|
||||
repositories_analyzed: ["claude-code-flow", "ruv-swarm"],
|
||||
optimization_areas: ["structure", "workflows", "templates"],
|
||||
recommendations: ["standardize_structure", "improve_workflows"]
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
#### Template Creation
|
||||
```javascript
|
||||
// Create standardized repository template
|
||||
[Template Creation]:
|
||||
// Create template repository
|
||||
mcp__github__create_repository({
|
||||
name: "claude-project-template",
|
||||
description: "Standardized template for Claude Code projects",
|
||||
private: false,
|
||||
autoInit: true
|
||||
})
|
||||
|
||||
// Push template structure
|
||||
mcp__github__push_files({
|
||||
repo: "claude-project-template",
|
||||
files: [
|
||||
{
|
||||
path: ".claude/commands/github/github-modes.md",
|
||||
content: "[GitHub modes template]"
|
||||
},
|
||||
{
|
||||
path: ".claude/config.json",
|
||||
content: JSON.stringify({
|
||||
version: "1.0",
|
||||
mcp_servers: {
|
||||
"ruv-swarm": {
|
||||
command: "npx",
|
||||
args: ["ruv-swarm", "mcp", "start"]
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
{
|
||||
path: "CLAUDE.md",
|
||||
content: "[Standardized CLAUDE.md]"
|
||||
},
|
||||
{
|
||||
path: "package.json",
|
||||
content: JSON.stringify({
|
||||
name: "claude-project-template",
|
||||
engines: { node: ">=20.0.0" },
|
||||
dependencies: { "ruv-swarm": "^1.0.11" }
|
||||
})
|
||||
}
|
||||
],
|
||||
message: "feat: Create standardized template"
|
||||
})
|
||||
```
|
||||
|
||||
#### Cross-Repository Standardization
|
||||
```javascript
|
||||
// Synchronize structure across repositories
|
||||
[Structure Standardization]:
|
||||
const repositories = ["claude-code-flow", "ruv-swarm", "claude-extensions"]
|
||||
|
||||
// Update common files across all repositories
|
||||
repositories.forEach(repo => {
|
||||
mcp__github__create_or_update_file({
|
||||
repo: "ruv-FANN",
|
||||
path: `${repo}/.github/workflows/integration.yml`,
|
||||
content: `name: Integration Tests
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-node@v3
|
||||
with: { node-version: '20' }
|
||||
- run: npm install && npm test`,
|
||||
message: "ci: Standardize integration workflow",
|
||||
branch: "structure/standardization"
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
### 4. Orchestration Workflows
|
||||
|
||||
#### Dependency Management
|
||||
```javascript
|
||||
// Update dependencies across all repositories
|
||||
[Organization-Wide Dependency Update]:
|
||||
// Create tracking issue
|
||||
TRACKING_ISSUE=$(Bash(`gh issue create \
|
||||
--title "Dependency Update: typescript@5.0.0" \
|
||||
--body "Tracking TypeScript update across all repositories" \
|
||||
--label "dependencies,tracking" \
|
||||
--json number -q .number`))
|
||||
|
||||
// Find all TypeScript repositories
|
||||
TS_REPOS=$(Bash(`gh repo list org --limit 100 --json name | \
|
||||
jq -r '.[].name' | while read -r repo; do
|
||||
if gh api repos/org/$repo/contents/package.json 2>/dev/null | \
|
||||
jq -r '.content' | base64 -d | grep -q '"typescript"'; then
|
||||
echo "$repo"
|
||||
fi
|
||||
done`))
|
||||
|
||||
// Update each repository
|
||||
Bash(`echo "$TS_REPOS" | while read -r repo; do
|
||||
gh repo clone org/$repo /tmp/$repo -- --depth=1
|
||||
cd /tmp/$repo
|
||||
|
||||
npm install --save-dev typescript@5.0.0
|
||||
|
||||
if npm test; then
|
||||
git checkout -b update-typescript-5
|
||||
git add package.json package-lock.json
|
||||
git commit -m "chore: Update TypeScript to 5.0.0
|
||||
|
||||
Part of #$TRACKING_ISSUE"
|
||||
|
||||
git push origin HEAD
|
||||
gh pr create \
|
||||
--title "Update TypeScript to 5.0.0" \
|
||||
--body "Updates TypeScript\n\nTracking: #$TRACKING_ISSUE" \
|
||||
--label "dependencies"
|
||||
else
|
||||
gh issue comment $TRACKING_ISSUE \
|
||||
--body "❌ Failed to update $repo - tests failing"
|
||||
fi
|
||||
done`)
|
||||
```
|
||||
|
||||
#### Refactoring Operations
|
||||
```javascript
|
||||
// Coordinate large-scale refactoring
|
||||
[Cross-Repo Refactoring]:
|
||||
// Initialize refactoring swarm
|
||||
mcp__claude-flow__swarm_init({ topology: "mesh", maxAgents: 8 })
|
||||
|
||||
// Spawn specialized agents
|
||||
Task("Refactoring Coordinator", "Coordinate refactoring across repos", "coordinator")
|
||||
Task("Impact Analyzer", "Analyze refactoring impact", "analyst")
|
||||
Task("Code Transformer", "Apply refactoring changes", "coder")
|
||||
Task("Migration Guide Creator", "Create migration documentation", "documenter")
|
||||
Task("Integration Tester", "Validate refactored code", "tester")
|
||||
|
||||
// Execute refactoring
|
||||
mcp__claude-flow__task_orchestrate({
|
||||
task: "Rename OldAPI to NewAPI across all repositories",
|
||||
strategy: "sequential",
|
||||
priority: "high"
|
||||
})
|
||||
```
|
||||
|
||||
#### Security Updates
|
||||
```javascript
|
||||
// Coordinate security patches
|
||||
[Security Patch Deployment]:
|
||||
// Scan all repositories
|
||||
Bash(`gh repo list org --limit 100 --json name | jq -r '.[].name' | \
|
||||
while read -r repo; do
|
||||
gh repo clone org/$repo /tmp/$repo -- --depth=1
|
||||
cd /tmp/$repo
|
||||
npm audit --json > /tmp/audit-$repo.json
|
||||
done`)
|
||||
|
||||
// Apply patches
|
||||
Bash(`for repo in /tmp/audit-*.json; do
|
||||
if [ $(jq '.vulnerabilities | length' $repo) -gt 0 ]; then
|
||||
cd /tmp/$(basename $repo .json | sed 's/audit-//')
|
||||
npm audit fix
|
||||
|
||||
if npm test; then
|
||||
git checkout -b security/patch-$(date +%Y%m%d)
|
||||
git add -A
|
||||
git commit -m "security: Apply security patches"
|
||||
git push origin HEAD
|
||||
gh pr create --title "Security patches" --label "security"
|
||||
fi
|
||||
fi
|
||||
done`)
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Multi-Repo Config File
|
||||
```yaml
|
||||
# .swarm/multi-repo.yml
|
||||
version: 1
|
||||
organization: my-org
|
||||
|
||||
repositories:
|
||||
- name: frontend
|
||||
url: github.com/my-org/frontend
|
||||
role: ui
|
||||
agents: [coder, designer, tester]
|
||||
|
||||
- name: backend
|
||||
url: github.com/my-org/backend
|
||||
role: api
|
||||
agents: [architect, coder, tester]
|
||||
|
||||
- name: shared
|
||||
url: github.com/my-org/shared
|
||||
role: library
|
||||
agents: [analyst, coder]
|
||||
|
||||
coordination:
|
||||
topology: hierarchical
|
||||
communication: webhook
|
||||
memory: redis://shared-memory
|
||||
|
||||
dependencies:
|
||||
- from: frontend
|
||||
to: [backend, shared]
|
||||
- from: backend
|
||||
to: [shared]
|
||||
```
|
||||
|
||||
### Repository Roles
|
||||
```javascript
|
||||
{
|
||||
"roles": {
|
||||
"ui": {
|
||||
"responsibilities": ["user-interface", "ux", "accessibility"],
|
||||
"default-agents": ["designer", "coder", "tester"]
|
||||
},
|
||||
"api": {
|
||||
"responsibilities": ["endpoints", "business-logic", "data"],
|
||||
"default-agents": ["architect", "coder", "security"]
|
||||
},
|
||||
"library": {
|
||||
"responsibilities": ["shared-code", "utilities", "types"],
|
||||
"default-agents": ["analyst", "coder", "documenter"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Communication Strategies
|
||||
|
||||
### 1. Webhook-Based Coordination
|
||||
```javascript
|
||||
const { MultiRepoSwarm } = require('ruv-swarm');
|
||||
|
||||
const swarm = new MultiRepoSwarm({
|
||||
webhook: {
|
||||
url: 'https://swarm-coordinator.example.com',
|
||||
secret: process.env.WEBHOOK_SECRET
|
||||
}
|
||||
});
|
||||
|
||||
swarm.on('repo:update', async (event) => {
|
||||
await swarm.propagate(event, {
|
||||
to: event.dependencies,
|
||||
strategy: 'eventual-consistency'
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Event Streaming
|
||||
```yaml
|
||||
# Kafka configuration for real-time coordination
|
||||
kafka:
|
||||
brokers: ['kafka1:9092', 'kafka2:9092']
|
||||
topics:
|
||||
swarm-events:
|
||||
partitions: 10
|
||||
replication: 3
|
||||
swarm-memory:
|
||||
partitions: 5
|
||||
replication: 3
|
||||
```
|
||||
|
||||
## Synchronization Patterns
|
||||
|
||||
### 1. Eventually Consistent
|
||||
```javascript
|
||||
{
|
||||
"sync": {
|
||||
"strategy": "eventual",
|
||||
"max-lag": "5m",
|
||||
"retry": {
|
||||
"attempts": 3,
|
||||
"backoff": "exponential"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Strong Consistency
|
||||
```javascript
|
||||
{
|
||||
"sync": {
|
||||
"strategy": "strong",
|
||||
"consensus": "raft",
|
||||
"quorum": 0.51,
|
||||
"timeout": "30s"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Hybrid Approach
|
||||
```javascript
|
||||
{
|
||||
"sync": {
|
||||
"default": "eventual",
|
||||
"overrides": {
|
||||
"security-updates": "strong",
|
||||
"dependency-updates": "strong",
|
||||
"documentation": "eventual"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
### 1. Microservices Coordination
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo microservices \
|
||||
--services "auth,users,orders,payments" \
|
||||
--ensure-compatibility \
|
||||
--sync-contracts \
|
||||
--integration-tests
|
||||
```
|
||||
|
||||
### 2. Library Updates
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo lib-update \
|
||||
--library "org/shared-lib" \
|
||||
--version "2.0.0" \
|
||||
--find-consumers \
|
||||
--update-imports \
|
||||
--run-tests
|
||||
```
|
||||
|
||||
### 3. Organization-Wide Changes
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo org-policy \
|
||||
--policy "add-security-headers" \
|
||||
--repos "org/*" \
|
||||
--validate-compliance \
|
||||
--create-reports
|
||||
```
|
||||
|
||||
## Architecture Patterns
|
||||
|
||||
### Monorepo Structure
|
||||
```
|
||||
ruv-FANN/
|
||||
├── packages/
|
||||
│ ├── claude-code-flow/
|
||||
│ │ ├── src/
|
||||
│ │ ├── .claude/
|
||||
│ │ └── package.json
|
||||
│ ├── ruv-swarm/
|
||||
│ │ ├── src/
|
||||
│ │ ├── wasm/
|
||||
│ │ └── package.json
|
||||
│ └── shared/
|
||||
│ ├── types/
|
||||
│ ├── utils/
|
||||
│ └── config/
|
||||
├── tools/
|
||||
│ ├── build/
|
||||
│ ├── test/
|
||||
│ └── deploy/
|
||||
├── docs/
|
||||
│ ├── architecture/
|
||||
│ ├── integration/
|
||||
│ └── examples/
|
||||
└── .github/
|
||||
├── workflows/
|
||||
├── templates/
|
||||
└── actions/
|
||||
```
|
||||
|
||||
### Command Structure
|
||||
```
|
||||
.claude/
|
||||
├── commands/
|
||||
│ ├── github/
|
||||
│ │ ├── github-modes.md
|
||||
│ │ ├── pr-manager.md
|
||||
│ │ ├── issue-tracker.md
|
||||
│ │ └── sync-coordinator.md
|
||||
│ ├── sparc/
|
||||
│ │ ├── sparc-modes.md
|
||||
│ │ ├── coder.md
|
||||
│ │ └── tester.md
|
||||
│ └── swarm/
|
||||
│ ├── coordination.md
|
||||
│ └── orchestration.md
|
||||
├── templates/
|
||||
│ ├── issue.md
|
||||
│ ├── pr.md
|
||||
│ └── project.md
|
||||
└── config.json
|
||||
```
|
||||
|
||||
## Monitoring & Visualization
|
||||
|
||||
### Multi-Repo Dashboard
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo dashboard \
|
||||
--port 3000 \
|
||||
--metrics "agent-activity,task-progress,memory-usage" \
|
||||
--real-time
|
||||
```
|
||||
|
||||
### Dependency Graph
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo dep-graph \
|
||||
--format mermaid \
|
||||
--include-agents \
|
||||
--show-data-flow
|
||||
```
|
||||
|
||||
### Health Monitoring
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo health-check \
|
||||
--repos "org/*" \
|
||||
--check "connectivity,memory,agents" \
|
||||
--alert-on-issues
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Repository Organization
|
||||
- Clear repository roles and boundaries
|
||||
- Consistent naming conventions
|
||||
- Documented dependencies
|
||||
- Shared configuration standards
|
||||
|
||||
### 2. Communication
|
||||
- Use appropriate sync strategies
|
||||
- Implement circuit breakers
|
||||
- Monitor latency and failures
|
||||
- Clear error propagation
|
||||
|
||||
### 3. Security
|
||||
- Secure cross-repo authentication
|
||||
- Encrypted communication channels
|
||||
- Audit trail for all operations
|
||||
- Principle of least privilege
|
||||
|
||||
### 4. Version Management
|
||||
- Semantic versioning alignment
|
||||
- Dependency compatibility validation
|
||||
- Automated version bump coordination
|
||||
|
||||
### 5. Testing Integration
|
||||
- Cross-package test validation
|
||||
- Integration test automation
|
||||
- Performance regression detection
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Caching Strategy
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo cache-strategy \
|
||||
--analyze-patterns \
|
||||
--suggest-cache-layers \
|
||||
--implement-invalidation
|
||||
```
|
||||
|
||||
### Parallel Execution
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo parallel-optimize \
|
||||
--analyze-dependencies \
|
||||
--identify-parallelizable \
|
||||
--execute-optimal
|
||||
```
|
||||
|
||||
### Resource Pooling
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo resource-pool \
|
||||
--share-agents \
|
||||
--distribute-load \
|
||||
--monitor-usage
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Connectivity Issues
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo diagnose-connectivity \
|
||||
--test-all-repos \
|
||||
--check-permissions \
|
||||
--verify-webhooks
|
||||
```
|
||||
|
||||
### Memory Synchronization
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo debug-memory \
|
||||
--check-consistency \
|
||||
--identify-conflicts \
|
||||
--repair-state
|
||||
```
|
||||
|
||||
### Performance Bottlenecks
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo perf-analysis \
|
||||
--profile-operations \
|
||||
--identify-bottlenecks \
|
||||
--suggest-optimizations
|
||||
```
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### 1. Distributed Task Queue
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo queue \
|
||||
--backend redis \
|
||||
--workers 10 \
|
||||
--priority-routing \
|
||||
--dead-letter-queue
|
||||
```
|
||||
|
||||
### 2. Cross-Repo Testing
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo test \
|
||||
--setup-test-env \
|
||||
--link-services \
|
||||
--run-e2e \
|
||||
--tear-down
|
||||
```
|
||||
|
||||
### 3. Monorepo Migration
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo to-monorepo \
|
||||
--analyze-repos \
|
||||
--suggest-structure \
|
||||
--preserve-history \
|
||||
--create-migration-prs
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Full-Stack Application Update
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo fullstack-update \
|
||||
--frontend "org/web-app" \
|
||||
--backend "org/api-server" \
|
||||
--database "org/db-migrations" \
|
||||
--coordinate-deployment
|
||||
```
|
||||
|
||||
### Cross-Team Collaboration
|
||||
```bash
|
||||
npx claude-flow skill run github-multi-repo cross-team \
|
||||
--teams "frontend,backend,devops" \
|
||||
--task "implement-feature-x" \
|
||||
--assign-by-expertise \
|
||||
--track-progress
|
||||
```
|
||||
|
||||
## Metrics and Reporting
|
||||
|
||||
### Sync Quality Metrics
|
||||
- Package version alignment percentage
|
||||
- Documentation consistency score
|
||||
- Integration test success rate
|
||||
- Synchronization completion time
|
||||
|
||||
### Architecture Health Metrics
|
||||
- Repository structure consistency score
|
||||
- Documentation coverage percentage
|
||||
- Cross-repository integration success rate
|
||||
- Template adoption and usage statistics
|
||||
|
||||
### Automated Reporting
|
||||
- Weekly sync status reports
|
||||
- Dependency drift detection
|
||||
- Documentation divergence alerts
|
||||
- Integration health monitoring
|
||||
|
||||
## Integration Points
|
||||
|
||||
### Related Skills
|
||||
- `github-workflow` - GitHub workflow automation
|
||||
- `github-pr` - Pull request management
|
||||
- `sparc-architect` - Architecture design
|
||||
- `sparc-optimizer` - Performance optimization
|
||||
|
||||
### Related Commands
|
||||
- `/github sync-coordinator` - Cross-repo synchronization
|
||||
- `/github release-manager` - Coordinated releases
|
||||
- `/github repo-architect` - Repository optimization
|
||||
- `/sparc architect` - Detailed architecture design
|
||||
|
||||
## Support and Resources
|
||||
|
||||
- Documentation: https://github.com/ruvnet/claude-flow
|
||||
- Issues: https://github.com/ruvnet/claude-flow/issues
|
||||
- Examples: `.claude/examples/github-multi-repo/`
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.0.0
|
||||
**Last Updated:** 2025-10-19
|
||||
**Maintainer:** Claude Flow Team
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,47 @@
|
||||
---
|
||||
name: github
|
||||
description: "Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries."
|
||||
---
|
||||
|
||||
# GitHub Skill
|
||||
|
||||
Use the `gh` CLI to interact with GitHub. Always specify `--repo owner/repo` when not in a git directory, or use URLs directly.
|
||||
|
||||
## Pull Requests
|
||||
|
||||
Check CI status on a PR:
|
||||
```bash
|
||||
gh pr checks 55 --repo owner/repo
|
||||
```
|
||||
|
||||
List recent workflow runs:
|
||||
```bash
|
||||
gh run list --repo owner/repo --limit 10
|
||||
```
|
||||
|
||||
View a run and see which steps failed:
|
||||
```bash
|
||||
gh run view <run-id> --repo owner/repo
|
||||
```
|
||||
|
||||
View logs for failed steps only:
|
||||
```bash
|
||||
gh run view <run-id> --repo owner/repo --log-failed
|
||||
```
|
||||
|
||||
## API for Advanced Queries
|
||||
|
||||
The `gh api` command is useful for accessing data not available through other subcommands.
|
||||
|
||||
Get PR with specific fields:
|
||||
```bash
|
||||
gh api repos/owner/repo/pulls/55 --jq '.title, .state, .user.login'
|
||||
```
|
||||
|
||||
## JSON Output
|
||||
|
||||
Most commands support `--json` for structured output. You can use `--jq` to filter:
|
||||
|
||||
```bash
|
||||
gh issue list --repo owner/repo --json number,title --jq '.[] | "\(.number): \(.title)"'
|
||||
```
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
name: gog
|
||||
description: Google Workspace CLI for Gmail, Calendar, Drive, Contacts, Sheets, and Docs.
|
||||
homepage: https://gogcli.sh
|
||||
metadata: {"zee":{"emoji":"🎮","requires":{"bins":["gog"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/gogcli","bins":["gog"],"label":"Install gog (brew)"}]}}
|
||||
---
|
||||
|
||||
# gog
|
||||
|
||||
Use `gog` for Gmail/Calendar/Drive/Contacts/Sheets/Docs. Requires OAuth setup.
|
||||
|
||||
Setup (once)
|
||||
- `gog auth credentials /path/to/client_secret.json`
|
||||
- `gog auth add you@gmail.com --services gmail,calendar,drive,contacts,sheets,docs`
|
||||
- `gog auth list`
|
||||
|
||||
Common commands
|
||||
- Gmail search: `gog gmail search 'newer_than:7d' --max 10`
|
||||
- Gmail send: `gog gmail send --to a@b.com --subject "Hi" --body "Hello"`
|
||||
- Calendar: `gog calendar events <calendarId> --from <iso> --to <iso>`
|
||||
- Drive search: `gog drive search "query" --max 10`
|
||||
- Contacts: `gog contacts list --max 20`
|
||||
- Sheets get: `gog sheets get <sheetId> "Tab!A1:D10" --json`
|
||||
- Sheets update: `gog sheets update <sheetId> "Tab!A1:B2" --values-json '[["A","B"],["1","2"]]' --input USER_ENTERED`
|
||||
- Sheets append: `gog sheets append <sheetId> "Tab!A:C" --values-json '[["x","y","z"]]' --insert INSERT_ROWS`
|
||||
- Sheets clear: `gog sheets clear <sheetId> "Tab!A2:Z"`
|
||||
- Sheets metadata: `gog sheets metadata <sheetId> --json`
|
||||
- Docs export: `gog docs export <docId> --format txt --out /tmp/doc.txt`
|
||||
- Docs cat: `gog docs cat <docId>`
|
||||
|
||||
Notes
|
||||
- Set `GOG_ACCOUNT=you@gmail.com` to avoid repeating `--account`.
|
||||
- For scripting, prefer `--json` plus `--no-input`.
|
||||
- Sheets values can be passed via `--values-json` (recommended) or as inline rows.
|
||||
- Docs supports export/cat/copy. In-place edits require a Docs API client (not in gog).
|
||||
- Confirm before sending mail or creating events.
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: goplaces
|
||||
description: Query Google Places API (New) via the goplaces CLI for text search, place details, resolve, and reviews. Use for human-friendly place lookup or JSON output for scripts.
|
||||
homepage: https://github.com/steipete/goplaces
|
||||
metadata: {"zee":{"emoji":"📍","requires":{"bins":["goplaces"],"env":["GOOGLE_PLACES_API_KEY"]},"primaryEnv":"GOOGLE_PLACES_API_KEY","install":[{"id":"brew","kind":"brew","formula":"steipete/tap/goplaces","bins":["goplaces"],"label":"Install goplaces (brew)"}]}}
|
||||
---
|
||||
|
||||
# goplaces
|
||||
|
||||
Modern Google Places API (New) CLI. Human output by default, `--json` for scripts.
|
||||
|
||||
Install
|
||||
- Homebrew: `brew install steipete/tap/goplaces`
|
||||
|
||||
Config
|
||||
- `GOOGLE_PLACES_API_KEY` required.
|
||||
- Optional: `GOOGLE_PLACES_BASE_URL` for testing/proxying.
|
||||
|
||||
Common commands
|
||||
- Search: `goplaces search "coffee" --open-now --min-rating 4 --limit 5`
|
||||
- Bias: `goplaces search "pizza" --lat 40.8 --lng -73.9 --radius-m 3000`
|
||||
- Pagination: `goplaces search "pizza" --page-token "NEXT_PAGE_TOKEN"`
|
||||
- Resolve: `goplaces resolve "Soho, London" --limit 5`
|
||||
- Details: `goplaces details <place_id> --reviews`
|
||||
- JSON: `goplaces search "sushi" --json`
|
||||
|
||||
Notes
|
||||
- `--no-color` or `NO_COLOR` disables ANSI color.
|
||||
- Price levels: 0..4 (free → very expensive).
|
||||
- Type filter sends only the first `--type` value (API accepts one).
|
||||
@@ -0,0 +1,217 @@
|
||||
---
|
||||
name: himalaya
|
||||
description: "CLI to manage emails via IMAP/SMTP. Use `himalaya` to list, read, write, reply, forward, search, and organize emails from the terminal. Supports multiple accounts and message composition with MML (MIME Meta Language)."
|
||||
homepage: https://github.com/pimalaya/himalaya
|
||||
metadata: {"zee":{"emoji":"📧","requires":{"bins":["himalaya"]},"install":[{"id":"brew","kind":"brew","formula":"himalaya","bins":["himalaya"],"label":"Install Himalaya (brew)"}]}}
|
||||
---
|
||||
|
||||
# Himalaya Email CLI
|
||||
|
||||
Himalaya is a CLI email client that lets you manage emails from the terminal using IMAP, SMTP, Notmuch, or Sendmail backends.
|
||||
|
||||
## References
|
||||
|
||||
- `references/configuration.md` (config file setup + IMAP/SMTP authentication)
|
||||
- `references/message-composition.md` (MML syntax for composing emails)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. Himalaya CLI installed (`himalaya --version` to verify)
|
||||
2. A configuration file at `~/.config/himalaya/config.toml`
|
||||
3. IMAP/SMTP credentials configured (password stored securely)
|
||||
|
||||
## Configuration Setup
|
||||
|
||||
Run the interactive wizard to set up an account:
|
||||
```bash
|
||||
himalaya account configure
|
||||
```
|
||||
|
||||
Or create `~/.config/himalaya/config.toml` manually:
|
||||
```toml
|
||||
[accounts.personal]
|
||||
email = "you@example.com"
|
||||
display-name = "Your Name"
|
||||
default = true
|
||||
|
||||
backend.type = "imap"
|
||||
backend.host = "imap.example.com"
|
||||
backend.port = 993
|
||||
backend.encryption.type = "tls"
|
||||
backend.login = "you@example.com"
|
||||
backend.auth.type = "password"
|
||||
backend.auth.cmd = "pass show email/imap" # or use keyring
|
||||
|
||||
message.send.backend.type = "smtp"
|
||||
message.send.backend.host = "smtp.example.com"
|
||||
message.send.backend.port = 587
|
||||
message.send.backend.encryption.type = "start-tls"
|
||||
message.send.backend.login = "you@example.com"
|
||||
message.send.backend.auth.type = "password"
|
||||
message.send.backend.auth.cmd = "pass show email/smtp"
|
||||
```
|
||||
|
||||
## Common Operations
|
||||
|
||||
### List Folders
|
||||
|
||||
```bash
|
||||
himalaya folder list
|
||||
```
|
||||
|
||||
### List Emails
|
||||
|
||||
List emails in INBOX (default):
|
||||
```bash
|
||||
himalaya envelope list
|
||||
```
|
||||
|
||||
List emails in a specific folder:
|
||||
```bash
|
||||
himalaya envelope list --folder "Sent"
|
||||
```
|
||||
|
||||
List with pagination:
|
||||
```bash
|
||||
himalaya envelope list --page 1 --page-size 20
|
||||
```
|
||||
|
||||
### Search Emails
|
||||
|
||||
```bash
|
||||
himalaya envelope list from john@example.com subject meeting
|
||||
```
|
||||
|
||||
### Read an Email
|
||||
|
||||
Read email by ID (shows plain text):
|
||||
```bash
|
||||
himalaya message read 42
|
||||
```
|
||||
|
||||
Export raw MIME:
|
||||
```bash
|
||||
himalaya message export 42 --full
|
||||
```
|
||||
|
||||
### Reply to an Email
|
||||
|
||||
Interactive reply (opens $EDITOR):
|
||||
```bash
|
||||
himalaya message reply 42
|
||||
```
|
||||
|
||||
Reply-all:
|
||||
```bash
|
||||
himalaya message reply 42 --all
|
||||
```
|
||||
|
||||
### Forward an Email
|
||||
|
||||
```bash
|
||||
himalaya message forward 42
|
||||
```
|
||||
|
||||
### Write a New Email
|
||||
|
||||
Interactive compose (opens $EDITOR):
|
||||
```bash
|
||||
himalaya message write
|
||||
```
|
||||
|
||||
Send directly using template:
|
||||
```bash
|
||||
cat << 'EOF' | himalaya template send
|
||||
From: you@example.com
|
||||
To: recipient@example.com
|
||||
Subject: Test Message
|
||||
|
||||
Hello from Himalaya!
|
||||
EOF
|
||||
```
|
||||
|
||||
Or with headers flag:
|
||||
```bash
|
||||
himalaya message write -H "To:recipient@example.com" -H "Subject:Test" "Message body here"
|
||||
```
|
||||
|
||||
### Move/Copy Emails
|
||||
|
||||
Move to folder:
|
||||
```bash
|
||||
himalaya message move 42 "Archive"
|
||||
```
|
||||
|
||||
Copy to folder:
|
||||
```bash
|
||||
himalaya message copy 42 "Important"
|
||||
```
|
||||
|
||||
### Delete an Email
|
||||
|
||||
```bash
|
||||
himalaya message delete 42
|
||||
```
|
||||
|
||||
### Manage Flags
|
||||
|
||||
Add flag:
|
||||
```bash
|
||||
himalaya flag add 42 --flag seen
|
||||
```
|
||||
|
||||
Remove flag:
|
||||
```bash
|
||||
himalaya flag remove 42 --flag seen
|
||||
```
|
||||
|
||||
## Multiple Accounts
|
||||
|
||||
List accounts:
|
||||
```bash
|
||||
himalaya account list
|
||||
```
|
||||
|
||||
Use a specific account:
|
||||
```bash
|
||||
himalaya --account work envelope list
|
||||
```
|
||||
|
||||
## Attachments
|
||||
|
||||
Save attachments from a message:
|
||||
```bash
|
||||
himalaya attachment download 42
|
||||
```
|
||||
|
||||
Save to specific directory:
|
||||
```bash
|
||||
himalaya attachment download 42 --dir ~/Downloads
|
||||
```
|
||||
|
||||
## Output Formats
|
||||
|
||||
Most commands support `--output` for structured output:
|
||||
```bash
|
||||
himalaya envelope list --output json
|
||||
himalaya envelope list --output plain
|
||||
```
|
||||
|
||||
## Debugging
|
||||
|
||||
Enable debug logging:
|
||||
```bash
|
||||
RUST_LOG=debug himalaya envelope list
|
||||
```
|
||||
|
||||
Full trace with backtrace:
|
||||
```bash
|
||||
RUST_LOG=trace RUST_BACKTRACE=1 himalaya envelope list
|
||||
```
|
||||
|
||||
## Tips
|
||||
|
||||
- Use `himalaya --help` or `himalaya <command> --help` for detailed usage.
|
||||
- Message IDs are relative to the current folder; re-list after folder changes.
|
||||
- For composing rich emails with attachments, use MML syntax (see `references/message-composition.md`).
|
||||
- Store passwords securely using `pass`, system keyring, or a command that outputs the password.
|
||||
@@ -0,0 +1,174 @@
|
||||
# Himalaya Configuration Reference
|
||||
|
||||
Configuration file location: `~/.config/himalaya/config.toml`
|
||||
|
||||
## Minimal IMAP + SMTP Setup
|
||||
|
||||
```toml
|
||||
[accounts.default]
|
||||
email = "user@example.com"
|
||||
display-name = "Your Name"
|
||||
default = true
|
||||
|
||||
# IMAP backend for reading emails
|
||||
backend.type = "imap"
|
||||
backend.host = "imap.example.com"
|
||||
backend.port = 993
|
||||
backend.encryption.type = "tls"
|
||||
backend.login = "user@example.com"
|
||||
backend.auth.type = "password"
|
||||
backend.auth.raw = "your-password"
|
||||
|
||||
# SMTP backend for sending emails
|
||||
message.send.backend.type = "smtp"
|
||||
message.send.backend.host = "smtp.example.com"
|
||||
message.send.backend.port = 587
|
||||
message.send.backend.encryption.type = "start-tls"
|
||||
message.send.backend.login = "user@example.com"
|
||||
message.send.backend.auth.type = "password"
|
||||
message.send.backend.auth.raw = "your-password"
|
||||
```
|
||||
|
||||
## Password Options
|
||||
|
||||
### Raw password (testing only, not recommended)
|
||||
```toml
|
||||
backend.auth.raw = "your-password"
|
||||
```
|
||||
|
||||
### Password from command (recommended)
|
||||
```toml
|
||||
backend.auth.cmd = "pass show email/imap"
|
||||
# backend.auth.cmd = "security find-generic-password -a user@example.com -s imap -w"
|
||||
```
|
||||
|
||||
### System keyring (requires keyring feature)
|
||||
```toml
|
||||
backend.auth.keyring = "imap-example"
|
||||
```
|
||||
Then run `himalaya account configure <account>` to store the password.
|
||||
|
||||
## Gmail Configuration
|
||||
|
||||
```toml
|
||||
[accounts.gmail]
|
||||
email = "you@gmail.com"
|
||||
display-name = "Your Name"
|
||||
default = true
|
||||
|
||||
backend.type = "imap"
|
||||
backend.host = "imap.gmail.com"
|
||||
backend.port = 993
|
||||
backend.encryption.type = "tls"
|
||||
backend.login = "you@gmail.com"
|
||||
backend.auth.type = "password"
|
||||
backend.auth.cmd = "pass show google/app-password"
|
||||
|
||||
message.send.backend.type = "smtp"
|
||||
message.send.backend.host = "smtp.gmail.com"
|
||||
message.send.backend.port = 587
|
||||
message.send.backend.encryption.type = "start-tls"
|
||||
message.send.backend.login = "you@gmail.com"
|
||||
message.send.backend.auth.type = "password"
|
||||
message.send.backend.auth.cmd = "pass show google/app-password"
|
||||
```
|
||||
|
||||
**Note:** Gmail requires an App Password if 2FA is enabled.
|
||||
|
||||
## iCloud Configuration
|
||||
|
||||
```toml
|
||||
[accounts.icloud]
|
||||
email = "you@icloud.com"
|
||||
display-name = "Your Name"
|
||||
|
||||
backend.type = "imap"
|
||||
backend.host = "imap.mail.me.com"
|
||||
backend.port = 993
|
||||
backend.encryption.type = "tls"
|
||||
backend.login = "you@icloud.com"
|
||||
backend.auth.type = "password"
|
||||
backend.auth.cmd = "pass show icloud/app-password"
|
||||
|
||||
message.send.backend.type = "smtp"
|
||||
message.send.backend.host = "smtp.mail.me.com"
|
||||
message.send.backend.port = 587
|
||||
message.send.backend.encryption.type = "start-tls"
|
||||
message.send.backend.login = "you@icloud.com"
|
||||
message.send.backend.auth.type = "password"
|
||||
message.send.backend.auth.cmd = "pass show icloud/app-password"
|
||||
```
|
||||
|
||||
**Note:** Generate an app-specific password at appleid.apple.com
|
||||
|
||||
## Folder Aliases
|
||||
|
||||
Map custom folder names:
|
||||
```toml
|
||||
[accounts.default.folder.alias]
|
||||
inbox = "INBOX"
|
||||
sent = "Sent"
|
||||
drafts = "Drafts"
|
||||
trash = "Trash"
|
||||
```
|
||||
|
||||
## Multiple Accounts
|
||||
|
||||
```toml
|
||||
[accounts.personal]
|
||||
email = "personal@example.com"
|
||||
default = true
|
||||
# ... backend config ...
|
||||
|
||||
[accounts.work]
|
||||
email = "work@company.com"
|
||||
# ... backend config ...
|
||||
```
|
||||
|
||||
Switch accounts with `--account`:
|
||||
```bash
|
||||
himalaya --account work envelope list
|
||||
```
|
||||
|
||||
## Notmuch Backend (local mail)
|
||||
|
||||
```toml
|
||||
[accounts.local]
|
||||
email = "user@example.com"
|
||||
|
||||
backend.type = "notmuch"
|
||||
backend.db-path = "~/.mail/.notmuch"
|
||||
```
|
||||
|
||||
## OAuth2 Authentication (for providers that support it)
|
||||
|
||||
```toml
|
||||
backend.auth.type = "oauth2"
|
||||
backend.auth.client-id = "your-client-id"
|
||||
backend.auth.client-secret.cmd = "pass show oauth/client-secret"
|
||||
backend.auth.access-token.cmd = "pass show oauth/access-token"
|
||||
backend.auth.refresh-token.cmd = "pass show oauth/refresh-token"
|
||||
backend.auth.auth-url = "https://provider.com/oauth/authorize"
|
||||
backend.auth.token-url = "https://provider.com/oauth/token"
|
||||
```
|
||||
|
||||
## Additional Options
|
||||
|
||||
### Signature
|
||||
```toml
|
||||
[accounts.default]
|
||||
signature = "Best regards,\nYour Name"
|
||||
signature-delim = "-- \n"
|
||||
```
|
||||
|
||||
### Downloads directory
|
||||
```toml
|
||||
[accounts.default]
|
||||
downloads-dir = "~/Downloads/himalaya"
|
||||
```
|
||||
|
||||
### Editor for composing
|
||||
Set via environment variable:
|
||||
```bash
|
||||
export EDITOR="vim"
|
||||
```
|
||||
@@ -0,0 +1,182 @@
|
||||
# Message Composition with MML (MIME Meta Language)
|
||||
|
||||
Himalaya uses MML for composing emails. MML is a simple XML-based syntax that compiles to MIME messages.
|
||||
|
||||
## Basic Message Structure
|
||||
|
||||
An email message is a list of **headers** followed by a **body**, separated by a blank line:
|
||||
|
||||
```
|
||||
From: sender@example.com
|
||||
To: recipient@example.com
|
||||
Subject: Hello World
|
||||
|
||||
This is the message body.
|
||||
```
|
||||
|
||||
## Headers
|
||||
|
||||
Common headers:
|
||||
- `From`: Sender address
|
||||
- `To`: Primary recipient(s)
|
||||
- `Cc`: Carbon copy recipients
|
||||
- `Bcc`: Blind carbon copy recipients
|
||||
- `Subject`: Message subject
|
||||
- `Reply-To`: Address for replies (if different from From)
|
||||
- `In-Reply-To`: Message ID being replied to
|
||||
|
||||
### Address Formats
|
||||
|
||||
```
|
||||
To: user@example.com
|
||||
To: John Doe <john@example.com>
|
||||
To: "John Doe" <john@example.com>
|
||||
To: user1@example.com, user2@example.com, "Jane" <jane@example.com>
|
||||
```
|
||||
|
||||
## Plain Text Body
|
||||
|
||||
Simple plain text email:
|
||||
```
|
||||
From: alice@localhost
|
||||
To: bob@localhost
|
||||
Subject: Plain Text Example
|
||||
|
||||
Hello, this is a plain text email.
|
||||
No special formatting needed.
|
||||
|
||||
Best,
|
||||
Alice
|
||||
```
|
||||
|
||||
## MML for Rich Emails
|
||||
|
||||
### Multipart Messages
|
||||
|
||||
Alternative text/html parts:
|
||||
```
|
||||
From: alice@localhost
|
||||
To: bob@localhost
|
||||
Subject: Multipart Example
|
||||
|
||||
<#multipart type=alternative>
|
||||
This is the plain text version.
|
||||
<#part type=text/html>
|
||||
<html><body><h1>This is the HTML version</h1></body></html>
|
||||
<#/multipart>
|
||||
```
|
||||
|
||||
### Attachments
|
||||
|
||||
Attach a file:
|
||||
```
|
||||
From: alice@localhost
|
||||
To: bob@localhost
|
||||
Subject: With Attachment
|
||||
|
||||
Here is the document you requested.
|
||||
|
||||
<#part filename=/path/to/document.pdf><#/part>
|
||||
```
|
||||
|
||||
Attachment with custom name:
|
||||
```
|
||||
<#part filename=/path/to/file.pdf name=report.pdf><#/part>
|
||||
```
|
||||
|
||||
Multiple attachments:
|
||||
```
|
||||
<#part filename=/path/to/doc1.pdf><#/part>
|
||||
<#part filename=/path/to/doc2.pdf><#/part>
|
||||
```
|
||||
|
||||
### Inline Images
|
||||
|
||||
Embed an image inline:
|
||||
```
|
||||
From: alice@localhost
|
||||
To: bob@localhost
|
||||
Subject: Inline Image
|
||||
|
||||
<#multipart type=related>
|
||||
<#part type=text/html>
|
||||
<html><body>
|
||||
<p>Check out this image:</p>
|
||||
<img src="cid:image1">
|
||||
</body></html>
|
||||
<#part disposition=inline id=image1 filename=/path/to/image.png><#/part>
|
||||
<#/multipart>
|
||||
```
|
||||
|
||||
### Mixed Content (Text + Attachments)
|
||||
|
||||
```
|
||||
From: alice@localhost
|
||||
To: bob@localhost
|
||||
Subject: Mixed Content
|
||||
|
||||
<#multipart type=mixed>
|
||||
<#part type=text/plain>
|
||||
Please find the attached files.
|
||||
|
||||
Best,
|
||||
Alice
|
||||
<#part filename=/path/to/file1.pdf><#/part>
|
||||
<#part filename=/path/to/file2.zip><#/part>
|
||||
<#/multipart>
|
||||
```
|
||||
|
||||
## MML Tag Reference
|
||||
|
||||
### `<#multipart>`
|
||||
Groups multiple parts together.
|
||||
- `type=alternative`: Different representations of same content
|
||||
- `type=mixed`: Independent parts (text + attachments)
|
||||
- `type=related`: Parts that reference each other (HTML + images)
|
||||
|
||||
### `<#part>`
|
||||
Defines a message part.
|
||||
- `type=<mime-type>`: Content type (e.g., `text/html`, `application/pdf`)
|
||||
- `filename=<path>`: File to attach
|
||||
- `name=<name>`: Display name for attachment
|
||||
- `disposition=inline`: Display inline instead of as attachment
|
||||
- `id=<cid>`: Content ID for referencing in HTML
|
||||
|
||||
## Composing from CLI
|
||||
|
||||
### Interactive compose
|
||||
Opens your `$EDITOR`:
|
||||
```bash
|
||||
himalaya message write
|
||||
```
|
||||
|
||||
### Reply (opens editor with quoted message)
|
||||
```bash
|
||||
himalaya message reply 42
|
||||
himalaya message reply 42 --all # reply-all
|
||||
```
|
||||
|
||||
### Forward
|
||||
```bash
|
||||
himalaya message forward 42
|
||||
```
|
||||
|
||||
### Send from stdin
|
||||
```bash
|
||||
cat message.txt | himalaya template send
|
||||
```
|
||||
|
||||
### Prefill headers from CLI
|
||||
```bash
|
||||
himalaya message write \
|
||||
-H "To:recipient@example.com" \
|
||||
-H "Subject:Quick Message" \
|
||||
"Message body here"
|
||||
```
|
||||
|
||||
## Tips
|
||||
|
||||
- The editor opens with a template; fill in headers and body.
|
||||
- Save and exit the editor to send; exit without saving to cancel.
|
||||
- MML parts are compiled to proper MIME when sending.
|
||||
- Use `himalaya message export --full` to inspect the raw MIME structure of received emails.
|
||||
@@ -0,0 +1,712 @@
|
||||
---
|
||||
name: hive-mind-advanced
|
||||
description: Advanced Hive Mind collective intelligence system for queen-led multi-agent coordination with consensus mechanisms and persistent memory
|
||||
version: 1.0.0
|
||||
category: coordination
|
||||
tags: [hive-mind, swarm, queen-worker, consensus, collective-intelligence, multi-agent, coordination]
|
||||
author: Claude Flow Team
|
||||
---
|
||||
|
||||
# Hive Mind Advanced Skill
|
||||
|
||||
Master the advanced Hive Mind collective intelligence system for sophisticated multi-agent coordination using queen-led architecture, Byzantine consensus, and collective memory.
|
||||
|
||||
## Overview
|
||||
|
||||
The Hive Mind system represents the pinnacle of multi-agent coordination in Claude Flow, implementing a queen-led hierarchical architecture where a strategic queen coordinator directs specialized worker agents through collective decision-making and shared memory.
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Architecture Patterns
|
||||
|
||||
**Queen-Led Coordination**
|
||||
- Strategic queen agents orchestrate high-level objectives
|
||||
- Tactical queens manage mid-level execution
|
||||
- Adaptive queens dynamically adjust strategies based on performance
|
||||
|
||||
**Worker Specialization**
|
||||
- Researcher agents: Analysis and investigation
|
||||
- Coder agents: Implementation and development
|
||||
- Analyst agents: Data processing and metrics
|
||||
- Tester agents: Quality assurance and validation
|
||||
- Architect agents: System design and planning
|
||||
- Reviewer agents: Code review and improvement
|
||||
- Optimizer agents: Performance enhancement
|
||||
- Documenter agents: Documentation generation
|
||||
|
||||
**Collective Memory System**
|
||||
- Shared knowledge base across all agents
|
||||
- LRU cache with memory pressure handling
|
||||
- SQLite persistence with WAL mode
|
||||
- Memory consolidation and association
|
||||
- Access pattern tracking and optimization
|
||||
|
||||
### Consensus Mechanisms
|
||||
|
||||
**Majority Consensus**
|
||||
Simple voting where the option with most votes wins.
|
||||
|
||||
**Weighted Consensus**
|
||||
Queen vote counts as 3x weight, providing strategic guidance.
|
||||
|
||||
**Byzantine Fault Tolerance**
|
||||
Requires 2/3 majority for decision approval, ensuring robust consensus even with faulty agents.
|
||||
|
||||
## Getting Started
|
||||
|
||||
### 1. Initialize Hive Mind
|
||||
|
||||
```bash
|
||||
# Basic initialization
|
||||
npx claude-flow hive-mind init
|
||||
|
||||
# Force reinitialize
|
||||
npx claude-flow hive-mind init --force
|
||||
|
||||
# Custom configuration
|
||||
npx claude-flow hive-mind init --config hive-config.json
|
||||
```
|
||||
|
||||
### 2. Spawn a Swarm
|
||||
|
||||
```bash
|
||||
# Basic spawn with objective
|
||||
npx claude-flow hive-mind spawn "Build microservices architecture"
|
||||
|
||||
# Strategic queen type
|
||||
npx claude-flow hive-mind spawn "Research AI patterns" --queen-type strategic
|
||||
|
||||
# Tactical queen with max workers
|
||||
npx claude-flow hive-mind spawn "Implement API" --queen-type tactical --max-workers 12
|
||||
|
||||
# Adaptive queen with consensus
|
||||
npx claude-flow hive-mind spawn "Optimize system" --queen-type adaptive --consensus byzantine
|
||||
|
||||
# Generate Claude Code commands
|
||||
npx claude-flow hive-mind spawn "Build full-stack app" --claude
|
||||
```
|
||||
|
||||
### 3. Monitor Status
|
||||
|
||||
```bash
|
||||
# Check hive mind status
|
||||
npx claude-flow hive-mind status
|
||||
|
||||
# Get detailed metrics
|
||||
npx claude-flow hive-mind metrics
|
||||
|
||||
# Monitor collective memory
|
||||
npx claude-flow hive-mind memory
|
||||
```
|
||||
|
||||
## Advanced Workflows
|
||||
|
||||
### Session Management
|
||||
|
||||
**Create and Manage Sessions**
|
||||
|
||||
```bash
|
||||
# List active sessions
|
||||
npx claude-flow hive-mind sessions
|
||||
|
||||
# Pause a session
|
||||
npx claude-flow hive-mind pause <session-id>
|
||||
|
||||
# Resume a paused session
|
||||
npx claude-flow hive-mind resume <session-id>
|
||||
|
||||
# Stop a running session
|
||||
npx claude-flow hive-mind stop <session-id>
|
||||
```
|
||||
|
||||
**Session Features**
|
||||
- Automatic checkpoint creation
|
||||
- Progress tracking with completion percentages
|
||||
- Parent-child process management
|
||||
- Session logs with event tracking
|
||||
- Export/import capabilities
|
||||
|
||||
### Consensus Building
|
||||
|
||||
The Hive Mind builds consensus through structured voting:
|
||||
|
||||
```javascript
|
||||
// Programmatic consensus building
|
||||
const decision = await hiveMind.buildConsensus(
|
||||
'Architecture pattern selection',
|
||||
['microservices', 'monolith', 'serverless']
|
||||
);
|
||||
|
||||
// Result includes:
|
||||
// - decision: Winning option
|
||||
// - confidence: Vote percentage
|
||||
// - votes: Individual agent votes
|
||||
```
|
||||
|
||||
**Consensus Algorithms**
|
||||
|
||||
1. **Majority** - Simple democratic voting
|
||||
2. **Weighted** - Queen has 3x voting power
|
||||
3. **Byzantine** - 2/3 supermajority required
|
||||
|
||||
### Collective Memory
|
||||
|
||||
**Storing Knowledge**
|
||||
|
||||
```javascript
|
||||
// Store in collective memory
|
||||
await memory.store('api-patterns', {
|
||||
rest: { pros: [...], cons: [...] },
|
||||
graphql: { pros: [...], cons: [...] }
|
||||
}, 'knowledge', { confidence: 0.95 });
|
||||
```
|
||||
|
||||
**Memory Types**
|
||||
- `knowledge`: Permanent insights (no TTL)
|
||||
- `context`: Session context (1 hour TTL)
|
||||
- `task`: Task-specific data (30 min TTL)
|
||||
- `result`: Execution results (permanent, compressed)
|
||||
- `error`: Error logs (24 hour TTL)
|
||||
- `metric`: Performance metrics (1 hour TTL)
|
||||
- `consensus`: Decision records (permanent)
|
||||
- `system`: System configuration (permanent)
|
||||
|
||||
**Searching and Retrieval**
|
||||
|
||||
```javascript
|
||||
// Search memory by pattern
|
||||
const results = await memory.search('api*', {
|
||||
type: 'knowledge',
|
||||
minConfidence: 0.8,
|
||||
limit: 50
|
||||
});
|
||||
|
||||
// Get related memories
|
||||
const related = await memory.getRelated('api-patterns', 10);
|
||||
|
||||
// Build associations
|
||||
await memory.associate('rest-api', 'authentication', 0.9);
|
||||
```
|
||||
|
||||
### Task Distribution
|
||||
|
||||
**Automatic Worker Assignment**
|
||||
|
||||
The system intelligently assigns tasks based on:
|
||||
- Keyword matching with agent specialization
|
||||
- Historical performance metrics
|
||||
- Worker availability and load
|
||||
- Task complexity analysis
|
||||
|
||||
```javascript
|
||||
// Create task (auto-assigned)
|
||||
const task = await hiveMind.createTask(
|
||||
'Implement user authentication',
|
||||
priority: 8,
|
||||
{ estimatedDuration: 30000 }
|
||||
);
|
||||
```
|
||||
|
||||
**Auto-Scaling**
|
||||
|
||||
```javascript
|
||||
// Configure auto-scaling
|
||||
const config = {
|
||||
autoScale: true,
|
||||
maxWorkers: 12,
|
||||
scaleUpThreshold: 2, // Pending tasks per idle worker
|
||||
scaleDownThreshold: 2 // Idle workers above pending tasks
|
||||
};
|
||||
```
|
||||
|
||||
## Integration Patterns
|
||||
|
||||
### With Claude Code
|
||||
|
||||
Generate Claude Code spawn commands directly:
|
||||
|
||||
```bash
|
||||
npx claude-flow hive-mind spawn "Build REST API" --claude
|
||||
```
|
||||
|
||||
Output:
|
||||
```javascript
|
||||
Task("Queen Coordinator", "Orchestrate REST API development...", "coordinator")
|
||||
Task("Backend Developer", "Implement Express routes...", "backend-dev")
|
||||
Task("Database Architect", "Design PostgreSQL schema...", "code-analyzer")
|
||||
Task("Test Engineer", "Create Jest test suite...", "tester")
|
||||
```
|
||||
|
||||
### With SPARC Methodology
|
||||
|
||||
```bash
|
||||
# Use hive mind for SPARC workflow
|
||||
npx claude-flow sparc tdd "User authentication" --hive-mind
|
||||
|
||||
# Spawns:
|
||||
# - Specification agent
|
||||
# - Architecture agent
|
||||
# - Coder agents
|
||||
# - Tester agents
|
||||
# - Reviewer agents
|
||||
```
|
||||
|
||||
### With GitHub Integration
|
||||
|
||||
```bash
|
||||
# Repository analysis with hive mind
|
||||
npx claude-flow hive-mind spawn "Analyze repo quality" --objective "owner/repo"
|
||||
|
||||
# PR review coordination
|
||||
npx claude-flow hive-mind spawn "Review PR #123" --queen-type tactical
|
||||
```
|
||||
|
||||
## Performance Optimization
|
||||
|
||||
### Memory Optimization
|
||||
|
||||
The collective memory system includes advanced optimizations:
|
||||
|
||||
**LRU Cache**
|
||||
- Configurable cache size (default: 1000 entries)
|
||||
- Memory pressure handling (default: 50MB)
|
||||
- Automatic eviction of least-used entries
|
||||
|
||||
**Database Optimization**
|
||||
- WAL (Write-Ahead Logging) mode
|
||||
- 64MB cache size
|
||||
- 256MB memory mapping
|
||||
- Prepared statements for common queries
|
||||
- Automatic ANALYZE and OPTIMIZE
|
||||
|
||||
**Object Pooling**
|
||||
- Query result pooling
|
||||
- Memory entry pooling
|
||||
- Reduced garbage collection pressure
|
||||
|
||||
### Performance Metrics
|
||||
|
||||
```javascript
|
||||
// Get performance insights
|
||||
const insights = hiveMind.getPerformanceInsights();
|
||||
|
||||
// Includes:
|
||||
// - asyncQueue utilization
|
||||
// - Batch processing stats
|
||||
// - Success rates
|
||||
// - Average processing times
|
||||
// - Memory efficiency
|
||||
```
|
||||
|
||||
### Task Execution
|
||||
|
||||
**Parallel Processing**
|
||||
- Batch agent spawning (5 agents per batch)
|
||||
- Concurrent task orchestration
|
||||
- Async operation optimization
|
||||
- Non-blocking task assignment
|
||||
|
||||
**Benchmarks**
|
||||
- 10-20x faster batch spawning
|
||||
- 2.8-4.4x speed improvement overall
|
||||
- 32.3% token reduction
|
||||
- 84.8% SWE-Bench solve rate
|
||||
|
||||
## Configuration
|
||||
|
||||
### Hive Mind Config
|
||||
|
||||
```javascript
|
||||
{
|
||||
"objective": "Build microservices",
|
||||
"name": "my-hive",
|
||||
"queenType": "strategic", // strategic | tactical | adaptive
|
||||
"maxWorkers": 8,
|
||||
"consensusAlgorithm": "byzantine", // majority | weighted | byzantine
|
||||
"autoScale": true,
|
||||
"memorySize": 100, // MB
|
||||
"taskTimeout": 60, // minutes
|
||||
"encryption": false
|
||||
}
|
||||
```
|
||||
|
||||
### Memory Config
|
||||
|
||||
```javascript
|
||||
{
|
||||
"maxSize": 100, // MB
|
||||
"compressionThreshold": 1024, // bytes
|
||||
"gcInterval": 300000, // 5 minutes
|
||||
"cacheSize": 1000,
|
||||
"cacheMemoryMB": 50,
|
||||
"enablePooling": true,
|
||||
"enableAsyncOperations": true
|
||||
}
|
||||
```
|
||||
|
||||
## Hooks Integration
|
||||
|
||||
Hive Mind integrates with Claude Flow hooks for automation:
|
||||
|
||||
**Pre-Task Hooks**
|
||||
- Auto-assign agents by file type
|
||||
- Validate objective complexity
|
||||
- Optimize topology selection
|
||||
- Cache search patterns
|
||||
|
||||
**Post-Task Hooks**
|
||||
- Auto-format deliverables
|
||||
- Train neural patterns
|
||||
- Update collective memory
|
||||
- Analyze performance bottlenecks
|
||||
|
||||
**Session Hooks**
|
||||
- Generate session summaries
|
||||
- Persist checkpoint data
|
||||
- Track comprehensive metrics
|
||||
- Restore execution context
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Choose the Right Queen Type
|
||||
|
||||
**Strategic Queens** - For research, planning, and analysis
|
||||
```bash
|
||||
npx claude-flow hive-mind spawn "Research ML frameworks" --queen-type strategic
|
||||
```
|
||||
|
||||
**Tactical Queens** - For implementation and execution
|
||||
```bash
|
||||
npx claude-flow hive-mind spawn "Build authentication" --queen-type tactical
|
||||
```
|
||||
|
||||
**Adaptive Queens** - For optimization and dynamic tasks
|
||||
```bash
|
||||
npx claude-flow hive-mind spawn "Optimize performance" --queen-type adaptive
|
||||
```
|
||||
|
||||
### 2. Leverage Consensus
|
||||
|
||||
Use consensus for critical decisions:
|
||||
- Architecture pattern selection
|
||||
- Technology stack choices
|
||||
- Implementation approach
|
||||
- Code review approval
|
||||
- Release readiness
|
||||
|
||||
### 3. Utilize Collective Memory
|
||||
|
||||
**Store Learnings**
|
||||
```javascript
|
||||
// After successful pattern implementation
|
||||
await memory.store('auth-pattern', {
|
||||
approach: 'JWT with refresh tokens',
|
||||
pros: ['Stateless', 'Scalable'],
|
||||
cons: ['Token size', 'Revocation complexity'],
|
||||
implementation: {...}
|
||||
}, 'knowledge', { confidence: 0.95 });
|
||||
```
|
||||
|
||||
**Build Associations**
|
||||
```javascript
|
||||
// Link related concepts
|
||||
await memory.associate('jwt-auth', 'refresh-tokens', 0.9);
|
||||
await memory.associate('jwt-auth', 'oauth2', 0.7);
|
||||
```
|
||||
|
||||
### 4. Monitor Performance
|
||||
|
||||
```bash
|
||||
# Regular status checks
|
||||
npx claude-flow hive-mind status
|
||||
|
||||
# Track metrics
|
||||
npx claude-flow hive-mind metrics
|
||||
|
||||
# Analyze memory usage
|
||||
npx claude-flow hive-mind memory
|
||||
```
|
||||
|
||||
### 5. Session Management
|
||||
|
||||
**Checkpoint Frequently**
|
||||
```javascript
|
||||
// Create checkpoints at key milestones
|
||||
await sessionManager.saveCheckpoint(
|
||||
sessionId,
|
||||
'api-routes-complete',
|
||||
{ completedRoutes: [...], remaining: [...] }
|
||||
);
|
||||
```
|
||||
|
||||
**Resume Sessions**
|
||||
```bash
|
||||
# Resume from any previous state
|
||||
npx claude-flow hive-mind resume <session-id>
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Memory Issues
|
||||
|
||||
**High Memory Usage**
|
||||
```bash
|
||||
# Run garbage collection
|
||||
npx claude-flow hive-mind memory --gc
|
||||
|
||||
# Optimize database
|
||||
npx claude-flow hive-mind memory --optimize
|
||||
|
||||
# Export and clear
|
||||
npx claude-flow hive-mind memory --export --clear
|
||||
```
|
||||
|
||||
**Low Cache Hit Rate**
|
||||
```javascript
|
||||
// Increase cache size in config
|
||||
{
|
||||
"cacheSize": 2000,
|
||||
"cacheMemoryMB": 100
|
||||
}
|
||||
```
|
||||
|
||||
### Performance Issues
|
||||
|
||||
**Slow Task Assignment**
|
||||
```javascript
|
||||
// Enable worker type caching
|
||||
// The system caches best worker matches for 5 minutes
|
||||
// Automatic - no configuration needed
|
||||
```
|
||||
|
||||
**High Queue Utilization**
|
||||
```javascript
|
||||
// Increase async queue concurrency
|
||||
{
|
||||
"asyncQueueConcurrency": 20 // Default: min(maxWorkers * 2, 20)
|
||||
}
|
||||
```
|
||||
|
||||
### Consensus Failures
|
||||
|
||||
**No Consensus Reached (Byzantine)**
|
||||
```bash
|
||||
# Switch to weighted consensus for more decisive results
|
||||
npx claude-flow hive-mind spawn "..." --consensus weighted
|
||||
|
||||
# Or use simple majority
|
||||
npx claude-flow hive-mind spawn "..." --consensus majority
|
||||
```
|
||||
|
||||
## Advanced Topics
|
||||
|
||||
### Custom Worker Types
|
||||
|
||||
Define specialized workers in `.claude/agents/`:
|
||||
|
||||
```yaml
|
||||
name: security-auditor
|
||||
type: specialist
|
||||
capabilities:
|
||||
- vulnerability-scanning
|
||||
- security-review
|
||||
- penetration-testing
|
||||
- compliance-checking
|
||||
priority: high
|
||||
```
|
||||
|
||||
### Neural Pattern Training
|
||||
|
||||
The system trains on successful patterns:
|
||||
|
||||
```javascript
|
||||
// Automatic pattern learning
|
||||
// Happens after successful task completion
|
||||
// Stores in collective memory
|
||||
// Improves future task matching
|
||||
```
|
||||
|
||||
### Multi-Hive Coordination
|
||||
|
||||
Run multiple hive minds simultaneously:
|
||||
|
||||
```bash
|
||||
# Frontend hive
|
||||
npx claude-flow hive-mind spawn "Build UI" --name frontend-hive
|
||||
|
||||
# Backend hive
|
||||
npx claude-flow hive-mind spawn "Build API" --name backend-hive
|
||||
|
||||
# They share collective memory for coordination
|
||||
```
|
||||
|
||||
### Export/Import Sessions
|
||||
|
||||
```bash
|
||||
# Export session for backup
|
||||
npx claude-flow hive-mind export <session-id> --output backup.json
|
||||
|
||||
# Import session
|
||||
npx claude-flow hive-mind import backup.json
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### HiveMindCore
|
||||
|
||||
```javascript
|
||||
const hiveMind = new HiveMindCore({
|
||||
objective: 'Build system',
|
||||
queenType: 'strategic',
|
||||
maxWorkers: 8,
|
||||
consensusAlgorithm: 'byzantine'
|
||||
});
|
||||
|
||||
await hiveMind.initialize();
|
||||
await hiveMind.spawnQueen(queenData);
|
||||
await hiveMind.spawnWorkers(['coder', 'tester']);
|
||||
await hiveMind.createTask('Implement feature', 7);
|
||||
const decision = await hiveMind.buildConsensus('topic', options);
|
||||
const status = hiveMind.getStatus();
|
||||
await hiveMind.shutdown();
|
||||
```
|
||||
|
||||
### CollectiveMemory
|
||||
|
||||
```javascript
|
||||
const memory = new CollectiveMemory({
|
||||
swarmId: 'hive-123',
|
||||
maxSize: 100,
|
||||
cacheSize: 1000
|
||||
});
|
||||
|
||||
await memory.store(key, value, type, metadata);
|
||||
const data = await memory.retrieve(key);
|
||||
const results = await memory.search(pattern, options);
|
||||
const related = await memory.getRelated(key, limit);
|
||||
await memory.associate(key1, key2, strength);
|
||||
const stats = memory.getStatistics();
|
||||
const analytics = memory.getAnalytics();
|
||||
const health = await memory.healthCheck();
|
||||
```
|
||||
|
||||
### HiveMindSessionManager
|
||||
|
||||
```javascript
|
||||
const sessionManager = new HiveMindSessionManager();
|
||||
|
||||
const sessionId = await sessionManager.createSession(
|
||||
swarmId, swarmName, objective, metadata
|
||||
);
|
||||
|
||||
await sessionManager.saveCheckpoint(sessionId, name, data);
|
||||
const sessions = await sessionManager.getActiveSessions();
|
||||
const session = await sessionManager.getSession(sessionId);
|
||||
await sessionManager.pauseSession(sessionId);
|
||||
await sessionManager.resumeSession(sessionId);
|
||||
await sessionManager.stopSession(sessionId);
|
||||
await sessionManager.completeSession(sessionId);
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Full-Stack Development
|
||||
|
||||
```bash
|
||||
# Initialize hive mind
|
||||
npx claude-flow hive-mind init
|
||||
|
||||
# Spawn full-stack hive
|
||||
npx claude-flow hive-mind spawn "Build e-commerce platform" \
|
||||
--queen-type strategic \
|
||||
--max-workers 10 \
|
||||
--consensus weighted \
|
||||
--claude
|
||||
|
||||
# Output generates Claude Code commands:
|
||||
# - Queen coordinator
|
||||
# - Frontend developers (React)
|
||||
# - Backend developers (Node.js)
|
||||
# - Database architects
|
||||
# - DevOps engineers
|
||||
# - Security auditors
|
||||
# - Test engineers
|
||||
# - Documentation specialists
|
||||
```
|
||||
|
||||
### Research and Analysis
|
||||
|
||||
```bash
|
||||
# Spawn research hive
|
||||
npx claude-flow hive-mind spawn "Research GraphQL vs REST" \
|
||||
--queen-type adaptive \
|
||||
--consensus byzantine
|
||||
|
||||
# Researchers gather data
|
||||
# Analysts process findings
|
||||
# Queen builds consensus on recommendation
|
||||
# Results stored in collective memory
|
||||
```
|
||||
|
||||
### Code Review
|
||||
|
||||
```bash
|
||||
# Review coordination
|
||||
npx claude-flow hive-mind spawn "Review PR #456" \
|
||||
--queen-type tactical \
|
||||
--max-workers 6
|
||||
|
||||
# Spawns:
|
||||
# - Code analyzers
|
||||
# - Security reviewers
|
||||
# - Performance reviewers
|
||||
# - Test coverage analyzers
|
||||
# - Documentation reviewers
|
||||
# - Consensus on approval/changes
|
||||
```
|
||||
|
||||
## Skill Progression
|
||||
|
||||
### Beginner
|
||||
1. Initialize hive mind
|
||||
2. Spawn basic swarms
|
||||
3. Monitor status
|
||||
4. Use majority consensus
|
||||
|
||||
### Intermediate
|
||||
1. Configure queen types
|
||||
2. Implement session management
|
||||
3. Use weighted consensus
|
||||
4. Access collective memory
|
||||
5. Enable auto-scaling
|
||||
|
||||
### Advanced
|
||||
1. Byzantine fault tolerance
|
||||
2. Memory optimization
|
||||
3. Custom worker types
|
||||
4. Multi-hive coordination
|
||||
5. Neural pattern training
|
||||
6. Session export/import
|
||||
7. Performance tuning
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `swarm-orchestration`: Basic swarm coordination
|
||||
- `consensus-mechanisms`: Distributed decision making
|
||||
- `memory-systems`: Advanced memory management
|
||||
- `sparc-methodology`: Structured development workflow
|
||||
- `github-integration`: Repository coordination
|
||||
|
||||
## References
|
||||
|
||||
- [Hive Mind Documentation](https://github.com/ruvnet/claude-flow/docs/hive-mind)
|
||||
- [Collective Intelligence Patterns](https://github.com/ruvnet/claude-flow/docs/patterns)
|
||||
- [Byzantine Consensus](https://github.com/ruvnet/claude-flow/docs/consensus)
|
||||
- [Memory Optimization](https://github.com/ruvnet/claude-flow/docs/memory)
|
||||
|
||||
---
|
||||
|
||||
**Skill Version**: 1.0.0
|
||||
**Last Updated**: 2025-10-19
|
||||
**Maintained By**: Claude Flow Team
|
||||
**License**: MIT
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: imsg
|
||||
description: iMessage/SMS CLI for listing chats, history, watch, and sending.
|
||||
homepage: https://imsg.to
|
||||
metadata: {"zee":{"emoji":"📨","os":["darwin"],"requires":{"bins":["imsg"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/imsg","bins":["imsg"],"label":"Install imsg (brew)"}]}}
|
||||
---
|
||||
|
||||
# imsg
|
||||
|
||||
Use `imsg` to read and send Messages.app iMessage/SMS on macOS.
|
||||
|
||||
Requirements
|
||||
- Messages.app signed in
|
||||
- Full Disk Access for your terminal
|
||||
- Automation permission to control Messages.app (for sending)
|
||||
|
||||
Common commands
|
||||
- List chats: `imsg chats --limit 10 --json`
|
||||
- History: `imsg history --chat-id 1 --limit 20 --attachments --json`
|
||||
- Watch: `imsg watch --chat-id 1 --attachments`
|
||||
- Send: `imsg send --to "+14155551212" --text "hi" --file /path/pic.jpg`
|
||||
|
||||
Notes
|
||||
- `--service imessage|sms|auto` controls delivery.
|
||||
- Confirm recipient + message before sending.
|
||||
@@ -0,0 +1,136 @@
|
||||
---
|
||||
name: investment-thesis
|
||||
description: Create and track investment theses with conviction levels
|
||||
triggers:
|
||||
- investment thesis
|
||||
- stock thesis
|
||||
- create thesis
|
||||
- update thesis
|
||||
- thesis tracking
|
||||
---
|
||||
|
||||
# Investment Thesis Management
|
||||
|
||||
Create, track, and manage investment theses using Stanley's note system.
|
||||
|
||||
## Creating a Thesis
|
||||
|
||||
### Research Phase
|
||||
1. Gather fundamental data (via OpenBB)
|
||||
2. Analyze financial statements (via Stanley/edgartools)
|
||||
3. Assess competitive position
|
||||
4. Build valuation model
|
||||
5. Identify risks and catalysts
|
||||
|
||||
### Thesis Template
|
||||
|
||||
Using Stanley's NoteManager:
|
||||
```
|
||||
from stanley.notes import NoteManager, ConvictionLevel
|
||||
|
||||
notes = NoteManager()
|
||||
|
||||
thesis = notes.create_thesis(
|
||||
symbol="AAPL",
|
||||
company_name="Apple Inc.",
|
||||
sector="Technology",
|
||||
conviction="high" # low, medium, high, very_high
|
||||
)
|
||||
```
|
||||
|
||||
## Thesis Structure
|
||||
|
||||
```markdown
|
||||
## Investment Thesis: AAPL
|
||||
|
||||
### Bull Case
|
||||
- Services revenue growing 15%+ annually
|
||||
- Installed base creates recurring revenue
|
||||
- Strong cash generation, shareholder returns
|
||||
|
||||
### Bear Case
|
||||
- iPhone dependence (50%+ revenue)
|
||||
- China regulatory/geopolitical risk
|
||||
- Hardware margin pressure
|
||||
|
||||
### Valuation
|
||||
- DCF Target: $185
|
||||
- Comparable Multiple: 28x forward PE
|
||||
- Current Price: $172
|
||||
|
||||
### Conviction Level: HIGH
|
||||
- Time Horizon: 12-18 months
|
||||
- Position Size: 5% of portfolio
|
||||
|
||||
### Catalysts
|
||||
- Q1 2024 earnings (Jan 25)
|
||||
- WWDC 2024 (Jun)
|
||||
- iPhone 16 launch (Sep)
|
||||
|
||||
### Risk Monitoring
|
||||
- Services growth < 10%
|
||||
- China revenue decline > 15%
|
||||
- Gross margin < 42%
|
||||
```
|
||||
|
||||
## Tracking Theses
|
||||
|
||||
```
|
||||
# Get active theses
|
||||
active = notes.get_theses(status="active")
|
||||
|
||||
# Get by symbol
|
||||
aapl_thesis = notes.get_theses(symbol="AAPL")
|
||||
|
||||
# Search theses
|
||||
results = notes.search("Services growth Technology")
|
||||
```
|
||||
|
||||
## Memory Integration
|
||||
|
||||
```typescript
|
||||
// Store thesis in memory for cross-session access
|
||||
await memory.store({
|
||||
namespace: "stanley/theses",
|
||||
key: symbol,
|
||||
value: {
|
||||
symbol,
|
||||
conviction,
|
||||
targetPrice,
|
||||
bullCase: [...],
|
||||
bearCase: [...],
|
||||
catalysts: [...],
|
||||
riskTriggers: [...],
|
||||
lastReviewed: new Date()
|
||||
}
|
||||
});
|
||||
|
||||
// Retrieve for quick access
|
||||
const thesis = await memory.retrieve("stanley/theses", symbol);
|
||||
```
|
||||
|
||||
## Thesis Review Workflow
|
||||
|
||||
Weekly review checklist:
|
||||
1. Price action vs thesis
|
||||
2. Any material news/events?
|
||||
3. Estimate revisions direction
|
||||
4. Technical levels
|
||||
5. Thesis still valid?
|
||||
|
||||
## Conviction Changes
|
||||
|
||||
Track conviction history:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "stanley/theses",
|
||||
key: symbol,
|
||||
value: {
|
||||
// ... existing fields
|
||||
history: [
|
||||
{ date: "2024-01-01", conviction: "medium", note: "Initial thesis" },
|
||||
{ date: "2024-01-20", conviction: "high", note: "Strong Q4 results" }
|
||||
]
|
||||
}
|
||||
});
|
||||
```
|
||||
@@ -76,7 +76,7 @@ johny: Shows mastery levels, at-risk topics, review schedule
|
||||
|
||||
## Integration Points
|
||||
|
||||
- **persona repo**: `~/Repositories/personas/johny/scripts/johny_cli.py`
|
||||
- **persona repo**: `~/.local/src/agent-core/vendor/personas/johny/scripts/johny_cli.py`
|
||||
- **Memory**: Qdrant vector store for topic embeddings
|
||||
- **Council**: Multi-model deliberation for explanations
|
||||
- **Browser**: Ingest content from web, PDFs, videos
|
||||
@@ -91,8 +91,8 @@ npx tsx scripts/johny-daemon.ts status
|
||||
|
||||
## Environment
|
||||
|
||||
- `JOHNY_REPO` (default: `~/Repositories/personas/johny`)
|
||||
- `JOHNY_CLI` (default: `~/Repositories/personas/johny/scripts/johny_cli.py`)
|
||||
- `JOHNY_REPO` (default: `~/.local/src/agent-core/vendor/personas/johny`)
|
||||
- `JOHNY_CLI` (default: `~/.local/src/agent-core/vendor/personas/johny/scripts/johny_cli.py`)
|
||||
|
||||
## When to Use johny
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ function getArg(name: string): string | undefined {
|
||||
|
||||
function resolveJohnyCli(): { python: string; cliPath: string } {
|
||||
const python = process.env.JOHNY_PYTHON || "python3";
|
||||
const repo = process.env.JOHNY_REPO || join(homedir(), "Repositories", "personas", "johny");
|
||||
const repo = process.env.JOHNY_REPO || join(homedir(), ".local", "src", "agent-core", "vendor", "personas", "johny");
|
||||
const cliPath = process.env.JOHNY_CLI || join(repo, "scripts", "johny_cli.py");
|
||||
return { python, cliPath };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# Local Places
|
||||
|
||||
This repo is a fusion of two pieces:
|
||||
|
||||
- A FastAPI server that exposes endpoints for searching and resolving places via the Google Maps Places API.
|
||||
- A companion agent skill that explains how to use the API and can call it to find places efficiently.
|
||||
|
||||
Together, the skill and server let an agent turn natural-language place queries into structured results quickly.
|
||||
|
||||
## Run locally
|
||||
|
||||
```bash
|
||||
# copy skill definition into the relevant folder (where the agent looks for it)
|
||||
# then run the server
|
||||
|
||||
uv venv
|
||||
uv pip install -e ".[dev]"
|
||||
uv run --env-file .env uvicorn local_places.main:app --host 0.0.0.0 --reload
|
||||
```
|
||||
|
||||
Open the API docs at http://127.0.0.1:8000/docs.
|
||||
|
||||
## Places API
|
||||
|
||||
Set the Google Places API key before running:
|
||||
|
||||
```bash
|
||||
export GOOGLE_PLACES_API_KEY="your-key"
|
||||
```
|
||||
|
||||
Endpoints:
|
||||
|
||||
- `POST /places/search` (free-text query + filters)
|
||||
- `GET /places/{place_id}` (place details)
|
||||
- `POST /locations/resolve` (resolve a user-provided location string)
|
||||
|
||||
Example search request:
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "italian restaurant",
|
||||
"filters": {
|
||||
"types": ["restaurant"],
|
||||
"open_now": true,
|
||||
"min_rating": 4.0,
|
||||
"price_levels": [1, 2]
|
||||
},
|
||||
"limit": 10
|
||||
}
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `filters.types` supports a single type (mapped to Google `includedType`).
|
||||
|
||||
Example search request (curl):
|
||||
|
||||
```bash
|
||||
curl -X POST http://127.0.0.1:8000/places/search \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"query": "italian restaurant",
|
||||
"location_bias": {
|
||||
"lat": 40.8065,
|
||||
"lng": -73.9719,
|
||||
"radius_m": 3000
|
||||
},
|
||||
"filters": {
|
||||
"types": ["restaurant"],
|
||||
"open_now": true,
|
||||
"min_rating": 4.0,
|
||||
"price_levels": [1, 2, 3]
|
||||
},
|
||||
"limit": 10
|
||||
}'
|
||||
```
|
||||
|
||||
Example resolve request (curl):
|
||||
|
||||
```bash
|
||||
curl -X POST http://127.0.0.1:8000/locations/resolve \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"location_text": "Riverside Park, New York",
|
||||
"limit": 5
|
||||
}'
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
```bash
|
||||
uv run pytest
|
||||
```
|
||||
|
||||
## OpenAPI
|
||||
|
||||
Generate the OpenAPI schema:
|
||||
|
||||
```bash
|
||||
uv run python scripts/generate_openapi.py
|
||||
```
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
name: local-places
|
||||
description: Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
|
||||
homepage: https://github.com/Hyaxia/local_places
|
||||
metadata: {"zee":{"emoji":"📍","requires":{"bins":["uv"],"env":["GOOGLE_PLACES_API_KEY"]},"primaryEnv":"GOOGLE_PLACES_API_KEY"}}
|
||||
---
|
||||
|
||||
# 📍 Local Places
|
||||
|
||||
*Find places, Go fast*
|
||||
|
||||
Search for nearby places using a local Google Places API proxy. Two-step flow: resolve location first, then search.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
cd {baseDir}
|
||||
echo "GOOGLE_PLACES_API_KEY=your-key" > .env
|
||||
uv venv && uv pip install -e ".[dev]"
|
||||
uv run --env-file .env uvicorn local_places.main:app --host 127.0.0.1 --port 8000
|
||||
```
|
||||
|
||||
Requires `GOOGLE_PLACES_API_KEY` in `.env` or environment.
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. **Check server:** `curl http://127.0.0.1:8000/ping`
|
||||
|
||||
2. **Resolve location:**
|
||||
```bash
|
||||
curl -X POST http://127.0.0.1:8000/locations/resolve \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"location_text": "Soho, London", "limit": 5}'
|
||||
```
|
||||
|
||||
3. **Search places:**
|
||||
```bash
|
||||
curl -X POST http://127.0.0.1:8000/places/search \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"query": "coffee shop",
|
||||
"location_bias": {"lat": 51.5137, "lng": -0.1366, "radius_m": 1000},
|
||||
"filters": {"open_now": true, "min_rating": 4.0},
|
||||
"limit": 10
|
||||
}'
|
||||
```
|
||||
|
||||
4. **Get details:**
|
||||
```bash
|
||||
curl http://127.0.0.1:8000/places/{place_id}
|
||||
```
|
||||
|
||||
## Conversation Flow
|
||||
|
||||
1. If user says "near me" or gives vague location → resolve it first
|
||||
2. If multiple results → show numbered list, ask user to pick
|
||||
3. Ask for preferences: type, open now, rating, price level
|
||||
4. Search with `location_bias` from chosen location
|
||||
5. Present results with name, rating, address, open status
|
||||
6. Offer to fetch details or refine search
|
||||
|
||||
## Filter Constraints
|
||||
|
||||
- `filters.types`: exactly ONE type (e.g., "restaurant", "cafe", "gym")
|
||||
- `filters.price_levels`: integers 0-4 (0=free, 4=very expensive)
|
||||
- `filters.min_rating`: 0-5 in 0.5 increments
|
||||
- `filters.open_now`: boolean
|
||||
- `limit`: 1-20 for search, 1-10 for resolve
|
||||
- `location_bias.radius_m`: must be > 0
|
||||
|
||||
## Response Format
|
||||
|
||||
```json
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"place_id": "ChIJ...",
|
||||
"name": "Coffee Shop",
|
||||
"address": "123 Main St",
|
||||
"location": {"lat": 51.5, "lng": -0.1},
|
||||
"rating": 4.6,
|
||||
"price_level": 2,
|
||||
"types": ["cafe", "food"],
|
||||
"open_now": true
|
||||
}
|
||||
],
|
||||
"next_page_token": "..."
|
||||
}
|
||||
```
|
||||
|
||||
Use `next_page_token` as `page_token` in next request for more results.
|
||||
@@ -0,0 +1,27 @@
|
||||
[project]
|
||||
name = "my-api"
|
||||
version = "0.1.0"
|
||||
description = "FastAPI server"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"fastapi>=0.110.0",
|
||||
"httpx>=0.27.0",
|
||||
"uvicorn[standard]>=0.29.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["src/local_places"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
addopts = "-q"
|
||||
testpaths = ["tests"]
|
||||
@@ -0,0 +1,2 @@
|
||||
__all__ = ["__version__"]
|
||||
__version__ = "0.1.0"
|
||||
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,314 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
from fastapi import HTTPException
|
||||
|
||||
from local_places.schemas import (
|
||||
LatLng,
|
||||
LocationResolveRequest,
|
||||
LocationResolveResponse,
|
||||
PlaceDetails,
|
||||
PlaceSummary,
|
||||
ResolvedLocation,
|
||||
SearchRequest,
|
||||
SearchResponse,
|
||||
)
|
||||
|
||||
GOOGLE_PLACES_BASE_URL = os.getenv(
|
||||
"GOOGLE_PLACES_BASE_URL", "https://places.googleapis.com/v1"
|
||||
)
|
||||
logger = logging.getLogger("local_places.google_places")
|
||||
|
||||
_PRICE_LEVEL_TO_ENUM = {
|
||||
0: "PRICE_LEVEL_FREE",
|
||||
1: "PRICE_LEVEL_INEXPENSIVE",
|
||||
2: "PRICE_LEVEL_MODERATE",
|
||||
3: "PRICE_LEVEL_EXPENSIVE",
|
||||
4: "PRICE_LEVEL_VERY_EXPENSIVE",
|
||||
}
|
||||
_ENUM_TO_PRICE_LEVEL = {value: key for key, value in _PRICE_LEVEL_TO_ENUM.items()}
|
||||
|
||||
_SEARCH_FIELD_MASK = (
|
||||
"places.id,"
|
||||
"places.displayName,"
|
||||
"places.formattedAddress,"
|
||||
"places.location,"
|
||||
"places.rating,"
|
||||
"places.priceLevel,"
|
||||
"places.types,"
|
||||
"places.currentOpeningHours,"
|
||||
"nextPageToken"
|
||||
)
|
||||
|
||||
_DETAILS_FIELD_MASK = (
|
||||
"id,"
|
||||
"displayName,"
|
||||
"formattedAddress,"
|
||||
"location,"
|
||||
"rating,"
|
||||
"priceLevel,"
|
||||
"types,"
|
||||
"regularOpeningHours,"
|
||||
"currentOpeningHours,"
|
||||
"nationalPhoneNumber,"
|
||||
"websiteUri"
|
||||
)
|
||||
|
||||
_RESOLVE_FIELD_MASK = (
|
||||
"places.id,"
|
||||
"places.displayName,"
|
||||
"places.formattedAddress,"
|
||||
"places.location,"
|
||||
"places.types"
|
||||
)
|
||||
|
||||
|
||||
class _GoogleResponse:
|
||||
def __init__(self, response: httpx.Response):
|
||||
self.status_code = response.status_code
|
||||
self._response = response
|
||||
|
||||
def json(self) -> dict[str, Any]:
|
||||
return self._response.json()
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return self._response.text
|
||||
|
||||
|
||||
def _api_headers(field_mask: str) -> dict[str, str]:
|
||||
api_key = os.getenv("GOOGLE_PLACES_API_KEY")
|
||||
if not api_key:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="GOOGLE_PLACES_API_KEY is not set.",
|
||||
)
|
||||
return {
|
||||
"Content-Type": "application/json",
|
||||
"X-Goog-Api-Key": api_key,
|
||||
"X-Goog-FieldMask": field_mask,
|
||||
}
|
||||
|
||||
|
||||
def _request(
|
||||
method: str, url: str, payload: dict[str, Any] | None, field_mask: str
|
||||
) -> _GoogleResponse:
|
||||
try:
|
||||
with httpx.Client(timeout=10.0) as client:
|
||||
response = client.request(
|
||||
method=method,
|
||||
url=url,
|
||||
headers=_api_headers(field_mask),
|
||||
json=payload,
|
||||
)
|
||||
except httpx.HTTPError as exc:
|
||||
raise HTTPException(status_code=502, detail="Google Places API unavailable.") from exc
|
||||
|
||||
return _GoogleResponse(response)
|
||||
|
||||
|
||||
def _build_text_query(request: SearchRequest) -> str:
|
||||
keyword = request.filters.keyword if request.filters else None
|
||||
if keyword:
|
||||
return f"{request.query} {keyword}".strip()
|
||||
return request.query
|
||||
|
||||
|
||||
def _build_search_body(request: SearchRequest) -> dict[str, Any]:
|
||||
body: dict[str, Any] = {
|
||||
"textQuery": _build_text_query(request),
|
||||
"pageSize": request.limit,
|
||||
}
|
||||
|
||||
if request.page_token:
|
||||
body["pageToken"] = request.page_token
|
||||
|
||||
if request.location_bias:
|
||||
body["locationBias"] = {
|
||||
"circle": {
|
||||
"center": {
|
||||
"latitude": request.location_bias.lat,
|
||||
"longitude": request.location_bias.lng,
|
||||
},
|
||||
"radius": request.location_bias.radius_m,
|
||||
}
|
||||
}
|
||||
|
||||
if request.filters:
|
||||
filters = request.filters
|
||||
if filters.types:
|
||||
body["includedType"] = filters.types[0]
|
||||
if filters.open_now is not None:
|
||||
body["openNow"] = filters.open_now
|
||||
if filters.min_rating is not None:
|
||||
body["minRating"] = filters.min_rating
|
||||
if filters.price_levels:
|
||||
body["priceLevels"] = [
|
||||
_PRICE_LEVEL_TO_ENUM[level] for level in filters.price_levels
|
||||
]
|
||||
|
||||
return body
|
||||
|
||||
|
||||
def _parse_lat_lng(raw: dict[str, Any] | None) -> LatLng | None:
|
||||
if not raw:
|
||||
return None
|
||||
latitude = raw.get("latitude")
|
||||
longitude = raw.get("longitude")
|
||||
if latitude is None or longitude is None:
|
||||
return None
|
||||
return LatLng(lat=latitude, lng=longitude)
|
||||
|
||||
|
||||
def _parse_display_name(raw: dict[str, Any] | None) -> str | None:
|
||||
if not raw:
|
||||
return None
|
||||
return raw.get("text")
|
||||
|
||||
|
||||
def _parse_open_now(raw: dict[str, Any] | None) -> bool | None:
|
||||
if not raw:
|
||||
return None
|
||||
return raw.get("openNow")
|
||||
|
||||
|
||||
def _parse_hours(raw: dict[str, Any] | None) -> list[str] | None:
|
||||
if not raw:
|
||||
return None
|
||||
return raw.get("weekdayDescriptions")
|
||||
|
||||
|
||||
def _parse_price_level(raw: str | None) -> int | None:
|
||||
if not raw:
|
||||
return None
|
||||
return _ENUM_TO_PRICE_LEVEL.get(raw)
|
||||
|
||||
|
||||
def search_places(request: SearchRequest) -> SearchResponse:
|
||||
url = f"{GOOGLE_PLACES_BASE_URL}/places:searchText"
|
||||
response = _request("POST", url, _build_search_body(request), _SEARCH_FIELD_MASK)
|
||||
|
||||
if response.status_code >= 400:
|
||||
logger.error(
|
||||
"Google Places API error %s. response=%s",
|
||||
response.status_code,
|
||||
response.text,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"Google Places API error ({response.status_code}).",
|
||||
)
|
||||
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Google Places API returned invalid JSON. response=%s",
|
||||
response.text,
|
||||
)
|
||||
raise HTTPException(status_code=502, detail="Invalid Google response.") from exc
|
||||
|
||||
places = payload.get("places", [])
|
||||
results = []
|
||||
for place in places:
|
||||
results.append(
|
||||
PlaceSummary(
|
||||
place_id=place.get("id", ""),
|
||||
name=_parse_display_name(place.get("displayName")),
|
||||
address=place.get("formattedAddress"),
|
||||
location=_parse_lat_lng(place.get("location")),
|
||||
rating=place.get("rating"),
|
||||
price_level=_parse_price_level(place.get("priceLevel")),
|
||||
types=place.get("types"),
|
||||
open_now=_parse_open_now(place.get("currentOpeningHours")),
|
||||
)
|
||||
)
|
||||
|
||||
return SearchResponse(
|
||||
results=results,
|
||||
next_page_token=payload.get("nextPageToken"),
|
||||
)
|
||||
|
||||
|
||||
def get_place_details(place_id: str) -> PlaceDetails:
|
||||
url = f"{GOOGLE_PLACES_BASE_URL}/places/{place_id}"
|
||||
response = _request("GET", url, None, _DETAILS_FIELD_MASK)
|
||||
|
||||
if response.status_code >= 400:
|
||||
logger.error(
|
||||
"Google Places API error %s. response=%s",
|
||||
response.status_code,
|
||||
response.text,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"Google Places API error ({response.status_code}).",
|
||||
)
|
||||
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Google Places API returned invalid JSON. response=%s",
|
||||
response.text,
|
||||
)
|
||||
raise HTTPException(status_code=502, detail="Invalid Google response.") from exc
|
||||
|
||||
return PlaceDetails(
|
||||
place_id=payload.get("id", place_id),
|
||||
name=_parse_display_name(payload.get("displayName")),
|
||||
address=payload.get("formattedAddress"),
|
||||
location=_parse_lat_lng(payload.get("location")),
|
||||
rating=payload.get("rating"),
|
||||
price_level=_parse_price_level(payload.get("priceLevel")),
|
||||
types=payload.get("types"),
|
||||
phone=payload.get("nationalPhoneNumber"),
|
||||
website=payload.get("websiteUri"),
|
||||
hours=_parse_hours(payload.get("regularOpeningHours")),
|
||||
open_now=_parse_open_now(payload.get("currentOpeningHours")),
|
||||
)
|
||||
|
||||
|
||||
def resolve_locations(request: LocationResolveRequest) -> LocationResolveResponse:
|
||||
url = f"{GOOGLE_PLACES_BASE_URL}/places:searchText"
|
||||
body = {"textQuery": request.location_text, "pageSize": request.limit}
|
||||
response = _request("POST", url, body, _RESOLVE_FIELD_MASK)
|
||||
|
||||
if response.status_code >= 400:
|
||||
logger.error(
|
||||
"Google Places API error %s. response=%s",
|
||||
response.status_code,
|
||||
response.text,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"Google Places API error ({response.status_code}).",
|
||||
)
|
||||
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Google Places API returned invalid JSON. response=%s",
|
||||
response.text,
|
||||
)
|
||||
raise HTTPException(status_code=502, detail="Invalid Google response.") from exc
|
||||
|
||||
places = payload.get("places", [])
|
||||
results = []
|
||||
for place in places:
|
||||
results.append(
|
||||
ResolvedLocation(
|
||||
place_id=place.get("id", ""),
|
||||
name=_parse_display_name(place.get("displayName")),
|
||||
address=place.get("formattedAddress"),
|
||||
location=_parse_lat_lng(place.get("location")),
|
||||
types=place.get("types"),
|
||||
)
|
||||
)
|
||||
|
||||
return LocationResolveResponse(results=results)
|
||||
@@ -0,0 +1,65 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from local_places.google_places import get_place_details, resolve_locations, search_places
|
||||
from local_places.schemas import (
|
||||
LocationResolveRequest,
|
||||
LocationResolveResponse,
|
||||
PlaceDetails,
|
||||
SearchRequest,
|
||||
SearchResponse,
|
||||
)
|
||||
|
||||
app = FastAPI(
|
||||
title="My API",
|
||||
servers=[{"url": os.getenv("OPENAPI_SERVER_URL", "http://maxims-macbook-air:8000")}],
|
||||
)
|
||||
logger = logging.getLogger("local_places.validation")
|
||||
|
||||
|
||||
@app.get("/ping")
|
||||
def ping() -> dict[str, str]:
|
||||
return {"message": "pong"}
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_exception_handler(
|
||||
request: Request, exc: RequestValidationError
|
||||
) -> JSONResponse:
|
||||
logger.error(
|
||||
"Validation error on %s %s. body=%s errors=%s",
|
||||
request.method,
|
||||
request.url.path,
|
||||
exc.body,
|
||||
exc.errors(),
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=422,
|
||||
content=jsonable_encoder({"detail": exc.errors()}),
|
||||
)
|
||||
|
||||
|
||||
@app.post("/places/search", response_model=SearchResponse)
|
||||
def places_search(request: SearchRequest) -> SearchResponse:
|
||||
return search_places(request)
|
||||
|
||||
|
||||
@app.get("/places/{place_id}", response_model=PlaceDetails)
|
||||
def places_details(place_id: str) -> PlaceDetails:
|
||||
return get_place_details(place_id)
|
||||
|
||||
|
||||
@app.post("/locations/resolve", response_model=LocationResolveResponse)
|
||||
def locations_resolve(request: LocationResolveRequest) -> LocationResolveResponse:
|
||||
return resolve_locations(request)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run("local_places.main:app", host="0.0.0.0", port=8000)
|
||||
@@ -0,0 +1,107 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
class LatLng(BaseModel):
|
||||
lat: float = Field(ge=-90, le=90)
|
||||
lng: float = Field(ge=-180, le=180)
|
||||
|
||||
|
||||
class LocationBias(BaseModel):
|
||||
lat: float = Field(ge=-90, le=90)
|
||||
lng: float = Field(ge=-180, le=180)
|
||||
radius_m: float = Field(gt=0)
|
||||
|
||||
|
||||
class Filters(BaseModel):
|
||||
types: list[str] | None = None
|
||||
open_now: bool | None = None
|
||||
min_rating: float | None = Field(default=None, ge=0, le=5)
|
||||
price_levels: list[int] | None = None
|
||||
keyword: str | None = Field(default=None, min_length=1)
|
||||
|
||||
@field_validator("types")
|
||||
@classmethod
|
||||
def validate_types(cls, value: list[str] | None) -> list[str] | None:
|
||||
if value is None:
|
||||
return value
|
||||
if len(value) > 1:
|
||||
raise ValueError(
|
||||
"Only one type is supported. Use query/keyword for additional filtering."
|
||||
)
|
||||
return value
|
||||
|
||||
@field_validator("price_levels")
|
||||
@classmethod
|
||||
def validate_price_levels(cls, value: list[int] | None) -> list[int] | None:
|
||||
if value is None:
|
||||
return value
|
||||
invalid = [level for level in value if level not in range(0, 5)]
|
||||
if invalid:
|
||||
raise ValueError("price_levels must be integers between 0 and 4.")
|
||||
return value
|
||||
|
||||
@field_validator("min_rating")
|
||||
@classmethod
|
||||
def validate_min_rating(cls, value: float | None) -> float | None:
|
||||
if value is None:
|
||||
return value
|
||||
if (value * 2) % 1 != 0:
|
||||
raise ValueError("min_rating must be in 0.5 increments.")
|
||||
return value
|
||||
|
||||
|
||||
class SearchRequest(BaseModel):
|
||||
query: str = Field(min_length=1)
|
||||
location_bias: LocationBias | None = None
|
||||
filters: Filters | None = None
|
||||
limit: int = Field(default=10, ge=1, le=20)
|
||||
page_token: str | None = None
|
||||
|
||||
|
||||
class PlaceSummary(BaseModel):
|
||||
place_id: str
|
||||
name: str | None = None
|
||||
address: str | None = None
|
||||
location: LatLng | None = None
|
||||
rating: float | None = None
|
||||
price_level: int | None = None
|
||||
types: list[str] | None = None
|
||||
open_now: bool | None = None
|
||||
|
||||
|
||||
class SearchResponse(BaseModel):
|
||||
results: list[PlaceSummary]
|
||||
next_page_token: str | None = None
|
||||
|
||||
|
||||
class LocationResolveRequest(BaseModel):
|
||||
location_text: str = Field(min_length=1)
|
||||
limit: int = Field(default=5, ge=1, le=10)
|
||||
|
||||
|
||||
class ResolvedLocation(BaseModel):
|
||||
place_id: str
|
||||
name: str | None = None
|
||||
address: str | None = None
|
||||
location: LatLng | None = None
|
||||
types: list[str] | None = None
|
||||
|
||||
|
||||
class LocationResolveResponse(BaseModel):
|
||||
results: list[ResolvedLocation]
|
||||
|
||||
|
||||
class PlaceDetails(BaseModel):
|
||||
place_id: str
|
||||
name: str | None = None
|
||||
address: str | None = None
|
||||
location: LatLng | None = None
|
||||
rating: float | None = None
|
||||
price_level: int | None = None
|
||||
types: list[str] | None = None
|
||||
phone: str | None = None
|
||||
website: str | None = None
|
||||
hours: list[str] | None = None
|
||||
open_now: bool | None = None
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
name: market-analysis
|
||||
description: Analyze market conditions, sector rotation, and macro trends
|
||||
triggers:
|
||||
- market analysis
|
||||
- sector rotation
|
||||
- market overview
|
||||
- macro outlook
|
||||
- economic data
|
||||
---
|
||||
|
||||
# Market Analysis
|
||||
|
||||
Analyze overall market conditions and identify sector opportunities.
|
||||
|
||||
## Market Overview Queries
|
||||
|
||||
### Major Indices
|
||||
```
|
||||
# Index performance
|
||||
obb.index.price.historical(symbol="^SPX,^IXIC,^DJI", provider="yfinance")
|
||||
|
||||
# VIX (fear gauge)
|
||||
obb.index.price.historical(symbol="^VIX", provider="cboe")
|
||||
```
|
||||
|
||||
### Sector Performance
|
||||
```
|
||||
# Sector ETF performance comparison
|
||||
sectors = ["XLK", "XLF", "XLE", "XLV", "XLI", "XLC", "XLY", "XLP", "XLU", "XLRE", "XLB"]
|
||||
obb.equity.price.performance(symbol=",".join(sectors), provider="fmp")
|
||||
```
|
||||
|
||||
### Economic Indicators
|
||||
```
|
||||
# Key FRED series
|
||||
obb.economy.fred_series(symbol="GDP") # GDP
|
||||
obb.economy.fred_series(symbol="UNRATE") # Unemployment
|
||||
obb.economy.fred_series(symbol="CPIAUCSL") # CPI
|
||||
obb.economy.fred_series(symbol="FEDFUNDS") # Fed Funds Rate
|
||||
obb.economy.fred_series(symbol="T10Y2Y") # Yield curve spread
|
||||
```
|
||||
|
||||
## Sector Rotation Analysis
|
||||
|
||||
Using Stanley's SectorRotationAnalyzer:
|
||||
```
|
||||
from stanley.analytics import SectorRotationAnalyzer
|
||||
|
||||
analyzer = SectorRotationAnalyzer(stanley)
|
||||
rotation = analyzer.detect_rotation(lookback_days=90)
|
||||
momentum = analyzer.calculate_sector_momentum()
|
||||
regime = analyzer.detect_market_regime()
|
||||
```
|
||||
|
||||
## Money Flow Analysis
|
||||
|
||||
```
|
||||
from stanley.analytics import MoneyFlowAnalyzer
|
||||
|
||||
mf = MoneyFlowAnalyzer(stanley)
|
||||
sector_flows = mf.get_sector_money_flow(["XLK", "XLF", "XLE"])
|
||||
institutional_flow = mf.get_institutional_flow("SPY")
|
||||
```
|
||||
|
||||
## Output Templates
|
||||
|
||||
### Daily Market Brief
|
||||
- Index moves and VIX
|
||||
- Sector leadership/laggards
|
||||
- Key economic data releases
|
||||
- Notable earnings/events
|
||||
|
||||
### Weekly Market Review
|
||||
- Sector rotation trends
|
||||
- Money flow analysis
|
||||
- Risk-on vs risk-off positioning
|
||||
- Forward calendar
|
||||
|
||||
## Memory Integration
|
||||
|
||||
Store market context:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "stanley/market",
|
||||
key: `daily/${date}`,
|
||||
value: {
|
||||
indices: { spx, ndx, vix },
|
||||
sectorLeaders: [...],
|
||||
sectorLaggards: [...],
|
||||
keyEvents: [...]
|
||||
},
|
||||
ttl: 86400 * 7
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
name: mcporter
|
||||
description: Use the mcporter CLI to list, configure, auth, and call MCP servers/tools directly (HTTP or stdio), including ad-hoc servers, config edits, and CLI/type generation.
|
||||
homepage: http://mcporter.dev
|
||||
metadata: {"zee":{"emoji":"📦","requires":{"bins":["mcporter"]},"install":[{"id":"node","kind":"node","package":"mcporter","bins":["mcporter"],"label":"Install mcporter (node)"}]}}
|
||||
---
|
||||
|
||||
# mcporter
|
||||
|
||||
Use `mcporter` to work with MCP servers directly.
|
||||
|
||||
Quick start
|
||||
- `mcporter list`
|
||||
- `mcporter list <server> --schema`
|
||||
- `mcporter call <server.tool> key=value`
|
||||
|
||||
Call tools
|
||||
- Selector: `mcporter call linear.list_issues team=ENG limit:5`
|
||||
- Function syntax: `mcporter call "linear.create_issue(title: \"Bug\")"`
|
||||
- Full URL: `mcporter call https://api.example.com/mcp.fetch url:https://example.com`
|
||||
- Stdio: `mcporter call --stdio "bun run ./server.ts" scrape url=https://example.com`
|
||||
- JSON payload: `mcporter call <server.tool> --args '{"limit":5}'`
|
||||
|
||||
Auth + config
|
||||
- OAuth: `mcporter auth <server | url> [--reset]`
|
||||
- Config: `mcporter config list|get|add|remove|import|login|logout`
|
||||
|
||||
Daemon
|
||||
- `mcporter daemon start|status|stop|restart`
|
||||
|
||||
Codegen
|
||||
- CLI: `mcporter generate-cli --server <name>` or `--command <url>`
|
||||
- Inspect: `mcporter inspect-cli <path> [--json]`
|
||||
- TS: `mcporter emit-ts <server> --mode client|types`
|
||||
|
||||
Notes
|
||||
- Config default: `./config/mcporter.json` (override with `--config`).
|
||||
- Prefer `--output json` for machine-readable results.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
name: model-usage
|
||||
description: Use CodexBar CLI local cost usage to summarize per-model usage for Codex or Claude, including the current (most recent) model or a full model breakdown. Trigger when asked for model-level usage/cost data from codexbar, or when you need a scriptable per-model summary from codexbar cost JSON.
|
||||
metadata: {"zee":{"emoji":"📊","os":["darwin"],"requires":{"bins":["codexbar"]},"install":[{"id":"brew-cask","kind":"brew","cask":"steipete/tap/codexbar","bins":["codexbar"],"label":"Install CodexBar (brew cask)"}]}}
|
||||
---
|
||||
|
||||
# Model usage
|
||||
|
||||
## Overview
|
||||
Get per-model usage cost from CodexBar's local cost logs. Supports "current model" (most recent daily entry) or "all models" summaries for Codex or Claude.
|
||||
|
||||
TODO: add Linux CLI support guidance once CodexBar CLI install path is documented for Linux.
|
||||
|
||||
## Quick start
|
||||
1) Fetch cost JSON via CodexBar CLI or pass a JSON file.
|
||||
2) Use the bundled script to summarize by model.
|
||||
|
||||
```bash
|
||||
python {baseDir}/scripts/model_usage.py --provider codex --mode current
|
||||
python {baseDir}/scripts/model_usage.py --provider codex --mode all
|
||||
python {baseDir}/scripts/model_usage.py --provider claude --mode all --format json --pretty
|
||||
```
|
||||
|
||||
## Current model logic
|
||||
- Uses the most recent daily row with `modelBreakdowns`.
|
||||
- Picks the model with the highest cost in that row.
|
||||
- Falls back to the last entry in `modelsUsed` when breakdowns are missing.
|
||||
- Override with `--model <name>` when you need a specific model.
|
||||
|
||||
## Inputs
|
||||
- Default: runs `codexbar cost --format json --provider <codex|claude>`.
|
||||
- File or stdin:
|
||||
|
||||
```bash
|
||||
codexbar cost --provider codex --format json > /tmp/cost.json
|
||||
python {baseDir}/scripts/model_usage.py --input /tmp/cost.json --mode all
|
||||
cat /tmp/cost.json | python {baseDir}/scripts/model_usage.py --input - --mode current
|
||||
```
|
||||
|
||||
## Output
|
||||
- Text (default) or JSON (`--format json --pretty`).
|
||||
- Values are cost-only per model; tokens are not split by model in CodexBar output.
|
||||
|
||||
## References
|
||||
- Read `references/codexbar-cli.md` for CLI flags and cost JSON fields.
|
||||
@@ -0,0 +1,28 @@
|
||||
# CodexBar CLI quick ref (usage + cost)
|
||||
|
||||
## Install
|
||||
- App: Preferences -> Advanced -> Install CLI
|
||||
- Repo: ./bin/install-codexbar-cli.sh
|
||||
|
||||
## Commands
|
||||
- Usage snapshot (web/cli sources):
|
||||
- codexbar usage --format json --pretty
|
||||
- codexbar --provider all --format json
|
||||
- Local cost usage (Codex + Claude only):
|
||||
- codexbar cost --format json --pretty
|
||||
- codexbar cost --provider codex|claude --format json
|
||||
|
||||
## Cost JSON fields
|
||||
The payload is an array (one per provider).
|
||||
- provider, source, updatedAt
|
||||
- sessionTokens, sessionCostUSD
|
||||
- last30DaysTokens, last30DaysCostUSD
|
||||
- daily[]: date, inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, totalTokens, totalCost, modelsUsed, modelBreakdowns[]
|
||||
- modelBreakdowns[]: modelName, cost
|
||||
- totals: totalInputTokens, totalOutputTokens, cacheReadTokens, cacheCreationTokens, totalTokens, totalCost
|
||||
|
||||
## Notes
|
||||
- Cost usage is local-only. It reads JSONL logs under:
|
||||
- Codex: ~/.codex/sessions/**/*.jsonl
|
||||
- Claude: ~/.config/claude/projects/**/*.jsonl or ~/.claude/projects/**/*.jsonl
|
||||
- If web usage is required (non-local), use codexbar usage (not cost).
|
||||
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Summarize CodexBar local cost usage by model.
|
||||
|
||||
Defaults to current model (most recent daily entry), or list all models.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
||||
|
||||
|
||||
def eprint(msg: str) -> None:
|
||||
print(msg, file=sys.stderr)
|
||||
|
||||
|
||||
def run_codexbar_cost(provider: str) -> List[Dict[str, Any]]:
|
||||
cmd = ["codexbar", "cost", "--format", "json", "--provider", provider]
|
||||
try:
|
||||
output = subprocess.check_output(cmd, text=True)
|
||||
except FileNotFoundError:
|
||||
raise RuntimeError("codexbar not found on PATH. Install CodexBar CLI first.")
|
||||
except subprocess.CalledProcessError as exc:
|
||||
raise RuntimeError(f"codexbar cost failed (exit {exc.returncode}).")
|
||||
try:
|
||||
payload = json.loads(output)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError(f"Failed to parse codexbar JSON output: {exc}")
|
||||
if not isinstance(payload, list):
|
||||
raise RuntimeError("Expected codexbar cost JSON array.")
|
||||
return payload
|
||||
|
||||
|
||||
def load_payload(input_path: Optional[str], provider: str) -> Dict[str, Any]:
|
||||
if input_path:
|
||||
if input_path == "-":
|
||||
raw = sys.stdin.read()
|
||||
else:
|
||||
with open(input_path, "r", encoding="utf-8") as handle:
|
||||
raw = handle.read()
|
||||
data = json.loads(raw)
|
||||
else:
|
||||
data = run_codexbar_cost(provider)
|
||||
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
|
||||
if isinstance(data, list):
|
||||
for entry in data:
|
||||
if isinstance(entry, dict) and entry.get("provider") == provider:
|
||||
return entry
|
||||
raise RuntimeError(f"Provider '{provider}' not found in codexbar payload.")
|
||||
|
||||
raise RuntimeError("Unsupported JSON input format.")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ModelCost:
|
||||
model: str
|
||||
cost: float
|
||||
|
||||
|
||||
def parse_daily_entries(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
daily = payload.get("daily")
|
||||
if not daily:
|
||||
return []
|
||||
if not isinstance(daily, list):
|
||||
return []
|
||||
return [entry for entry in daily if isinstance(entry, dict)]
|
||||
|
||||
|
||||
def parse_date(value: str) -> Optional[date]:
|
||||
try:
|
||||
return datetime.strptime(value, "%Y-%m-%d").date()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def filter_by_days(entries: List[Dict[str, Any]], days: Optional[int]) -> List[Dict[str, Any]]:
|
||||
if not days:
|
||||
return entries
|
||||
cutoff = date.today() - timedelta(days=days - 1)
|
||||
filtered: List[Dict[str, Any]] = []
|
||||
for entry in entries:
|
||||
day = entry.get("date")
|
||||
if not isinstance(day, str):
|
||||
continue
|
||||
parsed = parse_date(day)
|
||||
if parsed and parsed >= cutoff:
|
||||
filtered.append(entry)
|
||||
return filtered
|
||||
|
||||
|
||||
def aggregate_costs(entries: Iterable[Dict[str, Any]]) -> Dict[str, float]:
|
||||
totals: Dict[str, float] = {}
|
||||
for entry in entries:
|
||||
breakdowns = entry.get("modelBreakdowns")
|
||||
if not breakdowns:
|
||||
continue
|
||||
if not isinstance(breakdowns, list):
|
||||
continue
|
||||
for item in breakdowns:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
model = item.get("modelName")
|
||||
cost = item.get("cost")
|
||||
if not isinstance(model, str):
|
||||
continue
|
||||
if not isinstance(cost, (int, float)):
|
||||
continue
|
||||
totals[model] = totals.get(model, 0.0) + float(cost)
|
||||
return totals
|
||||
|
||||
|
||||
def pick_current_model(entries: List[Dict[str, Any]]) -> Tuple[Optional[str], Optional[str]]:
|
||||
if not entries:
|
||||
return None, None
|
||||
sorted_entries = sorted(
|
||||
entries,
|
||||
key=lambda entry: entry.get("date") or "",
|
||||
)
|
||||
for entry in reversed(sorted_entries):
|
||||
breakdowns = entry.get("modelBreakdowns")
|
||||
if isinstance(breakdowns, list) and breakdowns:
|
||||
scored: List[ModelCost] = []
|
||||
for item in breakdowns:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
model = item.get("modelName")
|
||||
cost = item.get("cost")
|
||||
if isinstance(model, str) and isinstance(cost, (int, float)):
|
||||
scored.append(ModelCost(model=model, cost=float(cost)))
|
||||
if scored:
|
||||
scored.sort(key=lambda item: item.cost, reverse=True)
|
||||
return scored[0].model, entry.get("date") if isinstance(entry.get("date"), str) else None
|
||||
models_used = entry.get("modelsUsed")
|
||||
if isinstance(models_used, list) and models_used:
|
||||
last = models_used[-1]
|
||||
if isinstance(last, str):
|
||||
return last, entry.get("date") if isinstance(entry.get("date"), str) else None
|
||||
return None, None
|
||||
|
||||
|
||||
def usd(value: Optional[float]) -> str:
|
||||
if value is None:
|
||||
return "—"
|
||||
return f"${value:,.2f}"
|
||||
|
||||
|
||||
def latest_day_cost(entries: List[Dict[str, Any]], model: str) -> Tuple[Optional[str], Optional[float]]:
|
||||
if not entries:
|
||||
return None, None
|
||||
sorted_entries = sorted(
|
||||
entries,
|
||||
key=lambda entry: entry.get("date") or "",
|
||||
)
|
||||
for entry in reversed(sorted_entries):
|
||||
breakdowns = entry.get("modelBreakdowns")
|
||||
if not isinstance(breakdowns, list):
|
||||
continue
|
||||
for item in breakdowns:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if item.get("modelName") == model:
|
||||
cost = item.get("cost") if isinstance(item.get("cost"), (int, float)) else None
|
||||
day = entry.get("date") if isinstance(entry.get("date"), str) else None
|
||||
return day, float(cost) if cost is not None else None
|
||||
return None, None
|
||||
|
||||
|
||||
def render_text_current(
|
||||
provider: str,
|
||||
model: str,
|
||||
latest_date: Optional[str],
|
||||
total_cost: Optional[float],
|
||||
latest_cost: Optional[float],
|
||||
latest_cost_date: Optional[str],
|
||||
entry_count: int,
|
||||
) -> str:
|
||||
lines = [f"Provider: {provider}", f"Current model: {model}"]
|
||||
if latest_date:
|
||||
lines.append(f"Latest model date: {latest_date}")
|
||||
lines.append(f"Total cost (rows): {usd(total_cost)}")
|
||||
if latest_cost_date:
|
||||
lines.append(f"Latest day cost: {usd(latest_cost)} ({latest_cost_date})")
|
||||
lines.append(f"Daily rows: {entry_count}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def render_text_all(provider: str, totals: Dict[str, float]) -> str:
|
||||
lines = [f"Provider: {provider}", "Models:"]
|
||||
for model, cost in sorted(totals.items(), key=lambda item: item[1], reverse=True):
|
||||
lines.append(f"- {model}: {usd(cost)}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_json_current(
|
||||
provider: str,
|
||||
model: str,
|
||||
latest_date: Optional[str],
|
||||
total_cost: Optional[float],
|
||||
latest_cost: Optional[float],
|
||||
latest_cost_date: Optional[str],
|
||||
entry_count: int,
|
||||
) -> Dict[str, Any]:
|
||||
return {
|
||||
"provider": provider,
|
||||
"mode": "current",
|
||||
"model": model,
|
||||
"latestModelDate": latest_date,
|
||||
"totalCostUSD": total_cost,
|
||||
"latestDayCostUSD": latest_cost,
|
||||
"latestDayCostDate": latest_cost_date,
|
||||
"dailyRowCount": entry_count,
|
||||
}
|
||||
|
||||
|
||||
def build_json_all(provider: str, totals: Dict[str, float]) -> Dict[str, Any]:
|
||||
return {
|
||||
"provider": provider,
|
||||
"mode": "all",
|
||||
"models": [
|
||||
{"model": model, "totalCostUSD": cost}
|
||||
for model, cost in sorted(totals.items(), key=lambda item: item[1], reverse=True)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Summarize CodexBar model usage from local cost logs.")
|
||||
parser.add_argument("--provider", choices=["codex", "claude"], default="codex")
|
||||
parser.add_argument("--mode", choices=["current", "all"], default="current")
|
||||
parser.add_argument("--model", help="Explicit model name to report instead of auto-current.")
|
||||
parser.add_argument("--input", help="Path to codexbar cost JSON (or '-' for stdin).")
|
||||
parser.add_argument("--days", type=int, help="Limit to last N days (based on daily rows).")
|
||||
parser.add_argument("--format", choices=["text", "json"], default="text")
|
||||
parser.add_argument("--pretty", action="store_true", help="Pretty-print JSON output.")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
payload = load_payload(args.input, args.provider)
|
||||
except Exception as exc:
|
||||
eprint(str(exc))
|
||||
return 1
|
||||
|
||||
entries = parse_daily_entries(payload)
|
||||
entries = filter_by_days(entries, args.days)
|
||||
|
||||
if args.mode == "current":
|
||||
model = args.model
|
||||
latest_date = None
|
||||
if not model:
|
||||
model, latest_date = pick_current_model(entries)
|
||||
if not model:
|
||||
eprint("No model data found in codexbar cost payload.")
|
||||
return 2
|
||||
totals = aggregate_costs(entries)
|
||||
total_cost = totals.get(model)
|
||||
latest_cost_date, latest_cost = latest_day_cost(entries, model)
|
||||
|
||||
if args.format == "json":
|
||||
payload_out = build_json_current(
|
||||
provider=args.provider,
|
||||
model=model,
|
||||
latest_date=latest_date,
|
||||
total_cost=total_cost,
|
||||
latest_cost=latest_cost,
|
||||
latest_cost_date=latest_cost_date,
|
||||
entry_count=len(entries),
|
||||
)
|
||||
indent = 2 if args.pretty else None
|
||||
print(json.dumps(payload_out, indent=indent, sort_keys=args.pretty))
|
||||
else:
|
||||
print(
|
||||
render_text_current(
|
||||
provider=args.provider,
|
||||
model=model,
|
||||
latest_date=latest_date,
|
||||
total_cost=total_cost,
|
||||
latest_cost=latest_cost,
|
||||
latest_cost_date=latest_cost_date,
|
||||
entry_count=len(entries),
|
||||
)
|
||||
)
|
||||
return 0
|
||||
|
||||
totals = aggregate_costs(entries)
|
||||
if not totals:
|
||||
eprint("No model breakdowns found in codexbar cost payload.")
|
||||
return 2
|
||||
|
||||
if args.format == "json":
|
||||
payload_out = build_json_all(provider=args.provider, totals=totals)
|
||||
indent = 2 if args.pretty else None
|
||||
print(json.dumps(payload_out, indent=indent, sort_keys=args.pretty))
|
||||
else:
|
||||
print(render_text_all(provider=args.provider, totals=totals))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: nano-banana-pro
|
||||
description: Generate or edit images via Gemini 3 Pro Image (Nano Banana Pro).
|
||||
homepage: https://ai.google.dev/
|
||||
metadata: {"zee":{"emoji":"🍌","requires":{"bins":["uv"],"env":["GEMINI_API_KEY"]},"primaryEnv":"GEMINI_API_KEY","install":[{"id":"uv-brew","kind":"brew","formula":"uv","bins":["uv"],"label":"Install uv (brew)"}]}}
|
||||
---
|
||||
|
||||
# Nano Banana Pro (Gemini 3 Pro Image)
|
||||
|
||||
Use the bundled script to generate or edit images.
|
||||
|
||||
Generate
|
||||
```bash
|
||||
uv run {baseDir}/scripts/generate_image.py --prompt "your image description" --filename "output.png" --resolution 1K
|
||||
```
|
||||
|
||||
Edit
|
||||
```bash
|
||||
uv run {baseDir}/scripts/generate_image.py --prompt "edit instructions" --filename "output.png" --input-image "/path/in.png" --resolution 2K
|
||||
```
|
||||
|
||||
API key
|
||||
- `GEMINI_API_KEY` env var
|
||||
- Or set `skills."nano-banana-pro".apiKey` / `skills."nano-banana-pro".env.GEMINI_API_KEY` in `~/.zee/zee.json`
|
||||
|
||||
Notes
|
||||
- Resolutions: `1K` (default), `2K`, `4K`.
|
||||
- Use timestamps in filenames: `yyyy-mm-dd-hh-mm-ss-name.png`.
|
||||
- The script prints a `MEDIA:` line for Zee to auto-attach on supported chat providers.
|
||||
- Do not read the image back; report the saved path only.
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = [
|
||||
# "google-genai>=1.0.0",
|
||||
# "pillow>=10.0.0",
|
||||
# ]
|
||||
# ///
|
||||
"""
|
||||
Generate images using Google's Nano Banana Pro (Gemini 3 Pro Image) API.
|
||||
|
||||
Usage:
|
||||
uv run generate_image.py --prompt "your image description" --filename "output.png" [--resolution 1K|2K|4K] [--api-key KEY]
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def get_api_key(provided_key: str | None) -> str | None:
|
||||
"""Get API key from argument first, then environment."""
|
||||
if provided_key:
|
||||
return provided_key
|
||||
return os.environ.get("GEMINI_API_KEY")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate images using Nano Banana Pro (Gemini 3 Pro Image)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--prompt", "-p",
|
||||
required=True,
|
||||
help="Image description/prompt"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--filename", "-f",
|
||||
required=True,
|
||||
help="Output filename (e.g., sunset-mountains.png)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--input-image", "-i",
|
||||
help="Optional input image path for editing/modification"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--resolution", "-r",
|
||||
choices=["1K", "2K", "4K"],
|
||||
default="1K",
|
||||
help="Output resolution: 1K (default), 2K, or 4K"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--api-key", "-k",
|
||||
help="Gemini API key (overrides GEMINI_API_KEY env var)"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Get API key
|
||||
api_key = get_api_key(args.api_key)
|
||||
if not api_key:
|
||||
print("Error: No API key provided.", file=sys.stderr)
|
||||
print("Please either:", file=sys.stderr)
|
||||
print(" 1. Provide --api-key argument", file=sys.stderr)
|
||||
print(" 2. Set GEMINI_API_KEY environment variable", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Import here after checking API key to avoid slow import on error
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
from PIL import Image as PILImage
|
||||
|
||||
# Initialise client
|
||||
client = genai.Client(api_key=api_key)
|
||||
|
||||
# Set up output path
|
||||
output_path = Path(args.filename)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Load input image if provided
|
||||
input_image = None
|
||||
output_resolution = args.resolution
|
||||
if args.input_image:
|
||||
try:
|
||||
input_image = PILImage.open(args.input_image)
|
||||
print(f"Loaded input image: {args.input_image}")
|
||||
|
||||
# Auto-detect resolution if not explicitly set by user
|
||||
if args.resolution == "1K": # Default value
|
||||
# Map input image size to resolution
|
||||
width, height = input_image.size
|
||||
max_dim = max(width, height)
|
||||
if max_dim >= 3000:
|
||||
output_resolution = "4K"
|
||||
elif max_dim >= 1500:
|
||||
output_resolution = "2K"
|
||||
else:
|
||||
output_resolution = "1K"
|
||||
print(f"Auto-detected resolution: {output_resolution} (from input {width}x{height})")
|
||||
except Exception as e:
|
||||
print(f"Error loading input image: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Build contents (image first if editing, prompt only if generating)
|
||||
if input_image:
|
||||
contents = [input_image, args.prompt]
|
||||
print(f"Editing image with resolution {output_resolution}...")
|
||||
else:
|
||||
contents = args.prompt
|
||||
print(f"Generating image with resolution {output_resolution}...")
|
||||
|
||||
try:
|
||||
response = client.models.generate_content(
|
||||
model="gemini-3-pro-image-preview",
|
||||
contents=contents,
|
||||
config=types.GenerateContentConfig(
|
||||
response_modalities=["TEXT", "IMAGE"],
|
||||
image_config=types.ImageConfig(
|
||||
image_size=output_resolution
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# Process response and convert to PNG
|
||||
image_saved = False
|
||||
for part in response.parts:
|
||||
if part.text is not None:
|
||||
print(f"Model response: {part.text}")
|
||||
elif part.inline_data is not None:
|
||||
# Convert inline data to PIL Image and save as PNG
|
||||
from io import BytesIO
|
||||
|
||||
# inline_data.data is already bytes, not base64
|
||||
image_data = part.inline_data.data
|
||||
if isinstance(image_data, str):
|
||||
# If it's a string, it might be base64
|
||||
import base64
|
||||
image_data = base64.b64decode(image_data)
|
||||
|
||||
image = PILImage.open(BytesIO(image_data))
|
||||
|
||||
# Ensure RGB mode for PNG (convert RGBA to RGB with white background if needed)
|
||||
if image.mode == 'RGBA':
|
||||
rgb_image = PILImage.new('RGB', image.size, (255, 255, 255))
|
||||
rgb_image.paste(image, mask=image.split()[3])
|
||||
rgb_image.save(str(output_path), 'PNG')
|
||||
elif image.mode == 'RGB':
|
||||
image.save(str(output_path), 'PNG')
|
||||
else:
|
||||
image.convert('RGB').save(str(output_path), 'PNG')
|
||||
image_saved = True
|
||||
|
||||
if image_saved:
|
||||
full_path = output_path.resolve()
|
||||
print(f"\nImage saved: {full_path}")
|
||||
# Clawdbot parses MEDIA tokens and will attach the file on supported providers.
|
||||
print(f"MEDIA: {full_path}")
|
||||
else:
|
||||
print("Error: No image was generated in the response.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error generating image: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: nano-pdf
|
||||
description: Edit PDFs with natural-language instructions using the nano-pdf CLI.
|
||||
homepage: https://pypi.org/project/nano-pdf/
|
||||
metadata: {"zee":{"emoji":"📄","requires":{"bins":["nano-pdf"]},"install":[{"id":"uv","kind":"uv","package":"nano-pdf","bins":["nano-pdf"],"label":"Install nano-pdf (uv)"}]}}
|
||||
---
|
||||
|
||||
# nano-pdf
|
||||
|
||||
Use `nano-pdf` to apply edits to a specific page in a PDF using a natural-language instruction.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
nano-pdf edit deck.pdf 1 "Change the title to 'Q3 Results' and fix the typo in the subtitle"
|
||||
```
|
||||
|
||||
Notes:
|
||||
- Page numbers are 0-based or 1-based depending on the tool’s version/config; if the result looks off by one, retry with the other.
|
||||
- Always sanity-check the output PDF before sending it out.
|
||||
@@ -0,0 +1,335 @@
|
||||
---
|
||||
name: "News Digest"
|
||||
description: "Generate daily news digests for portfolio holdings and watchlist. Aggregates financial news from multiple sources, summarizes key developments, and highlights market-moving events. Use when you need a comprehensive market briefing or want to stay informed on specific tickers."
|
||||
---
|
||||
|
||||
# News Digest
|
||||
|
||||
## What This Skill Does
|
||||
|
||||
Generates comprehensive news digests for your portfolio holdings and watchlist by:
|
||||
|
||||
1. **Searching** via agent-core's Exa MCP (no API key needed)
|
||||
2. **Filtering** for financially relevant content (earnings, filings, analyst ratings, M&A)
|
||||
3. **Summarizing** using agent-core's LLM providers (already authenticated)
|
||||
4. **Categorizing** news by sentiment and impact level
|
||||
5. **Outputting** structured digests in multiple formats (JSON, Markdown, Email)
|
||||
|
||||
**Use Cases**:
|
||||
- Morning market briefing before market open
|
||||
- End-of-day summary of portfolio-relevant news
|
||||
- Earnings season monitoring
|
||||
- SEC filing alerts
|
||||
- Macro event tracking
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Stanley -> Tiara (claude-flow) -> Agent-Core
|
||||
│ │
|
||||
│ ├── WebSearch (Exa MCP)
|
||||
│ ├── WebFetch (content extraction)
|
||||
│ └── 15+ LLM providers (auth.json)
|
||||
│
|
||||
└── MCP Tools (100+ orchestration tools)
|
||||
```
|
||||
|
||||
**No separate API keys required** - leverages agent-core infrastructure:
|
||||
- Web search via `mcp.exa.ai` (same as agent-core's websearch.ts)
|
||||
- LLM summarization via `~/.opencode/auth.json` providers
|
||||
- Python 3.10+ with `httpx`
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Single ticker digest
|
||||
python {baseDir}/scripts/news_digest.py --tickers AAPL
|
||||
|
||||
# Portfolio digest (multiple tickers)
|
||||
python {baseDir}/scripts/news_digest.py --tickers AAPL,NVDA,MSFT,GOOGL
|
||||
|
||||
# With summarization
|
||||
python {baseDir}/scripts/news_digest.py --tickers AAPL --summarize
|
||||
|
||||
# Custom time range (last 24h, 7d, 30d)
|
||||
python {baseDir}/scripts/news_digest.py --tickers AAPL --range 7d
|
||||
|
||||
# Output formats
|
||||
python {baseDir}/scripts/news_digest.py --tickers AAPL --format json
|
||||
python {baseDir}/scripts/news_digest.py --tickers AAPL --format markdown
|
||||
python {baseDir}/scripts/news_digest.py --tickers AAPL --format email
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Search Categories
|
||||
|
||||
The digest searches for news in these categories per ticker:
|
||||
|
||||
| Category | Search Query Pattern |
|
||||
|----------|---------------------|
|
||||
| **General** | `{ticker} stock news` |
|
||||
| **Earnings** | `{ticker} earnings report results` |
|
||||
| **SEC Filings** | `{ticker} SEC filing 10-K 10-Q 8-K` |
|
||||
| **Analyst** | `{ticker} analyst rating upgrade downgrade` |
|
||||
| **Insider** | `{ticker} insider trading buy sell` |
|
||||
| **M&A** | `{ticker} merger acquisition deal` |
|
||||
| **Macro** | `{ticker} Fed interest rates inflation` |
|
||||
|
||||
---
|
||||
|
||||
## Output Formats
|
||||
|
||||
### JSON (for programmatic use)
|
||||
|
||||
```json
|
||||
{
|
||||
"generated_at": "2026-01-09T08:00:00Z",
|
||||
"tickers": ["AAPL"],
|
||||
"range": "24h",
|
||||
"articles": [
|
||||
{
|
||||
"ticker": "AAPL",
|
||||
"category": "earnings",
|
||||
"title": "Apple Reports Record Q1 Revenue",
|
||||
"url": "https://...",
|
||||
"source": "Reuters",
|
||||
"published": "2026-01-09T06:30:00Z",
|
||||
"summary": "Apple reported Q1 revenue of $130B...",
|
||||
"sentiment": "positive",
|
||||
"impact": "high"
|
||||
}
|
||||
],
|
||||
"summary": {
|
||||
"total_articles": 15,
|
||||
"by_sentiment": {"positive": 8, "neutral": 5, "negative": 2},
|
||||
"key_themes": ["earnings beat", "services growth", "China recovery"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Markdown (for reading/sharing)
|
||||
|
||||
```markdown
|
||||
# News Digest - 2026-01-09
|
||||
|
||||
## AAPL - Apple Inc.
|
||||
|
||||
### High Impact
|
||||
- **[Apple Reports Record Q1 Revenue](https://...)** (Reuters)
|
||||
Revenue beat expectations at $130B, driven by services growth...
|
||||
|
||||
### Earnings & Financials
|
||||
- [Apple CFO Comments on Margin Outlook](https://...)
|
||||
- [Analysts Raise Price Targets Post-Earnings](https://...)
|
||||
|
||||
### Analyst Activity
|
||||
- [Morgan Stanley Upgrades to Overweight](https://...)
|
||||
```
|
||||
|
||||
### Email (for notifications)
|
||||
|
||||
Generates HTML email-ready content with:
|
||||
- Executive summary at top
|
||||
- Color-coded sentiment indicators
|
||||
- Clickable article links
|
||||
- Unsubscribe footer
|
||||
|
||||
---
|
||||
|
||||
## Integration with Stanley
|
||||
|
||||
### Use with Portfolio Analyzer
|
||||
|
||||
```python
|
||||
from stanley.portfolio import PortfolioAnalyzer
|
||||
from stanley.skills.news_digest import generate_digest
|
||||
|
||||
# Get holdings from portfolio
|
||||
portfolio = PortfolioAnalyzer()
|
||||
holdings = portfolio.get_holdings()
|
||||
tickers = [h['symbol'] for h in holdings]
|
||||
|
||||
# Generate digest for all holdings
|
||||
digest = await generate_digest(
|
||||
tickers=tickers,
|
||||
range='24h',
|
||||
summarize=True
|
||||
)
|
||||
```
|
||||
|
||||
### Use with Research Module
|
||||
|
||||
```python
|
||||
from stanley.research import ResearchAnalyzer
|
||||
from stanley.skills.news_digest import search_news
|
||||
|
||||
# Enrich research report with recent news
|
||||
research = ResearchAnalyzer()
|
||||
report = await research.get_report('AAPL')
|
||||
|
||||
news = await search_news('AAPL', categories=['earnings', 'analyst'])
|
||||
report['recent_news'] = news
|
||||
```
|
||||
|
||||
### API Endpoint
|
||||
|
||||
```python
|
||||
# Add to stanley/api/routers/news.py
|
||||
@router.get("/news/digest/{symbols}")
|
||||
async def get_news_digest(
|
||||
symbols: str,
|
||||
range: str = "24h",
|
||||
summarize: bool = False,
|
||||
format: str = "json"
|
||||
):
|
||||
tickers = symbols.upper().split(",")
|
||||
return await generate_digest(tickers, range, summarize, format)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Agent-Core Auth (automatic)
|
||||
|
||||
Authentication is handled by agent-core's centralized auth system:
|
||||
|
||||
```bash
|
||||
# View current auth status
|
||||
cat ~/.opencode/auth.json
|
||||
|
||||
# Auth is managed via opencode CLI
|
||||
opencode auth login anthropic
|
||||
opencode auth login openai
|
||||
```
|
||||
|
||||
### Config File (optional)
|
||||
|
||||
Create `~/.stanley/news_digest.toml`:
|
||||
|
||||
```toml
|
||||
[search]
|
||||
max_results_per_category = 5
|
||||
excluded_domains = ["seekingalpha.com"] # Paywall sites
|
||||
preferred_sources = ["reuters.com", "bloomberg.com", "wsj.com"]
|
||||
|
||||
[summarization]
|
||||
enabled = true
|
||||
max_tokens = 150
|
||||
|
||||
[categories]
|
||||
# Enable/disable specific categories
|
||||
earnings = true
|
||||
sec_filings = true
|
||||
analyst = true
|
||||
insider = true
|
||||
ma = true
|
||||
macro = false # Disable macro news
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Scheduling
|
||||
|
||||
### Cron Job (Daily Digest)
|
||||
|
||||
```bash
|
||||
# Morning digest at 6:30 AM ET (before market open)
|
||||
30 6 * * 1-5 cd ~/stanley && python -m stanley.skills.news_digest \
|
||||
--portfolio --summarize --format email --send
|
||||
|
||||
# Evening digest at 5:00 PM ET (after market close)
|
||||
0 17 * * 1-5 cd ~/stanley && python -m stanley.skills.news_digest \
|
||||
--portfolio --summarize --format markdown > ~/digests/$(date +%Y-%m-%d).md
|
||||
```
|
||||
|
||||
### With Zee Integration
|
||||
|
||||
```bash
|
||||
# Zee can trigger digest and send via messaging
|
||||
zee agent --message "Generate news digest for my portfolio and send to Slack"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sentiment Analysis
|
||||
|
||||
Articles are classified by sentiment using keyword analysis and optional LLM scoring:
|
||||
|
||||
| Sentiment | Indicators |
|
||||
|-----------|------------|
|
||||
| **Positive** | beat, exceeds, upgrade, growth, record, surge, rally |
|
||||
| **Negative** | miss, downgrade, decline, layoffs, lawsuit, warning |
|
||||
| **Neutral** | announces, reports, files, updates, maintains |
|
||||
|
||||
Impact levels (high/medium/low) are determined by:
|
||||
- Source authority (Bloomberg/Reuters = higher)
|
||||
- Article recency
|
||||
- Keyword intensity
|
||||
- Ticker mention prominence
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### No results returned
|
||||
- Check `BRAVE_API_KEY` is set and valid
|
||||
- Verify ticker symbol is correct (use standard symbols)
|
||||
- Try broader time range (`--range 7d`)
|
||||
|
||||
### Rate limiting
|
||||
- Brave Search API has rate limits
|
||||
- Use `--cache` flag to cache results
|
||||
- Reduce `max_results_per_category` in config
|
||||
|
||||
### Summarization failures
|
||||
- Check LLM API key is set
|
||||
- Fall back to excerpt mode: `--no-summarize`
|
||||
- Check model availability
|
||||
|
||||
---
|
||||
|
||||
## Examples
|
||||
|
||||
### Morning Briefing Workflow
|
||||
|
||||
```bash
|
||||
# 1. Generate digest
|
||||
python {baseDir}/scripts/news_digest.py \
|
||||
--tickers AAPL,NVDA,MSFT,GOOGL,AMZN \
|
||||
--range 24h \
|
||||
--summarize \
|
||||
--format markdown \
|
||||
> /tmp/morning_digest.md
|
||||
|
||||
# 2. View in terminal
|
||||
cat /tmp/morning_digest.md | less
|
||||
|
||||
# 3. Or open in browser
|
||||
python -m markdown /tmp/morning_digest.md > /tmp/digest.html && open /tmp/digest.html
|
||||
```
|
||||
|
||||
### Earnings Season Monitor
|
||||
|
||||
```bash
|
||||
# Track earnings-specific news for tech holdings
|
||||
python {baseDir}/scripts/news_digest.py \
|
||||
--tickers AAPL,GOOGL,META,AMZN,MSFT \
|
||||
--categories earnings,analyst \
|
||||
--range 7d \
|
||||
--format json \
|
||||
| jq '.articles[] | select(.impact == "high")'
|
||||
```
|
||||
|
||||
### SEC Filing Alerts
|
||||
|
||||
```bash
|
||||
# Monitor for new SEC filings
|
||||
python {baseDir}/scripts/news_digest.py \
|
||||
--tickers AAPL \
|
||||
--categories sec_filings \
|
||||
--range 24h \
|
||||
--format json \
|
||||
| jq '.articles[] | {title, url, published}'
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
News Digest module for Stanley.
|
||||
|
||||
Provides functions to generate news digests for portfolio holdings.
|
||||
"""
|
||||
|
||||
from .news_digest import (
|
||||
Article,
|
||||
Digest,
|
||||
generate_digest,
|
||||
search_ticker_news,
|
||||
analyze_sentiment,
|
||||
format_json,
|
||||
format_markdown,
|
||||
format_email,
|
||||
CATEGORIES,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Article",
|
||||
"Digest",
|
||||
"generate_digest",
|
||||
"search_ticker_news",
|
||||
"analyze_sentiment",
|
||||
"format_json",
|
||||
"format_markdown",
|
||||
"format_email",
|
||||
"CATEGORIES",
|
||||
]
|
||||
Binary file not shown.
+527
@@ -0,0 +1,527 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
News Digest Generator for Stanley
|
||||
|
||||
Generates comprehensive news digests for portfolio holdings by leveraging
|
||||
agent-core's WebSearch and LLM providers. No separate API keys required.
|
||||
|
||||
Architecture:
|
||||
Stanley -> Tiara (claude-flow) -> Agent-Core
|
||||
- WebSearch via Exa MCP (built into agent-core)
|
||||
- LLM summarization via agent-core providers
|
||||
- Auth handled by ~/.opencode/auth.json
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
# Sentiment keywords
|
||||
POSITIVE_KEYWORDS = {
|
||||
"beat", "beats", "exceeds", "exceeded", "upgrade", "upgraded", "growth",
|
||||
"record", "surge", "surged", "rally", "rallies", "outperform", "bullish",
|
||||
"raises", "raised", "optimistic", "strong", "stronger", "positive"
|
||||
}
|
||||
NEGATIVE_KEYWORDS = {
|
||||
"miss", "missed", "misses", "downgrade", "downgraded", "decline", "declined",
|
||||
"layoffs", "lawsuit", "warning", "warns", "bearish", "weak", "weaker",
|
||||
"cuts", "slashes", "disappoints", "negative", "concern", "risk"
|
||||
}
|
||||
|
||||
# News categories and their search patterns
|
||||
CATEGORIES = {
|
||||
"general": "{ticker} stock news today",
|
||||
"earnings": "{ticker} earnings report results quarterly",
|
||||
"sec_filings": "{ticker} SEC filing 10-K 10-Q 8-K",
|
||||
"analyst": "{ticker} analyst rating upgrade downgrade price target",
|
||||
"insider": "{ticker} insider trading executive",
|
||||
"ma": "{ticker} merger acquisition deal",
|
||||
"macro": "{ticker} Fed interest rates economy",
|
||||
}
|
||||
|
||||
# High-authority sources
|
||||
AUTHORITY_SOURCES = {
|
||||
"reuters.com", "bloomberg.com", "wsj.com", "ft.com", "cnbc.com",
|
||||
"marketwatch.com", "barrons.com", "yahoo.com", "investing.com"
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Article:
|
||||
"""Represents a news article."""
|
||||
ticker: str
|
||||
category: str
|
||||
title: str
|
||||
url: str
|
||||
source: str
|
||||
description: str
|
||||
published: Optional[str] = None
|
||||
summary: Optional[str] = None
|
||||
sentiment: str = "neutral"
|
||||
impact: str = "medium"
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {
|
||||
"ticker": self.ticker,
|
||||
"category": self.category,
|
||||
"title": self.title,
|
||||
"url": self.url,
|
||||
"source": self.source,
|
||||
"published": self.published,
|
||||
"description": self.description,
|
||||
"summary": self.summary,
|
||||
"sentiment": self.sentiment,
|
||||
"impact": self.impact,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Digest:
|
||||
"""Represents a complete news digest."""
|
||||
generated_at: str
|
||||
tickers: list[str]
|
||||
range: str
|
||||
articles: list[Article] = field(default_factory=list)
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
articles = [a.to_dict() for a in self.articles]
|
||||
sentiment_counts = {"positive": 0, "neutral": 0, "negative": 0}
|
||||
for a in self.articles:
|
||||
sentiment_counts[a.sentiment] = sentiment_counts.get(a.sentiment, 0) + 1
|
||||
|
||||
return {
|
||||
"generated_at": self.generated_at,
|
||||
"tickers": self.tickers,
|
||||
"range": self.range,
|
||||
"articles": articles,
|
||||
"summary": {
|
||||
"total_articles": len(articles),
|
||||
"by_sentiment": sentiment_counts,
|
||||
"by_ticker": self._count_by_ticker(),
|
||||
}
|
||||
}
|
||||
|
||||
def _count_by_ticker(self) -> dict[str, int]:
|
||||
counts = {}
|
||||
for a in self.articles:
|
||||
counts[a.ticker] = counts.get(a.ticker, 0) + 1
|
||||
return counts
|
||||
|
||||
|
||||
def analyze_sentiment(text: str) -> str:
|
||||
"""Simple keyword-based sentiment analysis."""
|
||||
text_lower = text.lower()
|
||||
positive_count = sum(1 for kw in POSITIVE_KEYWORDS if kw in text_lower)
|
||||
negative_count = sum(1 for kw in NEGATIVE_KEYWORDS if kw in text_lower)
|
||||
|
||||
if positive_count > negative_count + 1:
|
||||
return "positive"
|
||||
elif negative_count > positive_count + 1:
|
||||
return "negative"
|
||||
return "neutral"
|
||||
|
||||
|
||||
def determine_impact(article: Article) -> str:
|
||||
"""Determine article impact level."""
|
||||
source_lower = article.source.lower()
|
||||
is_authority = any(s in source_lower for s in AUTHORITY_SOURCES)
|
||||
high_impact_categories = {"earnings", "ma", "sec_filings"}
|
||||
|
||||
if article.category in high_impact_categories and is_authority:
|
||||
return "high"
|
||||
elif article.category in high_impact_categories or is_authority:
|
||||
return "medium"
|
||||
return "low"
|
||||
|
||||
|
||||
def extract_source(url: str) -> str:
|
||||
"""Extract source domain from URL."""
|
||||
try:
|
||||
from urllib.parse import urlparse
|
||||
parsed = urlparse(url)
|
||||
domain = parsed.netloc.replace("www.", "")
|
||||
return domain
|
||||
except Exception:
|
||||
return "unknown"
|
||||
|
||||
|
||||
def find_agent_core_path() -> Optional[Path]:
|
||||
"""Find agent-core installation path."""
|
||||
# Check common locations
|
||||
paths = [
|
||||
Path.home() / ".local/src/agent-core",
|
||||
Path.home() / ".opencode",
|
||||
Path("/opt/agent-core"),
|
||||
]
|
||||
for p in paths:
|
||||
if p.exists():
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
def get_opencode_bin() -> str:
|
||||
"""Get opencode binary path."""
|
||||
# Check if opencode is in PATH
|
||||
result = subprocess.run(["which", "opencode"], capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
return result.stdout.strip()
|
||||
|
||||
# Check common locations
|
||||
paths = [
|
||||
Path.home() / ".local/bin/opencode",
|
||||
Path("/usr/local/bin/opencode"),
|
||||
Path.home() / ".local/src/agent-core/dist/opencode",
|
||||
]
|
||||
for p in paths:
|
||||
if p.exists():
|
||||
return str(p)
|
||||
|
||||
# Fallback to npx
|
||||
return "npx opencode-ai"
|
||||
|
||||
|
||||
async def search_via_agent_core(query: str, num_results: int = 5) -> list[dict]:
|
||||
"""
|
||||
Search using agent-core's WebSearch tool via Exa MCP.
|
||||
Uses EXA_API_KEY from environment if available.
|
||||
"""
|
||||
try:
|
||||
import httpx
|
||||
|
||||
# Use Exa MCP endpoint directly (same as agent-core's websearch.ts)
|
||||
search_request = {
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "web_search_exa",
|
||||
"arguments": {
|
||||
"query": query,
|
||||
"type": "auto",
|
||||
"numResults": num_results,
|
||||
"livecrawl": "fallback",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
headers = {
|
||||
"accept": "application/json, text/event-stream",
|
||||
"content-type": "application/json",
|
||||
}
|
||||
|
||||
# Add API key if available
|
||||
exa_key = os.environ.get("EXA_API_KEY")
|
||||
if exa_key:
|
||||
headers["x-api-key"] = exa_key
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
"https://mcp.exa.ai/mcp",
|
||||
json=search_request,
|
||||
headers=headers,
|
||||
timeout=25.0
|
||||
)
|
||||
|
||||
if resp.status_code == 200:
|
||||
# Parse SSE response (format: "event: message\ndata: {...}")
|
||||
for line in resp.text.split("\n"):
|
||||
if line.startswith("data:"):
|
||||
json_str = line[5:].strip()
|
||||
if json_str:
|
||||
data = json.loads(json_str)
|
||||
if data.get("result", {}).get("content"):
|
||||
text = data["result"]["content"][0]["text"]
|
||||
return parse_exa_results(text)
|
||||
except Exception as e:
|
||||
print(f"Exa MCP call failed: {e}", file=sys.stderr)
|
||||
|
||||
return []
|
||||
|
||||
|
||||
async def search_via_claude_code(query: str, num_results: int = 5) -> list[dict]:
|
||||
"""
|
||||
When running as a Claude Code skill, we can leverage the built-in WebSearch.
|
||||
This function returns a marker that tells the parent skill to use WebSearch.
|
||||
"""
|
||||
# Return instruction for Claude Code to execute WebSearch
|
||||
# The actual search happens at the skill execution layer
|
||||
return [{
|
||||
"_use_websearch": True,
|
||||
"query": query,
|
||||
"num_results": num_results
|
||||
}]
|
||||
|
||||
|
||||
def parse_exa_results(text: str) -> list[dict]:
|
||||
"""Parse search results from Exa MCP response text."""
|
||||
results = []
|
||||
# Exa returns structured text with Title:, URL:, Published Date:, Text: fields
|
||||
current = {}
|
||||
|
||||
for line in text.split("\n"):
|
||||
line = line.strip()
|
||||
if line.startswith("Title:"):
|
||||
if current.get("title") and current.get("url"):
|
||||
results.append(current)
|
||||
current = {"title": line[6:].strip()}
|
||||
elif line.startswith("URL:"):
|
||||
current["url"] = line[4:].strip()
|
||||
elif line.startswith("Published Date:"):
|
||||
current["published"] = line[15:].strip()
|
||||
elif line.startswith("Text:"):
|
||||
current["description"] = line[5:].strip()
|
||||
elif current.get("description") and line and not line.startswith(("Title:", "URL:", "Published")):
|
||||
# Append to description (but limit length)
|
||||
if len(current["description"]) < 500:
|
||||
current["description"] += " " + line
|
||||
|
||||
if current.get("title") and current.get("url"):
|
||||
results.append(current)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
async def search_ticker_news(
|
||||
ticker: str,
|
||||
categories: list[str],
|
||||
results_per_category: int = 3,
|
||||
) -> list[Article]:
|
||||
"""Search news for a single ticker across categories."""
|
||||
articles = []
|
||||
seen_urls = set()
|
||||
|
||||
for category in categories:
|
||||
if category not in CATEGORIES:
|
||||
continue
|
||||
|
||||
query = CATEGORIES[category].format(ticker=ticker)
|
||||
results = await search_via_agent_core(query, results_per_category)
|
||||
|
||||
for r in results:
|
||||
# Check if this is a marker to use WebSearch
|
||||
if r.get("_use_websearch"):
|
||||
# Skip - this will be handled by Claude Code
|
||||
continue
|
||||
|
||||
url = r.get("url", "")
|
||||
if not url or url in seen_urls:
|
||||
continue
|
||||
seen_urls.add(url)
|
||||
|
||||
title = r.get("title", "").strip()
|
||||
description = r.get("description", "").strip()
|
||||
|
||||
article = Article(
|
||||
ticker=ticker,
|
||||
category=category,
|
||||
title=title,
|
||||
url=url,
|
||||
source=extract_source(url),
|
||||
description=description,
|
||||
)
|
||||
|
||||
combined_text = f"{title} {description}"
|
||||
article.sentiment = analyze_sentiment(combined_text)
|
||||
article.impact = determine_impact(article)
|
||||
|
||||
articles.append(article)
|
||||
|
||||
return articles
|
||||
|
||||
|
||||
async def generate_digest(
|
||||
tickers: list[str],
|
||||
range_str: str = "24h",
|
||||
categories: Optional[list[str]] = None,
|
||||
summarize: bool = False,
|
||||
max_articles: int = 50
|
||||
) -> Digest:
|
||||
"""Generate a news digest for the given tickers."""
|
||||
if categories is None:
|
||||
categories = list(CATEGORIES.keys())
|
||||
|
||||
all_articles = []
|
||||
for ticker in tickers:
|
||||
ticker_articles = await search_ticker_news(
|
||||
ticker.upper(),
|
||||
categories,
|
||||
results_per_category=3,
|
||||
)
|
||||
all_articles.extend(ticker_articles)
|
||||
|
||||
# Sort by impact then sentiment
|
||||
impact_order = {"high": 0, "medium": 1, "low": 2}
|
||||
all_articles.sort(key=lambda a: (impact_order.get(a.impact, 2), a.sentiment != "positive"))
|
||||
all_articles = all_articles[:max_articles]
|
||||
|
||||
return Digest(
|
||||
generated_at=datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
tickers=[t.upper() for t in tickers],
|
||||
range=range_str,
|
||||
articles=all_articles
|
||||
)
|
||||
|
||||
|
||||
def format_json(digest: Digest) -> str:
|
||||
"""Format digest as JSON."""
|
||||
return json.dumps(digest.to_dict(), indent=2)
|
||||
|
||||
|
||||
def format_markdown(digest: Digest) -> str:
|
||||
"""Format digest as Markdown."""
|
||||
lines = [
|
||||
f"# News Digest - {digest.generated_at[:10]}",
|
||||
"",
|
||||
f"**Tickers:** {', '.join(digest.tickers)}",
|
||||
f"**Range:** {digest.range}",
|
||||
f"**Total Articles:** {len(digest.articles)}",
|
||||
"",
|
||||
]
|
||||
|
||||
by_ticker: dict[str, list[Article]] = {}
|
||||
for a in digest.articles:
|
||||
by_ticker.setdefault(a.ticker, []).append(a)
|
||||
|
||||
for ticker, articles in by_ticker.items():
|
||||
lines.append(f"## {ticker}")
|
||||
lines.append("")
|
||||
|
||||
high_impact = [a for a in articles if a.impact == "high"]
|
||||
other = [a for a in articles if a.impact != "high"]
|
||||
|
||||
if high_impact:
|
||||
lines.append("### High Impact")
|
||||
for a in high_impact:
|
||||
sentiment_icon = {"positive": "+", "negative": "-", "neutral": ""}[a.sentiment]
|
||||
lines.append(f"- {sentiment_icon}**[{a.title}]({a.url})** ({a.source})")
|
||||
if a.description:
|
||||
lines.append(f" {a.description[:200]}...")
|
||||
lines.append("")
|
||||
|
||||
if other:
|
||||
lines.append("### Other News")
|
||||
for a in other:
|
||||
sentiment_icon = {"positive": "+", "negative": "-", "neutral": ""}[a.sentiment]
|
||||
lines.append(f"- {sentiment_icon}[{a.title}]({a.url}) ({a.source})")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def format_email(digest: Digest) -> str:
|
||||
"""Format digest as HTML email."""
|
||||
sentiment_colors = {
|
||||
"positive": "#22c55e",
|
||||
"negative": "#ef4444",
|
||||
"neutral": "#6b7280"
|
||||
}
|
||||
|
||||
articles_html = []
|
||||
for a in digest.articles:
|
||||
color = sentiment_colors.get(a.sentiment, "#6b7280")
|
||||
articles_html.append(f"""
|
||||
<tr>
|
||||
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb;">
|
||||
<span style="color: {color}; font-weight: bold;">{a.ticker}</span>
|
||||
</td>
|
||||
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb;">
|
||||
<a href="{a.url}" style="color: #2563eb; text-decoration: none;">{a.title}</a>
|
||||
<br><small style="color: #6b7280;">{a.source} | {a.category}</small>
|
||||
</td>
|
||||
<td style="padding: 12px; border-bottom: 1px solid #e5e7eb;">
|
||||
<span style="background: {color}; color: white; padding: 2px 8px; border-radius: 4px; font-size: 12px;">
|
||||
{a.sentiment}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
""")
|
||||
|
||||
return f"""<!DOCTYPE html>
|
||||
<html>
|
||||
<head><style>body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }}</style></head>
|
||||
<body style="max-width: 800px; margin: 0 auto; padding: 20px;">
|
||||
<h1 style="color: #1f2937;">News Digest</h1>
|
||||
<p style="color: #6b7280;">Generated: {digest.generated_at[:10]} | Tickers: {', '.join(digest.tickers)}</p>
|
||||
<table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
|
||||
<thead><tr style="background: #f3f4f6;">
|
||||
<th style="padding: 12px; text-align: left;">Ticker</th>
|
||||
<th style="padding: 12px; text-align: left;">Article</th>
|
||||
<th style="padding: 12px; text-align: left;">Sentiment</th>
|
||||
</tr></thead>
|
||||
<tbody>{''.join(articles_html)}</tbody>
|
||||
</table>
|
||||
<hr style="margin-top: 40px; border: none; border-top: 1px solid #e5e7eb;">
|
||||
<p style="color: #9ca3af; font-size: 12px;">Generated by Stanley via agent-core</p>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate news digests for portfolio holdings (uses agent-core infrastructure)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--tickers", "-t",
|
||||
required=True,
|
||||
help="Comma-separated list of tickers (e.g., AAPL,NVDA,MSFT)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--range", "-r",
|
||||
default="24h",
|
||||
choices=["24h", "7d", "30d"],
|
||||
help="Time range for news (default: 24h)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--categories", "-c",
|
||||
help="Comma-separated categories (default: all)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--summarize", "-s",
|
||||
action="store_true",
|
||||
help="Summarize articles using agent-core LLM"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--format", "-f",
|
||||
default="markdown",
|
||||
choices=["json", "markdown", "email"],
|
||||
help="Output format (default: markdown)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-articles", "-m",
|
||||
type=int,
|
||||
default=50,
|
||||
help="Maximum articles in digest (default: 50)"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
tickers = [t.strip() for t in args.tickers.split(",")]
|
||||
categories = None
|
||||
if args.categories:
|
||||
categories = [c.strip() for c in args.categories.split(",")]
|
||||
|
||||
digest = asyncio.run(generate_digest(
|
||||
tickers=tickers,
|
||||
range_str=args.range,
|
||||
categories=categories,
|
||||
summarize=args.summarize,
|
||||
max_articles=args.max_articles
|
||||
))
|
||||
|
||||
if args.format == "json":
|
||||
print(format_json(digest))
|
||||
elif args.format == "markdown":
|
||||
print(format_markdown(digest))
|
||||
elif args.format == "email":
|
||||
print(format_email(digest))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,156 @@
|
||||
---
|
||||
name: notion
|
||||
description: Notion API for creating and managing pages, databases, and blocks.
|
||||
homepage: https://developers.notion.com
|
||||
metadata: {"zee":{"emoji":"📝"}}
|
||||
---
|
||||
|
||||
# notion
|
||||
|
||||
Use the Notion API to create/read/update pages, data sources (databases), and blocks.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Create an integration at https://notion.so/my-integrations
|
||||
2. Copy the API key (starts with `ntn_` or `secret_`)
|
||||
3. Store it:
|
||||
```bash
|
||||
mkdir -p ~/.config/notion
|
||||
echo "ntn_your_key_here" > ~/.config/notion/api_key
|
||||
```
|
||||
4. Share target pages/databases with your integration (click "..." → "Connect to" → your integration name)
|
||||
|
||||
## API Basics
|
||||
|
||||
All requests need:
|
||||
```bash
|
||||
NOTION_KEY=$(cat ~/.config/notion/api_key)
|
||||
curl -X GET "https://api.notion.com/v1/..." \
|
||||
-H "Authorization: Bearer $NOTION_KEY" \
|
||||
-H "Notion-Version: 2025-09-03" \
|
||||
-H "Content-Type: application/json"
|
||||
```
|
||||
|
||||
> **Note:** The `Notion-Version` header is required. This skill uses `2025-09-03` (latest). In this version, databases are called "data sources" in the API.
|
||||
|
||||
## Common Operations
|
||||
|
||||
**Search for pages and data sources:**
|
||||
```bash
|
||||
curl -X POST "https://api.notion.com/v1/search" \
|
||||
-H "Authorization: Bearer $NOTION_KEY" \
|
||||
-H "Notion-Version: 2025-09-03" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"query": "page title"}'
|
||||
```
|
||||
|
||||
**Get page:**
|
||||
```bash
|
||||
curl "https://api.notion.com/v1/pages/{page_id}" \
|
||||
-H "Authorization: Bearer $NOTION_KEY" \
|
||||
-H "Notion-Version: 2025-09-03"
|
||||
```
|
||||
|
||||
**Get page content (blocks):**
|
||||
```bash
|
||||
curl "https://api.notion.com/v1/blocks/{page_id}/children" \
|
||||
-H "Authorization: Bearer $NOTION_KEY" \
|
||||
-H "Notion-Version: 2025-09-03"
|
||||
```
|
||||
|
||||
**Create page in a data source:**
|
||||
```bash
|
||||
curl -X POST "https://api.notion.com/v1/pages" \
|
||||
-H "Authorization: Bearer $NOTION_KEY" \
|
||||
-H "Notion-Version: 2025-09-03" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"parent": {"database_id": "xxx"},
|
||||
"properties": {
|
||||
"Name": {"title": [{"text": {"content": "New Item"}}]},
|
||||
"Status": {"select": {"name": "Todo"}}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**Query a data source (database):**
|
||||
```bash
|
||||
curl -X POST "https://api.notion.com/v1/data_sources/{data_source_id}/query" \
|
||||
-H "Authorization: Bearer $NOTION_KEY" \
|
||||
-H "Notion-Version: 2025-09-03" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"filter": {"property": "Status", "select": {"equals": "Active"}},
|
||||
"sorts": [{"property": "Date", "direction": "descending"}]
|
||||
}'
|
||||
```
|
||||
|
||||
**Create a data source (database):**
|
||||
```bash
|
||||
curl -X POST "https://api.notion.com/v1/data_sources" \
|
||||
-H "Authorization: Bearer $NOTION_KEY" \
|
||||
-H "Notion-Version: 2025-09-03" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"parent": {"page_id": "xxx"},
|
||||
"title": [{"text": {"content": "My Database"}}],
|
||||
"properties": {
|
||||
"Name": {"title": {}},
|
||||
"Status": {"select": {"options": [{"name": "Todo"}, {"name": "Done"}]}},
|
||||
"Date": {"date": {}}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**Update page properties:**
|
||||
```bash
|
||||
curl -X PATCH "https://api.notion.com/v1/pages/{page_id}" \
|
||||
-H "Authorization: Bearer $NOTION_KEY" \
|
||||
-H "Notion-Version: 2025-09-03" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"properties": {"Status": {"select": {"name": "Done"}}}}'
|
||||
```
|
||||
|
||||
**Add blocks to page:**
|
||||
```bash
|
||||
curl -X PATCH "https://api.notion.com/v1/blocks/{page_id}/children" \
|
||||
-H "Authorization: Bearer $NOTION_KEY" \
|
||||
-H "Notion-Version: 2025-09-03" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"children": [
|
||||
{"object": "block", "type": "paragraph", "paragraph": {"rich_text": [{"text": {"content": "Hello"}}]}}
|
||||
]
|
||||
}'
|
||||
```
|
||||
|
||||
## Property Types
|
||||
|
||||
Common property formats for database items:
|
||||
- **Title:** `{"title": [{"text": {"content": "..."}}]}`
|
||||
- **Rich text:** `{"rich_text": [{"text": {"content": "..."}}]}`
|
||||
- **Select:** `{"select": {"name": "Option"}}`
|
||||
- **Multi-select:** `{"multi_select": [{"name": "A"}, {"name": "B"}]}`
|
||||
- **Date:** `{"date": {"start": "2024-01-15", "end": "2024-01-16"}}`
|
||||
- **Checkbox:** `{"checkbox": true}`
|
||||
- **Number:** `{"number": 42}`
|
||||
- **URL:** `{"url": "https://..."}`
|
||||
- **Email:** `{"email": "a@b.com"}`
|
||||
- **Relation:** `{"relation": [{"id": "page_id"}]}`
|
||||
|
||||
## Key Differences in 2025-09-03
|
||||
|
||||
- **Databases → Data Sources:** Use `/data_sources/` endpoints for queries and retrieval
|
||||
- **Two IDs:** Each database now has both a `database_id` and a `data_source_id`
|
||||
- Use `database_id` when creating pages (`parent: {"database_id": "..."}`)
|
||||
- Use `data_source_id` when querying (`POST /v1/data_sources/{id}/query`)
|
||||
- **Search results:** Databases return as `"object": "data_source"` with their `data_source_id`
|
||||
- **Parent in responses:** Pages show `parent.data_source_id` alongside `parent.database_id`
|
||||
- **Finding the data_source_id:** Search for the database, or call `GET /v1/data_sources/{data_source_id}`
|
||||
|
||||
## Notes
|
||||
|
||||
- Page/database IDs are UUIDs (with or without dashes)
|
||||
- The API cannot set database view filters — that's UI-only
|
||||
- Rate limit: ~3 requests/second average
|
||||
- Use `is_inline: true` when creating data sources to embed them in pages
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
name: obsidian
|
||||
description: Work with Obsidian vaults (plain Markdown notes) and automate via obsidian-cli.
|
||||
homepage: https://help.obsidian.md
|
||||
metadata: {"zee":{"emoji":"💎","requires":{"bins":["obsidian-cli"]},"install":[{"id":"brew","kind":"brew","formula":"yakitrak/yakitrak/obsidian-cli","bins":["obsidian-cli"],"label":"Install obsidian-cli (brew)"}]}}
|
||||
---
|
||||
|
||||
# Obsidian
|
||||
|
||||
Obsidian vault = a normal folder on disk.
|
||||
|
||||
Vault structure (typical)
|
||||
- Notes: `*.md` (plain text Markdown; edit with any editor)
|
||||
- Config: `.obsidian/` (workspace + plugin settings; usually don’t touch from scripts)
|
||||
- Canvases: `*.canvas` (JSON)
|
||||
- Attachments: whatever folder you chose in Obsidian settings (images/PDFs/etc.)
|
||||
|
||||
## Find the active vault(s)
|
||||
|
||||
Obsidian desktop tracks vaults here (source of truth):
|
||||
- `~/Library/Application Support/obsidian/obsidian.json`
|
||||
|
||||
`obsidian-cli` resolves vaults from that file; vault name is typically the **folder name** (path suffix).
|
||||
|
||||
Fast “what vault is active / where are the notes?”
|
||||
- If you’ve already set a default: `obsidian-cli print-default --path-only`
|
||||
- Otherwise, read `~/Library/Application Support/obsidian/obsidian.json` and use the vault entry with `"open": true`.
|
||||
|
||||
Notes
|
||||
- Multiple vaults common (iCloud vs `~/Documents`, work/personal, etc.). Don’t guess; read config.
|
||||
- Avoid writing hardcoded vault paths into scripts; prefer reading the config or using `print-default`.
|
||||
|
||||
## obsidian-cli quick start
|
||||
|
||||
Pick a default vault (once):
|
||||
- `obsidian-cli set-default "<vault-folder-name>"`
|
||||
- `obsidian-cli print-default` / `obsidian-cli print-default --path-only`
|
||||
|
||||
Search
|
||||
- `obsidian-cli search "query"` (note names)
|
||||
- `obsidian-cli search-content "query"` (inside notes; shows snippets + lines)
|
||||
|
||||
Create
|
||||
- `obsidian-cli create "Folder/New note" --content "..." --open`
|
||||
- Requires Obsidian URI handler (`obsidian://…`) working (Obsidian installed).
|
||||
- Avoid creating notes under “hidden” dot-folders (e.g. `.something/...`) via URI; Obsidian may refuse.
|
||||
|
||||
Move/rename (safe refactor)
|
||||
- `obsidian-cli move "old/path/note" "new/path/note"`
|
||||
- Updates `[[wikilinks]]` and common Markdown links across the vault (this is the main win vs `mv`).
|
||||
|
||||
Delete
|
||||
- `obsidian-cli delete "path/note"`
|
||||
|
||||
Prefer direct edits when appropriate: open the `.md` file and change it; Obsidian will pick it up.
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
name: openai-image-gen
|
||||
description: Batch-generate images via OpenAI Images API. Random prompt sampler + `index.html` gallery.
|
||||
homepage: https://platform.openai.com/docs/api-reference/images
|
||||
metadata: {"zee":{"emoji":"🖼️","requires":{"bins":["python3"],"env":["OPENAI_API_KEY"]},"primaryEnv":"OPENAI_API_KEY","install":[{"id":"python-brew","kind":"brew","formula":"python","bins":["python3"],"label":"Install Python (brew)"}]}}
|
||||
---
|
||||
|
||||
# OpenAI Image Gen
|
||||
|
||||
Generate a handful of “random but structured” prompts and render them via the OpenAI Images API.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
python3 {baseDir}/scripts/gen.py
|
||||
open ~/Projects/tmp/openai-image-gen-*/index.html # if ~/Projects/tmp exists; else ./tmp/...
|
||||
```
|
||||
|
||||
Useful flags:
|
||||
|
||||
```bash
|
||||
python3 {baseDir}/scripts/gen.py --count 16 --model gpt-image-1
|
||||
python3 {baseDir}/scripts/gen.py --prompt "ultra-detailed studio photo of a lobster astronaut" --count 4
|
||||
python3 {baseDir}/scripts/gen.py --size 1536x1024 --quality high --out-dir ./out/images
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
- `*.png` images
|
||||
- `prompts.json` (prompt → file mapping)
|
||||
- `index.html` (thumbnail gallery)
|
||||
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def slugify(text: str) -> str:
|
||||
text = text.lower().strip()
|
||||
text = re.sub(r"[^a-z0-9]+", "-", text)
|
||||
text = re.sub(r"-{2,}", "-", text).strip("-")
|
||||
return text or "image"
|
||||
|
||||
|
||||
def default_out_dir() -> Path:
|
||||
now = dt.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
|
||||
preferred = Path.home() / "Projects" / "tmp"
|
||||
base = preferred if preferred.is_dir() else Path("./tmp")
|
||||
base.mkdir(parents=True, exist_ok=True)
|
||||
return base / f"openai-image-gen-{now}"
|
||||
|
||||
|
||||
def pick_prompts(count: int) -> list[str]:
|
||||
subjects = [
|
||||
"a lobster astronaut",
|
||||
"a brutalist lighthouse",
|
||||
"a cozy reading nook",
|
||||
"a cyberpunk noodle shop",
|
||||
"a Vienna street at dusk",
|
||||
"a minimalist product photo",
|
||||
"a surreal underwater library",
|
||||
]
|
||||
styles = [
|
||||
"ultra-detailed studio photo",
|
||||
"35mm film still",
|
||||
"isometric illustration",
|
||||
"editorial photography",
|
||||
"soft watercolor",
|
||||
"architectural render",
|
||||
"high-contrast monochrome",
|
||||
]
|
||||
lighting = [
|
||||
"golden hour",
|
||||
"overcast soft light",
|
||||
"neon lighting",
|
||||
"dramatic rim light",
|
||||
"candlelight",
|
||||
"foggy atmosphere",
|
||||
]
|
||||
prompts: list[str] = []
|
||||
for _ in range(count):
|
||||
prompts.append(
|
||||
f"{random.choice(styles)} of {random.choice(subjects)}, {random.choice(lighting)}"
|
||||
)
|
||||
return prompts
|
||||
|
||||
|
||||
def request_images(
|
||||
api_key: str,
|
||||
prompt: str,
|
||||
model: str,
|
||||
size: str,
|
||||
quality: str,
|
||||
) -> dict:
|
||||
url = "https://api.openai.com/v1/images/generations"
|
||||
body = json.dumps(
|
||||
{
|
||||
"model": model,
|
||||
"prompt": prompt,
|
||||
"size": size,
|
||||
"quality": quality,
|
||||
"n": 1,
|
||||
"response_format": "b64_json",
|
||||
}
|
||||
).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
method="POST",
|
||||
headers={
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
data=body,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=300) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as e:
|
||||
payload = e.read().decode("utf-8", errors="replace")
|
||||
raise RuntimeError(f"OpenAI Images API failed ({e.code}): {payload}") from e
|
||||
|
||||
|
||||
def write_gallery(out_dir: Path, items: list[dict]) -> None:
|
||||
thumbs = "\n".join(
|
||||
[
|
||||
f"""
|
||||
<figure>
|
||||
<a href="{it["file"]}"><img src="{it["file"]}" loading="lazy" /></a>
|
||||
<figcaption>{it["prompt"]}</figcaption>
|
||||
</figure>
|
||||
""".strip()
|
||||
for it in items
|
||||
]
|
||||
)
|
||||
html = f"""<!doctype html>
|
||||
<meta charset="utf-8" />
|
||||
<title>openai-image-gen</title>
|
||||
<style>
|
||||
:root {{ color-scheme: dark; }}
|
||||
body {{ margin: 24px; font: 14px/1.4 ui-sans-serif, system-ui; background: #0b0f14; color: #e8edf2; }}
|
||||
h1 {{ font-size: 18px; margin: 0 0 16px; }}
|
||||
.grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 16px; }}
|
||||
figure {{ margin: 0; padding: 12px; border: 1px solid #1e2a36; border-radius: 14px; background: #0f1620; }}
|
||||
img {{ width: 100%; height: auto; border-radius: 10px; display: block; }}
|
||||
figcaption {{ margin-top: 10px; color: #b7c2cc; }}
|
||||
code {{ color: #9cd1ff; }}
|
||||
</style>
|
||||
<h1>openai-image-gen</h1>
|
||||
<p>Output: <code>{out_dir.as_posix()}</code></p>
|
||||
<div class="grid">
|
||||
{thumbs}
|
||||
</div>
|
||||
"""
|
||||
(out_dir / "index.html").write_text(html, encoding="utf-8")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="Generate images via OpenAI Images API.")
|
||||
ap.add_argument("--prompt", help="Single prompt. If omitted, random prompts are generated.")
|
||||
ap.add_argument("--count", type=int, default=8, help="How many images to generate.")
|
||||
ap.add_argument("--model", default="gpt-image-1", help="Image model id.")
|
||||
ap.add_argument("--size", default="1024x1024", help="Image size (e.g. 1024x1024, 1536x1024).")
|
||||
ap.add_argument("--quality", default="high", help="Image quality (varies by model).")
|
||||
ap.add_argument("--out-dir", default="", help="Output directory (default: ./tmp/openai-image-gen-<ts>).")
|
||||
args = ap.parse_args()
|
||||
|
||||
api_key = (os.environ.get("OPENAI_API_KEY") or "").strip()
|
||||
if not api_key:
|
||||
print("Missing OPENAI_API_KEY", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
out_dir = Path(args.out_dir).expanduser() if args.out_dir else default_out_dir()
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
prompts = [args.prompt] * args.count if args.prompt else pick_prompts(args.count)
|
||||
|
||||
items: list[dict] = []
|
||||
for idx, prompt in enumerate(prompts, start=1):
|
||||
print(f"[{idx}/{len(prompts)}] {prompt}")
|
||||
res = request_images(api_key, prompt, args.model, args.size, args.quality)
|
||||
b64 = res.get("data", [{}])[0].get("b64_json")
|
||||
if not b64:
|
||||
raise RuntimeError(f"Unexpected response: {json.dumps(res)[:400]}")
|
||||
png = base64.b64decode(b64)
|
||||
filename = f"{idx:03d}-{slugify(prompt)[:40]}.png"
|
||||
(out_dir / filename).write_bytes(png)
|
||||
items.append({"prompt": prompt, "file": filename})
|
||||
|
||||
(out_dir / "prompts.json").write_text(json.dumps(items, indent=2), encoding="utf-8")
|
||||
write_gallery(out_dir, items)
|
||||
print(f"\nWrote: {(out_dir / 'index.html').as_posix()}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
name: openai-whisper-api
|
||||
description: Transcribe audio via OpenAI Audio Transcriptions API (Whisper).
|
||||
homepage: https://platform.openai.com/docs/guides/speech-to-text
|
||||
metadata: {"zee":{"emoji":"☁️","requires":{"bins":["curl"],"env":["OPENAI_API_KEY"]},"primaryEnv":"OPENAI_API_KEY"}}
|
||||
---
|
||||
|
||||
# OpenAI Whisper API (curl)
|
||||
|
||||
Transcribe an audio file via OpenAI’s `/v1/audio/transcriptions` endpoint.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
{baseDir}/scripts/transcribe.sh /path/to/audio.m4a
|
||||
```
|
||||
|
||||
Defaults:
|
||||
- Model: `whisper-1`
|
||||
- Output: `<input>.txt`
|
||||
|
||||
## Useful flags
|
||||
|
||||
```bash
|
||||
{baseDir}/scripts/transcribe.sh /path/to/audio.ogg --model whisper-1 --out /tmp/transcript.txt
|
||||
{baseDir}/scripts/transcribe.sh /path/to/audio.m4a --language en
|
||||
{baseDir}/scripts/transcribe.sh /path/to/audio.m4a --prompt "Speaker names: Peter, Daniel"
|
||||
{baseDir}/scripts/transcribe.sh /path/to/audio.m4a --json --out /tmp/transcript.json
|
||||
```
|
||||
|
||||
## API key
|
||||
|
||||
Set `OPENAI_API_KEY`, or configure it in `~/.zee/zee.json`:
|
||||
|
||||
```json5
|
||||
{
|
||||
skills: {
|
||||
"openai-whisper-api": {
|
||||
apiKey: "OPENAI_KEY_HERE"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
cat >&2 <<'EOF'
|
||||
Usage:
|
||||
transcribe.sh <audio-file> [--model whisper-1] [--out /path/to/out.txt] [--language en] [--prompt "hint"] [--json]
|
||||
EOF
|
||||
exit 2
|
||||
}
|
||||
|
||||
if [[ "${1:-}" == "" || "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
in="${1:-}"
|
||||
shift || true
|
||||
|
||||
model="whisper-1"
|
||||
out=""
|
||||
language=""
|
||||
prompt=""
|
||||
response_format="text"
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--model)
|
||||
model="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--out)
|
||||
out="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--language)
|
||||
language="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--prompt)
|
||||
prompt="${2:-}"
|
||||
shift 2
|
||||
;;
|
||||
--json)
|
||||
response_format="json"
|
||||
shift 1
|
||||
;;
|
||||
*)
|
||||
echo "Unknown arg: $1" >&2
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ ! -f "$in" ]]; then
|
||||
echo "File not found: $in" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "${OPENAI_API_KEY:-}" == "" ]]; then
|
||||
echo "Missing OPENAI_API_KEY" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$out" == "" ]]; then
|
||||
base="${in%.*}"
|
||||
if [[ "$response_format" == "json" ]]; then
|
||||
out="${base}.json"
|
||||
else
|
||||
out="${base}.txt"
|
||||
fi
|
||||
fi
|
||||
|
||||
mkdir -p "$(dirname "$out")"
|
||||
|
||||
curl -sS https://api.openai.com/v1/audio/transcriptions \
|
||||
-H "Authorization: Bearer $OPENAI_API_KEY" \
|
||||
-H "Accept: application/json" \
|
||||
-F "file=@${in}" \
|
||||
-F "model=${model}" \
|
||||
-F "response_format=${response_format}" \
|
||||
${language:+-F "language=${language}"} \
|
||||
${prompt:+-F "prompt=${prompt}"} \
|
||||
>"$out"
|
||||
|
||||
echo "$out"
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
name: openai-whisper
|
||||
description: Local speech-to-text with the Whisper CLI (no API key).
|
||||
homepage: https://openai.com/research/whisper
|
||||
metadata: {"zee":{"emoji":"🎙️","requires":{"bins":["whisper"]},"install":[{"id":"brew","kind":"brew","formula":"openai-whisper","bins":["whisper"],"label":"Install OpenAI Whisper (brew)"}]}}
|
||||
---
|
||||
|
||||
# Whisper (CLI)
|
||||
|
||||
Use `whisper` to transcribe audio locally.
|
||||
|
||||
Quick start
|
||||
- `whisper /path/audio.mp3 --model medium --output_format txt --output_dir .`
|
||||
- `whisper /path/audio.m4a --task translate --output_format srt`
|
||||
|
||||
Notes
|
||||
- Models download to `~/.cache/whisper` on first run.
|
||||
- `--model` defaults to `turbo` on this install.
|
||||
- Use smaller models for speed, larger for accuracy.
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
name: openhue
|
||||
description: Control Philips Hue lights/scenes via the OpenHue CLI.
|
||||
homepage: https://www.openhue.io/cli
|
||||
metadata: {"zee":{"emoji":"💡","requires":{"bins":["openhue"]},"install":[{"id":"brew","kind":"brew","formula":"openhue/cli/openhue-cli","bins":["openhue"],"label":"Install OpenHue CLI (brew)"}]}}
|
||||
---
|
||||
|
||||
# OpenHue CLI
|
||||
|
||||
Use `openhue` to control Hue lights and scenes via a Hue Bridge.
|
||||
|
||||
Setup
|
||||
- Discover bridges: `openhue discover`
|
||||
- Guided setup: `openhue setup`
|
||||
|
||||
Read
|
||||
- `openhue get light --json`
|
||||
- `openhue get room --json`
|
||||
- `openhue get scene --json`
|
||||
|
||||
Write
|
||||
- Turn on: `openhue set light <id-or-name> --on`
|
||||
- Turn off: `openhue set light <id-or-name> --off`
|
||||
- Brightness: `openhue set light <id> --on --brightness 50`
|
||||
- Color: `openhue set light <id> --on --rgb #3399FF`
|
||||
- Scene: `openhue set scene <scene-id>`
|
||||
|
||||
Notes
|
||||
- You may need to press the Hue Bridge button during setup.
|
||||
- Use `--room "Room Name"` when light names are ambiguous.
|
||||
@@ -0,0 +1,105 @@
|
||||
---
|
||||
name: oracle
|
||||
description: Best practices for using the oracle CLI (prompt + file bundling, engines, sessions, and file attachment patterns).
|
||||
homepage: https://askoracle.dev
|
||||
metadata: {"zee":{"emoji":"🧿","requires":{"bins":["oracle"]},"install":[{"id":"node","kind":"node","package":"@steipete/oracle","bins":["oracle"],"label":"Install oracle (node)"}]}}
|
||||
---
|
||||
|
||||
# oracle — best use
|
||||
|
||||
Oracle bundles your prompt + selected files into one “one-shot” request so another model can answer with real repo context (API or browser automation). Treat output as advisory: verify against code + tests.
|
||||
|
||||
## Main use case (browser, GPT‑5.2 Pro)
|
||||
|
||||
Default workflow here: `--engine browser` with GPT‑5.2 Pro in ChatGPT. This is the common “long think” path: ~10 minutes to ~1 hour is normal; expect a stored session you can reattach to.
|
||||
|
||||
Recommended defaults:
|
||||
- Engine: browser (`--engine browser`)
|
||||
- Model: GPT‑5.2 Pro (`--model gpt-5.2-pro` or `--model "5.2 Pro"`)
|
||||
|
||||
## Golden path
|
||||
|
||||
1. Pick a tight file set (fewest files that still contain the truth).
|
||||
2. Preview payload + token spend (`--dry-run` + `--files-report`).
|
||||
3. Use browser mode for the usual GPT‑5.2 Pro workflow; use API only when you explicitly want it.
|
||||
4. If the run detaches/timeouts: reattach to the stored session (don’t re-run).
|
||||
|
||||
## Commands (preferred)
|
||||
|
||||
- Help:
|
||||
- `oracle --help`
|
||||
- If the binary isn’t installed: `npx -y @steipete/oracle --help` (avoid `pnpx` here; sqlite bindings).
|
||||
|
||||
- Preview (no tokens):
|
||||
- `oracle --dry-run summary -p "<task>" --file "src/**" --file "!**/*.test.*"`
|
||||
- `oracle --dry-run full -p "<task>" --file "src/**"`
|
||||
|
||||
- Token sanity:
|
||||
- `oracle --dry-run summary --files-report -p "<task>" --file "src/**"`
|
||||
|
||||
- Browser run (main path; long-running is normal):
|
||||
- `oracle --engine browser --model gpt-5.2-pro -p "<task>" --file "src/**"`
|
||||
|
||||
- Manual paste fallback:
|
||||
- `oracle --render --copy -p "<task>" --file "src/**"`
|
||||
- Note: `--copy` is a hidden alias for `--copy-markdown`.
|
||||
|
||||
## Attaching files (`--file`)
|
||||
|
||||
`--file` accepts files, directories, and globs. You can pass it multiple times; entries can be comma-separated.
|
||||
|
||||
- Include:
|
||||
- `--file "src/**"`
|
||||
- `--file src/index.ts`
|
||||
- `--file docs --file README.md`
|
||||
|
||||
- Exclude:
|
||||
- `--file "src/**" --file "!src/**/*.test.ts" --file "!**/*.snap"`
|
||||
|
||||
- Defaults (implementation behavior):
|
||||
- Default-ignored dirs: `node_modules`, `dist`, `coverage`, `.git`, `.turbo`, `.next`, `build`, `tmp` (skipped unless explicitly passed as literal dirs/files).
|
||||
- Honors `.gitignore` when expanding globs.
|
||||
- Does not follow symlinks.
|
||||
- Dotfiles filtered unless opted in via pattern (e.g. `--file ".github/**"`).
|
||||
- Files > 1 MB rejected.
|
||||
|
||||
## Engines (API vs browser)
|
||||
|
||||
- Auto-pick: `api` when `OPENAI_API_KEY` is set; otherwise `browser`.
|
||||
- Browser supports GPT + Gemini only; use `--engine api` for Claude/Grok/Codex or multi-model runs.
|
||||
- Browser attachments:
|
||||
- `--browser-attachments auto|never|always` (auto pastes inline up to ~60k chars then uploads).
|
||||
- Remote browser host:
|
||||
- Host: `oracle serve --host 0.0.0.0 --port 9473 --token <secret>`
|
||||
- Client: `oracle --engine browser --remote-host <host:port> --remote-token <secret> -p "<task>" --file "src/**"`
|
||||
|
||||
## Sessions + slugs
|
||||
|
||||
- Stored under `~/.oracle/sessions` (override with `ORACLE_HOME_DIR`).
|
||||
- Runs may detach or take a long time (browser + GPT‑5.2 Pro often does). If the CLI times out: don’t re-run; reattach.
|
||||
- List: `oracle status --hours 72`
|
||||
- Attach: `oracle session <id> --render`
|
||||
- Use `--slug "<3-5 words>"` to keep session IDs readable.
|
||||
- Duplicate prompt guard exists; use `--force` only when you truly want a fresh run.
|
||||
|
||||
## Prompt template (high signal)
|
||||
|
||||
Oracle starts with **zero** project knowledge. Assume the model cannot infer your stack, build tooling, conventions, or “obvious” paths. Include:
|
||||
- Project briefing (stack + build/test commands + platform constraints).
|
||||
- “Where things live” (key directories, entrypoints, config files, boundaries).
|
||||
- Exact question + what you tried + the error text (verbatim).
|
||||
- Constraints (“don’t change X”, “must keep public API”, etc).
|
||||
- Desired output (“return patch plan + tests”, “give 3 options with tradeoffs”).
|
||||
|
||||
## Safety
|
||||
|
||||
- Don’t attach secrets by default (`.env`, key files, auth tokens). Redact aggressively; share only what’s required.
|
||||
|
||||
## “Exhaustive prompt” restoration pattern
|
||||
|
||||
For long investigations, write a standalone prompt + file set so you can rerun days later:
|
||||
- 6–30 sentence project briefing + the goal.
|
||||
- Repro steps + exact errors + what you tried.
|
||||
- Attach all context files needed (entrypoints, configs, key modules, docs).
|
||||
|
||||
Oracle runs are one-shot; the model doesn’t remember prior runs. “Restoring context” means re-running with the same prompt + `--file …` set (or reattaching a still-running stored session).
|
||||
@@ -0,0 +1,47 @@
|
||||
---
|
||||
name: ordercli
|
||||
description: Foodora-only CLI for checking past orders and active order status (Deliveroo WIP).
|
||||
homepage: https://ordercli.sh
|
||||
metadata: {"zee":{"emoji":"🛵","requires":{"bins":["ordercli"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/ordercli","bins":["ordercli"],"label":"Install ordercli (brew)"},{"id":"go","kind":"go","module":"github.com/steipete/ordercli/cmd/ordercli@latest","bins":["ordercli"],"label":"Install ordercli (go)"}]}}
|
||||
---
|
||||
|
||||
# ordercli
|
||||
|
||||
Use `ordercli` to check past orders and track active order status (Foodora only right now).
|
||||
|
||||
Quick start (Foodora)
|
||||
- `ordercli foodora countries`
|
||||
- `ordercli foodora config set --country AT`
|
||||
- `ordercli foodora login --email you@example.com --password-stdin`
|
||||
- `ordercli foodora orders`
|
||||
- `ordercli foodora history --limit 20`
|
||||
- `ordercli foodora history show <orderCode>`
|
||||
|
||||
Orders
|
||||
- Active list (arrival/status): `ordercli foodora orders`
|
||||
- Watch: `ordercli foodora orders --watch`
|
||||
- Active order detail: `ordercli foodora order <orderCode>`
|
||||
- History detail JSON: `ordercli foodora history show <orderCode> --json`
|
||||
|
||||
Reorder (adds to cart)
|
||||
- Preview: `ordercli foodora reorder <orderCode>`
|
||||
- Confirm: `ordercli foodora reorder <orderCode> --confirm`
|
||||
- Address: `ordercli foodora reorder <orderCode> --confirm --address-id <id>`
|
||||
|
||||
Cloudflare / bot protection
|
||||
- Browser login: `ordercli foodora login --email you@example.com --password-stdin --browser`
|
||||
- Reuse profile: `--browser-profile "$HOME/Library/Application Support/ordercli/browser-profile"`
|
||||
- Import Chrome cookies: `ordercli foodora cookies chrome --profile "Default"`
|
||||
|
||||
Session import (no password)
|
||||
- `ordercli foodora session chrome --url https://www.foodora.at/ --profile "Default"`
|
||||
- `ordercli foodora session refresh --client-id android`
|
||||
|
||||
Deliveroo (WIP, not working yet)
|
||||
- Requires `DELIVEROO_BEARER_TOKEN` (optional `DELIVEROO_COOKIE`).
|
||||
- `ordercli deliveroo config set --market uk`
|
||||
- `ordercli deliveroo history`
|
||||
|
||||
Notes
|
||||
- Use `--config /tmp/ordercli.json` for testing.
|
||||
- Confirm before any reorder or cart-changing action.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,153 @@
|
||||
---
|
||||
name: peekaboo
|
||||
description: Capture and automate macOS UI with the Peekaboo CLI.
|
||||
homepage: https://peekaboo.boo
|
||||
metadata: {"zee":{"emoji":"👀","os":["darwin"],"requires":{"bins":["peekaboo"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/peekaboo","bins":["peekaboo"],"label":"Install Peekaboo (brew)"}]}}
|
||||
---
|
||||
|
||||
# Peekaboo
|
||||
|
||||
Peekaboo is a full macOS UI automation CLI: capture/inspect screens, target UI
|
||||
elements, drive input, and manage apps/windows/menus. Commands share a snapshot
|
||||
cache and support `--json`/`-j` for scripting. Run `peekaboo` or
|
||||
`peekaboo <cmd> --help` for flags; `peekaboo --version` prints build metadata.
|
||||
Tip: run via `polter peekaboo` to ensure fresh builds.
|
||||
|
||||
## Features (all CLI capabilities, excluding agent/MCP)
|
||||
|
||||
Core
|
||||
- `bridge`: inspect Peekaboo Bridge host connectivity
|
||||
- `capture`: live capture or video ingest + frame extraction
|
||||
- `clean`: prune snapshot cache and temp files
|
||||
- `config`: init/show/edit/validate, providers, models, credentials
|
||||
- `image`: capture screenshots (screen/window/menu bar regions)
|
||||
- `learn`: print the full agent guide + tool catalog
|
||||
- `list`: apps, windows, screens, menubar, permissions
|
||||
- `permissions`: check Screen Recording/Accessibility status
|
||||
- `run`: execute `.peekaboo.json` scripts
|
||||
- `sleep`: pause execution for a duration
|
||||
- `tools`: list available tools with filtering/display options
|
||||
|
||||
Interaction
|
||||
- `click`: target by ID/query/coords with smart waits
|
||||
- `drag`: drag & drop across elements/coords/Dock
|
||||
- `hotkey`: modifier combos like `cmd,shift,t`
|
||||
- `move`: cursor positioning with optional smoothing
|
||||
- `paste`: set clipboard -> paste -> restore
|
||||
- `press`: special-key sequences with repeats
|
||||
- `scroll`: directional scrolling (targeted + smooth)
|
||||
- `swipe`: gesture-style drags between targets
|
||||
- `type`: text + control keys (`--clear`, delays)
|
||||
|
||||
System
|
||||
- `app`: launch/quit/relaunch/hide/unhide/switch/list apps
|
||||
- `clipboard`: read/write clipboard (text/images/files)
|
||||
- `dialog`: click/input/file/dismiss/list system dialogs
|
||||
- `dock`: launch/right-click/hide/show/list Dock items
|
||||
- `menu`: click/list application menus + menu extras
|
||||
- `menubar`: list/click status bar items
|
||||
- `open`: enhanced `open` with app targeting + JSON payloads
|
||||
- `space`: list/switch/move-window (Spaces)
|
||||
- `visualizer`: exercise Peekaboo visual feedback animations
|
||||
- `window`: close/minimize/maximize/move/resize/focus/list
|
||||
|
||||
Vision
|
||||
- `see`: annotated UI maps, snapshot IDs, optional analysis
|
||||
|
||||
Global runtime flags
|
||||
- `--json`/`-j`, `--verbose`/`-v`, `--log-level <level>`
|
||||
- `--no-remote`, `--bridge-socket <path>`
|
||||
|
||||
## Quickstart (happy path)
|
||||
```bash
|
||||
peekaboo permissions
|
||||
peekaboo list apps --json
|
||||
peekaboo see --annotate --path /tmp/peekaboo-see.png
|
||||
peekaboo click --on B1
|
||||
peekaboo type "Hello" --return
|
||||
```
|
||||
|
||||
## Common targeting parameters (most interaction commands)
|
||||
- App/window: `--app`, `--pid`, `--window-title`, `--window-id`, `--window-index`
|
||||
- Snapshot targeting: `--snapshot` (ID from `see`; defaults to latest)
|
||||
- Element/coords: `--on`/`--id` (element ID), `--coords x,y`
|
||||
- Focus control: `--no-auto-focus`, `--space-switch`, `--bring-to-current-space`,
|
||||
`--focus-timeout-seconds`, `--focus-retry-count`
|
||||
|
||||
## Common capture parameters
|
||||
- Output: `--path`, `--format png|jpg`, `--retina`
|
||||
- Targeting: `--mode screen|window|frontmost`, `--screen-index`,
|
||||
`--window-title`, `--window-id`
|
||||
- Analysis: `--analyze "prompt"`, `--annotate`
|
||||
- Capture engine: `--capture-engine auto|classic|cg|modern|sckit`
|
||||
|
||||
## Common motion/typing parameters
|
||||
- Timing: `--duration` (drag/swipe), `--steps`, `--delay` (type/scroll/press)
|
||||
- Human-ish movement: `--profile human|linear`, `--wpm` (typing)
|
||||
- Scroll: `--direction up|down|left|right`, `--amount <ticks>`, `--smooth`
|
||||
|
||||
## Examples
|
||||
### See -> click -> type (most reliable flow)
|
||||
```bash
|
||||
peekaboo see --app Safari --window-title "Login" --annotate --path /tmp/see.png
|
||||
peekaboo click --on B3 --app Safari
|
||||
peekaboo type "user@example.com" --app Safari
|
||||
peekaboo press tab --count 1 --app Safari
|
||||
peekaboo type "supersecret" --app Safari --return
|
||||
```
|
||||
|
||||
### Target by window id
|
||||
```bash
|
||||
peekaboo list windows --app "Visual Studio Code" --json
|
||||
peekaboo click --window-id 12345 --coords 120,160
|
||||
peekaboo type "Hello from Peekaboo" --window-id 12345
|
||||
```
|
||||
|
||||
### Capture screenshots + analyze
|
||||
```bash
|
||||
peekaboo image --mode screen --screen-index 0 --retina --path /tmp/screen.png
|
||||
peekaboo image --app Safari --window-title "Dashboard" --analyze "Summarize KPIs"
|
||||
peekaboo see --mode screen --screen-index 0 --analyze "Summarize the dashboard"
|
||||
```
|
||||
|
||||
### Live capture (motion-aware)
|
||||
```bash
|
||||
peekaboo capture live --mode region --region 100,100,800,600 --duration 30 \
|
||||
--active-fps 8 --idle-fps 2 --highlight-changes --path /tmp/capture
|
||||
```
|
||||
|
||||
### App + window management
|
||||
```bash
|
||||
peekaboo app launch "Safari" --open https://example.com
|
||||
peekaboo window focus --app Safari --window-title "Example"
|
||||
peekaboo window set-bounds --app Safari --x 50 --y 50 --width 1200 --height 800
|
||||
peekaboo app quit --app Safari
|
||||
```
|
||||
|
||||
### Menus, menubar, dock
|
||||
```bash
|
||||
peekaboo menu click --app Safari --item "New Window"
|
||||
peekaboo menu click --app TextEdit --path "Format > Font > Show Fonts"
|
||||
peekaboo menu click-extra --title "WiFi"
|
||||
peekaboo dock launch Safari
|
||||
peekaboo menubar list --json
|
||||
```
|
||||
|
||||
### Mouse + gesture input
|
||||
```bash
|
||||
peekaboo move 500,300 --smooth
|
||||
peekaboo drag --from B1 --to T2
|
||||
peekaboo swipe --from-coords 100,500 --to-coords 100,200 --duration 800
|
||||
peekaboo scroll --direction down --amount 6 --smooth
|
||||
```
|
||||
|
||||
### Keyboard input
|
||||
```bash
|
||||
peekaboo hotkey --keys "cmd,shift,t"
|
||||
peekaboo press escape
|
||||
peekaboo type "Line 1\nLine 2" --delay 10
|
||||
```
|
||||
|
||||
Notes
|
||||
- Requires Screen Recording + Accessibility permissions.
|
||||
- Use `peekaboo see --annotate` to identify targets before clicking.
|
||||
@@ -0,0 +1,563 @@
|
||||
---
|
||||
name: performance-analysis
|
||||
version: 1.0.0
|
||||
description: Comprehensive performance analysis, bottleneck detection, and optimization recommendations for Claude Flow swarms
|
||||
category: monitoring
|
||||
tags: [performance, bottleneck, optimization, profiling, metrics, analysis]
|
||||
author: Claude Flow Team
|
||||
---
|
||||
|
||||
# Performance Analysis Skill
|
||||
|
||||
Comprehensive performance analysis suite for identifying bottlenecks, profiling swarm operations, generating detailed reports, and providing actionable optimization recommendations.
|
||||
|
||||
## Overview
|
||||
|
||||
This skill consolidates all performance analysis capabilities:
|
||||
- **Bottleneck Detection**: Identify performance bottlenecks across communication, processing, memory, and network
|
||||
- **Performance Profiling**: Real-time monitoring and historical analysis of swarm operations
|
||||
- **Report Generation**: Create comprehensive performance reports in multiple formats
|
||||
- **Optimization Recommendations**: AI-powered suggestions for improving performance
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Basic Bottleneck Detection
|
||||
```bash
|
||||
npx claude-flow bottleneck detect
|
||||
```
|
||||
|
||||
### Generate Performance Report
|
||||
```bash
|
||||
npx claude-flow analysis performance-report --format html --include-metrics
|
||||
```
|
||||
|
||||
### Analyze and Auto-Fix
|
||||
```bash
|
||||
npx claude-flow bottleneck detect --fix --threshold 15
|
||||
```
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
### 1. Bottleneck Detection
|
||||
|
||||
#### Command Syntax
|
||||
```bash
|
||||
npx claude-flow bottleneck detect [options]
|
||||
```
|
||||
|
||||
#### Options
|
||||
- `--swarm-id, -s <id>` - Analyze specific swarm (default: current)
|
||||
- `--time-range, -t <range>` - Analysis period: 1h, 24h, 7d, all (default: 1h)
|
||||
- `--threshold <percent>` - Bottleneck threshold percentage (default: 20)
|
||||
- `--export, -e <file>` - Export analysis to file
|
||||
- `--fix` - Apply automatic optimizations
|
||||
|
||||
#### Usage Examples
|
||||
```bash
|
||||
# Basic detection for current swarm
|
||||
npx claude-flow bottleneck detect
|
||||
|
||||
# Analyze specific swarm over 24 hours
|
||||
npx claude-flow bottleneck detect --swarm-id swarm-123 -t 24h
|
||||
|
||||
# Export detailed analysis
|
||||
npx claude-flow bottleneck detect -t 24h -e bottlenecks.json
|
||||
|
||||
# Auto-fix detected issues
|
||||
npx claude-flow bottleneck detect --fix --threshold 15
|
||||
|
||||
# Low threshold for sensitive detection
|
||||
npx claude-flow bottleneck detect --threshold 10 --export critical-issues.json
|
||||
```
|
||||
|
||||
#### Metrics Analyzed
|
||||
|
||||
**Communication Bottlenecks:**
|
||||
- Message queue delays
|
||||
- Agent response times
|
||||
- Coordination overhead
|
||||
- Memory access patterns
|
||||
- Inter-agent communication latency
|
||||
|
||||
**Processing Bottlenecks:**
|
||||
- Task completion times
|
||||
- Agent utilization rates
|
||||
- Parallel execution efficiency
|
||||
- Resource contention
|
||||
- CPU/memory usage patterns
|
||||
|
||||
**Memory Bottlenecks:**
|
||||
- Cache hit rates
|
||||
- Memory access patterns
|
||||
- Storage I/O performance
|
||||
- Neural pattern loading times
|
||||
- Memory allocation efficiency
|
||||
|
||||
**Network Bottlenecks:**
|
||||
- API call latency
|
||||
- MCP communication delays
|
||||
- External service timeouts
|
||||
- Concurrent request limits
|
||||
- Network throughput issues
|
||||
|
||||
#### Output Format
|
||||
```
|
||||
🔍 Bottleneck Analysis Report
|
||||
━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||
|
||||
📊 Summary
|
||||
├── Time Range: Last 1 hour
|
||||
├── Agents Analyzed: 6
|
||||
├── Tasks Processed: 42
|
||||
└── Critical Issues: 2
|
||||
|
||||
🚨 Critical Bottlenecks
|
||||
1. Agent Communication (35% impact)
|
||||
└── coordinator → coder-1 messages delayed by 2.3s avg
|
||||
|
||||
2. Memory Access (28% impact)
|
||||
└── Neural pattern loading taking 1.8s per access
|
||||
|
||||
⚠️ Warning Bottlenecks
|
||||
1. Task Queue (18% impact)
|
||||
└── 5 tasks waiting > 10s for assignment
|
||||
|
||||
💡 Recommendations
|
||||
1. Switch to hierarchical topology (est. 40% improvement)
|
||||
2. Enable memory caching (est. 25% improvement)
|
||||
3. Increase agent concurrency to 8 (est. 20% improvement)
|
||||
|
||||
✅ Quick Fixes Available
|
||||
Run with --fix to apply:
|
||||
- Enable smart caching
|
||||
- Optimize message routing
|
||||
- Adjust agent priorities
|
||||
```
|
||||
|
||||
### 2. Performance Profiling
|
||||
|
||||
#### Real-time Detection
|
||||
Automatic analysis during task execution:
|
||||
- Execution time vs. complexity
|
||||
- Agent utilization rates
|
||||
- Resource constraints
|
||||
- Operation patterns
|
||||
|
||||
#### Common Bottleneck Patterns
|
||||
|
||||
**Time Bottlenecks:**
|
||||
- Tasks taking > 5 minutes
|
||||
- Sequential operations that could parallelize
|
||||
- Redundant file operations
|
||||
- Inefficient algorithm implementations
|
||||
|
||||
**Coordination Bottlenecks:**
|
||||
- Single agent for complex tasks
|
||||
- Unbalanced agent workloads
|
||||
- Poor topology selection
|
||||
- Excessive synchronization points
|
||||
|
||||
**Resource Bottlenecks:**
|
||||
- High operation count (> 100)
|
||||
- Memory constraints
|
||||
- I/O limitations
|
||||
- Thread pool saturation
|
||||
|
||||
#### MCP Integration
|
||||
```javascript
|
||||
// Check for bottlenecks in Claude Code
|
||||
mcp__claude-flow__bottleneck_detect({
|
||||
timeRange: "1h",
|
||||
threshold: 20,
|
||||
autoFix: false
|
||||
})
|
||||
|
||||
// Get detailed task results with bottleneck analysis
|
||||
mcp__claude-flow__task_results({
|
||||
taskId: "task-123",
|
||||
format: "detailed"
|
||||
})
|
||||
```
|
||||
|
||||
**Result Format:**
|
||||
```json
|
||||
{
|
||||
"bottlenecks": [
|
||||
{
|
||||
"type": "coordination",
|
||||
"severity": "high",
|
||||
"description": "Single agent used for complex task",
|
||||
"recommendation": "Spawn specialized agents for parallel work",
|
||||
"impact": "35%",
|
||||
"affectedComponents": ["coordinator", "coder-1"]
|
||||
}
|
||||
],
|
||||
"improvements": [
|
||||
{
|
||||
"area": "execution_time",
|
||||
"suggestion": "Use parallel task execution",
|
||||
"expectedImprovement": "30-50% time reduction",
|
||||
"implementationSteps": [
|
||||
"Split task into smaller units",
|
||||
"Spawn 3-4 specialized agents",
|
||||
"Use mesh topology for coordination"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metrics": {
|
||||
"avgExecutionTime": "142s",
|
||||
"agentUtilization": "67%",
|
||||
"cacheHitRate": "82%",
|
||||
"parallelizationFactor": 1.2
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Report Generation
|
||||
|
||||
#### Command Syntax
|
||||
```bash
|
||||
npx claude-flow analysis performance-report [options]
|
||||
```
|
||||
|
||||
#### Options
|
||||
- `--format <type>` - Report format: json, html, markdown (default: markdown)
|
||||
- `--include-metrics` - Include detailed metrics and charts
|
||||
- `--compare <id>` - Compare with previous swarm
|
||||
- `--time-range <range>` - Analysis period: 1h, 24h, 7d, 30d, all
|
||||
- `--output <file>` - Output file path
|
||||
- `--sections <list>` - Comma-separated sections to include
|
||||
|
||||
#### Report Sections
|
||||
1. **Executive Summary**
|
||||
- Overall performance score
|
||||
- Key metrics overview
|
||||
- Critical findings
|
||||
|
||||
2. **Swarm Overview**
|
||||
- Topology configuration
|
||||
- Agent distribution
|
||||
- Task statistics
|
||||
|
||||
3. **Performance Metrics**
|
||||
- Execution times
|
||||
- Throughput analysis
|
||||
- Resource utilization
|
||||
- Latency breakdown
|
||||
|
||||
4. **Bottleneck Analysis**
|
||||
- Identified bottlenecks
|
||||
- Impact assessment
|
||||
- Optimization priorities
|
||||
|
||||
5. **Comparative Analysis** (when --compare used)
|
||||
- Performance trends
|
||||
- Improvement metrics
|
||||
- Regression detection
|
||||
|
||||
6. **Recommendations**
|
||||
- Prioritized action items
|
||||
- Expected improvements
|
||||
- Implementation guidance
|
||||
|
||||
#### Usage Examples
|
||||
```bash
|
||||
# Generate HTML report with all metrics
|
||||
npx claude-flow analysis performance-report --format html --include-metrics
|
||||
|
||||
# Compare current swarm with previous
|
||||
npx claude-flow analysis performance-report --compare swarm-123 --format markdown
|
||||
|
||||
# Custom output with specific sections
|
||||
npx claude-flow analysis performance-report \
|
||||
--sections summary,metrics,recommendations \
|
||||
--output reports/perf-analysis.html \
|
||||
--format html
|
||||
|
||||
# Weekly performance report
|
||||
npx claude-flow analysis performance-report \
|
||||
--time-range 7d \
|
||||
--include-metrics \
|
||||
--format markdown \
|
||||
--output docs/weekly-performance.md
|
||||
|
||||
# JSON format for CI/CD integration
|
||||
npx claude-flow analysis performance-report \
|
||||
--format json \
|
||||
--output build/performance.json
|
||||
```
|
||||
|
||||
#### Sample Markdown Report
|
||||
```markdown
|
||||
# Performance Analysis Report
|
||||
|
||||
## Executive Summary
|
||||
- **Overall Score**: 87/100
|
||||
- **Analysis Period**: Last 24 hours
|
||||
- **Swarms Analyzed**: 3
|
||||
- **Critical Issues**: 1
|
||||
|
||||
## Key Metrics
|
||||
| Metric | Value | Trend | Target |
|
||||
|--------|-------|-------|--------|
|
||||
| Avg Task Time | 42s | ↓ 12% | 35s |
|
||||
| Agent Utilization | 78% | ↑ 5% | 85% |
|
||||
| Cache Hit Rate | 91% | → | 90% |
|
||||
| Parallel Efficiency | 2.3x | ↑ 0.4x | 2.5x |
|
||||
|
||||
## Bottleneck Analysis
|
||||
### Critical
|
||||
1. **Agent Communication Delay** (Impact: 35%)
|
||||
- Coordinator → Coder messages delayed by 2.3s avg
|
||||
- **Fix**: Switch to hierarchical topology
|
||||
|
||||
### Warnings
|
||||
1. **Memory Access Pattern** (Impact: 18%)
|
||||
- Neural pattern loading: 1.8s per access
|
||||
- **Fix**: Enable memory caching
|
||||
|
||||
## Recommendations
|
||||
1. **High Priority**: Switch to hierarchical topology (40% improvement)
|
||||
2. **Medium Priority**: Enable memory caching (25% improvement)
|
||||
3. **Low Priority**: Increase agent concurrency to 8 (20% improvement)
|
||||
```
|
||||
|
||||
### 4. Optimization Recommendations
|
||||
|
||||
#### Automatic Fixes
|
||||
When using `--fix`, the following optimizations may be applied:
|
||||
|
||||
**1. Topology Optimization**
|
||||
- Switch to more efficient topology (mesh → hierarchical)
|
||||
- Adjust communication patterns
|
||||
- Reduce coordination overhead
|
||||
- Optimize message routing
|
||||
|
||||
**2. Caching Enhancement**
|
||||
- Enable memory caching
|
||||
- Optimize cache strategies
|
||||
- Preload common patterns
|
||||
- Implement cache warming
|
||||
|
||||
**3. Concurrency Tuning**
|
||||
- Adjust agent counts
|
||||
- Optimize parallel execution
|
||||
- Balance workload distribution
|
||||
- Implement load balancing
|
||||
|
||||
**4. Priority Adjustment**
|
||||
- Reorder task queues
|
||||
- Prioritize critical paths
|
||||
- Reduce wait times
|
||||
- Implement fair scheduling
|
||||
|
||||
**5. Resource Optimization**
|
||||
- Optimize memory usage
|
||||
- Reduce I/O operations
|
||||
- Batch API calls
|
||||
- Implement connection pooling
|
||||
|
||||
#### Performance Impact
|
||||
Typical improvements after bottleneck resolution:
|
||||
|
||||
- **Communication**: 30-50% faster message delivery
|
||||
- **Processing**: 20-40% reduced task completion time
|
||||
- **Memory**: 40-60% fewer cache misses
|
||||
- **Network**: 25-45% reduced API latency
|
||||
- **Overall**: 25-45% total performance improvement
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Continuous Monitoring
|
||||
```bash
|
||||
# Monitor performance in real-time
|
||||
npx claude-flow swarm monitor --interval 5
|
||||
|
||||
# Generate hourly reports
|
||||
while true; do
|
||||
npx claude-flow analysis performance-report \
|
||||
--format json \
|
||||
--output logs/perf-$(date +%Y%m%d-%H%M).json
|
||||
sleep 3600
|
||||
done
|
||||
```
|
||||
|
||||
### CI/CD Integration
|
||||
```yaml
|
||||
# .github/workflows/performance.yml
|
||||
name: Performance Analysis
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: Run Performance Analysis
|
||||
run: |
|
||||
npx claude-flow analysis performance-report \
|
||||
--format json \
|
||||
--output performance.json
|
||||
- name: Check Performance Thresholds
|
||||
run: |
|
||||
npx claude-flow bottleneck detect \
|
||||
--threshold 15 \
|
||||
--export bottlenecks.json
|
||||
- name: Upload Reports
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: performance-reports
|
||||
path: |
|
||||
performance.json
|
||||
bottlenecks.json
|
||||
```
|
||||
|
||||
### Custom Analysis Scripts
|
||||
```javascript
|
||||
// scripts/analyze-performance.js
|
||||
const { exec } = require('child_process');
|
||||
const fs = require('fs');
|
||||
|
||||
async function analyzePerformance() {
|
||||
// Run bottleneck detection
|
||||
const bottlenecks = await runCommand(
|
||||
'npx claude-flow bottleneck detect --format json'
|
||||
);
|
||||
|
||||
// Generate performance report
|
||||
const report = await runCommand(
|
||||
'npx claude-flow analysis performance-report --format json'
|
||||
);
|
||||
|
||||
// Analyze results
|
||||
const analysis = {
|
||||
bottlenecks: JSON.parse(bottlenecks),
|
||||
performance: JSON.parse(report),
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
|
||||
// Save combined analysis
|
||||
fs.writeFileSync(
|
||||
'analysis/combined-report.json',
|
||||
JSON.stringify(analysis, null, 2)
|
||||
);
|
||||
|
||||
// Generate alerts if needed
|
||||
if (analysis.bottlenecks.critical.length > 0) {
|
||||
console.error('CRITICAL: Performance bottlenecks detected!');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function runCommand(cmd) {
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd, (error, stdout, stderr) => {
|
||||
if (error) reject(error);
|
||||
else resolve(stdout);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
analyzePerformance().catch(console.error);
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Regular Analysis
|
||||
- Run bottleneck detection after major changes
|
||||
- Generate weekly performance reports
|
||||
- Monitor trends over time
|
||||
- Set up automated alerts
|
||||
|
||||
### 2. Threshold Tuning
|
||||
- Start with default threshold (20%)
|
||||
- Lower for production systems (10-15%)
|
||||
- Higher for development (25-30%)
|
||||
- Adjust based on requirements
|
||||
|
||||
### 3. Fix Strategy
|
||||
- Always review before applying --fix
|
||||
- Test fixes in development first
|
||||
- Apply fixes incrementally
|
||||
- Monitor impact after changes
|
||||
|
||||
### 4. Report Integration
|
||||
- Include in documentation
|
||||
- Share with team regularly
|
||||
- Track improvements over time
|
||||
- Use for capacity planning
|
||||
|
||||
### 5. Continuous Optimization
|
||||
- Learn from each analysis
|
||||
- Build performance budgets
|
||||
- Establish baselines
|
||||
- Set improvement goals
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**High Memory Usage**
|
||||
```bash
|
||||
# Analyze memory bottlenecks
|
||||
npx claude-flow bottleneck detect --threshold 10
|
||||
|
||||
# Check cache performance
|
||||
npx claude-flow cache manage --action stats
|
||||
|
||||
# Review memory metrics
|
||||
npx claude-flow memory usage
|
||||
```
|
||||
|
||||
**Slow Task Execution**
|
||||
```bash
|
||||
# Identify slow tasks
|
||||
npx claude-flow task status --detailed
|
||||
|
||||
# Analyze coordination overhead
|
||||
npx claude-flow bottleneck detect --time-range 1h
|
||||
|
||||
# Check agent utilization
|
||||
npx claude-flow agent metrics
|
||||
```
|
||||
|
||||
**Poor Cache Performance**
|
||||
```bash
|
||||
# Analyze cache hit rates
|
||||
npx claude-flow analysis performance-report --sections metrics
|
||||
|
||||
# Review cache strategy
|
||||
npx claude-flow cache manage --action analyze
|
||||
|
||||
# Enable cache warming
|
||||
npx claude-flow bottleneck detect --fix
|
||||
```
|
||||
|
||||
## Integration with Other Skills
|
||||
|
||||
- **swarm-orchestration**: Use performance data to optimize topology
|
||||
- **memory-management**: Improve cache strategies based on analysis
|
||||
- **task-coordination**: Adjust scheduling based on bottlenecks
|
||||
- **neural-training**: Train patterns from performance data
|
||||
|
||||
## Related Commands
|
||||
|
||||
- `npx claude-flow swarm monitor` - Real-time monitoring
|
||||
- `npx claude-flow token usage` - Token optimization analysis
|
||||
- `npx claude-flow cache manage` - Cache optimization
|
||||
- `npx claude-flow agent metrics` - Agent performance metrics
|
||||
- `npx claude-flow task status` - Task execution analysis
|
||||
|
||||
## See Also
|
||||
|
||||
- [Bottleneck Detection Guide](/workspaces/claude-code-flow/.claude/commands/analysis/bottleneck-detect.md)
|
||||
- [Performance Report Guide](/workspaces/claude-code-flow/.claude/commands/analysis/performance-report.md)
|
||||
- [Performance Bottlenecks Overview](/workspaces/claude-code-flow/.claude/commands/analysis/performance-bottlenecks.md)
|
||||
- [Swarm Monitoring Documentation](../swarm-orchestration/SKILL.md)
|
||||
- [Memory Management Documentation](../memory-management/SKILL.md)
|
||||
|
||||
---
|
||||
|
||||
**Version**: 1.0.0
|
||||
**Last Updated**: 2025-10-19
|
||||
**Maintainer**: Claude Flow Team
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
name: portfolio-analytics
|
||||
description: Analyze portfolio risk, performance, and allocation
|
||||
triggers:
|
||||
- portfolio analysis
|
||||
- risk metrics
|
||||
- portfolio performance
|
||||
- allocation analysis
|
||||
- VaR
|
||||
---
|
||||
|
||||
# Portfolio Analytics
|
||||
|
||||
Comprehensive portfolio risk and performance analysis.
|
||||
|
||||
## Risk Metrics
|
||||
|
||||
### Using Stanley Backend
|
||||
```
|
||||
from stanley.portfolio import PortfolioAnalyzer
|
||||
|
||||
# Example portfolio
|
||||
positions = [
|
||||
{"symbol": "AAPL", "shares": 100, "avg_cost": 150.0},
|
||||
{"symbol": "MSFT", "shares": 50, "avg_cost": 280.0},
|
||||
{"symbol": "GOOGL", "shares": 25, "avg_cost": 130.0},
|
||||
]
|
||||
|
||||
analyzer = PortfolioAnalyzer(positions)
|
||||
|
||||
# Risk metrics
|
||||
var_95 = analyzer.calculate_var(confidence=0.95, days=1)
|
||||
cvar = analyzer.calculate_cvar(confidence=0.95)
|
||||
beta = analyzer.calculate_portfolio_beta(benchmark="SPY")
|
||||
sharpe = analyzer.calculate_sharpe_ratio()
|
||||
```
|
||||
|
||||
### Via OpenBB
|
||||
```
|
||||
# Get correlation matrix
|
||||
symbols = [p["symbol"] for p in positions]
|
||||
prices = obb.equity.price.historical(symbol=",".join(symbols))
|
||||
# Calculate correlation from prices DataFrame
|
||||
```
|
||||
|
||||
## Sector Exposure
|
||||
|
||||
```
|
||||
# Sector breakdown
|
||||
exposure = analyzer.get_sector_exposure()
|
||||
# {
|
||||
# "Technology": 0.65,
|
||||
# "Communication Services": 0.15,
|
||||
# "Consumer Discretionary": 0.20
|
||||
# }
|
||||
```
|
||||
|
||||
## Performance Attribution
|
||||
|
||||
```
|
||||
# Factor attribution
|
||||
attribution = analyzer.calculate_attribution(
|
||||
start_date="2024-01-01",
|
||||
end_date="2024-06-30",
|
||||
factors=["SPY", "QQQ", "IWM"]
|
||||
)
|
||||
```
|
||||
|
||||
## Stress Testing
|
||||
|
||||
```
|
||||
# Historical scenarios
|
||||
scenarios = analyzer.stress_test([
|
||||
{"name": "2008 Crisis", "spy_return": -0.38},
|
||||
{"name": "COVID Crash", "spy_return": -0.34},
|
||||
{"name": "Tech Correction", "qqq_return": -0.25},
|
||||
])
|
||||
```
|
||||
|
||||
## Output Format
|
||||
|
||||
Portfolio Report:
|
||||
1. Holdings summary with current values
|
||||
2. Risk metrics (VaR, Sharpe, Beta)
|
||||
3. Sector/factor exposure
|
||||
4. Performance vs benchmark
|
||||
5. Risk-adjusted returns
|
||||
6. Recommendations for rebalancing
|
||||
|
||||
## Memory Integration
|
||||
|
||||
Store portfolio state:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "stanley/portfolio",
|
||||
key: "positions",
|
||||
value: {
|
||||
holdings: [...],
|
||||
lastUpdated: new Date(),
|
||||
totalValue: 125000,
|
||||
dayChange: 1250,
|
||||
dayChangePct: 0.01
|
||||
}
|
||||
});
|
||||
|
||||
await memory.store({
|
||||
namespace: "stanley/portfolio",
|
||||
key: "performance",
|
||||
value: {
|
||||
ytdReturn: 0.12,
|
||||
sharpe: 1.25,
|
||||
beta: 1.1,
|
||||
maxDrawdown: -0.08,
|
||||
benchmarkReturn: 0.10
|
||||
}
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,107 @@
|
||||
---
|
||||
name: problem-solving
|
||||
description: Structured problem-solving with scaffolding for math and informatics
|
||||
triggers:
|
||||
- solve
|
||||
- problem
|
||||
- exercise
|
||||
- challenge
|
||||
- stuck
|
||||
---
|
||||
|
||||
# Problem Solving
|
||||
|
||||
Guide through problems with appropriate scaffolding, developing independence.
|
||||
|
||||
## Problem-Solving Framework
|
||||
|
||||
### Polya's Four Steps
|
||||
1. **Understand**: What is given? What is asked?
|
||||
2. **Plan**: What approach? What tools needed?
|
||||
3. **Execute**: Carry out the plan carefully
|
||||
4. **Reflect**: Is answer reasonable? What did I learn?
|
||||
|
||||
## Scaffolding Levels
|
||||
|
||||
### Level 1: Heavy Support
|
||||
- Break problem into small steps
|
||||
- Provide hints at each step
|
||||
- Model the thinking process
|
||||
|
||||
### Level 2: Moderate Support
|
||||
- Outline the approach
|
||||
- Let student fill in details
|
||||
- Intervene only when stuck
|
||||
|
||||
### Level 3: Light Support
|
||||
- Only confirm approach is valid
|
||||
- Student does all work
|
||||
- Review at end
|
||||
|
||||
### Level 4: Independence
|
||||
- Student works alone
|
||||
- Only helps if explicitly asked
|
||||
- Focus on meta-cognitive skills
|
||||
|
||||
## Hint Progression
|
||||
|
||||
When student is stuck:
|
||||
|
||||
1. **Metacognitive**: "What have you tried? What do you know?"
|
||||
2. **Strategic**: "Have you seen a similar problem?"
|
||||
3. **Tactical**: "Try looking at [specific aspect]"
|
||||
4. **Direct**: "The next step is..."
|
||||
|
||||
Never jump to direct hints. Work down the ladder.
|
||||
|
||||
## Problem Categories
|
||||
|
||||
### Math Problems
|
||||
- Computational (apply algorithms)
|
||||
- Conceptual (apply understanding)
|
||||
- Proof (logical reasoning)
|
||||
- Modeling (translate real-world)
|
||||
|
||||
### Informatics Problems
|
||||
- Implementation (code it correctly)
|
||||
- Algorithm design (find efficient approach)
|
||||
- Debugging (find and fix errors)
|
||||
- Optimization (improve existing solution)
|
||||
|
||||
## Error Response
|
||||
|
||||
When student makes error:
|
||||
1. Don't immediately correct
|
||||
2. Ask "Are you sure about that step?"
|
||||
3. If they can't find error: point to location, not solution
|
||||
4. If still stuck: explain the error type
|
||||
5. Have them redo with understanding
|
||||
|
||||
## Memory Integration
|
||||
|
||||
Track problem-solving patterns:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "johny/problems",
|
||||
key: `${topic}/${problemId}`,
|
||||
value: {
|
||||
problem: "...",
|
||||
topic,
|
||||
difficulty: "medium",
|
||||
attemptCount: 2,
|
||||
solvedIndependently: false,
|
||||
scaffoldingUsed: "level-2",
|
||||
timeToSolve: 480, // seconds
|
||||
hintsUsed: ["strategic"],
|
||||
errorsEncountered: ["sign-error", "index-off-by-one"],
|
||||
reflection: "Need more practice with boundary conditions"
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Progression Tracking
|
||||
|
||||
Move to harder problems when:
|
||||
- 3 consecutive problems solved at current level
|
||||
- Less than 1 hint needed on average
|
||||
- Time under threshold for problem type
|
||||
@@ -0,0 +1,137 @@
|
||||
---
|
||||
name: progress-tracking
|
||||
description: Track learning progress, identify gaps, and adapt curriculum
|
||||
triggers:
|
||||
- progress
|
||||
- status
|
||||
- what should I learn
|
||||
- review
|
||||
- dashboard
|
||||
---
|
||||
|
||||
# Progress Tracking
|
||||
|
||||
Monitor learning journey with data-driven insights.
|
||||
|
||||
## Mastery-Based Progression
|
||||
|
||||
### Mastery Levels
|
||||
```
|
||||
Level 0: Never seen
|
||||
Level 1: Introduced (< 50% accuracy)
|
||||
Level 2: Developing (50-70% accuracy)
|
||||
Level 3: Proficient (70-90% accuracy)
|
||||
Level 4: Mastered (> 90% accuracy, retained over time)
|
||||
```
|
||||
|
||||
### Advancement Criteria
|
||||
To advance from Level N to N+1:
|
||||
- Accuracy threshold met for 3+ sessions
|
||||
- Demonstrated retention after 7 days
|
||||
- Can apply to novel problems
|
||||
|
||||
## Learning Metrics
|
||||
|
||||
### Daily Metrics
|
||||
- Time spent practicing
|
||||
- Problems attempted / solved
|
||||
- New concepts introduced
|
||||
- Items reviewed via spaced repetition
|
||||
|
||||
### Weekly Metrics
|
||||
- Topics progressed
|
||||
- Mastery levels gained
|
||||
- Retention rate (% of reviewed items correct)
|
||||
- Streak days
|
||||
|
||||
### Long-term Metrics
|
||||
- Overall curriculum completion %
|
||||
- Average time to mastery per topic
|
||||
- Retention curve
|
||||
- Skill tree coverage
|
||||
|
||||
## Gap Analysis
|
||||
|
||||
Identify what's blocking progress:
|
||||
|
||||
```typescript
|
||||
async function findGaps(targetTopic: string) {
|
||||
const prereqs = await getPrerequisites(targetTopic);
|
||||
const mastery = await getMasteryLevels(prereqs);
|
||||
|
||||
return prereqs.filter(p => mastery[p] < 3); // Not proficient
|
||||
}
|
||||
```
|
||||
|
||||
## Curriculum Adaptation
|
||||
|
||||
### When Student Is Struggling
|
||||
- Review prerequisites
|
||||
- More scaffolded practice
|
||||
- Simpler examples first
|
||||
- More spaced repetition
|
||||
|
||||
### When Student Is Breezing
|
||||
- Skip ahead
|
||||
- Introduce harder variants
|
||||
- Reduce scaffolding
|
||||
- Challenge problems
|
||||
|
||||
## Memory Schema
|
||||
|
||||
### Student Profile
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "johny/profile",
|
||||
key: "current",
|
||||
value: {
|
||||
currentTopics: ["calculus/integration"],
|
||||
overallProgress: 0.35, // 35% of curriculum
|
||||
streakDays: 12,
|
||||
totalPracticeHours: 47,
|
||||
strongAreas: ["algebra", "logic"],
|
||||
weakAreas: ["geometry", "probability"],
|
||||
learningStyle: "visual",
|
||||
preferredSessionLength: 25 // minutes
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Topic Progress
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "johny/topics",
|
||||
key: topic,
|
||||
value: {
|
||||
topic,
|
||||
masteryLevel: 3,
|
||||
accuracy7day: 0.82,
|
||||
accuracy30day: 0.78,
|
||||
lastPracticed: new Date(),
|
||||
nextReview: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||||
problemsSolved: 45,
|
||||
averageTimePerProblem: 120, // seconds
|
||||
notes: "Struggles with integration by parts"
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Progress Reports
|
||||
|
||||
### Daily Summary
|
||||
- What was practiced
|
||||
- Accuracy by topic
|
||||
- Items added to review queue
|
||||
- Recommendations for tomorrow
|
||||
|
||||
### Weekly Review
|
||||
- Topics progressed
|
||||
- New masteries achieved
|
||||
- Gaps identified
|
||||
- Curriculum adjustments
|
||||
|
||||
### Monthly Review
|
||||
- Overall trajectory
|
||||
- Comparison to goals
|
||||
- Major achievements
|
||||
- Strategic recommendations
|
||||
@@ -0,0 +1,26 @@
|
||||
---
|
||||
name: qmd
|
||||
description: Local search/indexing CLI (BM25 + vectors + rerank) with MCP mode.
|
||||
homepage: https://tobi.lutke.com
|
||||
metadata: {"zee":{"emoji":"📝","requires":{"bins":["qmd"]},"install":[{"id":"node","kind":"node","package":"https://github.com/tobi/qmd","bins":["qmd"],"label":"Install qmd (node)"}]}}
|
||||
---
|
||||
|
||||
# qmd
|
||||
|
||||
Use `qmd` to index local files and search them.
|
||||
|
||||
Indexing
|
||||
- Add collection: `qmd collection add /path --name docs --mask "**/*.md"`
|
||||
- Update index: `qmd update`
|
||||
- Status: `qmd status`
|
||||
|
||||
Search
|
||||
- BM25: `qmd search "query"`
|
||||
- Vector: `qmd vsearch "query"`
|
||||
- Hybrid: `qmd query "query"`
|
||||
- Get doc: `qmd get docs/path.md:10 -l 40`
|
||||
|
||||
Notes
|
||||
- Embeddings/rerank use Ollama at `OLLAMA_URL` (default `http://localhost:11434`).
|
||||
- Index lives under `~/.cache/qmd` by default.
|
||||
- MCP mode: `qmd mcp`.
|
||||
@@ -0,0 +1,446 @@
|
||||
---
|
||||
name: "ReasoningBank with AgentDB"
|
||||
description: "Implement ReasoningBank adaptive learning with AgentDB's 150x faster vector database. Includes trajectory tracking, verdict judgment, memory distillation, and pattern recognition. Use when building self-learning agents, optimizing decision-making, or implementing experience replay systems."
|
||||
---
|
||||
|
||||
# ReasoningBank with AgentDB
|
||||
|
||||
## What This Skill Does
|
||||
|
||||
Provides ReasoningBank adaptive learning patterns using AgentDB's high-performance backend (150x-12,500x faster). Enables agents to learn from experiences, judge outcomes, distill memories, and improve decision-making over time with 100% backward compatibility.
|
||||
|
||||
**Performance**: 150x faster pattern retrieval, 500x faster batch operations, <1ms memory access.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node.js 18+
|
||||
- AgentDB v1.0.7+ (via agentic-flow)
|
||||
- Understanding of reinforcement learning concepts (optional)
|
||||
|
||||
---
|
||||
|
||||
## Quick Start with CLI
|
||||
|
||||
### Initialize ReasoningBank Database
|
||||
|
||||
```bash
|
||||
# Initialize AgentDB for ReasoningBank
|
||||
npx agentdb@latest init ./.agentdb/reasoningbank.db --dimension 1536
|
||||
|
||||
# Start MCP server for Claude Code integration
|
||||
npx agentdb@latest mcp
|
||||
claude mcp add agentdb npx agentdb@latest mcp
|
||||
```
|
||||
|
||||
### Migrate from Legacy ReasoningBank
|
||||
|
||||
```bash
|
||||
# Automatic migration with validation
|
||||
npx agentdb@latest migrate --source .swarm/memory.db
|
||||
|
||||
# Verify migration
|
||||
npx agentdb@latest stats ./.agentdb/reasoningbank.db
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Quick Start with API
|
||||
|
||||
```typescript
|
||||
import { createAgentDBAdapter, computeEmbedding } from 'agentic-flow/reasoningbank';
|
||||
|
||||
// Initialize ReasoningBank with AgentDB
|
||||
const rb = await createAgentDBAdapter({
|
||||
dbPath: '.agentdb/reasoningbank.db',
|
||||
enableLearning: true, // Enable learning plugins
|
||||
enableReasoning: true, // Enable reasoning agents
|
||||
cacheSize: 1000, // 1000 pattern cache
|
||||
});
|
||||
|
||||
// Store successful experience
|
||||
const query = "How to optimize database queries?";
|
||||
const embedding = await computeEmbedding(query);
|
||||
|
||||
await rb.insertPattern({
|
||||
id: '',
|
||||
type: 'experience',
|
||||
domain: 'database-optimization',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding,
|
||||
pattern: {
|
||||
query,
|
||||
approach: 'indexing + query optimization',
|
||||
outcome: 'success',
|
||||
metrics: { latency_reduction: 0.85 }
|
||||
}
|
||||
}),
|
||||
confidence: 0.95,
|
||||
usage_count: 1,
|
||||
success_count: 1,
|
||||
created_at: Date.now(),
|
||||
last_used: Date.now(),
|
||||
});
|
||||
|
||||
// Retrieve similar experiences with reasoning
|
||||
const result = await rb.retrieveWithReasoning(embedding, {
|
||||
domain: 'database-optimization',
|
||||
k: 5,
|
||||
useMMR: true, // Diverse results
|
||||
synthesizeContext: true, // Rich context synthesis
|
||||
});
|
||||
|
||||
console.log('Memories:', result.memories);
|
||||
console.log('Context:', result.context);
|
||||
console.log('Patterns:', result.patterns);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Core ReasoningBank Concepts
|
||||
|
||||
### 1. Trajectory Tracking
|
||||
|
||||
Track agent execution paths and outcomes:
|
||||
|
||||
```typescript
|
||||
// Record trajectory (sequence of actions)
|
||||
const trajectory = {
|
||||
task: 'optimize-api-endpoint',
|
||||
steps: [
|
||||
{ action: 'analyze-bottleneck', result: 'found N+1 query' },
|
||||
{ action: 'add-eager-loading', result: 'reduced queries' },
|
||||
{ action: 'add-caching', result: 'improved latency' }
|
||||
],
|
||||
outcome: 'success',
|
||||
metrics: { latency_before: 2500, latency_after: 150 }
|
||||
};
|
||||
|
||||
const embedding = await computeEmbedding(JSON.stringify(trajectory));
|
||||
|
||||
await rb.insertPattern({
|
||||
id: '',
|
||||
type: 'trajectory',
|
||||
domain: 'api-optimization',
|
||||
pattern_data: JSON.stringify({ embedding, pattern: trajectory }),
|
||||
confidence: 0.9,
|
||||
usage_count: 1,
|
||||
success_count: 1,
|
||||
created_at: Date.now(),
|
||||
last_used: Date.now(),
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Verdict Judgment
|
||||
|
||||
Judge whether a trajectory was successful:
|
||||
|
||||
```typescript
|
||||
// Retrieve similar past trajectories
|
||||
const similar = await rb.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'api-optimization',
|
||||
k: 10,
|
||||
});
|
||||
|
||||
// Judge based on similarity to successful patterns
|
||||
const verdict = similar.memories.filter(m =>
|
||||
m.pattern.outcome === 'success' &&
|
||||
m.similarity > 0.8
|
||||
).length > 5 ? 'likely_success' : 'needs_review';
|
||||
|
||||
console.log('Verdict:', verdict);
|
||||
console.log('Confidence:', similar.memories[0]?.similarity || 0);
|
||||
```
|
||||
|
||||
### 3. Memory Distillation
|
||||
|
||||
Consolidate similar experiences into patterns:
|
||||
|
||||
```typescript
|
||||
// Get all experiences in domain
|
||||
const experiences = await rb.retrieveWithReasoning(embedding, {
|
||||
domain: 'api-optimization',
|
||||
k: 100,
|
||||
optimizeMemory: true, // Automatic consolidation
|
||||
});
|
||||
|
||||
// Distill into high-level pattern
|
||||
const distilledPattern = {
|
||||
domain: 'api-optimization',
|
||||
pattern: 'For N+1 queries: add eager loading, then cache',
|
||||
success_rate: 0.92,
|
||||
sample_size: experiences.memories.length,
|
||||
confidence: 0.95
|
||||
};
|
||||
|
||||
await rb.insertPattern({
|
||||
id: '',
|
||||
type: 'distilled-pattern',
|
||||
domain: 'api-optimization',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding: await computeEmbedding(JSON.stringify(distilledPattern)),
|
||||
pattern: distilledPattern
|
||||
}),
|
||||
confidence: 0.95,
|
||||
usage_count: 0,
|
||||
success_count: 0,
|
||||
created_at: Date.now(),
|
||||
last_used: Date.now(),
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration with Reasoning Agents
|
||||
|
||||
AgentDB provides 4 reasoning modules that enhance ReasoningBank:
|
||||
|
||||
### 1. PatternMatcher
|
||||
|
||||
Find similar successful patterns:
|
||||
|
||||
```typescript
|
||||
const result = await rb.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'problem-solving',
|
||||
k: 10,
|
||||
useMMR: true, // Maximal Marginal Relevance for diversity
|
||||
});
|
||||
|
||||
// PatternMatcher returns diverse, relevant memories
|
||||
result.memories.forEach(mem => {
|
||||
console.log(`Pattern: ${mem.pattern.approach}`);
|
||||
console.log(`Similarity: ${mem.similarity}`);
|
||||
console.log(`Success Rate: ${mem.success_count / mem.usage_count}`);
|
||||
});
|
||||
```
|
||||
|
||||
### 2. ContextSynthesizer
|
||||
|
||||
Generate rich context from multiple memories:
|
||||
|
||||
```typescript
|
||||
const result = await rb.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'code-optimization',
|
||||
synthesizeContext: true, // Enable context synthesis
|
||||
k: 5,
|
||||
});
|
||||
|
||||
// ContextSynthesizer creates coherent narrative
|
||||
console.log('Synthesized Context:', result.context);
|
||||
// "Based on 5 similar optimizations, the most effective approach
|
||||
// involves profiling, identifying bottlenecks, and applying targeted
|
||||
// improvements. Success rate: 87%"
|
||||
```
|
||||
|
||||
### 3. MemoryOptimizer
|
||||
|
||||
Automatically consolidate and prune:
|
||||
|
||||
```typescript
|
||||
const result = await rb.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'testing',
|
||||
optimizeMemory: true, // Enable automatic optimization
|
||||
});
|
||||
|
||||
// MemoryOptimizer consolidates similar patterns and prunes low-quality
|
||||
console.log('Optimizations:', result.optimizations);
|
||||
// { consolidated: 15, pruned: 3, improved_quality: 0.12 }
|
||||
```
|
||||
|
||||
### 4. ExperienceCurator
|
||||
|
||||
Filter by quality and relevance:
|
||||
|
||||
```typescript
|
||||
const result = await rb.retrieveWithReasoning(queryEmbedding, {
|
||||
domain: 'debugging',
|
||||
k: 20,
|
||||
minConfidence: 0.8, // Only high-confidence experiences
|
||||
});
|
||||
|
||||
// ExperienceCurator returns only quality experiences
|
||||
result.memories.forEach(mem => {
|
||||
console.log(`Confidence: ${mem.confidence}`);
|
||||
console.log(`Success Rate: ${mem.success_count / mem.usage_count}`);
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Legacy API Compatibility
|
||||
|
||||
AgentDB maintains 100% backward compatibility with legacy ReasoningBank:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
retrieveMemories,
|
||||
judgeTrajectory,
|
||||
distillMemories
|
||||
} from 'agentic-flow/reasoningbank';
|
||||
|
||||
// Legacy API works unchanged (uses AgentDB backend automatically)
|
||||
const memories = await retrieveMemories(query, {
|
||||
domain: 'code-generation',
|
||||
agent: 'coder'
|
||||
});
|
||||
|
||||
const verdict = await judgeTrajectory(trajectory, query);
|
||||
|
||||
const newMemories = await distillMemories(
|
||||
trajectory,
|
||||
verdict,
|
||||
query,
|
||||
{ domain: 'code-generation' }
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Performance Characteristics
|
||||
|
||||
- **Pattern Search**: 150x faster (100µs vs 15ms)
|
||||
- **Memory Retrieval**: <1ms (with cache)
|
||||
- **Batch Insert**: 500x faster (2ms vs 1s for 100 patterns)
|
||||
- **Trajectory Judgment**: <5ms (including retrieval + analysis)
|
||||
- **Memory Distillation**: <50ms (consolidate 100 patterns)
|
||||
|
||||
---
|
||||
|
||||
## Advanced Patterns
|
||||
|
||||
### Hierarchical Memory
|
||||
|
||||
Organize memories by abstraction level:
|
||||
|
||||
```typescript
|
||||
// Low-level: Specific implementation
|
||||
await rb.insertPattern({
|
||||
type: 'concrete',
|
||||
domain: 'debugging/null-pointer',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding,
|
||||
pattern: { bug: 'NPE in UserService.getUser()', fix: 'Add null check' }
|
||||
}),
|
||||
confidence: 0.9,
|
||||
// ...
|
||||
});
|
||||
|
||||
// Mid-level: Pattern across similar cases
|
||||
await rb.insertPattern({
|
||||
type: 'pattern',
|
||||
domain: 'debugging',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding,
|
||||
pattern: { category: 'null-pointer', approach: 'defensive-checks' }
|
||||
}),
|
||||
confidence: 0.85,
|
||||
// ...
|
||||
});
|
||||
|
||||
// High-level: General principle
|
||||
await rb.insertPattern({
|
||||
type: 'principle',
|
||||
domain: 'software-engineering',
|
||||
pattern_data: JSON.stringify({
|
||||
embedding,
|
||||
pattern: { principle: 'fail-fast with clear errors' }
|
||||
}),
|
||||
confidence: 0.95,
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
### Multi-Domain Learning
|
||||
|
||||
Transfer learning across domains:
|
||||
|
||||
```typescript
|
||||
// Learn from backend optimization
|
||||
const backendExperience = await rb.retrieveWithReasoning(embedding, {
|
||||
domain: 'backend-optimization',
|
||||
k: 10,
|
||||
});
|
||||
|
||||
// Apply to frontend optimization
|
||||
const transferredKnowledge = backendExperience.memories.map(mem => ({
|
||||
...mem,
|
||||
domain: 'frontend-optimization',
|
||||
adapted: true,
|
||||
}));
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CLI Operations
|
||||
|
||||
### Database Management
|
||||
|
||||
```bash
|
||||
# Export trajectories and patterns
|
||||
npx agentdb@latest export ./.agentdb/reasoningbank.db ./backup.json
|
||||
|
||||
# Import experiences
|
||||
npx agentdb@latest import ./experiences.json
|
||||
|
||||
# Get statistics
|
||||
npx agentdb@latest stats ./.agentdb/reasoningbank.db
|
||||
# Shows: total patterns, domains, confidence distribution
|
||||
```
|
||||
|
||||
### Migration
|
||||
|
||||
```bash
|
||||
# Migrate from legacy ReasoningBank
|
||||
npx agentdb@latest migrate --source .swarm/memory.db --target .agentdb/reasoningbank.db
|
||||
|
||||
# Validate migration
|
||||
npx agentdb@latest stats .agentdb/reasoningbank.db
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Issue: Migration fails
|
||||
```bash
|
||||
# Check source database exists
|
||||
ls -la .swarm/memory.db
|
||||
|
||||
# Run with verbose logging
|
||||
DEBUG=agentdb:* npx agentdb@latest migrate --source .swarm/memory.db
|
||||
```
|
||||
|
||||
### Issue: Low confidence scores
|
||||
```typescript
|
||||
// Enable context synthesis for better quality
|
||||
const result = await rb.retrieveWithReasoning(embedding, {
|
||||
synthesizeContext: true,
|
||||
useMMR: true,
|
||||
k: 10,
|
||||
});
|
||||
```
|
||||
|
||||
### Issue: Memory growing too large
|
||||
```typescript
|
||||
// Enable automatic optimization
|
||||
const result = await rb.retrieveWithReasoning(embedding, {
|
||||
optimizeMemory: true, // Consolidates similar patterns
|
||||
});
|
||||
|
||||
// Or manually optimize
|
||||
await rb.optimize();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Learn More
|
||||
|
||||
- **AgentDB Integration**: node_modules/agentic-flow/docs/AGENTDB_INTEGRATION.md
|
||||
- **GitHub**: https://github.com/ruvnet/agentic-flow/tree/main/packages/agentdb
|
||||
- **MCP Integration**: `npx agentdb@latest mcp`
|
||||
- **Website**: https://agentdb.ruv.io
|
||||
|
||||
---
|
||||
|
||||
**Category**: Machine Learning / Reinforcement Learning
|
||||
**Difficulty**: Intermediate
|
||||
**Estimated Time**: 20-30 minutes
|
||||
@@ -0,0 +1,201 @@
|
||||
---
|
||||
name: "ReasoningBank Intelligence"
|
||||
description: "Implement adaptive learning with ReasoningBank for pattern recognition, strategy optimization, and continuous improvement. Use when building self-learning agents, optimizing workflows, or implementing meta-cognitive systems."
|
||||
---
|
||||
|
||||
# ReasoningBank Intelligence
|
||||
|
||||
## What This Skill Does
|
||||
|
||||
Implements ReasoningBank's adaptive learning system for AI agents to learn from experience, recognize patterns, and optimize strategies over time. Enables meta-cognitive capabilities and continuous improvement.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- agentic-flow v1.5.11+
|
||||
- AgentDB v1.0.4+ (for persistence)
|
||||
- Node.js 18+
|
||||
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import { ReasoningBank } from 'agentic-flow/reasoningbank';
|
||||
|
||||
// Initialize ReasoningBank
|
||||
const rb = new ReasoningBank({
|
||||
persist: true,
|
||||
learningRate: 0.1,
|
||||
adapter: 'agentdb' // Use AgentDB for storage
|
||||
});
|
||||
|
||||
// Record task outcome
|
||||
await rb.recordExperience({
|
||||
task: 'code_review',
|
||||
approach: 'static_analysis_first',
|
||||
outcome: {
|
||||
success: true,
|
||||
metrics: {
|
||||
bugs_found: 5,
|
||||
time_taken: 120,
|
||||
false_positives: 1
|
||||
}
|
||||
},
|
||||
context: {
|
||||
language: 'typescript',
|
||||
complexity: 'medium'
|
||||
}
|
||||
});
|
||||
|
||||
// Get optimal strategy
|
||||
const strategy = await rb.recommendStrategy('code_review', {
|
||||
language: 'typescript',
|
||||
complexity: 'high'
|
||||
});
|
||||
```
|
||||
|
||||
## Core Features
|
||||
|
||||
### 1. Pattern Recognition
|
||||
```typescript
|
||||
// Learn patterns from data
|
||||
await rb.learnPattern({
|
||||
pattern: 'api_errors_increase_after_deploy',
|
||||
triggers: ['deployment', 'traffic_spike'],
|
||||
actions: ['rollback', 'scale_up'],
|
||||
confidence: 0.85
|
||||
});
|
||||
|
||||
// Match patterns
|
||||
const matches = await rb.matchPatterns(currentSituation);
|
||||
```
|
||||
|
||||
### 2. Strategy Optimization
|
||||
```typescript
|
||||
// Compare strategies
|
||||
const comparison = await rb.compareStrategies('bug_fixing', [
|
||||
'tdd_approach',
|
||||
'debug_first',
|
||||
'reproduce_then_fix'
|
||||
]);
|
||||
|
||||
// Get best strategy
|
||||
const best = comparison.strategies[0];
|
||||
console.log(`Best: ${best.name} (score: ${best.score})`);
|
||||
```
|
||||
|
||||
### 3. Continuous Learning
|
||||
```typescript
|
||||
// Enable auto-learning from all tasks
|
||||
await rb.enableAutoLearning({
|
||||
threshold: 0.7, // Only learn from high-confidence outcomes
|
||||
updateFrequency: 100 // Update models every 100 experiences
|
||||
});
|
||||
```
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Meta-Learning
|
||||
```typescript
|
||||
// Learn about learning
|
||||
await rb.metaLearn({
|
||||
observation: 'parallel_execution_faster_for_independent_tasks',
|
||||
confidence: 0.95,
|
||||
applicability: {
|
||||
task_types: ['batch_processing', 'data_transformation'],
|
||||
conditions: ['tasks_independent', 'io_bound']
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Transfer Learning
|
||||
```typescript
|
||||
// Apply knowledge from one domain to another
|
||||
await rb.transferKnowledge({
|
||||
from: 'code_review_javascript',
|
||||
to: 'code_review_typescript',
|
||||
similarity: 0.8
|
||||
});
|
||||
```
|
||||
|
||||
### Adaptive Agents
|
||||
```typescript
|
||||
// Create self-improving agent
|
||||
class AdaptiveAgent {
|
||||
async execute(task: Task) {
|
||||
// Get optimal strategy
|
||||
const strategy = await rb.recommendStrategy(task.type, task.context);
|
||||
|
||||
// Execute with strategy
|
||||
const result = await this.executeWithStrategy(task, strategy);
|
||||
|
||||
// Learn from outcome
|
||||
await rb.recordExperience({
|
||||
task: task.type,
|
||||
approach: strategy.name,
|
||||
outcome: result,
|
||||
context: task.context
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Integration with AgentDB
|
||||
|
||||
```typescript
|
||||
// Persist ReasoningBank data
|
||||
await rb.configure({
|
||||
storage: {
|
||||
type: 'agentdb',
|
||||
options: {
|
||||
database: './reasoning-bank.db',
|
||||
enableVectorSearch: true
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Query learned patterns
|
||||
const patterns = await rb.query({
|
||||
category: 'optimization',
|
||||
minConfidence: 0.8,
|
||||
timeRange: { last: '30d' }
|
||||
});
|
||||
```
|
||||
|
||||
## Performance Metrics
|
||||
|
||||
```typescript
|
||||
// Track learning effectiveness
|
||||
const metrics = await rb.getMetrics();
|
||||
console.log(`
|
||||
Total Experiences: ${metrics.totalExperiences}
|
||||
Patterns Learned: ${metrics.patternsLearned}
|
||||
Strategy Success Rate: ${metrics.strategySuccessRate}
|
||||
Improvement Over Time: ${metrics.improvement}
|
||||
`);
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Record consistently**: Log all task outcomes, not just successes
|
||||
2. **Provide context**: Rich context improves pattern matching
|
||||
3. **Set thresholds**: Filter low-confidence learnings
|
||||
4. **Review periodically**: Audit learned patterns for quality
|
||||
5. **Use vector search**: Enable semantic pattern matching
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Issue: Poor recommendations
|
||||
**Solution**: Ensure sufficient training data (100+ experiences per task type)
|
||||
|
||||
### Issue: Slow pattern matching
|
||||
**Solution**: Enable vector indexing in AgentDB
|
||||
|
||||
### Issue: Memory growing large
|
||||
**Solution**: Set TTL for old experiences or enable pruning
|
||||
|
||||
## Learn More
|
||||
|
||||
- ReasoningBank Guide: agentic-flow/src/reasoningbank/README.md
|
||||
- AgentDB Integration: packages/agentdb/docs/reasoningbank.md
|
||||
- Pattern Learning: docs/reasoning/patterns.md
|
||||
@@ -0,0 +1,173 @@
|
||||
---
|
||||
name: risk-management
|
||||
description: Portfolio risk analysis using nautilus_trader and Stanley risk metrics
|
||||
triggers:
|
||||
- risk analysis
|
||||
- VaR
|
||||
- value at risk
|
||||
- portfolio risk
|
||||
- stress test
|
||||
- drawdown
|
||||
- beta
|
||||
- volatility
|
||||
---
|
||||
|
||||
# Risk Management
|
||||
|
||||
Comprehensive portfolio risk analysis using Stanley's risk_metrics module and nautilus_trader integration.
|
||||
|
||||
## Risk Metrics Available
|
||||
|
||||
### Value at Risk (VaR)
|
||||
- **Historical VaR**: Non-parametric, uses actual return distribution
|
||||
- **Parametric VaR**: Assumes normal distribution
|
||||
- **95% and 99% confidence levels**
|
||||
|
||||
### Conditional VaR (CVaR / Expected Shortfall)
|
||||
Expected loss given that loss exceeds VaR - more conservative than VaR alone.
|
||||
|
||||
### Beta & Alpha
|
||||
- **Beta**: Market sensitivity (vs SPY or custom benchmark)
|
||||
- **Alpha**: Jensen's alpha - risk-adjusted excess return
|
||||
- **R-squared**: Benchmark correlation
|
||||
|
||||
### Volatility Metrics
|
||||
- Daily and annualized volatility
|
||||
- Downside volatility (for Sortino)
|
||||
- Maximum drawdown and duration
|
||||
|
||||
### Risk-Adjusted Returns
|
||||
- **Sharpe Ratio**: Return per unit of total risk
|
||||
- **Sortino Ratio**: Return per unit of downside risk
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Basic Risk Assessment
|
||||
```python
|
||||
from stanley.portfolio.risk_metrics import (
|
||||
calculate_portfolio_var,
|
||||
calculate_beta,
|
||||
calculate_sharpe_ratio,
|
||||
calculate_volatility_metrics
|
||||
)
|
||||
|
||||
# Calculate VaR
|
||||
var_result = calculate_portfolio_var(
|
||||
returns_matrix=returns_df,
|
||||
weights=np.array([0.4, 0.3, 0.3]),
|
||||
portfolio_value=100000,
|
||||
method="historical",
|
||||
lookback_days=252
|
||||
)
|
||||
# Returns: VaRResult with var_95, var_99, cvar_95, cvar_99
|
||||
|
||||
# Calculate Beta
|
||||
beta_result = calculate_beta(
|
||||
asset_returns=portfolio_returns,
|
||||
benchmark_returns=spy_returns,
|
||||
risk_free_rate=0.05
|
||||
)
|
||||
# Returns: BetaResult with beta, alpha, r_squared
|
||||
```
|
||||
|
||||
### Stress Testing
|
||||
```python
|
||||
# Historical scenario analysis
|
||||
scenarios = [
|
||||
{"name": "2008 Crisis", "factor": -0.38},
|
||||
{"name": "COVID Crash", "factor": -0.34},
|
||||
{"name": "Tech Correction 2022", "factor": -0.25},
|
||||
]
|
||||
|
||||
for scenario in scenarios:
|
||||
stressed_value = portfolio_value * (1 + scenario["factor"])
|
||||
loss = portfolio_value - stressed_value
|
||||
print(f"{scenario['name']}: -${loss:,.0f}")
|
||||
```
|
||||
|
||||
### Nautilus Trader Integration
|
||||
```python
|
||||
from stanley.integrations.nautilus import DataClient
|
||||
from nautilus_trader.risk import RiskEngine
|
||||
|
||||
# Real-time risk monitoring with nautilus
|
||||
risk_engine = RiskEngine()
|
||||
risk_engine.set_max_position_size(symbol, max_shares)
|
||||
risk_engine.set_max_notional(symbol, max_dollars)
|
||||
risk_engine.set_max_daily_loss(max_loss)
|
||||
```
|
||||
|
||||
## Risk Limits (Configurable)
|
||||
|
||||
| Parameter | Default | Description |
|
||||
|-----------|---------|-------------|
|
||||
| Max Position Size | 10% | Maximum single position |
|
||||
| Max Sector Exposure | 30% | Maximum sector weight |
|
||||
| Max VaR 95 | 5% | Maximum daily VaR |
|
||||
| Max Drawdown | 15% | Stop-loss trigger |
|
||||
| Min Diversification | 5 | Minimum holdings |
|
||||
|
||||
## Memory Integration
|
||||
|
||||
Track risk metrics over time:
|
||||
```typescript
|
||||
await memory.store({
|
||||
namespace: "stanley/risk",
|
||||
key: `snapshot/${date}`,
|
||||
value: {
|
||||
date,
|
||||
portfolioValue: 125000,
|
||||
var95: 2500,
|
||||
var95Pct: 2.0,
|
||||
cvar95: 3200,
|
||||
beta: 1.15,
|
||||
sharpe: 1.45,
|
||||
maxDrawdown: -0.08,
|
||||
sectorConcentration: {
|
||||
Technology: 0.45,
|
||||
Healthcare: 0.20
|
||||
},
|
||||
alerts: ["Technology sector over 40% limit"]
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Alerts & Monitoring
|
||||
|
||||
Trigger alerts when:
|
||||
- VaR exceeds threshold
|
||||
- Drawdown exceeds limit
|
||||
- Sector concentration too high
|
||||
- Correlation spike detected
|
||||
- Volatility regime change
|
||||
|
||||
## Output Format
|
||||
|
||||
### Risk Dashboard
|
||||
```
|
||||
## Portfolio Risk Summary
|
||||
|
||||
**Value at Risk (1-day)**
|
||||
- VaR 95%: $2,450 (1.96%)
|
||||
- VaR 99%: $3,890 (3.11%)
|
||||
- CVaR 95%: $3,120 (2.50%)
|
||||
|
||||
**Market Sensitivity**
|
||||
- Beta: 1.15
|
||||
- Alpha: 2.3% (annualized)
|
||||
- R²: 0.87
|
||||
|
||||
**Risk-Adjusted Returns**
|
||||
- Sharpe: 1.45
|
||||
- Sortino: 1.92
|
||||
|
||||
**Stress Scenarios**
|
||||
- 2008 Crisis: -$47,500
|
||||
- COVID Crash: -$42,500
|
||||
- 10% Correction: -$12,500
|
||||
|
||||
**Alerts**
|
||||
⚠️ Technology exposure at 45% (limit: 40%)
|
||||
✓ VaR within limits
|
||||
✓ Drawdown acceptable
|
||||
```
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
name: sag
|
||||
description: ElevenLabs text-to-speech with mac-style say UX.
|
||||
homepage: https://sag.sh
|
||||
metadata: {"zee":{"emoji":"🗣️","requires":{"bins":["sag"],"env":["ELEVENLABS_API_KEY"]},"primaryEnv":"ELEVENLABS_API_KEY","install":[{"id":"brew","kind":"brew","formula":"steipete/tap/sag","bins":["sag"],"label":"Install sag (brew)"}]}}
|
||||
---
|
||||
|
||||
# sag
|
||||
|
||||
Use `sag` for ElevenLabs TTS with local playback.
|
||||
|
||||
API key (required)
|
||||
- `ELEVENLABS_API_KEY` (preferred)
|
||||
- `SAG_API_KEY` also supported by the CLI
|
||||
|
||||
Quick start
|
||||
- `sag "Hello there"`
|
||||
- `sag speak -v "Roger" "Hello"`
|
||||
- `sag voices`
|
||||
- `sag prompting` (model-specific tips)
|
||||
|
||||
Model notes
|
||||
- Default: `eleven_v3` (expressive)
|
||||
- Stable: `eleven_multilingual_v2`
|
||||
- Fast: `eleven_flash_v2_5`
|
||||
|
||||
Pronunciation + delivery rules
|
||||
- First fix: respell (e.g. "key-note"), add hyphens, adjust casing.
|
||||
- Numbers/units/URLs: `--normalize auto` (or `off` if it harms names).
|
||||
- Language bias: `--lang en|de|fr|...` to guide normalization.
|
||||
- v3: SSML `<break>` not supported; use `[pause]`, `[short pause]`, `[long pause]`.
|
||||
- v2/v2.5: SSML `<break time="1.5s" />` supported; `<phoneme>` not exposed in `sag`.
|
||||
|
||||
v3 audio tags (put at the entrance of a line)
|
||||
- `[whispers]`, `[shouts]`, `[sings]`
|
||||
- `[laughs]`, `[starts laughing]`, `[sighs]`, `[exhales]`
|
||||
- `[sarcastic]`, `[curious]`, `[excited]`, `[crying]`, `[mischievously]`
|
||||
- Example: `sag "[whispers] keep this quiet. [short pause] ok?"`
|
||||
|
||||
Voice defaults
|
||||
- `ELEVENLABS_VOICE_ID` or `SAG_VOICE_ID`
|
||||
|
||||
Confirm voice + speaker before long output.
|
||||
|
||||
## Chat voice responses
|
||||
|
||||
When Peter asks for a "voice" reply (e.g., "crazy scientist voice", "explain in voice"), generate audio and send it:
|
||||
|
||||
```bash
|
||||
# Generate audio file
|
||||
sag -v Clawd -o /tmp/voice-reply.mp3 "Your message here"
|
||||
|
||||
# Then include in reply:
|
||||
# MEDIA:/tmp/voice-reply.mp3
|
||||
```
|
||||
|
||||
Voice character tips:
|
||||
- Crazy scientist: Use `[excited]` tags, dramatic pauses `[short pause]`, vary intensity
|
||||
- Calm: Use `[whispers]` or slower pacing
|
||||
- Dramatic: Use `[sings]` or `[shouts]` sparingly
|
||||
|
||||
Default voice for Clawd: `lj2rcrvANS3gaWWnczSX` (or just `-v Clawd`)
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
name: session-logs
|
||||
description: Search and analyze your own conversation history from session log files using jq.
|
||||
metadata: {"zee":{"emoji":"📜","requires":{"bins":["jq"]}}}
|
||||
---
|
||||
|
||||
# session-logs
|
||||
|
||||
Search your complete conversation history stored in session JSONL files. Use this when you need to recall something not in your memory files.
|
||||
|
||||
## Location
|
||||
|
||||
Session logs live at: `~/.zee/agents/main/sessions/`
|
||||
|
||||
- **`sessions.json`** - Index mapping session keys to session IDs
|
||||
- **`<session-id>.jsonl`** - Full conversation transcript per session
|
||||
|
||||
## Structure
|
||||
|
||||
Each `.jsonl` file contains messages with:
|
||||
- `type`: "session" (metadata) or "message"
|
||||
- `timestamp`: ISO timestamp
|
||||
- `message.role`: "user", "assistant", or "toolResult"
|
||||
- `message.content[]`: Text, thinking, or tool calls
|
||||
- `message.usage.cost.total`: Cost per response
|
||||
|
||||
## Common Queries
|
||||
|
||||
### List all sessions by date and size
|
||||
```bash
|
||||
for f in ~/.zee/agents/main/sessions/*.jsonl; do
|
||||
date=$(head -1 "$f" | jq -r '.timestamp' | cut -dT -f1)
|
||||
size=$(ls -lh "$f" | awk '{print $5}')
|
||||
echo "$date $size $(basename $f)"
|
||||
done | sort -r
|
||||
```
|
||||
|
||||
### Find sessions from a specific day
|
||||
```bash
|
||||
for f in ~/.zee/agents/main/sessions/*.jsonl; do
|
||||
head -1 "$f" | jq -r '.timestamp' | grep -q "2026-01-06" && echo "$f"
|
||||
done
|
||||
```
|
||||
|
||||
### Extract user messages from a session
|
||||
```bash
|
||||
jq -r 'select(.message.role == "user") | .message.content[0].text' <session>.jsonl
|
||||
```
|
||||
|
||||
### Search for keyword in assistant responses
|
||||
```bash
|
||||
jq -r 'select(.message.role == "assistant") | .message.content[]? | select(.type == "text") | .text' <session>.jsonl | grep -i "keyword"
|
||||
```
|
||||
|
||||
### Get total cost for a session
|
||||
```bash
|
||||
jq -s '[.[] | .message.usage.cost.total // 0] | add' <session>.jsonl
|
||||
```
|
||||
|
||||
### Daily cost summary
|
||||
```bash
|
||||
for f in ~/.zee/agents/main/sessions/*.jsonl; do
|
||||
date=$(head -1 "$f" | jq -r '.timestamp' | cut -dT -f1)
|
||||
cost=$(jq -s '[.[] | .message.usage.cost.total // 0] | add' "$f")
|
||||
echo "$date $cost"
|
||||
done | awk '{a[$1]+=$2} END {for(d in a) print d, "$"a[d]}' | sort -r
|
||||
```
|
||||
|
||||
### Count messages and tokens in a session
|
||||
```bash
|
||||
jq -s '{
|
||||
messages: length,
|
||||
user: [.[] | select(.message.role == "user")] | length,
|
||||
assistant: [.[] | select(.message.role == "assistant")] | length,
|
||||
first: .[0].timestamp,
|
||||
last: .[-1].timestamp
|
||||
}' <session>.jsonl
|
||||
```
|
||||
|
||||
### Tool usage breakdown
|
||||
```bash
|
||||
jq -r '.message.content[]? | select(.type == "toolCall") | .name' <session>.jsonl | sort | uniq -c | sort -rn
|
||||
```
|
||||
|
||||
### Search across ALL sessions for a phrase
|
||||
```bash
|
||||
grep -l "phrase" ~/.zee/agents/main/sessions/*.jsonl
|
||||
```
|
||||
|
||||
## Tips
|
||||
|
||||
- Sessions are append-only JSONL (one JSON object per line)
|
||||
- Large sessions can be several MB - use `head`/`tail` for sampling
|
||||
- The `sessions.json` index maps chat providers (discord, whatsapp, etc.) to session IDs
|
||||
- Deleted sessions have `.deleted.<timestamp>` suffix
|
||||
@@ -57,7 +57,7 @@ npx tsx scripts/shared-plan.ts read 2026-01-07-10-00-00-project_alpha.md
|
||||
|
||||
## Environment
|
||||
|
||||
- `ZEE_REPO` (default: `~/Repositories/personas/zee`)
|
||||
- `ZEE_REPO` (default: `~/.local/src/agent-core/vendor/personas/zee`)
|
||||
- `ZEE_RUNTIME` (default: `bun`)
|
||||
|
||||
Telegram (user mode):
|
||||
|
||||
@@ -10,7 +10,7 @@ export type ZeeCliResult = {
|
||||
};
|
||||
|
||||
export function runZeeCli(args: string[]): ZeeCliResult {
|
||||
const repo = process.env.ZEE_REPO || join(homedir(), "Repositories", "personas", "zee");
|
||||
const repo = process.env.ZEE_REPO || join(homedir(), ".local", "src", "agent-core", "vendor", "personas", "zee");
|
||||
const runtime = process.env.ZEE_RUNTIME || "bun";
|
||||
const entry = join(repo, "src", "entry.ts");
|
||||
|
||||
|
||||
@@ -0,0 +1,910 @@
|
||||
---
|
||||
name: "Skill Builder"
|
||||
description: "Create new Claude Code Skills with proper YAML frontmatter, progressive disclosure structure, and complete directory organization. Use when you need to build custom skills for specific workflows, generate skill templates, or understand the Claude Skills specification."
|
||||
---
|
||||
|
||||
# Skill Builder
|
||||
|
||||
## What This Skill Does
|
||||
|
||||
Creates production-ready Claude Code Skills with proper YAML frontmatter, progressive disclosure architecture, and complete file/folder structure. This skill guides you through building skills that Claude can autonomously discover and use across all surfaces (Claude.ai, Claude Code, SDK, API).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Claude Code 2.0+ or Claude.ai with Skills support
|
||||
- Basic understanding of Markdown and YAML
|
||||
- Text editor or IDE
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Creating Your First Skill
|
||||
|
||||
```bash
|
||||
# 1. Create skill directory (MUST be at top level, NOT in subdirectories!)
|
||||
mkdir -p ~/.claude/skills/my-first-skill
|
||||
|
||||
# 2. Create SKILL.md with proper format
|
||||
cat > ~/.claude/skills/my-first-skill/SKILL.md << 'EOF'
|
||||
---
|
||||
name: "My First Skill"
|
||||
description: "Brief description of what this skill does and when Claude should use it. Maximum 1024 characters."
|
||||
---
|
||||
|
||||
# My First Skill
|
||||
|
||||
## What This Skill Does
|
||||
[Your instructions here]
|
||||
|
||||
## Quick Start
|
||||
[Basic usage]
|
||||
EOF
|
||||
|
||||
# 3. Verify skill is detected
|
||||
# Restart Claude Code or refresh Claude.ai
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Complete Specification
|
||||
|
||||
### 📋 YAML Frontmatter (REQUIRED)
|
||||
|
||||
Every SKILL.md **must** start with YAML frontmatter containing exactly two required fields:
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: "Skill Name" # REQUIRED: Max 64 chars
|
||||
description: "What this skill does # REQUIRED: Max 1024 chars
|
||||
and when Claude should use it." # Include BOTH what & when
|
||||
---
|
||||
```
|
||||
|
||||
#### Field Requirements
|
||||
|
||||
**`name`** (REQUIRED):
|
||||
- **Type**: String
|
||||
- **Max Length**: 64 characters
|
||||
- **Format**: Human-friendly display name
|
||||
- **Usage**: Shown in skill lists, UI, and loaded into Claude's system prompt
|
||||
- **Best Practice**: Use Title Case, be concise and descriptive
|
||||
- **Examples**:
|
||||
- ✅ "API Documentation Generator"
|
||||
- ✅ "React Component Builder"
|
||||
- ✅ "Database Schema Designer"
|
||||
- ❌ "skill-1" (not descriptive)
|
||||
- ❌ "This is a very long skill name that exceeds sixty-four characters" (too long)
|
||||
|
||||
**`description`** (REQUIRED):
|
||||
- **Type**: String
|
||||
- **Max Length**: 1024 characters
|
||||
- **Format**: Plain text or minimal markdown
|
||||
- **Content**: MUST include:
|
||||
1. **What** the skill does (functionality)
|
||||
2. **When** Claude should invoke it (trigger conditions)
|
||||
- **Usage**: Loaded into Claude's system prompt for autonomous matching
|
||||
- **Best Practice**: Front-load key trigger words, be specific about use cases
|
||||
- **Examples**:
|
||||
- ✅ "Generate OpenAPI 3.0 documentation from Express.js routes. Use when creating API docs, documenting endpoints, or building API specifications."
|
||||
- ✅ "Create React functional components with TypeScript, hooks, and tests. Use when scaffolding new components or converting class components."
|
||||
- ❌ "A comprehensive guide to API documentation" (no "when" clause)
|
||||
- ❌ "Documentation tool" (too vague)
|
||||
|
||||
#### YAML Formatting Rules
|
||||
|
||||
```yaml
|
||||
---
|
||||
# ✅ CORRECT: Simple string
|
||||
name: "API Builder"
|
||||
description: "Creates REST APIs with Express and TypeScript."
|
||||
|
||||
# ✅ CORRECT: Multi-line description
|
||||
name: "Full-Stack Generator"
|
||||
description: "Generates full-stack applications with React frontend and Node.js backend. Use when starting new projects or scaffolding applications."
|
||||
|
||||
# ✅ CORRECT: Special characters quoted
|
||||
name: "JSON:API Builder"
|
||||
description: "Creates JSON:API compliant endpoints: pagination, filtering, relationships."
|
||||
|
||||
# ❌ WRONG: Missing quotes with special chars
|
||||
name: API:Builder # YAML parse error!
|
||||
|
||||
# ❌ WRONG: Extra fields (ignored but discouraged)
|
||||
name: "My Skill"
|
||||
description: "My description"
|
||||
version: "1.0.0" # NOT part of spec
|
||||
author: "Me" # NOT part of spec
|
||||
tags: ["dev", "api"] # NOT part of spec
|
||||
---
|
||||
```
|
||||
|
||||
**Critical**: Only `name` and `description` are used by Claude. Additional fields are ignored.
|
||||
|
||||
---
|
||||
|
||||
### 📂 Directory Structure
|
||||
|
||||
#### Minimal Skill (Required)
|
||||
```
|
||||
~/.claude/skills/ # Personal skills location
|
||||
└── my-skill/ # Skill directory (MUST be at top level!)
|
||||
└── SKILL.md # REQUIRED: Main skill file
|
||||
```
|
||||
|
||||
**IMPORTANT**: Skills MUST be directly under `~/.claude/skills/[skill-name]/`.
|
||||
Claude Code does NOT support nested subdirectories or namespaces!
|
||||
|
||||
#### Full-Featured Skill (Recommended)
|
||||
```
|
||||
~/.claude/skills/
|
||||
└── my-skill/ # Top-level skill directory
|
||||
├── SKILL.md # REQUIRED: Main skill file
|
||||
├── README.md # Optional: Human-readable docs
|
||||
├── scripts/ # Optional: Executable scripts
|
||||
│ ├── setup.sh
|
||||
│ ├── validate.js
|
||||
│ └── deploy.py
|
||||
├── resources/ # Optional: Supporting files
|
||||
│ ├── templates/
|
||||
│ │ ├── api-template.js
|
||||
│ │ └── component.tsx
|
||||
│ ├── examples/
|
||||
│ │ └── sample-output.json
|
||||
│ └── schemas/
|
||||
│ └── config-schema.json
|
||||
└── docs/ # Optional: Additional documentation
|
||||
├── ADVANCED.md
|
||||
├── TROUBLESHOOTING.md
|
||||
└── API_REFERENCE.md
|
||||
```
|
||||
|
||||
#### Skills Locations
|
||||
|
||||
**Personal Skills** (available across all projects):
|
||||
```
|
||||
~/.claude/skills/
|
||||
└── [your-skills]/
|
||||
```
|
||||
- **Path**: `~/.claude/skills/` or `$HOME/.claude/skills/`
|
||||
- **Scope**: Available in all projects for this user
|
||||
- **Version Control**: NOT committed to git (outside repo)
|
||||
- **Use Case**: Personal productivity tools, custom workflows
|
||||
|
||||
**Project Skills** (team-shared, version controlled):
|
||||
```
|
||||
<project-root>/.claude/skills/
|
||||
└── [team-skills]/
|
||||
```
|
||||
- **Path**: `.claude/skills/` in project root
|
||||
- **Scope**: Available only in this project
|
||||
- **Version Control**: SHOULD be committed to git
|
||||
- **Use Case**: Team workflows, project-specific tools, shared knowledge
|
||||
|
||||
---
|
||||
|
||||
### 🎯 Progressive Disclosure Architecture
|
||||
|
||||
Claude Code uses a **3-level progressive disclosure system** to scale to 100+ skills without context penalty:
|
||||
|
||||
#### Level 1: Metadata (Name + Description)
|
||||
**Loaded**: At Claude Code startup, always
|
||||
**Size**: ~200 chars per skill
|
||||
**Purpose**: Enable autonomous skill matching
|
||||
**Context**: Loaded into system prompt for ALL skills
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: "API Builder" # 11 chars
|
||||
description: "Creates REST APIs..." # ~50 chars
|
||||
---
|
||||
# Total: ~61 chars per skill
|
||||
# 100 skills = ~6KB context (minimal!)
|
||||
```
|
||||
|
||||
#### Level 2: SKILL.md Body
|
||||
**Loaded**: When skill is triggered/matched
|
||||
**Size**: ~1-10KB typically
|
||||
**Purpose**: Main instructions and procedures
|
||||
**Context**: Only loaded for ACTIVE skills
|
||||
|
||||
```markdown
|
||||
# API Builder
|
||||
|
||||
## What This Skill Does
|
||||
[Main instructions - loaded only when skill is active]
|
||||
|
||||
## Quick Start
|
||||
[Basic procedures]
|
||||
|
||||
## Step-by-Step Guide
|
||||
[Detailed instructions]
|
||||
```
|
||||
|
||||
#### Level 3+: Referenced Files
|
||||
**Loaded**: On-demand as Claude navigates
|
||||
**Size**: Variable (KB to MB)
|
||||
**Purpose**: Deep reference, examples, schemas
|
||||
**Context**: Loaded only when Claude accesses specific files
|
||||
|
||||
```markdown
|
||||
# In SKILL.md
|
||||
See [Advanced Configuration](docs/ADVANCED.md) for complex scenarios.
|
||||
See [API Reference](docs/API_REFERENCE.md) for complete documentation.
|
||||
Use template: `resources/templates/api-template.js`
|
||||
|
||||
# Claude will load these files ONLY if needed
|
||||
```
|
||||
|
||||
**Benefit**: Install 100+ skills with ~6KB context. Only active skill content (1-10KB) enters context.
|
||||
|
||||
---
|
||||
|
||||
### 📝 SKILL.md Content Structure
|
||||
|
||||
#### Recommended 4-Level Structure
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: "Your Skill Name"
|
||||
description: "What it does and when to use it"
|
||||
---
|
||||
|
||||
# Your Skill Name
|
||||
|
||||
## Level 1: Overview (Always Read First)
|
||||
Brief 2-3 sentence description of the skill.
|
||||
|
||||
## Prerequisites
|
||||
- Requirement 1
|
||||
- Requirement 2
|
||||
|
||||
## What This Skill Does
|
||||
1. Primary function
|
||||
2. Secondary function
|
||||
3. Key benefit
|
||||
|
||||
---
|
||||
|
||||
## Level 2: Quick Start (For Fast Onboarding)
|
||||
|
||||
### Basic Usage
|
||||
```bash
|
||||
# Simplest use case
|
||||
command --option value
|
||||
```
|
||||
|
||||
### Common Scenarios
|
||||
1. **Scenario 1**: How to...
|
||||
2. **Scenario 2**: How to...
|
||||
|
||||
---
|
||||
|
||||
## Level 3: Detailed Instructions (For Deep Work)
|
||||
|
||||
### Step-by-Step Guide
|
||||
|
||||
#### Step 1: Initial Setup
|
||||
```bash
|
||||
# Commands
|
||||
```
|
||||
Expected output:
|
||||
```
|
||||
Success message
|
||||
```
|
||||
|
||||
#### Step 2: Configuration
|
||||
- Configuration option 1
|
||||
- Configuration option 2
|
||||
|
||||
#### Step 3: Execution
|
||||
- Run the main command
|
||||
- Verify results
|
||||
|
||||
### Advanced Options
|
||||
|
||||
#### Option 1: Custom Configuration
|
||||
```bash
|
||||
# Advanced usage
|
||||
```
|
||||
|
||||
#### Option 2: Integration
|
||||
```bash
|
||||
# Integration steps
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Level 4: Reference (Rarely Needed)
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
#### Issue: Common Problem
|
||||
**Symptoms**: What you see
|
||||
**Cause**: Why it happens
|
||||
**Solution**: How to fix
|
||||
```bash
|
||||
# Fix command
|
||||
```
|
||||
|
||||
#### Issue: Another Problem
|
||||
**Solution**: Steps to resolve
|
||||
|
||||
### Complete API Reference
|
||||
See [API_REFERENCE.md](docs/API_REFERENCE.md)
|
||||
|
||||
### Examples
|
||||
See [examples/](resources/examples/)
|
||||
|
||||
### Related Skills
|
||||
- [Related Skill 1](#)
|
||||
- [Related Skill 2](#)
|
||||
|
||||
### Resources
|
||||
- [External Link 1](https://example.com)
|
||||
- [Documentation](https://docs.example.com)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🎨 Content Best Practices
|
||||
|
||||
#### Writing Effective Descriptions
|
||||
|
||||
**Front-Load Keywords**:
|
||||
```yaml
|
||||
# ✅ GOOD: Keywords first
|
||||
description: "Generate TypeScript interfaces from JSON schema. Use when converting schemas, creating types, or building API clients."
|
||||
|
||||
# ❌ BAD: Keywords buried
|
||||
description: "This skill helps developers who need to work with JSON schemas by providing a way to generate TypeScript interfaces."
|
||||
```
|
||||
|
||||
**Include Trigger Conditions**:
|
||||
```yaml
|
||||
# ✅ GOOD: Clear "when" clause
|
||||
description: "Debug React performance issues using Chrome DevTools. Use when components re-render unnecessarily, investigating slow updates, or optimizing bundle size."
|
||||
|
||||
# ❌ BAD: No trigger conditions
|
||||
description: "Helps with React performance debugging."
|
||||
```
|
||||
|
||||
**Be Specific**:
|
||||
```yaml
|
||||
# ✅ GOOD: Specific technologies
|
||||
description: "Create Express.js REST endpoints with Joi validation, Swagger docs, and Jest tests. Use when building new APIs or adding endpoints."
|
||||
|
||||
# ❌ BAD: Too generic
|
||||
description: "Build API endpoints with proper validation and testing."
|
||||
```
|
||||
|
||||
#### Progressive Disclosure Writing
|
||||
|
||||
**Keep Level 1 Brief** (Overview):
|
||||
```markdown
|
||||
## What This Skill Does
|
||||
Creates production-ready React components with TypeScript, hooks, and tests in 3 steps.
|
||||
```
|
||||
|
||||
**Level 2 for Common Paths** (Quick Start):
|
||||
```markdown
|
||||
## Quick Start
|
||||
```bash
|
||||
# Most common use case (80% of users)
|
||||
generate-component MyComponent
|
||||
```
|
||||
```
|
||||
|
||||
**Level 3 for Details** (Step-by-Step):
|
||||
```markdown
|
||||
## Step-by-Step Guide
|
||||
|
||||
### Creating a Basic Component
|
||||
1. Run generator
|
||||
2. Choose template
|
||||
3. Customize options
|
||||
[Detailed explanations]
|
||||
```
|
||||
|
||||
**Level 4 for Edge Cases** (Reference):
|
||||
```markdown
|
||||
## Advanced Configuration
|
||||
For complex scenarios like HOCs, render props, or custom hooks, see [ADVANCED.md](docs/ADVANCED.md).
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🛠️ Adding Scripts and Resources
|
||||
|
||||
#### Scripts Directory
|
||||
|
||||
**Purpose**: Executable scripts that Claude can run
|
||||
**Location**: `scripts/` in skill directory
|
||||
**Usage**: Referenced from SKILL.md
|
||||
|
||||
Example:
|
||||
```bash
|
||||
# In skill directory
|
||||
scripts/
|
||||
├── setup.sh # Initialization script
|
||||
├── validate.js # Validation logic
|
||||
├── generate.py # Code generation
|
||||
└── deploy.sh # Deployment script
|
||||
```
|
||||
|
||||
Reference from SKILL.md:
|
||||
```markdown
|
||||
## Setup
|
||||
Run the setup script:
|
||||
```bash
|
||||
./scripts/setup.sh
|
||||
```
|
||||
|
||||
## Validation
|
||||
Validate your configuration:
|
||||
```bash
|
||||
node scripts/validate.js config.json
|
||||
```
|
||||
```
|
||||
|
||||
#### Resources Directory
|
||||
|
||||
**Purpose**: Templates, examples, schemas, static files
|
||||
**Location**: `resources/` in skill directory
|
||||
**Usage**: Referenced or copied by scripts
|
||||
|
||||
Example:
|
||||
```bash
|
||||
resources/
|
||||
├── templates/
|
||||
│ ├── component.tsx.template
|
||||
│ ├── test.spec.ts.template
|
||||
│ └── story.stories.tsx.template
|
||||
├── examples/
|
||||
│ ├── basic-example/
|
||||
│ ├── advanced-example/
|
||||
│ └── integration-example/
|
||||
└── schemas/
|
||||
├── config.schema.json
|
||||
└── output.schema.json
|
||||
```
|
||||
|
||||
Reference from SKILL.md:
|
||||
```markdown
|
||||
## Templates
|
||||
Use the component template:
|
||||
```bash
|
||||
cp resources/templates/component.tsx.template src/components/MyComponent.tsx
|
||||
```
|
||||
|
||||
## Examples
|
||||
See working examples in `resources/examples/`:
|
||||
- `basic-example/` - Simple component
|
||||
- `advanced-example/` - With hooks and context
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🔗 File References and Navigation
|
||||
|
||||
Claude can navigate to referenced files automatically. Use these patterns:
|
||||
|
||||
#### Markdown Links
|
||||
```markdown
|
||||
See [Advanced Configuration](docs/ADVANCED.md) for complex scenarios.
|
||||
See [Troubleshooting Guide](docs/TROUBLESHOOTING.md) if you encounter errors.
|
||||
```
|
||||
|
||||
#### Relative File Paths
|
||||
```markdown
|
||||
Use the template located at `resources/templates/api-template.js`
|
||||
See examples in `resources/examples/basic-usage/`
|
||||
```
|
||||
|
||||
#### Inline File Content
|
||||
```markdown
|
||||
## Example Configuration
|
||||
See `resources/examples/config.json`:
|
||||
```json
|
||||
{
|
||||
"option": "value"
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
**Best Practice**: Keep SKILL.md lean (~2-5KB). Move lengthy content to separate files and reference them. Claude will load only what's needed.
|
||||
|
||||
---
|
||||
|
||||
### ✅ Validation Checklist
|
||||
|
||||
Before publishing a skill, verify:
|
||||
|
||||
**YAML Frontmatter**:
|
||||
- [ ] Starts with `---`
|
||||
- [ ] Contains `name` field (max 64 chars)
|
||||
- [ ] Contains `description` field (max 1024 chars)
|
||||
- [ ] Description includes "what" and "when"
|
||||
- [ ] Ends with `---`
|
||||
- [ ] No YAML syntax errors
|
||||
|
||||
**File Structure**:
|
||||
- [ ] SKILL.md exists in skill directory
|
||||
- [ ] Directory is DIRECTLY in `~/.claude/skills/[skill-name]/` or `.claude/skills/[skill-name]/`
|
||||
- [ ] Uses clear, descriptive directory name
|
||||
- [ ] **NO nested subdirectories** (Claude Code requires top-level structure)
|
||||
|
||||
**Content Quality**:
|
||||
- [ ] Level 1 (Overview) is brief and clear
|
||||
- [ ] Level 2 (Quick Start) shows common use case
|
||||
- [ ] Level 3 (Details) provides step-by-step guide
|
||||
- [ ] Level 4 (Reference) links to advanced content
|
||||
- [ ] Examples are concrete and runnable
|
||||
- [ ] Troubleshooting section addresses common issues
|
||||
|
||||
**Progressive Disclosure**:
|
||||
- [ ] Core instructions in SKILL.md (~2-5KB)
|
||||
- [ ] Advanced content in separate docs/
|
||||
- [ ] Large resources in resources/ directory
|
||||
- [ ] Clear navigation between levels
|
||||
|
||||
**Testing**:
|
||||
- [ ] Skill appears in Claude's skill list
|
||||
- [ ] Description triggers on relevant queries
|
||||
- [ ] Instructions are clear and actionable
|
||||
- [ ] Scripts execute successfully (if included)
|
||||
- [ ] Examples work as documented
|
||||
|
||||
---
|
||||
|
||||
## Skill Builder Templates
|
||||
|
||||
### Template 1: Basic Skill (Minimal)
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: "My Basic Skill"
|
||||
description: "One sentence what. One sentence when to use."
|
||||
---
|
||||
|
||||
# My Basic Skill
|
||||
|
||||
## What This Skill Does
|
||||
[2-3 sentences describing functionality]
|
||||
|
||||
## Quick Start
|
||||
```bash
|
||||
# Single command to get started
|
||||
```
|
||||
|
||||
## Step-by-Step Guide
|
||||
|
||||
### Step 1: Setup
|
||||
[Instructions]
|
||||
|
||||
### Step 2: Usage
|
||||
[Instructions]
|
||||
|
||||
### Step 3: Verify
|
||||
[Instructions]
|
||||
|
||||
## Troubleshooting
|
||||
- **Issue**: Problem description
|
||||
- **Solution**: Fix description
|
||||
```
|
||||
|
||||
### Template 2: Intermediate Skill (With Scripts)
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: "My Intermediate Skill"
|
||||
description: "Detailed what with key features. When to use with specific triggers: scaffolding, generating, building."
|
||||
---
|
||||
|
||||
# My Intermediate Skill
|
||||
|
||||
## Prerequisites
|
||||
- Requirement 1
|
||||
- Requirement 2
|
||||
|
||||
## What This Skill Does
|
||||
1. Primary function
|
||||
2. Secondary function
|
||||
3. Integration capability
|
||||
|
||||
## Quick Start
|
||||
```bash
|
||||
./scripts/setup.sh
|
||||
./scripts/generate.sh my-project
|
||||
```
|
||||
|
||||
## Configuration
|
||||
Edit `config.json`:
|
||||
```json
|
||||
{
|
||||
"option1": "value1",
|
||||
"option2": "value2"
|
||||
}
|
||||
```
|
||||
|
||||
## Step-by-Step Guide
|
||||
|
||||
### Basic Usage
|
||||
[Steps for 80% use case]
|
||||
|
||||
### Advanced Usage
|
||||
[Steps for complex scenarios]
|
||||
|
||||
## Available Scripts
|
||||
- `scripts/setup.sh` - Initial setup
|
||||
- `scripts/generate.sh` - Code generation
|
||||
- `scripts/validate.sh` - Validation
|
||||
|
||||
## Resources
|
||||
- Templates: `resources/templates/`
|
||||
- Examples: `resources/examples/`
|
||||
|
||||
## Troubleshooting
|
||||
[Common issues and solutions]
|
||||
```
|
||||
|
||||
### Template 3: Advanced Skill (Full-Featured)
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: "My Advanced Skill"
|
||||
description: "Comprehensive what with all features and integrations. Use when [trigger 1], [trigger 2], or [trigger 3]. Supports [technology stack]."
|
||||
---
|
||||
|
||||
# My Advanced Skill
|
||||
|
||||
## Overview
|
||||
[Brief 2-3 sentence description]
|
||||
|
||||
## Prerequisites
|
||||
- Technology 1 (version X+)
|
||||
- Technology 2 (version Y+)
|
||||
- API keys or credentials
|
||||
|
||||
## What This Skill Does
|
||||
1. **Core Feature**: Description
|
||||
2. **Integration**: Description
|
||||
3. **Automation**: Description
|
||||
|
||||
---
|
||||
|
||||
## Quick Start (60 seconds)
|
||||
|
||||
### Installation
|
||||
```bash
|
||||
./scripts/install.sh
|
||||
```
|
||||
|
||||
### First Use
|
||||
```bash
|
||||
./scripts/quickstart.sh
|
||||
```
|
||||
|
||||
Expected output:
|
||||
```
|
||||
✓ Setup complete
|
||||
✓ Configuration validated
|
||||
→ Ready to use
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Basic Configuration
|
||||
Edit `config.json`:
|
||||
```json
|
||||
{
|
||||
"mode": "production",
|
||||
"features": ["feature1", "feature2"]
|
||||
}
|
||||
```
|
||||
|
||||
### Advanced Configuration
|
||||
See [Configuration Guide](docs/CONFIGURATION.md)
|
||||
|
||||
---
|
||||
|
||||
## Step-by-Step Guide
|
||||
|
||||
### 1. Initial Setup
|
||||
[Detailed steps]
|
||||
|
||||
### 2. Core Workflow
|
||||
[Main procedures]
|
||||
|
||||
### 3. Integration
|
||||
[Integration steps]
|
||||
|
||||
---
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Feature 1: Custom Templates
|
||||
```bash
|
||||
./scripts/generate.sh --template custom
|
||||
```
|
||||
|
||||
### Feature 2: Batch Processing
|
||||
```bash
|
||||
./scripts/batch.sh --input data.json
|
||||
```
|
||||
|
||||
### Feature 3: CI/CD Integration
|
||||
See [CI/CD Guide](docs/CICD.md)
|
||||
|
||||
---
|
||||
|
||||
## Scripts Reference
|
||||
|
||||
| Script | Purpose | Usage |
|
||||
|--------|---------|-------|
|
||||
| `install.sh` | Install dependencies | `./scripts/install.sh` |
|
||||
| `generate.sh` | Generate code | `./scripts/generate.sh [name]` |
|
||||
| `validate.sh` | Validate output | `./scripts/validate.sh` |
|
||||
| `deploy.sh` | Deploy to environment | `./scripts/deploy.sh [env]` |
|
||||
|
||||
---
|
||||
|
||||
## Resources
|
||||
|
||||
### Templates
|
||||
- `resources/templates/basic.template` - Basic template
|
||||
- `resources/templates/advanced.template` - Advanced template
|
||||
|
||||
### Examples
|
||||
- `resources/examples/basic/` - Simple example
|
||||
- `resources/examples/advanced/` - Complex example
|
||||
- `resources/examples/integration/` - Integration example
|
||||
|
||||
### Schemas
|
||||
- `resources/schemas/config.schema.json` - Configuration schema
|
||||
- `resources/schemas/output.schema.json` - Output validation
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Issue: Installation Failed
|
||||
**Symptoms**: Error during `install.sh`
|
||||
**Cause**: Missing dependencies
|
||||
**Solution**:
|
||||
```bash
|
||||
# Install prerequisites
|
||||
npm install -g required-package
|
||||
./scripts/install.sh --force
|
||||
```
|
||||
|
||||
### Issue: Validation Errors
|
||||
**Symptoms**: Validation script fails
|
||||
**Solution**: See [Troubleshooting Guide](docs/TROUBLESHOOTING.md)
|
||||
|
||||
---
|
||||
|
||||
## API Reference
|
||||
Complete API documentation: [API_REFERENCE.md](docs/API_REFERENCE.md)
|
||||
|
||||
## Related Skills
|
||||
- [Related Skill 1](../related-skill-1/)
|
||||
- [Related Skill 2](../related-skill-2/)
|
||||
|
||||
## Resources
|
||||
- [Official Documentation](https://example.com/docs)
|
||||
- [GitHub Repository](https://github.com/example/repo)
|
||||
- [Community Forum](https://forum.example.com)
|
||||
|
||||
---
|
||||
|
||||
**Created**: 2025-10-19
|
||||
**Category**: Advanced
|
||||
**Difficulty**: Intermediate
|
||||
**Estimated Time**: 15-30 minutes
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Examples from the Wild
|
||||
|
||||
### Example 1: Simple Documentation Skill
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: "README Generator"
|
||||
description: "Generate comprehensive README.md files for GitHub repositories. Use when starting new projects, documenting code, or improving existing READMEs."
|
||||
---
|
||||
|
||||
# README Generator
|
||||
|
||||
## What This Skill Does
|
||||
Creates well-structured README.md files with badges, installation, usage, and contribution sections.
|
||||
|
||||
## Quick Start
|
||||
```bash
|
||||
# Answer a few questions
|
||||
./scripts/generate-readme.sh
|
||||
|
||||
# README.md created with:
|
||||
# - Project title and description
|
||||
# - Installation instructions
|
||||
# - Usage examples
|
||||
# - Contribution guidelines
|
||||
```
|
||||
|
||||
## Customization
|
||||
Edit sections in `resources/templates/sections/` before generating.
|
||||
```
|
||||
|
||||
### Example 2: Code Generation Skill
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: "React Component Generator"
|
||||
description: "Generate React functional components with TypeScript, hooks, tests, and Storybook stories. Use when creating new components, scaffolding UI, or following component architecture patterns."
|
||||
---
|
||||
|
||||
# React Component Generator
|
||||
|
||||
## Prerequisites
|
||||
- Node.js 18+
|
||||
- React 18+
|
||||
- TypeScript 5+
|
||||
|
||||
## Quick Start
|
||||
```bash
|
||||
./scripts/generate-component.sh MyComponent
|
||||
|
||||
# Creates:
|
||||
# - src/components/MyComponent/MyComponent.tsx
|
||||
# - src/components/MyComponent/MyComponent.test.tsx
|
||||
# - src/components/MyComponent/MyComponent.stories.tsx
|
||||
# - src/components/MyComponent/index.ts
|
||||
```
|
||||
|
||||
## Step-by-Step Guide
|
||||
|
||||
### 1. Run Generator
|
||||
```bash
|
||||
./scripts/generate-component.sh ComponentName
|
||||
```
|
||||
|
||||
### 2. Choose Template
|
||||
- Basic: Simple functional component
|
||||
- With State: useState hooks
|
||||
- With Context: useContext integration
|
||||
- With API: Data fetching component
|
||||
|
||||
### 3. Customize
|
||||
Edit generated files in `src/components/ComponentName/`
|
||||
|
||||
## Templates
|
||||
See `resources/templates/` for available component templates.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Learn More
|
||||
|
||||
### Official Resources
|
||||
- [Anthropic Agent Skills Documentation](https://docs.claude.com/en/docs/agents-and-tools/agent-skills)
|
||||
- [GitHub Skills Repository](https://github.com/anthropics/skills)
|
||||
- [Claude Code Documentation](https://docs.claude.com/en/docs/claude-code)
|
||||
|
||||
### Community
|
||||
- [Skills Marketplace](https://github.com/anthropics/skills) - Browse community skills
|
||||
- [Anthropic Discord](https://discord.gg/anthropic) - Get help from community
|
||||
|
||||
### Advanced Topics
|
||||
- Multi-file skills with complex navigation
|
||||
- Skills that spawn other skills
|
||||
- Integration with MCP tools
|
||||
- Dynamic skill generation
|
||||
|
||||
---
|
||||
|
||||
**Created**: 2025-10-19
|
||||
**Version**: 1.0.0
|
||||
**Maintained By**: agentic-flow team
|
||||
**License**: MIT
|
||||
@@ -0,0 +1,143 @@
|
||||
---
|
||||
name: slack
|
||||
description: Use when you need to control Slack from Zee via the slack tool, including reacting to messages or pinning/unpinning items in Slack channels or DMs.
|
||||
---
|
||||
|
||||
# Slack Actions
|
||||
|
||||
## Overview
|
||||
|
||||
Use `slack` to react, manage pins, send/edit/delete messages, and fetch member info. The tool uses the bot token configured for Zee.
|
||||
|
||||
## Inputs to collect
|
||||
|
||||
- `channelId` and `messageId` (Slack message timestamp, e.g. `1712023032.1234`).
|
||||
- For reactions, an `emoji` (Unicode or `:name:`).
|
||||
- For message sends, a `to` target (`channel:<id>` or `user:<id>`) and `content`.
|
||||
|
||||
Message context lines include `slack message id` and `channel` fields you can reuse directly.
|
||||
|
||||
## Actions
|
||||
|
||||
### Action groups
|
||||
|
||||
| Action group | Default | Notes |
|
||||
| --- | --- | --- |
|
||||
| reactions | enabled | React + list reactions |
|
||||
| messages | enabled | Read/send/edit/delete |
|
||||
| pins | enabled | Pin/unpin/list |
|
||||
| memberInfo | enabled | Member info |
|
||||
| emojiList | enabled | Custom emoji list |
|
||||
|
||||
### React to a message
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "react",
|
||||
"channelId": "C123",
|
||||
"messageId": "1712023032.1234",
|
||||
"emoji": "✅"
|
||||
}
|
||||
```
|
||||
|
||||
### List reactions
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "reactions",
|
||||
"channelId": "C123",
|
||||
"messageId": "1712023032.1234"
|
||||
}
|
||||
```
|
||||
|
||||
### Send a message
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "sendMessage",
|
||||
"to": "channel:C123",
|
||||
"content": "Hello from Zee"
|
||||
}
|
||||
```
|
||||
|
||||
### Edit a message
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "editMessage",
|
||||
"channelId": "C123",
|
||||
"messageId": "1712023032.1234",
|
||||
"content": "Updated text"
|
||||
}
|
||||
```
|
||||
|
||||
### Delete a message
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "deleteMessage",
|
||||
"channelId": "C123",
|
||||
"messageId": "1712023032.1234"
|
||||
}
|
||||
```
|
||||
|
||||
### Read recent messages
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "readMessages",
|
||||
"channelId": "C123",
|
||||
"limit": 20
|
||||
}
|
||||
```
|
||||
|
||||
### Pin a message
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "pinMessage",
|
||||
"channelId": "C123",
|
||||
"messageId": "1712023032.1234"
|
||||
}
|
||||
```
|
||||
|
||||
### Unpin a message
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "unpinMessage",
|
||||
"channelId": "C123",
|
||||
"messageId": "1712023032.1234"
|
||||
}
|
||||
```
|
||||
|
||||
### List pinned items
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "listPins",
|
||||
"channelId": "C123"
|
||||
}
|
||||
```
|
||||
|
||||
### Member info
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "memberInfo",
|
||||
"userId": "U123"
|
||||
}
|
||||
```
|
||||
|
||||
### Emoji list
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "emojiList"
|
||||
}
|
||||
```
|
||||
|
||||
## Ideas to try
|
||||
|
||||
- React with ✅ to mark completed tasks.
|
||||
- Pin key decisions or weekly status updates.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user